[jboss-cvs] JBossAS SVN: r71808 - in projects/security/security-xacml/trunk: jboss-sunxacml/src/main/java/org/jboss/security/xacml/sunxacml/support and 5 other directories.

jboss-cvs-commits at lists.jboss.org jboss-cvs-commits at lists.jboss.org
Tue Apr 8 18:51:45 EDT 2008


Author: mmoyses
Date: 2008-04-08 18:51:45 -0400 (Tue, 08 Apr 2008)
New Revision: 71808

Added:
   projects/security/security-xacml/trunk/jboss-sunxacml/src/main/java/org/jboss/security/xacml/sunxacml/support/
   projects/security/security-xacml/trunk/jboss-sunxacml/src/main/java/org/jboss/security/xacml/sunxacml/support/SimplePDP.java
   projects/security/security-xacml/trunk/jboss-sunxacml/src/main/java/org/jboss/security/xacml/sunxacml/support/finder/
   projects/security/security-xacml/trunk/jboss-sunxacml/src/main/java/org/jboss/security/xacml/sunxacml/support/finder/BasicPolicyFinderModule.java
   projects/security/security-xacml/trunk/jboss-sunxacml/src/main/java/org/jboss/security/xacml/sunxacml/support/finder/FilePolicyModule.java
   projects/security/security-xacml/trunk/jboss-sunxacml/src/main/java/org/jboss/security/xacml/sunxacml/support/finder/PolicyCollection.java
   projects/security/security-xacml/trunk/jboss-sunxacml/src/main/java/org/jboss/security/xacml/sunxacml/support/finder/PolicyReader.java
   projects/security/security-xacml/trunk/jboss-sunxacml/src/main/java/org/jboss/security/xacml/sunxacml/support/finder/StaticPolicyFinderModule.java
   projects/security/security-xacml/trunk/jboss-sunxacml/src/main/java/org/jboss/security/xacml/sunxacml/support/finder/StaticRefPolicyFinderModule.java
   projects/security/security-xacml/trunk/jboss-sunxacml/src/main/java/org/jboss/security/xacml/sunxacml/support/finder/TopLevelPolicyException.java
   projects/security/security-xacml/trunk/jboss-sunxacml/src/main/java/org/jboss/security/xacml/sunxacml/support/finder/URLPolicyFinderModule.java
   projects/security/security-xacml/trunk/jboss-xacml/src/tests/java/org/jboss/test/security/test/
   projects/security/security-xacml/trunk/jboss-xacml/src/tests/java/org/jboss/test/security/test/xacml/
   projects/security/security-xacml/trunk/jboss-xacml/src/tests/java/org/jboss/test/security/test/xacml/XACMLRequestCreationUnitTestCase.java
   projects/security/security-xacml/trunk/jboss-xacml/src/tests/java/org/jboss/test/security/test/xacml/XACMLUnitTestCase.java
   projects/security/security-xacml/trunk/jboss-xacml/src/tests/java/org/jboss/test/security/test/xacml/XACMLUtil.java
   projects/security/security-xacml/trunk/jboss-xacml/src/tests/java/org/jboss/test/security/test/xacml/modules/
   projects/security/security-xacml/trunk/jboss-xacml/src/tests/java/org/jboss/test/security/test/xacml/modules/JBossStaticPolicyFinderModule.java
   projects/security/security-xacml/trunk/jboss-xacml/src/tests/java/org/jboss/test/security/test/xacml/modules/TestResourceFinderModule.java
   projects/security/security-xacml/trunk/jboss-xacml/src/tests/java/org/jboss/test/security/test/xacml/modules/TestRoleAttributeFinderModule.java
Log:
JBAS-5372

Added: projects/security/security-xacml/trunk/jboss-sunxacml/src/main/java/org/jboss/security/xacml/sunxacml/support/SimplePDP.java
===================================================================
--- projects/security/security-xacml/trunk/jboss-sunxacml/src/main/java/org/jboss/security/xacml/sunxacml/support/SimplePDP.java	                        (rev 0)
+++ projects/security/security-xacml/trunk/jboss-sunxacml/src/main/java/org/jboss/security/xacml/sunxacml/support/SimplePDP.java	2008-04-08 22:51:45 UTC (rev 71808)
@@ -0,0 +1,220 @@
+/*
+ * @(#)SimplePDP.java
+ *
+ * Copyright 2003-2006 Sun Microsystems, Inc. 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. Redistribution of source code must retain the above copyright notice,
+ *      this list of conditions and the following disclaimer.
+ * 
+ *   2. Redistribution 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.
+ *
+ * Neither the name of Sun Microsystems, Inc. or the names of contributors may
+ * be used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ * 
+ * This software is provided "AS IS," without a warranty of any kind. ALL
+ * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
+ * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
+ * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
+ * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
+ * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+ * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
+ * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
+ * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
+ * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
+ * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
+ *
+ * You acknowledge that this software is not designed or intended for use in
+ * the design, construction, operation or maintenance of any nuclear facility.
+ */
+
+package org.jboss.security.xacml.sunxacml.support;
+
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import org.jboss.security.xacml.sunxacml.ConfigurationStore;
+import org.jboss.security.xacml.sunxacml.Indenter;
+import org.jboss.security.xacml.sunxacml.PDP;
+import org.jboss.security.xacml.sunxacml.PDPConfig;
+import org.jboss.security.xacml.sunxacml.ParsingException;
+import org.jboss.security.xacml.sunxacml.combine.PermitOverridesPolicyAlg;
+import org.jboss.security.xacml.sunxacml.ctx.RequestCtx;
+import org.jboss.security.xacml.sunxacml.ctx.ResponseCtx;
+import org.jboss.security.xacml.sunxacml.finder.AttributeFinder;
+import org.jboss.security.xacml.sunxacml.finder.PolicyFinder;
+import org.jboss.security.xacml.sunxacml.finder.impl.CurrentEnvModule;
+import org.jboss.security.xacml.sunxacml.finder.impl.SelectorModule;
+import org.jboss.security.xacml.sunxacml.support.finder.StaticPolicyFinderModule;
+import org.jboss.security.xacml.sunxacml.support.finder.StaticRefPolicyFinderModule;
+import org.jboss.security.xacml.sunxacml.support.finder.URLPolicyFinderModule;
+
+/**
+ * This is a simple, command-line driven XACML PDP. It acts both as an example
+ * of how to write a full-featured PDP and as a sample program that lets you
+ * evaluate requests against policies. See the comments for the main() method
+ * for correct usage.
+ * <p>
+ * As of the 2.0 release, this has been moved into the new support tree of the
+ * codebase. It has also been updated to use several of the new finder
+ * modules provided in the support tree codebase, so that static and dynamic
+ * references are supported, policies can be loaded from URLs, top-level
+ * policies are wrapped in a policy set when more than one applies, etc.
+ * <p>
+ * If you don't use a configuration file, then the default modules can all
+ * optionally support schema validation. To turn this on, provide the filename
+ * of the schema file in the property "com.sun.xacml.PolicySchema". You can
+ * also turn this on if you use a configuration file and it includes the
+ * modules provided in the support package.
+ *
+ * @since 1.1
+ * @author Seth Proctor
+ */
+public class SimplePDP
+{
+
+   // this is the actual PDP object we'll use for evaluation
+   private PDP pdp = null;
+
+   /**
+    * Default constructor. This creates a <code>SimplePDP</code> with a
+    * <code>PDP</code> based on the configuration defined by the runtime
+    * property com.sun.xcaml.PDPConfigFile.
+    */
+   public SimplePDP() throws Exception
+   {
+      // load the configuration
+      ConfigurationStore store = new ConfigurationStore();
+
+      // use the default factories from the configuration
+      store.useDefaultFactories();
+
+      // get the PDP configuration's and setup the PDP
+      pdp = new PDP(store.getDefaultPDPConfig());
+   }
+
+   /**
+    * Constructor that takes an array of filenames and URLs, each of which
+    * points to an XACML policy, and sets up a <code>PDP</code> with access
+    * to these policies only. These policies may be accessed based on
+    * context matching or by reference (based on their policy identifiers).
+    * The <code>PDP</code> is also setup to support dynamic URL references.
+    *
+    * @param policies an arry of filenames and URLs that specify policies
+    */
+   public SimplePDP(String[] policies) throws Exception
+   {
+      // Create the two static modules with the given policies so that
+      // we have context-based and reference-based access to all the
+      // policies provided on the command-line
+      List policyList = Arrays.asList(policies);
+      StaticPolicyFinderModule staticModule = new StaticPolicyFinderModule(PermitOverridesPolicyAlg.algId, policyList);
+      StaticRefPolicyFinderModule staticRefModule = new StaticRefPolicyFinderModule(policyList);
+
+      // also create a module that lets us get at URL-based policies
+      URLPolicyFinderModule urlModule = new URLPolicyFinderModule();
+
+      // next, setup the PolicyFinder that this PDP will use
+      PolicyFinder policyFinder = new PolicyFinder();
+      Set policyModules = new HashSet();
+      policyModules.add(staticModule);
+      policyModules.add(staticRefModule);
+      policyModules.add(urlModule);
+      policyFinder.setModules(policyModules);
+
+      // now setup attribute finder modules for the current date/time and
+      // AttributeSelectors (selectors are optional, but this project does
+      // support a basic implementation)
+      CurrentEnvModule envAttributeModule = new CurrentEnvModule();
+      SelectorModule selectorAttributeModule = new SelectorModule();
+
+      // Setup the AttributeFinder just like we setup the PolicyFinder. Note
+      // that unlike with the policy finder, the order matters here. See the
+      // the javadocs for more details.
+      AttributeFinder attributeFinder = new AttributeFinder();
+      List attributeModules = new ArrayList();
+      attributeModules.add(envAttributeModule);
+      attributeModules.add(selectorAttributeModule);
+      attributeFinder.setModules(attributeModules);
+
+      // finally, initialize our pdp
+      pdp = new PDP(new PDPConfig(attributeFinder, policyFinder, null));
+   }
+
+   /**
+    * Evaluates the given request and returns the Response that the PDP
+    * will hand back to the PEP.
+    *
+    * @param requestFile the name of a file that contains a Request
+    *
+    * @return the result of the evaluation
+    *
+    * @throws IOException if there is a problem accessing the file
+    * @throws ParsingException if the Request is invalid
+    */
+   public ResponseCtx evaluate(String requestFile) throws IOException, ParsingException
+   {
+      // setup the request based on the file
+      RequestCtx request = RequestCtx.getInstance(new FileInputStream(requestFile));
+
+      // evaluate the request
+      return pdp.evaluate(request);
+   }
+
+   /**
+    * Main-line driver for this sample code. This method lets you invoke
+    * the PDP directly from the command-line.
+    *
+    * @param args the input arguments to the class. They are either the
+    *             flag "-config" followed by a request file, or a request
+    *             file followed by one or more policy files. In the case
+    *             that the configuration flag is used, the configuration
+    *             file must be specified in the standard java property,
+    *             com.sun.xacml.PDPConfigFile.
+    */
+   public static void main(String[] args) throws Exception
+   {
+      if (args.length < 2)
+      {
+         System.out.println("Usage: -config <request>");
+         System.out.println("       <request> <policy> [policies]");
+         System.exit(1);
+      }
+
+      SimplePDP simplePDP = null;
+      String requestFile = null;
+
+      if (args[0].equals("-config"))
+      {
+         requestFile = args[1];
+         simplePDP = new SimplePDP();
+      }
+      else
+      {
+         requestFile = args[0];
+         String[] policyFiles = new String[args.length - 1];
+
+         for (int i = 1; i < args.length; i++)
+            policyFiles[i - 1] = args[i];
+
+         simplePDP = new SimplePDP(policyFiles);
+      }
+
+      // evaluate the request
+      ResponseCtx response = simplePDP.evaluate(requestFile);
+
+      // for this sample program, we'll just print out the response
+      response.encode(System.out, new Indenter());
+   }
+
+}

