/*
 * $Header: /home/cvspublic/jakarta-slide/proposals/wvcm/src/org/apache/wvcm/store/webdav/ControllableResourceWebdavAccessor.java,v 1.16 2005/03/04 18:14:31 pnever Exp $
 * $Revision: 1.16 $
 * $Date: 2005/03/04 18:14:31 $
 *
 * ====================================================================
 *
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 1999-2003 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution, if
 *    any, must include the following acknowlegement:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowlegement may appear in the software itself,
 *    if and wherever such third-party acknowlegements normally appear.
 *
 * 4. The names "The Jakarta Project", "Slide", and "Apache Software
 *    Foundation" must not be used to endorse or promote products derived
 *    from this software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache"
 *    nor may "Apache" appear in their names without prior written
 *    permission of the Apache Group.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 *
 * [Additional notices, if required by prior licensing conditions]
 *
 */

package org.apache.wvcm.store.webdav;
import java.util.Iterator;
import java.util.List;
import javax.wvcm.PropertyNameList;
import javax.wvcm.Resource;
import javax.wvcm.Version;
import javax.wvcm.WvcmException;
import javax.wvcm.WvcmException.ReasonCode;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.webdav.methods.CheckinMethod;
import org.apache.webdav.methods.CheckoutMethod;
import org.apache.webdav.methods.PropfindMethod;
import org.apache.webdav.methods.PutMethod;
import org.apache.webdav.methods.UncheckoutMethod;
import org.apache.webdav.methods.UpdateMethod;
import org.apache.webdav.methods.VersionControlMethod;
import org.apache.wvcm.LocationImpl;
import org.apache.wvcm.LockTokenImpl;
import org.apache.wvcm.ResourceImpl;
import org.apache.wvcm.store.ControllableResourceAccessor;
import org.apache.wvcm.store.webdav.request.CheckinRequest;
import org.apache.wvcm.store.webdav.request.CheckoutRequest;
import org.apache.wvcm.store.webdav.request.LabelRequest;
import org.apache.wvcm.store.webdav.request.PropfindRequest;
import org.apache.wvcm.store.webdav.request.UpdateRequest;
import org.apache.wvcm.store.webdav.request.VersionControlRequest;
import org.apache.wvcm.store.webdav.response.ErrorResponse;
import org.apache.wvcm.store.webdav.response.MultistatusResponse;

/**
 * WebDAV-based implementation of ControllableResourceAccessor.
 *
 * @author <a href="mailto:peter.nevermann@softwareag.com">Peter Nevermann</a>
 * @version $Revision: 1.16 $
 */
public class ControllableResourceWebdavAccessor extends ResourceWebdavAccessor implements ControllableResourceAccessor {
    
    /**
     * Constructor.
     */
    public ControllableResourceWebdavAccessor( Resource resource ) {
        super( resource );
    }
    
    /**
     * Create a new persistent controllable resource at the location of the associated
     * resource.
     *
     * @throws   WvcmException
     */
    public void doCreateResource() throws WvcmException {
        // TODO: prio=h, effort=1.0, descr=(use <If-Non-Match: *> header)
        // Should use <If-Non-Match: *> header to enforce
        // resource-must-be-null precondition
        // Unfortunately, this header is not supported by Slide at the moment.
        // The following method call is therefore a workaround.
        preResourceMustBeNull();
        LocationImpl loc = (LocationImpl)resource().location();
        String resourcepath = loc.path();
        PutMethod method = new PutMethod(loc.escapedPath());
        method.addRequestHeader( "Content-Length", "0" );
        addLockTokens(method);

        try {
            method = (PutMethod)retryHandler().executeMethod( method );
            int sc = method.getStatusCode();
            String st = method.getStatusText();
            switch( sc ) {
                case HttpStatus.SC_CREATED:
                    break;
                case HttpStatus.SC_NO_CONTENT:
                    throw new WvcmException(
                        "Resource already existed and has been overwritten!!", resourcepath, ReasonCode.CONFLICT, null);
                case HttpStatus.SC_UNAUTHORIZED:
                    throw new WvcmException(
                        st, resourcepath, ReasonCode.UNAUTHORIZED, null);
                case HttpStatus.SC_LOCKED:
                    throw new WvcmException(
                        st, resourcepath, ReasonCode.LOCKED, null);
                case HttpStatus.SC_FORBIDDEN:
                case HttpStatus.SC_CONFLICT:
                    ErrorResponse errorRsp = new ErrorResponse( method.getResponseBodyAsStream() );
                    throw new WvcmException(
                        st, resourcepath, errorRsp.getWvcmReasonCode(), null);
                default:
                    throw new WvcmException(
                        st, resourcepath, ReasonCode.CANNOT_INITIALIZE_RESOURCE, null);
            }
        }
        catch (java.io.IOException e) {
            throw new WvcmException(
                "Write failed", resourcepath, ReasonCode.WRITE_FAILED, new Exception[]{e});
        }
        finally {
            method.releaseConnection();
        }
    }
    
