/*
 * $Header: /home/cvspublic/jakarta-slide/src/webdav/server/org/apache/slide/webdav/method/VersionControlMethod.java,v 1.34 2005/02/25 17:03:53 luetzkendorf Exp $
 * $Revision: 1.34 $
 * $Date: 2005/02/25 17:03:53 $
 *
 * ====================================================================
 *
 * Copyright 1999-2002 The Apache Software Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package org.apache.slide.webdav.method;

import java.io.IOException;
import java.util.Iterator;

import org.apache.slide.common.Domain;
import org.apache.slide.common.NamespaceAccessToken;
import org.apache.slide.common.ServiceAccessException;
import org.apache.slide.event.EventDispatcher;
import org.apache.slide.macro.ForbiddenException;
import org.apache.slide.webdav.WebdavException;
import org.apache.slide.webdav.WebdavServletConfig;
import org.apache.slide.webdav.event.WebdavEvent;
import org.apache.slide.webdav.util.DeltavConstants;
import org.apache.slide.webdav.util.PreconditionViolationException;
import org.apache.slide.webdav.util.WebdavStatus;
import org.jdom.Element;
import org.jdom.JDOMException;
/**
 * VERSION-CONTROL method.
 *
 */
public class VersionControlMethod extends AbstractWebdavMethod
    implements DeltavConstants, WriteMethod, FineGrainedLockingMethod {
    
    /**
     * Resource to be written.
     */
    private String resourcePath;
    
    /**
     * The VERSION-CONTROL request can be used to create a new VCR for an existing
     * version history (see 6.7 of RFC3253)
     */
    private String existingVersionPath;
    
    
    // ----------------------------------------------------------- Constructors
    
    
    /**
     * Constructor.
     *
     * @param token     the token for accessing the namespace
     * @param config    configuration of the WebDAV servlet
     */
    public VersionControlMethod(NamespaceAccessToken token,
                                WebdavServletConfig config) {
        super(token, config);
    }

    /**
     * @see org.apache.slide.webdav.method.FineGrainedLockingMethod#acquireFineGrainLocks()
     */
    public void acquireFineGrainLocks() {
        acquireStandardLocks(resourcePath);
        // lock history folder in case we have auto versioning turned on
        acquireHistoryLocks(resourcePath);
        // changes this and parent
        acquireLock(resourcePath, WRITE_LOCK);
        acquireParentLock(resourcePath, WRITE_LOCK);
    }

    /**
     * Parse WebDAV XML query.
     *
     * @exception WebdavException
     */
    protected void parseRequest() throws WebdavException {
        //        readRequestContent();
        
        resourcePath = requestUri;
        if (resourcePath == null) {
            resourcePath = "/";
        }
        
        if( req.getContentLength() > 0 ) {
            try{
                Element ve = null;
                Iterator i = parseRequestContent(E_VERSION_CONTROL).getChildren().iterator();
                while( i.hasNext() ) {
                    Element e = (Element)i.next();
                    if( e.getName().equals(E_VERSION) ) {
                        // version element found
                        ve = e;
                        // get the href element
                        try {
                            Element hre = (Element)ve.getChildren().get(0);
                            if( hre == null || !hre.getName().equals(E_HREF) )
                                throw new Exception();
                            existingVersionPath = getSlidePath( hre.getText() );
                        }
                        catch( Exception x ) {
                            Domain.warn( E_VERSION+" element must contain "+E_HREF+" element" );
                            throw new JDOMException("<"+E_VERSION+"> element must contain <"+E_HREF+"> element" );
                        }
                        break;
                    }
                }
            }
            catch (JDOMException  e){
                int statusCode = WebdavStatus.SC_BAD_REQUEST;
                sendError( statusCode, e );
                throw new WebdavException( statusCode );
            }
            catch( IOException e ){
                int statusCode = WebdavStatus.SC_INTERNAL_SERVER_ERROR;
                sendError( statusCode, e );
                throw new WebdavException( statusCode );
            }
        }
    }
    
    /**
     * Execute the request.
     *
     * @exception WebdavException
     */
    protected void executeRequest() throws WebdavException, IOException {
        
        // Prevent dirty reads
        slideToken.setForceStoreEnlistment(true);
        
        // check lock-null resources
        try {
            if (isLockNull(resourcePath)) {
                int statusCode = WebdavStatus.SC_NOT_FOUND;
                sendError( statusCode, "lock-null resource", new Object[]{resourcePath} );
                throw new WebdavException( statusCode );
            }
        }
        catch (ServiceAccessException e) {
            int statusCode = getErrorCode((Exception)e);
            sendError( statusCode, e );
            throw new WebdavException( statusCode );
        }
        
        try {
            if (isExcludedForVersionControl(resourcePath)) {
                throw new ForbiddenException(
                    resourcePath,
                    new Exception("The resource path has been excluded from version-control") );
            }
            if ( WebdavEvent.VERSION_CONTROL.isEnabled() ) EventDispatcher.getInstance().fireVetoableEvent(WebdavEvent.VERSION_CONTROL, new WebdavEvent(this));

            if( existingVersionPath == null )
                versioningHelper.versionControl(resourcePath);
            else
                versioningHelper.versionControl(resourcePath, existingVersionPath);
        }
        catch (PreconditionViolationException e) {
            sendPreconditionViolation(e);
            throw e;
        }
        catch (Exception e) {
            int statusCode = getErrorCode( e );
            sendError( statusCode, e );
            throw new WebdavException( statusCode );
        }
    }
}