Added: projects/security/security-xacml/trunk/jboss-sunxacml/src/main/java/org/jboss/security/xacml/sunxacml/support/finder/BasicPolicyFinderModule.java
===================================================================
--- projects/security/security-xacml/trunk/jboss-sunxacml/src/main/java/org/jboss/security/xacml/sunxacml/support/finder/BasicPolicyFinderModule.java	                        (rev 0)
+++ projects/security/security-xacml/trunk/jboss-sunxacml/src/main/java/org/jboss/security/xacml/sunxacml/support/finder/BasicPolicyFinderModule.java	2008-04-08 22:51:45 UTC (rev 71808)
@@ -0,0 +1,260 @@
+/*
+ * @(#)BasicPolicyFinderModule.java
+ *
+ * Copyright 2006 Sun Microsystems, Inc. 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. Redistribution of source code must retain the above copyright notice,
+ *      this list of conditions and the following disclaimer.
+ * 
+ *   2. Redistribution 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.
+ *
+ * Neither the name of Sun Microsystems, Inc. or the names of contributors may
+ * be used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ * 
+ * This software is provided "AS IS," without a warranty of any kind. ALL
+ * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
+ * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
+ * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
+ * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
+ * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+ * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
+ * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
+ * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
+ * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
+ * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
+ *
+ * You acknowledge that this software is not designed or intended for use in
+ * the design, construction, operation or maintenance of any nuclear facility.
+ */
+
+package org.jboss.security.xacml.sunxacml.support.finder;
+
+import java.net.URI;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import org.jboss.security.xacml.sunxacml.AbstractPolicy;
+import org.jboss.security.xacml.sunxacml.EvaluationCtx;
+import org.jboss.security.xacml.sunxacml.PolicyMetaData;
+import org.jboss.security.xacml.sunxacml.VersionConstraints;
+import org.jboss.security.xacml.sunxacml.combine.PolicyCombiningAlgorithm;
+import org.jboss.security.xacml.sunxacml.finder.PolicyFinder;
+import org.jboss.security.xacml.sunxacml.finder.PolicyFinderModule;
+import org.jboss.security.xacml.sunxacml.finder.PolicyFinderResult;
+
+/**
+ * This is a basic implementation of <code>PolicyFinderModule</code> that
+ * accepts already created <code>AbstractPolicy</code>s and supports
+ * finding by context and reference. All policies are held forever once
+ * added to this module, and cannot be refreshed or removed. New policies
+ * may be added at any point. You may optionally specify a combining
+ * algorithm to use when more than one applicable policy is found, and then
+ * a new PolicySet is wrapped around the policies using this algorithm. If
+ * no combining algorithm is provided, then an error is returned if more
+ * than one policy matches.
+ * <p>
+ * This module is provided as an example, but is still fully functional, and
+ * should be useful for many simple applications. This is provided in the
+ * <code>support</code> package rather than the core codebase because it
+ * implements non-standard behavior.
+ *
+ * @since 2.0
+ * @author Seth Proctor
+ */
+public class BasicPolicyFinderModule extends PolicyFinderModule
+{
+
+   // the collections used to handle both kinds of policies
+   private PolicyCollection ctxPolicies;
+
+   private PolicyCollection refPolicies;
+
+   // the combining alg, or null if none is used
+   private PolicyCombiningAlgorithm combiningAlg;
+
+   // the policy identifier for any policy sets we dynamically create
+   private static final String POLICY_ID = "urn:com:sun:xacml:support:finder:dynamic-policy-set";
+
+   private static URI policyId = null;
+
+   // the logger we'll use for all messages
+   private static final Logger logger = Logger.getLogger(BasicPolicyFinderModule.class.getName());
+
+   static
+   {
+      try
+      {
+         policyId = new URI(POLICY_ID);
+      }
+      catch (Exception e)
+      {
+         // this can't actually happen, but just in case...
+         if (logger.isLoggable(Level.SEVERE))
+            logger.log(Level.SEVERE, "couldn't assign default policy id");
+      }
+   };
+
+   /**
+    * Creates a <code>BasicPolicyFinderModule</code>.
+    */
+   public BasicPolicyFinderModule()
+   {
+      ctxPolicies = new PolicyCollection();
+      refPolicies = new PolicyCollection();
+   }
+
+   /**
+    * Creates a <code>BasicPolicyFinderModule</code> that can combine
+    * multiple applicable policies under a single, dynamic PolicySet.
+    *
+    * @param combiningAlg the algorithm to use in a new PolicySet when more
+    *                     than one policy applies
+    */
+   public BasicPolicyFinderModule(PolicyCombiningAlgorithm combiningAlg)
+   {
+      ctxPolicies = new PolicyCollection(combiningAlg, policyId);
+      refPolicies = new PolicyCollection(combiningAlg, policyId);
+   }
+
+   /**
+    * Adds a policy that will be available both by reference and by
+    * matching to a context. The policy's identifier is used for finding
+    * by reference. If a policy with the same identifier and version is
+    * already handled by this module, then the policy is not added.
+    *
+    * @param policy the policy to add
+    *
+    * @return true if the policy was added, false otherwise
+    */
+   public synchronized boolean addPolicy(AbstractPolicy policy)
+   {
+      if (ctxPolicies.addPolicy(policy))
+         return refPolicies.addPolicy(policy);
+      else
+         return false;
+   }
+
+   /**
+    * Adds a policy that will be available only by matching to a context.
+    * If a policy with the same identifier and version is already handled
+    * by this module, then the policy is not added.
+    *
+    * @param policy the policy to add
+    *
+    * @return true if the policy was added, false otherwise
+    */
+   public synchronized boolean addPolicyNoRef(AbstractPolicy policy)
+   {
+      return ctxPolicies.addPolicy(policy);
+   }
+
+   /**
+    * Adds a policy that will be available only by reference. The policy's
+    * identifier is used for finding by reference. If a policy with the
+    * same identifier and version is already handled by this module, then
+    * the policy is not added.
+    *
+    * @param policy the policy to add
+    *
+    * @return true if the policy was added, false otherwise
+    */
+   public synchronized boolean addPolicyOnlyRef(AbstractPolicy policy)
+   {
+      return refPolicies.addPolicy(policy);
+   }
+
+   /**
+    * Always returns <code>true</code> since this module does support
+    * finding policies based on context matching.
+    *
+    * @return true
+    */
+   public boolean isRequestSupported()
+   {
+      return true;
+   }
+
+   /**
+    * Always returns <code>true</code> since this module does support
+    * finding policies based on reference.
+    *
+    * @return true
+    */
+   public boolean isIdReferenceSupported()
+   {
+      return true;
+   }
+
+   /**
+    * Initialize this module. Typically this is called by
+    * <code>PolicyFinder</code> when a PDP is created.
+    *
+    * @param finder the <code>PolicyFinder</code> using this module
+    */
+   public void init(PolicyFinder finder)
+   {
+      // we don't need to do anything here
+   }
+
+   /**
+    * Finds a policy based on a request's context. If more than one policy
+    * matches, then this either returns an error or a new policy wrapping
+    * the multiple policies (depending on which constructor was used to
+    * construct this instance).
+    *
+    * @param context the representation of the request data
+    *
+    * @return the result of trying to find an applicable policy
+    */
+   public PolicyFinderResult findPolicy(EvaluationCtx context)
+   {
+      try
+      {
+         AbstractPolicy policy = ctxPolicies.getPolicy(context);
+
+         if (policy == null)
+            return new PolicyFinderResult();
+         else
+            return new PolicyFinderResult(policy);
+      }
+      catch (TopLevelPolicyException tlpe)
+      {
+         return new PolicyFinderResult(tlpe.getStatus());
+      }
+   }
+
+   /**
+    * Attempts to find a policy by reference, based on the provided
+    * parameters.
+    *
+    * @param idReference an identifier specifying some policy
+    * @param type type of reference (policy or policySet) as identified by
+    *             the fields in <code>PolicyReference</code>
+    * @param constraints any optional constraints on the version of the
+    *                    referenced policy (this will never be null, but
+    *                    it may impose no constraints, and in fact will
+    *                    never impose constraints when used from a pre-2.0
+    *                    XACML policy)
+    * @param parentMetaData the meta-data from the parent policy, which
+    *                       provides XACML version, factories, etc.
+    *
+    * @return the result of looking for a matching policy
+    */
+   public PolicyFinderResult findPolicy(URI idReference, int type, VersionConstraints constraints,
+         PolicyMetaData parentMetaData)
+   {
+      AbstractPolicy policy = refPolicies.getPolicy(idReference.toString(), type, constraints);
+
+      if (policy == null)
+         return new PolicyFinderResult();
+      else
+         return new PolicyFinderResult(policy);
+   }
+
+}

Added: projects/security/security-xacml/trunk/jboss-sunxacml/src/main/java/org/jboss/security/xacml/sunxacml/support/finder/FilePolicyModule.java
===================================================================
--- projects/security/security-xacml/trunk/jboss-sunxacml/src/main/java/org/jboss/security/xacml/sunxacml/support/finder/FilePolicyModule.java	                        (rev 0)
+++ projects/security/security-xacml/trunk/jboss-sunxacml/src/main/java/org/jboss/security/xacml/sunxacml/support/finder/FilePolicyModule.java	2008-04-08 22:51:45 UTC (rev 71808)
@@ -0,0 +1,263 @@
+/*
+ * @(#)FilePolicyModule.java
+ *
+ * Copyright 2003-2006 Sun Microsystems, Inc. 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. Redistribution of source code must retain the above copyright notice,
+ *      this list of conditions and the following disclaimer.
+ * 
+ *   2. Redistribution 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.
+ *
+ * Neither the name of Sun Microsystems, Inc. or the names of contributors may
+ * be used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ * 
+ * This software is provided "AS IS," without a warranty of any kind. ALL
+ * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
+ * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
+ * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
+ * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
+ * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+ * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
+ * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
+ * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
+ * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
+ * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
+ *
+ * You acknowledge that this software is not designed or intended for use in
+ * the design, construction, operation or maintenance of any nuclear facility.
+ */
+
+package org.jboss.security.xacml.sunxacml.support.finder;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import org.jboss.security.xacml.sunxacml.AbstractPolicy;
+import org.jboss.security.xacml.sunxacml.EvaluationCtx;
+import org.jboss.security.xacml.sunxacml.ParsingException;
+import org.jboss.security.xacml.sunxacml.finder.PolicyFinder;
+import org.jboss.security.xacml.sunxacml.finder.PolicyFinderModule;
+import org.jboss.security.xacml.sunxacml.finder.PolicyFinderResult;
+
+/**
+ * This module represents a collection of files containing polices,
+ * each of which will be searched through when trying to find a
+ * policy that is applicable to a specific request. It does not support
+ * policy references.
+ * <p>
+ * Note that this class used to be provided in the
+ * <code>com.sun.xacml.finder.impl</code> package with a warning that it
+ * would move out of the core packages eventually. This is partly because
+ * this class doesn't represent standard functionality, and partly because
+ * it isn't designed to be generally useful as anything more than an
+ * example. Because so many people have used this class, however, it stayed
+ * in place until the 2.0 release.
+ * <p>
+ * As of the 2.0 release, you may still use this class (in its new location),
+ * but you are encouraged to migrate to the new support modules that are
+ * much richer and designed for general-purpose use. Also, note that the
+ * <code>loadPolicy</code> methods that used to be available from this class
+ * have been removed. That functionality has been replaced by the much more
+ * useful <code>PolicyReader</code> class. If you need to load policies
+ * directly, you should consider that new class.
+ *
+ * @since 1.0
+ * @author Seth Proctor
+ */
+public class FilePolicyModule extends PolicyFinderModule
+{
+
+   // the schema file we're using, if any
+   private File schemaFile = null;
+
+   // the filenames for the files we'll load
+   private Set fileNames;
+
+   // the actual loaded policies
+   private PolicyCollection policies;
+
+   // the logger we'll use for all messages
+   private static final Logger logger = Logger.getLogger(FilePolicyModule.class.getName());
+
+   /**
+    * Constructor which retrieves the schema file to validate policies against
+    * from the <code>PolicyReader.POLICY_SCHEMA_PROPERTY</code>. If the
+    * retrieved property is null, then no schema validation will occur.
+    */
+   public FilePolicyModule()
+   {
+      fileNames = new HashSet();
+      policies = new PolicyCollection();
+
+      String schemaName = System.getProperty(PolicyReader.POLICY_SCHEMA_PROPERTY);
+
+      if (schemaName != null)
+         schemaFile = new File(schemaName);
+   }
+
+   /**
+    * Constructor that uses the specified <code>File</code> as the schema
+    * file for XML validation. If schema validation is not desired, a null
+    * value should be used.
+    *
+    * @param schemaFile the schema file to validate policies against,
+    *                   or null if schema validation is not desired.
+    */
+   public FilePolicyModule(File schemaFile)
+   {
+      fileNames = new HashSet();
+      policies = new PolicyCollection();
+
+      this.schemaFile = schemaFile;
+   }
+
+   /**
+    * Constructor that uses the specified <code>String</code> as the schema
+    * file for XML validation. If schema validation is not desired, a null
+    * value should be used.
+    *
+    * @param schemaFile the schema file to validate policies against,
+    *                   or null if schema validation is not desired.
+    */
+   public FilePolicyModule(String schemaFile)
+   {
+      this((schemaFile != null) ? new File(schemaFile) : null);
+   }
+
+   /**
+    * Constructor that specifies a set of initial policy files to use. This
+    * retrieves the schema file to validate policies against from the
+    * <code>PolicyReader.POLICY_SCHEMA_PROPERTY</code>. If the retrieved
+    * property is null, then no schema validation will occur.
+    *
+    * @param fileNames a <code>List</code> of <code>String</code>s that
+    *                  identify policy files
+    */
+   public FilePolicyModule(List fileNames)
+   {
+      this();
+
+      if (fileNames != null)
+         this.fileNames.addAll(fileNames);
+   }
+
+   /**
+    * Constructor that specifies a set of initial policy files to use and
+    * the schema file used to validate the policies. If schema validation is
+    * not desired, a null value should be used.
+    *
+    * @param fileNames a <code>List</code> of <code>String</code>s that
+    *                  identify policy files
+    * @param schemaFile the schema file to validate policies against,
+    *                   or null if schema validation is not desired.
+    */
+   public FilePolicyModule(List fileNames, String schemaFile)
+   {
+      this(schemaFile);
+
+      if (fileNames != null)
+         this.fileNames.addAll(fileNames);
+   }
+
+   /**
+    * Adds a file (containing a policy) to the collection of filenames
+    * associated with this module. Note that this doesn't actually load the
+    * policy file. Policies aren't loaded from their files until the
+    * module is initialized through the <code>init</code> method (which
+    * is called automatically by the <code>PolicyFinder</code> when the
+    * system comes up).
+    *
+    * @param filename the file to add to this module's collection of files
+    */
+   public boolean addPolicy(String filename)
+   {
+      return fileNames.add(filename);
+   }
+
+   /**
+    * Indicates whether this module supports finding policies based on
+    * a request (target matching). Since this module does support
+    * finding policies based on requests, it returns true.
+    *
+    * @return true, since finding policies based on requests is supported
+    */
+   public boolean isRequestSupported()
+   {
+      return true;
+   }
+
+   /**
+    * Initializes the <code>FilePolicyModule</code> by loading
+    * the policies contained in the collection of files associated
+    * with this module. This method also uses the specified 
+    * <code>PolicyFinder</code> to help in instantiating PolicySets.
+    *
+    * @param finder a PolicyFinder used to help in instantiating PolicySets
+    */
+   public void init(PolicyFinder finder)
+   {
+      PolicyReader reader = new PolicyReader(finder, logger, schemaFile);
+
+      Iterator it = fileNames.iterator();
+      while (it.hasNext())
+      {
+         String fname = (String) (it.next());
+         try
+         {
+            AbstractPolicy policy = reader.readPolicy(new FileInputStream(fname));
+            policies.addPolicy(policy);
+         }
+         catch (FileNotFoundException fnfe)
+         {
+            if (logger.isLoggable(Level.WARNING))
+               logger.log(Level.WARNING, "File couldn't be read: " + fname, fnfe);
+         }
+         catch (ParsingException pe)
+         {
+            if (logger.isLoggable(Level.WARNING))
+               logger.log(Level.WARNING, "Error reading policy from file " + fname, pe);
+         }
+      }
+   }
+
+   /**
+    * Finds a policy based on a request's context. If more than one
+    * applicable policy is found, this will return an error. Note that
+    * this is basically just a subset of the OnlyOneApplicable Policy
+    * Combining Alg that skips the evaluation step. See comments in there
+    * for details on this algorithm.
+    *
+    * @param context the representation of the request data
+    *
+    * @return the result of trying to find an applicable policy
+    */
+   public PolicyFinderResult findPolicy(EvaluationCtx context)
+   {
+      try
+      {
+         AbstractPolicy policy = policies.getPolicy(context);
+         if (policy == null)
+            return new PolicyFinderResult();
+         else
+            return new PolicyFinderResult(policy);
+      }
+      catch (TopLevelPolicyException tlpe)
+      {
+         return new PolicyFinderResult(tlpe.getStatus());
+      }
+   }
+
+}