    /**
     * Checkout the associated resource so that its content can be modified.
     * @param forkOK Indicates whether to do the checkout even if the
     * version already has a successor or a checkout.
     * @param activityList A list of {@link Activity} objects that identify
     * the activities to which the work on the
     * checked-out resource will contribute.
     * @param newActivity Indicates whether to create a new activity
     * for the checkout.
     * @param unreserved Indicates whether to do the checkout even
     * if there already is a checkout from the currently selected
     * version in one of the activities specified in the activityList.
     */
    public void doCheckout(boolean forkOK, List activityList, boolean newActivity, boolean unreserved) throws WvcmException {
        LocationImpl loc = (LocationImpl)resource().location();
        String resourcepath = loc.path();
        CheckoutMethod method = new CheckoutMethod(loc.escapedPath());
        CheckoutRequest req = new CheckoutRequest( forkOK );
        method.setRequestBody( req.reqBodyAsString() );
        method.addRequestHeader( "Content-Type", "text/xml; charset=\"utf-8\"" );
        addLockTokens(method);
        
        try {
            method = (CheckoutMethod)retryHandler(req.reqBodyAsString()).executeMethod( method );
            int sc = method.getStatusCode();
            String st = method.getStatusText();
            switch( sc ) {
                case HttpStatus.SC_OK:
                    break;
                case HttpStatus.SC_FORBIDDEN:
                case HttpStatus.SC_CONFLICT:
                    ErrorResponse errorRsp = new ErrorResponse( method.getResponseBodyAsStream() );
                    throw new WvcmException(
                        st, resourcepath, errorRsp.getWvcmReasonCode(), null);
                case HttpStatus.SC_UNAUTHORIZED:
                    throw new WvcmException(
                        st, resourcepath, ReasonCode.UNAUTHORIZED, null);
                case HttpStatus.SC_NOT_FOUND:
                    throw new WvcmException(
                        st, resourcepath, ReasonCode.NOT_FOUND, null);
                case HttpStatus.SC_LOCKED:
                    throw new WvcmException(
                        st, resourcepath, ReasonCode.LOCKED, null);
                default:
                    throw new WvcmException(
                        st, resourcepath, ReasonCode.CANNOT_CHECK_OUT, null);
            }
        }
        catch (java.io.IOException e) {
            throw new WvcmException(
                "Write failed", resourcepath, ReasonCode.WRITE_FAILED, new Exception[]{e});
        }
        finally {
            method.releaseConnection();
        }
    }
    
    /**
     * Changes the state of the resource identified by the associated {@link ControllableResource}
     * to be checked-in.  If version history is being tracked for the
     * resource, the current content of the resource is captured
     * in a new version resource at a server-defined location.
     * @param keepCheckedOut indicates whether to checkout the
     * resource again immediately after checking it in.
     * If keepCheckedOut is <code>true</code>, the ActivityList
     * and Unreserved properties should not be changed by the checkout.
     * @param forkOK indicates whether to fork even if forking
     * is discouraged.
     */
    public void doCheckin(boolean keepCheckedOut, boolean forkOK) throws WvcmException {
        LocationImpl loc = (LocationImpl)resource().location();
        String resourcepath = loc.path();
        CheckinMethod method = new CheckinMethod(loc.escapedPath());
        CheckinRequest req = new CheckinRequest( keepCheckedOut, forkOK );
        method.setRequestBody( req.reqBodyAsString() );
        method.addRequestHeader( "Content-Type", "text/xml; charset=\"utf-8\"" );
        addLockTokens(method);
        
        try {
            method = (CheckinMethod)retryHandler(req.reqBodyAsString()).executeMethod( method );
            int sc = method.getStatusCode();
            String st = method.getStatusText();
            switch( sc ) {
                case HttpStatus.SC_CREATED:
                    break;
                case HttpStatus.SC_FORBIDDEN:
                case HttpStatus.SC_CONFLICT:
                    ErrorResponse errorRsp = new ErrorResponse( method.getResponseBodyAsStream() );
                    throw new WvcmException(
                        st, resourcepath, errorRsp.getWvcmReasonCode(), null);
                case HttpStatus.SC_UNAUTHORIZED:
                    throw new WvcmException(
                        st, resourcepath, ReasonCode.UNAUTHORIZED, null);
                case HttpStatus.SC_NOT_FOUND:
                    throw new WvcmException(
                        st, resourcepath, ReasonCode.NOT_FOUND, null);
                case HttpStatus.SC_LOCKED:
                    throw new WvcmException(
                        st, resourcepath, ReasonCode.LOCKED, null);
                default:
                    throw new WvcmException(
                        st, resourcepath, ReasonCode.CANNOT_CHECK_IN, null);
            }
        }
        catch (java.io.IOException e) {
            throw new WvcmException(
                "Write failed", resourcepath, ReasonCode.WRITE_FAILED, new Exception[]{e});
        }
        finally {
            method.releaseConnection();
        }
    }
    
