avalon-cvs mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From dona...@apache.org
Subject cvs commit: jakarta-avalon-excalibur/policy/src/xdocs index.xml menu.xml sample.xml
Date Wed, 25 Sep 2002 12:37:44 GMT
donaldp     2002/09/25 05:37:44

  Added:       policy   .cvsignore build.xml default.properties
               policy/src/java/org/apache/excalibur/policy/builder
                        PolicyBuilder.java PolicyResolver.java
               policy/src/java/org/apache/excalibur/policy/metadata
                        GrantMetaData.java KeyStoreMetaData.java
                        PermissionMetaData.java PolicyMetaData.java
               policy/src/java/org/apache/excalibur/policy/reader
                        PolicyReader.java policy.dtd
               policy/src/java/org/apache/excalibur/policy/runtime
                        AbstractPolicy.java DefaultPolicy.java
                        PolicyEntry.java
               policy/src/java/org/apache/excalibur/policy/verifier
                        PolicyVerifier.java Resources.properties
               policy/src/test/org/apache/excalibur/policy/reader/test
                        ReaderTestCase.java config1.xml config2.xml
                        config3.xml
               policy/src/test/org/apache/excalibur/policy/test
                        AbstractPolicyTestCase.java PolicyTestSuite.java
               policy/src/test/org/apache/excalibur/policy/verifier/test
                        VerifierTestCase.java config1.xml config2.xml
                        config3.xml config4.xml config5.xml
               policy/src/xdocs index.xml menu.xml sample.xml
  Log:
  Migrate policy code to new product.
  
  Write some basic documentation that describes a sample descriptor and intention of library.
  
  Revision  Changes    Path
  1.1                  jakarta-avalon-excalibur/policy/.cvsignore
  
  Index: .cvsignore
  ===================================================================
  docs
  velocity.log*
  ant.properties
  build
  checkstyle.cache
  distributions
  dist
  excalibur-*
  *.el
  *.ipr
  
  
  
  1.1                  jakarta-avalon-excalibur/policy/build.xml
  
  Index: build.xml
  ===================================================================
  <?xml version="1.0"?>
  
  <project name="Excalibur Policy" default="main" basedir=".">
  
      <property file="${user.home}/build.properties"/>
      <property file="${basedir}/../ant.properties"/>
      <property file="${basedir}/ant.properties"/>
      <property file="${user.home}/.ant.properties"/>
      <property file="${basedir}/../default.properties"/>
      <property file="${basedir}/default.properties"/>
  
      <!-- Classpath for product -->
      <path id="project.class.path">
          <pathelement location="${build.classes}"/>
          <pathelement location="${avalon-framework.jar}"/>
          <pathelement location="${excalibur-i18n.jar}"/>
          <pathelement location="${checkstyle.jar}"/>
          <pathelement location="${xml-apis.jar}"/>
          <pathelement path="${java.class.path}"/>
      </path>
  
      <path id="tools.class.path">
          <pathelement location="${junit.jar}"/>
          <fileset dir="${jakarta-site.dir}/lib"/>
      </path>
  
      <path id="test.class.path">
          <pathelement location="${build.testclasses}"/>
          <pathelement location="${junit.jar}"/>
          <path refid="project.class.path"/>
      </path>
      <property name="cp" refid="test.class.path"/>
  
      <target name="main" depends="jar" description="Build the project"/>
      <target name="rebuild" depends="clean,main" description="Rebuild the project"/>
  
      <target name="dependencies" description="Check dependencies" unless="skip.dependencies">
          <ant antfile="${depchecker.prefix}/depchecker.xml" target="checkCommon"/>
          <ant antfile="${depchecker.prefix}/depchecker.xml" target="checkFramework"/>
          <ant antfile="${depchecker.prefix}/depchecker.xml" target="checkI18N"/>
      </target>
  
      <target name="dependencies-test" depends="dist-jar, dependencies"
          description="Check unit test dependencies" unless="skip.dependencies">
          <!-- Need the jar to prevent recursive deps. -->
  
          <ant antfile="${depchecker.prefix}/depchecker.xml" target="checkJUnit"/>
      </target>
  
  
      <!-- Compiles the source code -->
      <target name="compile" depends="dependencies" description="Compiles the source code">
  
          <mkdir dir="${build.classes}"/>
  
          <!-- Compile all classes excluding the tests. -->
          <javac srcdir="${java.dir}"
              destdir="${build.classes}"
              debug="${build.debug}"
              optimize="${build.optimize}"
              deprecation="${build.deprecation}"
              target="1.2">
              <classpath refid="project.class.path" />
              <include name="**/*.java"/>
          </javac>
  
          <!-- copy resources to same location as .class files -->
          <copy todir="${build.classes}">
              <fileset dir="${java.dir}">
                  <exclude name="**/*.java"/>
                  <exclude name="**/package.html"/>
              </fileset>
          </copy>
  
      </target>
  
      <!-- Compiles the unit test source code -->
      <target name="compile-test" depends="compile, dependencies-test" description="Compiles the source code">
          <mkdir dir="${build.testsrc}"/>
  
          <!-- Copy over all of the tests applying test filters -->
          <copy todir="${build.testsrc}">
              <fileset dir="${test.dir}"/>
          </copy>
  
          <mkdir dir="${build.testclasses}"/>
  
          <!-- Compile all test classes. -->
          <javac srcdir="${build.testsrc}"
              destdir="${build.testclasses}"
              debug="${build.debug}"
              optimize="${build.optimize}"
              deprecation="${build.deprecation}"
              target="1.2">
              <classpath refid="test.class.path" />
              <include name="**/*.java"/>
          </javac>
  
          <copy todir="${build.testclasses}">
              <fileset dir="${test.dir}">
                  <exclude name="**/*.java"/>
                  <exclude name="**/package.html"/>
              </fileset>
          </copy>
  
      </target>
  
      <!-- Copies and filters the license. Used by jar and dist -->
      <target name="prepare-conf">
          <mkdir dir="${build.conf}"/>
          <copy todir="${build.conf}" flatten="true">
              <fileset dir="../" includes="LICENSE.txt"/>
              <filterset>
                  <filter token="year" value="${year}"/>
              </filterset>
          </copy>
      </target>
  
      <!-- Creates all the .jar file -->
      <target name="jar" depends="compile, prepare-conf" description="Generates the jar files">
  
          <mkdir dir="${build.lib}"/>
  
          <jar jarfile="${build.lib}/${jar.name}"
              basedir="${build.classes}"
              compress="${build.compress}">
              <manifest>
                  <attribute name="Extension-Name" value="${name}"/>
                  <attribute name="Specification-Vendor" value="Apache Software Foundation"/>
                  <attribute name="Specification-Version" value="1.0"/>
                  <attribute name="Implementation-Vendor" value="Apache Software Foundation"/>
                  <attribute name="Implementation-Version" value="${package-version}"/>
              </manifest>
              <exclude name="**/test/**"/>
              <zipfileset dir="${build.conf}" prefix="META-INF/">
                  <include name="LICENSE.txt"/>
              </zipfileset>
          </jar>
      </target>
  
      <!-- Creates all the Javadocs -->
      <target name="javadocs" depends="compile" description="Generates the javadocs" unless="skip.javadocs">
  
          <mkdir dir="${dist.javadocs}"/>
          <javadoc packagenames="org.apache.*"
              sourcepath="${java.dir}"
              destdir="${dist.javadocs}">
              <classpath refid="project.class.path" />
              <group title="${Name} API" packages="org.apache.excalibur.*" />
              <doclet name="com.sun.tools.doclets.standard.Standard">
                  <param name="-author"/>
                  <param name="-version"/>
                  <param name="-doctitle" value="${Name}"/>
                  <param name="-windowtitle" value="${Name} API"/>
                  <param name="-link" value="http://java.sun.com/j2se/1.4/docs/api/"/>
                  <param name="-link" value="http://java.sun.com/j2ee/sdk_1.3/techdocs/api/"/>
                  <param name="-link" value="http://jakarta.apache.org/avalon/api/"/>
                  <param name="-bottom"
                      value="&quot;Copyright &#169; ${year} Apache Jakarta Project. All Rights Reserved.&quot;"/>
              </doclet>
  
          </javadoc>
      </target>
  
      <target name="test" depends="compile-test" description="Perform the unit tests" unless="skip.tests">
  
          <echo message="Performing Unit Tests" />
  
          <mkdir dir="${build.tests}"/>
  
          <junit fork="true"
              haltonfailure="${junit.failonerror}"
              printsummary="yes"
              dir="${build.tests}">
              <classpath refid="test.class.path"/>
  
              <formatter type="xml"/>    <!-- xml reports for junitreport -->
              <formatter type="plain" usefile="false"/>  <!-- text reports for humans     -->
  
              <batchtest todir="${build.tests}">
                  <fileset dir="${build.testclasses}">
                      <include name="**/test/*TestCase.class"/>
                      <exclude name="**/Abstract*"/>
                  </fileset>
              </batchtest>
          </junit>
  
      </target>
  
      <target name="test-reports" depends="test" description="Generate Reports for the unit tests">
  
          <ant antfile="${depchecker.prefix}/depchecker.xml" target="checkBSF"/>
  
          <mkdir dir="${build.reports}/junit"/>
  
          <junitreport todir="${build.reports}/junit">
              <fileset dir="${build.tests}">
                  <include name="TEST-*.xml"/>
              </fileset>
              <report format="frames" todir="${build.reports}/junit"/>
          </junitreport>
  
          <!-- Clean up the xml reports used by the junitreport task -->
          <!--
          <delete>
              <fileset dir="${build.tests}" includes="TEST-*.xml"/>
              <fileset dir="${build.tests}" includes="TESTS-*.xml"/>
          </delete>
          -->
  
      </target>
  
      <target name="checkstyle" if="do.checkstyle" description="Checkstyle">
  
          <!-- this invocation of checkstyle requires that checkstyle be downloaded and setup -->
          <!-- thats why you are required to define do.checkstyle property to generate the report -->
          <taskdef name="checkstyle"
              classname="com.puppycrawl.tools.checkstyle.CheckStyleTask">
              <classpath refid="project.class.path"/>
          </taskdef>
          <checkstyle
              lcurlyType="nl"
              lcurlyMethod="nl"
              lcurlyOther="nl"
              rcurly="ignore"
              allowProtected="false"
              allowPackage="false"
              allowNoAuthor="false"
              maxLineLen="100"
              maxMethodLen="100"
              maxConstructorLen="100"
              memberPattern="^m_[a-z][a-zA-Z0-9]*$"
              staticPattern="^c_[a-z][a-zA-Z0-9]*$"
              constPattern="(^c_[a-z][a-zA-Z0-9]*$)|([A-Z_]*$)"
              ignoreImportLen="true"
              allowTabs="false"
              javadocScope="protected"
              ignoreWhitespace="true"
              cacheFile="checkstyle.cache"
              failOnViolation="false"
              ignoreCastWhitespace="true">
              <fileset dir="${java.dir}">
                  <include name="**/*.java"/>
              </fileset>
              <formatter type="plain"/>
              <formatter type="xml" toFile="${build.dir}/checkstyle-results.xml"/>
          </checkstyle>
      </target>
  
      <target name="checkstyle-report"
          depends="checkstyle"
          if="do.checkstyle"
          description="Generate Checkstyle Report">
  
          <mkdir dir="${build.reports}/checkstyle"/>
          <property name="checkstyle.pathhack" location="."/>
          <style style="${tools.dir}/etc/checkstyle-frames.xsl" in="${build.dir}/checkstyle-results.xml"
              out="${build.reports}/checkstyle/delete-me.html">
              <param name="pathhack" expression="${checkstyle.pathhack}"/>
          </style>
  
      </target>
  
      <target name="xdoclet" depends="main" description="Generates the XML descriptors">
          <taskdef name="avalon-xinfo"
              classname="org.apache.excalibur.containerkit.tools.xdoclet.AvalonXDoclet">
              <classpath>
                  <path refid="project.class.path"/>
                  <pathelement location="${build.classes}"/>
              </classpath>
          </taskdef>
          <taskdef name="serialize-info"
              classname="org.apache.excalibur.containerkit.tools.ant.SerializeInfoTask">
              <classpath>
                  <path refid="project.class.path"/>
                  <pathelement location="${build.classes}"/>
              </classpath>
          </taskdef>
  
          <mkdir dir="gen"/>
          <avalon-xinfo force="true" destdir="gen" >
              <fileset dir="${java.dir}">
                  <include name="**/demo/components/*.java" />
              </fileset>
              <componentinfo/>
          </avalon-xinfo>
  
          <serialize-info destDir="gen">
              <fileset dir="gen">
                  <include name="**/*.xinfo" />
              </fileset>
          </serialize-info>
      </target>
  
      <!-- Creates the distribution -->
      <target name="dist"
          depends="dist-jar, test-reports, checkstyle-report, docs, javadocs"
          description="Generates a distribution (jar + docs + javadocs + unit tests + checkstyle reports)">
  
          <copy file="${build.conf}/LICENSE.txt" todir="${dist.dir}"/>
          <copy file="../KEYS" todir="${dist.dir}"/>
          <copy file="README.txt" todir="${dist.dir}"/>
  
          <zip zipfile="${dist.dir}/src.zip" compress="false">
              <zipfileset dir="src/java"/>
          </zip>
  
          <mkdir dir="${dist.base}"/>
  
          <zip zipfile="${dist.base}/${dist.name}.zip" compress="true">
              <zipfileset dir="${dist.dir}" prefix="${dist.name}"/>
              <zipfileset dir="${docs.dir}" prefix="${dist.name}/docs"/>
          </zip>
      </target>
  
      <!-- Creates a mini jar-only distribution -->
      <target name="dist-jar" depends="jar">
          <mkdir dir="${dist.dir}"/>
          <copy todir="${dist.dir}">
              <fileset dir="${build.lib}">
                  <include name="*.jar"/>
              </fileset>
          </copy>
      </target>
  
      <!-- Creates a minimal distribution -->
      <target name="dist.lite"
          depends="dist-jar, test, javadocs"
          description="Generates a minimal distribution (jar + javadocs)">
  
          <copy file="../LICENSE.txt" todir="${dist.dir}"/>
          <copy file="../KEYS" todir="${dist.dir}"/>
          <copy file="README.txt" todir="${dist.dir}"/>
  
      </target>
  
      <target name="anakia-avail">
          <available classname="org.apache.velocity.anakia.AnakiaTask"
              property="AnakiaTask.present">
              <classpath refid="tools.class.path"/>
          </available>
      </target>
  
      <target name="anakia-check" depends="anakia-avail" unless="AnakiaTask.present">
          <echo>
              AnakiaTask is not present! Please check to make sure that
              velocity.jar is in your classpath. The easiest way to build
              the documentation is to checkout jakarta-site CVS and specify
              jakarta-site.dir property.
          </echo>
      </target>
  
      <target name="docs" depends="anakia-check" description="Generate documentation and website">
          <taskdef name="anakia"
              classname="org.apache.velocity.anakia.AnakiaTask">
              <classpath refid="tools.class.path"/>
          </taskdef>
  
          <echo message="jakarta-site.dir=${jakarta-site.dir}"/>
  
          <anakia basedir="${xdocs.dir}"
              destdir="${docs.dir}"
              style="docs.vsl"
              projectfile="menu.xml"
              includes="**/*.xml"
              excludes="menu.xml"
              velocitypropertiesfile="../site/src/stylesheets/velocity.properties"
              />
  
       <copy todir="${docs.dir}" filtering="off">
        <fileset dir="../site/src" includes="css/*.css" />
        <fileset dir="${xdocs.dir}">
          <include name="**/images/**"/>
          <include name="**/*.gif"/>
          <include name="**/*.jpg"/>
          <include name="**/*.png"/>
          <include name="**/*.css"/>
          <include name="**/*.js"/>
        </fileset>
      </copy>
  
      <copy todir="${docs.dir}" filtering="off">
        <fileset dir="${java.dir}">
          <include name="org/apache/excalibur/policy/reader/policy.dtd"/>
        </fileset>
        <mapper type="flatten"/>
      </copy>
  
      </target>
  
      <target name="site" depends="javadocs, docs" description=" Places Docs ready for hosting on website">
  
          <mkdir dir="../site/dist/docs/${dir-name}"/>
          <copy todir="../site/dist/docs/${dir-name}">
              <fileset dir="${docs.dir}">
                  <include name="**"/>
              </fileset>
          </copy>
  
      </target>
  
      <!-- Cleans up build and distribution directories -->
      <target name="clean" description="Cleans up the project">
          <delete file="checkstyle.cache"/>
          <delete dir="${build.dir}" />
          <delete dir="${dist.dir}" />
          <delete dir="${docs.dir}" />
          <delete dir="test" /> <!-- unit testing output directory -->
          <delete>
              <fileset dir="." includes="velocity.*"/>
              <fileset dir="." includes="**/*~" defaultexcludes="no"/>
          </delete>
      </target>
  
      <target name="real-clean" depends="clean" description="Cleans up the project, including distributions">
          <delete dir="${dist.base}" />
      </target>
  
  </project>
  
  
  
  1.1                  jakarta-avalon-excalibur/policy/default.properties
  
  Index: default.properties
  ===================================================================
  # -------------------------------------------------------------------
  # B U I L D  P R O P E R T I E S
  # -------------------------------------------------------------------
  # Specifies default property values
  # Overridden by ../default.properties and all ant.properties
  # Not user-editable; use ant.properties files instead
  
  name=excalibur-policy
  Name=Excalibur Policy
  dir-name=policy
  version=1.0a
  package-version=0.99
  year=2002
  
  # --------------------------------------------------
  #                REQUIRED LIBRARIES
  # --------------------------------------------------
  
  # ----- Avalon Framework, version 4.1 or later -----
  avalon-framework.home=${basedir}/../../jakarta-avalon
  avalon-framework.lib=${avalon-framework.home}/build/lib
  avalon-framework.jar=${avalon-framework.lib}/avalon-framework.jar
  
  # ----- Excalibur i18n, version 1.0 or later -----
  excalibur-i18n.home=${basedir}/../i18n/dist
  excalibur-i18n.lib=${excalibur-i18n.home}
  excalibur-i18n.jar=${excalibur-i18n.lib}/excalibur-i18n-1.0.jar
  
  # --------------------------------------------------
  
  #  Settings used to configure compile environment
  build.debug = on
  build.optimize = off
  build.deprecation = off
  build.compress = false
  junit.failonerror = false
  
  #  location of intermediate products
  build.dir = build
  build.testsrc = ${build.dir}/testsrc
  build.testclasses = ${build.dir}/testclasses
  build.lib = ${build.dir}/lib
  build.conf = ${build.dir}/conf
  build.classes = ${build.dir}/classes
  build.tests = ${build.dir}/tests
  build.reports = ${build.dir}/reports
  
  #  Set the properties for source directories
  src.dir = src
  java.dir = ${src.dir}/java
  conf.dir = ${src.dir}/conf
  test.dir = ${src.dir}/test
  
  #  needed by Cocoon
  build.context = ${build.dir}/documentation
  build.docs = ${build.dir}/docs
  build.xdocs = ${build.dir}/xdocs
  context.dir = ../../jakarta-avalon/src/documentation
  tools.dir = ../../jakarta-avalon/tools
  tools.jar = ${java.home}/../lib/tools.jar
  docs.dir = docs
  xdocs.dir = src/xdocs
  
  #  Set the properties for distribution directories
  dist.dir = dist
  dist.javadocs = ${docs.dir}/api
  
  #  name of .zip/.tar.gz/.bz2 files and their top-level directory
  dist.name = ${name}-${version}
  
  #  name of jar file
  jar.name = ${name}-${version}.jar
  
  #  property indicating directory where all distribution archives are placed
  dist.base = distributions
  
  depchecker.prefix=.
  
  
  
  
  1.1                  jakarta-avalon-excalibur/policy/src/java/org/apache/excalibur/policy/builder/PolicyBuilder.java
  
  Index: PolicyBuilder.java
  ===================================================================
  /*
   * Copyright (C) The Apache Software Foundation. All rights reserved.
   *
   * This software is published under the terms of the Apache Software License
   * version 1.1, a copy of which has been included with this distribution in
   * the LICENSE.txt file.
   */
  package org.apache.excalibur.policy.builder;
  
  import java.io.InputStream;
  import java.lang.reflect.Constructor;
  import java.net.MalformedURLException;
  import java.net.URL;
  import java.security.CodeSource;
  import java.security.KeyStore;
  import java.security.KeyStoreException;
  import java.security.Permission;
  import java.security.Policy;
  import java.security.UnresolvedPermission;
  import java.security.cert.Certificate;
  import java.util.ArrayList;
  import java.util.HashMap;
  import java.util.List;
  import java.util.Map;
  import java.util.PropertyPermission;
  import java.util.StringTokenizer;
  import org.apache.excalibur.policy.metadata.GrantMetaData;
  import org.apache.excalibur.policy.metadata.KeyStoreMetaData;
  import org.apache.excalibur.policy.metadata.PermissionMetaData;
  import org.apache.excalibur.policy.metadata.PolicyMetaData;
  
  /**
   * A Utility class that builds a Policy object from a specified
   * PolicyMetaData.
   *
   * @author <a href="mailto:peter at apache.org">Peter Donald</a>
   * @version $Revision: 1.1 $ $Date: 2002/09/25 12:37:43 $
   */
  public class PolicyBuilder
  {
      /**
       * Build a policy for a specified meta data.
       *
       * @param policy the policy metadata
       * @return the Policy object
       * @throws Exception if unable to create Policy object
       */
      public Policy buildPolicy( final PolicyMetaData policy,
                                 final PolicyResolver resolver )
          throws Exception
      {
          final Map keyStores =
              createKeyStores( policy.getKeyStores(), resolver );
          final Map grants = new HashMap();
          processGrants( policy.getGrants(), keyStores, grants, resolver );
  
          final CodeSource codeSource = createDefaultCodeSource();
          final Permission[] permissions = getDefaultPermissions();
          grants.put( codeSource, permissions );
  
          return resolver.createPolicy( grants );
      }
  
      /**
       * Porcess all the grants and build up a grant map.
       *
       * @param metaDatas the metadata
       * @param keyStores the configured keystores
       * @param grants the grant map
       * @param resolver the resolver to use to resolve locations etc
       * @throws Exception if unable to create grant map
       */
      private void processGrants( final GrantMetaData[] metaDatas,
                                  final Map keyStores,
                                  final Map grants,
                                  final PolicyResolver resolver )
          throws Exception
      {
          for( int i = 0; i < metaDatas.length; i++ )
          {
              processGrant( metaDatas[ i ], keyStores, grants, resolver );
          }
      }
  
      /**
       * Porcess a grants and add to the grant map.
       *
       * @param metaData the metadata
       * @param keyStores the configured keystores
       * @param grants the grant map
       * @param resolver the resolver to use to resolve locations etc
       * @throws Exception if unable to create grant map
       */
      private void processGrant( final GrantMetaData metaData,
                                 final Map keyStores,
                                 final Map grants,
                                 final PolicyResolver resolver )
          throws Exception
      {
          final URL url =
              resolver.resolveLocation( metaData.getCodebase() );
  
          final Certificate[] signers =
              getSigners( metaData.getSignedBy(),
                          metaData.getKeyStore(),
                          keyStores );
          final CodeSource codeSource = new CodeSource( url, signers );
  
          final Permission[] permissions =
              createPermissions( metaData.getPermissions(),
                                 keyStores,
                                 resolver );
          grants.put( codeSource, permissions );
      }
  
      /**
       * Create all permissions for specified metadata.
       *
       * @param metaDatas the metadata
       * @param keyStores the keystores to use when loading signers
       * @param resolver the resolver to use to resolve targets
       * @return the created permissions
       * @throws Exception if unabel to create permissions
       */
      private Permission[] createPermissions( final PermissionMetaData[] metaDatas,
                                              final Map keyStores,
                                              final PolicyResolver resolver )
          throws Exception
      {
          final List set = new ArrayList();
  
          for( int i = 0; i < metaDatas.length; i++ )
          {
              final Permission permission =
                  createPermission( metaDatas[ i ], keyStores, resolver );
              set.add( permission );
          }
  
          return (Permission[]) set.toArray( new Permission[ set.size() ] );
      }
  
      /**
       * Create a permission for metadata.
       *
       * @param metaData the permission metadata
       * @param keyStores the keystore to use (if needed)
       * @param resolver the resovler to use when resolving target
       * @return the created permission
       * @throws Exception if unable to create permission
       */
      private Permission createPermission( final PermissionMetaData metaData,
                                           final Map keyStores,
                                           final PolicyResolver resolver )
          throws Exception
      {
          final String type = metaData.getClassname();
          final String actions = metaData.getAction();
          final String signedBy = metaData.getSignedBy();
          final String keyStoreName = metaData.getKeyStore();
  
          String target = metaData.getTarget();
          if( null != target )
          {
              target = resolver.resolveTarget( target );
          }
  
          final Certificate[] signers =
              getSigners( signedBy, keyStoreName, keyStores );
          try
          {
              return createPermission( type, target, actions, signers );
          }
          catch( final Exception e )
          {
              throw new Exception( e.getMessage() );
          }
      }
  
      /**
       * Create a mpa of keystores from specified metadata.
       *
       * @param metaDatas the metadata
       * @return the keystore map
       * @throws Exception if unable to create all keystores
       */
      private Map createKeyStores( final KeyStoreMetaData[] metaDatas,
                                   final PolicyResolver resolver )
          throws Exception
      {
          final Map keyStores = new HashMap();
  
          for( int i = 0; i < metaDatas.length; i++ )
          {
              final KeyStoreMetaData metaData = metaDatas[ i ];
              final String name = metaData.getName();
  
              try
              {
                  final URL url =
                      resolver.resolveLocation( metaData.getLocation() );
                  final KeyStore keyStore =
                      createKeyStore( metaData.getType(), url );
  
                  keyStores.put( name, keyStore );
              }
              catch( final Exception e )
              {
                  final String message =
                      "Error creating keystore " + name + ". Due to " + e;
                  throw new Exception( message );
              }
          }
  
          return keyStores;
      }
  
      /**
       * Create a permission of specified class and
       * with specified target, action and signers.
       *
       * @param type the classname of Permission object
       * @param target the target of permission
       * @param actions the actions allowed on permission (if any)
       * @param signers the signers (if any)
       * @return the created Permission object
       * @throws Exception if unable to create permission
       */
      private final Permission createPermission( final String type,
                                                 final String target,
                                                 final String actions,
                                                 final Certificate[] signers )
          throws Exception
      {
          if( null != signers )
          {
              return new UnresolvedPermission( type, target, actions, signers );
          }
  
          try
          {
              final Class clazz = Class.forName( type );
  
              Class paramClasses[] = null;
              Object params[] = null;
  
              if( null == actions && null == target )
              {
                  paramClasses = new Class[ 0 ];
                  params = new Object[ 0 ];
              }
              else if( null == actions )
              {
                  paramClasses = new Class[ 1 ];
                  paramClasses[ 0 ] = String.class;
                  params = new Object[ 1 ];
                  params[ 0 ] = target;
              }
              else
              {
                  paramClasses = new Class[ 2 ];
                  paramClasses[ 0 ] = String.class;
                  paramClasses[ 1 ] = String.class;
                  params = new Object[ 2 ];
                  params[ 0 ] = target;
                  params[ 1 ] = actions;
              }
  
              final Constructor constructor = clazz.getConstructor( paramClasses );
              return (Permission) constructor.newInstance( params );
          }
          catch( final ClassNotFoundException cnfe )
          {
              return new UnresolvedPermission( type, target, actions, signers );
          }
      }
  
      /**
       * A utility method to get a default codesource
       * that covers all files on fielsystem
       *
       * @return the code source
       */
      private CodeSource createDefaultCodeSource()
      {
          //Create a URL that covers whole file system.
          final URL url;
          try
          {
              url = new URL( "file:/-" );
          }
          catch( final MalformedURLException mue )
          {
              //will never happen
              throw new IllegalStateException( mue.getMessage() );
          }
          final CodeSource codeSource = new CodeSource( url, null );
          return codeSource;
      }
  
      /**
       * A utility method to get all the default permissions.
       */
      private Permission[] getDefaultPermissions()
      {
          final ArrayList list = new ArrayList();
          //these properties straight out ot ${java.home}/lib/security/java.policy
          list.add( new PropertyPermission( "os.name", "read" ) );
          list.add( new PropertyPermission( "os.arch", "read" ) );
          list.add( new PropertyPermission( "os.version", "read" ) );
          list.add( new PropertyPermission( "file.separator", "read" ) );
          list.add( new PropertyPermission( "path.separator", "read" ) );
          list.add( new PropertyPermission( "line.separator", "read" ) );
  
          list.add( new PropertyPermission( "java.version", "read" ) );
          list.add( new PropertyPermission( "java.vendor", "read" ) );
          list.add( new PropertyPermission( "java.vendor.url", "read" ) );
  
          list.add( new PropertyPermission( "java.class.version", "read" ) );
          list.add( new PropertyPermission( "java.vm.version", "read" ) );
          list.add( new PropertyPermission( "java.vm.vendor", "read" ) );
          list.add( new PropertyPermission( "java.vm.name", "read" ) );
  
          list.add( new PropertyPermission( "java.specification.version", "read" ) );
          list.add( new PropertyPermission( "java.specification.vendor", "read" ) );
          list.add( new PropertyPermission( "java.specification.name", "read" ) );
          list.add( new PropertyPermission( "java.vm.specification.version", "read" ) );
          list.add( new PropertyPermission( "java.vm.specification.vendor", "read" ) );
          list.add( new PropertyPermission( "java.vm.specification.name", "read" ) );
  
          return (Permission[]) list.toArray( new Permission[ list.size() ] );
      }
  
      /**
       * Create a keystore of specified type and loading from specified url.
       *
       * @param type the type of key store
       * @param url the location of key store data
       * @return the create and configured keystore
       * @throws Exception if unable to create or load keystore
       */
      private final KeyStore createKeyStore( final String type,
                                            final URL url )
          throws Exception
      {
          final KeyStore keyStore = KeyStore.getInstance( type );
          final InputStream ins = url.openStream();
          keyStore.load( ins, null );
          return keyStore;
      }
  
      /**
       * Retrieve Certificates for specified signers
       * as loaded from keyStore.
       *
       * @param signedBy the signers
       * @param keyStoreName the name of keystore
       * @param keyStores the list of keystores to lookup
       * @return the certificates
       * @throws Exception if unable to get signers
       */
      private Certificate[] getSigners( final String signedBy,
                                        final String keyStoreName,
                                        final Map keyStores )
          throws Exception
      {
          if( null == signedBy )
          {
              return null;
          }
          else
          {
              final KeyStore keyStore = getKeyStore( keyStoreName, keyStores );
              return getCertificates( signedBy, keyStore );
          }
      }
  
      /**
       * Retrieve the set of Ceritificates for all signers.
       *
       * @param signedBy the comma separated list of signers
       * @param keyStore the keystore to look for signers certificates in
       * @return the certificate set
       * @throws Exception if unabel to create certificates
       */
      private Certificate[] getCertificates( final String signedBy,
                                             final KeyStore keyStore )
          throws Exception
      {
          final List certificateSet = new ArrayList();
  
          final StringTokenizer st = new StringTokenizer( signedBy, "," );
          while( st.hasMoreTokens() )
          {
              final String alias = st.nextToken().trim();
              Certificate certificate = null;
  
              try
              {
                  certificate = keyStore.getCertificate( alias );
              }
              catch( final KeyStoreException kse )
              {
                  final String message =
                      "Unable to get certificate for alias " +
                      alias + " due to " + kse;
                  throw new Exception( message );
              }
  
              if( null == certificate )
              {
                  final String message =
                      "Missing certificate for alias " + alias;
                  throw new Exception( message );
              }
  
              if( !certificateSet.contains( certificate ) )
              {
                  certificateSet.add( certificate );
              }
          }
  
          return (Certificate[]) certificateSet.toArray( new Certificate[ certificateSet.size() ] );
      }
  
      /**
       * Retrieve keystore with specified name from map.
       * If missing throw an exception.
       *
       * @param keyStoreName the name of key store
       * @param keyStores the map of stores
       * @return the keystore
       * @throws Exception thrown if unable to locate keystore
       */
      private KeyStore getKeyStore( final String keyStoreName, final Map keyStores ) throws Exception
      {
          final KeyStore keyStore = (KeyStore) keyStores.get( keyStoreName );
          if( null == keyStore )
          {
              final String message = "Missing keystore named: " + keyStoreName;
              throw new Exception( message );
          }
          else
          {
              return keyStore;
          }
      }
  }
  
  
  
  1.1                  jakarta-avalon-excalibur/policy/src/java/org/apache/excalibur/policy/builder/PolicyResolver.java
  
  Index: PolicyResolver.java
  ===================================================================
  /*
   * Copyright (C) The Apache Software Foundation. All rights reserved.
   *
   * This software is published under the terms of the Apache Software License
   * version 1.1, a copy of which has been included with this distribution in
   * the LICENSE.txt file.
   */
  package org.apache.excalibur.policy.builder;
  
  import java.net.URL;
  import java.security.Policy;
  import java.util.Map;
  
  /**
   * This is the interface via which elements of Policy are resolved.
   * For example it is possible for the Policy file to use abstract URLs
   * such as "sar:/SAR-INF/lib/" which need to be mapped to a concrete
   * URL. It is also necessary for the target values of permissions
   * to be "resolved" using a pseuedo expression language.
   *
   * @author <a href="mailto:peter at apache.org">Peter Donald</a>
   * @version $Revision: 1.1 $ $Date: 2002/09/25 12:37:43 $
   */
  public interface PolicyResolver
  {
      /**
       * Resolve a location to a URL.
       *
       * @param location the location
       * @return the URL
       * @throws Exception if unable to resolve URL
       */
      URL resolveLocation( String location )
          throws Exception;
  
      /**
       * Expand a target string to correct value.
       *
       * @param target the target
       * @return the expanded value
       */
      String resolveTarget( String target );
  
      /**
       * Create a Policy object from a grant map.
       *
       * @param grants the grants map
       * @return the Policy object
       */
      Policy createPolicy( Map grants )
          throws Exception;
  }
  
  
  
  1.1                  jakarta-avalon-excalibur/policy/src/java/org/apache/excalibur/policy/metadata/GrantMetaData.java
  
  Index: GrantMetaData.java
  ===================================================================
  /*
   * Copyright (C) The Apache Software Foundation. All rights reserved.
   *
   * This software is published under the terms of the Apache Software License
   * version 1.1, a copy of which has been included with this distribution in
   * the LICENSE.txt file.
   */
  package org.apache.excalibur.policy.metadata;
  
  /**
   * This class defines a keystore that is used when locating
   * signers of a codebase.
   *
   * @author <a href="mailto:peter at apache.org">Peter Donald</a>
   * @version $Revision: 1.1 $ $Date: 2002/09/25 12:37:43 $
   */
  public class GrantMetaData
  {
      /**
       * The codebase that grant applies to.
       */
      private final String m_codebase;
  
      /**
       * The signer of codebase. May be null but if null then
       * keyStore must also be null.
       */
      private final String m_signedBy;
  
      /**
       * The keyStore to load signer from. May be null but if
       * null then signedBy must also be null.
       */
      private final String m_keyStore;
  
      /**
       * The set of permissions to grant codebase.
       */
      private final PermissionMetaData[] m_permissions;
  
      /**
       * Construct a grant.
       *
       * @param codebase the codebase grant is about
       * @param signedBy who signed the codebase
       * @param keyStore the name of the keystore the signer is loaded from
       * @param permissions the set of permissions associated with grant
       */
      public GrantMetaData( final String codebase,
                            final String signedBy,
                            final String keyStore,
                            final PermissionMetaData[] permissions )
      {
          if( null == codebase )
          {
              throw new NullPointerException( "codebase" );
          }
          if( null == permissions )
          {
              throw new NullPointerException( "permissions" );
          }
          if( null == signedBy && null != keyStore )
          {
              throw new NullPointerException( "signedBy" );
          }
          if( null == keyStore && null != signedBy )
          {
              throw new NullPointerException( "keyStore" );
          }
  
          m_codebase = codebase;
          m_signedBy = signedBy;
          m_keyStore = keyStore;
          m_permissions = permissions;
      }
  
      /**
       * Return the code base for grant.
       *
       * @return the code base for grant.
       */
      public String getCodebase()
      {
          return m_codebase;
      }
  
      /**
       * Return the signer for grant.
       *
       * @return the signer for grant.
       */
      public String getSignedBy()
      {
          return m_signedBy;
      }
  
      /**
       * Return the key store to load signer from.
       *
       * @return the key store to load signer from.
       */
      public String getKeyStore()
      {
          return m_keyStore;
      }
  
      /**
       * Return the set of permissions associated with grant.
       *
       * @return the set of permissions associated with grant.
       */
      public PermissionMetaData[] getPermissions()
      {
          return m_permissions;
      }
  }
  
  
  
  1.1                  jakarta-avalon-excalibur/policy/src/java/org/apache/excalibur/policy/metadata/KeyStoreMetaData.java
  
  Index: KeyStoreMetaData.java
  ===================================================================
  /*
   * Copyright (C) The Apache Software Foundation. All rights reserved.
   *
   * This software is published under the terms of the Apache Software License
   * version 1.1, a copy of which has been included with this distribution in
   * the LICENSE.txt file.
   */
  package org.apache.excalibur.policy.metadata;
  
  /**
   * This class defines a keystore that is used when locating
   * signers of a codebase.
   *
   * @author <a href="mailto:peter at apache.org">Peter Donald</a>
   * @version $Revision: 1.1 $ $Date: 2002/09/25 12:37:43 $
   */
  public class KeyStoreMetaData
  {
      /**
       * The name of the keystore. Used by Grants to
       * refer to particular key stores.
       */
      private final String m_name;
  
      /**
       * The location of the keystore (usually a URL).
       */
      private final String m_location;
  
      /**
       * The type of the keystore.
       */
      private final String m_type;
  
      /**
       * Construct a keysotre.
       *
       * @param name the name of the key store
       * @param location the location of keystore
       * @param type the keystore type
       */
      public KeyStoreMetaData( final String name,
                               final String location,
                               final String type )
      {
          if( null == name )
          {
              throw new NullPointerException( "name" );
          }
          if( null == location )
          {
              throw new NullPointerException( "location" );
          }
          if( null == type )
          {
              throw new NullPointerException( "type" );
          }
  
          m_name = name;
          m_location = location;
          m_type = type;
      }
  
      /**
       * Return the name of keystore.
       *
       * @return the name of keystore.
       */
      public String getName()
      {
          return m_name;
      }
  
      /**
       * Return the location of the KeyStore (usually a URL).
       *
       * @return the location of the KeyStore (usually a URL).
       */
      public String getLocation()
      {
          return m_location;
      }
  
      /**
       * Return the type of the key store (ie JKS).
       *
       * @return the type of the key store (ie JKS).
       */
      public String getType()
      {
          return m_type;
      }
  }
  
  
  
  1.1                  jakarta-avalon-excalibur/policy/src/java/org/apache/excalibur/policy/metadata/PermissionMetaData.java
  
  Index: PermissionMetaData.java
  ===================================================================
  /*
   * Copyright (C) The Apache Software Foundation. All rights reserved.
   *
   * This software is published under the terms of the Apache Software License
   * version 1.1, a copy of which has been included with this distribution in
   * the LICENSE.txt file.
   */
  package org.apache.excalibur.policy.metadata;
  
  /**
   * This class defines a keystore that is used when locating
   * signers of a codebase.
   *
   * @author <a href="mailto:peter at apache.org">Peter Donald</a>
   * @version $Revision: 1.1 $ $Date: 2002/09/25 12:37:43 $
   */
  public class PermissionMetaData
  {
      /**
       * The class name of permission.
       */
      private final String m_classname;
  
      /**
       * The target of permission. The interpretation of this is
       * determined by underlying permission classname.
       */
      private final String m_target;
  
      /**
       * The action(s) associated with permission.
       * The interpretation of this field is relative to
       * the permission and target.
       */
      private final String m_action;
  
      /**
       * The signer of the permission.
       * (ie who signed the permission class).
       */
      private final String m_signedBy;
  
      /**
       * The keyStore to load signer from. May be null but if
       * null then signedBy must also be null.
       */
      private final String m_keyStore;
  
      /**
       * Construct the permission meta data.
       *
       * @param classname the name of permission class
       * @param target the target of permission (may be null)
       * @param action the action of permission (may be null)
       */
      public PermissionMetaData( final String classname,
                                 final String target,
                                 final String action,
                                 final String signedBy,
                                 final String keyStore )
      {
          if( null == classname )
          {
              throw new NullPointerException( "classname" );
          }
  
          m_classname = classname;
          m_target = target;
          m_action = action;
          m_signedBy = signedBy;
          m_keyStore = keyStore;
      }
  
      /**
       * Return the name of permission class.
       *
       * @return the name of permission class.
       */
      public String getClassname()
      {
          return m_classname;
      }
  
      /**
       * Return the action of permission (may be null).
       *
       * @return the action of permission (may be null).
       */
      public String getTarget()
      {
          return m_target;
      }
  
      /**
       * Return the action of permission (may be null).
       *
       * @return the action of permission (may be null)
       */
      public String getAction()
      {
          return m_action;
      }
  
      /**
       * Return the principle name who signed the permission.
       *
       * @return the the principle name who signed the permission.
       */
      public String getSignedBy()
      {
          return m_signedBy;
      }
  
      /**
       * Return the key store to load signer from.
       *
       * @return the key store to load signer from.
       */
      public String getKeyStore()
      {
          return m_keyStore;
      }
  }
  
  
  
  1.1                  jakarta-avalon-excalibur/policy/src/java/org/apache/excalibur/policy/metadata/PolicyMetaData.java
  
  Index: PolicyMetaData.java
  ===================================================================
  /*
   * Copyright (C) The Apache Software Foundation. All rights reserved.
   *
   * This software is published under the terms of the Apache Software License
   * version 1.1, a copy of which has been included with this distribution in
   * the LICENSE.txt file.
   */
  package org.apache.excalibur.policy.metadata;
  
  /**
   * This class defines the set of KeyStores and Grants
   * in a policy declaration.
   *
   * @author <a href="mailto:peter at apache.org">Peter Donald</a>
   * @version $Revision: 1.1 $ $Date: 2002/09/25 12:37:43 $
   */
  public class PolicyMetaData
  {
      /**
       * The KeyStores associated with policy.
       */
      private final KeyStoreMetaData[] m_keyStores;
  
      /**
       * The grants that make up the policy.
       */
      private final GrantMetaData[] m_grants;
  
      /**
       * Create a policy with specific keystores and grants.
       *
       * @param keyStores the key stores
       * @param grants the grants
       */
      public PolicyMetaData( final KeyStoreMetaData[] keyStores,
                             final GrantMetaData[] grants )
      {
          m_keyStores = keyStores;
          m_grants = grants;
      }
  
      /**
       * Return the KeyStores associated with policy.
       *
       * @return the KeyStores associated with policy.
       */
      public KeyStoreMetaData[] getKeyStores()
      {
          return m_keyStores;
      }
  
      /**
       * Return the grants that make up policy.
       *
       * @return the grants that make up policy.
       */
      public GrantMetaData[] getGrants()
      {
          return m_grants;
      }
  }
  
  
  
  1.1                  jakarta-avalon-excalibur/policy/src/java/org/apache/excalibur/policy/reader/PolicyReader.java
  
  Index: PolicyReader.java
  ===================================================================
  /*
   * Copyright (C) The Apache Software Foundation. All rights reserved.
   *
   * This software is published under the terms of the Apache Software License
   * version 1.1, a copy of which has been included with this distribution in
   * the LICENSE.txt file.
   */
  package org.apache.excalibur.policy.reader;
  
  import java.util.ArrayList;
  import org.apache.excalibur.policy.metadata.GrantMetaData;
  import org.apache.excalibur.policy.metadata.KeyStoreMetaData;
  import org.apache.excalibur.policy.metadata.PolicyMetaData;
  import org.apache.excalibur.policy.metadata.PermissionMetaData;
  import org.w3c.dom.Element;
  import org.w3c.dom.NodeList;
  
  /**
   * This class builds a {@link PolicyMetaData} object from
   * specified XML document.
   *
   * @author <a href="mailto:peter at apache.org">Peter Donald</a>
   * @version $Revision: 1.1 $ $Date: 2002/09/25 12:37:43 $
   */
  public class PolicyReader
  {
      /**
       * Build ClassLoader MetaData from a DOM tree.
       *
       * @param element the root element
       * @return the meta data
       * @throws Exception if malformed DOM
       */
      public PolicyMetaData readPolicy( final Element element )
          throws Exception
      {
          final String version = element.getAttribute( "version" );
          if( !"1.0".equals( version ) )
          {
              final String message = "Bad version:" + version;
              throw new Exception( message );
          }
  
          final NodeList keyStoreConfigs = element.getElementsByTagName( "keystore" );
          final KeyStoreMetaData[] keyStores = buildKeyStores( keyStoreConfigs );
  
          final NodeList grantConfigs =
              element.getElementsByTagName( "grant" );
          final GrantMetaData[] grants = buildGrants( grantConfigs );
  
          return new PolicyMetaData( keyStores, grants );
      }
  
      /**
       * Build an array of GrantMetaDatas from node list.
       *
       * @param elements the nodes to process
       * @return the GrantMetaData
       */
      private GrantMetaData[] buildGrants( final NodeList elements )
          throws Exception
      {
          final ArrayList grants = new ArrayList();
          final int length = elements.getLength();
  
          for( int i = 0; i < length; i++ )
          {
              final Element element = (Element) elements.item( i );
              final GrantMetaData grant = buildGrant( element );
              grants.add( grant );
          }
  
          return (GrantMetaData[]) grants.toArray( new GrantMetaData[ grants.size() ] );
      }
  
      /**
       * Build a GrantMetaData from an element.
       *
       * @param element the nodes to process
       * @return the GrantMetaData
       */
      private GrantMetaData buildGrant( final Element element )
          throws Exception
      {
          final String codeBase = getAttribute( element, "code-base" );
          final String signedBy = getAttribute( element, "signed-by" );
          String keyStore = getAttribute( element, "key-store" );
          if( null != signedBy && null == keyStore )
          {
              keyStore = "default";
          }
          final NodeList permissionElements =
              element.getElementsByTagName( "permission" );
          final PermissionMetaData[] permissions = buildPermissions( permissionElements );
          return new GrantMetaData( codeBase, signedBy, keyStore, permissions );
      }
  
      /**
       * Build an array of PermissionMetaDatas from node list.
       *
       * @param elements the nodes to process
       * @return the PermissionMetaDatas
       */
      private PermissionMetaData[] buildPermissions( final NodeList elements )
          throws Exception
      {
          final ArrayList grants = new ArrayList();
          final int length = elements.getLength();
  
          for( int i = 0; i < length; i++ )
          {
              final Element element = (Element) elements.item( i );
              final PermissionMetaData permission = buildPermission( element );
              grants.add( permission );
          }
  
          return (PermissionMetaData[]) grants.toArray( new PermissionMetaData[ grants.size() ] );
      }
  
      /**
       * Build a PermissionMetaData from an element.
       *
       * @param element the node to process
       * @return the PermissionMetaData
       */
      private PermissionMetaData buildPermission( final Element element )
          throws Exception
      {
          final String classname = getAttribute( element, "class" );
          final String target = getAttribute( element, "target" );
          final String action = getAttribute( element, "action" );
          final String signedBy = getAttribute( element, "signed-by" );
          String keyStore = getAttribute( element, "key-store" );
          if( null != signedBy && null == keyStore )
          {
              keyStore = "default";
          }
          return new PermissionMetaData( classname, target, action,
                                         signedBy, keyStore );
      }
  
      /**
       * Build an array of KeyStore meta datas from node list.
       *
       * @param elements the nodes to process
       * @return the keyStores
       */
      private KeyStoreMetaData[] buildKeyStores( final NodeList elements )
          throws Exception
      {
          final ArrayList keyStores = new ArrayList();
          final int length = elements.getLength();
  
          for( int i = 0; i < length; i++ )
          {
              final Element element = (Element) elements.item( i );
              final KeyStoreMetaData keyStore = buildKeyStore( element );
              keyStores.add( keyStore );
          }
  
          return (KeyStoreMetaData[]) keyStores.toArray( new KeyStoreMetaData[ keyStores.size() ] );
      }
  
      /**
       * Build a KeyStoreMetaData from an element.
       *
       * @param element the nodes to process
       * @return the keyStore
       */
      private KeyStoreMetaData buildKeyStore( final Element element )
          throws Exception
      {
          final String name = getAttribute( element, "name" );
          final String location = getAttribute( element, "location" );
          final String type = getAttribute( element, "type" );
          return new KeyStoreMetaData( name, location, type );
      }
  
      /**
       * Utility method to get value of attribute. If attribute
       * has a empty/null value or does not appear in XML then return
       * null, elese return value.
       *
       * @param element the element
       * @param name the attribute name
       * @return the cleaned attribute value
       */
      private String getAttribute( final Element element,
                                   final String name )
      {
          final String value = element.getAttribute( name );
          if( "".equals( value ) )
          {
              return null;
          }
          else
          {
              return value;
          }
      }
  }
  
  
  
  1.1                  jakarta-avalon-excalibur/policy/src/java/org/apache/excalibur/policy/reader/policy.dtd
  
  Index: policy.dtd
  ===================================================================
  <!--
  
     This is the DTD defining the Policy 1.0
     descriptor (XML) file format/syntax.
  
     Author: Peter Donald <peter at apache.org>
  
     This descriptor is used to define information in a java.policy
     excep in the XML file format.
  
     Copyright (C) The Apache Software Foundation. All rights reserved.
  
     This software is published under the terms of the Apache Software License
     version 1.1, a copy of which has been included  with this distribution in
     the LICENSE.txt file.
  
  -->
  
  <!--
  The policy is the document root and contians the other elements:
  -->
  <!ELEMENT policy (keystore*,grant*)>
    <!ATTLIST policy
            version CDATA #REQUIRED
            xmlns CDATA #FIXED "http://jakarta.apache.org/avalon/dtds/phoenix/policy_1_0.dtd" >
  
  <!--
  The keystore element describes a particular keystore. It defines:
  
  Attributes:
  name	        the name of keystore. Must be a string
               containing alphanumeric characters, '.', '-', '_' and
               starting with a letter or a '_'.
  location     the location of the keystore
  type         the keystore type
  -->
  <!ELEMENT policy EMPTY>
    <!ATTLIST policy
         name CDATA #REQUIRED
         location CDATA #REQUIRED
         type CDATA #REQUIRED >
  
  <!--
  The grant defines a set of permisisons allowed for
  a particular codebase. It defines:
  
  Attributes:
  name	        the code-base URL
  signed-by    who needs to have signed code at codebase for grant to apply (optional)
  key-store    where to load signature from (optional)
  
  Elements:
  permission  the permissions to grant
  -->
  <!ELEMENT grant          (permission*)>
    <!ATTLIST grant
         code-base CDATA #REQUIRED
         signed-by CDATA #IMPLIED
         key-store CDATA #IMPLIED >
  
  <!--
  The permission element defines a permission for a codebase.
  -->
  <!ELEMENT permission EMPTY>
    <!ATTLIST permission
         class CDATA #REQUIRED
         target CDATA #IMPLIED
         action CDATA #IMPLIED
         signed-by CDATA #IMPLIED
         key-store CDATA #IMPLIED >
  
  
  
  1.1                  jakarta-avalon-excalibur/policy/src/java/org/apache/excalibur/policy/runtime/AbstractPolicy.java
  
  Index: AbstractPolicy.java
  ===================================================================
  /*
   * Copyright (C) The Apache Software Foundation. All rights reserved.
   *
   * This software is published under the terms of the Apache Software License
   * version 1.1, a copy of which has been included with this distribution in
   * the LICENSE.txt file.
   */
  package org.apache.excalibur.policy.runtime;
  
  import java.io.File;
  import java.net.MalformedURLException;
  import java.net.URL;
  import java.security.CodeSource;
  import java.security.Permission;
  import java.security.PermissionCollection;
  import java.security.Permissions;
  import java.security.Policy;
  import java.util.ArrayList;
  import java.util.Enumeration;
  
  /**
   * Abstract Policy class that makes it easy to add permission
   * sets to policy.
   *
   * @author <a href="mailto:peter at apache.org">Peter Donald</a>
   */
  public abstract class AbstractPolicy
      extends Policy
  {
      private final ArrayList m_entries = new ArrayList();
  
      /**
       * Overide so we can have a per-application security policy with
       * no side-effects to other applications.
       *
       * @param codeSource the CodeSource to get permissions for
       * @return the PermissionCollection
       */
      public PermissionCollection getPermissions( final CodeSource codeSource )
      {
          final CodeSource target = normalize( codeSource );
  
          final Permissions permissions = new Permissions();
          final int size = m_entries.size();
  
          for( int i = 0; i < size; i++ )
          {
              final PolicyEntry entry = (PolicyEntry)m_entries.get( i );
              if( entry.getCodeSource().implies( target ) )
              {
                  copyPermissions( permissions, entry.getPermissions() );
              }
          }
  
          return permissions;
      }
  
      /**
       * Refresh policy. Ignored in this implementation.
       */
      public void refresh()
      {
      }
  
      /**
       * Create a set of permissions for a particular codesource.
       * These are read-write permissions and can be written till until the
       * time in which they are applied to code.
       *
       * @param codeSource the code source
       * @return the permission set
       */
      protected Permissions createPermissionSetFor( final CodeSource codeSource )
      {
          final CodeSource target = normalize( codeSource );
          final PolicyEntry entry =
              new PolicyEntry( target, new Permissions() );
          m_entries.add( entry );
          return entry.getPermissions();
      }
  
      /**
       * Normalizing CodeSource involves removing relative addressing
       * (like .. and .) for file urls.
       *
       * @param codeSource the codeSource to be normalized
       * @return the normalized codeSource
       */
      private CodeSource normalize( final CodeSource codeSource )
      {
          final URL initialLocation = codeSource.getLocation();
  
          // This is a bit of a h ack.  I don't know why CodeSource should behave like this
          // Fear not, this only seems to be a problem for home grown classloaders.
          // - Paul Hammant, Nov 2000
          if( null == initialLocation )
          {
              return codeSource;
          }
  
          String location = null;
  
          if( !initialLocation.getProtocol().equalsIgnoreCase( "file" ) )
          {
              location = initialLocation.getFile();
              location = normalize( location );
          }
          else
          {
              final File file = new File( initialLocation.getFile() );
              location = file.getAbsoluteFile().toString().replace( File.separatorChar, '/' );
              location = normalize( location );
          }
  
          URL finalLocation = null;
          try
          {
              finalLocation = new URL( initialLocation.getProtocol(),
                                       initialLocation.getHost(),
                                       initialLocation.getPort(),
                                       location );
          }
          catch( final MalformedURLException mue )
          {
              error( "Error building codeBase", mue );
          }
  
          return new CodeSource( finalLocation, codeSource.getCertificates() );
      }
  
      /**
       * Utility method to cpoy permissions from specified source to specified destination.
       *
       * @param destination the destination of permissions
       * @param source the source of permissions
       */
      private void copyPermissions( final Permissions destination,
                                    final Permissions source )
      {
          final Enumeration enum = source.elements();
          while( enum.hasMoreElements() )
          {
              destination.add( (Permission)enum.nextElement() );
          }
      }
  
      /**
       * Error occured in policy. Subclasses should overide.
       */
      protected void error( final String message,
                            final Throwable throwable )
      {
          System.err.println( message );
      }
  
      /**
       * Note: This is copied from FileUtil.normalize();
       *
       * Normalize a path. That means:
       * <ul>
       *   <li>changes to unix style if under windows</li>
       *   <li>eliminates "/../" and "/./"</li>
       *   <li>if path is absolute (starts with '/') and there are
       *   too many occurences of "../" (would then have some kind
       *   of 'negative' path) returns null.</li>
       *   <li>If path is relative, the exceeding ../ are kept at
       *   the begining of the path.</li>
       * </ul>
       * <br><br>
       *
       * <b>Note:</b> note that this method has been tested with unix and windows only.
       *
       * <p>Eg:</p>
       * <pre>
       * /foo//               -->     /foo/
       * /foo/./              -->     /foo/
       * /foo/../bar          -->     /bar
       * /foo/../bar/         -->     /bar/
       * /foo/../bar/../baz   -->     /baz
       * //foo//./bar         -->     /foo/bar
       * /../                 -->     null
       * </pre>
       *
       * @param path the path to be normalized.
       * @return the normalized path or null.
       * @throws NullPointerException if path is null.
       */
      protected static final String normalize( String path )
      {
          if( path.length() < 2 )
          {
              return path;
          }
  
          StringBuffer buff = new StringBuffer( path );
  
          int length = path.length();
  
          // this whole prefix thing is for windows compatibility only.
          String prefix = null;
  
          if( length > 2 && buff.charAt( 1 ) == ':' )
          {
              prefix = path.substring( 0, 2 );
              buff.delete( 0, 2 );
              path = path.substring( 2 );
              length -= 2;
          }
  
          boolean startsWithSlash = length > 0 && (buff.charAt( 0 ) == '/' || buff.charAt( 0 ) == '\\');
  
          boolean expStart = true;
          int ptCount = 0;
          int lastSlash = length + 1;
          int upLevel = 0;
  
          for( int i = length - 1; i >= 0; i-- )
              switch( path.charAt( i ) )
              {
                  case '\\':
                      buff.setCharAt( i, '/' );
                  case '/':
                      if( lastSlash == i + 1 )
                      {
                          buff.deleteCharAt( i );
                      }
  
                      switch( ptCount )
                      {
                          case 1:
                              buff.delete( i, lastSlash );
                              break;
  
                          case 2:
                              upLevel++;
                              break;
  
                          default:
                              if( upLevel > 0 && lastSlash != i + 1 )
                              {
                                  buff.delete( i, lastSlash + 3 );
                                  upLevel--;
                              }
                              break;
                      }
  
                      ptCount = 0;
                      expStart = true;
                      lastSlash = i;
                      break;
  
                  case '.':
                      if( expStart )
                      {
                          ptCount++;
                      }
                      break;
  
                  default:
                      ptCount = 0;
                      expStart = false;
                      break;
              }
  
          switch( ptCount )
          {
              case 1:
                  buff.delete( 0, lastSlash );
                  break;
  
              case 2:
                  break;
  
              default:
                  if( upLevel > 0 )
                  {
                      if( startsWithSlash )
                      {
                          return null;
                      }
                      else
                      {
                          upLevel = 1;
                      }
                  }
  
                  while( upLevel > 0 )
                  {
                      buff.delete( 0, lastSlash + 3 );
                      upLevel--;
                  }
                  break;
          }
  
          length = buff.length();
          boolean isLengthNull = length == 0;
          char firstChar = isLengthNull?(char)0:buff.charAt( 0 );
  
          if( !startsWithSlash && !isLengthNull && firstChar == '/' )
          {
              buff.deleteCharAt( 0 );
          }
          else if( startsWithSlash &&
              (isLengthNull || (!isLengthNull && firstChar != '/')) )
          {
              buff.insert( 0, '/' );
          }
  
          if( prefix != null )
          {
              buff.insert( 0, prefix );
          }
  
          return buff.toString();
      }
  }
  
  
  1.1                  jakarta-avalon-excalibur/policy/src/java/org/apache/excalibur/policy/runtime/DefaultPolicy.java
  
  Index: DefaultPolicy.java
  ===================================================================
  /*
   * Copyright (C) The Apache Software Foundation. All rights reserved.
   *
   * This software is published under the terms of the Apache Software License
   * version 1.1, a copy of which has been included with this distribution in
   * the LICENSE.txt file.
   */
  package org.apache.excalibur.policy.runtime;
  
  import java.util.Map;
  import java.util.Iterator;
  import java.security.CodeSource;
  import java.security.Permission;
  import java.security.Permissions;
  
  /**
   * A policy implementation that accepts policys details from a map.
   * The map is between a codebase and a array of permissions.
   * Note that it was a deliberate decision to limit the time at which you can
   * specify policy data for security reasons.
   *
   * @author <a href="mailto:peter at apache.org">Peter Donald</a>
   */
  public class DefaultPolicy
      extends AbstractPolicy
  {
      /**
       * Create a Policy that applies specified grants.
       * Each entry in map maps a codeSOurce to an array
       * of Permissions.
       *
       * @param grants the grant map
       * @throws Exception if unable to construct Policy
       */
      public DefaultPolicy( final Map grants )
          throws Exception
      {
          processGrants( grants );
      }
  
      /**
       * Create a policy with zero entrys.
       * Sub-classes usually use this constructor then
       * invoke processGrants separately.
       */
      public DefaultPolicy()
      {
      }
  
      /**
       * Process map of grants and configure Policy appropriately.
       *
       * @param grants the grants map
       * @throws Exception if unable to perform configuration
       */
      protected final void processGrants( final Map grants )
          throws Exception
      {
          final Iterator iterator = grants.keySet().iterator();
          while( iterator.hasNext() )
          {
              final CodeSource codeSource = (CodeSource) iterator.next();
              final Permission[] permissions = (Permission[]) grants.get( codeSource );
              final Permissions permissionSet = createPermissionSetFor( codeSource );
  
              for( int i = 0; i < permissions.length; i++ )
              {
                  final Permission permission = permissions[ i ];
                  permissionSet.add( permission );
              }
          }
      }
  }
  
  
  
  1.1                  jakarta-avalon-excalibur/policy/src/java/org/apache/excalibur/policy/runtime/PolicyEntry.java
  
  Index: PolicyEntry.java
  ===================================================================
  /*
   * Copyright (C) The Apache Software Foundation. All rights reserved.
   *
   * This software is published under the terms of the Apache Software License
   * version 1.1, a copy of which has been included  with this distribution in
   * the LICENSE.txt file.
   */
  package org.apache.excalibur.policy.runtime;
  
  import java.security.CodeSource;
  import java.security.Permissions;
  
  /**
   * Internal Policy Entry holder class.
   * Holds information about an entry in policy file.
   */
  final class PolicyEntry
  {
      /**
       * The code source that entry is about.
       */
      private final CodeSource m_codeSource;
  
      /**
       * the set of permissions for code source.
       */
      private final Permissions m_permissions;
  
      public PolicyEntry( final CodeSource codeSource,
                          final Permissions permissions )
      {
          m_codeSource = codeSource;
          m_permissions = permissions;
      }
  
      public CodeSource getCodeSource()
      {
          return m_codeSource;
      }
  
      public Permissions getPermissions()
      {
          return m_permissions;
      }
  }
  
  
  
  1.1                  jakarta-avalon-excalibur/policy/src/java/org/apache/excalibur/policy/verifier/PolicyVerifier.java
  
  Index: PolicyVerifier.java
  ===================================================================
  /*
   * Copyright (C) The Apache Software Foundation. All rights reserved.
   *
   * This software is published under the terms of the Apache Software License
   * version 1.1, a copy of which has been included with this distribution in
   * the LICENSE.txt file.
   */
  package org.apache.excalibur.policy.verifier;
  
  import org.apache.avalon.excalibur.i18n.ResourceManager;
  import org.apache.avalon.excalibur.i18n.Resources;
  import org.apache.excalibur.policy.metadata.GrantMetaData;
  import org.apache.excalibur.policy.metadata.KeyStoreMetaData;
  import org.apache.excalibur.policy.metadata.PermissionMetaData;
  import org.apache.excalibur.policy.metadata.PolicyMetaData;
  
  /**
   * Verify Policy set is valid. Validity is defined as
   * <ul>
   *   <li>All KeyStore names should be defined starting with
   *       letters or '_' and then continuing with Alpha-Numeric
   *       characters, '-', '.' or '_'.</li>
   *   <li>If signedBy is specified then keystore is specified
   *       for both grants and permissions.</li>
   *   <li>That any keystore names used by grant or permission
   *       reference actual keystores.</li>
   *   <li>If target is null then actions is null.</li>
   * </ul>
   *
   * @author <a href="mailto:peter at apache.org">Peter Donald</a>
   * @version $Revision: 1.1 $ $Date: 2002/09/25 12:37:44 $
   */
  public class PolicyVerifier
  {
      private final static Resources REZ =
          ResourceManager.getPackageResources( PolicyVerifier.class );
  
      public void verifyPolicy( final PolicyMetaData policy )
          throws Exception
      {
          String message = null;
  
          message = REZ.getString( "valid-names.notice" );
          info( message );
          verifyNames( policy );
  
          message = REZ.getString( "valid-signedBy.notice" );
          info( message );
          verifySignedBy( policy );
  
          message = REZ.getString( "valid-keyStoreReferences.notice" );
          info( message );
          verifyKeyStoreReferences( policy );
  
          message = REZ.getString( "valid-actions.notice" );
          info( message );
          verifyActions( policy );
      }
  
      /**
       * Log an informational message.
       * Sub-classes should overide this.
       *
       * @param message the message
       */
      protected void info( final String message )
      {
          //noop
      }
  
      /**
       * Verify that all the keystores have valid names.
       *
       * @throws Exception if validity check fails
       */
      private void verifyNames( final PolicyMetaData policy )
          throws Exception
      {
          final KeyStoreMetaData[] keyStores = policy.getKeyStores();
          for( int i = 0; i < keyStores.length; i++ )
          {
              final String name = keyStores[ i ].getName();
              verifyName( name );
          }
      }
  
      /**
       * Verify that all the signedBy are accompanied by keystores.
       *
       * @throws Exception if validity check fails
       */
      private void verifySignedBy( final PolicyMetaData policy )
          throws Exception
      {
          final GrantMetaData[] grants = policy.getGrants();
          for( int i = 0; i < grants.length; i++ )
          {
              verifySignedBy( grants[ i ] );
          }
      }
  
      /**
       * Verify that all the signedBy are accompanied by keystores.
       *
       * @throws Exception if validity check fails
       */
      private void verifySignedBy( final GrantMetaData grant ) throws Exception
      {
          final String signedBy = grant.getSignedBy();
          final String keyStore = grant.getKeyStore();
          if( null != signedBy && null == keyStore )
          {
              final String message =
                  REZ.getString( "grant-missing-keystore.error",
                                 grant.getCodebase() );
              throw new Exception( message );
  
          }
          else if( null == signedBy && null != keyStore )
          {
              final String message =
                  REZ.getString( "grant-extra-keystore.error",
                                 grant.getCodebase() );
              throw new Exception( message );
          }
          final PermissionMetaData[] permissions = grant.getPermissions();
          for( int i = 0; i < permissions.length; i++ )
          {
              final PermissionMetaData permission = permissions[ i ];
              verifySignedBy( grant, permission );
          }
      }
  
      /**
       * Verify that all the signedBy are accompanied by keystores.
       *
       * @throws Exception if validity check fails
       */
      private void verifySignedBy( final GrantMetaData grant,
                                   final PermissionMetaData permission )
          throws Exception
      {
          final String signedBy = permission.getSignedBy();
          final String keyStore = permission.getKeyStore();
          if( null != signedBy && null == keyStore )
          {
              final String message =
                  REZ.getString( "permission-missing-keystore.error",
                                 grant.getCodebase(),
                                 permission.getClassname() );
              throw new Exception( message );
  
          }
          else if( null == signedBy && null != keyStore )
          {
              final String message =
                  REZ.getString( "permission-extra-keystore.error",
                                 grant.getCodebase(),
                                 permission.getClassname() );
              throw new Exception( message );
          }
      }
  
      /**
       * Verify that each reference to a keystore is valid.
       *
       * @throws Exception if validity check fails
       */
      private void verifyKeyStoreReferences( final PolicyMetaData policy )
          throws Exception
      {
          final GrantMetaData[] grants = policy.getGrants();
          for( int i = 0; i < grants.length; i++ )
          {
              verifyKeyStore( policy, grants[ i ] );
          }
      }
  
      /**
       * Verify that each reference to a keystore is valid.
       *
       * @throws Exception if validity check fails
       */
      private void verifyKeyStore( final PolicyMetaData policy,
                                   final GrantMetaData grant )
          throws Exception
      {
          verifyKeyStoreReference( policy, grant.getKeyStore() );
          final PermissionMetaData[] permissions = grant.getPermissions();
          for( int j = 0; j < permissions.length; j++ )
          {
              final PermissionMetaData permission = permissions[ j ];
              verifyKeyStoreReference( policy, permission.getKeyStore() );
          }
      }
  
      /**
       * Verify that each reference to a keystore is valid.
       *
       * @throws Exception if validity check fails
       */
      private void verifyKeyStoreReference( final PolicyMetaData policy,
                                            final String keyStoreName )
          throws Exception
      {
          //Ignore keystores that are not specified
          if( null == keyStoreName )
          {
              return;
          }
          final KeyStoreMetaData[] keyStores = policy.getKeyStores();
          for( int i = 0; i < keyStores.length; i++ )
          {
              final KeyStoreMetaData keyStore = keyStores[ i ];
              if( keyStore.getName().equals( keyStoreName ) )
              {
                  return;
              }
          }
  
          final String message =
              REZ.getString( "bad-keystore-reference.error",
                             keyStoreName );
          throw new Exception( message );
      }
  
      /**
       * Verify that all the classloaders have valid names.
       *
       * @throws Exception if validity check fails
       */
      private void verifyName( final String name )
          throws Exception
      {
          final int size = name.length();
          if( 0 == size )
          {
              final String message =
                  REZ.getString( "empty-name.error",
                                 name );
              throw new Exception( message );
          }
          final char ch = name.charAt( 0 );
          if( !Character.isLetter( ch ) &&
              '_' != ch )
          {
              final String message =
                  REZ.getString( "name-invalid-start.error",
                                 name );
              throw new Exception( message );
          }
  
          for( int i = 1; i < size; i++ )
          {
              final char c = name.charAt( i );
              if( !Character.isLetterOrDigit( c ) &&
                  '_' != c &&
                  '-' != c &&
                  '.' != c )
              {
                  final String message =
                      REZ.getString( "name-invalid-char.error",
                                     name,
                                     String.valueOf( c ) );
                  throw new Exception( message );
              }
          }
      }
  
      /**
       * Verify that an action is null if a target is null.
       *
       * @throws Exception if validity check fails
       */
      private void verifyActions( final PolicyMetaData policy )
          throws Exception
      {
          final GrantMetaData[] grants = policy.getGrants();
          for( int i = 0; i < grants.length; i++ )
          {
              final GrantMetaData grant = grants[ i ];
              final PermissionMetaData[] permissions = grant.getPermissions();
              for( int j = 0; j < permissions.length; j++ )
              {
                  final PermissionMetaData permission = permissions[ j ];
                  final String target = permission.getTarget();
                  final String action = permission.getAction();
                  if( null == target && null != action )
                  {
                      final String message =
                          REZ.getString( "permission-missing-action.error",
                                         grant.getCodebase(),
                                         permission.getClassname() );
                      throw new Exception( message );
                  }
              }
          }
      }
  }
  
  
  
  1.1                  jakarta-avalon-excalibur/policy/src/java/org/apache/excalibur/policy/verifier/Resources.properties
  
  Index: Resources.properties
  ===================================================================
  valid-names.notice=Verifying that all key-stores have valid names.
  valid-signedBy.notice=Verifying that all signed-by attributes are accompanied by a key-store attribute.
  valid-keyStoreReferences.notice=Verify that any keystore names used by grant or permission reference actual keystores
  valid-actions.notice=Verify that if target is null then actions is null.
  
  grant-missing-keystore.error=Grant for codebase "{0}" has a signed-by attribute but no key-store attribute.
  grant-extra-keystore.error=Grant for codebase "{0}" defined a key-store attribute without defining a signed-by attribute.
  permission-missing-keystore.error=Permission loaded from codebase "{0}" of type "{1}" has a signed-by attribute but no key-store attribute.
  permission-extra-keystore.error=Permission loaded from codebase "{0}" of type "{1}" defined a key-store attribute without defining a signed-by attribute.
  
  bad-keystore-reference.error=Referenced non-existent keystore {0}.
  
  empty-name.error=Keystore name is empty.
  name-invalid-start.error=Keystore name "{0}" starts with an invalid character.
  name-invalid-char.error=Keystore name "{0}" contains an invalid character "{1}".
  permission-missing-action.error=Permission on codebase "{0}" of type "{1}" defines a target without an action.
  
  
  1.1                  jakarta-avalon-excalibur/policy/src/test/org/apache/excalibur/policy/reader/test/ReaderTestCase.java
  
  Index: ReaderTestCase.java
  ===================================================================
  /*
   * Copyright (C) The Apache Software Foundation. All rights reserved.
   *
   * This software is published under the terms of the Apache Software License
   * version 1.1, a copy of which has been included with this distribution in
   * the LICENSE.txt file.
   */
  package org.apache.excalibur.policy.reader.test;
  
  import org.apache.excalibur.policy.metadata.GrantMetaData;
  import org.apache.excalibur.policy.metadata.KeyStoreMetaData;
  import org.apache.excalibur.policy.metadata.PermissionMetaData;
  import org.apache.excalibur.policy.metadata.PolicyMetaData;
  import org.apache.excalibur.policy.test.AbstractPolicyTestCase;
  
  /**
   * TestCase for {@link org.apache.excalibur.policy.reader.PolicyReader}.
   *
   * @author <a href="mailto:peter at apache.org">Peter Donald</a>
   */
  public class ReaderTestCase
      extends AbstractPolicyTestCase
  {
      public ReaderTestCase( final String name )
      {
          super( name );
      }
  
      public void testConfig1()
          throws Exception
      {
          final PolicyMetaData policy = buildFromResource( "config1.xml" );
  
          assertEquals( "Policy KeyStore Count",
                        1,
                        policy.getKeyStores().length );
  
          final KeyStoreMetaData keyStore = policy.getKeyStores()[ 0 ];
          assertEquals( "KeyStore Name",
                        "myKeystore",
                        keyStore.getName() );
          assertEquals( "KeyStore Location",
                        "sar:/conf/keystore",
                        keyStore.getLocation() );
          assertEquals( "KeyStore Type",
                        "JKS",
                        keyStore.getType() );
  
          assertEquals( "Policy Grant Count",
                        2,
                        policy.getGrants().length );
  
          final GrantMetaData grant1 = policy.getGrants()[ 0 ];
          final GrantMetaData grant2 = policy.getGrants()[ 1 ];
  
          assertEquals( "grant1.getCodebase()",
                        "myCodeBase",
                        grant1.getCodebase() );
          assertEquals( "grant1.getKeyStore()",
                        null,
                        grant1.getKeyStore() );
          assertEquals( "grant1.getSignedBy()",
                        null,
                        grant1.getSignedBy() );
  
          assertEquals( "grant1.getPermissions().length",
                        1,
                        grant1.getPermissions().length );
  
          final PermissionMetaData permission1 = grant1.getPermissions()[ 0 ];
          assertEquals( "permission1.getClassname()",
                        "java.io.FilePermission",
                        permission1.getClassname() );
          assertEquals( "permission1.getAction()",
                        "read,write",
                        permission1.getAction() );
          assertEquals( "permission1.getTarget()",
                        "${/}tmp${/}*",
                        permission1.getTarget() );
          assertEquals( "permission1.getKeyStore()",
                        "myKeystore",
                        permission1.getKeyStore() );
          assertEquals( "permission1.getSignedBy()",
                        "Bob",
                        permission1.getSignedBy() );
  
          assertEquals( "grant2.getCodebase()",
                        "sar:/SAR-INF/lib/*",
                        grant2.getCodebase() );
          assertEquals( "grant2.getKeyStore()",
                        "myKeystore",
                        grant2.getKeyStore() );
          assertEquals( "grant2.getSignedBy()",
                        "Bob",
                        grant2.getSignedBy() );
  
          assertEquals( "grant2.getPermissions().length",
                        1,
                        grant2.getPermissions().length );
  
          final PermissionMetaData permission2 = grant2.getPermissions()[ 0 ];
          assertEquals( "permission2.getClassname()",
                        "java.io.FilePermission",
                        permission2.getClassname() );
          assertEquals( "permission2.getAction()",
                        null,
                        permission2.getAction() );
          assertEquals( "permission2.getTarget()",
                        null,
                        permission2.getTarget() );
          assertEquals( "permission2.getKeyStore()",
                        null,
                        permission2.getKeyStore() );
          assertEquals( "permission2.getSignedBy()",
                        null,
                        permission2.getSignedBy() );
      }
  
      public void testConfig2()
          throws Exception
      {
          try
          {
              buildFromResource( "config2.xml" );
          }
          catch( final Throwable t )
          {
              return;
          }
          fail( "Should have failed as loaded a " +
                "configuration with no version" );
      }
  
      public void testConfig3()
          throws Exception
      {
          try
          {
              buildFromResource( "config3.xml" );
          }
          catch( final Throwable t )
          {
              return;
          }
          fail( "Should have failed as loaded a " +
                "configuration with bad version set" );
      }
  }
  
  
  
  1.1                  jakarta-avalon-excalibur/policy/src/test/org/apache/excalibur/policy/reader/test/config1.xml
  
  Index: config1.xml
  ===================================================================
  <policy version="1.0">
      <keystore name="myKeystore"
          location="sar:/conf/keystore"
          type="JKS"/>
  
      <grant code-base="myCodeBase">
          <permission class="java.io.FilePermission"
              target="${/}tmp${/}*"
              signed-by="Bob"
              key-store="myKeystore"
              action="read,write"/>
      </grant>
  
      <grant signed-by="Bob" key-store="myKeystore" code-base="sar:/SAR-INF/lib/*">
          <permission class="java.io.FilePermission"/>
      </grant>
  </policy>
  
  
  
  1.1                  jakarta-avalon-excalibur/policy/src/test/org/apache/excalibur/policy/reader/test/config2.xml
  
  Index: config2.xml
  ===================================================================
  <policy>
  </policy>
  
  
  1.1                  jakarta-avalon-excalibur/policy/src/test/org/apache/excalibur/policy/reader/test/config3.xml
  
  Index: config3.xml
  ===================================================================
  <policy version="3.2">
  </policy>
  
  
  1.1                  jakarta-avalon-excalibur/policy/src/test/org/apache/excalibur/policy/test/AbstractPolicyTestCase.java
  
  Index: AbstractPolicyTestCase.java
  ===================================================================
  /*
   * Copyright (C) The Apache Software Foundation. All rights reserved.
   *
   * This software is published under the terms of the Apache Software License
   * version 1.1, a copy of which has been included with this distribution in
   * the LICENSE.txt file.
   */
  package org.apache.excalibur.policy.test;
  
  import java.io.InputStream;
  import javax.xml.parsers.DocumentBuilder;
  import javax.xml.parsers.DocumentBuilderFactory;
  import junit.framework.TestCase;
  import org.apache.excalibur.policy.metadata.PolicyMetaData;
  import org.apache.excalibur.policy.reader.PolicyReader;
  import org.w3c.dom.Document;
  
  /**
   *  An abstract testcase to test policys.
   *
   * @author <a href="mailto:peter at apache.org">Peter Donald</a>
   * @version $Revision: 1.1 $ $Date: 2002/09/25 12:37:44 $
   */
  public class AbstractPolicyTestCase
      extends TestCase
  {
      protected PolicyMetaData buildFromStream( final InputStream stream )
          throws Exception
      {
          try
          {
              final PolicyReader builder = new PolicyReader();
              final Document config = load( stream );
              return builder.readPolicy( config.getDocumentElement() );
          }
          catch( final Exception e )
          {
              fail( "Error building Policy: " + e );
              return null;
          }
      }
  
      protected Document load( final InputStream stream )
          throws Exception
      {
          final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
          //factory.setValidating(true);
          //factory.setNamespaceAware(true);
          final DocumentBuilder builder = factory.newDocumentBuilder();
          return builder.parse( stream );
      }
  
      protected PolicyMetaData buildFromResource( final String resource )
          throws Exception
      {
          final InputStream stream = getClass().getResourceAsStream( resource );
          if( null == stream )
          {
              fail( "Missing resource " + resource );
          }
          return buildFromStream( stream );
      }
  
      public AbstractPolicyTestCase( String name )
      {
          super( name );
      }
  }
  
  
  
  1.1                  jakarta-avalon-excalibur/policy/src/test/org/apache/excalibur/policy/test/PolicyTestSuite.java
  
  Index: PolicyTestSuite.java
  ===================================================================
  /*
   * Copyright  The Apache Software Foundation. All rights reserved.
   *
   * This software is published under the terms of the Apache Software License
   * version 1.1, a copy of which has been included with this distribution in
   * the LICENSE.txt file.
   */
  package org.apache.excalibur.policy.test;
  
  import junit.framework.Test;
  import junit.framework.TestSuite;
  import org.apache.excalibur.policy.reader.test.ReaderTestCase;
  import org.apache.excalibur.policy.verifier.test.VerifierTestCase;
  
  /**
   * A basic test suite that tests all the Policy package.
   */
  public class PolicyTestSuite
  {
      public static Test suite()
      {
          final TestSuite suite = new TestSuite( "Policy Utilities" );
          suite.addTestSuite( ReaderTestCase.class );
          suite.addTestSuite( VerifierTestCase.class );
          return suite;
      }
  }
  
  
  
  1.1                  jakarta-avalon-excalibur/policy/src/test/org/apache/excalibur/policy/verifier/test/VerifierTestCase.java
  
  Index: VerifierTestCase.java
  ===================================================================
  /*
   * Copyright (C) The Apache Software Foundation. All rights reserved.
   *
   * This software is published under the terms of the Apache Software License
   * version 1.1, a copy of which has been included with this distribution in
   * the LICENSE.txt file.
   */
  package org.apache.excalibur.policy.verifier.test;
  
  import org.apache.excalibur.policy.metadata.PolicyMetaData;
  import org.apache.excalibur.policy.test.AbstractPolicyTestCase;
  import org.apache.excalibur.policy.verifier.PolicyVerifier;
  
  /**
   * TestCase for {@link org.apache.excalibur.policy.reader.PolicyReader}.
   *
   * @author <a href="mailto:peter at apache.org">Peter Donald</a>
   */
  public class VerifierTestCase
      extends AbstractPolicyTestCase
  {
      public VerifierTestCase( final String name )
      {
          super( name );
      }
  
      public void testConfig1()
          throws Exception
      {
          try
          {
              verifyResource( "config1.xml" );
          }
          catch( final Throwable t )
          {
              return;
          }
  
          fail( "Expected verify to fail as specified " +
                "bad name for keyStore" );
      }
  
      public void testConfig2()
          throws Exception
      {
          try
          {
              verifyResource( "config2.xml" );
          }
          catch( final Throwable t )
          {
              return;
          }
  
          fail( "Expected verify to fail as permission " +
                "references non existent keystore" );
      }
  
      public void testConfig3()
          throws Exception
      {
          try
          {
              verifyResource( "config3.xml" );
          }
          catch( final Throwable t )
          {
              return;
          }
  
          fail( "Expected verify to fail as grant " +
                "references non existent keystore" );
      }
  
      public void testConfig4()
          throws Exception
      {
          try
          {
              verifyResource( "config4.xml" );
          }
          catch( final Throwable t )
          {
              return;
          }
  
          fail( "Expected verify to fail as specified " +
                "action with null target" );
      }
  
      public void testConfig5()
          throws Exception
      {
          try
          {
              verifyResource( "config5.xml" );
          }
          catch( final Throwable t )
          {
              fail( "Expected to pass when not specifying keystore" );
          }
  
      }
  
      private void verifyResource( final String resource )
          throws Exception
      {
          final PolicyMetaData defs = buildFromResource( resource );
          final PolicyVerifier verifier = new PolicyVerifier();
          verifier.verifyPolicy( defs );
      }
  }
  
  
  
  1.1                  jakarta-avalon-excalibur/policy/src/test/org/apache/excalibur/policy/verifier/test/config1.xml
  
  Index: config1.xml
  ===================================================================
  <policy version="1.0">
      <keystore name="$myKeystore"
          location="sar:/conf/keystore"
          type="JKS"/>
  </policy>
  
  
  
  1.1                  jakarta-avalon-excalibur/policy/src/test/org/apache/excalibur/policy/verifier/test/config2.xml
  
  Index: config2.xml
  ===================================================================
  <policy version="1.0">
      <grant code-base="myCodeBase">
          <permission class="java.io.FilePermission"
              target="${/}tmp${/}*"
              signed-by="Bob"
              key-store="nonExistingKeystore"
              action="read,write"/>
      </grant>
  </policy>
  
  
  
  1.1                  jakarta-avalon-excalibur/policy/src/test/org/apache/excalibur/policy/verifier/test/config3.xml
  
  Index: config3.xml
  ===================================================================
  <policy version="1.0">
      <grant signed-by="Bob" key-store="nonExistentKeystore"
          code-base="sar:/SAR-INF/lib/*">
          <permission class="java.io.FilePermission"/>
      </grant>
  </policy>
  
  
  
  1.1                  jakarta-avalon-excalibur/policy/src/test/org/apache/excalibur/policy/verifier/test/config4.xml
  
  Index: config4.xml
  ===================================================================
  <policy version="1.0">
      <grant code-base="sar:/SAR-INF/lib/*">
          <permission class="java.io.FilePermission" action="BadActionValue"/>
      </grant>
  </policy>
  
  
  
  1.1                  jakarta-avalon-excalibur/policy/src/test/org/apache/excalibur/policy/verifier/test/config5.xml
  
  Index: config5.xml
  ===================================================================
  <policy version="1.0">
      <grant code-base="sar:/SAR-INF/lib/*">
          <permission class="java.io.FilePermission"/>
      </grant>
  </policy>
  
  
  
  1.1                  jakarta-avalon-excalibur/policy/src/xdocs/index.xml
  
  Index: index.xml
  ===================================================================
  <?xml version="1.0"?>
  
  <document>
      <properties>
          <title>Excalibur Policy - Overview</title>
          <author email="peter at apache.org">Peter Donald</author>
      </properties>
      <body>
          <section name="Introduction">
              <p>The Policy toolkit is a set of utility classes that
              will read in an xml file that describes a code-based security
              policy xml descriptor. The descriptor contains the same
              information as is present in the java.policy file but described
              in an xml file. This toolkit is also capable of validating a
              descriptor to make sure it is well formed and follows some basic
              semantic rules. Please see the <a href="sample.html">sample</a>
              descriptor for an example of the format that the Policy toolkit
              supports.</p>
          </section>
      </body>
  </document>
  
  
  1.1                  jakarta-avalon-excalibur/policy/src/xdocs/menu.xml
  
  Index: menu.xml
  ===================================================================
  <?xml version="1.0" encoding="UTF-8"?>
  <project
      href="http://jakarta.apache.org/avalon/excalibur/policy/"
      name="Avalon Policy">
  
      <title>Avalon Policy</title>
      <body>
          <menu name="About">
              <item name="Overview" href="index.html"/>
              <item name="Excalibur Home" href="http://jakarta.apache.org/avalon/excalibur/index.html"/>
              <item name="Download" href="http://jakarta.apache.org/builds/jakarta-avalon-excalibur/release"/>
              <item name="API Docs" href="api/"/>
          </menu>
          <menu name="User Guide">
              <item name="Sample Descriptor" href="/sample.html"/>
              <item name="DTD" href="/policy.dtd"/>
          </menu>
      </body>
  </project>
  
  
  
  1.1                  jakarta-avalon-excalibur/policy/src/xdocs/sample.xml
  
  Index: sample.xml
  ===================================================================
  <?xml version="1.0"?>
  
  <document>
      <properties>
          <title>Excalibur Policy - Example</title>
          <author email="peter at apache.org">Peter Donald</author>
      </properties>
      <body>
          <section name="Introduction">
              <p>This describes a simple example of a Policy descriptor.
              Let us assume that
              <a href="http://jakarta.apache.org/avalon/phoenix">Phoenix</a>
              has been integrated with the Policy toolkit and that the snippet
              defining classloader is included in the deployment format of
              Phoenix (the .sar file).</p>
              <p>The format below should be largely self explanatory if you
              are familiar with the java.policy file format. One thing that
              is worth mentioning is that the example uses codebases with a
              protocol of "sar:". This is a protocol specific to Phoenix and
              makes it possible to refer to jars and classes contained within
              the deployment archive.</p>
  <source>
  <![CDATA[
  <policy version="1.0">
  
    <!-- define the keystore that is used to load signers from -->
    <keystore name="myKeystore"
              location="sar:/conf/keystore"
              type="JKS"/>
  
    <!-- grant the java classes defined in
         /SAR-INF/classes/ directory the permission
         to read and write files to temp directory. -->
    <grant code-base="sar:/SAR-INF/classes/">
      <permission class="java.io.FilePermission"
                  target="${/}tmp${/}*"
                  action="read,write"/>
    </grant>
  
    <!-- grant the secure.jar the permission to connect
         a socket to localhost ports 1024 and above,
         as long as code has been signed by "Fred". -->
    <grant code-base="sar:/SAR-INF/lib/secure.jar"
           signed-by="Fred"
           key-store="myKeystore" >
      <permission class="java.io.FilePermission"
                  target="localhost:1024-"
                  action="accept,connect,listen"/>
    </grant>
  
  </policy>
  ]]></source>
          </section>
      </body>
  </document>
  
  

--
To unsubscribe, e-mail:   <mailto:avalon-cvs-unsubscribe@jakarta.apache.org>
For additional commands, e-mail: <mailto:avalon-cvs-help@jakarta.apache.org>


Mime
View raw message