Added: projects/security/security-xacml/trunk/jboss-sunxacml/src/main/java/org/jboss/security/xacml/sunxacml/support/finder/PolicyCollection.java
===================================================================
--- projects/security/security-xacml/trunk/jboss-sunxacml/src/main/java/org/jboss/security/xacml/sunxacml/support/finder/PolicyCollection.java	                        (rev 0)
+++ projects/security/security-xacml/trunk/jboss-sunxacml/src/main/java/org/jboss/security/xacml/sunxacml/support/finder/PolicyCollection.java	2008-04-08 22:51:45 UTC (rev 71808)
@@ -0,0 +1,364 @@
+/*
+ * @(#)PolicyCollection.java
+ *
+ * Copyright 2006 Sun Microsystems, Inc. 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. Redistribution of source code must retain the above copyright notice,
+ *      this list of conditions and the following disclaimer.
+ * 
+ *   2. Redistribution 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.
+ *
+ * Neither the name of Sun Microsystems, Inc. or the names of contributors may
+ * be used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ * 
+ * This software is provided "AS IS," without a warranty of any kind. ALL
+ * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
+ * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
+ * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
+ * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
+ * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+ * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
+ * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
+ * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
+ * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
+ * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
+ *
+ * You acknowledge that this software is not designed or intended for use in
+ * the design, construction, operation or maintenance of any nuclear facility.
+ */
+
+package org.jboss.security.xacml.sunxacml.support.finder;
+
+import java.net.URI;
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.StringTokenizer;
+import java.util.TreeSet;
+
+import org.jboss.security.xacml.sunxacml.AbstractPolicy;
+import org.jboss.security.xacml.sunxacml.EvaluationCtx;
+import org.jboss.security.xacml.sunxacml.MatchResult;
+import org.jboss.security.xacml.sunxacml.Policy;
+import org.jboss.security.xacml.sunxacml.PolicyMetaData;
+import org.jboss.security.xacml.sunxacml.PolicyReference;
+import org.jboss.security.xacml.sunxacml.PolicySet;
+import org.jboss.security.xacml.sunxacml.Target;
+import org.jboss.security.xacml.sunxacml.TargetMatch;
+import org.jboss.security.xacml.sunxacml.TargetSection;
+import org.jboss.security.xacml.sunxacml.VersionConstraints;
+import org.jboss.security.xacml.sunxacml.combine.PolicyCombiningAlgorithm;
+import org.jboss.security.xacml.sunxacml.ctx.Status;
+
+/**
+ * This class handles collections of <code>AbstractPolicy</code> instances,
+ * and provides some commonly useful operations. Specifically, it lets you
+ * retrieve matching policies (based on reference or context), it optionally
+ * handles wrapping multiple matches under a single PolicySet, and it manages
+ * different versions of policies correctly. This class is intended for use
+ * as a backing store to <code>PolicyFinderModule</code>s, but in practice
+ * may have many uses.
+ * <p>
+ * Note that this class will accept multiple versions of the same policy. This
+ * means that when you retieve a policy by reference, you will get the
+ * correct version. It also means that when you retrieve a policy based on
+ * context, there may be multiple revisions of the same policy, any number
+ * of which may apply. Generally speaking, the correct behavior here is not
+ * to return all of these policies, since they are (virtually speaking) the
+ * same policy, but may have conflicting rules. So, as a simplification, and
+ * to handle the most common cases, only the most recent version of a policy
+ * is returned in these cases. If you need a more complex solution, you
+ * will need to implement it yourself. Because the support modules use this
+ * class as their backing store, this is true also of those modules.
+ * <p>
+ * Note that this is not a heavily optimized class. It is intended more as
+ * an example, support code for the finder modules, and a starting utility
+ * for other programmers than as an enterprise-quality implementation. That
+ * said, it is fully functional, and should be useful for many applications.
+ *
+ * @since 2.0
+ * @author Seth Proctor
+ */
+public class PolicyCollection
+{
+
+   // the actual collection of policies
+   private HashMap policies;
+
+   // the single instance of the comparator we'll use for managing versions
+   private VersionComparator versionComparator = new VersionComparator();
+
+   // the optional combining algorithm used when wrapping multiple policies
+   private PolicyCombiningAlgorithm combiningAlg;
+
+   // the optional policy id used when wrapping multiple policies
+   private URI parentId;
+
+   // default target that matches anything, used in wrapping policies
+   private static final Target target;
+
+   /**
+    * This static initializer just sets up the default target, which is
+    * used by all wrapping policy sets.
+    */
+   static
+   {
+      target = new Target(new TargetSection(null, TargetMatch.SUBJECT, PolicyMetaData.XACML_VERSION_2_0),
+            new TargetSection(null, TargetMatch.RESOURCE, PolicyMetaData.XACML_VERSION_2_0), new TargetSection(null,
+                  TargetMatch.ACTION, PolicyMetaData.XACML_VERSION_2_0), new TargetSection(null,
+                  TargetMatch.ENVIRONMENT, PolicyMetaData.XACML_VERSION_2_0));
+   };
+
+   /**
+    * Creates a new <code>PolicyCollection</code> that will return errors
+    * when multiple policies match for a given request.
+    */
+   public PolicyCollection()
+   {
+      policies = new HashMap();
+      combiningAlg = null;
+   }
+
+   /**
+    * Creates a new <code>PolicyCollection</code> that will create a new
+    * top-level PolicySet when multiple policies match for a given request.
+    *
+    * @param combiningAlg the algorithm to use in a new PolicySet when more
+    *                     than one policy applies
+    * @param parentPolicyId the identifier to use for the new PolicySet
+    */
+   public PolicyCollection(PolicyCombiningAlgorithm combiningAlg, URI parentPolicyId)
+   {
+      policies = new HashMap();
+
+      this.combiningAlg = combiningAlg;
+      this.parentId = parentPolicyId;
+   }
+
+   /**
+    * Adds a new policy to the collection, and uses the policy's identifier
+    * as the reference identifier. If this identifier already exists in the
+    * collection, and this policy does not represent a new version of the
+    * policy, then the policy is not added.
+    *
+    * @param policy the policy to add
+    *
+    * @return true if the policy was added, false otherwise
+    */
+   public boolean addPolicy(AbstractPolicy policy)
+   {
+      return addPolicy(policy, policy.getId().toString());
+   }
+
+   /**
+    * Adds a new policy to the collection using the given identifier as
+    * the reference identifier. If this identifier already exists in the
+    * collection, and this policy does not represent a new version of the
+    * policy, then the policy is not added.
+    *
+    * @param policy the policy to add
+    * @param identifier the identifier to use when referencing this policy
+    *
+    * @return true if the policy was added, false otherwise
+    */
+   public boolean addPolicy(AbstractPolicy policy, String identifier)
+   {
+      if (policies.containsKey(identifier))
+      {
+         // this identifier is already is use, so see if this version is
+         // already in the set
+         TreeSet set = (TreeSet) (policies.get(identifier));
+         return set.add(policy);
+      }
+      else
+      {
+         // this identifier isn't already being used, so create a new
+         // set in the map for it, and add the policy
+         TreeSet set = new TreeSet(versionComparator);
+         policies.put(identifier, set);
+         return set.add(policy);
+      }
+   }
+
+   /**
+    * Attempts to retrieve a policy based on the given context. If multiple
+    * policies match then this will either throw an exception or wrap the
+    * policies under a new PolicySet (depending on how this instance was
+    * constructed). If no policies match, then this will return null. See
+    * the comment in the class header about how this behaves when multiple
+    * versions of the same policy exist.
+    *
+    * @param context representation of a request
+    *
+    * @return a matching policy, or null if no policy matches
+    *
+    * @throws TopLevelPolicyException if multiple policies match but this
+    *                                 instance wasn't setup to wrap policies
+    */
+   public AbstractPolicy getPolicy(EvaluationCtx context) throws TopLevelPolicyException
+   {
+      // setup a list of matching policies
+      ArrayList list = new ArrayList();
+      // get an iterator over all the identifiers
+      Iterator it = policies.values().iterator();
+
+      while (it.hasNext())
+      {
+         // for each identifier, get only the most recent policy
+         AbstractPolicy policy = (AbstractPolicy) (((TreeSet) (it.next())).first());
+
+         // see if we match
+         MatchResult match = policy.match(context);
+         int result = match.getResult();
+
+         // if there was an error, we stop right away
+         if (result == MatchResult.INDETERMINATE)
+            throw new TopLevelPolicyException(match.getStatus());
+
+         // if we matched, we keep track of the matching policy...
+         if (result == MatchResult.MATCH)
+         {
+            // ...first checking if this is the first match and if
+            // we automaticlly nest policies
+            if ((combiningAlg == null) && (list.size() > 0))
+            {
+               ArrayList code = new ArrayList();
+               code.add(Status.STATUS_PROCESSING_ERROR);
+               Status status = new Status(code, "too many applicable" + " top-level policies");
+               throw new TopLevelPolicyException(status);
+            }
+
+            list.add(policy);
+         }
+      }
+
+      // no errors happened during the search, so now take the right
+      // action based on how many policies we found
+      switch (list.size())
+      {
+         case 0 :
+            return null;
+         case 1 :
+            return ((AbstractPolicy) (list.get(0)));
+         default :
+            return new PolicySet(parentId, combiningAlg, target, list);
+      }
+   }
+
+   /**
+    * Attempts to retrieve a policy based on the given identifier and other
+    * constraints. If there are multiple versions of the identified policy
+    * that meet the version constraints, then the most recent version is
+    * returned.
+    *
+    * @param identifier an identifier specifying some policy
+    * @param type type of reference (policy or policySet) as identified by
+    *             the fields in <code>PolicyReference</code>
+    * @param constraints any optional constraints on the version of the
+    *                    referenced policy (this will never be null, but
+    *                    it may impose no constraints, and in fact will
+    *                    never impose constraints when used from a pre-2.0
+    *                    XACML policy)
+    */
+   public AbstractPolicy getPolicy(String identifier, int type, VersionConstraints constraints)
+   {
+      TreeSet set = (TreeSet) (policies.get(identifier));
+
+      // if we don't know about this identifier then there's nothing to do
+      if (set == null)
+         return null;
+
+      // walk through the set starting with the most recent version, looking
+      // for a match until we exhaust all known versions
+      Iterator it = set.iterator();
+      while (it.hasNext())
+      {
+         AbstractPolicy policy = (AbstractPolicy) (it.next());
+         if (constraints.meetsConstraint(policy.getVersion()))
+         {
+            // we found a valid version, so see if it's the right kind,
+            // and if it is then we return it
+            if (type == PolicyReference.POLICY_REFERENCE)
+            {
+               if (policy instanceof Policy)
+                  return policy;
+            }
+            else
+            {
+               if (policy instanceof PolicySet)
+                  return policy;
+            }
+         }
+      }
+
+      // we didn't find a match
+      return null;
+   }
+
+   /**
+    * A <code>Comparator</code> that is used within this class to maintain
+    * ordering amongst different versions of the same policy. Note that
+    * it actually maintains reverse-ordering, since we want to traverse the
+    * sets in decreasing, not increasing order.
+    * <p>
+    * Note that this comparator is only used when there are multiple versions
+    * of the same policy, which in practice will probably happen far less
+    * (from this class' point of view) than additions or fetches.
+    */
+   class VersionComparator implements Comparator
+   {
+      public int compare(Object o1, Object o2)
+      {
+         // we swap the parameters so that sorting goes largest to smallest
+         String v1 = ((AbstractPolicy) o2).getVersion();
+         String v2 = ((AbstractPolicy) o1).getVersion();
+
+         // do a quick check to see if the strings are equal (note that
+         // even if the strings aren't equal, the versions can still
+         // be equal)
+         if (v1.equals(v2))
+            return 0;
+
+         // setup tokenizers, and walk through both strings one set of
+         // numeric values at a time
+         StringTokenizer tok1 = new StringTokenizer(v1, ".");
+         StringTokenizer tok2 = new StringTokenizer(v2, ".");
+
+         while (tok1.hasMoreTokens())
+         {
+            // if there's nothing left in tok2, then v1 is bigger
+            if (!tok2.hasMoreTokens())
+               return 1;
+
+            // get the next elements in the version, convert to numbers,
+            // and compare them (continuing with the loop only if the
+            // two values were equal)
+            int num1 = Integer.parseInt(tok1.nextToken());
+            int num2 = Integer.parseInt(tok2.nextToken());
+
+            if (num1 > num2)
+               return 1;
+
+            if (num1 < num2)
+               return -1;
+         }
+
+         // if there's still something left in tok2, then it's bigger
+         if (tok2.hasMoreTokens())
+            return -1;
+
+         // if we got here it means both versions had the same number of
+         // elements and all the elements were equal, so the versions
+         // are in fact equal
+         return 0;
+      }
+   }
+
+}

Added: projects/security/security-xacml/trunk/jboss-sunxacml/src/main/java/org/jboss/security/xacml/sunxacml/support/finder/PolicyReader.java
===================================================================
--- projects/security/security-xacml/trunk/jboss-sunxacml/src/main/java/org/jboss/security/xacml/sunxacml/support/finder/PolicyReader.java	                        (rev 0)
+++ projects/security/security-xacml/trunk/jboss-sunxacml/src/main/java/org/jboss/security/xacml/sunxacml/support/finder/PolicyReader.java	2008-04-08 22:51:45 UTC (rev 71808)
@@ -0,0 +1,307 @@
+/*
+ * @(#)PolicyReader.java
+ *
+ * Copyright 2006 Sun Microsystems, Inc. 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. Redistribution of source code must retain the above copyright notice,
+ *      this list of conditions and the following disclaimer.
+ * 
+ *   2. Redistribution 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.
+ *
+ * Neither the name of Sun Microsystems, Inc. or the names of contributors may
+ * be used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ * 
+ * This software is provided "AS IS," without a warranty of any kind. ALL
+ * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
+ * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
+ * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
+ * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
+ * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+ * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
+ * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
+ * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
+ * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
+ * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
+ *
+ * You acknowledge that this software is not designed or intended for use in
+ * the design, construction, operation or maintenance of any nuclear facility.
+ */
+
+package org.jboss.security.xacml.sunxacml.support.finder;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+
+import org.jboss.security.xacml.sunxacml.AbstractPolicy;
+import org.jboss.security.xacml.sunxacml.ParsingException;
+import org.jboss.security.xacml.sunxacml.Policy;
+import org.jboss.security.xacml.sunxacml.PolicySet;
+import org.jboss.security.xacml.sunxacml.finder.PolicyFinder;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.xml.sax.ErrorHandler;
+import org.xml.sax.SAXException;
+import org.xml.sax.SAXParseException;
+
+/**
+ * This class is provided as a utility for reading policies from common,
+ * simple sources: <code>InputStream</code>s, <code>File</code>s, and
+ * <code>URL</code>s. It can optionally schema validate the policies.
+ * <p>
+ * Note: some of this functionality was previously provided in
+ * <code>com.sun.xacml.finder.impl.FilePolicyModule</code>, but as of
+ * the 2.0 release, that class has been removed. This new
+ * <code>PolicyReader</code> class provides much better functionality
+ * for loading policies.
+ *
+ * @since 2.0
+ * @author Seth Proctor
+ */
+public class PolicyReader implements ErrorHandler
+{
+
+   /**
+    * The property which is used to specify the schema file to validate
+    * against (if any). Note that this isn't used directly by
+    * <code>PolicyReader</code>, but is referenced by many classes that
+    * use this class to load policies.
+    */
+   public static final String POLICY_SCHEMA_PROPERTY = "com.sun.xacml.PolicySchema";
+
+   // the standard attribute for specifying the XML schema language
+   private static final String JAXP_SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
+
+   // the standard identifier for the XML schema specification
+   private static final String W3C_XML_SCHEMA = "http://www.w3.org/2001/XMLSchema";
+
+   // the standard attribute for specifying schema source
+   private static final String JAXP_SCHEMA_SOURCE = "http://java.sun.com/xml/jaxp/properties/schemaSource";
+
+   // the finder, which is used by PolicySets
+   private PolicyFinder finder;
+
+   // the builder used to create DOM documents
+   private DocumentBuilder builder;
+
+   // the optional logger used for error reporting
+   private Logger logger;
+
+   /**
+    * Creates a <code>PolicyReader</code> that does not schema-validate
+    * policies.
+    *
+    * @param finder a <code>PolicyFinder</code> that is used by policy sets,
+    *               which may be null only if no references are used
+    * @param logger a <code>Logger</code> used to report parsing errors
+    */
+   public PolicyReader(PolicyFinder finder, Logger logger)
+   {
+      this(finder, logger, null);
+   }
+
+   /**
+    * Creates a <code>PolicyReader</code> that may schema-validate policies.
+    *
+    * @param finder a <code>PolicyFinder</code> that is used by policy sets,
+    *               which may be null only if no references are used
+    * @param logger a <code>Logger</code> used to report parsing errors
+    * @param schemaFile the schema file used to validate policies, or
+    *                   null if schema validation is not desired
+    */
+   public PolicyReader(PolicyFinder finder, Logger logger, File schemaFile)
+   {
+      this.logger = logger;
+      this.finder = finder;
+
+      // create the factory
+      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
+      factory.setIgnoringComments(true);
+      factory.setNamespaceAware(true);
+
+      // see if we want to schema-validate policies
+      if (schemaFile == null)
+      {
+         factory.setValidating(false);
+      }
+      else
+      {
+         factory.setValidating(true);
+         factory.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
+         factory.setAttribute(JAXP_SCHEMA_SOURCE, schemaFile);
+      }
+
+      // now use the factory to create the document builder
+      try
+      {
+         builder = factory.newDocumentBuilder();
+         builder.setErrorHandler(this);
+      }
+      catch (ParserConfigurationException pce)
+      {
+         throw new IllegalArgumentException("Filed to setup reader: " + pce.toString());
+      }
+   }
+
+   /**
+    * Tries to read an XACML policy or policy set from the given file.
+    *
+    * @param file the file containing the policy to read
+    *
+    * @return a (potentially schema-validated) policy loaded from the
+    *         given file
+    *
+    * @throws ParsingException if an error occurs while reading or
+    *                          parsing the policy
+    */
+   public synchronized AbstractPolicy readPolicy(File file) throws ParsingException
+   {
+      try
+      {
+         return handleDocument(builder.parse(file));
+      }
+      catch (IOException ioe)
+      {
+         throw new ParsingException("Failed to read the file", ioe);
+      }
+      catch (SAXException saxe)
+      {
+         throw new ParsingException("Failed to parse the file", saxe);
+      }
+   }
+
+   /**
+    * Tries to read an XACML policy or policy set from the given stream.
+    *
+    * @param input the stream containing the policy to read
+    *
+    * @return a (potentially schema-validated) policy loaded from the
+    *         given file
+    *
+    * @throws ParsingException if an error occurs while reading or
+    *                          parsing the policy
+    */
+   public synchronized AbstractPolicy readPolicy(InputStream input) throws ParsingException
+   {
+      try
+      {
+         return handleDocument(builder.parse(input));
+      }
+      catch (IOException ioe)
+      {
+         throw new ParsingException("Failed to read the stream", ioe);
+      }
+      catch (SAXException saxe)
+      {
+         throw new ParsingException("Failed to parse the stream", saxe);
+      }
+   }
+
+   /**
+    * Tries to read an XACML policy or policy set based on the given URL.
+    * This may be any resolvable URL, like a file or http pointer.
+    *
+    * @param url a URL pointing to the policy to read
+    *
+    * @return a (potentially schema-validated) policy loaded from the
+    *         given file
+    *
+    * @throws ParsingException if an error occurs while reading or
+    *                          parsing the policy, or if the URL can't
+    *                          be resolved
+    */
+   public synchronized AbstractPolicy readPolicy(URL url) throws ParsingException
+   {
+      try
+      {
+         return readPolicy(url.openStream());
+      }
+      catch (IOException ioe)
+      {
+         throw new ParsingException("Failed to resolve the URL: " + url.toString(), ioe);
+      }
+   }
+
+   /**
+    * A private method that handles reading the policy and creates the
+    * correct kind of AbstractPolicy.
+    */
+   private AbstractPolicy handleDocument(Document doc) throws ParsingException
+   {
+      // handle the policy, if it's a known type
+      Element root = doc.getDocumentElement();
+      String name = root.getTagName();
+
+      // see what type of policy this is
+      if (name.equals("Policy"))
+      {
+         return Policy.getInstance(root);
+      }
+      else if (name.equals("PolicySet"))
+      {
+         return PolicySet.getInstance(root, finder);
+      }
+      else
+      {
+         // this isn't a root type that we know how to handle
+         throw new ParsingException("Unknown root document type: " + name);
+      }
+   }
+
+   /**
+    * Standard handler routine for the XML parsing.
+    *
+    * @param exception information on what caused the problem
+    */
+   public void warning(SAXParseException exception) throws SAXException
+   {
+      if (logger.isLoggable(Level.WARNING))
+         logger.warning("Warning on line " + exception.getLineNumber() + ": " + exception.getMessage());
+   }
+
+   /**
+    * Standard handler routine for the XML parsing.
+    *
+    * @param exception information on what caused the problem
+    *
+    * @throws SAXException always to halt parsing on errors
+    */
+   public void error(SAXParseException exception) throws SAXException
+   {
+      if (logger.isLoggable(Level.WARNING))
+         logger.warning("Error on line " + exception.getLineNumber() + ": " + exception.getMessage() + " ... "
+               + "Policy will not be available");
+
+      throw new SAXException("error parsing policy");
+   }
+
+   /**
+    * Standard handler routine for the XML parsing.
+    *
+    * @param exception information on what caused the problem
+    *
+    * @throws SAXException always to halt parsing on errors
+    */
+   public void fatalError(SAXParseException exception) throws SAXException
+   {
+      if (logger.isLoggable(Level.WARNING))
+         logger.warning("Fatal error on line " + exception.getLineNumber() + ": " + exception.getMessage() + " ... "
+               + "Policy will not be available");
+
+      throw new SAXException("fatal error parsing policy");
+   }
+
+}