    /**
     * Cancels the checkout of a version-controlled resource,
     * and restores its content to the state of its CheckedOut version.
     */
    public void doUncheckout() throws WvcmException {
        LocationImpl loc = (LocationImpl)resource().location();
        String resourcepath = loc.path();
        UncheckoutMethod method = new UncheckoutMethod(loc.escapedPath());
        method.addRequestHeader( "Content-Length", "0" );
        addLockTokens(method);
        
        try {
            method = (UncheckoutMethod)retryHandler().executeMethod( method );
            int sc = method.getStatusCode();
            String st = method.getStatusText();
            switch( sc ) {
                case HttpStatus.SC_OK:
                    break;
                case HttpStatus.SC_FORBIDDEN:
                case HttpStatus.SC_CONFLICT:
                    ErrorResponse errorRsp = new ErrorResponse( method.getResponseBodyAsStream() );
                    throw new WvcmException(
                        st, resourcepath, errorRsp.getWvcmReasonCode(), null);
                case HttpStatus.SC_UNAUTHORIZED:
                    throw new WvcmException(
                        st, resourcepath, ReasonCode.UNAUTHORIZED, null);
                case HttpStatus.SC_NOT_FOUND:
                    throw new WvcmException(
                        st, resourcepath, ReasonCode.NOT_FOUND, null);
                case HttpStatus.SC_LOCKED:
                    throw new WvcmException(
                        st, resourcepath, ReasonCode.LOCKED, null);
                default:
                    throw new WvcmException(
                        st, resourcepath, ReasonCode.CANNOT_CANCEL_CHECKED_OUT, null);
            }
        }
        catch (java.io.IOException e) {
            throw new WvcmException(
                "Write failed", resourcepath, ReasonCode.WRITE_FAILED, new Exception[]{e});
        }
        finally {
            method.releaseConnection();
        }
    }
    
    /**
     * Put the associated resource under (version) control.
     *
     * @throws   WvcmException
     */
    public void doControl() throws WvcmException {
        LocationImpl loc = (LocationImpl)resource().location();
        String resourcepath = loc.path();
        HttpMethod method = new VersionControlMethod(loc.escapedPath());
        method.addRequestHeader( "Content-Length", "0" );
        addLockTokens(method);
        
        try {
            method = (VersionControlMethod)retryHandler().executeMethod( method );
            int sc = method.getStatusCode();
            String st = method.getStatusText();
            switch( sc ) {
                case HttpStatus.SC_OK:
                    break;
                case HttpStatus.SC_FORBIDDEN:
                case HttpStatus.SC_CONFLICT:
                    ErrorResponse errorRsp = new ErrorResponse( method.getResponseBodyAsStream() );
                    throw new WvcmException(
                        st, resourcepath, errorRsp.getWvcmReasonCode(), null);
                case HttpStatus.SC_UNAUTHORIZED:
                    throw new WvcmException(
                        st, resourcepath, ReasonCode.UNAUTHORIZED, null);
                case HttpStatus.SC_NOT_FOUND:
                    throw new WvcmException(
                        st, resourcepath, ReasonCode.NOT_FOUND, null);
                case HttpStatus.SC_LOCKED:
                    throw new WvcmException(
                        st, resourcepath, ReasonCode.LOCKED, null);
                default:
                    throw new WvcmException(
                        st, resourcepath, ReasonCode.CANNOT_PUT_UNDER_CONTROL, null);
            }
        }
        catch (java.io.IOException e) {
            throw new WvcmException(
                "Write failed", resourcepath, ReasonCode.WRITE_FAILED, new Exception[]{e});
        }
        finally {
            method.releaseConnection();
        }
    }
    
