/*
 * $Header: /home/cvspublic/jakarta-slide/src/webdav/server/org/apache/slide/webdav/method/report/AclPrincipalPropSetReport.java,v 1.8 2004/12/21 16:04:20 luetzkendorf Exp $
 * $Revision: 1.8 $
 * $Date: 2004/12/21 16:04:20 $
 *
 * ====================================================================
 *
 * 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.report;

import java.io.IOException;
import java.util.Enumeration;
import java.util.List;

import org.apache.slide.common.NamespaceAccessToken;
import org.apache.slide.common.PropertyParseException;
import org.apache.slide.common.RequestedProperties;
import org.apache.slide.common.RequestedPropertiesImpl;
import org.apache.slide.common.ServiceAccessException;
import org.apache.slide.common.SlideException;
import org.apache.slide.common.SlideToken;
import org.apache.slide.content.NodeProperty;
import org.apache.slide.content.NodeRevisionDescriptor;
import org.apache.slide.content.NodeRevisionDescriptors;
import org.apache.slide.content.NodeRevisionNumber;
import org.apache.slide.security.NodePermission;
import org.apache.slide.structure.SubjectNode;
import org.apache.slide.webdav.WebdavServletConfig;
import org.apache.slide.webdav.util.AclConstants;
import org.apache.slide.webdav.util.PreconditionViolationException;
import org.apache.slide.webdav.util.ViolatedPrecondition;
import org.apache.slide.webdav.util.WebdavStatus;
import org.jdom.Element;


/**
 * DAV:acl-principal-prop-set report worker.
 *
 */
public class AclPrincipalPropSetReport extends AbstractReport implements AclConstants {
    
    private RequestedProperties requestedProperties = null;
    
    /**
     * Constructor
     *
     * @param    slideToken          a  SlideToken
     * @param    token               a  NamespaceAccessToken
     * @param    config              a  WebdavServletConfig
     * @param    serverUrl           a  String
     * @param    contextPath         a  String
     */
    public AclPrincipalPropSetReport(SlideToken slideToken, NamespaceAccessToken token, WebdavServletConfig config, String slideContextPath) {
        super(slideToken, token, config, slideContextPath);
    }
    
    /**
     * Initialize report worker with specified report element
     *
     * @param    resourcePath           a  String
     * @param    aclPrincipalPropSetElm an Element
     *
     * @throws   PreconditionViolationException
     */
    public void init(String resourcePath, Element aclPrincipalPropSetElm) throws PreconditionViolationException {
        if (aclPrincipalPropSetElm.getChildren().size() == 0) {
            throw new PreconditionViolationException(
                new ViolatedPrecondition("at-least-one-child-element",
                                         WebdavStatus.SC_BAD_REQUEST,
                                         "DAV:acl-principal-prop-set element must have at least one child"),
                resourcePath
            );
        }
        List propElmL = aclPrincipalPropSetElm.getChildren(E_PROP, DNSP);
        if (propElmL.size() > 1) {
            throw new PreconditionViolationException(
                new ViolatedPrecondition("at-most-one-prop-element",
                                         WebdavStatus.SC_BAD_REQUEST,
                                         "DAV:acl-principal-prop-set element must have at most one DAV:prop child"),
                resourcePath
            );
        }
        
        if (propElmL.size() == 1) {
            Element propElm = (Element)propElmL.get(0);
            try {
                this.requestedProperties = new RequestedPropertiesImpl(propElm);
            }
            catch (PropertyParseException e) {
                throw new PreconditionViolationException(
                    new ViolatedPrecondition("invalid-prop",
                                             WebdavStatus.SC_BAD_REQUEST,
                                             e.getMessage()),
                    resourcePath
                );
            }
        }
    }
    
    /**
     * Execute report and add results to given multistatus element
     *
     * @param    resourcePath        a  String
     * @param    multistatusElm      an Element
     * @param    depth               an int
     *
     * @throws   SlideException
     * @throws   IOException
     */
    public void execute(String resourcePath, Element multistatusElm, int depth) throws SlideException, IOException {
        NodeRevisionDescriptors nrds = content.retrieve(slideToken, resourcePath);
        NodeRevisionDescriptor nrd = content.retrieve(slideToken, nrds);
        Enumeration permissions = security.enumeratePermissions(slideToken, resourcePath, true);
        while (permissions != null && permissions.hasMoreElements()) {
            NodePermission p = (NodePermission)permissions.nextElement();
            SubjectNode principalNode = SubjectNode.getSubjectNode(p.getSubjectUri());
            String principalPath = getPrincipalPath(principalNode, nrd);
            if (principalPath != null) {
                multistatusElm.addContent(getResponseElement(slideToken, principalPath, new NodeRevisionNumber(), requestedProperties));
            }
        }
    }
    
    private String getPrincipalPath(SubjectNode principalNode, NodeRevisionDescriptor nrd) throws SlideException {
        if (principalNode.equals(SubjectNode.ALL)
            || principalNode.equals(SubjectNode.SELF)
            || principalNode.equals(SubjectNode.AUTHENTICATED)
            || principalNode.equals(SubjectNode.UNAUTHENTICATED)
           )  {
            return null;
        }
        else if (principalNode.equals(SubjectNode.OWNER)) {
            NodeProperty ownerProp = nrd.getProperty(PN_OWNER);
            if (ownerProp != null) {
                return token.getNamespaceConfig().getUsersPath()+"/"+ownerProp.getValue();
            }
            else {
                return null;
            }
        }
        else {
            return principalNode.getUri();
        }
    }
    
    /**
     * Method checkPreconditions
     * @param    resourcePath        a  String
     * @param    depth               an int
     * @throws   PreconditionViolationException
     * @throws   ServiceAccessException
     */
    public void checkPreconditions(String resourcePath, int depth) throws PreconditionViolationException, ServiceAccessException {
        if (depth != 0) {
            throw new PreconditionViolationException(
                new ViolatedPrecondition("depth-must-be-zero",
                                         WebdavStatus.SC_BAD_REQUEST,
                                         "This report is only defined for depth=0."),
                resourcePath
            );
        }
    }
}