Added: projects/security/security-xacml/trunk/jboss-sunxacml/src/main/java/org/jboss/security/xacml/sunxacml/support/finder/StaticPolicyFinderModule.java
===================================================================
--- projects/security/security-xacml/trunk/jboss-sunxacml/src/main/java/org/jboss/security/xacml/sunxacml/support/finder/StaticPolicyFinderModule.java	                        (rev 0)
+++ projects/security/security-xacml/trunk/jboss-sunxacml/src/main/java/org/jboss/security/xacml/sunxacml/support/finder/StaticPolicyFinderModule.java	2008-04-08 22:51:45 UTC (rev 71808)
@@ -0,0 +1,311 @@
+/*
+ * @(#)StaticPolicyFinderModule.java
+ *
+ * Copyright 2006 Sun Microsystems, Inc. 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. Redistribution of source code must retain the above copyright notice,
+ *      this list of conditions and the following disclaimer.
+ * 
+ *   2. Redistribution 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.
+ *
+ * Neither the name of Sun Microsystems, Inc. or the names of contributors may
+ * be used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ * 
+ * This software is provided "AS IS," without a warranty of any kind. ALL
+ * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
+ * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
+ * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
+ * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
+ * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+ * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
+ * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
+ * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
+ * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
+ * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
+ *
+ * You acknowledge that this software is not designed or intended for use in
+ * the design, construction, operation or maintenance of any nuclear facility.
+ */
+
+package org.jboss.security.xacml.sunxacml.support.finder;
+
+import java.io.File;
+import java.net.MalformedURLException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.URL;
+import java.util.Iterator;
+import java.util.List;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import org.jboss.security.xacml.sunxacml.AbstractPolicy;
+import org.jboss.security.xacml.sunxacml.EvaluationCtx;
+import org.jboss.security.xacml.sunxacml.ParsingException;
+import org.jboss.security.xacml.sunxacml.UnknownIdentifierException;
+import org.jboss.security.xacml.sunxacml.combine.CombiningAlgFactory;
+import org.jboss.security.xacml.sunxacml.combine.PolicyCombiningAlgorithm;
+import org.jboss.security.xacml.sunxacml.finder.PolicyFinder;
+import org.jboss.security.xacml.sunxacml.finder.PolicyFinderModule;
+import org.jboss.security.xacml.sunxacml.finder.PolicyFinderResult;
+
+/**
+ * This is a simple implementation of <code>PolicyFinderModule</code> that
+ * supports retrieval based on context, and is designed for use with a
+ * run-time configuration. Its constructor accepts a <code>List</code> of
+ * <code>String</code>s that represent URLs or files, and these are resolved
+ * to policies when the module is initialized. Beyond this, there is no
+ * modifying or re-loading the policies represented by this class. This
+ * class will optionally wrap multiple applicable policies into a dynamic
+ * PolicySet.
+ * <p>
+ * Note that this class is designed to complement
+ * <code>StaticRefPolicyFinderModule</code>. It would be easy to support both
+ * kinds of policy retrieval in a single class, but the functionality is
+ * instead split between two classes. The reason is that when you define a
+ * configuration for your PDP, it's easier to specify the two sets of policies
+ * by using two different finder modules. Typically, there aren't many
+ * policies that exist in both sets, so loading the sets separately isn't
+ * a problem. If this is a concern to you, simply create your own class and
+ * merge the two existing classes.
+ * <p>
+ * This module is provided as an example, but is still fully functional, and
+ * should be useful for many simple applications. This is provided in the
+ * <code>support</code> package rather than the core codebase because it
+ * implements non-standard behavior.
+ *
+ * @since 2.0
+ * @author Seth Proctor
+ */
+public class StaticPolicyFinderModule extends PolicyFinderModule
+{
+
+   // the list of policy URLs passed to the constructor
+   private List policyList;
+
+   // the map of policies
+   private PolicyCollection policies;
+
+   // the optional schema file
+   private File schemaFile = null;
+
+   // the policy identifier for any policy sets we dynamically create
+   private static final String POLICY_ID = "urn:com:sun:xacml:support:finder:dynamic-policy-set";
+
+   private static URI policyId = null;
+
+   // the logger we'll use for all messages
+   private static final Logger logger = Logger.getLogger(StaticPolicyFinderModule.class.getName());
+
+   static
+   {
+      try
+      {
+         policyId = new URI(POLICY_ID);
+      }
+      catch (Exception e)
+      {
+         // this can't actually happen, but just in case...
+         if (logger.isLoggable(Level.SEVERE))
+            logger.log(Level.SEVERE, "couldn't assign default policy id");
+      }
+   };
+
+   /**
+    * Creates a <code>StaticPolicyFinderModule</code> that provides
+    * access to the given collection of policies and returns an error when
+    * more than one policy matches a given context. Any policy that cannot
+    * be loaded will be noted in the log, but will not cause an error. The
+    * schema file used to validate policies is defined by the property
+    * <code>PolicyReader.POLICY_SCHEMA_PROPERTY</code>. If the retrieved
+    * property is null, then no schema validation will occur.
+    *
+    * @param policyList a <code>List</code> of <code>String</code>s that
+    *                   represent URLs or files pointing to XACML policies
+    */
+   public StaticPolicyFinderModule(List policyList)
+   {
+      this.policyList = policyList;
+      this.policies = new PolicyCollection();
+
+      String schemaName = System.getProperty(PolicyReader.POLICY_SCHEMA_PROPERTY);
+      if (schemaName != null)
+         schemaFile = new File(schemaName);
+   }
+
+   /**
+    * Creates a <code>StaticPolicyFinderModule</code> that provides
+    * access to the given collection of policies and returns an error when
+    * more than one policy matches a given context. Any policy that cannot
+    * be loaded will be noted in the log, but will not cause an error.
+    *
+    * @param policyList a <code>List</code> of <code>String</code>s that
+    *                   represent URLs or files pointing to XACML policies
+    * @param schemaFile the schema file to validate policies against,
+    *                   or null if schema validation is not desired
+    */
+   public StaticPolicyFinderModule(List policyList, String schemaFile)
+   {
+      this.policyList = policyList;
+      this.policies = new PolicyCollection();
+
+      if (schemaFile != null)
+         this.schemaFile = new File(schemaFile);
+   }
+
+   /**
+    * Creates a <code>StaticPolicyFinderModule</code> that provides
+    * access to the given collection of policies. The given combining
+    * algorithm is used to create new PolicySets when more than one
+    * policy applies. Any policy that cannot be loaded will be noted in
+    * the log, but will not cause an error. The schema file used to
+    * validate policies is defined by the property
+    * <code>PolicyReader.POLICY_SCHEMA_PROPERTY</code>. If the retrieved
+    * property is null, then no schema validation will occur.
+    *
+    * @param combiningAlg the algorithm to use in a new PolicySet when more
+    *                     than one policy applies
+    * @param policyList a <code>List</code> of <code>String</code>s that
+    *                   represent URLs or files pointing to XACML policies
+    *
+    * @throws URISyntaxException if the combining algorithm is not a
+    *                            well-formed URI
+    * @throws UnknownIdentifierException if the combining algorithm identifier
+    *                                    isn't known
+    */
+   public StaticPolicyFinderModule(String combiningAlg, List policyList) throws URISyntaxException,
+         UnknownIdentifierException
+   {
+      PolicyCombiningAlgorithm alg = (PolicyCombiningAlgorithm) (CombiningAlgFactory.getInstance()
+            .createAlgorithm(new URI(combiningAlg)));
+
+      this.policyList = policyList;
+      this.policies = new PolicyCollection(alg, policyId);
+
+      String schemaName = System.getProperty(PolicyReader.POLICY_SCHEMA_PROPERTY);
+      if (schemaName != null)
+         schemaFile = new File(schemaName);
+   }
+
+   /**
+    * Creates a <code>StaticPolicyFinderModule</code> that provides
+    * access to the given collection of policies. The given combining
+    * algorithm is used to create new PolicySets when more than one
+    * policy applies. Any policy that cannot be loaded will be noted in
+    * the log, but will not cause an error.
+    *
+    * @param combiningAlg the algorithm to use in a new PolicySet when more
+    *                     than one policy applies
+    * @param policyList a <code>List</code> of <code>String</code>s that
+    *                   represent URLs or files pointing to XACML policies
+    * @param schemaFile the schema file to validate policies against,
+    *                   or null if schema validation is not desired
+    *
+    * @throws URISyntaxException if the combining algorithm is not a
+    *                            well-formed URI
+    * @throws UnknownIdentifierException if the combining algorithm identifier
+    *                                    isn't known
+    */
+   public StaticPolicyFinderModule(String combiningAlg, List policyList, String schemaFile) throws URISyntaxException,
+         UnknownIdentifierException
+   {
+      PolicyCombiningAlgorithm alg = (PolicyCombiningAlgorithm) (CombiningAlgFactory.getInstance()
+            .createAlgorithm(new URI(combiningAlg)));
+
+      this.policyList = policyList;
+      this.policies = new PolicyCollection(alg, policyId);
+
+      if (schemaFile != null)
+         this.schemaFile = new File(schemaFile);
+   }
+
+   /**
+    * Always returns <code>true</code> since this module does support
+    * finding policies based on context.
+    *
+    * @return true
+    */
+   public boolean isRequestSupported()
+   {
+      return true;
+   }
+
+   /**
+    * Initialize this module. Typically this is called by
+    * <code>PolicyFinder</code> when a PDP is created. This method is
+    * where the policies are actually loaded.
+    *
+    * @param finder the <code>PolicyFinder</code> using this module
+    */
+   public void init(PolicyFinder finder)
+   {
+      // now that we have the PolicyFinder, we can load the policies
+      PolicyReader reader = new PolicyReader(finder, logger, schemaFile);
+
+      Iterator it = policyList.iterator();
+      while (it.hasNext())
+      {
+         String str = (String) (it.next());
+         AbstractPolicy policy = null;
+
+         try
+         {
+            try
+            {
+               // first try to load it as a URL
+               URL url = new URL(str);
+               policy = reader.readPolicy(url);
+            }
+            catch (MalformedURLException murle)
+            {
+               // assume that this is a filename, and try again
+               policy = reader.readPolicy(new File(str));
+            }
+
+            // we loaded the policy, so try putting it in the collection
+            if (!policies.addPolicy(policy))
+               if (logger.isLoggable(Level.WARNING))
+                  logger.log(Level.WARNING, "tried to load the same " + "policy multiple times: " + str);
+         }
+         catch (ParsingException pe)
+         {
+            if (logger.isLoggable(Level.WARNING))
+               logger.log(Level.WARNING, "Error reading policy: " + str, pe);
+         }
+      }
+   }
+
+   /**
+    * Finds a policy based on a request's context. If more than one policy
+    * matches, then this either returns an error or a new policy wrapping
+    * the multiple policies (depending on which constructor was used to
+    * construct this instance).
+    *
+    * @param context the representation of the request data
+    *
+    * @return the result of trying to find an applicable policy
+    */
+   public PolicyFinderResult findPolicy(EvaluationCtx context)
+   {
+      try
+      {
+         AbstractPolicy policy = policies.getPolicy(context);
+
+         if (policy == null)
+            return new PolicyFinderResult();
+         else
+            return new PolicyFinderResult(policy);
+      }
+      catch (TopLevelPolicyException tlpe)
+      {
+         return new PolicyFinderResult(tlpe.getStatus());
+      }
+   }
+
+}