    /**
     * Update the state of the associated checked-in version-controlled
     * {@link ControllableResource} to be the same as the specified version from
     * the version history of the associated {@link ControllableResource}.
     * @param version The version specifying the new state of the resource
     * @param wantedPropertyList The list of properties that will be available
     * @return An iterator of {@link ControllableResource} objects that
     * have been modified as a result of the doUpdate request.
     * Each version-controlled resource contains a value for each
     * of the properties specified in the WantedPropertyList.
     */
    public Iterator doUpdate(Version version, PropertyNameList wantedPropertyList) throws WvcmException {
        LocationImpl loc = (LocationImpl)resource().location();
        String resourcepath = loc.path();
        UpdateMethod method = new UpdateMethod(loc.escapedPath());
        UpdateRequest req = new UpdateRequest( version, wantedPropertyList );
        method.setRequestBody( req.reqBodyAsString() );
        method.addRequestHeader( "Content-Type", "text/xml; charset=\"utf-8\"" );
        addLockTokens(method);
        
        try {
            method = (UpdateMethod)retryHandler(req.reqBodyAsString()).executeMethod( method );
            int sc = method.getStatusCode();
            String st = method.getStatusText();
            switch( sc ) {
                case HttpStatus.SC_MULTI_STATUS:
                    MultistatusResponse resp =
                        new MultistatusResponse( resource(), method.getResponseBodyAsStream(), wantedPropertyList );
                    return resp.createResourceProxies().iterator();
                case HttpStatus.SC_FORBIDDEN:
                case HttpStatus.SC_CONFLICT:
                    ErrorResponse errorRsp = new ErrorResponse( method.getResponseBodyAsStream() );
                    throw new WvcmException(
                        st, resourcepath, errorRsp.getWvcmReasonCode(), null);
                case HttpStatus.SC_NOT_FOUND:
                    throw new WvcmException(
                        st, resourcepath, ReasonCode.NOT_FOUND, null);
                case HttpStatus.SC_UNAUTHORIZED:
                    throw new WvcmException(
                        st, resourcepath, ReasonCode.UNAUTHORIZED, null);
                case HttpStatus.SC_LOCKED:
                    throw new WvcmException(
                        st, resourcepath, ReasonCode.LOCKED, null);
                default:
                    throw new WvcmException(
                        st, resourcepath, ReasonCode.CANNOT_UPDATE_CONTENT_AND_PROPERTIES, null);
            }
        }
        catch (java.io.IOException e) {
            throw new WvcmException(
                "Read failed", resourcepath, ReasonCode.READ_FAILED, new Exception[]{e});
        }
        finally {
            method.releaseConnection();
        }
    }
    
    /**
     * Create a new controlled resource
     * at the location identified by the proxy.  The resource
     * is associated with an existing version history,
     * and is initialized with a specified version from that
     * version history.  The request will
     * fail if a resource already exists at that location.
     * @param v The version used to initialize the controlled
     * resource.
     */
    public void doCreateVersionControlledResource(Version v) throws WvcmException {
        preResourceMustBeNull();
        LocationImpl loc = (LocationImpl)resource().location();
        String resourcepath = loc.path();
        VersionControlMethod method = new VersionControlMethod(loc.escapedPath());
        VersionControlRequest req = new VersionControlRequest( v );
        method.setRequestBody( req.reqBodyAsString() );
        method.addRequestHeader( "Content-Type", "text/xml; charset=\"utf-8\"" );
        addLockTokens(method);
        
        try {
            method = (VersionControlMethod)retryHandler(req.reqBodyAsString()).executeMethod( method );
            int sc = method.getStatusCode();
            String st = method.getStatusText();
            switch( sc ) {
                case HttpStatus.SC_CREATED:
                    break;
                case HttpStatus.SC_FORBIDDEN:
                case HttpStatus.SC_CONFLICT:
                    ErrorResponse errorRsp = new ErrorResponse( method.getResponseBodyAsStream() );
                    throw new WvcmException(
                        st, resourcepath, errorRsp.getWvcmReasonCode(), null);
                case HttpStatus.SC_UNAUTHORIZED:
                    throw new WvcmException(
                        st, resourcepath, ReasonCode.UNAUTHORIZED, null);
                case HttpStatus.SC_LOCKED:
                    throw new WvcmException(
                        st, resourcepath, ReasonCode.LOCKED, null);
                default:
                    throw new WvcmException(
                        st, resourcepath, ReasonCode.CANNOT_CREATE_NEW_CONTROLLED_RESOURCE, null);
            }
        }
        catch (java.io.IOException e) {
            throw new WvcmException(
                "Write failed", resourcepath, ReasonCode.WRITE_FAILED, new Exception[]{e});
        }
        finally {
            method.releaseConnection();
        }
    }

