/*
 * $Header: /home/cvspublic/jakarta-slide/proposals/tamino/src/store/org/apache/slide/store/tamino/report/XPrincipalHasPrivilegeReport.java,v 1.1 2004/09/15 14:58:25 pnever Exp $
 * $Revision: 1.1 $
 * $Date: 2004/09/15 14:58:25 $
 *
 * ====================================================================
 *
 * Copyright 1999-2004 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.store.tamino.report;

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.common.SlideToken;
import org.apache.slide.store.tamino.security.URMSecurityImpl;
import org.apache.slide.structure.SubjectNode;
import org.apache.slide.urm.URMException;
import org.apache.slide.urm.accesscontroler.URMAclAdministrator;
import org.apache.slide.urm.accesscontroler.URMAclValidator;
import org.apache.slide.urm.authenticator.URMAdministrator;
import org.apache.slide.urm.common.URMPrincipal;
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.apache.slide.webdav.util.WebdavUtils;
import org.jdom.Element;
import org.jdom.Text;


/**
 * URM-based report implementationimplementation.
 *
 * @author <a href="mailto:peter.nevermann@softwareag.com">Peter Nevermann</a>
 * @version $Revision: 1.1 $
 */

public final class XPrincipalHasPrivilegeReport extends XAbstractReport implements AclConstants {
    
    private static final String E_PRINCIPAL_HAS_PRIVILEGE = "principal-has-privilege";
    
    private String principalName = null;
    private String privilegeName = null;
    
    
    /**
     * Constructor
     *
     * @param    slideToken          a  SlideToken
     * @param    token               a  NamespaceAccessToken
     * @param    config              a  WebdavServletConfig
     * @param    serverUrl           a  String
     * @param    contextPath         a  String
     */
    public XPrincipalHasPrivilegeReport(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    principalHasPrivilegeElm  an Element
     *
     * @throws   PreconditionViolationException
     */
    public void init(String resourcePath, Element principalHasPrivilegeElm) throws PreconditionViolationException {
        List children = principalHasPrivilegeElm.getChildren(E_PRINCIPAL, DNSP);
        if (children.size() > 1) {
            throw new PreconditionViolationException(
                new ViolatedPrecondition("at-most-one-principal-element",
                                         WebdavStatus.SC_BAD_REQUEST,
                                         "the DAV:principal-has-privilege element must contain at most one DAV:principal element"),
                resourcePath
            );
        }
        else if (children.size() == 0) {
            return;
        }
        
        this.principalName = getPrincipalName((Element)children.get(0), resourcePath);
        
        // now get the privilege
        children = principalHasPrivilegeElm.getChildren(E_PRIVILEGE, DNSP);
        if (children.size() > 1) {
            throw new PreconditionViolationException(
                new ViolatedPrecondition("at-most-one-privilege-element",
                                         WebdavStatus.SC_BAD_REQUEST,
                                         "the DAV:principal-has-privilege element must contain at most one DAV:privilege element"),
                resourcePath
            );
        }
        else if (children.size() == 0) {
            return;
        }
        
        this.privilegeName = getPrivilegeName((Element)children.get(0), resourcePath);
    }
    
    protected void writeReport(String resourcePath, Element multistatusElm) throws SlideException {
        // check read-acl privilege first
        checkPermissions(resourcePath);
        
        // create the report
        Element responseElm = new Element(E_RESPONSE, DNSP);
        Element hrefElm = new Element(E_HREF, DNSP);
        Element propstatElm = new Element(E_PROPSTAT, DNSP);
        Element propElm = new Element(E_PROP, DNSP);
        Element statusElm = new Element(E_STATUS, DNSP);
        Element principalHasPrivilegeElm = new Element(E_PRINCIPAL_HAS_PRIVILEGE, DNSP);
        
        multistatusElm.addContent(responseElm);
        responseElm.addContent(hrefElm);
        
        String absUri = WebdavUtils.getAbsolutePath (resourcePath, slideContextPath, config);
        hrefElm.setText(absUri);
        responseElm.addContent(propstatElm);
        propstatElm.addContent(propElm);
        propElm.addContent(principalHasPrivilegeElm);
        propstatElm.addContent(statusElm);
        int sc = WebdavStatus.SC_OK;
        statusElm.addContent(new Text(HTTP_VERSION+" "+sc+" "+WebdavStatus.getStatusText(sc)));
        
        URMPrincipal principal = null;
        URMAdministrator urmadmin = null;
        URMAclAdministrator admin = null;
        
        try {
            principal = (URMPrincipal)slideToken.getCredentialsToken().getPrincipal();
            urmadmin = principal.getURMAdministrator();
            admin = principal.getURMAclAdministrator();
        }
        catch (URMException e) {
            throw new SlideException("URM access failed: "+e.getMessage());
        }
        
        List checkList = ((URMSecurityImpl)security).inheritedAclSet(slideToken, new SubjectNode(resourcePath));
        
        int result = -1;
        try {
            result = admin.subjectPermissionReport(principal, urmadmin.getUser(principalName, principal.getDomain()),checkList, privilegeName);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceAccessException(null, "Could not access URM: "+e.getMessage());
        }
        
        Element grantDenyElm = (result == URMAclValidator.URMPermit
                                    ? new Element(E_GRANT, DNSP)
                                    : new Element(E_DENY, DNSP));
        principalHasPrivilegeElm.addContent(grantDenyElm);
    }
}


