/*
 * Copyright (c) Members of the EGEE Collaboration. 2012.
 * See http://www.eu-egee.org/partners/ for details on the copyright holders.
 *
 * 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.
 *
 * $Id$
 */
package demo;

import java.io.IOException;
import java.security.cert.X509Certificate;

import org.glite.authz.common.model.Action;
import org.glite.authz.common.model.Request;
import org.glite.authz.common.model.Resource;
import org.glite.authz.common.model.Response;
import org.glite.authz.common.model.Result;
import org.glite.authz.common.model.Subject;
import org.glite.authz.common.security.PEMFileReader;
import org.glite.authz.pep.client.PEPClient;
import org.glite.authz.pep.client.PEPClientException;
import org.glite.authz.pep.client.config.PEPClientConfiguration;
import org.glite.authz.pep.client.config.PEPClientConfigurationException;
import org.glite.authz.pep.profile.AuthorizationProfile;
import org.glite.authz.pep.profile.GridCEAuthorizationProfile;
import org.glite.authz.pep.profile.ProfileException;

/**
 * ArgusPEPClient
 * <p>
 * Example using the gLite CE XACML profile:
 * https://edms.cern.ch/document/1078881/
 * <p>
 * The XACML Subject, identifying the user, contains the user proxy. The
 * authorization decision contains a XACML Obligation (on permit decision)
 * defining the local user mapping.
 * <p>
 * 
 * @author Valery Tschopp &lt;valery.tschopp&#64;switch.ch&gt;
 */
public class ArgusPEPClient_GLite {

    /**
     * @param args
     */
    public static void main(String[] args) {

        // //////////////////////////////////
        // Argus PEP daemon endpoint
        String endpoint= "https://chaos.switch.ch:8154/authz";

        // //////////////////////////////////
        // trust and key material for the HTTPS/TLS communication
        // with the Argus PEP daemon
        String cadirname= "/etc/grid-security/certificates";
        String hostcert= "/etc/grid-security/hostcert.pem";
        String hostkey= "/etc/grid-security/hostkey.pem";
        String keypasswd= "MANDATORY_random_string_if_key_not_encrypted";

        // //////////////////////////////////
        // create PEP client config
        PEPClientConfiguration config= new PEPClientConfiguration();

        try {
            // set the PEP Server endpoint
            config.addPEPDaemonEndpoint(endpoint);
            // set the trust material (IGTF bundle)
            config.setTrustMaterial(cadirname);

            // set the key material (HTTPS client authentication)
            config.setKeyMaterial(hostcert, hostkey, keypasswd);

        } catch (PEPClientConfigurationException e) {
            System.err.println(e.getMessage());
            e.printStackTrace();
            System.exit(1);
        }

        // //////////////////////////////////
        // create the PEP client
        PEPClient pep= null;
        try {
            pep= new PEPClient(config);
        } catch (PEPClientException e) {
            System.err.println(e.getMessage());
            e.printStackTrace();
            System.exit(2);
        }

        // //////////////////////////////////
        // create the authorization request

        // gLite example (with user mapping, requires the user proxy) //
        // get the correct XACML profile to construct the XACML request
        // (factory)
        AuthorizationProfile profile= GridCEAuthorizationProfile.getInstance();

        // create a XACML Subject with a key-info attribute (user proxy)
        String userProxy= "/tmp/x509up_u959";
        X509Certificate[] certs= null;
        try {
            PEMFileReader reader= new PEMFileReader();
            certs= reader.readCertificates(userProxy);
        } catch (IOException e) {
            System.err.println(e.getMessage());
            e.printStackTrace();
            System.exit(3);
        }

        Subject subject= null;
        try {
            subject= profile.createSubjectKeyInfo(certs);
        } catch (ProfileException e) {
            System.err.println(e.getMessage());
            e.printStackTrace();
            System.exit(3);
        }

        // create a XACML resource
        String resourceId= "test-glite";
        Resource resource= profile.createResourceId(resourceId);

        // create a XACML action
        String actionId= "test";
        Action action= profile.createActionId(actionId);

        // create a XACML request
        Request request= profile.createRequest(subject, resource, action);

        System.out.println("---Request---");
        System.out.println(request);

        // //////////////////////////////////
        // submit the authorization request

        Response response= null;
        try {
            response= pep.authorize(request);
        } catch (PEPClientException e) {
            System.err.println(e.getMessage());
            e.printStackTrace();
            System.exit(5);
        }

        System.out.println("---Response---");
        System.out.println(response);

        // //////////////////////////////////
        // check the response result and status
        for (Result result : response.getResults()) {
            System.out.println("---Decision---");
            System.out.println(result.getDecisionString());
            int decision= result.getDecision();
            if (decision == Result.DECISION_PERMIT) {
                // check if any obligations
                System.out.println("---Obligations---");
                System.out.println(result.getObligations());
            }
        }

        System.out.println("------");

    }

}