Added: projects/security/security-xacml/trunk/jboss-sunxacml/src/main/java/org/jboss/security/xacml/sunxacml/support/finder/StaticRefPolicyFinderModule.java
===================================================================
--- projects/security/security-xacml/trunk/jboss-sunxacml/src/main/java/org/jboss/security/xacml/sunxacml/support/finder/StaticRefPolicyFinderModule.java	                        (rev 0)
+++ projects/security/security-xacml/trunk/jboss-sunxacml/src/main/java/org/jboss/security/xacml/sunxacml/support/finder/StaticRefPolicyFinderModule.java	2008-04-08 22:51:45 UTC (rev 71808)
@@ -0,0 +1,220 @@
+/*
+ * @(#)StaticRefPolicyFinderModule.java
+ *
+ * Copyright 2006 Sun Microsystems, Inc. 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. Redistribution of source code must retain the above copyright notice,
+ *      this list of conditions and the following disclaimer.
+ * 
+ *   2. Redistribution 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.
+ *
+ * Neither the name of Sun Microsystems, Inc. or the names of contributors may
+ * be used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ * 
+ * This software is provided "AS IS," without a warranty of any kind. ALL
+ * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
+ * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
+ * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
+ * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
+ * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+ * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
+ * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
+ * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
+ * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
+ * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
+ *
+ * You acknowledge that this software is not designed or intended for use in
+ * the design, construction, operation or maintenance of any nuclear facility.
+ */
+
+package org.jboss.security.xacml.sunxacml.support.finder;
+
+import java.io.File;
+import java.net.MalformedURLException;
+import java.net.URI;
+import java.net.URL;
+import java.util.Iterator;
+import java.util.List;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import org.jboss.security.xacml.sunxacml.AbstractPolicy;
+import org.jboss.security.xacml.sunxacml.ParsingException;
+import org.jboss.security.xacml.sunxacml.PolicyMetaData;
+import org.jboss.security.xacml.sunxacml.VersionConstraints;
+import org.jboss.security.xacml.sunxacml.finder.PolicyFinder;
+import org.jboss.security.xacml.sunxacml.finder.PolicyFinderModule;
+import org.jboss.security.xacml.sunxacml.finder.PolicyFinderResult;
+
+/**
+ * This is a simple implementation of <code>PolicyFinderModule</code> that
+ * supports retrieval based on reference, and is designed for use with a
+ * run-time configuration. Its constructor accepts a <code>List</code> of
+ * <code>String</code>s that represent URLs or files, and these are resolved
+ * to policies when the module is initialized. Beyond this, there is no
+ * modifying or re-loading the policies represented by this class. The
+ * policy's identifiers are used for reference resolution.
+ * <p>
+ * Note that this class is designed to complement
+ * <code>StaticPolicyFinderModule</code>. It would be easy to support both
+ * kinds of policy retrieval in a single class, but the functionality is
+ * instead split between two classes. The reason is that when you define a
+ * configuration for your PDP, it's easier to specify the two sets of policies
+ * by using two different finder modules. Typically, there aren't many
+ * policies that exist in both sets, so loading the sets separately isn't
+ * a problem. If this is a concern to you, simply create your own class and
+ * merge the two existing classes.
+ * <p>
+ * This module is provided as an example, but is still fully functional, and
+ * should be useful for many simple applications. This is provided in the
+ * <code>support</code> package rather than the core codebase because it
+ * implements non-standard behavior.
+ *
+ * @since 2.0
+ * @author Seth Proctor
+ */
+public class StaticRefPolicyFinderModule extends PolicyFinderModule
+{
+
+   // the list of policy URLs passed to the constructor
+   private List policyList;
+
+   // the map of policies
+   private PolicyCollection policies;
+
+   // the optional schema file
+   private File schemaFile = null;
+
+   // the logger we'll use for all messages
+   private static final Logger logger = Logger.getLogger(StaticRefPolicyFinderModule.class.getName());
+
+   /**
+    * Creates a <code>StaticRefPolicyFinderModule</code> that provides
+    * access to the given collection of policies. Any policy that cannot
+    * be loaded will be noted in the log, but will not cause an error. The
+    * schema file used to validate policies is defined by the property
+    * <code>PolicyReader.POLICY_SCHEMA_PROPERTY</code>. If the retrieved
+    * property is null, then no schema validation will occur.
+    *
+    * @param policyList a <code>List</code> of <code>String</code>s that
+    *                   represent URLs or files pointing to XACML policies
+    */
+   public StaticRefPolicyFinderModule(List policyList)
+   {
+      this.policyList = policyList;
+      this.policies = new PolicyCollection();
+
+      String schemaName = System.getProperty(PolicyReader.POLICY_SCHEMA_PROPERTY);
+      if (schemaName != null)
+         schemaFile = new File(schemaName);
+   }
+
+   /**
+    * Creates a <code>StaticRefPolicyFinderModule</code> that provides
+    * access to the given collection of policyList.
+    *
+    * @param policyList a <code>List</code> of <code>String</code>s that
+    *                   represent URLs or files pointing to XACML policies
+    * @param schemaFile the schema file to validate policies against,
+    *                   or null if schema validation is not desired
+    */
+   public StaticRefPolicyFinderModule(List policyList, String schemaFile)
+   {
+      this.policyList = policyList;
+      this.policies = new PolicyCollection();
+
+      if (schemaFile != null)
+         this.schemaFile = new File(schemaFile);
+   }
+
+   /**
+    * Always returns <code>true</code> since this module does support
+    * finding policies based on reference.
+    *
+    * @return true
+    */
+   public boolean isIdReferenceSupported()
+   {
+      return true;
+   }
+
+   /**
+    * Initialize this module. Typically this is called by
+    * <code>PolicyFinder</code> when a PDP is created. This method is
+    * where the policies are actually loaded.
+    *
+    * @param finder the <code>PolicyFinder</code> using this module
+    */
+   public void init(PolicyFinder finder)
+   {
+      // now that we have the PolicyFinder, we can load the policies
+      PolicyReader reader = new PolicyReader(finder, logger, schemaFile);
+
+      Iterator it = policyList.iterator();
+      while (it.hasNext())
+      {
+         String str = (String) (it.next());
+         AbstractPolicy policy = null;
+
+         try
+         {
+            try
+            {
+               // first try to load it as a URL
+               URL url = new URL(str);
+               policy = reader.readPolicy(url);
+            }
+            catch (MalformedURLException murle)
+            {
+               // assume that this is a filename, and try again
+               policy = reader.readPolicy(new File(str));
+            }
+
+            // we loaded the policy, so try putting it in the collection
+            if (!policies.addPolicy(policy))
+               if (logger.isLoggable(Level.WARNING))
+                  logger.log(Level.WARNING, "tried to load the same " + "policy multiple times: " + str);
+         }
+         catch (ParsingException pe)
+         {
+            if (logger.isLoggable(Level.WARNING))
+               logger.log(Level.WARNING, "Error reading policy: " + str, pe);
+         }
+      }
+   }
+
+   /**
+    * Attempts to find a policy by reference, based on the provided
+    * parameters.
+    *
+    * @param idReference an identifier specifying some policy
+    * @param type type of reference (policy or policySet) as identified by
+    *             the fields in <code>PolicyReference</code>
+    * @param constraints any optional constraints on the version of the
+    *                    referenced policy (this will never be null, but
+    *                    it may impose no constraints, and in fact will
+    *                    never impose constraints when used from a pre-2.0
+    *                    XACML policy)
+    * @param parentMetaData the meta-data from the parent policy, which
+    *                       provides XACML version, factories, etc.
+    *
+    * @return the result of looking for a matching policy
+    */
+   public PolicyFinderResult findPolicy(URI idReference, int type, VersionConstraints constraints,
+         PolicyMetaData parentMetaData)
+   {
+      AbstractPolicy policy = policies.getPolicy(idReference.toString(), type, constraints);
+
+      if (policy == null)
+         return new PolicyFinderResult();
+      else
+         return new PolicyFinderResult(policy);
+   }
+
+}

Added: projects/security/security-xacml/trunk/jboss-sunxacml/src/main/java/org/jboss/security/xacml/sunxacml/support/finder/TopLevelPolicyException.java
===================================================================
--- projects/security/security-xacml/trunk/jboss-sunxacml/src/main/java/org/jboss/security/xacml/sunxacml/support/finder/TopLevelPolicyException.java	                        (rev 0)
+++ projects/security/security-xacml/trunk/jboss-sunxacml/src/main/java/org/jboss/security/xacml/sunxacml/support/finder/TopLevelPolicyException.java	2008-04-08 22:51:45 UTC (rev 71808)
@@ -0,0 +1,129 @@
+/*
+ * @(#)TopLevelPolicyException.java
+ *
+ * Copyright 2006 Sun Microsystems, Inc. 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. Redistribution of source code must retain the above copyright notice,
+ *      this list of conditions and the following disclaimer.
+ * 
+ *   2. Redistribution 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.
+ *
+ * Neither the name of Sun Microsystems, Inc. or the names of contributors may
+ * be used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ * 
+ * This software is provided "AS IS," without a warranty of any kind. ALL
+ * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
+ * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
+ * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
+ * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
+ * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+ * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
+ * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
+ * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
+ * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
+ * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
+ *
+ * You acknowledge that this software is not designed or intended for use in
+ * the design, construction, operation or maintenance of any nuclear facility.
+ */
+
+package org.jboss.security.xacml.sunxacml.support.finder;
+
+import org.jboss.security.xacml.sunxacml.ctx.Status;
+
+/**
+ * This is an exception thrown by the support code when there's an error
+ * trying to resolve a top-level policy
+ *
+ * @since 2.0
+ * @author Seth Proctor
+ */
+public class TopLevelPolicyException extends Exception
+{
+
+   // status explaining the error
+   private Status status;
+
+   /**
+    * Constructs a new <code>TopLevelPolicyException</code> with no message
+    * or cause.
+    *
+    * @param status the <code>Status</code> associated with this error
+    */
+   public TopLevelPolicyException(Status status)
+   {
+      this.status = status;
+   }
+
+   /**
+    * Constructs a new <code>TopLevelPolicyException</code> with a message,
+    * but no cause. The message is saved for later retrieval by the
+    * {@link java.lang#Throwable.getMessage() Throwable.getMessage()}
+    * method.
+    *
+    * @param status the <code>Status</code> associated with this error
+    * @param message the detail message (<code>null</code> if nonexistent
+    *                or unknown)
+    */
+   public TopLevelPolicyException(Status status, String message)
+   {
+      super(message);
+
+      this.status = status;
+   }
+
+   /**
+    * Constructs a new <code>TopLevelPolicyException</code> with a cause,
+    * but no message. The cause is saved for later retrieval by the
+    * {@link java.lang#Throwable.getCause() Throwable.getCause()}
+    * method.
+    *
+    * @param status the <code>Status</code> associated with this error
+    * @param cause the cause (<code>null</code> if nonexistent
+    *              or unknown)
+    */
+   public TopLevelPolicyException(Status status, Throwable cause)
+   {
+      super(cause);
+
+      this.status = status;
+   }
+
+   /**
+    * Constructs a new <code>TopLevelPolicyException</code> with a message
+    * and a cause. The message and cause are saved for later retrieval
+    * by the
+    * {@link java.lang#Throwable.getMessage() Throwable.getMessage()} and
+    * {@link java.lang#Throwable.getCause() Throwable.getCause()}
+    * methods.
+    *
+    * @param status the <code>Status</code> associated with this error
+    * @param message the detail message (<code>null</code> if nonexistent
+    *                or unknown)
+    * @param cause the cause (<code>null</code> if nonexistent
+    *              or unknown)
+    */
+   public TopLevelPolicyException(Status status, String message, Throwable cause)
+   {
+      super(message, cause);
+
+      this.status = status;
+   }
+
+   /**
+    * Returns the status information associated with this error.
+    *
+    * @return associated status
+    */
+   public Status getStatus()
+   {
+      return status;
+   }
+
+}

Added: projects/security/security-xacml/trunk/jboss-sunxacml/src/main/java/org/jboss/security/xacml/sunxacml/support/finder/URLPolicyFinderModule.java
===================================================================
--- projects/security/security-xacml/trunk/jboss-sunxacml/src/main/java/org/jboss/security/xacml/sunxacml/support/finder/URLPolicyFinderModule.java	                        (rev 0)
+++ projects/security/security-xacml/trunk/jboss-sunxacml/src/main/java/org/jboss/security/xacml/sunxacml/support/finder/URLPolicyFinderModule.java	2008-04-08 22:51:45 UTC (rev 71808)
@@ -0,0 +1,211 @@
+/*
+ * @(#)URLPolicyFinderModule.java
+ *
+ * Copyright 2006 Sun Microsystems, Inc. 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. Redistribution of source code must retain the above copyright notice,
+ *      this list of conditions and the following disclaimer.
+ * 
+ *   2. Redistribution 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.
+ *
+ * Neither the name of Sun Microsystems, Inc. or the names of contributors may
+ * be used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ * 
+ * This software is provided "AS IS," without a warranty of any kind. ALL
+ * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
+ * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
+ * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
+ * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
+ * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+ * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
+ * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
+ * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
+ * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
+ * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
+ *
+ * You acknowledge that this software is not designed or intended for use in
+ * the design, construction, operation or maintenance of any nuclear facility.
+ */
+
+package org.jboss.security.xacml.sunxacml.support.finder;
+
+import java.io.File;
+import java.net.MalformedURLException;
+import java.net.URI;
+import java.net.URL;
+import java.util.logging.Logger;
+
+import org.jboss.security.xacml.sunxacml.AbstractPolicy;
+import org.jboss.security.xacml.sunxacml.ParsingException;
+import org.jboss.security.xacml.sunxacml.Policy;
+import org.jboss.security.xacml.sunxacml.PolicyMetaData;
+import org.jboss.security.xacml.sunxacml.PolicyReference;
+import org.jboss.security.xacml.sunxacml.PolicySet;
+import org.jboss.security.xacml.sunxacml.VersionConstraints;
+import org.jboss.security.xacml.sunxacml.finder.PolicyFinder;
+import org.jboss.security.xacml.sunxacml.finder.PolicyFinderModule;
+import org.jboss.security.xacml.sunxacml.finder.PolicyFinderResult;
+
+/**
+ * This module supports references made with resolvable URLs (eg, http or
+ * file pointers). No policies are cached. Instead, all policy references are
+ * resolved in real-time. To make this module as generally applicable as
+ * possible, no errors are ever returned when attempting to resolve a
+ * policy. This means that if a resolved policy is invalid, a server cannot
+ * be contacted, etc., this module simply reports that it cannot provide a
+ * policy. If you need to report errors, or support any caching, you have to
+ * write your own implementation.
+ * <p>
+ * This module is provided as an example, but is still fully functional, and
+ * should be useful for many simple applications. This is provided in the
+ * <code>support</code> package rather than the core codebase because it
+ * implements non-standard behavior.
+ *
+ * @since 2.0
+ * @author Seth Proctor
+ */
+public class URLPolicyFinderModule extends PolicyFinderModule
+{
+
+   // the optional schema file for validating policies
+   private File schemaFile;
+
+   // the reader used to load all policies
+   private PolicyReader reader;
+
+   // the logger we'll use for all messages
+   private static final Logger logger = Logger.getLogger(URLPolicyFinderModule.class.getName());
+
+   /**
+    * Creates a <code>URLPolicyFinderModule</code>. The schema file used
+    * to validate policies is specified by the property
+    * <code>PolicyReader.POLICY_SCHEMA_PROPERTY</code>. If the retrieved
+    * property is null, then no schema validation will occur.
+    */
+   public URLPolicyFinderModule()
+   {
+      String schemaName = System.getProperty(PolicyReader.POLICY_SCHEMA_PROPERTY);
+
+      if (schemaName != null)
+         schemaFile = new File(schemaName);
+   }
+
+   /**
+    * Creates a <code>URLPolicyFinderModule</code> that may do schema
+    * validation of policies.
+    *
+    * @param schemaFile the schema file to use for validation, or null if
+    *                   validation isn't desired
+    */
+   public URLPolicyFinderModule(String schemaFile)
+   {
+      this.schemaFile = new File(schemaFile);
+   }
+
+   /**
+    * Always returns <code>true</code> since this module does support
+    * finding policies based on reference.
+    *
+    * @return true
+    */
+   public boolean isIdReferenceSupported()
+   {
+      return true;
+   }
+
+   /**
+    * Initialize this module. Typically this is called by
+    * <code>PolicyFinder</code> when a PDP is created.
+    *
+    * @param finder the <code>PolicyFinder</code> using this module
+    */
+   public void init(PolicyFinder finder)
+   {
+      reader = new PolicyReader(finder, logger, schemaFile);
+   }
+
+   /**
+    * Attempts to find a policy by reference, based on the provided
+    * parameters. Specifically, this module will try to treat the reference
+    * as a URL, and resolve that URL directly. If the reference is not
+    * a valid URL, cannot be resolved, or does not resolve to an XACML
+    * policy, then no matching policy is returned. This method never
+    * returns an error.
+    *
+    * @param idReference an identifier specifying some policy
+    * @param type type of reference (policy or policySet) as identified by
+    *             the fields in <code>PolicyReference</code>
+    * @param constraints any optional constraints on the version of the
+    *                    referenced policy (this will never be null, but
+    *                    it may impose no constraints, and in fact will
+    *                    never impose constraints when used from a pre-2.0
+    *                    XACML policy)
+    * @param parentMetaData the meta-data from the parent policy, which
+    *                       provides XACML version, factories, etc.
+    *
+    * @return the result of looking for a matching policy
+    */
+   public PolicyFinderResult findPolicy(URI idReference, int type, VersionConstraints constraints,
+         PolicyMetaData parentMetaData)
+   {
+      // see if the URI is in fact a URL
+      URL url = null;
+      try
+      {
+         url = new URL(idReference.toString());
+      }
+      catch (MalformedURLException murle)
+      {
+         // it's not a URL, so we can't handle this reference
+         return new PolicyFinderResult();
+      }
+
+      // try resolving the URL
+      AbstractPolicy policy = null;
+      try
+      {
+         policy = reader.readPolicy(url);
+      }
+      catch (ParsingException pe)
+      {
+         // An error loading the policy could be many things (the URL
+         // doesn't actually resolve a policy, the server is down, the
+         // policy is invalid, etc.). This could be interpreted as an
+         // error case, or simply as a case where no applicable policy
+         // is available (as is done when we pre-load policies). This
+         // module chooses the latter interpretation.
+         return new PolicyFinderResult();
+      }
+
+      // check that we got the right kind of policy...if we didn't, then
+      // we can't handle the reference
+      if (type == PolicyReference.POLICY_REFERENCE)
+      {
+         if (!(policy instanceof Policy))
+            return new PolicyFinderResult();
+      }
+      else
+      {
+         if (!(policy instanceof PolicySet))
+            return new PolicyFinderResult();
+      }
+
+      // finally, check that the constraints match ... note that in a more
+      // powerful module, you could actually have used the constraints to
+      // construct a more specific URL, passed the constraints to the
+      // server, etc., but this example module is staying simple
+      if (!constraints.meetsConstraint(policy.getVersion()))
+         return new PolicyFinderResult();
+
+      // if we got here, then we successfully resolved a policy that is
+      // the correct type, so return it
+      return new PolicyFinderResult(policy);
+   }
+
+}

