/*
 * $Header: /home/cvspublic/jakarta-slide/proposals/tamino/src/store/org/apache/slide/store/tamino/report/XPrincipalPrivilegeSetReport.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.Iterator;
import java.util.List;
import java.util.Map;
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.accesscontroler.impl.URMPermissionResultImpl;
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 XPrincipalPrivilegeSetReport extends XAbstractReport implements AclConstants {
    
    private static final String E_PRINCIPAL_PRIVILEGE_SET = "principal-privilege-set";
    
    private String principalName = null;
    
    
    /**
     * Constructor
     *
     * @param    slideToken          a  SlideToken
     * @param    token               a  NamespaceAccessToken
     * @param    config              a  WebdavServletConfig
     * @param    serverUrl           a  String
     * @param    contextPath         a  String
     */
    public XPrincipalPrivilegeSetReport(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    principalPrivilegeSetElm   an Element
     *
     * @throws   PreconditionViolationException
     */
    public void init(String resourcePath, Element principalPrivilegeSetElm) throws PreconditionViolationException {
        List children = principalPrivilegeSetElm.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-privilege-set element must contain at most one DAV:principal element"),
                resourcePath
            );
        }
        else if (children.size() == 0) {
            return;
        }
        
        this.principalName = getPrincipalName((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 principalPrivilegeSetElm = new Element(E_PRINCIPAL_PRIVILEGE_SET, DNSP);
        
        multistatusElm.addContent(responseElm);
        responseElm.addContent(hrefElm);
        hrefElm.setText (WebdavUtils.getAbsolutePath (resourcePath, slideContextPath, config));
        responseElm.addContent(propstatElm);
        propstatElm.addContent(propElm);
        propElm.addContent(principalPrivilegeSetElm);
        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));
        
        Map result = null;
        try {
            result = admin.subjectPermissionSetReport(principal, urmadmin.getUser(principalName, principal.getDomain()),checkList);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceAccessException(null, "Could not access URM: "+e.getMessage());
        }
        
        Iterator i = result.entrySet().iterator();
        while (i.hasNext()) {
            Map.Entry e = (Map.Entry)i.next();
            String key = (String)e.getKey();
            URMPermissionResultImpl value = (URMPermissionResultImpl)e.getValue();
            //            multistatusElm.addContent(new Text("key="+key+", value="+value.getPermission()+"\n"));
            if (value.getPermission() == URMAclValidator.URMPermit) {
                Element privilegeElement = new Element(E_PRIVILEGE, DNSP);
                principalPrivilegeSetElm.addContent(privilegeElement);
                Element pElm = new Element(key, DNSP);
                privilegeElement.addContent(pElm);
            }
        }
    }
}