    /**
     * Apply {@link Version#doAddLabel Version.doAddLabel} to the CheckedIn version of this {@link ControllableResource}.
     */
    public void doAddLabel(String label) throws WvcmException {
        int operator = LabelRequest.ADD;
        doLabel( label, operator );
    }
    
    /**
     * Apply {@link Version#doSetLabel Version.doSetLabel} to the CheckedIn version of this {@link ControllableResource}.
     */
    public void doSetLabel(String label) throws WvcmException {
        int operator = LabelRequest.SET;
        doLabel( label, operator );
    }
    
    /**
     * Apply {@link Version#doRemoveLabel Version.doRemoveLabel} to the CheckedIn version of this {@link ControllableResource}.
     */
    public void doRemoveLabel(String label) throws WvcmException {
        int operator = LabelRequest.REMOVE;
        doLabel( label, operator );
    }
    
    /**
     * Apply {@link VersionHistory#doReadLabelledVersionProperties
     * Version.doReadLabelledVersionProperties}
     * to the version history of this {@link ControllableResource}.
     */
    public Version doReadLabelledVersionProperties(String label, PropertyNameList wantedPropertyList) throws WvcmException {
        LocationImpl loc = (LocationImpl)resource().location();
        String resourcepath = loc.path();
        PropfindMethod method = new PropfindMethod(loc.escapedPath());
        PropfindRequest req = new PropfindRequest( wantedPropertyList );
        method.setRequestBody( req.reqBodyAsString() );
        method.addRequestHeader( "Content-Type", "text/xml; charset=\"utf-8\"" );
        method.addRequestHeader( "Label", label );
        method.addRequestHeader( "Depth", "0" );
        
        try {
            client().executeMethod( method );
            int sc = method.getStatusCode();
            String st = method.getStatusText();
            switch( sc ) {
                case HttpStatus.SC_MULTI_STATUS:
                    MultistatusResponse resp =
                        new MultistatusResponse( resource(), method.getResponseBodyAsStream(), wantedPropertyList );
                    return (Version)resp.createResourceProxy();
                case HttpStatus.SC_FORBIDDEN:
                case HttpStatus.SC_CONFLICT:
                    ErrorResponse errorRsp = new ErrorResponse( method.getResponseBodyAsStream() );
                    throw new WvcmException(
                        st, resourcepath, errorRsp.getWvcmReasonCode(), null);
                case HttpStatus.SC_NOT_FOUND:
                    throw new WvcmException(
                        st, resourcepath, ReasonCode.NOT_FOUND, null);
                case HttpStatus.SC_UNAUTHORIZED:
                    throw new WvcmException(
                        st, resourcepath, ReasonCode.UNAUTHORIZED, null);
                default:
                    throw new WvcmException(
                        st, resourcepath, ReasonCode.FORBIDDEN, null);
            }
        }
        catch (java.io.IOException e) {
            throw new WvcmException(
                "Read failed", resourcepath, ReasonCode.READ_FAILED, new Exception[]{e});
        }
        finally {
            method.releaseConnection();
        }
    }

    /**
     * Checks resource-must-be-null precondition
     *
     * @throws   WvcmException
     */
    private void preResourceMustBeNull() throws WvcmException {
        LocationImpl loc = (LocationImpl)resource().location();
        String resourcepath = loc.path();
        if( doCheckExists() )
            throw new WvcmException(
                "Precondition violation", resourcepath, ReasonCode.RESOURCE_ALREADY_EXISTS_AT_LOCATION, null);
    }
}