Added: projects/security/security-xacml/trunk/jboss-xacml/src/tests/java/org/jboss/test/security/test/xacml/XACMLRequestCreationUnitTestCase.java
===================================================================
--- projects/security/security-xacml/trunk/jboss-xacml/src/tests/java/org/jboss/test/security/test/xacml/XACMLRequestCreationUnitTestCase.java	                        (rev 0)
+++ projects/security/security-xacml/trunk/jboss-xacml/src/tests/java/org/jboss/test/security/test/xacml/XACMLRequestCreationUnitTestCase.java	2008-04-08 22:51:45 UTC (rev 71808)
@@ -0,0 +1,112 @@
+/*
+  * JBoss, Home of Professional Open Source
+  * Copyright 2005, JBoss Inc., and individual contributors as indicated
+  * by the @authors tag. See the copyright.txt in the distribution for a
+  * full listing of individual contributors.
+  *
+  * This is free software; you can redistribute it and/or modify it
+  * under the terms of the GNU Lesser General Public License as
+  * published by the Free Software Foundation; either version 2.1 of
+  * the License, or (at your option) any later version.
+  *
+  * This software is distributed in the hope that it will be useful,
+  * but WITHOUT ANY WARRANTY; without even the implied warranty of
+  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+  * Lesser General Public License for more details.
+  *
+  * You should have received a copy of the GNU Lesser General Public
+  * License along with this software; if not, write to the Free
+  * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+  * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+  */
+package org.jboss.test.security.test.xacml;
+
+import java.net.URI;
+import java.util.HashSet;
+import java.util.Set;
+
+import junit.framework.TestCase;
+
+import org.jboss.security.xacml.sunxacml.attr.StringAttribute;
+import org.jboss.security.xacml.sunxacml.ctx.Attribute;
+import org.jboss.security.xacml.sunxacml.ctx.RequestCtx;
+import org.jboss.security.xacml.sunxacml.ctx.Subject;
+
+//$Id: XACMLRequestCreationUnitTestCase.java 45705 2006-06-20 17:30:10Z asaldhana $
+
+/**
+ *  Test creation of XACML Requests
+ *  @author <a href="mailto:Anil.Saldhana at jboss.org">Anil Saldhana</a>
+ *  @since  Jun 20, 2006 
+ *  @version $Revision: 45705 $
+ */
+public class XACMLRequestCreationUnitTestCase extends TestCase
+{
+   private static final boolean DEBUG = true;
+
+   public XACMLRequestCreationUnitTestCase(String name)
+   {
+      super(name);
+   }
+
+   public void testCreationOfRequest() throws Exception
+   {
+      //refer to the src/resources/security/xacml/test1/request.xml
+
+      //Create the subject set
+      URI subjectAttrUri = new URI("urn:oasis:names:tc:xacml:1.0:subject:subject-id");
+      Set subjectAttributeValues = new HashSet();
+      subjectAttributeValues.add(new StringAttribute("Anil Saldhana"));
+      Attribute subjectAttr = new Attribute(subjectAttrUri, new URI(StringAttribute.identifier), null, null,
+            subjectAttributeValues);
+      Set subjectAttrSet = new HashSet();
+      subjectAttrSet.add(subjectAttr);
+      Set subjectSet = new HashSet();
+      subjectSet.add(new Subject(subjectAttrSet));
+
+      //Create the resource set
+      URI resourceUri = new URI("urn:oasis:names:tc:xacml:1.0:resource:resource-id");
+      Set resourceAttributeValues = new HashSet();
+      resourceAttributeValues.add(new StringAttribute("http://jboss.com/developers/payroll/anilsaldhana"));
+      Attribute resourceAttr = new Attribute(resourceUri, new URI(StringAttribute.identifier), null, null,
+            resourceAttributeValues);
+      Set resourceSet = new HashSet();
+      resourceSet.add(resourceAttr);
+
+      //Create the action set
+      URI actionUri = new URI("urn:oasis:names:tc:xacml:1.0:action:action-id");
+      Set actionAttributeValues = new HashSet();
+      actionAttributeValues.add(new StringAttribute("read"));
+      Attribute actionAttr = new Attribute(actionUri, new URI(StringAttribute.identifier), null, null,
+            actionAttributeValues);
+      Set actionSet = new HashSet();
+      actionSet.add(actionAttr);
+
+      //Create the environment set
+      Set environSet = new HashSet();
+
+      RequestCtx request = new RequestCtx(subjectSet, resourceSet, actionSet, environSet);
+      assertNotNull("XACML Request != null", request);
+
+      //Log the request for viewing
+      if (DEBUG)
+         XACMLUtil.logRequest(request);
+
+      //Test the request contents
+      Set subjects = request.getSubjects();
+      assertTrue("We have one subject?", subjects.size() == 1);
+      Subject subj = (Subject) (subjects.iterator().next());
+      assertNotNull("Subject != null", subj);
+      assertEquals("Attributes in subject match", subjectAttr, (Attribute) (subj.getAttributes().iterator().next()));
+
+      //Test the resource attributes
+      Set resources = request.getResource();
+      assertTrue("# of resources = 1", resources.size() == 1);
+      assertEquals("Attributes in resources match", resourceAttr, (Attribute) (resources.iterator().next()));
+
+      //Test the action attributes
+      Set actions = request.getAction();
+      assertTrue("# of actions = 1", actions.size() == 1);
+      assertEquals("Attributes in actions match", actionAttr, (Attribute) (actions.iterator().next()));
+   }
+}


Property changes on: projects/security/security-xacml/trunk/jboss-xacml/src/tests/java/org/jboss/test/security/test/xacml/XACMLRequestCreationUnitTestCase.java
___________________________________________________________________
Name: svn:executable
   + *

Added: projects/security/security-xacml/trunk/jboss-xacml/src/tests/java/org/jboss/test/security/test/xacml/XACMLUnitTestCase.java
===================================================================
--- projects/security/security-xacml/trunk/jboss-xacml/src/tests/java/org/jboss/test/security/test/xacml/XACMLUnitTestCase.java	                        (rev 0)
+++ projects/security/security-xacml/trunk/jboss-xacml/src/tests/java/org/jboss/test/security/test/xacml/XACMLUnitTestCase.java	2008-04-08 22:51:45 UTC (rev 71808)
@@ -0,0 +1,192 @@
+/*
+  * JBoss, Home of Professional Open Source
+  * Copyright 2005, JBoss Inc., and individual contributors as indicated
+  * by the @authors tag. See the copyright.txt in the distribution for a
+  * full listing of individual contributors.
+  *
+  * This is free software; you can redistribute it and/or modify it
+  * under the terms of the GNU Lesser General Public License as
+  * published by the Free Software Foundation; either version 2.1 of
+  * the License, or (at your option) any later version.
+  *
+  * This software is distributed in the hope that it will be useful,
+  * but WITHOUT ANY WARRANTY; without even the implied warranty of
+  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+  * Lesser General Public License for more details.
+  *
+  * You should have received a copy of the GNU Lesser General Public
+  * License along with this software; if not, write to the Free
+  * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+  * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+  */
+package org.jboss.test.security.test.xacml;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.net.URL;
+import java.util.ArrayList;
+
+import junit.framework.TestCase;
+
+import org.jboss.security.xacml.sunxacml.ConfigurationStore;
+import org.jboss.security.xacml.sunxacml.PDP;
+import org.jboss.security.xacml.sunxacml.PDPConfig;
+import org.jboss.security.xacml.sunxacml.ParsingException;
+import org.jboss.security.xacml.sunxacml.ctx.RequestCtx;
+import org.jboss.security.xacml.sunxacml.ctx.ResponseCtx;
+import org.jboss.security.xacml.sunxacml.ctx.Result;
+import org.jboss.security.xacml.sunxacml.ctx.Status;
+
+//$Id: XACMLUnitTestCase.java 45725 2006-06-21 17:19:15Z asaldhana $
+
+/**
+ *  Unit Tests for the XACML Integration
+ *  @author <a href="mailto:Anil.Saldhana at jboss.org">Anil Saldhana</a>
+ *  @since  May 26, 2006 
+ *  @version $Revision: 45725 $
+ */
+public class XACMLUnitTestCase extends TestCase
+{
+   /**
+    * There are basic xacml conformance tests in the resources folder(security/xacml)
+    * with the format testX where X is an integer in (firstTest,numberOfTests}.
+    * If you need to run a particular test - make both these variables to be
+    * the number of the test. So to run test6, both firstTest=6 and
+    * numberOfTests=6
+    */
+   private int firstTest = 1;
+
+   private int numberOfTests = 17;
+
+   //True: Response will be dumped to System.out
+   private boolean debug = false;
+
+   public XACMLUnitTestCase(String name)
+   {
+      super(name);
+   }
+
+   public void testPDPConstruction() throws Exception
+   {
+      assertNotNull("PDP != null", getBasicPDP());
+   }
+
+   public void testPDPResponse() throws Exception
+   {
+      for (int i = firstTest; i <= numberOfTests; i++)
+      {
+         String[] policyFiles = new String[]
+         {getPolicyFile(i)};
+         PDP pdp = new PDP(new PDPConfig(XACMLUtil.getAttributeFinder(), XACMLUtil.getPolicyFinder(policyFiles), null));
+         assertNotNull("PDP != null", pdp);
+         ResponseCtx first = processRequest(pdp, getRequestFile(i));
+         assertNotNull("Response != null", first);
+         //Print out the response to the System.Out
+         XACMLUtil.logResponseCtxToSystemOut(first, debug);
+         ResponseCtx second = ResponseCtx.getInstance(new FileInputStream(getResponseFile(i)));
+         try
+         {
+            XACMLUtil.assertEquals(first, second);
+         }
+         catch (Exception e)
+         {
+            Exception enew = new Exception("Test#" + i + "::" + e.getMessage());
+            enew.initCause(e);
+            throw enew;
+         }
+      }
+   }
+
+   /**
+    * Obtain a very basic PDP
+    * @return
+    * @throws Exception
+    */
+   private PDP getBasicPDP() throws Exception
+   {
+      String p = "security/xacml/basicConfig.xml";
+      ClassLoader tcl = Thread.currentThread().getContextClassLoader();
+      URL url = tcl.getResource(p);
+      File file = new File(url.getPath());
+      ConfigurationStore store = new ConfigurationStore(file);
+      store.useDefaultFactories();
+      return new PDP(store.getDefaultPDPConfig());
+   }
+
+   /**
+    * Ask the PDP to evaluate the input request file
+    * @param pdp
+    * @param requestFile
+    * @return
+    * @throws Exception
+    */
+   private ResponseCtx processRequest(PDP pdp, String requestFile) throws Exception
+   {
+      ResponseCtx response = null;
+
+      try
+      {
+         response = pdp.evaluate(RequestCtx.getInstance(new FileInputStream(requestFile)));
+      }
+      catch (ParsingException pse)
+      {
+         response = getSyntaxErrorResponseCtx();
+      }
+      return response;
+   }
+
+   /**
+    * Get the String that represents the temp file
+    * for the Policy 1
+    * @return
+    */
+   private String getPolicyFile(int num) throws Exception
+   {
+      String p1 = "security/xacml/test" + num + "/policy.xml";
+      ClassLoader tcl = Thread.currentThread().getContextClassLoader();
+      URL url = tcl.getResource(p1);
+      assertNotNull("policy file " + p1 + "  null", url);
+      return url.getPath();
+   }
+
+   /**
+    * Get the String that represents the file
+    * for the Request File 
+    * @return
+    */
+   private String getRequestFile(int num) throws Exception
+   {
+      String p1 = "security/xacml/test" + num + "/request.xml";
+      ClassLoader tcl = Thread.currentThread().getContextClassLoader();
+      URL url = tcl.getResource(p1);
+      assertNotNull("request file " + p1 + " null", url);
+      return url.getPath();
+   }
+
+   /**
+    * Get the String that represents the file
+    * for the Request File  
+    * @return
+    */
+   private String getResponseFile(int num) throws Exception
+   {
+      String p1 = "security/xacml/test" + num + "/response.xml";
+      ClassLoader tcl = Thread.currentThread().getContextClassLoader();
+      URL url = tcl.getResource(p1);
+      assertNotNull("response file " + p1 + " != null", url);
+      return url.getPath();
+   }
+
+   /**
+    * Get the ResponseCtx that represents a Syntax Error
+    * @return
+    */
+   private ResponseCtx getSyntaxErrorResponseCtx()
+   {
+      ArrayList code = new ArrayList();
+      code.add(Status.STATUS_SYNTAX_ERROR);
+      Status status = new Status(code);
+
+      return new ResponseCtx(new Result(Result.DECISION_INDETERMINATE, status));
+   }
+}


Property changes on: projects/security/security-xacml/trunk/jboss-xacml/src/tests/java/org/jboss/test/security/test/xacml/XACMLUnitTestCase.java
___________________________________________________________________
Name: svn:executable
   + *

