/*
 * $Header: /home/cvspublic/jakarta-slide/src/webdav/server/org/apache/slide/webdav/method/CheckoutMethod.java,v 1.35 2005/02/25 17:03:52 luetzkendorf Exp $
 * $Revision: 1.35 $
 * $Date: 2005/02/25 17:03:52 $
 *
 * ====================================================================
 *
 * 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.NamespaceAccessToken;
import org.apache.slide.common.ServiceAccessException;
import org.apache.slide.common.SlideException;
import org.apache.slide.event.EventDispatcher;
import org.apache.slide.util.Configuration;
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.LabeledRevisionNotFoundException;
import org.apache.slide.webdav.util.PreconditionViolationException;
import org.apache.slide.webdav.util.ViolatedPrecondition;
import org.apache.slide.webdav.util.WebdavStatus;
import org.apache.slide.webdav.util.WebdavUtils;
import org.jdom.Element;
import org.jdom.JDOMException;

/**
 * CHECKOUT method.
 *
 */
public class CheckoutMethod extends AbstractWebdavMethod implements DeltavConstants, WriteMethod,
        FineGrainedLockingMethod {

    /** Resource to be written. */
    private String resourcePath;

    /** Marshalling variables */
    private boolean applyToVersion = false;
    private boolean forkOk = false;

    // ----------------------------------------------------------- Constructors

    /**
     * Constructor.
     *
     * @param token     the token for accessing the namespace
     * @param config    configuration of the WebDAV servlet
     */
    public CheckoutMethod(NamespaceAccessToken token,
                          WebdavServletConfig config) {
        super(token, config);
    }

    /**
     * @see org.apache.slide.webdav.method.FineGrainedLockingMethod#acquireFineGrainLocks()
     */
    public void acquireFineGrainLocks() {
        acquireStandardLocks(resourcePath);
        // lock history folder
        acquireHistoryLocks(resourcePath);
        // changes this
        acquireLock(resourcePath, WRITE_LOCK);
    }

    /**
     * Parse WebDAV XML query.
     *
     * @throws WebdavException
     */
    protected void parseRequest() throws WebdavException {

        resourcePath = requestUri;
        if (resourcePath == null) {
            resourcePath = "/";
        }

        // evaluate "Label" header
        if (Configuration.useVersionControl()) {
            try {

                String labelHeader = WebdavUtils.fixTomcatHeader(requestHeaders.getLabel(), "UTF-8");

                applyToVersion = (labelHeader != null);
                resourcePath = versioningHelper.getLabeledResourceUri(resourcePath,
                                                                      labelHeader);
            }
            catch (LabeledRevisionNotFoundException e) {
                ViolatedPrecondition violatedPrecondition =
                    new ViolatedPrecondition(DeltavConstants.C_MUST_SELECT_VERSION_IN_HISTORY,
                                             WebdavStatus.SC_CONFLICT);
                try {
                    sendPreconditionViolation(new PreconditionViolationException(violatedPrecondition,
                                                                                 resourcePath));
                } catch (IOException ioe) {}
                throw new WebdavException(getErrorCode((Exception)e));
            }
            catch (SlideException e) {
                int statusCode = getErrorCode( e );
                sendError( statusCode, e );
                throw new WebdavException( statusCode );
            }
        }


        if( req.getContentLength() > 0 ) {
//            readRequestContent();
            try{
                Iterator i = parseRequestContent(E_CHECKOUT).getChildren().iterator();
                while( i.hasNext() ) {
                    Element e = (Element)i.next();
                    if ( e.getName().equals(E_APPLY_TO_VERSION) ) {

                        String labelHeader = WebdavUtils.fixTomcatHeader(requestHeaders.getLabel(), "UTF-8");

                        if (labelHeader != null) {
                            ViolatedPrecondition violatedPrecondition =
                                new ViolatedPrecondition(DeltavConstants.C_MUST_NOT_HAVE_LABEL_AND_APPLY_TO_VERSION,
                                                         WebdavStatus.SC_CONFLICT);
                            sendPreconditionViolation(new PreconditionViolationException(violatedPrecondition,
                                                                                         resourcePath));
                            throw new WebdavException(WebdavStatus.SC_CONFLICT);
                        }
                        applyToVersion = true;
                    }
                    if ( e.getName().equals(E_FORK_OK) ) {
                        forkOk = true;
                    }
                }
            }
            catch (IOException  e){
                int statusCode = WebdavStatus.SC_INTERNAL_SERVER_ERROR;
                sendError( statusCode, e );
                throw new WebdavException( statusCode );
            }
            catch (JDOMException  e){
                int statusCode = WebdavStatus.SC_BAD_REQUEST;
                sendError( statusCode, e );
                throw new WebdavException( statusCode );
            }
        }
    }

    /**
     * Execute the request.
     *
     * @throws WebdavException
     * @throws IOException
     */
    protected void executeRequest() throws WebdavException, IOException {
        String locationValue = null;

        // 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( e );
            sendError( statusCode, e );
            throw new WebdavException( statusCode );
        }

        try {
            if ( WebdavEvent.CHECKOUT.isEnabled() ) EventDispatcher.getInstance().fireVetoableEvent(WebdavEvent.CHECKOUT, new WebdavEvent(this));

            locationValue = versioningHelper.checkout( resourcePath, forkOk, applyToVersion );
        }
        catch (PreconditionViolationException e) {
            sendPreconditionViolation(e);
            throw e;
        }
        catch (Exception e) {
            int statusCode = getErrorCode( e );
            sendError( statusCode, e );
            throw new WebdavException( statusCode );
        }
        finally {
            resp.setHeader(H_CACHE_CONTROL, NO_CACHE);
            if( locationValue != null && locationValue.length() > 0 ) {
                locationValue = getFullPath( locationValue );
                // the location header is "utf-8" expected
                resp.setHeader( H_LOCATION, WebdavUtils.encodeURL(locationValue, "utf-8") );
            }
        }

    }


}



