/*
 * $Header: /home/cvspublic/jakarta-slide/src/webdav/server/org/apache/slide/webdav/method/BindMethod.java,v 1.20 2004/10/31 11:32:39 ozeigermann Exp $
 * $Revision: 1.20 $
 * $Date: 2004/10/31 11:32:39 $
 *
 * ====================================================================
 *
 * 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.List;

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.lock.ObjectLockedException;
import org.apache.slide.structure.CrossServerBindingException;
import org.apache.slide.structure.ObjectNode;
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.BindConstants;
import org.apache.slide.webdav.util.PreconditionViolationException;
import org.apache.slide.webdav.util.ViolatedPrecondition;
import org.apache.slide.webdav.util.WebdavStatus;
import org.jdom.JDOMException;


/**
 * BIND method.
 *
 */
public class BindMethod extends AbstractWebdavMethod implements BindConstants, WriteMethod,
        FineGrainedLockingMethod {

    private String sourceUri;
    private String collectionUri;
    private String segment;
    private boolean overwrite;
    private ObjectNode sourceNode = null;
    private ObjectNode collectionNode = null;


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

    /**
     * @see org.apache.slide.webdav.method.FineGrainedLockingMethod#acquireFineGrainLocks()
     */
    public void acquireFineGrainLocks() {
        // TODO a global write lock is certainly too much, but I have no better idea (OZ)
        acquireGlobalWriteLock();
    }

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

//        readRequestContent();
        try{
            content = parseRequestContent(E_BIND).getChildren();
            segment = MethodUtil.getChildText(content, E_SEGMENT);
            sourceUri = parseUri(MethodUtil.getChildUrl(content, E_HREF));
        }
        catch (IOException e) {  // TODO: merge exception handling into jdom access methods
            int statusCode = WebdavStatus.SC_INTERNAL_SERVER_ERROR;
            sendError( statusCode, e );
            throw new WebdavException( statusCode );
        }
        catch (JDOMException e) {  // TODO: merge exception handling into jdom access methods
            int statusCode = WebdavStatus.SC_BAD_REQUEST;
            sendError( statusCode, e );
            throw new WebdavException( statusCode );
        }

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

        overwrite = requestHeaders.getOverwrite(true);
    }

    /**
     * Method checkPreconditions
     *
     * @throws   PreconditionViolationException
     *
     */
    private void checkPreconditions() throws PreconditionViolationException, ServiceAccessException {
        resp.setStatus( WebdavStatus.SC_CREATED );

        try {
            collectionNode = structure.retrieve( slideToken, collectionUri );
        }
        catch( ServiceAccessException e ) {
            throw e;
        }
        catch (SlideException e) {} // ignore silently

        try {
            sourceNode = structure.retrieve( slideToken, sourceUri );
        }
        catch( ServiceAccessException e ) {
            throw e;
        }
        catch (Exception e) {} // ignore silently

        if (collectionNode == null || !isCollection(collectionUri)) {
            throw new PreconditionViolationException(
                new ViolatedPrecondition(C_BIND_INTO_COLLECTION, WebdavStatus.SC_CONFLICT), collectionUri);
        }
        if (!MethodUtil.isValidSegment(segment)) {
            throw new PreconditionViolationException(
                new ViolatedPrecondition(C_NAME_ALLOWED, WebdavStatus.SC_FORBIDDEN), segment);
        }
        if (sourceNode == null) {
            throw new PreconditionViolationException(
                new ViolatedPrecondition(C_BIND_SOURCE_EXISTS, WebdavStatus.SC_CONFLICT), sourceUri);
        }
        if (collectionNode.hasBinding(segment)) {
            if (overwrite) {
                resp.setStatus( WebdavStatus.SC_NO_CONTENT );
            }
            else {
                throw new PreconditionViolationException(
                    new ViolatedPrecondition(C_CAN_OVERWRITE, WebdavStatus.SC_FORBIDDEN), segment);
            }
        }
        if (isCollection(sourceUri)) {
            if (isDescendant(collectionNode, sourceNode)) {
                throw new PreconditionViolationException(
                    new ViolatedPrecondition(C_CYCLE_ALLOWED, WebdavStatus.SC_FORBIDDEN), sourceUri);
            }
        }
    }

    /**
     * Execute the request.
     *
     * @exception WebdavException
     */
    protected void executeRequest() throws WebdavException, IOException {

        // Prevent dirty reads
        slideToken.setForceStoreEnlistment(true);

        // check lock-null resources
        try {
            if (isLockNull(collectionUri)) {
                int statusCode = WebdavStatus.SC_NOT_FOUND;
                sendError( statusCode, "lock-null resource", new Object[]{collectionUri} );
                throw new WebdavException( statusCode );
            }
        }
        catch (ServiceAccessException e) {
            int statusCode = getErrorCode( e );
            sendError( statusCode, e );
            throw new WebdavException( statusCode );
        }

        try {
            checkPreconditions();

            if ( WebdavEvent.BIND.isEnabled() ) EventDispatcher.getInstance().fireVetoableEvent(WebdavEvent.BIND, new WebdavEvent(this));

            structure.addBinding( slideToken, collectionNode, segment, sourceNode );
        }
        catch (ObjectLockedException e) {
            ViolatedPrecondition violatedPrecondition;
            if (collectionUri.equals(e.getObjectUri())) {
                violatedPrecondition =
                    new ViolatedPrecondition(C_LOCKED_UPDATE_ALLOWED, WebdavStatus.SC_LOCKED);
            }
            else {
                violatedPrecondition =
                    new ViolatedPrecondition(C_LOCKED_OVERWRITE_ALLOWED, WebdavStatus.SC_CONFLICT);
            }
            sendPreconditionViolation(
                new PreconditionViolationException(violatedPrecondition, collectionNode.getUri())
            );
        }
        catch (CrossServerBindingException e) {
            sendPreconditionViolation(
                new PreconditionViolationException(
                                         new ViolatedPrecondition(C_CROSS_SERVER_BINDING, WebdavStatus.SC_FORBIDDEN),
                                         collectionNode.getUri()
                                     )
            );
        }
        catch (PreconditionViolationException e) {
            sendPreconditionViolation(e);
            throw e;
        }
        catch (Exception e) {
            int statusCode = getErrorCode( e );
            sendError( statusCode, e );
            throw new WebdavException( statusCode );
        }
    }

}