Added: projects/security/security-xacml/trunk/jboss-xacml/src/tests/java/org/jboss/test/security/test/xacml/XACMLUtil.java
===================================================================
--- projects/security/security-xacml/trunk/jboss-xacml/src/tests/java/org/jboss/test/security/test/xacml/XACMLUtil.java	                        (rev 0)
+++ projects/security/security-xacml/trunk/jboss-xacml/src/tests/java/org/jboss/test/security/test/xacml/XACMLUtil.java	2008-04-08 22:51:45 UTC (rev 71808)
@@ -0,0 +1,260 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005, JBoss Inc., and individual contributors as indicated
+ * by the @authors tag. See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.test.security.test.xacml;
+
+import java.io.ByteArrayOutputStream;
+import java.io.OutputStream;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+import org.jboss.test.security.test.xacml.modules.JBossStaticPolicyFinderModule;
+import org.jboss.test.security.test.xacml.modules.TestRoleAttributeFinderModule; 
+
+import org.jboss.security.xacml.sunxacml.Indenter;
+import org.jboss.security.xacml.sunxacml.Obligation;
+import org.jboss.security.xacml.sunxacml.combine.PermitOverridesPolicyAlg;
+import org.jboss.security.xacml.sunxacml.ctx.Attribute;
+import org.jboss.security.xacml.sunxacml.ctx.RequestCtx;
+import org.jboss.security.xacml.sunxacml.ctx.ResponseCtx;
+import org.jboss.security.xacml.sunxacml.ctx.Result;
+import org.jboss.security.xacml.sunxacml.ctx.Status;
+import org.jboss.security.xacml.sunxacml.finder.AttributeFinder;
+import org.jboss.security.xacml.sunxacml.finder.PolicyFinder;
+import org.jboss.security.xacml.sunxacml.finder.impl.CurrentEnvModule;
+import org.jboss.security.xacml.sunxacml.finder.impl.SelectorModule; 
+import org.jboss.security.xacml.sunxacml.support.finder.StaticRefPolicyFinderModule;
+import org.jboss.security.xacml.sunxacml.support.finder.URLPolicyFinderModule; 
+
+//$Id: XACMLUtil.java 58115 2006-11-04 08:42:14Z scott.stark at jboss.org $
+
+/**
+ *  Some Util methods for the XACML Suite of tests
+ *  @author <a href="mailto:Anil.Saldhana at jboss.org">Anil Saldhana</a>
+ *  @since  May 30, 2006 
+ *  @version $Revision: 58115 $
+ */
+public class XACMLUtil
+{ 
+   //Validate that two PDP responses are the same semantically
+   public static void assertEquals(ResponseCtx first, ResponseCtx second)
+   throws Exception
+   {
+      assertResults(first.getResults(), second.getResults()); 
+   }
+   
+   // Validate that two PDP response->results are the same semantically
+   public static void assertResults(Set first, Set second) throws Exception
+   {  
+      if (first.size() != second.size())
+         throw new Exception("Size of results mismatch");
+      
+      Iterator iter = first.iterator();
+      
+      // A set allows us to remove matching results individually
+      HashSet set2 = new HashSet(second);
+      
+      // consider each Result in the first Response, and try to find an
+      // equivalent one in the second Response
+      while (iter.hasNext()) 
+      {
+         Result result1 = (Result)(iter.next());
+         Iterator it2 = set2.iterator();
+         boolean matched = false;
+         
+         // go through the second list, and see if there's a matching Result
+         while (it2.hasNext() && (! matched)) 
+         {
+            Result result2 = (Result)(it2.next());
+            if (result1.getDecision() != result2.getDecision())
+               throw new Exception("decision in the result do not match");
+            assertStringMatch(result1.getResource(), result2.getResource());
+            assertStatus(result1.getStatus(), result2.getStatus());
+            assertObligations(result1.getObligations(),
+                  result2.getObligations()); 
+            matched = true; 
+         }
+         
+         // When matched, remove the result from the second set
+         if (matched)
+            it2.remove();
+         else
+            throw new Exception("result mismatch");
+      } 
+   }
+   
+   public static void assertStringMatch(String first, String second)
+   throws Exception
+   {
+      Exception ex = new Exception(first + "!=" + second); 
+      
+      if (first == null && second != null)  
+         throw ex;
+      if(second != null && first.equals(second) == false)
+         throw ex;  
+   }
+   
+   // Validate that two PDP response ->Status  are the same semantically
+   public static void assertStatus(Status first, Status second) 
+   throws Exception
+   {
+      Exception ex = new Exception(first + "!=" + second); 
+      Iterator it1 = first.getCode().iterator();
+      Iterator it2 = second.getCode().iterator();
+      
+      // Same code appear in the status?
+      while (it1.hasNext()) 
+      { 
+         if (! it2.hasNext())
+            throw ex;
+         String code = (String)(it1.next());
+         
+         // check that the specific code is the same at each step
+         if (! (code).equals((String)(it2.next())))
+            throw ex;
+      }
+      
+      // if there's still more in the second list, then they're not equal
+      if (it2.hasNext())
+         throw ex; 
+   }
+   
+   // Validate that two PDP response->Obligations are the same semantically
+   public static void assertObligations(Set first, Set second)
+   throws Exception
+   {
+      if (first.size() != first.size())
+         throw new Exception("Obligations sets do not match in size");
+      
+      Iterator it1 = first.iterator();
+      
+      // Set for the second set of Obligations, so we can
+      // remove the matching Obligation at each step
+      HashSet set2 = new HashSet(second);
+      
+      // For each Obligation in the first set, and try to find an
+      // equivalent one in the second set
+      while (it1.hasNext()) 
+      {
+         Obligation o1 = (Obligation)(it1.next());
+         Iterator it2 = set2.iterator();
+         boolean matched = false;
+         
+         // go through the second set, and see if there's a matching
+         // Obligation
+         while (it2.hasNext() && (! matched)) 
+         {
+            Obligation o2 = (Obligation)(it2.next());
+            
+            // Match identifier and fulfillOn setting
+            if ((o1.getId().equals(o2.getId())) &&
+                  (o1.getFulfillOn() == o2.getFulfillOn())) 
+            {
+               // Match the assignments 
+               List assignments1 = o1.getAssignments();
+               List assignments2 = o2.getAssignments();
+               
+               if (assignments1.size() == assignments2.size()) 
+               {
+                  Iterator ait1 = assignments1.iterator();
+                  Iterator ait2 = assignments2.iterator();
+                  boolean assignmentsMatch = true;
+                  
+                  while (ait1.hasNext() && assignmentsMatch) 
+                  {
+                     Attribute attr1 = (Attribute)(ait1.next());
+                     Attribute attr2 = (Attribute)(ait2.next());
+                     
+                     if ((! attr1.getId().equals(attr2.getId())) ||
+                           (! attr1.getType().equals(attr2.getType())) ||
+                           (! attr1.getValue().equals(attr2.getValue())))
+                        assignmentsMatch = false;
+                  }
+                  
+                  matched = assignmentsMatch;
+               }
+            }
+         }
+         
+         // If matched, remove it from the set 
+         if (matched)
+            it2.remove();
+         else
+            throw new Exception("Obligations do not match");
+      } 
+   }
+   
+   /**
+    * Get a prebuilt AttributeFinder
+    * @return
+    */
+   public static AttributeFinder getAttributeFinder()
+   {
+      //Prefill the attribute finder with the Sun's impl of 
+      //environment attribute module and the selector attribute module
+      AttributeFinder attributeFinder = new AttributeFinder();
+      List attributeModules = new ArrayList();
+      attributeModules.add(new TestRoleAttributeFinderModule()); 
+      attributeModules.add(new CurrentEnvModule());
+      attributeModules.add(new SelectorModule());
+      attributeFinder.setModules(attributeModules);
+      return attributeFinder;
+   } 
+   
+   /**
+    * Get a Prebuilt PolicyFinder with the passed array of policy files
+    * @param policyFiles
+    * @return
+    * @throws Exception
+    */
+   public static PolicyFinder getPolicyFinder(String[] policyFiles) throws Exception
+   {
+      List policyFileList = Arrays.asList(policyFiles);
+      PolicyFinder policyFinder = new PolicyFinder();
+      HashSet policyModules = new HashSet();
+      policyModules.add(new JBossStaticPolicyFinderModule(PermitOverridesPolicyAlg.algId,
+            policyFileList));
+      policyModules.add(new StaticRefPolicyFinderModule(policyFileList));
+      policyModules.add(new URLPolicyFinderModule());
+      policyFinder.setModules(policyModules);
+      return policyFinder;
+   }
+   
+   /**
+    * Log the PDP response to system out
+    * @param response
+    * @param flag true=response will be displayed false=no
+    */
+   public static void logResponseCtxToSystemOut(ResponseCtx response,
+         boolean flag)
+   {
+      if(flag)
+        response.encode(System.out, new Indenter());
+   } 
+   
+   public static void logRequest(RequestCtx request) throws Exception
+   {
+      request.encode(System.out, new Indenter());
+   }
+}


Property changes on: projects/security/security-xacml/trunk/jboss-xacml/src/tests/java/org/jboss/test/security/test/xacml/XACMLUtil.java
___________________________________________________________________
Name: svn:executable
   + *

Added: projects/security/security-xacml/trunk/jboss-xacml/src/tests/java/org/jboss/test/security/test/xacml/modules/JBossStaticPolicyFinderModule.java
===================================================================
--- projects/security/security-xacml/trunk/jboss-xacml/src/tests/java/org/jboss/test/security/test/xacml/modules/JBossStaticPolicyFinderModule.java	                        (rev 0)
+++ projects/security/security-xacml/trunk/jboss-xacml/src/tests/java/org/jboss/test/security/test/xacml/modules/JBossStaticPolicyFinderModule.java	2008-04-08 22:51:45 UTC (rev 71808)
@@ -0,0 +1,288 @@
+/*
+  * JBoss, Home of Professional Open Source
+  * Copyright 2005, JBoss Inc., and individual contributors as indicated
+  * by the @authors tag. See the copyright.txt in the distribution for a
+  * full listing of individual contributors.
+  *
+  * This is free software; you can redistribute it and/or modify it
+  * under the terms of the GNU Lesser General Public License as
+  * published by the Free Software Foundation; either version 2.1 of
+  * the License, or (at your option) any later version.
+  *
+  * This software is distributed in the hope that it will be useful,
+  * but WITHOUT ANY WARRANTY; without even the implied warranty of
+  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+  * Lesser General Public License for more details.
+  *
+  * You should have received a copy of the GNU Lesser General Public
+  * License along with this software; if not, write to the Free
+  * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+  * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+  */
+package org.jboss.test.security.test.xacml.modules;
+
+import java.io.File;
+import java.net.MalformedURLException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.logging.Logger;
+
+import org.jboss.security.xacml.sunxacml.AbstractPolicy;
+import org.jboss.security.xacml.sunxacml.EvaluationCtx;
+import org.jboss.security.xacml.sunxacml.ParsingException;
+import org.jboss.security.xacml.sunxacml.UnknownIdentifierException;
+import org.jboss.security.xacml.sunxacml.combine.CombiningAlgFactory;
+import org.jboss.security.xacml.sunxacml.combine.PolicyCombiningAlgorithm;
+import org.jboss.security.xacml.sunxacml.ctx.Status;
+import org.jboss.security.xacml.sunxacml.finder.PolicyFinder;
+import org.jboss.security.xacml.sunxacml.finder.PolicyFinderModule;
+import org.jboss.security.xacml.sunxacml.finder.PolicyFinderResult;
+import org.jboss.security.xacml.sunxacml.support.finder.PolicyCollection;
+import org.jboss.security.xacml.sunxacml.support.finder.PolicyReader;
+import org.jboss.security.xacml.sunxacml.support.finder.StaticPolicyFinderModule;
+import org.jboss.security.xacml.sunxacml.support.finder.TopLevelPolicyException;
+
+//$Id: JBossStaticPolicyFinderModule.java 45389 2006-05-30 21:29:37Z asaldhana $
+
+/**
+ *  Policy Finder Module that is based on the StaticPolicyFinderModule
+ *  but will always provide a status of syntax error if there has been
+ *  a parsing exception in policy file(s)
+ *  @author <a href="mailto:Anil.Saldhana at jboss.org">Anil Saldhana</a>
+ *  @since  May 30, 2006 
+ *  @version $Revision: 45389 $
+ */
+public class JBossStaticPolicyFinderModule extends PolicyFinderModule
+{
+   // the list of policy URLs passed to the constructor
+   private List policyList;
+
+   // the map of policies
+   private PolicyCollection policies;
+
+   // the optional schema file
+   private File schemaFile = null;
+
+   // the policy identifier for any policy sets we dynamically create
+   private static final String POLICY_ID = "urn:com:sun:xacml:support:finder:dynamic-policy-set";
+
+   private static URI policyId = null;
+
+   // the logger we'll use for all messages
+   private static final Logger log = Logger.getLogger(StaticPolicyFinderModule.class.getName());
+
+   //Was there an encounter of parse exception?
+   private boolean encounteredParsingException = false;
+
+   static
+   {
+      try
+      {
+         policyId = new URI(POLICY_ID);
+      }
+      catch (Exception e)
+      {
+         log.severe("couldn't assign default policy id: " + e.getMessage());
+      }
+   };
+
+   /**
+    * Creates a <code>StaticPolicyFinderModule</code> that provides
+    * access to the given collection of policies and returns an error when
+    * more than one policy matches a given context. Any policy that cannot
+    * be loaded will be noted in the log, but will not cause an error. The
+    * schema file used to validate policies is defined by the property
+    * <code>PolicyReader.POLICY_SCHEMA_PROPERTY</code>. If the retrieved
+    * property is null, then no schema validation will occur.
+    *
+    * @param policyList a <code>List</code> of <code>String</code>s that
+    *                   represent URLs or files pointing to XACML policies
+    */
+   public JBossStaticPolicyFinderModule(List policyList)
+   {
+      this.policyList = policyList;
+      this.policies = new PolicyCollection();
+
+      String schemaName = System.getProperty(PolicyReader.POLICY_SCHEMA_PROPERTY);
+      if (schemaName != null)
+         schemaFile = new File(schemaName);
+   }
+
+   /**
+    * Creates a <code>StaticPolicyFinderModule</code> that provides
+    * access to the given collection of policies and returns an error when
+    * more than one policy matches a given context. Any policy that cannot
+    * be loaded will be noted in the log, but will not cause an error.
+    *
+    * @param policyList a <code>List</code> of <code>String</code>s that
+    *                   represent URLs or files pointing to XACML policies
+    * @param schemaFile the schema file to validate policies against,
+    *                   or null if schema validation is not desired
+    */
+   public JBossStaticPolicyFinderModule(List policyList, String schemaFile)
+   {
+      this.policyList = policyList;
+      this.policies = new PolicyCollection();
+
+      if (schemaFile != null)
+         this.schemaFile = new File(schemaFile);
+   }
+
+   /**
+    * Creates a <code>StaticPolicyFinderModule</code> that provides
+    * access to the given collection of policies. The given combining
+    * algorithm is used to create new PolicySets when more than one
+    * policy applies. Any policy that cannot be loaded will be noted in
+    * the log, but will not cause an error. The schema file used to
+    * validate policies is defined by the property
+    * <code>PolicyReader.POLICY_SCHEMA_PROPERTY</code>. If the retrieved
+    * property is null, then no schema validation will occur.
+    *
+    * @param combiningAlg the algorithm to use in a new PolicySet when more
+    *                     than one policy applies
+    * @param policyList a <code>List</code> of <code>String</code>s that
+    *                   represent URLs or files pointing to XACML policies
+    *
+    * @throws URISyntaxException if the combining algorithm is not a
+    *                            well-formed URI
+    * @throws UnknownIdentifierException if the combining algorithm identifier
+    *                                    isn't known
+    */
+   public JBossStaticPolicyFinderModule(String combiningAlg, List policyList) throws URISyntaxException,
+         UnknownIdentifierException
+   {
+      PolicyCombiningAlgorithm alg = (PolicyCombiningAlgorithm) (CombiningAlgFactory.getInstance()
+            .createAlgorithm(new URI(combiningAlg)));
+
+      this.policyList = policyList;
+      this.policies = new PolicyCollection(alg, policyId);
+
+      String schemaName = System.getProperty(PolicyReader.POLICY_SCHEMA_PROPERTY);
+      if (schemaName != null)
+         schemaFile = new File(schemaName);
+   }
+
+   /**
+    * Creates a <code>StaticPolicyFinderModule</code> that provides
+    * access to the given collection of policies. The given combining
+    * algorithm is used to create new PolicySets when more than one
+    * policy applies. Any policy that cannot be loaded will be noted in
+    * the log, but will not cause an error.
+    *
+    * @param combiningAlg the algorithm to use in a new PolicySet when more
+    *                     than one policy applies
+    * @param policyList a <code>List</code> of <code>String</code>s that
+    *                   represent URLs or files pointing to XACML policies
+    * @param schemaFile the schema file to validate policies against,
+    *                   or null if schema validation is not desired
+    *
+    * @throws URISyntaxException if the combining algorithm is not a
+    *                            well-formed URI
+    * @throws UnknownIdentifierException if the combining algorithm identifier
+    *                                    isn't known
+    */
+   public JBossStaticPolicyFinderModule(String combiningAlg, List policyList, String schemaFile)
+         throws URISyntaxException, UnknownIdentifierException
+   {
+      PolicyCombiningAlgorithm alg = (PolicyCombiningAlgorithm) (CombiningAlgFactory.getInstance()
+            .createAlgorithm(new URI(combiningAlg)));
+
+      this.policyList = policyList;
+      this.policies = new PolicyCollection(alg, policyId);
+
+      if (schemaFile != null)
+         this.schemaFile = new File(schemaFile);
+   }
+
+   /**
+    * Always returns <code>true</code> since this module does support
+    * finding policies based on context.
+    *
+    * @return true
+    */
+   public boolean isRequestSupported()
+   {
+      return true;
+   }
+
+   /**
+    * Initialize this module. Typically this is called by
+    * <code>PolicyFinder</code> when a PDP is created. This method is
+    * where the policies are actually loaded.
+    *
+    * @param finder the <code>PolicyFinder</code> using this module
+    */
+   public void init(PolicyFinder finder)
+   {
+      String clazzName = JBossStaticPolicyFinderModule.class.getName();
+      // now that we have the PolicyFinder, we can load the policies
+      PolicyReader reader = new PolicyReader(finder, java.util.logging.Logger.getLogger(clazzName), schemaFile);
+
+      Iterator it = policyList.iterator();
+      while (it.hasNext())
+      {
+         String str = (String) (it.next());
+         AbstractPolicy policy = null;
+         try
+         {
+            try
+            {
+               // first try to load it as a URL
+               URL url = new URL(str);
+               policy = reader.readPolicy(url);
+            }
+            catch (MalformedURLException murle)
+            {
+               // assume that this is a filename, and try again
+               policy = reader.readPolicy(new File(str));
+            }
+         }
+         catch (ParsingException e)
+         {
+            this.encounteredParsingException = true;
+            log.severe("Parsing Exception in policy: " + e.getMessage());
+            continue;
+         }
+
+         // we loaded the policy, so try putting it in the collection
+         if (!policies.addPolicy(policy))
+            log.warning("tried to load the same " + "policy multiple times: " + str);
+      }
+   }
+
+   /**
+    * Finds a policy based on a request's context. If more than one policy
+    * matches, then this either returns an error or a new policy wrapping
+    * the multiple policies (depending on which constructor was used to
+    * construct this instance).
+    *
+    * @param context the representation of the request data
+    *
+    * @return the result of trying to find an applicable policy
+    */
+   public PolicyFinderResult findPolicy(EvaluationCtx context)
+   {
+      List aList = new ArrayList();
+      aList.add(Status.STATUS_SYNTAX_ERROR);
+
+      try
+      {
+         if (this.encounteredParsingException)
+            return new PolicyFinderResult(new Status(aList));
+         AbstractPolicy policy = policies.getPolicy(context);
+
+         if (policy == null)
+            return new PolicyFinderResult();
+         else
+            return new PolicyFinderResult(policy);
+      }
+      catch (TopLevelPolicyException tlpe)
+      {
+         return new PolicyFinderResult(tlpe.getStatus());
+      }
+   }
+}


Property changes on: projects/security/security-xacml/trunk/jboss-xacml/src/tests/java/org/jboss/test/security/test/xacml/modules/JBossStaticPolicyFinderModule.java
___________________________________________________________________
Name: svn:executable
   + *

Added: projects/security/security-xacml/trunk/jboss-xacml/src/tests/java/org/jboss/test/security/test/xacml/modules/TestResourceFinderModule.java
===================================================================
--- projects/security/security-xacml/trunk/jboss-xacml/src/tests/java/org/jboss/test/security/test/xacml/modules/TestResourceFinderModule.java	                        (rev 0)
+++ projects/security/security-xacml/trunk/jboss-xacml/src/tests/java/org/jboss/test/security/test/xacml/modules/TestResourceFinderModule.java	2008-04-08 22:51:45 UTC (rev 71808)
@@ -0,0 +1,149 @@
+/*
+  * JBoss, Home of Professional Open Source
+  * Copyright 2005, JBoss Inc., and individual contributors as indicated
+  * by the @authors tag. See the copyright.txt in the distribution for a
+  * full listing of individual contributors.
+  *
+  * This is free software; you can redistribute it and/or modify it
+  * under the terms of the GNU Lesser General Public License as
+  * published by the Free Software Foundation; either version 2.1 of
+  * the License, or (at your option) any later version.
+  *
+  * This software is distributed in the hope that it will be useful,
+  * but WITHOUT ANY WARRANTY; without even the implied warranty of
+  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+  * Lesser General Public License for more details.
+  *
+  * You should have received a copy of the GNU Lesser General Public
+  * License along with this software; if not, write to the Free
+  * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+  * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+  */
+package org.jboss.test.security.test.xacml.modules;
+
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.HashSet;
+
+import org.jboss.security.xacml.sunxacml.EvaluationCtx;
+import org.jboss.security.xacml.sunxacml.attr.AnyURIAttribute;
+import org.jboss.security.xacml.sunxacml.attr.AttributeValue;
+import org.jboss.security.xacml.sunxacml.finder.ResourceFinderModule;
+import org.jboss.security.xacml.sunxacml.finder.ResourceFinderResult;
+
+//$Id: TestResourceFinderModule.java 45389 2006-05-30 21:29:37Z asaldhana $
+
+/**
+ *  Resource Finder Module for testing purposes
+ *  @author <a href="mailto:Anil.Saldhana at jboss.org">Anil Saldhana</a>
+ *  @since  May 26, 2006 
+ *  @version $Revision: 45389 $
+ */
+public class TestResourceFinderModule extends ResourceFinderModule
+{
+
+   /**
+    * Default constructor.
+    */
+   public TestResourceFinderModule()
+   {
+   }
+
+   /**
+    * @see ResourceFinderModule#isChildSupported()
+    *
+    * @return true
+    */
+   public boolean isChildSupported()
+   {
+      return true;
+   }
+
+   /**
+    * @see ResourceFinderModule#isDescendantSupported()
+    *
+    * @return true
+    */
+   public boolean isDescendantSupported()
+   {
+      return true;
+   }
+
+   /**
+    * @see ResourceFinderModule#findChildResources(com.sun.xacml.attr.AttributeValue, 
+    *                com.sun.xacml.EvaluationCtx)  
+    */
+   public ResourceFinderResult findChildResources(AttributeValue root, EvaluationCtx context)
+   {
+      //Validate the root 
+      if (preValidateRequest(root) == false)
+         return new ResourceFinderResult();
+
+      // add the root to the set of resolved resources
+      HashSet set = new HashSet();
+      set.add(root);
+
+      // add the other resources, which are defined by the conformance tests
+      try
+      {
+         set.add(new AnyURIAttribute(new URI("urn:root:child1")));
+         set.add(new AnyURIAttribute(new URI("urn:root:child2")));
+      }
+      catch (URISyntaxException ex)
+      {
+      }
+
+      return new ResourceFinderResult(set);
+   }
+
+   /**
+    * @see ResourceFinderModule#findDescendantResources(com.sun.xacml.attr.AttributeValue, 
+    *             com.sun.xacml.EvaluationCtx) 
+    */
+   public ResourceFinderResult findDescendantResources(AttributeValue root, EvaluationCtx context)
+   {
+      // Validate the root 
+      if (preValidateRequest(root) == false)
+         return new ResourceFinderResult();
+
+      // add the root to the set of resolved resources
+      HashSet set = new HashSet();
+      set.add(root);
+
+      // add the other resources, which are defined by the conformance tests
+      try
+      {
+         set.add(new AnyURIAttribute(new URI("urn:root:child1")));
+         set.add(new AnyURIAttribute(new URI("urn:root:child1:descendant1")));
+         set.add(new AnyURIAttribute(new URI("urn:root:child1:descendant2")));
+         set.add(new AnyURIAttribute(new URI("urn:root:child2")));
+         set.add(new AnyURIAttribute(new URI("urn:root:child2:descendant1")));
+         set.add(new AnyURIAttribute(new URI("urn:root:child2:descendant2")));
+      }
+      catch (URISyntaxException ex)
+      {
+      }
+      return new ResourceFinderResult(set);
+   }
+
+   /**
+    * Verify the root
+    */
+   private boolean preValidateRequest(AttributeValue root)
+   {
+      String rootType = root.getType().toString();
+
+      //Check that the resource-id for the root is a URI
+      if (AnyURIAttribute.identifier.equals(rootType) == false)
+         return false;
+
+      AnyURIAttribute uriRoot = (AnyURIAttribute) root;
+
+      //Is root == urn:root?
+      if ("urn:root".equals(uriRoot.toString()) == false)
+         return false;
+
+      return true;
+   }
+
+}


Property changes on: projects/security/security-xacml/trunk/jboss-xacml/src/tests/java/org/jboss/test/security/test/xacml/modules/TestResourceFinderModule.java
___________________________________________________________________
Name: svn:executable
   + *

Added: projects/security/security-xacml/trunk/jboss-xacml/src/tests/java/org/jboss/test/security/test/xacml/modules/TestRoleAttributeFinderModule.java
===================================================================
--- projects/security/security-xacml/trunk/jboss-xacml/src/tests/java/org/jboss/test/security/test/xacml/modules/TestRoleAttributeFinderModule.java	                        (rev 0)
+++ projects/security/security-xacml/trunk/jboss-xacml/src/tests/java/org/jboss/test/security/test/xacml/modules/TestRoleAttributeFinderModule.java	2008-04-08 22:51:45 UTC (rev 71808)
@@ -0,0 +1,167 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005, JBoss Inc., and individual contributors as indicated
+ * by the @authors tag. See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.test.security.test.xacml.modules;
+
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Set;
+
+import org.jboss.security.xacml.sunxacml.EvaluationCtx;
+import org.jboss.security.xacml.sunxacml.attr.AttributeDesignator;
+import org.jboss.security.xacml.sunxacml.attr.BagAttribute;
+import org.jboss.security.xacml.sunxacml.attr.StringAttribute;
+import org.jboss.security.xacml.sunxacml.cond.EvaluationResult;
+import org.jboss.security.xacml.sunxacml.ctx.Status;
+import org.jboss.security.xacml.sunxacml.finder.AttributeFinderModule;
+
+//$Id: TestRoleAttributeFinderModule.java 58115 2006-11-04 08:42:14Z scott.stark at jboss.org $
+
+/**
+ *  An attribute finder module for testing that only deals with the
+ *  role identifier called as
+ *  "urn:oasis:names:tc:xacml:1.0:example:attribute:role"
+ *  @author <a href="mailto:Anil.Saldhana at jboss.org">Anil Saldhana</a>
+ *  @since  May 26, 2006 
+ *  @version $Revision: 58115 $
+ */
+
+public class TestRoleAttributeFinderModule extends AttributeFinderModule
+{
+   /**
+    * XACML Identifier supported by this module
+    */
+   public static final String ROLE_IDENTIFIER = "urn:oasis:names:tc:xacml:1.0:example:attribute:role";
+
+   // subject-id standard identifier
+   private static URI SUBJECT_IDENTIFIER = null;
+
+   private static URI SUBJECT_SOMEATTRIBUTE_IDENTIFIER = null;
+
+   // initialize the standard subject identifier
+   static
+   {
+      try
+      {
+         SUBJECT_IDENTIFIER = new URI("urn:oasis:names:tc:xacml:1.0:subject:subject-id");
+         SUBJECT_SOMEATTRIBUTE_IDENTIFIER = new URI("urn:oasis:names:tc:xacml:2.0:jboss-test:some-attribute");
+      }
+      catch (URISyntaxException ex)
+      {
+      }
+   };
+
+   /**
+    * Default constructor.
+    */
+   public TestRoleAttributeFinderModule()
+   {
+
+   }
+
+   /**
+    * @see AttributeFinderModule#isDesignatorSupported()
+    *
+    * @return true
+    */
+   public boolean isDesignatorSupported()
+   {
+      return true;
+   }
+
+   /**
+    * @see AttributeFinderModule#getSupportedDesignatorTypes()
+    * Returns only <code>SUBJECT_TARGET</code> since this module only
+    * supports Subject attributes.
+    *
+    * @return a <code>Set</code> with an <code>Integer</code> of value
+    *         <code>AttributeDesignator.SUBJECT_TARGET</code>
+    */
+   public Set getSupportedDesignatorTypes()
+   {
+      Set set = new HashSet();
+      set.add(new Integer(AttributeDesignator.SUBJECT_TARGET));
+      return set;
+   }
+
+   /**
+    * @see AttributeFinderModule#getSupportedIds()
+    *
+    * @return a <code>Set</code> containing <code>ROLE_IDENTIFIER</code>
+    */
+   public Set getSupportedIds()
+   {
+      Set set = new HashSet();
+      set.add(ROLE_IDENTIFIER);
+      return set;
+   }
+
+   /**
+    * Supports the retrieval of exactly one kind of attribute.
+    */
+   public EvaluationResult findAttribute(URI attributeType, URI attributeId, URI issuer, URI subjectLogger,
+         EvaluationCtx context, int designatorType)
+   {
+      // Check the identifier 
+      if (!attributeId.toString().equals(ROLE_IDENTIFIER))
+         return new EvaluationResult(BagAttribute.createEmptyBag(attributeType));
+
+      // Did they ask for a String??
+      if (!attributeType.toString().equals(StringAttribute.identifier))
+         return new EvaluationResult(BagAttribute.createEmptyBag(attributeType));
+
+      // Retrieve the subject identifer from the context
+      EvaluationResult result = context.getSubjectAttribute(attributeType, SUBJECT_IDENTIFIER, issuer, subjectLogger);
+      if (result.indeterminate())
+         return result;
+
+      // Check that we succeeded in getting the subject identifier
+      BagAttribute bag = (BagAttribute) (result.getAttributeValue());
+      if (bag.isEmpty())
+      {
+         ArrayList code = new ArrayList();
+         code.add(Status.STATUS_MISSING_ATTRIBUTE);
+         Status status = new Status(code, "missing subject-id");
+         return new EvaluationResult(status);
+      }
+
+      // Finally search for the subject with the role-mapping defined,
+      // and if there is a match, add their role
+      BagAttribute returnBag = null;
+      Iterator it = bag.iterator();
+      while (it.hasNext())
+      {
+         StringAttribute attr = (StringAttribute) (it.next());
+         if (attr.getValue().equals("Anil Saldhana"))
+         {
+            Set set = new HashSet();
+            set.add(new StringAttribute("Developer"));
+            returnBag = new BagAttribute(attributeType, set);
+            break;
+         }
+      }
+
+      return new EvaluationResult(returnBag);
+   }
+}


Property changes on: projects/security/security-xacml/trunk/jboss-xacml/src/tests/java/org/jboss/test/security/test/xacml/modules/TestRoleAttributeFinderModule.java
___________________________________________________________________
Name: svn:executable
   + *




More information about the jboss-cvs-commits mailing list