[jboss-cvs] JBossAS SVN: r93332 - in projects/security/security-jboss-sx/tags: 2.0.4.SP1 and 30 other directories.

jboss-cvs-commits at lists.jboss.org jboss-cvs-commits at lists.jboss.org
Wed Sep 9 16:59:53 EDT 2009


Author: anil.saldhana at jboss.com
Date: 2009-09-09 16:59:49 -0400 (Wed, 09 Sep 2009)
New Revision: 93332

Added:
   projects/security/security-jboss-sx/tags/2.0.4.SP1/
   projects/security/security-jboss-sx/tags/2.0.4.SP1/acl/pom.xml
   projects/security/security-jboss-sx/tags/2.0.4.SP1/assembly/pom.xml
   projects/security/security-jboss-sx/tags/2.0.4.SP1/identity/pom.xml
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx-bridge-as4/pom.xml
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx-client/pom.xml
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx-mc-int/pom.xml
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx-mc-int/src/test/java/org/jboss/test/security/microcontainer/metadata/support/MockMappingManager.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/pom.xml
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/resource/security/CallerIdentityLoginModule.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/resource/security/ConfiguredIdentityLoginModule.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/resource/security/JaasSecurityDomainIdentityLoginModule.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/resource/security/PBEIdentityLoginModule.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/resource/security/SecureIdentityLoginModule.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/AltClientLoginModule.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/ClientLoginModule.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/SecurityAssociation.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/audit/providers/LogAuditProvider.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/container/modules/AbstractServerAuthModule.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/container/modules/DelegatingServerAuthModule.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/login/XMLLoginConfigImpl.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/AbstractServerLoginModule.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/BaseCertLoginModule.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/CertRolesLoginModule.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/DatabaseCertLoginModule.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/DatabaseServerLoginModule.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/DecodeAction.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/LdapExtLoginModule.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/SimpleServerLoginModule.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/UsersObjectModelFactory.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/Util.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/config/ApplicationPolicy.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/config/AttributeMappingInfo.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/identitytrust/JBossIdentityTrustContext.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/jacc/ContextPolicy.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/jacc/DelegatingPolicy.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/mapping/providers/attribute/
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/mapping/providers/attribute/LdapAttributeMappingProvider.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/plugins/JBossAuthorizationManager.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/plugins/JBossPolicyRegistration.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/plugins/SubjectActions.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/plugins/TransactionManagerLocator.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/plugins/auth/JASPIServerAuthenticationManager.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/plugins/auth/JaasSecurityManagerBase.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/plugins/authorization/JBossAuthorizationContext.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/plugins/identitytrust/JBossIdentityTrustManager.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/plugins/mapping/JBossMappingManager.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/test/java/org/jboss/test/authentication/jaas/ClientLoginModuleUnitTestCase.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/test/java/org/jboss/test/authentication/jaas/LdapLoginModuleDecodeActionUnitTestCase.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/test/java/org/jboss/test/security/ldap/OpenDSUnitTestCase.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/test/java/org/jboss/test/security/ldap/OpenDSUnitTestsAdapter.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/test/java/org/jboss/test/security/mapping/LdapAttributeMappingProviderUnitTestCase.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/test/java/org/jboss/test/securitycontext/MappingContextTestCase.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/test/java/org/jboss/test/securitycontext/SecurityContextBaseTest.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/test/resources/ldap/ldapAttributes.ldif
   projects/security/security-jboss-sx/tags/2.0.4.SP1/parent/pom.xml
   projects/security/security-jboss-sx/tags/2.0.4.SP1/pom.xml
Removed:
   projects/security/security-jboss-sx/tags/2.0.4.SP1/acl/pom.xml
   projects/security/security-jboss-sx/tags/2.0.4.SP1/assembly/pom.xml
   projects/security/security-jboss-sx/tags/2.0.4.SP1/identity/pom.xml
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx-bridge-as4/pom.xml
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx-client/pom.xml
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx-mc-int/pom.xml
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx-mc-int/src/test/java/org/jboss/test/security/microcontainer/metadata/support/MockMappingManager.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/pom.xml
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/resource/security/CallerIdentityLoginModule.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/resource/security/ConfiguredIdentityLoginModule.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/resource/security/JaasSecurityDomainIdentityLoginModule.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/resource/security/PBEIdentityLoginModule.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/resource/security/SecureIdentityLoginModule.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/AltClientLoginModule.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/ClientLoginModule.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/SecurityAssociation.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/audit/providers/LogAuditProvider.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/container/modules/AbstractServerAuthModule.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/container/modules/DelegatingServerAuthModule.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/login/XMLLoginConfigImpl.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/AbstractServerLoginModule.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/BaseCertLoginModule.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/CertRolesLoginModule.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/DatabaseCertLoginModule.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/DatabaseServerLoginModule.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/DecodeAction.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/LdapExtLoginModule.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/SimpleServerLoginModule.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/UsersObjectModelFactory.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/Util.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/config/ApplicationPolicy.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/identitytrust/JBossIdentityTrustContext.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/jacc/ContextPolicy.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/jacc/DelegatingPolicy.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/mapping/providers/attribute/LdapAttributeMappingProvider.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/plugins/JBossAuthorizationManager.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/plugins/JBossPolicyRegistration.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/plugins/SubjectActions.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/plugins/TransactionManagerLocator.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/plugins/auth/JASPIServerAuthenticationManager.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/plugins/auth/JaasSecurityManagerBase.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/plugins/authorization/JBossAuthorizationContext.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/plugins/identitytrust/JBossIdentityTrustManager.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/plugins/mapping/JBossMappingManager.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/test/java/org/jboss/test/authentication/jaas/ClientLoginModuleUnitTestCase.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/test/java/org/jboss/test/security/ldap/OpenDSUnitTestCase.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/test/java/org/jboss/test/securitycontext/MappingContextTestCase.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/test/java/org/jboss/test/securitycontext/SecurityContextBaseTest.java
   projects/security/security-jboss-sx/tags/2.0.4.SP1/parent/pom.xml
   projects/security/security-jboss-sx/tags/2.0.4.SP1/pom.xml
Log:
[maven-release-plugin]  copy for tag 2.0.4.SP1

Copied: projects/security/security-jboss-sx/tags/2.0.4.SP1 (from rev 91524, projects/security/security-jboss-sx/branches/Branch_2_0)

Deleted: projects/security/security-jboss-sx/tags/2.0.4.SP1/acl/pom.xml
===================================================================
--- projects/security/security-jboss-sx/branches/Branch_2_0/acl/pom.xml	2009-07-21 21:59:08 UTC (rev 91524)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/acl/pom.xml	2009-09-09 20:59:49 UTC (rev 93332)
@@ -1,122 +0,0 @@
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
-   <parent>
-      <groupId>org.jboss.security</groupId>
-      <artifactId>jbosssx-parent</artifactId>
-      <version>2.0.3.SP2-SNAPSHOT</version>
-   </parent>
-   <modelVersion>4.0.0</modelVersion>
-   <artifactId>jboss-security-acl-impl</artifactId>
-   <packaging>jar</packaging>
-   <name>JBoss Security ACL Implementation</name>
-   <url>http://labs.jboss.org/portal/jbosssecurity/</url>
-   <description>JBoss Security is a cross cutting project that handles security for the JEMS projects</description>
-   <licenses>
-      <license>
-         <name>lgpl</name>
-         <url>http://repository.jboss.com/licenses/lgpl.txt</url>
-      </license>
-   </licenses>
-   <organization>
-      <name>JBoss Inc.</name>
-      <url>http://www.jboss.org</url>
-   </organization>
-   <profiles>
-    <!--    mvn install -Psecurity-manager    -->
-    <profile>
-      <id>security-manager</id>
-      <activation>
-         <activeByDefault>false</activeByDefault>
-      </activation>
-      <properties>
-         <test.env>-Dtest.basedir=${basedir}/target/test-classes</test.env>
-         <policy.file>${basedir}/src/tests/resources/java.policy</policy.file>
-         <surefire.jvm.args>-Djava.security.manager -Djava.security.policy=${policy.file} ${test.env}</surefire.jvm.args>
-      </properties>
-    </profile>
-    <!--     mvn install -Psecurity-manager-debug   -->
-    <!-- Best Practice:    mvn install -Psecurity-manager-debug  2>&1 > logfile2>&1 > logfile -->
-    <profile>
-      <id>security-manager-debug</id>
-      <activation>
-         <activeByDefault>false</activeByDefault>
-      </activation>
-      <properties>
-         <test.env>-Dtest.basedir=${basedir}/target/test-classes</test.env>
-         <policy.file>${basedir}/src/tests/resources/java.policy</policy.file>
-         <surefire.jvm.args>-Djava.security.manager -Djava.security.policy=${policy.file} -Djava.security.debug=failure,access ${test.env}</surefire.jvm.args>
-      </properties>
-    </profile>
-   </profiles>
-   <build>
-      <sourceDirectory>src/main/java</sourceDirectory>
-      <outputDirectory>target/classes</outputDirectory>
-      <testSourceDirectory>src/tests/java</testSourceDirectory>
-      <testOutputDirectory>target/test-classes</testOutputDirectory>
-      <finalName>${artifactId}</finalName>
-      <resources>
-         <resource>
-            <directory>${basedir}</directory>
-            <includes>
-               <include>JBossORG-EULA.txt</include>
-            </includes>
-         </resource>
-         <resource>
-            <directory>src/main/resources</directory>
-            <includes>
-               <include>**/*.dtd</include>
-               <include>**/*.xsd</include>
-            </includes>
-         </resource>
-      </resources> 
-      <testResources>
-         <testResource>
-            <directory>src/tests/resources/</directory>
-            <includes>
-               <include>**/*.xml</include>
-            </includes>
-         </testResource>
-      </testResources>
-   </build>
-   <dependencies> 
-      <dependency>
-         <groupId>jboss</groupId>
-         <artifactId>jboss-logging-log4j</artifactId>
-         <scope>runtime</scope>
-      </dependency>
-      <dependency>
-         <groupId>org.hibernate</groupId>
-         <artifactId>hibernate</artifactId>
-         <version>3.2.4.sp1</version>
-         <scope>compile</scope>
-      </dependency>
-      <dependency>
-         <groupId>org.hibernate</groupId>
-         <artifactId>hibernate-annotations</artifactId>
-         <version>3.3.0.ga</version>
-         <scope>compile</scope>
-      </dependency>
-      <dependency>
-         <groupId>org.hibernate</groupId>
-         <artifactId>hibernate-entitymanager</artifactId>
-         <version>3.3.1.ga</version>
-         <scope>compile</scope>
-      </dependency>
-      <dependency>
-         <groupId>hsqldb</groupId>
-         <artifactId>hsqldb</artifactId>
-         <version>1.8.0.2</version>
-         <scope>test</scope>
-      </dependency>
-      <dependency>
-         <groupId>junit</groupId>
-         <artifactId>junit</artifactId>
-         <scope>test</scope>
-      </dependency>
-      <dependency>
-         <groupId>org.jboss.security</groupId>
-         <artifactId>identity-impl</artifactId>
-         <version>${project.version}</version>
-         <scope>compile</scope>
-      </dependency>    
-   </dependencies>
-</project>

Copied: projects/security/security-jboss-sx/tags/2.0.4.SP1/acl/pom.xml (from rev 93331, projects/security/security-jboss-sx/branches/Branch_2_0/acl/pom.xml)
===================================================================
--- projects/security/security-jboss-sx/tags/2.0.4.SP1/acl/pom.xml	                        (rev 0)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/acl/pom.xml	2009-09-09 20:59:49 UTC (rev 93332)
@@ -0,0 +1,122 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+   <parent>
+      <groupId>org.jboss.security</groupId>
+      <artifactId>jbosssx-parent</artifactId>
+      <version>2.0.4.SP1</version>
+   </parent>
+   <modelVersion>4.0.0</modelVersion>
+   <artifactId>jboss-security-acl-impl</artifactId>
+   <packaging>jar</packaging>
+   <name>JBoss Security ACL Implementation</name>
+   <url>http://labs.jboss.org/portal/jbosssecurity/</url>
+   <description>JBoss Security is a cross cutting project that handles security for the JEMS projects</description>
+   <licenses>
+      <license>
+         <name>lgpl</name>
+         <url>http://repository.jboss.com/licenses/lgpl.txt</url>
+      </license>
+   </licenses>
+   <organization>
+      <name>JBoss Inc.</name>
+      <url>http://www.jboss.org</url>
+   </organization>
+   <profiles>
+    <!--    mvn install -Psecurity-manager    -->
+    <profile>
+      <id>security-manager</id>
+      <activation>
+         <activeByDefault>false</activeByDefault>
+      </activation>
+      <properties>
+         <test.env>-Dtest.basedir=${basedir}/target/test-classes</test.env>
+         <policy.file>${basedir}/src/tests/resources/java.policy</policy.file>
+         <surefire.jvm.args>-Djava.security.manager -Djava.security.policy=${policy.file} ${test.env}</surefire.jvm.args>
+      </properties>
+    </profile>
+    <!--     mvn install -Psecurity-manager-debug   -->
+    <!-- Best Practice:    mvn install -Psecurity-manager-debug  2>&1 > logfile2>&1 > logfile -->
+    <profile>
+      <id>security-manager-debug</id>
+      <activation>
+         <activeByDefault>false</activeByDefault>
+      </activation>
+      <properties>
+         <test.env>-Dtest.basedir=${basedir}/target/test-classes</test.env>
+         <policy.file>${basedir}/src/tests/resources/java.policy</policy.file>
+         <surefire.jvm.args>-Djava.security.manager -Djava.security.policy=${policy.file} -Djava.security.debug=failure,access ${test.env}</surefire.jvm.args>
+      </properties>
+    </profile>
+   </profiles>
+   <build>
+      <sourceDirectory>src/main/java</sourceDirectory>
+      <outputDirectory>target/classes</outputDirectory>
+      <testSourceDirectory>src/tests/java</testSourceDirectory>
+      <testOutputDirectory>target/test-classes</testOutputDirectory>
+      <finalName>${artifactId}</finalName>
+      <resources>
+         <resource>
+            <directory>${basedir}</directory>
+            <includes>
+               <include>JBossORG-EULA.txt</include>
+            </includes>
+         </resource>
+         <resource>
+            <directory>src/main/resources</directory>
+            <includes>
+               <include>**/*.dtd</include>
+               <include>**/*.xsd</include>
+            </includes>
+         </resource>
+      </resources> 
+      <testResources>
+         <testResource>
+            <directory>src/tests/resources/</directory>
+            <includes>
+               <include>**/*.xml</include>
+            </includes>
+         </testResource>
+      </testResources>
+   </build>
+   <dependencies> 
+      <dependency>
+         <groupId>jboss</groupId>
+         <artifactId>jboss-logging-log4j</artifactId>
+         <scope>runtime</scope>
+      </dependency>
+      <dependency>
+         <groupId>org.hibernate</groupId>
+         <artifactId>hibernate</artifactId>
+         <version>3.2.4.sp1</version>
+         <scope>compile</scope>
+      </dependency>
+      <dependency>
+         <groupId>org.hibernate</groupId>
+         <artifactId>hibernate-annotations</artifactId>
+         <version>3.3.0.ga</version>
+         <scope>compile</scope>
+      </dependency>
+      <dependency>
+         <groupId>org.hibernate</groupId>
+         <artifactId>hibernate-entitymanager</artifactId>
+         <version>3.3.1.ga</version>
+         <scope>compile</scope>
+      </dependency>
+      <dependency>
+         <groupId>hsqldb</groupId>
+         <artifactId>hsqldb</artifactId>
+         <version>1.8.0.2</version>
+         <scope>test</scope>
+      </dependency>
+      <dependency>
+         <groupId>junit</groupId>
+         <artifactId>junit</artifactId>
+         <scope>test</scope>
+      </dependency>
+      <dependency>
+         <groupId>org.jboss.security</groupId>
+         <artifactId>identity-impl</artifactId>
+         <version>${project.version}</version>
+         <scope>compile</scope>
+      </dependency>    
+   </dependencies>
+</project>

Deleted: projects/security/security-jboss-sx/tags/2.0.4.SP1/assembly/pom.xml
===================================================================
--- projects/security/security-jboss-sx/branches/Branch_2_0/assembly/pom.xml	2009-07-21 21:59:08 UTC (rev 91524)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/assembly/pom.xml	2009-09-09 20:59:49 UTC (rev 93332)
@@ -1,62 +0,0 @@
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
-  <parent>
-    <groupId>org.jboss.security</groupId>
-    <artifactId>jbosssx-parent</artifactId>
-    <version>2.0.3.SP2-SNAPSHOT</version>
-  </parent>
-  <modelVersion>4.0.0</modelVersion>
-  <groupId>org.jboss.security</groupId>
-  <artifactId>jbosssx</artifactId>
-  <packaging>pom</packaging>
-  <name>JBoss Security Implementation for the JBAS - Assembly</name>
-  <url>http://labs.jboss.org/portal/jbosssecurity/</url>
-  <description>JBoss Security is a cross cutting project that handles security for the JEMS projects</description>
-  <licenses>
-    <license>
-      <name>lgpl</name>
-      <url>http://repository.jboss.com/licenses/lgpl.txt</url>
-    </license>
-  </licenses>
-  <organization>
-    <name>JBoss Inc.</name>
-    <url>http://www.jboss.org</url>
-  </organization>
-    
-  <build>
-    <plugins>
-      <plugin>
-        <groupId>org.apache.maven.plugins</groupId>
-        <artifactId>maven-assembly-plugin</artifactId>
-        <version>2.1</version>
-        <executions>
-          <execution>
-            <phase>package</phase>
-            <goals>
-              <goal>attached</goal>
-            </goals>
-          </execution>
-        </executions>
-        <configuration>
-          <archive>
-            <manifestEntries>
-              <Specification-Title>JBoss Security Implementation for the JBAS</Specification-Title>
-              <Specification-Version>${project.version}</Specification-Version>
-              <Specification-Vendor>Red Hat Middleware LLC</Specification-Vendor>
-              <Implementation-Title>JBoss Security Implementation for the JBAS</Implementation-Title>
-              <Implementation-Version>${project.version}</Implementation-Version>
-              <Implementation-VendorId>org.jboss.security</Implementation-VendorId>
-              <Implementation-Vendor>Red Hat Middleware LLC</Implementation-Vendor>
-              <Implementation-URL>http://labs.jboss.org/portal/jbosssecurity/</Implementation-URL>
-            </manifestEntries>
-          </archive>
-          <descriptors>
-            <descriptor>src/assembly/bin.xml</descriptor>
-            <descriptor>src/assembly/sources.xml</descriptor>
-          </descriptors>
-        </configuration>
-        <inherited>false</inherited>
-      </plugin>
-    </plugins>
-  </build>
-  
-</project>

Copied: projects/security/security-jboss-sx/tags/2.0.4.SP1/assembly/pom.xml (from rev 93331, projects/security/security-jboss-sx/branches/Branch_2_0/assembly/pom.xml)
===================================================================
--- projects/security/security-jboss-sx/tags/2.0.4.SP1/assembly/pom.xml	                        (rev 0)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/assembly/pom.xml	2009-09-09 20:59:49 UTC (rev 93332)
@@ -0,0 +1,62 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+  <parent>
+    <groupId>org.jboss.security</groupId>
+    <artifactId>jbosssx-parent</artifactId>
+    <version>2.0.4.SP1</version>
+  </parent>
+  <modelVersion>4.0.0</modelVersion>
+  <groupId>org.jboss.security</groupId>
+  <artifactId>jbosssx</artifactId>
+  <packaging>pom</packaging>
+  <name>JBoss Security Implementation for the JBAS - Assembly</name>
+  <url>http://labs.jboss.org/portal/jbosssecurity/</url>
+  <description>JBoss Security is a cross cutting project that handles security for the JEMS projects</description>
+  <licenses>
+    <license>
+      <name>lgpl</name>
+      <url>http://repository.jboss.com/licenses/lgpl.txt</url>
+    </license>
+  </licenses>
+  <organization>
+    <name>JBoss Inc.</name>
+    <url>http://www.jboss.org</url>
+  </organization>
+    
+  <build>
+    <plugins>
+      <plugin>
+        <groupId>org.apache.maven.plugins</groupId>
+        <artifactId>maven-assembly-plugin</artifactId>
+        <version>2.1</version>
+        <executions>
+          <execution>
+            <phase>package</phase>
+            <goals>
+              <goal>attached</goal>
+            </goals>
+          </execution>
+        </executions>
+        <configuration>
+          <archive>
+            <manifestEntries>
+              <Specification-Title>JBoss Security Implementation for the JBAS</Specification-Title>
+              <Specification-Version>${project.version}</Specification-Version>
+              <Specification-Vendor>Red Hat Middleware LLC</Specification-Vendor>
+              <Implementation-Title>JBoss Security Implementation for the JBAS</Implementation-Title>
+              <Implementation-Version>${project.version}</Implementation-Version>
+              <Implementation-VendorId>org.jboss.security</Implementation-VendorId>
+              <Implementation-Vendor>Red Hat Middleware LLC</Implementation-Vendor>
+              <Implementation-URL>http://labs.jboss.org/portal/jbosssecurity/</Implementation-URL>
+            </manifestEntries>
+          </archive>
+          <descriptors>
+            <descriptor>src/assembly/bin.xml</descriptor>
+            <descriptor>src/assembly/sources.xml</descriptor>
+          </descriptors>
+        </configuration>
+        <inherited>false</inherited>
+      </plugin>
+    </plugins>
+  </build>
+  
+</project>

Deleted: projects/security/security-jboss-sx/tags/2.0.4.SP1/identity/pom.xml
===================================================================
--- projects/security/security-jboss-sx/branches/Branch_2_0/identity/pom.xml	2009-07-21 21:59:08 UTC (rev 91524)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/identity/pom.xml	2009-09-09 20:59:49 UTC (rev 93332)
@@ -1,86 +0,0 @@
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
-   <parent>
-      <groupId>org.jboss.security</groupId>
-      <artifactId>jbosssx-parent</artifactId>
-      <version>2.0.3.SP2-SNAPSHOT</version>
-   </parent>
-   <modelVersion>4.0.0</modelVersion>
-   <artifactId>identity-impl</artifactId>
-   <packaging>jar</packaging>
-   <name>JBoss Security Identity Implementation</name>
-   <url>http://labs.jboss.org/portal/jbosssecurity/</url>
-   <description>JBoss Security is a cross cutting project that handles security for the JEMS projects</description>
-   <licenses>
-      <license>
-         <name>lgpl</name>
-         <url>http://repository.jboss.com/licenses/lgpl.txt</url>
-      </license>
-   </licenses>
-   <organization>
-      <name>JBoss Inc.</name>
-      <url>http://www.jboss.org</url>
-   </organization>
-   <profiles>
-    <!--    mvn install -Psecurity-manager    -->
-    <profile>
-      <id>security-manager</id>
-      <activation>
-         <activeByDefault>false</activeByDefault>
-      </activation>
-      <properties>
-         <test.env>-Dtest.basedir=${basedir}/target/test-classes</test.env>
-         <policy.file>${basedir}/src/tests/resources/java.policy</policy.file>
-         <surefire.jvm.args>-Djava.security.manager -Djava.security.policy=${policy.file} ${test.env}</surefire.jvm.args>
-      </properties>
-    </profile>
-    <!--     mvn install -Psecurity-manager-debug   -->
-    <!-- Best Practice:    mvn install -Psecurity-manager-debug  2>&1 > logfile2>&1 > logfile -->
-    <profile>
-      <id>security-manager-debug</id>
-      <activation>
-         <activeByDefault>false</activeByDefault>
-      </activation>
-      <properties>
-         <test.env>-Dtest.basedir=${basedir}/target/test-classes</test.env>
-         <policy.file>${basedir}/src/tests/resources/java.policy</policy.file>
-         <surefire.jvm.args>-Djava.security.manager -Djava.security.policy=${policy.file} -Djava.security.debug=failure,access ${test.env}</surefire.jvm.args>
-      </properties>
-    </profile>
-   </profiles>
-   <build>
-      <finalName>${artifactId}</finalName>
-      <resources>
-         <resource>
-            <directory>src/main</directory>
-            <includes>
-               <include>**/*.xml</include>
-            </includes>
-         </resource>
-         <resource>
-            <directory>${basedir}</directory>
-            <includes>
-               <include>JBossORG-EULA.txt</include>
-            </includes>
-         </resource>
-         <resource>
-            <directory>src/resources</directory>
-            <includes>
-               <include>**/*.dtd</include>
-               <include>**/*.xsd</include>
-            </includes>
-         </resource>
-      </resources> 
-   </build>
-   <dependencies> 
-      <dependency>
-         <groupId>org.jboss.security</groupId>
-         <artifactId>jboss-security-spi</artifactId>
-         <scope>compile</scope>
-      </dependency>
-      <dependency>
-         <groupId>junit</groupId>
-         <artifactId>junit</artifactId>
-         <scope>test</scope>
-      </dependency>
-   </dependencies>
-</project>

Copied: projects/security/security-jboss-sx/tags/2.0.4.SP1/identity/pom.xml (from rev 93331, projects/security/security-jboss-sx/branches/Branch_2_0/identity/pom.xml)
===================================================================
--- projects/security/security-jboss-sx/tags/2.0.4.SP1/identity/pom.xml	                        (rev 0)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/identity/pom.xml	2009-09-09 20:59:49 UTC (rev 93332)
@@ -0,0 +1,86 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+   <parent>
+      <groupId>org.jboss.security</groupId>
+      <artifactId>jbosssx-parent</artifactId>
+      <version>2.0.4.SP1</version>
+   </parent>
+   <modelVersion>4.0.0</modelVersion>
+   <artifactId>identity-impl</artifactId>
+   <packaging>jar</packaging>
+   <name>JBoss Security Identity Implementation</name>
+   <url>http://labs.jboss.org/portal/jbosssecurity/</url>
+   <description>JBoss Security is a cross cutting project that handles security for the JEMS projects</description>
+   <licenses>
+      <license>
+         <name>lgpl</name>
+         <url>http://repository.jboss.com/licenses/lgpl.txt</url>
+      </license>
+   </licenses>
+   <organization>
+      <name>JBoss Inc.</name>
+      <url>http://www.jboss.org</url>
+   </organization>
+   <profiles>
+    <!--    mvn install -Psecurity-manager    -->
+    <profile>
+      <id>security-manager</id>
+      <activation>
+         <activeByDefault>false</activeByDefault>
+      </activation>
+      <properties>
+         <test.env>-Dtest.basedir=${basedir}/target/test-classes</test.env>
+         <policy.file>${basedir}/src/tests/resources/java.policy</policy.file>
+         <surefire.jvm.args>-Djava.security.manager -Djava.security.policy=${policy.file} ${test.env}</surefire.jvm.args>
+      </properties>
+    </profile>
+    <!--     mvn install -Psecurity-manager-debug   -->
+    <!-- Best Practice:    mvn install -Psecurity-manager-debug  2>&1 > logfile2>&1 > logfile -->
+    <profile>
+      <id>security-manager-debug</id>
+      <activation>
+         <activeByDefault>false</activeByDefault>
+      </activation>
+      <properties>
+         <test.env>-Dtest.basedir=${basedir}/target/test-classes</test.env>
+         <policy.file>${basedir}/src/tests/resources/java.policy</policy.file>
+         <surefire.jvm.args>-Djava.security.manager -Djava.security.policy=${policy.file} -Djava.security.debug=failure,access ${test.env}</surefire.jvm.args>
+      </properties>
+    </profile>
+   </profiles>
+   <build>
+      <finalName>${artifactId}</finalName>
+      <resources>
+         <resource>
+            <directory>src/main</directory>
+            <includes>
+               <include>**/*.xml</include>
+            </includes>
+         </resource>
+         <resource>
+            <directory>${basedir}</directory>
+            <includes>
+               <include>JBossORG-EULA.txt</include>
+            </includes>
+         </resource>
+         <resource>
+            <directory>src/resources</directory>
+            <includes>
+               <include>**/*.dtd</include>
+               <include>**/*.xsd</include>
+            </includes>
+         </resource>
+      </resources> 
+   </build>
+   <dependencies> 
+      <dependency>
+         <groupId>org.jboss.security</groupId>
+         <artifactId>jboss-security-spi</artifactId>
+         <scope>compile</scope>
+      </dependency>
+      <dependency>
+         <groupId>junit</groupId>
+         <artifactId>junit</artifactId>
+         <scope>test</scope>
+      </dependency>
+   </dependencies>
+</project>

Deleted: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/pom.xml
===================================================================
--- projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/pom.xml	2009-07-21 21:59:08 UTC (rev 91524)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/pom.xml	2009-09-09 20:59:49 UTC (rev 93332)
@@ -1,187 +0,0 @@
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
-   <parent>
-      <groupId>org.jboss.security</groupId>
-      <artifactId>jbosssx-parent</artifactId>
-      <version>2.0.3.SP2-SNAPSHOT</version>
-   </parent>
-   <modelVersion>4.0.0</modelVersion>
-   <artifactId>jbosssx-bare</artifactId>
-   <packaging>jar</packaging>
-   <name>JBoss Security Implementation for the JBAS</name>
-   <url>http://labs.jboss.org/portal/jbosssecurity/</url>
-   <description>JBoss Security is a cross cutting project that handles security for the JEMS projects</description>
-   <licenses>
-      <license>
-         <name>lgpl</name>
-         <url>http://repository.jboss.com/licenses/lgpl.txt</url>
-      </license>
-   </licenses>
-   <organization>
-      <name>JBoss Inc.</name>
-      <url>http://www.jboss.org</url>
-   </organization>
-   <profiles>
-    <!--    mvn install -Psecurity-manager    -->
-    <profile>
-      <id>security-manager</id>
-      <activation>
-         <activeByDefault>false</activeByDefault>
-      </activation>
-      <properties>
-         <test.env>-Dtest.basedir=${basedir}/target/test-classes</test.env>
-         <policy.file>${basedir}/src/tests/resources/java.policy</policy.file>
-         <surefire.jvm.args>-Djava.security.manager -Djava.security.policy=${policy.file} ${test.env}</surefire.jvm.args>
-      </properties>
-    </profile>
-    <!--     mvn install -Psecurity-manager-debug   -->
-    <!-- Best Practice:    mvn install -Psecurity-manager-debug  2>&1 > logfile2>&1 > logfile -->
-    <profile>
-      <id>security-manager-debug</id>
-      <activation>
-         <activeByDefault>false</activeByDefault>
-      </activation>
-      <properties>
-         <test.env>-Dtest.basedir=${basedir}/target/test-classes</test.env>
-         <policy.file>${basedir}/src/tests/resources/java.policy</policy.file>
-         <surefire.jvm.args>-Djava.security.manager -Djava.security.policy=${policy.file} -Djava.security.debug=policy,failure,access ${test.env}</surefire.jvm.args>
-      </properties>
-    </profile>
-    <profile>
-      <id>one-test</id>
-      <activation>
-         <activeByDefault>false</activeByDefault>
-      </activation>
-      <properties>
-         <surefire.jvm.args>-Xdebug -Xnoagent -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8686</surefire.jvm.args>
-      </properties>
-    </profile>
-   </profiles>
-
-   <build>
-      <finalName>${artifactId}</finalName>
-      <resources>
-         <resource>
-            <directory>src/main/java</directory>
-            <includes>
-               <include>**/*.xml</include>
-            </includes>
-         </resource>
-         <resource>
-            <directory>${basedir}</directory>
-            <includes>
-               <include>JBossORG-EULA.txt</include>
-            </includes>
-         </resource>
-         <resource>
-            <directory>src/resources</directory>
-            <includes>
-               <include>**/*.dtd</include>
-               <include>**/*.xsd</include>
-            </includes>
-         </resource>
-         <resource>
-            <directory>target/generated-sources/javacc</directory>
-            <includes>
-               <include>**/*.class</include>
-            </includes>
-         </resource> 
-      </resources> 
-      <plugins>
-         <!-- generate java files from grammar -->
-         <plugin>
-            <groupId>org.codehaus.mojo</groupId>
-            <artifactId>javacc-maven-plugin</artifactId>
-            <version>2.3-jboss-1</version>
-            <configuration>
-               <packageName>org/jboss/security/auth/login</packageName>
-               <sourceDirectory>src/main/java</sourceDirectory>
-               <isStatic>false</isStatic>
-            </configuration>
-            <executions>
-               <execution>
-                  <goals>
-                     <goal>javacc</goal>
-                  </goals>
-                  <id>javacc</id>
-               </execution>
-            </executions>
-         </plugin> 
-      </plugins>
-   </build>
-   <dependencies> 
-      <dependency>
-         <groupId>org.jboss.javaee</groupId>
-         <artifactId>jboss-jaspi-api</artifactId>
-         <scope>compile</scope>
-      </dependency>
-      <dependency>
-         <groupId>org.jboss</groupId>
-         <artifactId>jbossxb</artifactId>
-         <scope>compile</scope>
-      </dependency>
-      <dependency>
-         <groupId>org.jboss.security</groupId>
-         <artifactId>jboss-security-acl-impl</artifactId>
-         <version>${project.version}</version>
-         <scope>compile</scope>
-      </dependency>
-      <dependency>
-         <groupId>org.jboss.javaee</groupId>
-         <artifactId>jboss-javaee</artifactId>
-         <version>5.0.0.GA</version>
-         <scope>compile</scope>
-         <exclusions>
-           <exclusion>
-             <groupId>sun-jaxb</groupId>
-             <artifactId>jaxb-api</artifactId>
-           </exclusion>
-         </exclusions>
-      </dependency>
-      <dependency>
-         <groupId>jboss</groupId>
-         <artifactId>jboss-jmx</artifactId>
-         <version>4.2.1.GA</version>
-         <scope>compile</scope>
-      </dependency>
-      <dependency>
-         <groupId>org.jboss.security</groupId>
-         <artifactId>jbossxacml</artifactId>
-         <version>2.0.3.CR2</version>
-         <scope>compile</scope>
-      </dependency>
-      <dependency>
-         <groupId>sun-jaxb</groupId>
-         <artifactId>jaxb-impl</artifactId>
-         <version>2.1.9</version>
-         <scope>runtime</scope>
-      </dependency>
-      <dependency>
-         <groupId>stax</groupId>
-         <artifactId>stax-api</artifactId>
-         <version>1.0.1</version>
-      </dependency>
-      <dependency>
-         <groupId>org.jboss</groupId>
-         <artifactId>jnpserver</artifactId>
-         <version>4.2.3.GA</version>
-         <scope>test</scope>
-      </dependency>    
-      <dependency>
-         <groupId>org.jboss</groupId>
-         <artifactId>jboss-test</artifactId>
-         <scope>test</scope>
-      </dependency>    
-      <dependency>
-         <groupId>sun-opends</groupId>
-         <artifactId>OpenDS</artifactId>
-         <version>1.0.0</version>
-         <scope>test</scope>
-      </dependency>
-      <dependency>
-         <groupId>sleepycat</groupId>
-         <artifactId>je</artifactId>
-         <version>3.2.43</version>
-         <scope>test</scope>
-      </dependency>    
-   </dependencies>
-</project>

Copied: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/pom.xml (from rev 93331, projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/pom.xml)
===================================================================
--- projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/pom.xml	                        (rev 0)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/pom.xml	2009-09-09 20:59:49 UTC (rev 93332)
@@ -0,0 +1,187 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+   <parent>
+      <groupId>org.jboss.security</groupId>
+      <artifactId>jbosssx-parent</artifactId>
+      <version>2.0.4.SP1</version>
+   </parent>
+   <modelVersion>4.0.0</modelVersion>
+   <artifactId>jbosssx-bare</artifactId>
+   <packaging>jar</packaging>
+   <name>JBoss Security Implementation for the JBAS</name>
+   <url>http://labs.jboss.org/portal/jbosssecurity/</url>
+   <description>JBoss Security is a cross cutting project that handles security for the JEMS projects</description>
+   <licenses>
+      <license>
+         <name>lgpl</name>
+         <url>http://repository.jboss.com/licenses/lgpl.txt</url>
+      </license>
+   </licenses>
+   <organization>
+      <name>JBoss Inc.</name>
+      <url>http://www.jboss.org</url>
+   </organization>
+   <profiles>
+    <!--    mvn install -Psecurity-manager    -->
+    <profile>
+      <id>security-manager</id>
+      <activation>
+         <activeByDefault>false</activeByDefault>
+      </activation>
+      <properties>
+         <test.env>-Dtest.basedir=${basedir}/target/test-classes</test.env>
+         <policy.file>${basedir}/src/tests/resources/java.policy</policy.file>
+         <surefire.jvm.args>-Djava.security.manager -Djava.security.policy=${policy.file} ${test.env}</surefire.jvm.args>
+      </properties>
+    </profile>
+    <!--     mvn install -Psecurity-manager-debug   -->
+    <!-- Best Practice:    mvn install -Psecurity-manager-debug  2>&1 > logfile2>&1 > logfile -->
+    <profile>
+      <id>security-manager-debug</id>
+      <activation>
+         <activeByDefault>false</activeByDefault>
+      </activation>
+      <properties>
+         <test.env>-Dtest.basedir=${basedir}/target/test-classes</test.env>
+         <policy.file>${basedir}/src/tests/resources/java.policy</policy.file>
+         <surefire.jvm.args>-Djava.security.manager -Djava.security.policy=${policy.file} -Djava.security.debug=policy,failure,access ${test.env}</surefire.jvm.args>
+      </properties>
+    </profile>
+    <profile>
+      <id>one-test</id>
+      <activation>
+         <activeByDefault>false</activeByDefault>
+      </activation>
+      <properties>
+         <surefire.jvm.args>-Xdebug -Xnoagent -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8686</surefire.jvm.args>
+      </properties>
+    </profile>
+   </profiles>
+
+   <build>
+      <finalName>${artifactId}</finalName>
+      <resources>
+         <resource>
+            <directory>src/main/java</directory>
+            <includes>
+               <include>**/*.xml</include>
+            </includes>
+         </resource>
+         <resource>
+            <directory>${basedir}</directory>
+            <includes>
+               <include>JBossORG-EULA.txt</include>
+            </includes>
+         </resource>
+         <resource>
+            <directory>src/resources</directory>
+            <includes>
+               <include>**/*.dtd</include>
+               <include>**/*.xsd</include>
+            </includes>
+         </resource>
+         <resource>
+            <directory>target/generated-sources/javacc</directory>
+            <includes>
+               <include>**/*.class</include>
+            </includes>
+         </resource> 
+      </resources> 
+      <plugins>
+         <!-- generate java files from grammar -->
+         <plugin>
+            <groupId>org.codehaus.mojo</groupId>
+            <artifactId>javacc-maven-plugin</artifactId>
+            <version>2.3-jboss-1</version>
+            <configuration>
+               <packageName>org/jboss/security/auth/login</packageName>
+               <sourceDirectory>src/main/java</sourceDirectory>
+               <isStatic>false</isStatic>
+            </configuration>
+            <executions>
+               <execution>
+                  <goals>
+                     <goal>javacc</goal>
+                  </goals>
+                  <id>javacc</id>
+               </execution>
+            </executions>
+         </plugin> 
+      </plugins>
+   </build>
+   <dependencies> 
+      <dependency>
+         <groupId>org.jboss.javaee</groupId>
+         <artifactId>jboss-jaspi-api</artifactId>
+         <scope>compile</scope>
+      </dependency>
+      <dependency>
+         <groupId>org.jboss</groupId>
+         <artifactId>jbossxb</artifactId>
+         <scope>compile</scope>
+      </dependency>
+      <dependency>
+         <groupId>org.jboss.security</groupId>
+         <artifactId>jboss-security-acl-impl</artifactId>
+         <version>${project.version}</version>
+         <scope>compile</scope>
+      </dependency>
+      <dependency>
+         <groupId>org.jboss.javaee</groupId>
+         <artifactId>jboss-javaee</artifactId>
+         <version>5.0.0.GA</version>
+         <scope>compile</scope>
+         <exclusions>
+           <exclusion>
+             <groupId>sun-jaxb</groupId>
+             <artifactId>jaxb-api</artifactId>
+           </exclusion>
+         </exclusions>
+      </dependency>
+      <dependency>
+         <groupId>jboss</groupId>
+         <artifactId>jboss-jmx</artifactId>
+         <version>4.2.1.GA</version>
+         <scope>compile</scope>
+      </dependency>
+      <dependency>
+         <groupId>org.jboss.security</groupId>
+         <artifactId>jbossxacml</artifactId>
+         <version>2.0.3.CR2</version>
+         <scope>compile</scope>
+      </dependency>
+      <dependency>
+         <groupId>sun-jaxb</groupId>
+         <artifactId>jaxb-impl</artifactId>
+         <version>2.1.9</version>
+         <scope>runtime</scope>
+      </dependency>
+      <dependency>
+         <groupId>stax</groupId>
+         <artifactId>stax-api</artifactId>
+         <version>1.0.1</version>
+      </dependency>
+      <dependency>
+         <groupId>org.jboss</groupId>
+         <artifactId>jnpserver</artifactId>
+         <version>4.2.3.GA</version>
+         <scope>test</scope>
+      </dependency>    
+      <dependency>
+         <groupId>org.jboss</groupId>
+         <artifactId>jboss-test</artifactId>
+         <scope>test</scope>
+      </dependency>    
+      <dependency>
+         <groupId>sun-opends</groupId>
+         <artifactId>OpenDS</artifactId>
+         <version>1.0.0</version>
+         <scope>test</scope>
+      </dependency>
+      <dependency>
+         <groupId>sleepycat</groupId>
+         <artifactId>je</artifactId>
+         <version>3.2.43</version>
+         <scope>test</scope>
+      </dependency>    
+   </dependencies>
+</project>

Deleted: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/resource/security/CallerIdentityLoginModule.java
===================================================================
--- projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/resource/security/CallerIdentityLoginModule.java	2009-07-21 21:59:08 UTC (rev 91524)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/resource/security/CallerIdentityLoginModule.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -1,216 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * Copyright 2006, Red Hat Middleware LLC, and individual contributors
- * as indicated by the @author tags. See the copyright.txt file in the
- * distribution for a full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jboss.resource.security;
-
-import java.security.Principal;
-import java.security.acl.Group;
-import java.util.Map;
-import java.util.Set;
-
-import javax.resource.spi.security.PasswordCredential;
-import javax.security.auth.Subject;
-import javax.security.auth.callback.CallbackHandler;
-import javax.security.auth.login.LoginException;
-
-import org.jboss.logging.Logger;
-import org.jboss.security.RunAsIdentity;
-import org.jboss.security.SimplePrincipal;
-
-/**
- * A simple login module that simply associates the principal making the
- * connection request with the actual EIS connection requirements.
- *
- * The type of Principal class used is
- * <code>org.jboss.security.SimplePrincipal.</code>
- * <p>
- *
- * @see org.jboss.resource.security.ConfiguredIdentityLoginModule
- *
- * @author Scott.Stark at jboss.org
- * @author <a href="mailto:d_jencks at users.sourceforge.net">David Jencks</a>
- * @author <a href="mailto:dan.bunker at pbs.proquest.com">Dan Bunker</a>
- * @version $Revision: 71545 $
- */
-
- at SuppressWarnings("unchecked")
-public class CallerIdentityLoginModule
-   extends AbstractPasswordCredentialLoginModule
-{
-   /**
-    * Class logger
-    */
-   private static final Logger log = Logger.getLogger(CallerIdentityLoginModule.class);
-
-   /**
-    * The default username/principal to use for basic connections
-    */
-   private String userName;
-
-   /**
-    * The default password to use for basic connections
-    */
-   private char[] password;
-   /** A flag indicating if the run-as principal roles should be added to the subject */
-   private boolean addRunAsRoles;
-   private Set runAsRoles;
-
-   /**
-    * Default Constructor
-    */
-   public CallerIdentityLoginModule()
-   {
-   }
-
-   /**
-    * The initialize method sets up some default connection information for
-    * basic connections.  This is useful for container initialization connection
-    * use or running the application in a non-secure manner.  This method is
-    * called before the login method.
-    *
-    * @param subject
-    * @param handler
-    * @param sharedState
-    * @param options
-    */
-   public void initialize(Subject subject, CallbackHandler handler,
-      Map sharedState, Map options)
-   {
-      super.initialize(subject, handler, sharedState, options);
-
-      userName = (String) options.get("userName");
-      if (userName == null)
-      {
-         log.debug("No default username supplied.");
-      }
-
-      String pass = (String) options.get("password");
-      if (pass == null)
-      {
-         log.debug("No default password supplied.");
-      }
-      else
-      {
-         password = pass.toCharArray();
-      }
-
-      // Check the addRunAsRoles
-      String flag = (String) options.get("addRunAsRoles");
-      addRunAsRoles = Boolean.valueOf(flag).booleanValue();
-
-      log.debug("got default principal: " + userName + ", username: "
-         + userName + ", password: " + (password == null ? "null" : "****")
-         + " addRunAsRoles: "+addRunAsRoles);
-
-   }
-
-   /**
-    * Performs the login association between the caller and the resource for a
-    * 1 to 1 mapping.  This acts as a login propagation strategy and is useful
-    * for single-sign on requirements
-    *
-    * @return True if authentication succeeds
-    * @throws LoginException
-    */
-   public boolean login() throws LoginException
-   {
-      log.trace("Caller Association login called");
-
-      //setup to use the default connection info.  This will be overiden if security
-      //associations are found
-      String username = userName;
-
-      //ask the security association class for the principal info making this request
-      try
-      {
-         Principal user = GetPrincipalInfoAction.getPrincipal();
-         char[] userPassword = GetPrincipalInfoAction.getCredential();
-
-         if( userPassword != null )
-         {
-            password = userPassword;
-         }
-
-         if (user != null)
-         {
-            username = user.getName();
-            if (log.isTraceEnabled())
-            {
-               log.trace("Current Calling principal is: " + username
-                  + " ThreadName: " + Thread.currentThread().getName());
-            }
-            // Check for a RunAsIdentity
-            RunAsIdentity runAs = GetPrincipalInfoAction.peekRunAsIdentity();
-            if( runAs != null )
-            {
-               runAsRoles = runAs.getRunAsRoles();
-            }
-         }
-      }
-      catch (Throwable e)
-      {
-         throw new LoginException("Unable to get the calling principal or its credentials for resource association");
-      }
-
-      // Update userName so that getIdentity is consistent
-      userName = username;
-      if (super.login() == true)
-      {
-         return true;
-      }
-
-      // Put the principal name into the sharedState map
-      sharedState.put("javax.security.auth.login.name", username);
-      super.loginOk = true;
-
-      return true;
-   }
-
-   public boolean commit() throws LoginException
-   {
-      // Put the principal name into the sharedState map
-      sharedState.put("javax.security.auth.login.name", userName);
-      // Add any run-as roles if addRunAsRoles is true
-      if( addRunAsRoles && runAsRoles != null )
-      {
-         SubjectActions.addRoles(subject, runAsRoles);         
-      }
-
-      // Add the PasswordCredential
-      PasswordCredential cred = new PasswordCredential(userName, password);
-      cred.setManagedConnectionFactory(getMcf());
-      SubjectActions.addCredentials(subject, cred);
-      return super.commit();
-   }
-
-   protected Principal getIdentity()
-   {
-      log.trace("getIdentity called");
-      Principal principal = new SimplePrincipal(userName);
-      return principal;
-   }
-
-   protected Group[] getRoleSets() throws LoginException
-   {
-      log.trace("getRoleSets called");
-      return new Group[]{};
-   }
-}

Copied: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/resource/security/CallerIdentityLoginModule.java (from rev 93325, projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/resource/security/CallerIdentityLoginModule.java)
===================================================================
--- projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/resource/security/CallerIdentityLoginModule.java	                        (rev 0)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/resource/security/CallerIdentityLoginModule.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -0,0 +1,221 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2006, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.resource.security;
+
+import java.security.Principal;
+import java.security.acl.Group;
+import java.util.Map;
+import java.util.Set;
+
+import javax.resource.spi.security.PasswordCredential;
+import javax.security.auth.Subject;
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.login.LoginException;
+
+import org.jboss.logging.Logger;
+import org.jboss.security.RunAsIdentity;
+import org.jboss.security.SimplePrincipal;
+
+/**
+ * A simple login module that simply associates the principal making the
+ * connection request with the actual EIS connection requirements.
+ *
+ * The type of Principal class used is
+ * <code>org.jboss.security.SimplePrincipal.</code>
+ * <p>
+ *
+ * @see org.jboss.resource.security.ConfiguredIdentityLoginModule
+ *
+ * @author Scott.Stark at jboss.org
+ * @author <a href="mailto:d_jencks at users.sourceforge.net">David Jencks</a>
+ * @author <a href="mailto:dan.bunker at pbs.proquest.com">Dan Bunker</a>
+ * @version $Revision: 71545 $
+ */
+
+ at SuppressWarnings("unchecked")
+public class CallerIdentityLoginModule
+   extends AbstractPasswordCredentialLoginModule
+{
+   /**
+    * Class logger
+    */
+   private static final Logger log = Logger.getLogger(CallerIdentityLoginModule.class);
+
+   private boolean trace = log.isTraceEnabled();
+   
+   /**
+    * The default username/principal to use for basic connections
+    */
+   private String userName;
+
+   /**
+    * The default password to use for basic connections
+    */
+   private char[] password;
+   /** A flag indicating if the run-as principal roles should be added to the subject */
+   private boolean addRunAsRoles;
+   private Set runAsRoles;
+
+   /**
+    * Default Constructor
+    */
+   public CallerIdentityLoginModule()
+   {
+   }
+
+   /**
+    * The initialize method sets up some default connection information for
+    * basic connections.  This is useful for container initialization connection
+    * use or running the application in a non-secure manner.  This method is
+    * called before the login method.
+    *
+    * @param subject
+    * @param handler
+    * @param sharedState
+    * @param options
+    */
+   public void initialize(Subject subject, CallbackHandler handler,
+      Map sharedState, Map options)
+   {
+      super.initialize(subject, handler, sharedState, options);
+
+      userName = (String) options.get("userName");
+      if (userName == null)
+      {
+         log.debug("No default username supplied.");
+      }
+
+      String pass = (String) options.get("password");
+      if (pass == null)
+      {
+         log.debug("No default password supplied.");
+      }
+      else
+      {
+         password = pass.toCharArray();
+      }
+
+      // Check the addRunAsRoles
+      String flag = (String) options.get("addRunAsRoles");
+      addRunAsRoles = Boolean.valueOf(flag).booleanValue();
+
+      log.debug("got default principal: " + userName + ", username: "
+         + userName + ", password: " + (password == null ? "null" : "****")
+         + " addRunAsRoles: "+addRunAsRoles);
+
+   }
+
+   /**
+    * Performs the login association between the caller and the resource for a
+    * 1 to 1 mapping.  This acts as a login propagation strategy and is useful
+    * for single-sign on requirements
+    *
+    * @return True if authentication succeeds
+    * @throws LoginException
+    */
+   public boolean login() throws LoginException
+   {
+      if(trace)
+         log.trace("Caller Association login called");
+
+      //setup to use the default connection info.  This will be overiden if security
+      //associations are found
+      String username = userName;
+
+      //ask the security association class for the principal info making this request
+      try
+      {
+         Principal user = GetPrincipalInfoAction.getPrincipal();
+         char[] userPassword = GetPrincipalInfoAction.getCredential();
+
+         if( userPassword != null )
+         {
+            password = userPassword;
+         }
+
+         if (user != null)
+         {
+            username = user.getName();
+            if (trace)
+            {
+               log.trace("Current Calling principal is: " + username
+                  + " ThreadName: " + Thread.currentThread().getName());
+            }
+            // Check for a RunAsIdentity
+            RunAsIdentity runAs = GetPrincipalInfoAction.peekRunAsIdentity();
+            if( runAs != null )
+            {
+               runAsRoles = runAs.getRunAsRoles();
+            }
+         }
+      }
+      catch (Throwable e)
+      {
+         throw new LoginException("Unable to get the calling principal or its credentials for resource association");
+      }
+
+      // Update userName so that getIdentity is consistent
+      userName = username;
+      if (super.login() == true)
+      {
+         return true;
+      }
+
+      // Put the principal name into the sharedState map
+      sharedState.put("javax.security.auth.login.name", username);
+      super.loginOk = true;
+
+      return true;
+   }
+
+   public boolean commit() throws LoginException
+   {
+      // Put the principal name into the sharedState map
+      sharedState.put("javax.security.auth.login.name", userName);
+      // Add any run-as roles if addRunAsRoles is true
+      if( addRunAsRoles && runAsRoles != null )
+      {
+         SubjectActions.addRoles(subject, runAsRoles);         
+      }
+
+      // Add the PasswordCredential
+      PasswordCredential cred = new PasswordCredential(userName, password);
+      cred.setManagedConnectionFactory(getMcf());
+      SubjectActions.addCredentials(subject, cred);
+      return super.commit();
+   }
+
+   protected Principal getIdentity()
+   {
+      if(trace)
+         log.trace("getIdentity called");
+      Principal principal = new SimplePrincipal(userName);
+      return principal;
+   }
+
+   protected Group[] getRoleSets() throws LoginException
+   {
+      if(trace)
+         log.trace("getRoleSets called");
+      return new Group[]{};
+   }
+}

Deleted: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/resource/security/ConfiguredIdentityLoginModule.java
===================================================================
--- projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/resource/security/ConfiguredIdentityLoginModule.java	2009-07-21 21:59:08 UTC (rev 91524)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/resource/security/ConfiguredIdentityLoginModule.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -1,124 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * Copyright 2006, Red Hat Middleware LLC, and individual contributors
- * as indicated by the @author tags. See the copyright.txt file in the
- * distribution for a full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jboss.resource.security;
-
-
-import java.security.Principal;
-import java.security.acl.Group;
-import java.util.Map;
-
-import javax.resource.spi.security.PasswordCredential;
-import javax.security.auth.Subject;
-import javax.security.auth.callback.CallbackHandler;
-import javax.security.auth.login.LoginException;
-
-import org.jboss.logging.Logger;
-import org.jboss.security.SimplePrincipal;
-
-/**
- * A simple login module that simply associates the principal specified
- * in the module options with any subject authenticated against the module.
- * The type of Principal class used is
- * <code>org.jboss.security.SimplePrincipal.</code>
- * <p>
- * If no principal option is specified a principal with the name of 'guest'
- * is used.
- *
- * @see org.jboss.security.SimpleGroup
- * @see org.jboss.security.SimplePrincipal
- *
- * @author Scott.Stark at jboss.org
- * @author <a href="mailto:d_jencks at users.sourceforge.net">David Jencks</a>
- * @version $Revision: 71545 $
- */
-
- at SuppressWarnings("unchecked")
-public class ConfiguredIdentityLoginModule extends AbstractPasswordCredentialLoginModule
-{
-   private String principalName;
-   private String userName;
-   private String password;
-
-   private static final Logger log = Logger.getLogger(ConfiguredIdentityLoginModule.class);
-
-
-   public ConfiguredIdentityLoginModule()
-   {
-   }
-
-   public void initialize(Subject subject, CallbackHandler handler, Map sharedState, Map options)
-   {
-      super.initialize(subject, handler, sharedState, options);
-      principalName = (String) options.get("principal");
-      if( principalName == null )
-      {
-         throw new IllegalArgumentException("Must supply a principal name!");
-      }
-      userName = (String) options.get("userName");
-      if( userName == null )
-      {
-         throw new IllegalArgumentException("Must supply a user name!");
-      }
-      password = (String) options.get("password");
-      if( password == null )
-      {
-         log.warn("Creating LoginModule with no configured password!");
-         password = "";
-      }
-      log.trace("got principal: " + principalName + ", username: " + userName + ", password: " + password);
-
-   }
-
-   public boolean login() throws LoginException
-   {
-      log.trace("login called");
-      if( super.login() == true )
-         return true;
-
-      Principal principal = new SimplePrincipal(principalName);
-      SubjectActions.addPrincipals(subject, principal);
-      // Put the principal name into the sharedState map
-      sharedState.put("javax.security.auth.login.name", principalName);
-      PasswordCredential cred = new PasswordCredential(userName, password.toCharArray());
-      cred.setManagedConnectionFactory(getMcf());
-      SubjectActions.addCredentials(subject, cred);
-      super.loginOk = true;
-      return true;
-   }
-
-   protected Principal getIdentity()
-   {
-      log.trace("getIdentity called");
-      Principal principal = new SimplePrincipal(principalName);
-      return principal;
-   }
-
-   /** This method simply returns an empty array of Groups which means that
-   no role based permissions are assigned.
-   */
-   protected Group[] getRoleSets() throws LoginException
-   {
-      log.trace("getRoleSets called");
-      return new Group[] {};
-   }
-   
-}

Copied: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/resource/security/ConfiguredIdentityLoginModule.java (from rev 93325, projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/resource/security/ConfiguredIdentityLoginModule.java)
===================================================================
--- projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/resource/security/ConfiguredIdentityLoginModule.java	                        (rev 0)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/resource/security/ConfiguredIdentityLoginModule.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -0,0 +1,129 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2006, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.resource.security;
+
+
+import java.security.Principal;
+import java.security.acl.Group;
+import java.util.Map;
+
+import javax.resource.spi.security.PasswordCredential;
+import javax.security.auth.Subject;
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.login.LoginException;
+
+import org.jboss.logging.Logger;
+import org.jboss.security.SimplePrincipal;
+
+/**
+ * A simple login module that simply associates the principal specified
+ * in the module options with any subject authenticated against the module.
+ * The type of Principal class used is
+ * <code>org.jboss.security.SimplePrincipal.</code>
+ * <p>
+ * If no principal option is specified a principal with the name of 'guest'
+ * is used.
+ *
+ * @see org.jboss.security.SimpleGroup
+ * @see org.jboss.security.SimplePrincipal
+ *
+ * @author Scott.Stark at jboss.org
+ * @author <a href="mailto:d_jencks at users.sourceforge.net">David Jencks</a>
+ * @version $Revision: 71545 $
+ */
+
+ at SuppressWarnings("unchecked")
+public class ConfiguredIdentityLoginModule extends AbstractPasswordCredentialLoginModule
+{
+   private String principalName;
+   private String userName;
+   private String password;
+
+   private static final Logger log = Logger.getLogger(ConfiguredIdentityLoginModule.class);
+   private boolean trace = log.isTraceEnabled();
+
+
+   public ConfiguredIdentityLoginModule()
+   {
+   }
+
+   public void initialize(Subject subject, CallbackHandler handler, Map sharedState, Map options)
+   {
+      super.initialize(subject, handler, sharedState, options);
+      principalName = (String) options.get("principal");
+      if( principalName == null )
+      {
+         throw new IllegalArgumentException("Must supply a principal name!");
+      }
+      userName = (String) options.get("userName");
+      if( userName == null )
+      {
+         throw new IllegalArgumentException("Must supply a user name!");
+      }
+      password = (String) options.get("password");
+      if( password == null )
+      {
+         log.warn("Creating LoginModule with no configured password!");
+         password = "";
+      }
+      if(trace)
+         log.trace("got principal: " + principalName + ", username: " + userName + ", password: " + password);
+
+   }
+
+   public boolean login() throws LoginException
+   {
+      if(trace)
+         log.trace("login called");
+      if( super.login() == true )
+         return true;
+
+      Principal principal = new SimplePrincipal(principalName);
+      SubjectActions.addPrincipals(subject, principal);
+      // Put the principal name into the sharedState map
+      sharedState.put("javax.security.auth.login.name", principalName);
+      PasswordCredential cred = new PasswordCredential(userName, password.toCharArray());
+      cred.setManagedConnectionFactory(getMcf());
+      SubjectActions.addCredentials(subject, cred);
+      super.loginOk = true;
+      return true;
+   }
+
+   protected Principal getIdentity()
+   {
+      if(trace)
+         log.trace("getIdentity called");
+      Principal principal = new SimplePrincipal(principalName);
+      return principal;
+   }
+
+   /** This method simply returns an empty array of Groups which means that
+   no role based permissions are assigned.
+   */
+   protected Group[] getRoleSets() throws LoginException
+   {
+      if(trace)
+         log.trace("getRoleSets called");
+      return new Group[] {};
+   }
+   
+}
\ No newline at end of file

Deleted: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/resource/security/JaasSecurityDomainIdentityLoginModule.java
===================================================================
--- projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/resource/security/JaasSecurityDomainIdentityLoginModule.java	2009-07-21 21:59:08 UTC (rev 91524)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/resource/security/JaasSecurityDomainIdentityLoginModule.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -1,227 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * Copyright 2006, Red Hat Middleware LLC, and individual contributors
- * as indicated by the @author tags. See the copyright.txt file in the
- * distribution for a full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jboss.resource.security;
-
-import java.security.AccessController;
-import java.security.Principal;
-import java.security.PrivilegedActionException;
-import java.security.PrivilegedExceptionAction;
-import java.security.acl.Group;
-import java.util.Map;
-
-import javax.management.MBeanServer;
-import javax.management.ObjectName;
-import javax.resource.spi.security.PasswordCredential;
-import javax.security.auth.Subject;
-import javax.security.auth.callback.CallbackHandler;
-import javax.security.auth.login.LoginException;
-
-import org.jboss.logging.Logger;
-import org.jboss.security.SimplePrincipal;
-
-/** A login module for statically defining a data source username and password
- that uses a password that has been ecrypted by a JaasSecurityDomain. The
- base64 format of the data source password may be generated using the PBEUtils
- command:
- 
- java -cp jbosssx.jar org.jboss.security.plugins.PBEUtils salt count
-   domain-password data-source-password
-
- salt : the Salt attribute from the JaasSecurityDomain
- count : the IterationCount attribute from the JaasSecurityDomain
- domain-password : the plaintext password that maps to the KeyStorePass
-   attribute from the JaasSecurityDomain
- data-source-password : the plaintext password for the data source that
-   should be encrypted with the JaasSecurityDomain password
-
- for example:
-
- java -cp jbosssx.jar org.jboss.security.plugins.PBEUtils abcdefgh 13 master ''
- Encoded password: E5gtGMKcXPP
-
- A sample login-config.xml configuration entry would be:
- 
- <application-policy name = "EncryptedHsqlDbRealm">
-    <authentication>
-       <login-module code = "org.jboss.resource.security.JaasSecurityDomainIdentityLoginModule"
-       flag = "required">
-          <module-option name = "userName">sa</module-option>
-          <module-option name = "password">E5gtGMKcXPP</module-option>
-          <module-option name = "managedConnectionFactoryName">jboss.jca:service=LocalTxCM,name=DefaultDS</module-option>
-          <module-option name = "jaasSecurityDomain">jboss.security:service=JaasSecurityDomain,domain=ServerMasterPassword</module-option>
-       </login-module>
-    </authentication>
- </application-policy>
-
-
- @author Scott.Stark at jboss.org
- @author <a href="mailto:noel.rocher at jboss.org">Noel Rocher</a> 29, june 2004 username & userName issue
- @version $Revision: 71545 $
- */
-
- at SuppressWarnings("unchecked")
-public class JaasSecurityDomainIdentityLoginModule
-   extends AbstractPasswordCredentialLoginModule
-{
-   private static final Logger log = Logger.getLogger(JaasSecurityDomainIdentityLoginModule.class);
-
-   private String username;
-   private String password;
-   private ObjectName jaasSecurityDomain;
-
-   public void initialize(Subject subject, CallbackHandler handler,
-      Map sharedState, Map options)
-   {
-      super.initialize(subject, handler, sharedState, options);
-      // NR : we keep this username for compatibility
-      username = (String) options.get("username");
-      if( username == null )
-      {
-      	// NR : try with userName
-        username = (String) options.get("userName");      	
-        if( username == null )
-        {
-         throw new IllegalArgumentException("The user name is a required option");
-        }
-     }
-
-      password = (String) options.get("password");
-      if( password == null )
-      {
-         throw new IllegalArgumentException("The password is a required option");
-      }
-
-      String name = (String) options.get("jaasSecurityDomain");
-      if( name == null )
-      {
-         throw new IllegalArgumentException("The jaasSecurityDomain is a required option");
-      }
-
-      try
-      {
-         jaasSecurityDomain = new ObjectName(name);
-      }
-      catch(Exception e)
-      {
-         throw new IllegalArgumentException("Invalid jaasSecurityDomain: " + e.getMessage());
-      }
-   }
-
-   public boolean login() throws LoginException
-   {
-      log.trace("login called");
-      if( super.login() == true )
-         return true;
-
-      super.loginOk = true;
-      return true;
-   }
-
-   public boolean commit() throws LoginException
-   {
-      Principal principal = new SimplePrincipal(username);
-      SubjectActions.addPrincipals(subject, principal);
-      sharedState.put("javax.security.auth.login.name", username);
-      // Decode the encrypted password
-      try
-      {
-         char[] decodedPassword = DecodeAction.decode(password,
-            jaasSecurityDomain, getServer());
-         PasswordCredential cred = new PasswordCredential(username, decodedPassword);
-         cred.setManagedConnectionFactory(getMcf());
-         SubjectActions.addCredentials(subject, cred);
-      }
-      catch(Exception e)
-      {
-         log.debug("Failed to decode password", e);
-         throw new LoginException("Failed to decode password: " + e.getMessage());
-      }
-      return true;
-   }
-
-   public boolean abort()
-   {
-      username = null;
-      password = null;
-      return true;
-   }
-
-   protected Principal getIdentity()
-   {
-      log.trace("getIdentity called, username=" + username);
-      Principal principal = new SimplePrincipal(username);
-      return principal;
-   }
-
-   protected Group[] getRoleSets() throws LoginException
-   {
-      Group[] empty = new Group[0];
-      return empty;
-   }
-
-   private static class DecodeAction implements PrivilegedExceptionAction
-   {
-      String password;
-      ObjectName jaasSecurityDomain;
-      MBeanServer server;
-      
-      DecodeAction(String password, ObjectName jaasSecurityDomain,
-         MBeanServer server)
-      {
-         this.password = password;
-         this.jaasSecurityDomain = jaasSecurityDomain;
-         this.server = server;
-      }
-
-      /**
-       * 
-       * @return
-       * @throws Exception
-       */ 
-      public Object run() throws Exception
-      {
-         // Invoke the jaasSecurityDomain.decodeb64 op
-         Object[] args = {password};
-         String[] sig = {String.class.getName()};
-         byte[] secret = (byte[]) server.invoke(jaasSecurityDomain,
-            "decode64", args, sig);
-         // Convert to UTF-8 base char array
-         String secretPassword = new String(secret, "UTF-8");
-         return secretPassword.toCharArray();
-      }
-      static char[] decode(String password, ObjectName jaasSecurityDomain,
-         MBeanServer server)
-         throws Exception
-      {
-         DecodeAction action = new DecodeAction(password, jaasSecurityDomain, server);
-         try
-         {
-            char[] decode = (char[]) AccessController.doPrivileged(action);
-            return decode;
-         }
-         catch(PrivilegedActionException e)
-         {
-            throw e.getException();
-         }
-      }
-   }
-}

Copied: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/resource/security/JaasSecurityDomainIdentityLoginModule.java (from rev 93325, projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/resource/security/JaasSecurityDomainIdentityLoginModule.java)
===================================================================
--- projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/resource/security/JaasSecurityDomainIdentityLoginModule.java	                        (rev 0)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/resource/security/JaasSecurityDomainIdentityLoginModule.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -0,0 +1,231 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2006, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.resource.security;
+
+import java.security.AccessController;
+import java.security.Principal;
+import java.security.PrivilegedActionException;
+import java.security.PrivilegedExceptionAction;
+import java.security.acl.Group;
+import java.util.Map;
+
+import javax.management.MBeanServer;
+import javax.management.ObjectName;
+import javax.resource.spi.security.PasswordCredential;
+import javax.security.auth.Subject;
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.login.LoginException;
+
+import org.jboss.logging.Logger;
+import org.jboss.security.SimplePrincipal;
+
+/** A login module for statically defining a data source username and password
+ that uses a password that has been ecrypted by a JaasSecurityDomain. The
+ base64 format of the data source password may be generated using the PBEUtils
+ command:
+ 
+ java -cp jbosssx.jar org.jboss.security.plugins.PBEUtils salt count
+   domain-password data-source-password
+
+ salt : the Salt attribute from the JaasSecurityDomain
+ count : the IterationCount attribute from the JaasSecurityDomain
+ domain-password : the plaintext password that maps to the KeyStorePass
+   attribute from the JaasSecurityDomain
+ data-source-password : the plaintext password for the data source that
+   should be encrypted with the JaasSecurityDomain password
+
+ for example:
+
+ java -cp jbosssx.jar org.jboss.security.plugins.PBEUtils abcdefgh 13 master ''
+ Encoded password: E5gtGMKcXPP
+
+ A sample login-config.xml configuration entry would be:
+ 
+ <application-policy name = "EncryptedHsqlDbRealm">
+    <authentication>
+       <login-module code = "org.jboss.resource.security.JaasSecurityDomainIdentityLoginModule"
+       flag = "required">
+          <module-option name = "userName">sa</module-option>
+          <module-option name = "password">E5gtGMKcXPP</module-option>
+          <module-option name = "managedConnectionFactoryName">jboss.jca:service=LocalTxCM,name=DefaultDS</module-option>
+          <module-option name = "jaasSecurityDomain">jboss.security:service=JaasSecurityDomain,domain=ServerMasterPassword</module-option>
+       </login-module>
+    </authentication>
+ </application-policy>
+
+
+ @author Scott.Stark at jboss.org
+ @author <a href="mailto:noel.rocher at jboss.org">Noel Rocher</a> 29, june 2004 username & userName issue
+ @version $Revision: 71545 $
+ */
+
+ at SuppressWarnings("unchecked")
+public class JaasSecurityDomainIdentityLoginModule
+   extends AbstractPasswordCredentialLoginModule
+{
+   private static final Logger log = Logger.getLogger(JaasSecurityDomainIdentityLoginModule.class);
+   private boolean trace = log.isTraceEnabled();
+   
+   private String username;
+   private String password;
+   private ObjectName jaasSecurityDomain;
+
+   public void initialize(Subject subject, CallbackHandler handler,
+      Map sharedState, Map options)
+   {
+      super.initialize(subject, handler, sharedState, options);
+      // NR : we keep this username for compatibility
+      username = (String) options.get("username");
+      if( username == null )
+      {
+      	// NR : try with userName
+        username = (String) options.get("userName");      	
+        if( username == null )
+        {
+         throw new IllegalArgumentException("The user name is a required option");
+        }
+     }
+
+      password = (String) options.get("password");
+      if( password == null )
+      {
+         throw new IllegalArgumentException("The password is a required option");
+      }
+
+      String name = (String) options.get("jaasSecurityDomain");
+      if( name == null )
+      {
+         throw new IllegalArgumentException("The jaasSecurityDomain is a required option");
+      }
+
+      try
+      {
+         jaasSecurityDomain = new ObjectName(name);
+      }
+      catch(Exception e)
+      {
+         throw new IllegalArgumentException("Invalid jaasSecurityDomain: " + e.getMessage());
+      }
+   }
+
+   public boolean login() throws LoginException
+   {
+      if(trace)
+         log.trace("login called");
+      if( super.login() == true )
+         return true;
+
+      super.loginOk = true;
+      return true;
+   }
+
+   public boolean commit() throws LoginException
+   {
+      Principal principal = new SimplePrincipal(username);
+      SubjectActions.addPrincipals(subject, principal);
+      sharedState.put("javax.security.auth.login.name", username);
+      // Decode the encrypted password
+      try
+      {
+         char[] decodedPassword = DecodeAction.decode(password,
+            jaasSecurityDomain, getServer());
+         PasswordCredential cred = new PasswordCredential(username, decodedPassword);
+         cred.setManagedConnectionFactory(getMcf());
+         SubjectActions.addCredentials(subject, cred);
+      }
+      catch(Exception e)
+      {
+         if(trace)
+            log.trace("Failed to decode password", e);
+         throw new LoginException("Failed to decode password: " + e.getMessage());
+      }
+      return true;
+   }
+
+   public boolean abort()
+   {
+      username = null;
+      password = null;
+      return true;
+   }
+
+   protected Principal getIdentity()
+   {
+      if(trace)
+         log.trace("getIdentity called, username=" + username);
+      Principal principal = new SimplePrincipal(username);
+      return principal;
+   }
+
+   protected Group[] getRoleSets() throws LoginException
+   {
+      Group[] empty = new Group[0];
+      return empty;
+   }
+
+   private static class DecodeAction implements PrivilegedExceptionAction
+   {
+      String password;
+      ObjectName jaasSecurityDomain;
+      MBeanServer server;
+      
+      DecodeAction(String password, ObjectName jaasSecurityDomain,
+         MBeanServer server)
+      {
+         this.password = password;
+         this.jaasSecurityDomain = jaasSecurityDomain;
+         this.server = server;
+      }
+
+      /**
+       * 
+       * @return
+       * @throws Exception
+       */ 
+      public Object run() throws Exception
+      {
+         // Invoke the jaasSecurityDomain.decodeb64 op
+         Object[] args = {password};
+         String[] sig = {String.class.getName()};
+         byte[] secret = (byte[]) server.invoke(jaasSecurityDomain,
+            "decode64", args, sig);
+         // Convert to UTF-8 base char array
+         String secretPassword = new String(secret, "UTF-8");
+         return secretPassword.toCharArray();
+      }
+      static char[] decode(String password, ObjectName jaasSecurityDomain,
+         MBeanServer server)
+         throws Exception
+      {
+         DecodeAction action = new DecodeAction(password, jaasSecurityDomain, server);
+         try
+         {
+            char[] decode = (char[]) AccessController.doPrivileged(action);
+            return decode;
+         }
+         catch(PrivilegedActionException e)
+         {
+            throw e.getException();
+         }
+      }
+   }
+}
\ No newline at end of file

Deleted: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/resource/security/PBEIdentityLoginModule.java
===================================================================
--- projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/resource/security/PBEIdentityLoginModule.java	2009-07-21 21:59:08 UTC (rev 91524)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/resource/security/PBEIdentityLoginModule.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -1,271 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * Copyright 2006, Red Hat Middleware LLC, and individual contributors
- * as indicated by the @author tags. See the copyright.txt file in the
- * distribution for a full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jboss.resource.security;
-
-import java.security.Principal;
-import java.security.acl.Group;
-import java.util.Map;
-
-import javax.crypto.Cipher;
-import javax.crypto.SecretKey;
-import javax.crypto.SecretKeyFactory;
-import javax.crypto.spec.PBEKeySpec;
-import javax.crypto.spec.PBEParameterSpec;
-import javax.resource.spi.security.PasswordCredential;
-import javax.security.auth.Subject;
-import javax.security.auth.callback.CallbackHandler;
-import javax.security.auth.login.LoginException;
-
-import org.jboss.logging.Logger;
-import org.jboss.security.Base64Utils;
-import org.jboss.security.SimplePrincipal;
-import org.jboss.security.Util;
-
-/** An example of how one could encrypt the database password for a jca
-  connection factory. The corresponding login config entry illustrates
-  the usage:
- 
-   <application-policy name = "testPBEIdentityLoginModule">
-      <authentication>
-         <login-module code = "org.jboss.resource.security.PBEIdentityLoginModule"
-            flag = "required">
-            <module-option name = "principal">sa</module-option>
-            <module-option name = "userName">sa</module-option>
-            <!--
-            output from:
-               org.jboss.resource.security.PBEIdentityLoginModule
-               thesecret testPBEIdentityLoginModule abcdefgh 19 PBEWithMD5AndDES 
-            -->
-            <module-option name = "password">3fp7R/7TMjyTTxhmePdJVk</module-option>
-            <module-option name = "ignoreMissigingMCF">true</module-option>
-            <module-option name = "pbealgo">PBEWithMD5AndDES</module-option>
-            <module-option name = "pbepass">testPBEIdentityLoginModule</module-option>
-            <module-option name = "salt">abcdefgh</module-option>
-            <module-option name = "iterationCount">19</module-option>
-            <module-option name = "managedConnectionFactoryName">jboss.jca:service=LocalTxCM,name=DefaultDS</module-option>
-         </login-module>
-      </authentication>
-   </application-policy>
-
- This uses password based encryption (PBE) with algorithm parameters dervived
- from pbealgo, pbepass, salt, iterationCount options:
- + pbealgo - the PBE algorithm to use. Defaults to PBEwithMD5andDES.
- + pbepass - the PBE password to use. Can use the JaasSecurityDomain {CLASS}
- and {EXT} syntax to obtain the password from outside of the configuration.
- Defaults to "jaas is the way".
- + salt - the PBE salt as a string. Defaults to {1, 7, 2, 9, 3, 11, 4, 13}.
- + iterationCount - the PBE iterationCount. Defaults to 37.
-
- * @author Scott.Stark at jboss.org
- * @author <a href="mailto:noel.rocher at jboss.org">Noel Rocher</a> 29, june 2004 username & userName issue
- * @version $Revision: 57189 $
- */
-public class PBEIdentityLoginModule
-   extends AbstractPasswordCredentialLoginModule
-{
-   /**
-    * Class logger
-    */
-   private static final Logger log = Logger.getLogger(SecureIdentityLoginModule.class);
-
-   private String username;
-   private String password;
-   /** The Blowfish key material */
-   private char[] pbepass = "jaas is the way".toCharArray();
-   private String pbealgo = "PBEwithMD5andDES";
-   private byte[] salt = {1, 7, 2, 9, 3, 11, 4, 13};
-   private int iterationCount = 37;
-   private PBEParameterSpec cipherSpec;
-
-   public PBEIdentityLoginModule()
-   {
-   }
-   PBEIdentityLoginModule(String algo, char[] pass, byte[] pbesalt, int iter)
-   {
-      if( pass != null )
-         pbepass = pass;
-      if( algo != null )
-         pbealgo = algo;
-      if( pbesalt != null )
-         salt = pbesalt;
-      if( iter > 0 )
-         iterationCount = iter;
-   }
-
-   @SuppressWarnings("unchecked")
-   @Override
-   public void initialize(Subject subject, CallbackHandler handler, Map sharedState, Map options)
-   {
-      super.initialize(subject, handler, sharedState, options);
-      // NR : we keep this username for compatibility
-      username = (String) options.get("username");
-      if( username == null )
-      {
-      	// NR : try with userName
-        username = (String) options.get("userName");      	
-        if( username == null )
-        {
-         throw new IllegalArgumentException("The user name is a required option");
-        }
-     }
-      password = (String) options.get("password");
-      if( password == null )
-      {
-         throw new IllegalArgumentException("The password is a required option");
-      }
-      // Look for the cipher password and algo parameters
-      String tmp = (String) options.get("pbepass");
-      if( tmp != null )
-      {
-         try
-         {
-            pbepass = Util.loadPassword(tmp);
-         }
-         catch(Exception e)
-         {
-            throw new IllegalStateException(e);
-         }
-      }
-      tmp = (String) options.get("pbealgo");
-      if( tmp != null )
-         pbealgo = tmp;
-      tmp = (String) options.get("salt");
-      if( tmp != null )
-         salt = tmp.substring(0, 8).getBytes();
-      tmp = (String) options.get("iterationCount");
-      if( tmp != null )
-         iterationCount = Integer.parseInt(tmp);
-   }
-
-   public boolean login() throws LoginException
-   {
-      log.trace("login called");
-      if( super.login() == true )
-         return true;
-
-      super.loginOk = true;
-      return true;
-   }
-
-   @SuppressWarnings("unchecked")
-   public boolean commit() throws LoginException
-   {
-      Principal principal = new SimplePrincipal(username);
-      SubjectActions.addPrincipals(subject, principal);
-      sharedState.put("javax.security.auth.login.name", username);
-      // Decode the encrypted password
-      try
-      {
-         char[] decodedPassword = decode(password);
-         PasswordCredential cred = new PasswordCredential(username, decodedPassword);
-         cred.setManagedConnectionFactory(getMcf());
-         SubjectActions.addCredentials(subject, cred);
-      }
-      catch(Exception e)
-      {
-         log.debug("Failed to decode password", e);
-         throw new LoginException("Failed to decode password: "+e.getMessage());
-      }
-      return true;
-   }
-
-   public boolean abort()
-   {
-      username = null;
-      password = null;
-      return true;
-   }
-
-   protected Principal getIdentity()
-   {
-      log.trace("getIdentity called, username="+username);
-      Principal principal = new SimplePrincipal(username);
-      return principal;
-   }
-
-   protected Group[] getRoleSets() throws LoginException
-   {
-      Group[] empty = new Group[0];
-      return empty;
-   }
-
-   private String encode(String secret)
-      throws Exception
-   {
-      // Create the PBE secret key
-      cipherSpec = new PBEParameterSpec(salt, iterationCount);
-      PBEKeySpec keySpec = new PBEKeySpec(pbepass);
-      SecretKeyFactory factory = SecretKeyFactory.getInstance(pbealgo);
-      SecretKey cipherKey = factory.generateSecret(keySpec);
-
-      // Decode the secret
-      Cipher cipher = Cipher.getInstance(pbealgo);
-      cipher.init(Cipher.ENCRYPT_MODE, cipherKey, cipherSpec);
-      byte[] encoding = cipher.doFinal(secret.getBytes());
-      return Base64Utils.tob64(encoding);
-   }
-
-   private char[] decode(String secret)
-      throws Exception
-   {
-      // Create the PBE secret key
-      cipherSpec = new PBEParameterSpec(salt, iterationCount);
-      PBEKeySpec keySpec = new PBEKeySpec(pbepass);
-      SecretKeyFactory factory = SecretKeyFactory.getInstance(pbealgo);
-      SecretKey cipherKey = factory.generateSecret(keySpec);
-      // Decode the secret
-      byte[] encoding = Base64Utils.fromb64(secret);
-      Cipher cipher = Cipher.getInstance(pbealgo);
-      cipher.init(Cipher.DECRYPT_MODE, cipherKey, cipherSpec);
-      byte[] decode = cipher.doFinal(encoding);
-      return new String(decode).toCharArray();
-   }
-
-   /** Main entry point to encrypt a password using the hard-coded pass phrase 
-    * 
-    * @param args - [0] = the password to encode
-    *    [1] = PBE password 
-    *    [2] = PBE salt 
-    *    [3] = PBE iterationCount 
-    *    [4] = PBE algo 
-    * @throws Exception
-    */ 
-   public static void main(String[] args) throws Exception
-   {
-      String algo = null;
-      char[] pass = "jaas is the way".toCharArray();
-      byte[] salt = null;
-      int iter = -1;
-      if( args.length >= 2 )
-         pass = args[1].toCharArray();
-      if( args.length >= 3 )
-         salt = args[2].getBytes();
-      if( args.length >= 4 )
-         iter = Integer.decode(args[3]).intValue();
-      if( args.length >= 5 )
-         algo = args[4];
-
-      PBEIdentityLoginModule pbe = new PBEIdentityLoginModule(algo, pass, salt, iter);
-      String encode = pbe.encode(args[0]);
-      System.out.println("Encoded password: "+encode);
-   }
-}

Copied: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/resource/security/PBEIdentityLoginModule.java (from rev 93325, projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/resource/security/PBEIdentityLoginModule.java)
===================================================================
--- projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/resource/security/PBEIdentityLoginModule.java	                        (rev 0)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/resource/security/PBEIdentityLoginModule.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -0,0 +1,275 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2006, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.resource.security;
+
+import java.security.Principal;
+import java.security.acl.Group;
+import java.util.Map;
+
+import javax.crypto.Cipher;
+import javax.crypto.SecretKey;
+import javax.crypto.SecretKeyFactory;
+import javax.crypto.spec.PBEKeySpec;
+import javax.crypto.spec.PBEParameterSpec;
+import javax.resource.spi.security.PasswordCredential;
+import javax.security.auth.Subject;
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.login.LoginException;
+
+import org.jboss.logging.Logger;
+import org.jboss.security.Base64Utils;
+import org.jboss.security.SimplePrincipal;
+import org.jboss.security.Util;
+
+/** An example of how one could encrypt the database password for a jca
+  connection factory. The corresponding login config entry illustrates
+  the usage:
+ 
+   <application-policy name = "testPBEIdentityLoginModule">
+      <authentication>
+         <login-module code = "org.jboss.resource.security.PBEIdentityLoginModule"
+            flag = "required">
+            <module-option name = "principal">sa</module-option>
+            <module-option name = "userName">sa</module-option>
+            <!--
+            output from:
+               org.jboss.resource.security.PBEIdentityLoginModule
+               thesecret testPBEIdentityLoginModule abcdefgh 19 PBEWithMD5AndDES 
+            -->
+            <module-option name = "password">3fp7R/7TMjyTTxhmePdJVk</module-option>
+            <module-option name = "ignoreMissigingMCF">true</module-option>
+            <module-option name = "pbealgo">PBEWithMD5AndDES</module-option>
+            <module-option name = "pbepass">testPBEIdentityLoginModule</module-option>
+            <module-option name = "salt">abcdefgh</module-option>
+            <module-option name = "iterationCount">19</module-option>
+            <module-option name = "managedConnectionFactoryName">jboss.jca:service=LocalTxCM,name=DefaultDS</module-option>
+         </login-module>
+      </authentication>
+   </application-policy>
+
+ This uses password based encryption (PBE) with algorithm parameters dervived
+ from pbealgo, pbepass, salt, iterationCount options:
+ + pbealgo - the PBE algorithm to use. Defaults to PBEwithMD5andDES.
+ + pbepass - the PBE password to use. Can use the JaasSecurityDomain {CLASS}
+ and {EXT} syntax to obtain the password from outside of the configuration.
+ Defaults to "jaas is the way".
+ + salt - the PBE salt as a string. Defaults to {1, 7, 2, 9, 3, 11, 4, 13}.
+ + iterationCount - the PBE iterationCount. Defaults to 37.
+
+ * @author Scott.Stark at jboss.org
+ * @author <a href="mailto:noel.rocher at jboss.org">Noel Rocher</a> 29, june 2004 username & userName issue
+ * @version $Revision: 57189 $
+ */
+public class PBEIdentityLoginModule
+   extends AbstractPasswordCredentialLoginModule
+{
+   /**
+    * Class logger
+    */
+   private static final Logger log = Logger.getLogger(SecureIdentityLoginModule.class);
+   private boolean trace = log.isTraceEnabled();
+
+   private String username;
+   private String password;
+   /** The Blowfish key material */
+   private char[] pbepass = "jaas is the way".toCharArray();
+   private String pbealgo = "PBEwithMD5andDES";
+   private byte[] salt = {1, 7, 2, 9, 3, 11, 4, 13};
+   private int iterationCount = 37;
+   private PBEParameterSpec cipherSpec;
+
+   public PBEIdentityLoginModule()
+   {
+   }
+   PBEIdentityLoginModule(String algo, char[] pass, byte[] pbesalt, int iter)
+   {
+      if( pass != null )
+         pbepass = pass;
+      if( algo != null )
+         pbealgo = algo;
+      if( pbesalt != null )
+         salt = pbesalt;
+      if( iter > 0 )
+         iterationCount = iter;
+   }
+
+   @SuppressWarnings("unchecked")
+   @Override
+   public void initialize(Subject subject, CallbackHandler handler, Map sharedState, Map options)
+   {
+      super.initialize(subject, handler, sharedState, options);
+      // NR : we keep this username for compatibility
+      username = (String) options.get("username");
+      if( username == null )
+      {
+      	// NR : try with userName
+        username = (String) options.get("userName");      	
+        if( username == null )
+        {
+         throw new IllegalArgumentException("The user name is a required option");
+        }
+     }
+      password = (String) options.get("password");
+      if( password == null )
+      {
+         throw new IllegalArgumentException("The password is a required option");
+      }
+      // Look for the cipher password and algo parameters
+      String tmp = (String) options.get("pbepass");
+      if( tmp != null )
+      {
+         try
+         {
+            pbepass = Util.loadPassword(tmp);
+         }
+         catch(Exception e)
+         {
+            throw new IllegalStateException(e);
+         }
+      }
+      tmp = (String) options.get("pbealgo");
+      if( tmp != null )
+         pbealgo = tmp;
+      tmp = (String) options.get("salt");
+      if( tmp != null )
+         salt = tmp.substring(0, 8).getBytes();
+      tmp = (String) options.get("iterationCount");
+      if( tmp != null )
+         iterationCount = Integer.parseInt(tmp);
+   }
+
+   public boolean login() throws LoginException
+   {
+      if(trace)
+         log.trace("login called");
+      if( super.login() == true )
+         return true;
+
+      super.loginOk = true;
+      return true;
+   }
+
+   @SuppressWarnings("unchecked")
+   public boolean commit() throws LoginException
+   {
+      Principal principal = new SimplePrincipal(username);
+      SubjectActions.addPrincipals(subject, principal);
+      sharedState.put("javax.security.auth.login.name", username);
+      // Decode the encrypted password
+      try
+      {
+         char[] decodedPassword = decode(password);
+         PasswordCredential cred = new PasswordCredential(username, decodedPassword);
+         cred.setManagedConnectionFactory(getMcf());
+         SubjectActions.addCredentials(subject, cred);
+      }
+      catch(Exception e)
+      {
+         if(trace)
+            log.trace("Failed to decode password", e);
+         throw new LoginException("Failed to decode password: "+e.getMessage());
+      }
+      return true;
+   }
+
+   public boolean abort()
+   {
+      username = null;
+      password = null;
+      return true;
+   }
+
+   protected Principal getIdentity()
+   {
+      if(trace)
+         log.trace("getIdentity called, username="+username);
+      Principal principal = new SimplePrincipal(username);
+      return principal;
+   }
+
+   protected Group[] getRoleSets() throws LoginException
+   {
+      Group[] empty = new Group[0];
+      return empty;
+   }
+
+   private String encode(String secret)
+      throws Exception
+   {
+      // Create the PBE secret key
+      cipherSpec = new PBEParameterSpec(salt, iterationCount);
+      PBEKeySpec keySpec = new PBEKeySpec(pbepass);
+      SecretKeyFactory factory = SecretKeyFactory.getInstance(pbealgo);
+      SecretKey cipherKey = factory.generateSecret(keySpec);
+
+      // Decode the secret
+      Cipher cipher = Cipher.getInstance(pbealgo);
+      cipher.init(Cipher.ENCRYPT_MODE, cipherKey, cipherSpec);
+      byte[] encoding = cipher.doFinal(secret.getBytes());
+      return Base64Utils.tob64(encoding);
+   }
+
+   private char[] decode(String secret)
+      throws Exception
+   {
+      // Create the PBE secret key
+      cipherSpec = new PBEParameterSpec(salt, iterationCount);
+      PBEKeySpec keySpec = new PBEKeySpec(pbepass);
+      SecretKeyFactory factory = SecretKeyFactory.getInstance(pbealgo);
+      SecretKey cipherKey = factory.generateSecret(keySpec);
+      // Decode the secret
+      byte[] encoding = Base64Utils.fromb64(secret);
+      Cipher cipher = Cipher.getInstance(pbealgo);
+      cipher.init(Cipher.DECRYPT_MODE, cipherKey, cipherSpec);
+      byte[] decode = cipher.doFinal(encoding);
+      return new String(decode).toCharArray();
+   }
+
+   /** Main entry point to encrypt a password using the hard-coded pass phrase 
+    * 
+    * @param args - [0] = the password to encode
+    *    [1] = PBE password 
+    *    [2] = PBE salt 
+    *    [3] = PBE iterationCount 
+    *    [4] = PBE algo 
+    * @throws Exception
+    */ 
+   public static void main(String[] args) throws Exception
+   {
+      String algo = null;
+      char[] pass = "jaas is the way".toCharArray();
+      byte[] salt = null;
+      int iter = -1;
+      if( args.length >= 2 )
+         pass = args[1].toCharArray();
+      if( args.length >= 3 )
+         salt = args[2].getBytes();
+      if( args.length >= 4 )
+         iter = Integer.decode(args[3]).intValue();
+      if( args.length >= 5 )
+         algo = args[4];
+
+      PBEIdentityLoginModule pbe = new PBEIdentityLoginModule(algo, pass, salt, iter);
+      String encode = pbe.encode(args[0]);
+      System.out.println("Encoded password: "+encode);
+   }
+}
\ No newline at end of file

Deleted: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/resource/security/SecureIdentityLoginModule.java
===================================================================
--- projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/resource/security/SecureIdentityLoginModule.java	2009-07-21 21:59:08 UTC (rev 91524)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/resource/security/SecureIdentityLoginModule.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -1,204 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * Copyright 2006, Red Hat Middleware LLC, and individual contributors
- * as indicated by the @author tags. See the copyright.txt file in the
- * distribution for a full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jboss.resource.security;
-
-import java.math.BigInteger;
-import java.security.InvalidKeyException;
-import java.security.NoSuchAlgorithmException;
-import java.security.Principal;
-import java.security.acl.Group;
-import java.util.Map;
-
-import javax.crypto.BadPaddingException;
-import javax.crypto.Cipher;
-import javax.crypto.IllegalBlockSizeException;
-import javax.crypto.NoSuchPaddingException;
-import javax.crypto.spec.SecretKeySpec;
-import javax.resource.spi.security.PasswordCredential;
-import javax.security.auth.Subject;
-import javax.security.auth.callback.CallbackHandler;
-import javax.security.auth.login.LoginException;
-
-import org.jboss.logging.Logger;
-import org.jboss.security.SimplePrincipal;
-
-/** An example of how one could encrypt the database password for a jca
-  connection factory. The corresponding  
- 
-<application-policy name = "HsqlDbRealm">
-   <authentication>
-      <login-module code = "org.jboss.resource.security.SecureIdentityLoginMdule"
-         flag = "required">
-         <module-option name = "userName">sa</module-option>
-         <module-option name = "password">-207a6df87216de44</module-option>
-         <module-option name = "managedConnectionFactoryName">jboss.jca:servce=LocalTxCM,name=DefaultDS</module-option>
-      </login-module>
-   </authentication>
-</application-policy>
-
- This uses a hard-coded cipher algo of Blowfish, and key derived from the
- phrase 'jaas is the way'. Adjust to your requirements.
-
- * @author Scott.Stark at jboss.org
- * @author <a href="mailto:noel.rocher at jboss.org">Noel Rocher</a> 29, june 2004 username & userName issue
- * @version $Revision: 71545 $
- */
-
- at SuppressWarnings("unchecked")
-public class SecureIdentityLoginModule
-   extends AbstractPasswordCredentialLoginModule
-{
-   /**
-    * Class logger
-    */
-   private static final Logger log = Logger.getLogger(SecureIdentityLoginModule.class);
-
-   private String username;
-   private String password;
-
-   public void initialize(Subject subject, CallbackHandler handler, Map sharedState, Map options)
-   {
-      super.initialize(subject, handler, sharedState, options);
-      // NR : we keep this username for compatibility
-      username = (String) options.get("username");
-      if( username == null )
-      {
-      	// NR : try with userName
-        username = (String) options.get("userName");      	
-        if( username == null )
-        {
-         throw new IllegalArgumentException("The user name is a required option");
-        }
-     }
-      password = (String) options.get("password");
-      if( password == null )
-      {
-         throw new IllegalArgumentException("The password is a required option");
-      }
-   }
-
-   public boolean login() throws LoginException
-   {
-      log.trace("login called");
-      if( super.login() == true )
-         return true;
-
-      super.loginOk = true;
-      return true;
-   }
-
-   public boolean commit() throws LoginException
-   {
-      Principal principal = new SimplePrincipal(username);
-      SubjectActions.addPrincipals(subject, principal);
-      sharedState.put("javax.security.auth.login.name", username);
-      // Decode the encrypted password
-      try
-      {
-         char[] decodedPassword = decode(password);
-         PasswordCredential cred = new PasswordCredential(username, decodedPassword);
-         cred.setManagedConnectionFactory(getMcf());
-         SubjectActions.addCredentials(subject, cred);
-      }
-      catch(Exception e)
-      {
-         log.debug("Failed to decode password", e);
-         throw new LoginException("Failed to decode password: "+e.getMessage());
-      }
-      return true;
-   }
-
-   public boolean abort()
-   {
-      username = null;
-      password = null;
-      return true;
-   }
-
-   protected Principal getIdentity()
-   {
-      log.trace("getIdentity called, username="+username);
-      Principal principal = new SimplePrincipal(username);
-      return principal;
-   }
-
-   protected Group[] getRoleSets() throws LoginException
-   {
-      Group[] empty = new Group[0];
-      return empty;
-   }
-
-   private static String encode(String secret)
-      throws NoSuchPaddingException, NoSuchAlgorithmException,
-      InvalidKeyException, BadPaddingException, IllegalBlockSizeException
-   {
-      byte[] kbytes = "jaas is the way".getBytes();
-      SecretKeySpec key = new SecretKeySpec(kbytes, "Blowfish");
-
-      Cipher cipher = Cipher.getInstance("Blowfish");
-      cipher.init(Cipher.ENCRYPT_MODE, key);
-      byte[] encoding = cipher.doFinal(secret.getBytes());
-      BigInteger n = new BigInteger(encoding);
-      return n.toString(16);
-   }
-
-   private static char[] decode(String secret)
-      throws NoSuchPaddingException, NoSuchAlgorithmException,
-      InvalidKeyException, BadPaddingException, IllegalBlockSizeException
-   {
-      byte[] kbytes = "jaas is the way".getBytes();
-      SecretKeySpec key = new SecretKeySpec(kbytes, "Blowfish");
-
-      BigInteger n = new BigInteger(secret, 16);
-      byte[] encoding = n.toByteArray();
-      
-      //SECURITY-344: fix leading zeros
-      if (encoding.length % 8 != 0)
-      {
-         int length = encoding.length;
-         int newLength = ((length / 8) + 1) * 8;
-         int pad = newLength - length; //number of leading zeros
-         byte[] old = encoding;
-         encoding = new byte[newLength];
-         for (int i = old.length - 1; i >= 0; i--)
-         {
-            encoding[i + pad] = old[i];
-         }
-      }
-      
-      Cipher cipher = Cipher.getInstance("Blowfish");
-      cipher.init(Cipher.DECRYPT_MODE, key);
-      byte[] decode = cipher.doFinal(encoding);
-      return new String(decode).toCharArray();
-   }
-
-   /** Main entry point to encrypt a password using the hard-coded pass phrase 
-    * 
-    * @param args - [0] = the password to encode
-    * @throws Exception
-    */ 
-   public static void main(String[] args) throws Exception
-   {
-      String encode = encode(args[0]);
-      System.out.println("Encoded password: "+encode);
-   }
-}

Copied: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/resource/security/SecureIdentityLoginModule.java (from rev 93325, projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/resource/security/SecureIdentityLoginModule.java)
===================================================================
--- projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/resource/security/SecureIdentityLoginModule.java	                        (rev 0)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/resource/security/SecureIdentityLoginModule.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -0,0 +1,208 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2006, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.resource.security;
+
+import java.math.BigInteger;
+import java.security.InvalidKeyException;
+import java.security.NoSuchAlgorithmException;
+import java.security.Principal;
+import java.security.acl.Group;
+import java.util.Map;
+
+import javax.crypto.BadPaddingException;
+import javax.crypto.Cipher;
+import javax.crypto.IllegalBlockSizeException;
+import javax.crypto.NoSuchPaddingException;
+import javax.crypto.spec.SecretKeySpec;
+import javax.resource.spi.security.PasswordCredential;
+import javax.security.auth.Subject;
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.login.LoginException;
+
+import org.jboss.logging.Logger;
+import org.jboss.security.SimplePrincipal;
+
+/** An example of how one could encrypt the database password for a jca
+  connection factory. The corresponding  
+ 
+<application-policy name = "HsqlDbRealm">
+   <authentication>
+      <login-module code = "org.jboss.resource.security.SecureIdentityLoginMdule"
+         flag = "required">
+         <module-option name = "userName">sa</module-option>
+         <module-option name = "password">-207a6df87216de44</module-option>
+         <module-option name = "managedConnectionFactoryName">jboss.jca:servce=LocalTxCM,name=DefaultDS</module-option>
+      </login-module>
+   </authentication>
+</application-policy>
+
+ This uses a hard-coded cipher algo of Blowfish, and key derived from the
+ phrase 'jaas is the way'. Adjust to your requirements.
+
+ * @author Scott.Stark at jboss.org
+ * @author <a href="mailto:noel.rocher at jboss.org">Noel Rocher</a> 29, june 2004 username & userName issue
+ * @version $Revision: 71545 $
+ */
+
+ at SuppressWarnings("unchecked")
+public class SecureIdentityLoginModule
+   extends AbstractPasswordCredentialLoginModule
+{
+   /**
+    * Class logger
+    */
+   private static final Logger log = Logger.getLogger(SecureIdentityLoginModule.class);
+   private boolean trace = log.isTraceEnabled();
+
+   private String username;
+   private String password;
+
+   public void initialize(Subject subject, CallbackHandler handler, Map sharedState, Map options)
+   {
+      super.initialize(subject, handler, sharedState, options);
+      // NR : we keep this username for compatibility
+      username = (String) options.get("username");
+      if( username == null )
+      {
+      	// NR : try with userName
+        username = (String) options.get("userName");      	
+        if( username == null )
+        {
+         throw new IllegalArgumentException("The user name is a required option");
+        }
+     }
+      password = (String) options.get("password");
+      if( password == null )
+      {
+         throw new IllegalArgumentException("The password is a required option");
+      }
+   }
+
+   public boolean login() throws LoginException
+   {
+      if(trace)
+         log.trace("login called");
+      if( super.login() == true )
+         return true;
+
+      super.loginOk = true;
+      return true;
+   }
+
+   public boolean commit() throws LoginException
+   {
+      Principal principal = new SimplePrincipal(username);
+      SubjectActions.addPrincipals(subject, principal);
+      sharedState.put("javax.security.auth.login.name", username);
+      // Decode the encrypted password
+      try
+      {
+         char[] decodedPassword = decode(password);
+         PasswordCredential cred = new PasswordCredential(username, decodedPassword);
+         cred.setManagedConnectionFactory(getMcf());
+         SubjectActions.addCredentials(subject, cred);
+      }
+      catch(Exception e)
+      {
+         if(trace)
+            log.trace("Failed to decode password", e);
+         throw new LoginException("Failed to decode password: "+e.getMessage());
+      }
+      return true;
+   }
+
+   public boolean abort()
+   {
+      username = null;
+      password = null;
+      return true;
+   }
+
+   protected Principal getIdentity()
+   {
+      if(trace)
+         log.trace("getIdentity called, username="+username);
+      Principal principal = new SimplePrincipal(username);
+      return principal;
+   }
+
+   protected Group[] getRoleSets() throws LoginException
+   {
+      Group[] empty = new Group[0];
+      return empty;
+   }
+
+   private static String encode(String secret)
+      throws NoSuchPaddingException, NoSuchAlgorithmException,
+      InvalidKeyException, BadPaddingException, IllegalBlockSizeException
+   {
+      byte[] kbytes = "jaas is the way".getBytes();
+      SecretKeySpec key = new SecretKeySpec(kbytes, "Blowfish");
+
+      Cipher cipher = Cipher.getInstance("Blowfish");
+      cipher.init(Cipher.ENCRYPT_MODE, key);
+      byte[] encoding = cipher.doFinal(secret.getBytes());
+      BigInteger n = new BigInteger(encoding);
+      return n.toString(16);
+   }
+
+   private static char[] decode(String secret)
+      throws NoSuchPaddingException, NoSuchAlgorithmException,
+      InvalidKeyException, BadPaddingException, IllegalBlockSizeException
+   {
+      byte[] kbytes = "jaas is the way".getBytes();
+      SecretKeySpec key = new SecretKeySpec(kbytes, "Blowfish");
+
+      BigInteger n = new BigInteger(secret, 16);
+      byte[] encoding = n.toByteArray();
+      
+      //SECURITY-344: fix leading zeros
+      if (encoding.length % 8 != 0)
+      {
+         int length = encoding.length;
+         int newLength = ((length / 8) + 1) * 8;
+         int pad = newLength - length; //number of leading zeros
+         byte[] old = encoding;
+         encoding = new byte[newLength];
+         for (int i = old.length - 1; i >= 0; i--)
+         {
+            encoding[i + pad] = old[i];
+         }
+      }
+      
+      Cipher cipher = Cipher.getInstance("Blowfish");
+      cipher.init(Cipher.DECRYPT_MODE, key);
+      byte[] decode = cipher.doFinal(encoding);
+      return new String(decode).toCharArray();
+   }
+
+   /** Main entry point to encrypt a password using the hard-coded pass phrase 
+    * 
+    * @param args - [0] = the password to encode
+    * @throws Exception
+    */ 
+   public static void main(String[] args) throws Exception
+   {
+      String encode = encode(args[0]);
+      System.out.println("Encoded password: "+encode);
+   }
+}
\ No newline at end of file

Deleted: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/AltClientLoginModule.java
===================================================================
--- projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/security/AltClientLoginModule.java	2009-07-21 21:59:08 UTC (rev 91524)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/AltClientLoginModule.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -1,221 +0,0 @@
-/*
-* JBoss, Home of Professional Open Source
-* Copyright 2005, JBoss Inc., and individual contributors as indicated
-* by the @authors tag. See the copyright.txt in the distribution for a
-* full listing of individual contributors.
-*
-* This is free software; you can redistribute it and/or modify it
-* under the terms of the GNU Lesser General Public License as
-* published by the Free Software Foundation; either version 2.1 of
-* the License, or (at your option) any later version.
-*
-* This software is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-* Lesser General Public License for more details.
-*
-* You should have received a copy of the GNU Lesser General Public
-* License along with this software; if not, write to the Free
-* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
-*/
-package org.jboss.security;
-
-
-import java.security.Principal;
-import java.util.Map;
-import java.util.Set;
-
-import javax.security.auth.Subject;
-import javax.security.auth.callback.Callback;
-import javax.security.auth.callback.CallbackHandler;
-import javax.security.auth.callback.NameCallback;
-import javax.security.auth.callback.PasswordCallback;
-import javax.security.auth.callback.UnsupportedCallbackException;
-import javax.security.auth.login.LoginException;
-import javax.security.auth.spi.LoginModule;
-
-import org.jboss.logging.Logger;
-
-/** A simple implementation of LoginModule for use by JBoss clients for
- the establishment of the caller identity and credentials. This simply sets
- the SecurityAssociation principal to the value of the NameCallback
- filled in by the CallbackHandler, and the SecurityAssociation credential
- to the value of the PasswordCallback filled in by the CallbackHandler.
- This is a variation of the original ClientLoginModule that does not set the
- SecurityAssociation information until commit and that uses the Subject
- principal over a SimplePrincipal if available.
-
- It has the following options:
- <ul>
- <li>multi-threaded=[true|false]
- When the multi-threaded option is set to true, the SecurityAssociation.setServer()
- so that each login thread has its own principal and credential storage.
- <li>password-stacking=tryFirstPass|useFirstPass
- When password-stacking option is set, this module first looks for a shared
- username and password using "javax.security.auth.login.name" and
- "javax.security.auth.login.password" respectively. This allows a module configured
- prior to this one to establish a valid username and password that should be passed
- to JBoss.
- </ul>
- 
- @author Scott.Stark at jboss.org
- @version $Revision$
- */
-public class AltClientLoginModule implements LoginModule
-{
-   private static Logger log = Logger.getLogger(AltClientLoginModule.class);
-   private Subject subject;
-   private CallbackHandler callbackHandler;
-   /** Shared state between login modules */
-   private Map<String,?> sharedState;
-   /** Flag indicating if the shared password should be used */
-   private boolean useFirstPass;
-   private String username;
-   private char[] password = null;
-   private boolean trace;
-
-   /**
-    * Initialize this LoginModule.
-    */
-   public void initialize(Subject subject, CallbackHandler callbackHandler,
-      Map<String,?> sharedState, Map<String,?> options)
-   {
-      this.trace = log.isTraceEnabled();
-      this.subject = subject;
-      this.callbackHandler = callbackHandler;
-      this.sharedState = sharedState;
-
-      //log securityDomain, if set.
-      if(trace)
-	 log.trace("Security domain: " + 
-		   (String)options.get(SecurityConstants.SECURITY_DOMAIN_OPTION));
-
-      // Check for multi-threaded option
-      String mt = (String) options.get("multi-threaded");
-      if( Boolean.valueOf(mt).booleanValue() == true )
-      { 
-	 /* Turn on the server mode which uses thread local storage for
-	    the principal information.
-         */
-         if(trace)
-            log.trace("Enabling multi-threaded mode");
-         SecurityAssociationActions.setServer();
-      }
-      
-        /* Check for password sharing options. Any non-null value for
-            password_stacking sets useFirstPass as this module has no way to
-            validate any shared password.
-         */
-      String passwordStacking = (String) options.get("password-stacking");
-      useFirstPass = passwordStacking != null;
-      if(trace && useFirstPass)
-	 log.trace("Enabling useFirstPass mode");
-   }
-
-   /**
-    * Method to authenticate a Subject (phase 1).
-    */
-   public boolean login() throws LoginException
-   {
-      // If useFirstPass is true, look for the shared password
-      if( useFirstPass == true )
-      {
-            return true;
-      }
-
-     /* There is no password sharing or we are the first login module. Get
-         the username and password from the callback hander.
-      */
-      if (callbackHandler == null)
-         throw new LoginException("Error: no CallbackHandler available " +
-            "to garner authentication information from the user");
-      
-      PasswordCallback pc = new PasswordCallback("Password: ", false);
-      NameCallback nc = new NameCallback("User name: ", "guest");
-      Callback[] callbacks = {nc, pc};
-      try
-      {
-         char[] tmpPassword;
-         
-         callbackHandler.handle(callbacks);
-         username = nc.getName();
-         tmpPassword = pc.getPassword();
-         if (tmpPassword != null)
-         {
-            password = new char[tmpPassword.length];
-            System.arraycopy(tmpPassword, 0, password, 0, tmpPassword.length);
-            pc.clearPassword();
-         }
-      }
-      catch (java.io.IOException ioe)
-      {
-         throw new LoginException(ioe.toString());
-      }
-      catch (UnsupportedCallbackException uce)
-      {
-         throw new LoginException("Error: " + uce.getCallback().toString() +
-         " not available to garner authentication information " +
-         "from the user");
-      }
-      return true;
-   }
-
-   /** Method to commit the authentication process (phase 2). This is where the
-    * SecurityAssociation information is set. The principal is obtained from:
-    * The shared state javax.security.auth.login.name property when useFirstPass
-    * is true. If the value is a Principal it is used as is, else a SimplePrincipal
-    * using the value.toString() as its name is used. If useFirstPass the
-    * username obtained from the callback handler is used to build the
-    * SimplePrincipal. Both may be overriden if the resulting authenticated
-    * Subject principals set it not empty.
-    * 
-    */
-   public boolean commit() throws LoginException
-   {
-      Set<Principal> principals = subject.getPrincipals();
-      Principal p = null;
-      Object credential = password;
-      if( useFirstPass == true )
-      {
-         Object user = sharedState.get("javax.security.auth.login.name");
-         if( (user instanceof Principal) == false )
-         {
-            username = user != null ? user.toString() : "";
-            p = new SimplePrincipal(username);
-         }
-         else
-         {
-            p = (Principal) user;
-         }
-         credential = sharedState.get("javax.security.auth.login.password");
-      }
-      else
-      {
-         p = new SimplePrincipal(username);
-      }
-
-      if( principals.isEmpty() == false )
-         p = (Principal) principals.iterator().next();
-      SecurityAssociationActions.setPrincipalInfo(p, credential, subject);
-      return true;
-   }
-
-   /**
-    * Method to abort the authentication process (phase 2).
-    */
-   public boolean abort() throws LoginException
-   {
-      int length = password != null ? password.length : 0;
-      for(int n = 0; n < length; n ++)
-         password[n] = 0;
-      SecurityAssociationActions.clear();
-      return true;
-   }
-
-   public boolean logout() throws LoginException
-   {
-      SecurityAssociationActions.clear();
-      return true;
-   }
-}

Copied: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/AltClientLoginModule.java (from rev 93325, projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/security/AltClientLoginModule.java)
===================================================================
--- projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/AltClientLoginModule.java	                        (rev 0)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/AltClientLoginModule.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -0,0 +1,221 @@
+/*
+* JBoss, Home of Professional Open Source
+* Copyright 2005, JBoss Inc., and individual contributors as indicated
+* by the @authors tag. See the copyright.txt in the distribution for a
+* full listing of individual contributors.
+*
+* This is free software; you can redistribute it and/or modify it
+* under the terms of the GNU Lesser General Public License as
+* published by the Free Software Foundation; either version 2.1 of
+* the License, or (at your option) any later version.
+*
+* This software is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+* Lesser General Public License for more details.
+*
+* You should have received a copy of the GNU Lesser General Public
+* License along with this software; if not, write to the Free
+* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+*/
+package org.jboss.security;
+
+
+import java.security.Principal;
+import java.util.Map;
+import java.util.Set;
+
+import javax.security.auth.Subject;
+import javax.security.auth.callback.Callback;
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.callback.NameCallback;
+import javax.security.auth.callback.PasswordCallback;
+import javax.security.auth.callback.UnsupportedCallbackException;
+import javax.security.auth.login.LoginException;
+import javax.security.auth.spi.LoginModule;
+
+import org.jboss.logging.Logger;
+
+/** A simple implementation of LoginModule for use by JBoss clients for
+ the establishment of the caller identity and credentials. This simply sets
+ the SecurityAssociation principal to the value of the NameCallback
+ filled in by the CallbackHandler, and the SecurityAssociation credential
+ to the value of the PasswordCallback filled in by the CallbackHandler.
+ This is a variation of the original ClientLoginModule that does not set the
+ SecurityAssociation information until commit and that uses the Subject
+ principal over a SimplePrincipal if available.
+
+ It has the following options:
+ <ul>
+ <li>multi-threaded=[true|false]
+ When the multi-threaded option is set to true, the SecurityAssociation.setServer()
+ so that each login thread has its own principal and credential storage.
+ <li>password-stacking=tryFirstPass|useFirstPass
+ When password-stacking option is set, this module first looks for a shared
+ username and password using "javax.security.auth.login.name" and
+ "javax.security.auth.login.password" respectively. This allows a module configured
+ prior to this one to establish a valid username and password that should be passed
+ to JBoss.
+ </ul>
+ 
+ @author Scott.Stark at jboss.org
+ @version $Revision$
+ */
+public class AltClientLoginModule implements LoginModule
+{
+   private static Logger log = Logger.getLogger(AltClientLoginModule.class);
+   private Subject subject;
+   private CallbackHandler callbackHandler;
+   /** Shared state between login modules */
+   private Map<String,?> sharedState;
+   /** Flag indicating if the shared password should be used */
+   private boolean useFirstPass;
+   private String username;
+   private char[] password = null;
+   private boolean trace;
+
+   /**
+    * Initialize this LoginModule.
+    */
+   public void initialize(Subject subject, CallbackHandler callbackHandler,
+      Map<String,?> sharedState, Map<String,?> options)
+   {
+      this.trace = log.isTraceEnabled();
+      this.subject = subject;
+      this.callbackHandler = callbackHandler;
+      this.sharedState = sharedState;
+
+      //log securityDomain, if set.
+      if(trace)
+	    log.trace("Security domain: " + 
+		   (String)options.get(SecurityConstants.SECURITY_DOMAIN_OPTION));
+
+      // Check for multi-threaded option
+      String mt = (String) options.get("multi-threaded");
+      if( Boolean.valueOf(mt).booleanValue() == true )
+      { 
+	 /* Turn on the server mode which uses thread local storage for
+	    the principal information.
+         */
+         if(trace)
+            log.trace("Enabling multi-threaded mode");
+         SecurityAssociationActions.setServer();
+      }
+      
+        /* Check for password sharing options. Any non-null value for
+            password_stacking sets useFirstPass as this module has no way to
+            validate any shared password.
+         */
+      String passwordStacking = (String) options.get("password-stacking");
+      useFirstPass = passwordStacking != null;
+      if(trace && useFirstPass)
+	    log.trace("Enabling useFirstPass mode");
+   }
+
+   /**
+    * Method to authenticate a Subject (phase 1).
+    */
+   public boolean login() throws LoginException
+   {
+      // If useFirstPass is true, look for the shared password
+      if( useFirstPass == true )
+      {
+            return true;
+      }
+
+     /* There is no password sharing or we are the first login module. Get
+         the username and password from the callback hander.
+      */
+      if (callbackHandler == null)
+         throw new LoginException("Error: no CallbackHandler available " +
+            "to garner authentication information from the user");
+      
+      PasswordCallback pc = new PasswordCallback("Password: ", false);
+      NameCallback nc = new NameCallback("User name: ", "guest");
+      Callback[] callbacks = {nc, pc};
+      try
+      {
+         char[] tmpPassword;
+         
+         callbackHandler.handle(callbacks);
+         username = nc.getName();
+         tmpPassword = pc.getPassword();
+         if (tmpPassword != null)
+         {
+            password = new char[tmpPassword.length];
+            System.arraycopy(tmpPassword, 0, password, 0, tmpPassword.length);
+            pc.clearPassword();
+         }
+      }
+      catch (java.io.IOException ioe)
+      {
+         throw new LoginException(ioe.toString());
+      }
+      catch (UnsupportedCallbackException uce)
+      {
+         throw new LoginException("Error: " + uce.getCallback().toString() +
+         " not available to garner authentication information " +
+         "from the user");
+      }
+      return true;
+   }
+
+   /** Method to commit the authentication process (phase 2). This is where the
+    * SecurityAssociation information is set. The principal is obtained from:
+    * The shared state javax.security.auth.login.name property when useFirstPass
+    * is true. If the value is a Principal it is used as is, else a SimplePrincipal
+    * using the value.toString() as its name is used. If useFirstPass the
+    * username obtained from the callback handler is used to build the
+    * SimplePrincipal. Both may be overriden if the resulting authenticated
+    * Subject principals set it not empty.
+    * 
+    */
+   public boolean commit() throws LoginException
+   {
+      Set<Principal> principals = subject.getPrincipals();
+      Principal p = null;
+      Object credential = password;
+      if( useFirstPass == true )
+      {
+         Object user = sharedState.get("javax.security.auth.login.name");
+         if( (user instanceof Principal) == false )
+         {
+            username = user != null ? user.toString() : "";
+            p = new SimplePrincipal(username);
+         }
+         else
+         {
+            p = (Principal) user;
+         }
+         credential = sharedState.get("javax.security.auth.login.password");
+      }
+      else
+      {
+         p = new SimplePrincipal(username);
+      }
+
+      if( principals.isEmpty() == false )
+         p = (Principal) principals.iterator().next();
+      SecurityAssociationActions.setPrincipalInfo(p, credential, subject);
+      return true;
+   }
+
+   /**
+    * Method to abort the authentication process (phase 2).
+    */
+   public boolean abort() throws LoginException
+   {
+      int length = password != null ? password.length : 0;
+      for(int n = 0; n < length; n ++)
+         password[n] = 0;
+      SecurityAssociationActions.clear();
+      return true;
+   }
+
+   public boolean logout() throws LoginException
+   {
+      SecurityAssociationActions.clear();
+      return true;
+   }
+}
\ No newline at end of file

Deleted: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/ClientLoginModule.java
===================================================================
--- projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/security/ClientLoginModule.java	2009-07-21 21:59:08 UTC (rev 91524)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/ClientLoginModule.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -1,286 +0,0 @@
-/*
-* JBoss, Home of Professional Open Source
-* Copyright 2005, JBoss Inc., and individual contributors as indicated
-* by the @authors tag. See the copyright.txt in the distribution for a
-* full listing of individual contributors.
-*
-* This is free software; you can redistribute it and/or modify it
-* under the terms of the GNU Lesser General Public License as
-* published by the Free Software Foundation; either version 2.1 of
-* the License, or (at your option) any later version.
-*
-* This software is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-* Lesser General Public License for more details.
-*
-* You should have received a copy of the GNU Lesser General Public
-* License along with this software; if not, write to the Free
-* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
-*/
-package org.jboss.security;
-
-import java.io.IOException;
-import java.security.Principal;
-import java.util.Map;
-import java.util.Set;
-
-import javax.security.auth.Subject;
-import javax.security.auth.callback.Callback;
-import javax.security.auth.callback.CallbackHandler;
-import javax.security.auth.callback.NameCallback;
-import javax.security.auth.callback.PasswordCallback;
-import javax.security.auth.callback.UnsupportedCallbackException;
-import javax.security.auth.login.LoginException;
-import javax.security.auth.spi.LoginModule;
-
-import org.jboss.logging.Logger;
-
-/** A simple implementation of LoginModule for use by JBoss clients for
- the establishment of the caller identity and credentials. This simply sets
- the SecurityAssociation principal to the value of the NameCallback
- filled in by the CallbackHandler, and the SecurityAssociation credential
- to the value of the PasswordCallback filled in by the CallbackHandler.
- 
- It has the following options:
- <ul>
- <li>multi-threaded=[true|false]
- When the multi-threaded option is set to true, the SecurityAssociation.setServer()
- so that each login thread has its own principal and credential storage.
- <li>restore-login-identity=[true|false]
- When restore-login-identity is true, the SecurityAssociation principal
- and credential seen on entry to the login() method are saved and restored
- on either abort or logout. When false (the default), the abort and logout
- simply clears the SecurityAssociation. A restore-login-identity of true is
- needed if one need to change identities and then restore the original
- caller identity.
- <li>password-stacking=tryFirstPass|useFirstPass
- When password-stacking option is set, this module first looks for a shared
- username and password using "javax.security.auth.login.name" and
- "javax.security.auth.login.password" respectively. This allows a module configured
- prior to this one to establish a valid username and password that should be passed
- to JBoss.
- </ul>
- 
- @author <a href="mailto:on at ibis.odessa.ua">Oleg Nitz</a>
- @author Scott.Stark at jboss.org
- @author Anil.Saldhana at redhat.com
- */
-public class ClientLoginModule implements LoginModule
-{
-   private static Logger log = Logger.getLogger(ClientLoginModule.class);
-   private Subject subject;
-   private CallbackHandler callbackHandler;
-   /** The principal set during login() */
-   private Principal loginPrincipal;
-   /** The credential set during login() */
-   private Object loginCredential;
-   /** Shared state between login modules */
-   private Map<String,?> sharedState;
-   /** Flag indicating if the shared password should be used */
-   private boolean useFirstPass;
-   /** Flag indicating if the SecurityAssociation existing at login should
-    be restored on logout.
-    */
-   private boolean restoreLoginIdentity;
-   private boolean trace;
-   
-   /** To restore prelogin identity **/
-   private SecurityContext cachedSecurityContext;
-
-   /** Initialize this LoginModule. This checks for the options:
-    multi-threaded
-    restore-login-identity
-    password-stacking
-    */
-   public void initialize(Subject subject, CallbackHandler callbackHandler,
-                          Map<String,?> sharedState, Map<String,?> options)
-   {
-      this.trace = log.isTraceEnabled();
-      this.subject = subject;
-      this.callbackHandler = callbackHandler;
-      this.sharedState = sharedState;
-
-      //log securityDomain, if set.
-      if(trace)
-	 log.trace("Security domain: " + 
-		   (String)options.get(SecurityConstants.SECURITY_DOMAIN_OPTION));
-
-      // Check for multi-threaded option
-      String flag = (String) options.get("multi-threaded");
-      if (Boolean.valueOf(flag).booleanValue() == true)
-      {
-         /* Turn on the server mode which uses thread local storage for
-            the principal information.
-         */
-         if(trace)
-            log.trace("Enabling multi-threaded mode");
-         SecurityAssociationActions.setServer(); 
-      }
-      else
-      {
-         //Turn on the client side vm wide association
-         SecurityAssociationActions.setClient();
-      }
-
-      flag = (String) options.get("restore-login-identity");
-      restoreLoginIdentity = Boolean.valueOf(flag).booleanValue();
-      if(trace)
-	 log.trace("Enabling restore-login-identity mode");
-
-      /* Check for password sharing options. Any non-null value for
-          password_stacking sets useFirstPass as this module has no way to
-          validate any shared password.
-       */
-      String passwordStacking = (String) options.get("password-stacking");
-      useFirstPass = passwordStacking != null;
-      if(trace && useFirstPass)
-	 log.trace("Enabling useFirstPass mode");
-   }
-
-   /**
-    * Method to authenticate a Subject (phase 1).
-    */
-   public boolean login() throws LoginException
-   {
-      if( trace )
-         log.trace("Begin login");
-      // If useFirstPass is true, look for the shared password
-      if (useFirstPass == true)
-      {
-         try
-         {
-            Object name = sharedState.get("javax.security.auth.login.name");
-            if ((name instanceof Principal) == false)
-            {
-               String username = name != null ? name.toString() : "";
-               loginPrincipal = new SimplePrincipal(username);
-            } else
-            {
-               loginPrincipal = (Principal) name;
-            }
-            loginCredential = sharedState.get("javax.security.auth.login.password");
-            return true;
-         }
-         catch (Exception e)
-         {   // Dump the exception and continue
-            log.debug("Failed to obtain shared state", e);
-         }
-      }
-
-      /* There is no password sharing or we are the first login module. Get
-          the username and password from the callback hander.
-       */
-      if (callbackHandler == null)
-         throw new LoginException("Error: no CallbackHandler available " +
-            "to garner authentication information from the user");
-
-      PasswordCallback pc = new PasswordCallback("Password: ", false);
-      NameCallback nc = new NameCallback("User name: ", "guest");
-      Callback[] callbacks = {nc, pc};
-      try
-      {
-         String username;
-         char[] password = null;
-         char[] tmpPassword;
-
-         callbackHandler.handle(callbacks);
-         username = nc.getName();
-         loginPrincipal = new SimplePrincipal(username);
-         tmpPassword = pc.getPassword();
-         if (tmpPassword != null)
-         {
-            password = new char[tmpPassword.length];
-            System.arraycopy(tmpPassword, 0, password, 0, tmpPassword.length);
-            pc.clearPassword();
-         }
-         loginCredential = password;
-         if( trace )
-         {
-            String credType = "null";
-            if( loginCredential != null )
-               credType = loginCredential.getClass().getName();
-            log.trace("Obtained login: "+loginPrincipal
-               +", credential.class: " + credType);
-         }
-      }
-      catch (IOException ioe)
-      {
-         LoginException ex = new LoginException(ioe.toString());
-         ex.initCause(ioe);
-         throw ex;
-      }
-      catch (UnsupportedCallbackException uce)
-      {
-         LoginException ex = new LoginException("Error: " + uce.getCallback().toString() +
-            ", not able to use this callback for username/password");
-         ex.initCause(uce);
-         throw ex;
-      }
-      if( trace )
-         log.trace("End login");
-      return true;
-   }
-
-   /**
-    * Method to commit the authentication process (phase 2).
-    */
-   public boolean commit() throws LoginException
-   {
-      if( trace )
-         log.trace("commit, subject="+subject);
-      //Cache the existing security context
-      this.cachedSecurityContext = SecurityAssociationActions.getSecurityContext();
-      
-      SecurityAssociationActions.setPrincipalInfo(loginPrincipal, loginCredential, subject);
-
-      // Add the login principal to the subject if is not there
-      Set<Principal> principals = subject.getPrincipals();
-      if (principals.contains(loginPrincipal) == false)
-         principals.add(loginPrincipal);
-      return true;
-   }
-
-   /**
-    * Method to abort the authentication process (phase 2).
-    */
-   public boolean abort() throws LoginException
-   {
-      if( trace )
-         log.trace("abort");
-      if( restoreLoginIdentity == true )
-      {
-         SecurityAssociationActions.popPrincipalInfo();
-         SecurityAssociationActions.setSecurityContext(this.cachedSecurityContext);
-      }
-      else
-      {
-         // Clear the entire security association stack
-         SecurityAssociationActions.clear();  
-         SecurityAssociationActions.setSecurityContext(null);
-      }
-
-      return true;
-   }
-
-   public boolean logout() throws LoginException
-   {
-      if( trace )
-         log.trace("logout");
-      if( restoreLoginIdentity == true )
-      {
-         SecurityAssociationActions.popPrincipalInfo();
-         SecurityAssociationActions.setSecurityContext(this.cachedSecurityContext);
-      }
-      else
-      {
-         // Clear the entire security association stack
-         SecurityAssociationActions.clear();  
-         SecurityAssociationActions.clearSecurityContext(null);         
-      }
-      Set<Principal> principals = subject.getPrincipals();
-      principals.remove(loginPrincipal);
-      return true;
-   }
-}

Copied: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/ClientLoginModule.java (from rev 93325, projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/security/ClientLoginModule.java)
===================================================================
--- projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/ClientLoginModule.java	                        (rev 0)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/ClientLoginModule.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -0,0 +1,291 @@
+/*
+* JBoss, Home of Professional Open Source
+* Copyright 2005, JBoss Inc., and individual contributors as indicated
+* by the @authors tag. See the copyright.txt in the distribution for a
+* full listing of individual contributors.
+*
+* This is free software; you can redistribute it and/or modify it
+* under the terms of the GNU Lesser General Public License as
+* published by the Free Software Foundation; either version 2.1 of
+* the License, or (at your option) any later version.
+*
+* This software is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+* Lesser General Public License for more details.
+*
+* You should have received a copy of the GNU Lesser General Public
+* License along with this software; if not, write to the Free
+* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+*/
+package org.jboss.security;
+
+import java.io.IOException;
+import java.security.Principal;
+import java.util.Map;
+import java.util.Set;
+
+import javax.security.auth.Subject;
+import javax.security.auth.callback.Callback;
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.callback.NameCallback;
+import javax.security.auth.callback.PasswordCallback;
+import javax.security.auth.callback.UnsupportedCallbackException;
+import javax.security.auth.login.LoginException;
+import javax.security.auth.spi.LoginModule;
+
+import org.jboss.logging.Logger;
+
+/** A simple implementation of LoginModule for use by JBoss clients for
+ the establishment of the caller identity and credentials. This simply sets
+ the SecurityAssociation principal to the value of the NameCallback
+ filled in by the CallbackHandler, and the SecurityAssociation credential
+ to the value of the PasswordCallback filled in by the CallbackHandler.
+ 
+ It has the following options:
+ <ul>
+ <li>multi-threaded=[true|false]
+ When the multi-threaded option is set to true, the SecurityAssociation.setServer()
+ so that each login thread has its own principal and credential storage.
+ <li>restore-login-identity=[true|false]
+ When restore-login-identity is true, the SecurityAssociation principal
+ and credential seen on entry to the login() method are saved and restored
+ on either abort or logout. When false (the default), the abort and logout
+ simply clears the SecurityAssociation. A restore-login-identity of true is
+ needed if one need to change identities and then restore the original
+ caller identity.
+ <li>password-stacking=tryFirstPass|useFirstPass
+ When password-stacking option is set, this module first looks for a shared
+ username and password using "javax.security.auth.login.name" and
+ "javax.security.auth.login.password" respectively. This allows a module configured
+ prior to this one to establish a valid username and password that should be passed
+ to JBoss.
+ </ul>
+ 
+ @author <a href="mailto:on at ibis.odessa.ua">Oleg Nitz</a>
+ @author Scott.Stark at jboss.org
+ @author Anil.Saldhana at redhat.com
+ */
+public class ClientLoginModule implements LoginModule
+{
+   private static Logger log = Logger.getLogger(ClientLoginModule.class);
+   private Subject subject;
+   private CallbackHandler callbackHandler;
+   /** The principal set during login() */
+   private Principal loginPrincipal;
+   /** The credential set during login() */
+   private Object loginCredential;
+   /** Shared state between login modules */
+   private Map<String,?> sharedState;
+   /** Flag indicating if the shared password should be used */
+   private boolean useFirstPass;
+   /** Flag indicating if the SecurityAssociation existing at login should
+    be restored on logout.
+    */
+   private boolean restoreLoginIdentity;
+   private boolean trace;
+   
+   /** To restore prelogin identity **/
+   private SecurityContext cachedSecurityContext;
+
+   /** Initialize this LoginModule. This checks for the options:
+    multi-threaded
+    restore-login-identity
+    password-stacking
+    */
+   public void initialize(Subject subject, CallbackHandler callbackHandler,
+                          Map<String,?> sharedState, Map<String,?> options)
+   {
+      this.trace = log.isTraceEnabled();
+      this.subject = subject;
+      this.callbackHandler = callbackHandler;
+      this.sharedState = sharedState;
+
+      //log securityDomain, if set.
+      if(trace)
+	    log.trace("Security domain: " + 
+		   (String)options.get(SecurityConstants.SECURITY_DOMAIN_OPTION));
+
+      // Check for multi-threaded option
+      String flag = (String) options.get("multi-threaded");
+      if (Boolean.valueOf(flag).booleanValue() == true)
+      {
+         /* Turn on the server mode which uses thread local storage for
+            the principal information.
+         */
+         if(trace)
+            log.trace("Enabling multi-threaded mode");
+         SecurityAssociationActions.setServer(); 
+      }
+      
+      /**
+       * SECURITY-415: when the multi-threaded value is explictly set
+       * at false, then get into the client mode.
+       */
+      if(flag != null && flag.length() > 0 && "false".equalsIgnoreCase(flag))
+      {
+         SecurityAssociationActions.setClient();
+      }
+
+      flag = (String) options.get("restore-login-identity");
+      restoreLoginIdentity = Boolean.valueOf(flag).booleanValue();
+      if(trace)
+	    log.trace("Enabling restore-login-identity mode");
+
+      /* Check for password sharing options. Any non-null value for
+          password_stacking sets useFirstPass as this module has no way to
+          validate any shared password.
+       */
+      String passwordStacking = (String) options.get("password-stacking");
+      useFirstPass = passwordStacking != null;
+      if(trace && useFirstPass)
+	    log.trace("Enabling useFirstPass mode");
+
+      //Cache the existing security context
+      this.cachedSecurityContext = SecurityAssociationActions.getSecurityContext();
+   }
+
+   /**
+    * Method to authenticate a Subject (phase 1).
+    */
+   public boolean login() throws LoginException
+   {
+      if( trace )
+         log.trace("Begin login");
+      // If useFirstPass is true, look for the shared password
+      if (useFirstPass == true)
+      {
+         try
+         {
+            Object name = sharedState.get("javax.security.auth.login.name");
+            if ((name instanceof Principal) == false)
+            {
+               String username = name != null ? name.toString() : "";
+               loginPrincipal = new SimplePrincipal(username);
+            } else
+            {
+               loginPrincipal = (Principal) name;
+            }
+            loginCredential = sharedState.get("javax.security.auth.login.password");
+            return true;
+         }
+         catch (Exception e)
+         {   // Dump the exception and continue
+            log.debug("Failed to obtain shared state", e);
+         }
+      }
+
+      /* There is no password sharing or we are the first login module. Get
+          the username and password from the callback hander.
+       */
+      if (callbackHandler == null)
+         throw new LoginException("Error: no CallbackHandler available " +
+            "to garner authentication information from the user");
+
+      PasswordCallback pc = new PasswordCallback("Password: ", false);
+      NameCallback nc = new NameCallback("User name: ", "guest");
+      Callback[] callbacks = {nc, pc};
+      try
+      {
+         String username;
+         char[] password = null;
+         char[] tmpPassword;
+
+         callbackHandler.handle(callbacks);
+         username = nc.getName();
+         loginPrincipal = new SimplePrincipal(username);
+         tmpPassword = pc.getPassword();
+         if (tmpPassword != null)
+         {
+            password = new char[tmpPassword.length];
+            System.arraycopy(tmpPassword, 0, password, 0, tmpPassword.length);
+            pc.clearPassword();
+         }
+         loginCredential = password;
+         if( trace )
+         {
+            String credType = "null";
+            if( loginCredential != null )
+               credType = loginCredential.getClass().getName();
+            log.trace("Obtained login: "+loginPrincipal
+               +", credential.class: " + credType);
+         }
+      }
+      catch (IOException ioe)
+      {
+         LoginException ex = new LoginException(ioe.toString());
+         ex.initCause(ioe);
+         throw ex;
+      }
+      catch (UnsupportedCallbackException uce)
+      {
+         LoginException ex = new LoginException("Error: " + uce.getCallback().toString() +
+            ", not able to use this callback for username/password");
+         ex.initCause(uce);
+         throw ex;
+      }
+      if( trace )
+         log.trace("End login");
+      return true;
+   }
+
+   /**
+    * Method to commit the authentication process (phase 2).
+    */
+   public boolean commit() throws LoginException
+   {
+      if( trace )
+         log.trace("commit, subject="+subject);
+      
+      SecurityAssociationActions.setPrincipalInfo(loginPrincipal, loginCredential, subject);
+
+      // Add the login principal to the subject if is not there
+      Set<Principal> principals = subject.getPrincipals();
+      if (principals.contains(loginPrincipal) == false)
+         principals.add(loginPrincipal);
+      return true;
+   }
+
+   /**
+    * Method to abort the authentication process (phase 2).
+    */
+   public boolean abort() throws LoginException
+   {
+      if( trace )
+         log.trace("abort");
+      if( restoreLoginIdentity == true )
+      {
+         SecurityAssociationActions.popPrincipalInfo();
+         SecurityAssociationActions.setSecurityContext(this.cachedSecurityContext);
+      }
+      else
+      {
+         // Clear the entire security association stack
+         SecurityAssociationActions.clear();
+         SecurityAssociationActions.popPrincipalInfo(); //SECURITY-339
+      }
+
+      return true;
+   }
+
+   public boolean logout() throws LoginException
+   {
+      if( trace )
+         log.trace("logout");
+      if( restoreLoginIdentity == true )
+      {
+         SecurityAssociationActions.popPrincipalInfo();
+         SecurityAssociationActions.setSecurityContext(this.cachedSecurityContext);
+      }
+      else
+      {
+         // Clear the entire security association stack
+         SecurityAssociationActions.clear();  
+         SecurityAssociationActions.clearSecurityContext(null);         
+      }
+      Set<Principal> principals = subject.getPrincipals();
+      principals.remove(loginPrincipal);
+      return true;
+   }
+}
\ No newline at end of file

Deleted: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/SecurityAssociation.java
===================================================================
--- projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/security/SecurityAssociation.java	2009-07-21 21:59:08 UTC (rev 91524)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/SecurityAssociation.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -1,1143 +0,0 @@
-/*
-* JBoss, Home of Professional Open Source
-* Copyright 2005, JBoss Inc., and individual contributors as indicated
-* by the @authors tag. See the copyright.txt in the distribution for a
-* full listing of individual contributors.
-*
-* This is free software; you can redistribute it and/or modify it
-* under the terms of the GNU Lesser General Public License as
-* published by the Free Software Foundation; either version 2.1 of
-* the License, or (at your option) any later version.
-*
-* This software is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-* Lesser General Public License for more details.
-*
-* You should have received a copy of the GNU Lesser General Public
-* License along with this software; if not, write to the Free
-* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
-*/
-package org.jboss.security;
-
-import java.security.Principal;
-import java.util.ArrayList;
-import java.util.HashMap;
-
-import javax.security.auth.Subject;
-
-import org.jboss.logging.Logger;
-
-/**
- * The SecurityAssociation class maintains the security principal and
- * credentials. This can be done on either a singleton basis or a thread local
- * basis depending on the server property. When the server property has been set
- * to true, the security information is maintained in thread local storage. The
- * type of thread local storage depends on the org.jboss.security.SecurityAssociation.ThreadLocal
- * property. If this property is true, then the thread local storage object is
- * of type java.lang.ThreadLocal which results in the current thread's security
- * information NOT being propagated to child threads.
- *
- * When the property is false or does not exist, the thread local storage object
- * is of type java.lang.InheritableThreadLocal, and any threads spawned by the
- * current thread will inherit the security information of the current thread.
- * Subseqent changes to the current thread's security information are NOT
- * propagated to any previously spawned child threads.
- *
- * When the server property is false, security information is maintained in
- * class variables which makes the information available to all threads within
- * the current VM.
- * 
- * Note that this is not a public API class. Its an implementation detail that
- * is subject to change without notice.
- * 
- * @author Daniel O'Connor (docodan at nycap.rr.com)
- * @author Scott.Stark at jboss.org
- * @author Anil.Saldhana at redhat.com
- * @version $Revision$
- */
-public final class SecurityAssociation
-{
-   private static Logger log = Logger.getLogger(SecurityAssociation.class);
-   /**
-    * A flag indicating if trace level logging should be performed
-    */
-   private static boolean trace;
-   /**
-    * A flag indicating if security information is global or thread local
-    */
-   private static boolean server;
-   /**
-    * The SecurityAssociation principal used when the server flag is false
-    */
-   private static Principal principal;
-   /**
-    * The SecurityAssociation credential used when the server flag is false
-    */
-   private static Object credential;
-
-   /**
-    * The SecurityAssociation principal used when the server flag is true
-    */
-   private static ThreadLocal<Principal> threadPrincipal;
-   /**
-    * The SecurityAssociation credential used when the server flag is true
-    */
-   private static ThreadLocal<Object> threadCredential;
-   /**
-    * The SecurityAssociation HashMap<String, Object>
-    */
-   private static ThreadLocal<HashMap<String,Object>> threadContextMap;
-
-   /**
-    * Thread local stacks of run-as principal roles used to implement J2EE
-    * run-as identity propagation
-    */
-   private static RunAsThreadLocalStack threadRunAsStacks;
-   /**
-    * Thread local stacks of authenticated subject used to control the current
-    * caller security context
-    */ 
-   private static SubjectThreadLocalStack threadSubjectStacks; 
-
-   /**
-    * The permission required to access getPrincpal, getCredential
-    */
-   private static final RuntimePermission getPrincipalInfoPermission =
-      new RuntimePermission("org.jboss.security.SecurityAssociation.getPrincipalInfo");
-   /**
-    * The permission required to access getSubject
-    */
-   private static final RuntimePermission getSubjectPermission =
-      new RuntimePermission("org.jboss.security.SecurityAssociation.getSubject");
-   /**
-    * The permission required to access setPrincpal, setCredential, setSubject
-    * pushSubjectContext, popSubjectContext
-    */
-   private static final RuntimePermission setPrincipalInfoPermission =
-      new RuntimePermission("org.jboss.security.SecurityAssociation.setPrincipalInfo");
-   /**
-    * The permission required to access setServer
-    */
-   private static final RuntimePermission setServerPermission =
-      new RuntimePermission("org.jboss.security.SecurityAssociation.setServer");
-   /**
-    * The permission required to access pushRunAsIdentity/popRunAsIdentity
-    */
-   private static final RuntimePermission setRunAsIdentity =
-      new RuntimePermission("org.jboss.security.SecurityAssociation.setRunAsRole");
-   /**
-    * The permission required to get the current security context info
-    */
-   private static final RuntimePermission getContextInfo =
-      new RuntimePermission("org.jboss.security.SecurityAssociation.accessContextInfo", "get");
-   /**
-    * The permission required to set the current security context info
-    */
-   private static final RuntimePermission setContextInfo =
-      new RuntimePermission("org.jboss.security.SecurityAssociation.accessContextInfo", "set");
-
-   static
-   {
-      String flag = SecurityActions.getProperty("org.jboss.security.SecurityAssociation.ThreadLocal", "false");
-      boolean useThreadLocal = Boolean.valueOf(flag).booleanValue();
-      log.debug("Using ThreadLocal: "+useThreadLocal);
-
-      trace = log.isTraceEnabled();
-      if (useThreadLocal)
-      {
-         threadPrincipal = new ThreadLocal<Principal>();
-         threadCredential = new ThreadLocal<Object>();
-         threadContextMap = new ThreadLocal<HashMap<String,Object>>()
-         {
-            protected HashMap<String,Object> initialValue()
-            {
-               return new HashMap<String,Object>();
-            }
-         };
-      }
-      else
-      {
-         threadPrincipal = new InheritableThreadLocal<Principal>();
-         threadCredential = new InheritableThreadLocal<Object>();
-         threadContextMap = new HashMapInheritableLocal<HashMap<String,Object>>();
-      }
-      threadRunAsStacks = new RunAsThreadLocalStack(useThreadLocal);
-      threadSubjectStacks = new SubjectThreadLocalStack(useThreadLocal);
-   }
-
-   /**
-    * Get the current authentication principal information. If a security
-    * manager is present, then this method calls the security manager's
-    * <code>checkPermission</code> method with a
-    * <code>RuntimePermission("org.jboss.security.SecurityAssociation.getPrincipalInfo")
-    * </code> permission to ensure it's ok to access principal information. If
-    * not, a <code>SecurityException</code> will be thrown.
-    * @return Principal, the current principal identity.
-    */
-   public static Principal getPrincipal()
-   {
-      SecurityManager sm = System.getSecurityManager();
-      if (sm != null)
-         sm.checkPermission(getPrincipalInfoPermission);
-
-      Principal thePrincipal = principal;
-      
-      if(!server)
-         return principal;
-      
-      if( trace )
-         log.trace("getPrincipal, principal="+thePrincipal);
-      
-      SecurityContext sc = SecurityContextAssociation.getSecurityContext();
-      if(sc != null)
-      {
-         if( trace )
-            log.warn("You are using deprecated api to getPrincipal. Use security context based approach");
-         thePrincipal = sc.getUtil().getUserPrincipal();
-      }
-      return thePrincipal;
-   } 
-
-   /**
-    * Get the caller's principal. If a security manager is present,
-    * then this method calls the security manager's <code>checkPermission</code>
-    * method with a <code> RuntimePermission("org.jboss.security.SecurityAssociation.getPrincipalInfo")
-    * </code> permission to ensure it's ok to access principal information. If
-    * not, a <code>SecurityException</code> will be thrown.
-    * 
-    * @return Principal, the current principal identity.
-    */
-   public static Principal getCallerPrincipal()
-   {
-      SecurityManager sm = System.getSecurityManager();
-      if (sm != null)
-         sm.checkPermission(getPrincipalInfoPermission);
-
-      /*Principal thePrincipal = peekRunAsIdentity(1);
-      if( thePrincipal == null )
-      {
-         if (server)
-            thePrincipal = (Principal) threadPrincipal.get();
-         else
-            thePrincipal = principal;
-      }*/
-     
-      if(!server)
-         return principal;
-      
-      //Just pluck it from the current security context
-      SecurityContext sc = SecurityContextAssociation.getSecurityContext();
-      Principal thePrincipal = null;
-      if(sc != null)
-      {
-         //Check for runas
-         RunAs ras = sc.getIncomingRunAs();
-         if(ras != null)
-            thePrincipal = new SimplePrincipal(ras.getName());
-         else 
-            thePrincipal = sc.getUtil().getUserPrincipal();
-      }
-      if( trace )
-         log.trace("getCallerPrincipal, principal="+thePrincipal);
-      return thePrincipal;
-   }
-
-   /**
-    * Get the current authentication credential information. This can be of any type
-    * including: a String password, a char[] password, an X509 cert, etc. If a
-    * security manager is present, then this method calls the security manager's
-    * <code>checkPermission</code> method with a <code> RuntimePermission("org.jboss.security.SecurityAssociation.getPrincipalInfo")
-    * </code> permission to ensure it's ok to access principal information. If
-    * not, a <code>SecurityException</code> will be thrown.
-    * @return Object, the credential that proves the principal identity.
-    */
-   public static Object getCredential()
-   {
-      SecurityManager sm = System.getSecurityManager();
-      if (sm != null)
-         sm.checkPermission(getPrincipalInfoPermission);
-
-      if(!server)
-         return credential;
-      
-      SecurityContext sc = SecurityContextAssociation.getSecurityContext();
-      if(sc != null)
-      {
-         if(trace)
-            log.warn("You are using deprecated api to getCredential. Use security context based approach");
-         credential = sc.getUtil().getCredential();
-      }
-      return credential;
-   }
-
-   /**
-    * Get the current Subject information. If a security manager is present,
-    * then this method calls the security manager's checkPermission method with
-    * a  RuntimePermission("org.jboss.security.SecurityAssociation.getSubject")
-    * permission to ensure it's ok to access principal information. If not, a
-    * SecurityException will be thrown. Note that this method does not consider
-    * whether or not a run-as identity exists. For access to this information
-    * see the JACC PolicyContextHandler registered under the key
-    * "javax.security.auth.Subject.container"
-    * @return Subject, the current Subject identity.
-    * @see javax.security.jacc.PolicyContext#getContext(String)
-    */
-   public static Subject getSubject()
-   {
-      SecurityManager sm = System.getSecurityManager();
-      if (sm != null)
-         sm.checkPermission(getSubjectPermission);
-
-      SubjectContext sc = threadSubjectStacks.peek();
-      if( trace )
-         log.trace("getSubject, sc="+sc);
-      Subject subject = null;
-      /*if( sc != null )
-         subject = sc.getSubject();
-      return subject;*/
-      
-      SecurityContext secContext = SecurityAssociationActions.getSecurityContext();
-      if(secContext != null)
-      {
-         if(trace)
-            log.warn("You are using deprecated api to getSubject. Use security context based approach");
-         subject = secContext.getUtil().getSubject();
-      }
-      return subject;
-   }
-
-   /**
-    * Set the current principal information. If a security manager is present,
-    * then this method calls the security manager's <code>checkPermission</code>
-    * method with a <code> RuntimePermission("org.jboss.security.SecurityAssociation.setPrincipalInfo")
-    * </code> permission to ensure it's ok to access principal information. If
-    * not, a <code>SecurityException</code> will be thrown.
-    * @param principal - the current principal identity.
-    */
-   public static void setPrincipal(Principal principal)
-   {
-      SecurityManager sm = System.getSecurityManager();
-      if (sm != null)
-         sm.checkPermission(setPrincipalInfoPermission);
-
-      if (trace)
-         log.trace("setPrincipal, p=" + principal + ", server=" + server);
-      // Integrate with the new SubjectContext 
-      SubjectContext sc = threadSubjectStacks.peek();
-      if( sc == null )
-      {
-         // There is no active security context
-         sc = new SubjectContext();
-         threadSubjectStacks.push(sc);
-      }
-      else if( (sc.getFlags() & SubjectContext.PRINCIPAL_WAS_SET) != 0 )
-      {
-         // The current security context has its principal set
-         sc = new SubjectContext();
-         threadSubjectStacks.push(sc);    
-      }
-      sc.setPrincipal(principal);
-      
-      if(!server)
-      {
-         SecurityContextAssociation.setClient();
-         SecurityAssociation.principal = principal;
-         return; 
-      }
-      SecurityContext securityContext = SecurityContextAssociation.getSecurityContext();
-      //Clients code that may have set directly (Legacy)
-      if(securityContext == null)
-      {
-         try
-         {
-            securityContext = SecurityContextFactory.createSecurityContext("CLIENT_SIDE");
-         }
-         catch (Exception e)
-         {
-            throw new RuntimeException(e);
-         }
-         SecurityContextAssociation.setSecurityContext(securityContext);
-      }      
-      if(trace)
-         log.warn("Using deprecated API. Move to a security context based approach");
-      Object cred = securityContext.getUtil().getCredential();
-      Subject subj = securityContext.getUtil().getSubject();
-      securityContext.getUtil().createSubjectInfo(principal,cred, subj);
-     
-      if (trace)
-         log.trace("setPrincipal, sc="+sc);
-
-   } 
-
-   /**
-    * Set the current principal credential information. This can be of any type
-    * including: a String password, a char[] password, an X509 cert, etc.
-    *
-    * If a security manager is present, then this method calls the security
-    * manager's <code>checkPermission</code> method with a <code>
-    * RuntimePermission("org.jboss.security.SecurityAssociation.setPrincipalInfo")
-    * </code> permission to ensure it's ok to access principal information. If
-    * not, a <code>SecurityException</code> will be thrown.
-    * @param credential - the credential that proves the principal identity.
-    */
-   public static void setCredential(Object credential)
-   {
-      SecurityManager sm = System.getSecurityManager();
-      if (sm != null)
-         sm.checkPermission(setPrincipalInfoPermission);
-
-      // Integrate with the new SubjectContext 
-      SubjectContext sc = threadSubjectStacks.peek();
-      if( sc == null )
-      {
-         // There is no active security context
-         sc = new SubjectContext();
-         threadSubjectStacks.push(sc);
-      }
-      else if( (sc.getFlags() & SubjectContext.CREDENTIAL_WAS_SET) != 0 )
-      {
-         // The current security context has its principal set
-         sc = new SubjectContext();
-         threadSubjectStacks.push(sc);   
-      }
-      sc.setCredential(credential);
-      if (trace)
-         log.trace("setCredential, sc="+sc);
-
-      if(!server)
-      {
-         SecurityContextAssociation.setClient();
-         SecurityAssociation.credential = credential;
-         return;
-      }
-      
-      SecurityContext securityContext = SecurityContextAssociation.getSecurityContext();
-      //Clients code that may have set directly (Legacy)
-      if(securityContext == null)
-      {
-         try
-         {
-            securityContext = SecurityContextFactory.createSecurityContext("CLIENT_SIDE");
-         }
-         catch (Exception e)
-         {
-            throw new RuntimeException(e);
-         }
-         SecurityContextAssociation.setSecurityContext(securityContext);
-      }
-
-      if(trace)
-         log.warn("Using deprecated API. Move to a security context based approach");
-      Principal principal = securityContext.getUtil().getUserPrincipal();
-      Subject subj = securityContext.getUtil().getSubject();
-      securityContext.getUtil().createSubjectInfo(principal,credential, subj);      
-   }
-
-   /**
-    * Set the current Subject information. If a security manager is present,
-    * then this method calls the security manager's <code>checkPermission</code>
-    * method with a <code> RuntimePermission("org.jboss.security.SecurityAssociation.setPrincipalInfo")
-    * </code> permission to ensure it's ok to access principal information. If
-    * not, a <code>SecurityException</code> will be thrown.
-    * @param subject - the current identity.
-    */
-   public static void setSubject(Subject subject)
-   {
-      SecurityManager sm = System.getSecurityManager();
-      if (sm != null)
-         sm.checkPermission(setPrincipalInfoPermission);
-
-      if (trace)
-         log.trace("setSubject, s=" + subject + ", server=" + server);
-      // Integrate with the new SubjectContext 
-      SubjectContext sc = threadSubjectStacks.peek();
-      if( sc == null )
-      {
-         // There is no active security context
-         sc = new SubjectContext();
-         threadSubjectStacks.push(sc);
-      }
-      else if( (sc.getFlags() & SubjectContext.SUBJECT_WAS_SET) != 0 )
-      {
-         // The current security context has its subject set
-         sc = new SubjectContext();
-         threadSubjectStacks.push(sc); 
-      }
-      sc.setSubject(subject);
-      if (trace)
-         log.trace("setSubject, sc="+sc);
-      
-      SecurityContext sctx = SecurityContextAssociation.getSecurityContext();
-      if(sctx != null)
-      {
-         SubjectInfo si = sctx.getSubjectInfo();
-         if(si != null)
-         {
-            si.setAuthenticatedSubject(subject);
-         }
-         else
-            sctx.getUtil().createSubjectInfo(null, null, subject);
-      }
-   }
-
-   /**
-    * Get the current thread context info. If a security manager is present,
-    * then this method calls the security manager's <code>checkPermission</code>
-    * method with a <code> RuntimePermission("org.jboss.security.SecurityAssociation.accessContextInfo",
-    * "get") </code> permission to ensure it's ok to access context information.
-    * If not, a <code>SecurityException</code> will be thrown.
-    * @param key - the context key
-    * @return the mapping for the key in the current thread context
-    */
-   public static Object getContextInfo(String key)
-   {
-      SecurityManager sm = System.getSecurityManager();
-      if (sm != null)
-         sm.checkPermission(getContextInfo);
-
-      if(key == null)
-         throw new IllegalArgumentException("key is null");
-      HashMap<String,Object> contextInfo = (HashMap<String,Object>) threadContextMap.get();
-      return contextInfo != null ? contextInfo.get(key) : null;
-   }
-
-   /**
-    * Set the current thread context info. If a security manager is present,
-    * then this method calls the security manager's <code>checkPermission</code>
-    * method with a <code> RuntimePermission("org.jboss.security.SecurityAssociation.accessContextInfo",
-    * "set") </code> permission to ensure it's ok to access context information.
-    * If not, a <code>SecurityException</code> will be thrown.
-    * @param key - the context key
-    * @param value - the context value to associate under key
-    * @return the previous mapping for the key if one exists
-    */
-   public static Object setContextInfo(String key, Object value)
-   {
-      SecurityManager sm = System.getSecurityManager();
-      if (sm != null)
-         sm.checkPermission(setContextInfo);
-
-      HashMap<String,Object> contextInfo = (HashMap<String,Object>) threadContextMap.get();
-      return contextInfo.put(key, value);
-   }
-
-   /**
-    * Push the current authenticated context. This sets the authenticated subject
-    * along with the principal and proof of identity that was used to validate
-    * the subject. This context is used for authorization checks. Typically
-    * just the subject as seen by getSubject() is input into the authorization.
-    * When run under a security manager this requires the
-    * RuntimePermission("org.jboss.security.SecurityAssociation.setPrincipalInfo")
-    * permission.
-    * @param subject - the authenticated subject
-    * @param principal - the principal that was input into the authentication
-    * @param credential - the credential that was input into the authentication
-    * @deprecated
-    */ 
-   public static void pushSubjectContext(Subject subject,
-      Principal principal, Object credential)
-   {
-      SecurityManager sm = System.getSecurityManager();
-      if (sm != null)
-         sm.checkPermission(setPrincipalInfoPermission);
-
-      // Set the legacy single-value access points
-      if (server)
-      {
-         threadPrincipal.set(principal);
-         threadCredential.set(credential);    
-      }
-      else
-      {
-         SecurityAssociation.principal = principal;
-         SecurityAssociation.credential = credential;
-      }
-   
-      // Push the subject context
-      SubjectContext sc = new SubjectContext(subject, principal, credential);
-      threadSubjectStacks.push(sc);
-
-      if(server)
-      { 
-         if (trace)
-            log.trace("pushSubjectContext, subject=" + subject + ", sc="+sc);
-      
-         //Use the new method
-         SecurityContext sctx = SecurityContextAssociation.getSecurityContext();
-         if(sctx == null)
-         {
-            if(trace)
-               log.trace("WARN::Deprecated usage of SecurityAssociation. Use SecurityContext");
-            try
-            {
-               sctx = SecurityAssociationActions.createSecurityContext("FROM_SECURITY_ASSOCIATION");
-            }
-            catch (Exception e)
-            {
-               throw new RuntimeException(e);
-            }
-         }
-         sctx.getUtil().createSubjectInfo(principal, credential,subject);
-         SecurityAssociationActions.setSecurityContext(sctx);   
-      }
-   }
-   /**
-    * Push a duplicate of the current SubjectContext if one exists.
-    * When run under a security manager this requires the
-    * RuntimePermission("org.jboss.security.SecurityAssociation.setPrincipalInfo")
-    * permission.
-    */
-   public static void dupSubjectContext()
-   {
-      SecurityManager sm = System.getSecurityManager();
-      if (sm != null)
-         sm.checkPermission(setPrincipalInfoPermission);
-
-      SubjectContext sc = threadSubjectStacks.dup();
-      if (trace)
-         log.trace("dupSubjectContext, sc="+sc);
-   }
-
-   /**
-    * Pop the current SubjectContext from the previous pushSubjectContext call
-    * and return the pushed SubjectContext ig there was one.
-    * When run under a security manager this requires the
-    * RuntimePermission("org.jboss.security.SecurityAssociation.setPrincipalInfo")
-    * permission.
-    * @return the SubjectContext pushed previously by a pushSubjectContext call
-    * @deprecated
-    */ 
-   public static SubjectContext popSubjectContext()
-   {
-      SecurityManager sm = System.getSecurityManager();
-      if (sm != null)
-         sm.checkPermission(setPrincipalInfoPermission);
-
-      SubjectContext sc = threadSubjectStacks.pop();
-      if (trace)
-      {
-         log.trace("popSubjectContext, sc="+sc);
-      }
-      
-      Principal principal = null;
-      Object credential = null;
-      
-      SubjectContext top = threadSubjectStacks.peek();
-      
-      if (top != null)
-      {
-         principal = top.getPrincipal();
-         credential = top.getCredential();
-      }
-      
-      if (server)
-      {
-         threadPrincipal.set(principal);
-         threadCredential.set(credential);
-      }
-      else
-      {
-         SecurityAssociation.principal = principal;
-         SecurityAssociation.credential = credential;
-      }
-      
-      if(server)
-      { 
-         if(trace)
-            log.trace("WARN::Deprecated usage of SecurityAssociation. Use SecurityContext");
-         SecurityContext sctx = SecurityContextAssociation.getSecurityContext();
-         
-         if(sc == null)
-         {
-            if(sctx != null)
-            {  
-               sc = new SubjectContext(sctx.getUtil().getSubject(),
-                     sctx.getUtil().getUserPrincipal(),
-                     sctx.getUtil().getCredential()); 
-            }
-         }
-         //Now pop the subject context on the security context
-         if(sctx != null)
-         {
-            sctx.getUtil().createSubjectInfo(null, null, null); 
-         } 
-         return sc;  
-      }
-      return top;
-   }
-   
-   /**
-    * Look at the current thread of control's authenticated identity on the top
-    * of the stack.
-    * When run under a security manager this requires the
-    * RuntimePermission("org.jboss.security.SecurityAssociation.getPrincipalInfo")
-    * permission.
-    * @return the SubjectContext pushed previously by a pushSubjectContext call
-    */
-   public static SubjectContext peekSubjectContext()
-   {
-      SecurityManager sm = System.getSecurityManager();
-      if (sm != null)
-         sm.checkPermission(getPrincipalInfoPermission);
-
-      if(server)
-      {
-         //Get the subject context from the security context
-         SecurityContext sc = SecurityContextAssociation.getSecurityContext();
-         SubjectContext subjectCtx = null;
-         if( sc != null)
-         {
-            SecurityContextUtil util = sc.getUtil();
-            subjectCtx = new SubjectContext(util.getSubject(), util.getUserPrincipal(), util.getCredential());
-         }
-         return subjectCtx; 
-      }
-      return threadSubjectStacks.peek();
-   }
-
-   /**
-    * Clear all principal information. If a security manager is present, then
-    * this method calls the security manager's <code>checkPermission</code>
-    * method with a <code> RuntimePermission("org.jboss.security.SecurityAssociation.setPrincipalInfo")
-    * </code> permission to ensure it's ok to access principal information. If
-    * not, a <code>SecurityException</code> will be thrown.
-    */
-   public static void clear()
-   {
-      SecurityManager sm = System.getSecurityManager();
-      if (sm != null)
-         sm.checkPermission(setPrincipalInfoPermission);
-
-      if (trace)
-         log.trace("clear, server=" + server);
-      if (server == true)
-      {
-         threadPrincipal.set(null);
-         threadCredential.set(null);
-      }
-      else
-      {
-         SecurityAssociation.principal = null;
-         SecurityAssociation.credential = null;
-      }
-      // Remove all subject contexts
-      threadSubjectStacks.clear(); 
-      
-      //Clear the security context
-      SecurityContextAssociation.clearSecurityContext();
-   }
-
-   /**
-    * Push the current thread of control's run-as identity.
-    */
-   public static void pushRunAsIdentity(RunAsIdentity runAs)
-   {
-      SecurityManager sm = System.getSecurityManager();
-      if (sm != null)
-         sm.checkPermission(setRunAsIdentity);
-      if (trace)
-         log.trace("pushRunAsIdentity, runAs=" + runAs);
-      
-      threadRunAsStacks.push(runAs);
-      SecurityContext sc = SecurityContextAssociation.getSecurityContext(); 
-      if( sc != null)
-      { 
-         sc.setOutgoingRunAs(runAs);
-      }
-   }
-
-   /**
-    * Pop the current thread of control's run-as identity.
-    */
-   public static RunAsIdentity popRunAsIdentity()
-   {
-      SecurityManager sm = System.getSecurityManager();
-      if (sm != null)
-         sm.checkPermission(setRunAsIdentity);
-      /*RunAsIdentity runAs = threadRunAsStacks.pop();
-      if (trace)
-         log.trace("popRunAsIdentity, runAs=" + runAs);
-      return runAs;*/
-      SecurityContext sc = SecurityContextAssociation.getSecurityContext();
-      RunAsIdentity ra = null; 
-      if( sc != null)
-      {
-         ra = (RunAsIdentity) sc.getOutgoingRunAs();
-         sc.setOutgoingRunAs(null);
-      }
-      return ra;
-   }
-
-   /**
-    * Look at the current thread of control's run-as identity on the top of the
-    * stack.
-    */
-   public static RunAsIdentity peekRunAsIdentity()
-   {
-      //return peekRunAsIdentity(0);
-      RunAsIdentity ra = null;
-      SecurityContext sc = SecurityContextAssociation.getSecurityContext(); 
-      if( sc != null)
-      {
-         ra = (RunAsIdentity) sc.getOutgoingRunAs();
-      }
-      return ra;
-   }
-
-   /**
-    * Look at the current thread of control's run-as identity at the indicated
-    * depth. Typically depth is either 0 for the identity the current caller
-    * run-as that will be assumed, or 1 for the active run-as the previous
-    * caller has assumed.
-    * @return RunAsIdentity depth frames up.
-    */
-   public static RunAsIdentity peekRunAsIdentity(int depth)
-   {
-      //RunAsIdentity runAs = threadRunAsStacks.peek(depth);
-      //return runAs;
-      if(depth > 1)
-         throw new IllegalArgumentException("Security Context approach needs to be used. Depth upto 1");
-      if(depth == 0)
-         return peekRunAsIdentity();
-      else
-      {
-         SecurityContext sc = SecurityContextAssociation.getSecurityContext();
-         RunAsIdentity ra = null; 
-         if( sc != null)
-         {
-            RunAs ras = sc.getIncomingRunAs();
-            if(ras instanceof RunAsIdentity)
-               ra = (RunAsIdentity) ras; 
-         }
-         return ra;
-      }
-   }
-   
-   /**
-    * Indicate whether we are server side
-    * @return flag set by a {@link #setServer()} call
-    */
-   public static boolean isServer()
-   {
-      return server;
-   }
-
-   /**
-    * Set the server mode of operation. When the server property has been set to
-    * true, the security information is maintained in thread local storage. This
-    * should be called to enable property security semantics in any
-    * multi-threaded environment where more than one thread requires that
-    * security information be restricted to the thread's flow of control.
-    *
-    * If a security manager is present, then this method calls the security
-    * manager's <code>checkPermission</code> method with a <code>
-    * RuntimePermission("org.jboss.security.SecurityAssociation.setServer")
-    * </code> permission to ensure it's ok to access principal information. If
-    * not, a <code>SecurityException</code> will be thrown.
-    */
-   public static void setServer()
-   {
-      SecurityManager sm = System.getSecurityManager();
-      if (sm != null)
-         sm.checkPermission(setServerPermission);
-
-      server = true;
-   }
-
-   /**
-    * A subclass of ThreadLocal that implements a value stack using an ArrayList
-    * and implements push, pop and peek stack operations on the thread local
-    * ArrayList.
-    */
-   private static class RunAsThreadLocalStack
-   {
-      @SuppressWarnings("unchecked")
-      ThreadLocal local;
-
-      RunAsThreadLocalStack(boolean threadLocal)
-      {
-         if( threadLocal == true )
-            local = new ArrayListLocal();
-         else
-            local = new ArrayListInheritableLocal();
-      }
-      
-      @SuppressWarnings("unchecked")
-      int size()
-      {
-         ArrayList stack = (ArrayList) local.get();
-         return stack.size();
-      }
-
-      @SuppressWarnings("unchecked")
-      void push(RunAsIdentity runAs)
-      {
-         ArrayList stack = (ArrayList) local.get();
-         stack.add(runAs);
-      }
-
-      @SuppressWarnings("unchecked")
-      RunAsIdentity pop()
-      {
-         ArrayList stack = (ArrayList) local.get();
-         RunAsIdentity runAs = null;
-         int lastIndex = stack.size() - 1;
-         if (lastIndex >= 0)
-            runAs = (RunAsIdentity) stack.remove(lastIndex);
-         return runAs;
-      }
-
-      /**
-       * Look for the first non-null run-as identity on the stack starting
-       * with the value at depth.
-       * @return The run-as identity if one exists, null otherwise.
-       */
-      @SuppressWarnings("unchecked")
-      RunAsIdentity peek(int depth)
-      {
-         ArrayList stack = (ArrayList) local.get();
-         RunAsIdentity runAs = null;
-         final int stackSize = stack.size();
-         do
-         {
-            int index = stackSize - 1 - depth;
-            if( index >= 0 )
-               runAs = (RunAsIdentity) stack.get(index);
-            depth ++;
-         }
-         while (runAs == null && depth <= stackSize - 1);
-         return runAs;
-      }
-   }
-
-   /**
-    * The encapsulation of the authenticated subject
-    */ 
-   public static class SubjectContext
-   {
-      public static final int SUBJECT_WAS_SET = 1;
-      public static final int PRINCIPAL_WAS_SET = 2;
-      public static final int CREDENTIAL_WAS_SET = 4;
-
-      private Subject subject;
-      private Principal principal;
-      private Object credential;
-      private int flags;
-
-      public SubjectContext()
-      {
-         this.flags = 0;
-      }
-      public SubjectContext(Subject s, Principal p, Object cred)
-      {
-         this.subject = s;
-         this.principal = p;
-         this.credential = cred;
-         this.flags = SUBJECT_WAS_SET | PRINCIPAL_WAS_SET | CREDENTIAL_WAS_SET;
-      }
-
-      public Subject getSubject()
-      {
-         return subject;
-      }
-      public void setSubject(Subject subject)
-      {
-         this.subject = subject;
-         this.flags |= SUBJECT_WAS_SET;
-      }
-
-      public Principal getPrincipal()
-      {
-         return principal;
-      }
-      public void setPrincipal(Principal principal)
-      {
-         this.principal = principal;
-         this.flags |= PRINCIPAL_WAS_SET;
-      }
-
-      public Object getCredential()
-      {
-         return credential;
-      }
-      public void setCredential(Object credential)
-      {
-         this.credential = credential;
-         this.flags |= CREDENTIAL_WAS_SET;
-      }
-
-      public int getFlags()
-      {
-         return this.flags;
-      }
-
-      public String toString()
-      {
-         StringBuffer tmp = new StringBuffer(super.toString());
-         tmp.append("{principal=");
-         tmp.append(principal);
-         tmp.append(",subject=");
-         if( subject != null )
-            tmp.append(System.identityHashCode(subject));
-         else
-            tmp.append("null");
-         tmp.append("}");
-         return tmp.toString();
-      }
-   }
-
-   @SuppressWarnings("unchecked")
-   private static class SubjectThreadLocalStack
-   {
-      ThreadLocal local;
-
-      SubjectThreadLocalStack(boolean threadLocal)
-      {
-         if( threadLocal == true )
-            local = new ArrayListLocal();
-         else
-            local = new ArrayListInheritableLocal();
-      }
-      
-      int size()
-      {
-         ArrayList stack = (ArrayList) local.get();
-         return stack.size();
-      }
-
-      void push(SubjectContext context)
-      {
-         ArrayList stack = (ArrayList) local.get();
-         stack.add(context);
-      }
-
-      SubjectContext dup()
-      {
-         ArrayList stack = (ArrayList) local.get();
-         SubjectContext context = null;
-         int lastIndex = stack.size() - 1;
-         if (lastIndex >= 0)
-         {
-            context = (SubjectContext) stack.get(lastIndex);
-            stack.add(context);
-         }
-         return context;
-      }
-
-      SubjectContext pop()
-      {
-         ArrayList stack = (ArrayList) local.get();
-         SubjectContext context = null;
-         int lastIndex = stack.size() - 1;
-         if (lastIndex >= 0)
-            context = (SubjectContext) stack.remove(lastIndex);
-         return context;
-      }
-
-      /**
-       * Look for the first non-null run-as identity on the stack starting
-       * with the value at depth.
-       * @return The run-as identity if one exists, null otherwise.
-       */
-      SubjectContext peek()
-      {
-         ArrayList stack = (ArrayList) local.get();
-         SubjectContext context = null;
-         int lastIndex = stack.size() - 1;
-         if (lastIndex >= 0)
-            context = (SubjectContext) stack.get(lastIndex);
-         return context;
-      }
-      /**
-       * Remove all SubjectContext from the current thread stack
-       */ 
-      void clear()
-      {
-         ArrayList stack = (ArrayList) local.get();
-         stack.clear();
-      }
-   }
-
-   @SuppressWarnings("unchecked")
-   private static class ArrayListLocal extends ThreadLocal
-   {
-      protected Object initialValue()
-      {
-         return new ArrayList();
-      }
-      
-   }
-
-   @SuppressWarnings("unchecked")
-   private static class ArrayListInheritableLocal extends InheritableThreadLocal
-   {
-      /**
-       * Override to make a copy of the parent as not doing so results in multiple
-       * threads sharing the unsynchronized list of the parent thread.
-       * @param parentValue - the parent ArrayList
-       * @return a copy of the parent thread list
-       */
-      protected Object childValue(Object parentValue)
-      {
-         ArrayList list = (ArrayList) parentValue;
-         /* It seems there are scenarios where the size can change during the copy so there is
-         a fallback to an empty list here.
-         */
-         ArrayList copy = null;
-         try
-         {
-            copy = new ArrayList(list);
-         }
-         catch(Throwable t)
-         {
-            log.debug("Failed to copy parent list, using new list");
-            copy = new ArrayList();
-         }
-         return copy;
-      }
-
-      protected Object initialValue()
-      {
-         return new ArrayList();
-      }
-      
-   }
-
-   @SuppressWarnings("unchecked")
-   private static class HashMapInheritableLocal<T> 
-   extends InheritableThreadLocal<HashMap<String,Object>>
-   {
-      /**
-       * Override to make a copy of the parent as not doing so results in multiple
-       * threads sharing the unsynchronized map of the parent thread.
-       * @param parentValue - the parent HashMap
-       * @return a copy of the parent thread map
-       */
-      protected HashMap<String,Object> childValue(Object parentValue)
-      {
-         HashMap<String,Object> map = (HashMap<String,Object>) parentValue;
-         /* It seems there are scenarios where the size can change during the copy so there is
-         a fallback to an empty map here.
-         */
-         HashMap<String,Object> copy = null;
-         try
-         {
-            copy = new HashMap<String,Object>(map);
-         }
-         catch(Throwable t)
-         {
-            log.debug("Failed to copy parent map, using new map");
-            copy = new HashMap<String,Object>();
-         }
-         return copy;
-      }
-
-      protected HashMap<String,Object> initialValue()
-      {
-         return new HashMap<String,Object>();
-      }
-      
-   }
-}

Copied: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/SecurityAssociation.java (from rev 93325, projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/security/SecurityAssociation.java)
===================================================================
--- projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/SecurityAssociation.java	                        (rev 0)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/SecurityAssociation.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -0,0 +1,1143 @@
+/*
+* JBoss, Home of Professional Open Source
+* Copyright 2005, JBoss Inc., and individual contributors as indicated
+* by the @authors tag. See the copyright.txt in the distribution for a
+* full listing of individual contributors.
+*
+* This is free software; you can redistribute it and/or modify it
+* under the terms of the GNU Lesser General Public License as
+* published by the Free Software Foundation; either version 2.1 of
+* the License, or (at your option) any later version.
+*
+* This software is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+* Lesser General Public License for more details.
+*
+* You should have received a copy of the GNU Lesser General Public
+* License along with this software; if not, write to the Free
+* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+*/
+package org.jboss.security;
+
+import java.security.Principal;
+import java.util.ArrayList;
+import java.util.HashMap;
+
+import javax.security.auth.Subject;
+
+import org.jboss.logging.Logger;
+
+/**
+ * The SecurityAssociation class maintains the security principal and
+ * credentials. This can be done on either a singleton basis or a thread local
+ * basis depending on the server property. When the server property has been set
+ * to true, the security information is maintained in thread local storage. The
+ * type of thread local storage depends on the org.jboss.security.SecurityAssociation.ThreadLocal
+ * property. If this property is true, then the thread local storage object is
+ * of type java.lang.ThreadLocal which results in the current thread's security
+ * information NOT being propagated to child threads.
+ *
+ * When the property is false or does not exist, the thread local storage object
+ * is of type java.lang.InheritableThreadLocal, and any threads spawned by the
+ * current thread will inherit the security information of the current thread.
+ * Subseqent changes to the current thread's security information are NOT
+ * propagated to any previously spawned child threads.
+ *
+ * When the server property is false, security information is maintained in
+ * class variables which makes the information available to all threads within
+ * the current VM.
+ * 
+ * Note that this is not a public API class. Its an implementation detail that
+ * is subject to change without notice.
+ * 
+ * @author Daniel O'Connor (docodan at nycap.rr.com)
+ * @author Scott.Stark at jboss.org
+ * @author Anil.Saldhana at redhat.com
+ * @version $Revision$
+ */
+public final class SecurityAssociation
+{
+   private static Logger log = Logger.getLogger(SecurityAssociation.class);
+   /**
+    * A flag indicating if trace level logging should be performed
+    */
+   private static boolean trace;
+   /**
+    * A flag indicating if security information is global or thread local
+    */
+   private static boolean server;
+   /**
+    * The SecurityAssociation principal used when the server flag is false
+    */
+   private static Principal principal;
+   /**
+    * The SecurityAssociation credential used when the server flag is false
+    */
+   private static Object credential;
+
+   /**
+    * The SecurityAssociation principal used when the server flag is true
+    */
+   private static ThreadLocal<Principal> threadPrincipal;
+   /**
+    * The SecurityAssociation credential used when the server flag is true
+    */
+   private static ThreadLocal<Object> threadCredential;
+   /**
+    * The SecurityAssociation HashMap<String, Object>
+    */
+   private static ThreadLocal<HashMap<String,Object>> threadContextMap;
+
+   /**
+    * Thread local stacks of run-as principal roles used to implement J2EE
+    * run-as identity propagation
+    */
+   private static RunAsThreadLocalStack threadRunAsStacks;
+   /**
+    * Thread local stacks of authenticated subject used to control the current
+    * caller security context
+    */ 
+   private static SubjectThreadLocalStack threadSubjectStacks; 
+
+   /**
+    * The permission required to access getPrincpal, getCredential
+    */
+   private static final RuntimePermission getPrincipalInfoPermission =
+      new RuntimePermission("org.jboss.security.SecurityAssociation.getPrincipalInfo");
+   /**
+    * The permission required to access getSubject
+    */
+   private static final RuntimePermission getSubjectPermission =
+      new RuntimePermission("org.jboss.security.SecurityAssociation.getSubject");
+   /**
+    * The permission required to access setPrincpal, setCredential, setSubject
+    * pushSubjectContext, popSubjectContext
+    */
+   private static final RuntimePermission setPrincipalInfoPermission =
+      new RuntimePermission("org.jboss.security.SecurityAssociation.setPrincipalInfo");
+   /**
+    * The permission required to access setServer
+    */
+   private static final RuntimePermission setServerPermission =
+      new RuntimePermission("org.jboss.security.SecurityAssociation.setServer");
+   /**
+    * The permission required to access pushRunAsIdentity/popRunAsIdentity
+    */
+   private static final RuntimePermission setRunAsIdentity =
+      new RuntimePermission("org.jboss.security.SecurityAssociation.setRunAsRole");
+   /**
+    * The permission required to get the current security context info
+    */
+   private static final RuntimePermission getContextInfo =
+      new RuntimePermission("org.jboss.security.SecurityAssociation.accessContextInfo", "get");
+   /**
+    * The permission required to set the current security context info
+    */
+   private static final RuntimePermission setContextInfo =
+      new RuntimePermission("org.jboss.security.SecurityAssociation.accessContextInfo", "set");
+
+   static
+   {
+      String flag = SecurityActions.getProperty("org.jboss.security.SecurityAssociation.ThreadLocal", "false");
+      boolean useThreadLocal = Boolean.valueOf(flag).booleanValue();
+      log.debug("Using ThreadLocal: "+useThreadLocal);
+
+      trace = log.isTraceEnabled();
+      if (useThreadLocal)
+      {
+         threadPrincipal = new ThreadLocal<Principal>();
+         threadCredential = new ThreadLocal<Object>();
+         threadContextMap = new ThreadLocal<HashMap<String,Object>>()
+         {
+            protected HashMap<String,Object> initialValue()
+            {
+               return new HashMap<String,Object>();
+            }
+         };
+      }
+      else
+      {
+         threadPrincipal = new InheritableThreadLocal<Principal>();
+         threadCredential = new InheritableThreadLocal<Object>();
+         threadContextMap = new HashMapInheritableLocal<HashMap<String,Object>>();
+      }
+      threadRunAsStacks = new RunAsThreadLocalStack(useThreadLocal);
+      threadSubjectStacks = new SubjectThreadLocalStack(useThreadLocal);
+   }
+
+   /**
+    * Get the current authentication principal information. If a security
+    * manager is present, then this method calls the security manager's
+    * <code>checkPermission</code> method with a
+    * <code>RuntimePermission("org.jboss.security.SecurityAssociation.getPrincipalInfo")
+    * </code> permission to ensure it's ok to access principal information. If
+    * not, a <code>SecurityException</code> will be thrown.
+    * @return Principal, the current principal identity.
+    */
+   public static Principal getPrincipal()
+   {
+      SecurityManager sm = System.getSecurityManager();
+      if (sm != null)
+         sm.checkPermission(getPrincipalInfoPermission);
+
+      Principal thePrincipal = principal;
+      
+      if(!server)
+         return principal;
+      
+      if( trace )
+         log.trace("getPrincipal, principal="+thePrincipal);
+      
+      SecurityContext sc = SecurityContextAssociation.getSecurityContext();
+      if(sc != null)
+      {
+         if( trace )
+            log.warn("You are using deprecated api to getPrincipal. Use security context based approach");
+         thePrincipal = sc.getUtil().getUserPrincipal();
+      }
+      return thePrincipal;
+   } 
+
+   /**
+    * Get the caller's principal. If a security manager is present,
+    * then this method calls the security manager's <code>checkPermission</code>
+    * method with a <code> RuntimePermission("org.jboss.security.SecurityAssociation.getPrincipalInfo")
+    * </code> permission to ensure it's ok to access principal information. If
+    * not, a <code>SecurityException</code> will be thrown.
+    * 
+    * @return Principal, the current principal identity.
+    */
+   public static Principal getCallerPrincipal()
+   {
+      SecurityManager sm = System.getSecurityManager();
+      if (sm != null)
+         sm.checkPermission(getPrincipalInfoPermission);
+
+      /*Principal thePrincipal = peekRunAsIdentity(1);
+      if( thePrincipal == null )
+      {
+         if (server)
+            thePrincipal = (Principal) threadPrincipal.get();
+         else
+            thePrincipal = principal;
+      }*/
+     
+      if(!server)
+         return principal;
+      
+      //Just pluck it from the current security context
+      SecurityContext sc = SecurityContextAssociation.getSecurityContext();
+      Principal thePrincipal = null;
+      if(sc != null)
+      {
+         //Check for runas
+         RunAs ras = sc.getIncomingRunAs();
+         if(ras != null)
+            thePrincipal = new SimplePrincipal(ras.getName());
+         else 
+            thePrincipal = sc.getUtil().getUserPrincipal();
+      }
+      if( trace )
+         log.trace("getCallerPrincipal, principal="+thePrincipal);
+      return thePrincipal;
+   }
+
+   /**
+    * Get the current authentication credential information. This can be of any type
+    * including: a String password, a char[] password, an X509 cert, etc. If a
+    * security manager is present, then this method calls the security manager's
+    * <code>checkPermission</code> method with a <code> RuntimePermission("org.jboss.security.SecurityAssociation.getPrincipalInfo")
+    * </code> permission to ensure it's ok to access principal information. If
+    * not, a <code>SecurityException</code> will be thrown.
+    * @return Object, the credential that proves the principal identity.
+    */
+   public static Object getCredential()
+   {
+      SecurityManager sm = System.getSecurityManager();
+      if (sm != null)
+         sm.checkPermission(getPrincipalInfoPermission);
+
+      if(!server)
+         return credential;
+      
+      SecurityContext sc = SecurityContextAssociation.getSecurityContext();
+      if(sc != null)
+      {
+         if(trace)
+            log.warn("You are using deprecated api to getCredential. Use security context based approach");
+         credential = sc.getUtil().getCredential();
+      }
+      return credential;
+   }
+
+   /**
+    * Get the current Subject information. If a security manager is present,
+    * then this method calls the security manager's checkPermission method with
+    * a  RuntimePermission("org.jboss.security.SecurityAssociation.getSubject")
+    * permission to ensure it's ok to access principal information. If not, a
+    * SecurityException will be thrown. Note that this method does not consider
+    * whether or not a run-as identity exists. For access to this information
+    * see the JACC PolicyContextHandler registered under the key
+    * "javax.security.auth.Subject.container"
+    * @return Subject, the current Subject identity.
+    * @see javax.security.jacc.PolicyContext#getContext(String)
+    */
+   public static Subject getSubject()
+   {
+      SecurityManager sm = System.getSecurityManager();
+      if (sm != null)
+         sm.checkPermission(getSubjectPermission);
+
+      SubjectContext sc = threadSubjectStacks.peek();
+      if( trace )
+         log.trace("getSubject, sc="+sc);
+      Subject subject = null;
+      /*if( sc != null )
+         subject = sc.getSubject();
+      return subject;*/
+      
+      SecurityContext secContext = SecurityAssociationActions.getSecurityContext();
+      if(secContext != null)
+      {
+         if(trace)
+            log.warn("You are using deprecated api to getSubject. Use security context based approach");
+         subject = secContext.getUtil().getSubject();
+      }
+      return subject;
+   }
+
+   /**
+    * Set the current principal information. If a security manager is present,
+    * then this method calls the security manager's <code>checkPermission</code>
+    * method with a <code> RuntimePermission("org.jboss.security.SecurityAssociation.setPrincipalInfo")
+    * </code> permission to ensure it's ok to access principal information. If
+    * not, a <code>SecurityException</code> will be thrown.
+    * @param principal - the current principal identity.
+    */
+   public static void setPrincipal(Principal principal)
+   {
+      SecurityManager sm = System.getSecurityManager();
+      if (sm != null)
+         sm.checkPermission(setPrincipalInfoPermission);
+
+      if (trace)
+         log.trace("setPrincipal, p=" + principal + ", server=" + server);
+      // Integrate with the new SubjectContext 
+      SubjectContext sc = threadSubjectStacks.peek();
+      if( sc == null )
+      {
+         // There is no active security context
+         sc = new SubjectContext();
+         threadSubjectStacks.push(sc);
+      }
+      else if( (sc.getFlags() & SubjectContext.PRINCIPAL_WAS_SET) != 0 )
+      {
+         // The current security context has its principal set
+         sc = new SubjectContext();
+         threadSubjectStacks.push(sc);    
+      }
+      sc.setPrincipal(principal);
+      
+      if(!server)
+      {
+         SecurityContextAssociation.setClient();
+         SecurityAssociation.principal = principal;
+         return; 
+      }
+      SecurityContext securityContext = SecurityContextAssociation.getSecurityContext();
+      //Clients code that may have set directly (Legacy)
+      if(securityContext == null)
+      {
+         try
+         {
+            securityContext = SecurityContextFactory.createSecurityContext("CLIENT_SIDE");
+         }
+         catch (Exception e)
+         {
+            throw new RuntimeException(e);
+         }
+         SecurityContextAssociation.setSecurityContext(securityContext);
+      }      
+      if(trace)
+         log.warn("Using deprecated API. Move to a security context based approach");
+      Object cred = securityContext.getUtil().getCredential();
+      Subject subj = securityContext.getUtil().getSubject();
+      securityContext.getUtil().createSubjectInfo(principal,cred, subj);
+     
+      if (trace)
+         log.trace("setPrincipal, sc="+sc);
+
+   } 
+
+   /**
+    * Set the current principal credential information. This can be of any type
+    * including: a String password, a char[] password, an X509 cert, etc.
+    *
+    * If a security manager is present, then this method calls the security
+    * manager's <code>checkPermission</code> method with a <code>
+    * RuntimePermission("org.jboss.security.SecurityAssociation.setPrincipalInfo")
+    * </code> permission to ensure it's ok to access principal information. If
+    * not, a <code>SecurityException</code> will be thrown.
+    * @param credential - the credential that proves the principal identity.
+    */
+   public static void setCredential(Object credential)
+   {
+      SecurityManager sm = System.getSecurityManager();
+      if (sm != null)
+         sm.checkPermission(setPrincipalInfoPermission);
+
+      // Integrate with the new SubjectContext 
+      SubjectContext sc = threadSubjectStacks.peek();
+      if( sc == null )
+      {
+         // There is no active security context
+         sc = new SubjectContext();
+         threadSubjectStacks.push(sc);
+      }
+      else if( (sc.getFlags() & SubjectContext.CREDENTIAL_WAS_SET) != 0 )
+      {
+         // The current security context has its principal set
+         sc = new SubjectContext();
+         threadSubjectStacks.push(sc);   
+      }
+      sc.setCredential(credential);
+      if (trace)
+         log.trace("setCredential, sc="+sc);
+
+      if(!server)
+      {
+         SecurityContextAssociation.setClient();
+         SecurityAssociation.credential = credential;
+         return;
+      }
+      
+      SecurityContext securityContext = SecurityContextAssociation.getSecurityContext();
+      //Clients code that may have set directly (Legacy)
+      if(securityContext == null)
+      {
+         try
+         {
+            securityContext = SecurityContextFactory.createSecurityContext("CLIENT_SIDE");
+         }
+         catch (Exception e)
+         {
+            throw new RuntimeException(e);
+         }
+         SecurityContextAssociation.setSecurityContext(securityContext);
+      }
+
+      if(trace)
+         log.warn("Using deprecated API. Move to a security context based approach");
+      Principal principal = securityContext.getUtil().getUserPrincipal();
+      Subject subj = securityContext.getUtil().getSubject();
+      securityContext.getUtil().createSubjectInfo(principal,credential, subj);      
+   }
+
+   /**
+    * Set the current Subject information. If a security manager is present,
+    * then this method calls the security manager's <code>checkPermission</code>
+    * method with a <code> RuntimePermission("org.jboss.security.SecurityAssociation.setPrincipalInfo")
+    * </code> permission to ensure it's ok to access principal information. If
+    * not, a <code>SecurityException</code> will be thrown.
+    * @param subject - the current identity.
+    */
+   public static void setSubject(Subject subject)
+   {
+      SecurityManager sm = System.getSecurityManager();
+      if (sm != null)
+         sm.checkPermission(setPrincipalInfoPermission);
+
+      if (trace)
+         log.trace("setSubject, s=" + subject + ", server=" + server);
+      // Integrate with the new SubjectContext 
+      SubjectContext sc = threadSubjectStacks.peek();
+      if( sc == null )
+      {
+         // There is no active security context
+         sc = new SubjectContext();
+         threadSubjectStacks.push(sc);
+      }
+      else if( (sc.getFlags() & SubjectContext.SUBJECT_WAS_SET) != 0 )
+      {
+         // The current security context has its subject set
+         sc = new SubjectContext();
+         threadSubjectStacks.push(sc); 
+      }
+      sc.setSubject(subject);
+      if (trace)
+         log.trace("setSubject, sc="+sc);
+      
+      SecurityContext sctx = SecurityContextAssociation.getSecurityContext();
+      if(sctx != null)
+      {
+         SubjectInfo si = sctx.getSubjectInfo();
+         if(si != null)
+         {
+            si.setAuthenticatedSubject(subject);
+         }
+         else
+            sctx.getUtil().createSubjectInfo(null, null, subject);
+      }
+   }
+
+   /**
+    * Get the current thread context info. If a security manager is present,
+    * then this method calls the security manager's <code>checkPermission</code>
+    * method with a <code> RuntimePermission("org.jboss.security.SecurityAssociation.accessContextInfo",
+    * "get") </code> permission to ensure it's ok to access context information.
+    * If not, a <code>SecurityException</code> will be thrown.
+    * @param key - the context key
+    * @return the mapping for the key in the current thread context
+    */
+   public static Object getContextInfo(String key)
+   {
+      SecurityManager sm = System.getSecurityManager();
+      if (sm != null)
+         sm.checkPermission(getContextInfo);
+
+      if(key == null)
+         throw new IllegalArgumentException("key is null");
+      HashMap<String,Object> contextInfo = (HashMap<String,Object>) threadContextMap.get();
+      return contextInfo != null ? contextInfo.get(key) : null;
+   }
+
+   /**
+    * Set the current thread context info. If a security manager is present,
+    * then this method calls the security manager's <code>checkPermission</code>
+    * method with a <code> RuntimePermission("org.jboss.security.SecurityAssociation.accessContextInfo",
+    * "set") </code> permission to ensure it's ok to access context information.
+    * If not, a <code>SecurityException</code> will be thrown.
+    * @param key - the context key
+    * @param value - the context value to associate under key
+    * @return the previous mapping for the key if one exists
+    */
+   public static Object setContextInfo(String key, Object value)
+   {
+      SecurityManager sm = System.getSecurityManager();
+      if (sm != null)
+         sm.checkPermission(setContextInfo);
+
+      HashMap<String,Object> contextInfo = (HashMap<String,Object>) threadContextMap.get();
+      return contextInfo.put(key, value);
+   }
+
+   /**
+    * Push the current authenticated context. This sets the authenticated subject
+    * along with the principal and proof of identity that was used to validate
+    * the subject. This context is used for authorization checks. Typically
+    * just the subject as seen by getSubject() is input into the authorization.
+    * When run under a security manager this requires the
+    * RuntimePermission("org.jboss.security.SecurityAssociation.setPrincipalInfo")
+    * permission.
+    * @param subject - the authenticated subject
+    * @param principal - the principal that was input into the authentication
+    * @param credential - the credential that was input into the authentication
+    * @deprecated
+    */ 
+   public static void pushSubjectContext(Subject subject,
+      Principal principal, Object credential)
+   {
+      SecurityManager sm = System.getSecurityManager();
+      if (sm != null)
+         sm.checkPermission(setPrincipalInfoPermission);
+
+      // Set the legacy single-value access points
+      if (server)
+      {
+         threadPrincipal.set(principal);
+         threadCredential.set(credential);    
+      }
+      else
+      {
+         SecurityAssociation.principal = principal;
+         SecurityAssociation.credential = credential;
+      }
+   
+      // Push the subject context
+      SubjectContext sc = new SubjectContext(subject, principal, credential);
+      threadSubjectStacks.push(sc);
+
+      if(server)
+      { 
+         if (trace)
+            log.trace("pushSubjectContext, subject=" + subject + ", sc="+sc);
+      
+         //Use the new method
+         SecurityContext sctx = SecurityContextAssociation.getSecurityContext();
+         if(sctx == null)
+         {
+            if(trace)
+               log.trace("WARN::Deprecated usage of SecurityAssociation. Use SecurityContext");
+            try
+            {
+               sctx = SecurityAssociationActions.createSecurityContext("FROM_SECURITY_ASSOCIATION");
+            }
+            catch (Exception e)
+            {
+               throw new RuntimeException(e);
+            }
+         }
+         sctx.getUtil().createSubjectInfo(principal, credential,subject);
+         SecurityAssociationActions.setSecurityContext(sctx);   
+      }
+   }
+   /**
+    * Push a duplicate of the current SubjectContext if one exists.
+    * When run under a security manager this requires the
+    * RuntimePermission("org.jboss.security.SecurityAssociation.setPrincipalInfo")
+    * permission.
+    */
+   public static void dupSubjectContext()
+   {
+      SecurityManager sm = System.getSecurityManager();
+      if (sm != null)
+         sm.checkPermission(setPrincipalInfoPermission);
+
+      SubjectContext sc = threadSubjectStacks.dup();
+      if (trace)
+         log.trace("dupSubjectContext, sc="+sc);
+   }
+
+   /**
+    * Pop the current SubjectContext from the previous pushSubjectContext call
+    * and return the pushed SubjectContext ig there was one.
+    * When run under a security manager this requires the
+    * RuntimePermission("org.jboss.security.SecurityAssociation.setPrincipalInfo")
+    * permission.
+    * @return the SubjectContext pushed previously by a pushSubjectContext call
+    * @deprecated
+    */ 
+   public static SubjectContext popSubjectContext()
+   {
+      SecurityManager sm = System.getSecurityManager();
+      if (sm != null)
+         sm.checkPermission(setPrincipalInfoPermission);
+
+      SubjectContext sc = threadSubjectStacks.pop();
+      if (trace)
+      {
+         log.trace("popSubjectContext, sc="+sc);
+      }
+      
+      Principal principal = null;
+      Object credential = null;
+      
+      SubjectContext top = threadSubjectStacks.peek();
+      
+      if (top != null)
+      {
+         principal = top.getPrincipal();
+         credential = top.getCredential();
+      }
+      
+      if (server)
+      {
+         threadPrincipal.set(principal);
+         threadCredential.set(credential);
+      }
+      else
+      {
+         SecurityAssociation.principal = principal;
+         SecurityAssociation.credential = credential;
+      }
+      
+      if(server)
+      { 
+         if(trace)
+            log.trace("WARN::Deprecated usage of SecurityAssociation. Use SecurityContext");
+         SecurityContext sctx = SecurityContextAssociation.getSecurityContext();
+         
+         if(sc == null)
+         {
+            if(sctx != null)
+            {  
+               sc = new SubjectContext(sctx.getUtil().getSubject(),
+                     sctx.getUtil().getUserPrincipal(),
+                     sctx.getUtil().getCredential()); 
+            }
+         }
+         //Now pop the subject context on the security context
+         if(sctx != null)
+         {
+            sctx.getUtil().createSubjectInfo(null, null, null); 
+         } 
+         return sc;  
+      }
+      return top;
+   }
+   
+   /**
+    * Look at the current thread of control's authenticated identity on the top
+    * of the stack.
+    * When run under a security manager this requires the
+    * RuntimePermission("org.jboss.security.SecurityAssociation.getPrincipalInfo")
+    * permission.
+    * @return the SubjectContext pushed previously by a pushSubjectContext call
+    */
+   public static SubjectContext peekSubjectContext()
+   {
+      SecurityManager sm = System.getSecurityManager();
+      if (sm != null)
+         sm.checkPermission(getPrincipalInfoPermission);
+
+      if(server)
+      {
+         //Get the subject context from the security context
+         SecurityContext sc = SecurityContextAssociation.getSecurityContext();
+         SubjectContext subjectCtx = null;
+         if( sc != null)
+         {
+            SecurityContextUtil util = sc.getUtil();
+            subjectCtx = new SubjectContext(util.getSubject(), util.getUserPrincipal(), util.getCredential());
+         }
+         return subjectCtx; 
+      }
+      return threadSubjectStacks.peek();
+   }
+
+   /**
+    * Clear all principal information. If a security manager is present, then
+    * this method calls the security manager's <code>checkPermission</code>
+    * method with a <code> RuntimePermission("org.jboss.security.SecurityAssociation.setPrincipalInfo")
+    * </code> permission to ensure it's ok to access principal information. If
+    * not, a <code>SecurityException</code> will be thrown.
+    */
+   public static void clear()
+   {
+      SecurityManager sm = System.getSecurityManager();
+      if (sm != null)
+         sm.checkPermission(setPrincipalInfoPermission);
+
+      if (trace)
+         log.trace("clear, server=" + server);
+      if (server == true)
+      {
+         threadPrincipal.set(null);
+         threadCredential.set(null);
+      }
+      else
+      {
+         SecurityAssociation.principal = null;
+         SecurityAssociation.credential = null;
+      }
+      // Remove all subject contexts
+      threadSubjectStacks.clear(); 
+      
+      //Clear the security context
+      SecurityContextAssociation.clearSecurityContext();
+   }
+
+   /**
+    * Push the current thread of control's run-as identity.
+    */
+   public static void pushRunAsIdentity(RunAsIdentity runAs)
+   {
+      SecurityManager sm = System.getSecurityManager();
+      if (sm != null)
+         sm.checkPermission(setRunAsIdentity);
+      if (trace)
+         log.trace("pushRunAsIdentity, runAs=" + runAs);
+      
+      threadRunAsStacks.push(runAs);
+      SecurityContext sc = SecurityContextAssociation.getSecurityContext(); 
+      if( sc != null)
+      { 
+         sc.setOutgoingRunAs(runAs);
+      }
+   }
+
+   /**
+    * Pop the current thread of control's run-as identity.
+    */
+   public static RunAsIdentity popRunAsIdentity()
+   {
+      SecurityManager sm = System.getSecurityManager();
+      if (sm != null)
+         sm.checkPermission(setRunAsIdentity);
+      /*RunAsIdentity runAs = threadRunAsStacks.pop();
+      if (trace)
+         log.trace("popRunAsIdentity, runAs=" + runAs);
+      return runAs;*/
+      SecurityContext sc = SecurityContextAssociation.getSecurityContext();
+      RunAsIdentity ra = null; 
+      if( sc != null)
+      {
+         ra = (RunAsIdentity) sc.getOutgoingRunAs();
+         sc.setOutgoingRunAs(null);
+      }
+      return ra;
+   }
+
+   /**
+    * Look at the current thread of control's run-as identity on the top of the
+    * stack.
+    */
+   public static RunAsIdentity peekRunAsIdentity()
+   {
+      //return peekRunAsIdentity(0);
+      RunAsIdentity ra = null;
+      SecurityContext sc = SecurityContextAssociation.getSecurityContext(); 
+      if( sc != null)
+      {
+         ra = (RunAsIdentity) sc.getOutgoingRunAs();
+      }
+      return ra;
+   }
+
+   /**
+    * Look at the current thread of control's run-as identity at the indicated
+    * depth. Typically depth is either 0 for the identity the current caller
+    * run-as that will be assumed, or 1 for the active run-as the previous
+    * caller has assumed.
+    * @return RunAsIdentity depth frames up.
+    */
+   public static RunAsIdentity peekRunAsIdentity(int depth)
+   {
+      //RunAsIdentity runAs = threadRunAsStacks.peek(depth);
+      //return runAs;
+      if(depth > 1)
+         throw new IllegalArgumentException("Security Context approach needs to be used. Depth upto 1");
+      if(depth == 0)
+         return peekRunAsIdentity();
+      else
+      {
+         SecurityContext sc = SecurityContextAssociation.getSecurityContext();
+         RunAsIdentity ra = null; 
+         if( sc != null)
+         {
+            RunAs ras = sc.getIncomingRunAs();
+            if(ras instanceof RunAsIdentity)
+               ra = (RunAsIdentity) ras; 
+         }
+         return ra;
+      }
+   }
+   
+   /**
+    * Indicate whether we are server side
+    * @return flag set by a {@link #setServer()} call
+    */
+   public static boolean isServer()
+   {
+      return server;
+   }
+
+   /**
+    * Set the server mode of operation. When the server property has been set to
+    * true, the security information is maintained in thread local storage. This
+    * should be called to enable property security semantics in any
+    * multi-threaded environment where more than one thread requires that
+    * security information be restricted to the thread's flow of control.
+    *
+    * If a security manager is present, then this method calls the security
+    * manager's <code>checkPermission</code> method with a <code>
+    * RuntimePermission("org.jboss.security.SecurityAssociation.setServer")
+    * </code> permission to ensure it's ok to access principal information. If
+    * not, a <code>SecurityException</code> will be thrown.
+    */
+   public static void setServer()
+   {
+      SecurityManager sm = System.getSecurityManager();
+      if (sm != null)
+         sm.checkPermission(setServerPermission);
+
+      server = true;
+   }
+
+   /**
+    * A subclass of ThreadLocal that implements a value stack using an ArrayList
+    * and implements push, pop and peek stack operations on the thread local
+    * ArrayList.
+    */
+   private static class RunAsThreadLocalStack
+   {
+      @SuppressWarnings("unchecked")
+      ThreadLocal local;
+
+      RunAsThreadLocalStack(boolean threadLocal)
+      {
+         if( threadLocal == true )
+            local = new ArrayListLocal();
+         else
+            local = new ArrayListInheritableLocal();
+      }
+      
+      @SuppressWarnings("unchecked")
+      int size()
+      {
+         ArrayList stack = (ArrayList) local.get();
+         return stack.size();
+      }
+
+      @SuppressWarnings("unchecked")
+      void push(RunAsIdentity runAs)
+      {
+         ArrayList stack = (ArrayList) local.get();
+         stack.add(runAs);
+      }
+
+      @SuppressWarnings("unchecked")
+      RunAsIdentity pop()
+      {
+         ArrayList stack = (ArrayList) local.get();
+         RunAsIdentity runAs = null;
+         int lastIndex = stack.size() - 1;
+         if (lastIndex >= 0)
+            runAs = (RunAsIdentity) stack.remove(lastIndex);
+         return runAs;
+      }
+
+      /**
+       * Look for the first non-null run-as identity on the stack starting
+       * with the value at depth.
+       * @return The run-as identity if one exists, null otherwise.
+       */
+      @SuppressWarnings("unchecked")
+      RunAsIdentity peek(int depth)
+      {
+         ArrayList stack = (ArrayList) local.get();
+         RunAsIdentity runAs = null;
+         final int stackSize = stack.size();
+         do
+         {
+            int index = stackSize - 1 - depth;
+            if( index >= 0 )
+               runAs = (RunAsIdentity) stack.get(index);
+            depth ++;
+         }
+         while (runAs == null && depth <= stackSize - 1);
+         return runAs;
+      }
+   }
+
+   /**
+    * The encapsulation of the authenticated subject
+    */ 
+   public static class SubjectContext
+   {
+      public static final int SUBJECT_WAS_SET = 1;
+      public static final int PRINCIPAL_WAS_SET = 2;
+      public static final int CREDENTIAL_WAS_SET = 4;
+
+      private Subject subject;
+      private Principal principal;
+      private Object credential;
+      private int flags;
+
+      public SubjectContext()
+      {
+         this.flags = 0;
+      }
+      public SubjectContext(Subject s, Principal p, Object cred)
+      {
+         this.subject = s;
+         this.principal = p;
+         this.credential = cred;
+         this.flags = SUBJECT_WAS_SET | PRINCIPAL_WAS_SET | CREDENTIAL_WAS_SET;
+      }
+
+      public Subject getSubject()
+      {
+         return subject;
+      }
+      public void setSubject(Subject subject)
+      {
+         this.subject = subject;
+         this.flags |= SUBJECT_WAS_SET;
+      }
+
+      public Principal getPrincipal()
+      {
+         return principal;
+      }
+      public void setPrincipal(Principal principal)
+      {
+         this.principal = principal;
+         this.flags |= PRINCIPAL_WAS_SET;
+      }
+
+      public Object getCredential()
+      {
+         return credential;
+      }
+      public void setCredential(Object credential)
+      {
+         this.credential = credential;
+         this.flags |= CREDENTIAL_WAS_SET;
+      }
+
+      public int getFlags()
+      {
+         return this.flags;
+      }
+
+      public String toString()
+      {
+         StringBuffer tmp = new StringBuffer(super.toString());
+         tmp.append("{principal=");
+         tmp.append(principal);
+         tmp.append(",subject=");
+         if( subject != null )
+            tmp.append(System.identityHashCode(subject));
+         else
+            tmp.append("null");
+         tmp.append("}");
+         return tmp.toString();
+      }
+   }
+
+   @SuppressWarnings("unchecked")
+   private static class SubjectThreadLocalStack
+   {
+      ThreadLocal local;
+
+      SubjectThreadLocalStack(boolean threadLocal)
+      {
+         if( threadLocal == true )
+            local = new ArrayListLocal();
+         else
+            local = new ArrayListInheritableLocal();
+      }
+      
+      int size()
+      {
+         ArrayList stack = (ArrayList) local.get();
+         return stack.size();
+      }
+
+      void push(SubjectContext context)
+      {
+         ArrayList stack = (ArrayList) local.get();
+         stack.add(context);
+      }
+
+      SubjectContext dup()
+      {
+         ArrayList stack = (ArrayList) local.get();
+         SubjectContext context = null;
+         int lastIndex = stack.size() - 1;
+         if (lastIndex >= 0)
+         {
+            context = (SubjectContext) stack.get(lastIndex);
+            stack.add(context);
+         }
+         return context;
+      }
+
+      SubjectContext pop()
+      {
+         ArrayList stack = (ArrayList) local.get();
+         SubjectContext context = null;
+         int lastIndex = stack.size() - 1;
+         if (lastIndex >= 0)
+            context = (SubjectContext) stack.remove(lastIndex);
+         return context;
+      }
+
+      /**
+       * Look for the first non-null run-as identity on the stack starting
+       * with the value at depth.
+       * @return The run-as identity if one exists, null otherwise.
+       */
+      SubjectContext peek()
+      {
+         ArrayList stack = (ArrayList) local.get();
+         SubjectContext context = null;
+         int lastIndex = stack.size() - 1;
+         if (lastIndex >= 0)
+            context = (SubjectContext) stack.get(lastIndex);
+         return context;
+      }
+      /**
+       * Remove all SubjectContext from the current thread stack
+       */ 
+      void clear()
+      {
+         ArrayList stack = (ArrayList) local.get();
+         stack.clear();
+      }
+   }
+
+   @SuppressWarnings("unchecked")
+   private static class ArrayListLocal extends ThreadLocal
+   {
+      protected Object initialValue()
+      {
+         return new ArrayList();
+      }
+      
+   }
+
+   @SuppressWarnings("unchecked")
+   private static class ArrayListInheritableLocal extends InheritableThreadLocal
+   {
+      /**
+       * Override to make a copy of the parent as not doing so results in multiple
+       * threads sharing the unsynchronized list of the parent thread.
+       * @param parentValue - the parent ArrayList
+       * @return a copy of the parent thread list
+       */
+      protected Object childValue(Object parentValue)
+      {
+         ArrayList list = (ArrayList) parentValue;
+         /* It seems there are scenarios where the size can change during the copy so there is
+         a fallback to an empty list here.
+         */
+         ArrayList copy = null;
+         try
+         {
+            copy = new ArrayList(list);
+         }
+         catch(Throwable t)
+         {
+            log.debug("Failed to copy parent list, using new list");
+            copy = new ArrayList();
+         }
+         return copy;
+      }
+
+      protected Object initialValue()
+      {
+         return new ArrayList();
+      }
+      
+   }
+
+   @SuppressWarnings("unchecked")
+   private static class HashMapInheritableLocal<T> 
+   extends InheritableThreadLocal<HashMap<String,Object>>
+   {
+      /**
+       * Override to make a copy of the parent as not doing so results in multiple
+       * threads sharing the unsynchronized map of the parent thread.
+       * @param parentValue - the parent HashMap
+       * @return a copy of the parent thread map
+       */
+      protected HashMap<String,Object> childValue(Object parentValue)
+      {
+         HashMap<String,Object> map = (HashMap<String,Object>) parentValue;
+         /* It seems there are scenarios where the size can change during the copy so there is
+         a fallback to an empty map here.
+         */
+         HashMap<String,Object> copy = null;
+         try
+         {
+            copy = new HashMap<String,Object>(map);
+         }
+         catch(Throwable t)
+         {
+            log.debug("Failed to copy parent map, using new map");
+            copy = new HashMap<String,Object>();
+         }
+         return copy;
+      }
+
+      protected HashMap<String,Object> initialValue()
+      {
+         return new HashMap<String,Object>();
+      }
+      
+   }
+}
\ No newline at end of file

Deleted: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/audit/providers/LogAuditProvider.java
===================================================================
--- projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/security/audit/providers/LogAuditProvider.java	2009-07-21 21:59:08 UTC (rev 91524)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/audit/providers/LogAuditProvider.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -1,39 +0,0 @@
-/*
- * JBoss, the OpenSource J2EE webOS
- *
- * Distributable under LGPL license.
- * See terms of license at gnu.org.
- */ 
-package org.jboss.security.audit.providers;
- 
-import org.jboss.logging.Logger;
-import org.jboss.security.audit.AbstractAuditProvider;
-import org.jboss.security.audit.AuditEvent;
-
-/**
- *  Audit Provider that just logs the audit event using a Logger.
- *  The flexibility of passing the audit log entries to a different
- *  sink (database, jms queue, file etc) can be controlled in the
- *  logging configuration (Eg: log4j.xml in log4j)
- *  <p>
- *  Ensure that the appender is configured properly in the 
- *  global log4j.xml for log entries to go to a log, separate
- *  from the regular server logs.
- *  </p>
- *  @author <a href="mailto:Anil.Saldhana at jboss.org">Anil Saldhana</a>
- *  @version $Revision$
- *  @since  Aug 21, 2006
- */
-public class LogAuditProvider extends AbstractAuditProvider
-{ 
-   private static final Logger log = Logger.getLogger(LogAuditProvider.class);
-   
-   public void audit(AuditEvent auditEvent)
-   {  
-      Exception e = auditEvent.getUnderlyingException();
-      if(e != null)
-         log.trace(auditEvent, e);
-      else
-         log.trace(auditEvent);
-   } 
-}
\ No newline at end of file

Copied: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/audit/providers/LogAuditProvider.java (from rev 93325, projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/security/audit/providers/LogAuditProvider.java)
===================================================================
--- projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/audit/providers/LogAuditProvider.java	                        (rev 0)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/audit/providers/LogAuditProvider.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -0,0 +1,42 @@
+/*
+ * JBoss, the OpenSource J2EE webOS
+ *
+ * Distributable under LGPL license.
+ * See terms of license at gnu.org.
+ */ 
+package org.jboss.security.audit.providers;
+ 
+import org.jboss.logging.Logger;
+import org.jboss.security.audit.AbstractAuditProvider;
+import org.jboss.security.audit.AuditEvent;
+
+/**
+ *  Audit Provider that just logs the audit event using a Logger.
+ *  The flexibility of passing the audit log entries to a different
+ *  sink (database, jms queue, file etc) can be controlled in the
+ *  logging configuration (Eg: log4j.xml in log4j)
+ *  <p>
+ *  Ensure that the appender is configured properly in the 
+ *  global log4j.xml for log entries to go to a log, separate
+ *  from the regular server logs.
+ *  </p>
+ *  @author <a href="mailto:Anil.Saldhana at jboss.org">Anil Saldhana</a>
+ *  @version $Revision$
+ *  @since  Aug 21, 2006
+ */
+public class LogAuditProvider extends AbstractAuditProvider
+{ 
+   private static final Logger log = Logger.getLogger(LogAuditProvider.class);
+   private boolean trace = log.isTraceEnabled();
+   
+   public void audit(AuditEvent auditEvent)
+   {  
+      Exception e = auditEvent.getUnderlyingException();
+      if(e != null)
+         if(trace)
+            log.trace(auditEvent, e);
+      else
+         if(trace)
+            log.trace(auditEvent);
+   } 
+}
\ No newline at end of file

Deleted: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/container/modules/AbstractServerAuthModule.java
===================================================================
--- projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/security/auth/container/modules/AbstractServerAuthModule.java	2009-07-21 21:59:08 UTC (rev 91524)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/container/modules/AbstractServerAuthModule.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -1,154 +0,0 @@
-/*
-  * JBoss, Home of Professional Open Source
-  * Copyright 2005, JBoss Inc., and individual contributors as indicated
-  * by the @authors tag. See the copyright.txt in the distribution for a
-  * full listing of individual contributors.
-  *
-  * This is free software; you can redistribute it and/or modify it
-  * under the terms of the GNU Lesser General Public License as
-  * published by the Free Software Foundation; either version 2.1 of
-  * the License, or (at your option) any later version.
-  *
-  * This software is distributed in the hope that it will be useful,
-  * but WITHOUT ANY WARRANTY; without even the implied warranty of
-  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-  * Lesser General Public License for more details.
-  *
-  * You should have received a copy of the GNU Lesser General Public
-  * License along with this software; if not, write to the Free
-  * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-  * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
-  */
-package org.jboss.security.auth.container.modules;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.security.auth.Subject;
-import javax.security.auth.callback.CallbackHandler;
-import javax.security.auth.message.AuthException;
-import javax.security.auth.message.AuthStatus;
-import javax.security.auth.message.MessageInfo;
-import javax.security.auth.message.MessagePolicy;
-import javax.security.auth.message.module.ServerAuthModule;
-import javax.security.auth.spi.LoginModule;
-
-import org.jboss.logging.Logger;
-
-//$Id$
-
-/**
- *  Superclass of all ServerAuthModules
- *  Can be a container for common functionality and custom methods
- *  <p>
- *  The ServerAuthModule can delegate to a login module passed
- *  via the module option "login-module-delegate"
- *  </p>
- *  @author <a href="mailto:Anil.Saldhana at jboss.org">Anil Saldhana</a>
- *  @since  Jan 9, 2006 
- *  @version $Revision$
- */
- at SuppressWarnings("unchecked")
-public abstract class AbstractServerAuthModule implements ServerAuthModule
-{  
-   /**
-    * Call back handler  
-    */
-   protected CallbackHandler callbackHandler = null;
-   
-   protected MessagePolicy requestPolicy = null;
-   
-   protected MessagePolicy responsePolicy = null; 
-   
-   protected Map options = null;   
-   
-   protected ArrayList<Class> supportedTypes = new ArrayList<Class>();
-   
-   protected Logger log;
-
-   /**
-    * @see ServerAuthModule#initialize(MessagePolicy, MessagePolicy, CallbackHandler, Map, boolean)
-    */ 
-   public void initialize(MessagePolicy requestPolicy, MessagePolicy responsePolicy, 
-         CallbackHandler handler, Map options )
-         throws AuthException
-   {
-     this.requestPolicy = requestPolicy;
-     this.responsePolicy = responsePolicy;
-     this.callbackHandler = handler;
-     if(options == null)
-        options = new HashMap();
-     this.options = options; 
-   }  
-
-   public void cleanSubject(MessageInfo messageInfo, Subject subject) throws AuthException
-   {
-      //Clear out the principals and credentials
-      subject.getPrincipals().clear();
-      subject.getPublicCredentials().clear();
-      subject.getPrivateCredentials().clear();
-   }
-
-   /**
-    * This method delegates to a login module if configured in the module options.
-    * The sub classes will need to validate the request 
-    */
-   public AuthStatus validateRequest(MessageInfo messageInfo, Subject clientSubject, 
-         Subject serviceSubject) 
-   throws AuthException
-   {
-      String loginModuleName = (String) options.get("login-module-delegate");
-      if(loginModuleName != null)
-      {
-         ClassLoader tcl = SecurityActions.getContextClassLoader();
-         try
-         {
-            Class clazz = tcl.loadClass(loginModuleName);
-            LoginModule lm = (LoginModule) clazz.newInstance();
-            lm.initialize(clientSubject, callbackHandler, new HashMap(), options);
-            lm.login();
-            lm.commit();
-         }
-         catch (Exception e)
-         {
-            throw new AuthException(e.getLocalizedMessage());
-         }
-      } 
-      else
-      {
-         return validate(clientSubject, messageInfo) ? AuthStatus.SUCCESS : AuthStatus.FAILURE;
-      } 
-      
-      return AuthStatus.SUCCESS;
-   }
-   
-   /**
-    * @see ServerAuthModule#getSupportedMessageTypes()
-    */
-   public Class[] getSupportedMessageTypes()
-   { 
-      Class[] clsarr = new Class[this.supportedTypes.size()];
-      supportedTypes.toArray(clsarr);
-      return clsarr;
-   } 
-   
-    
-   //Value Added Methods 
-   public CallbackHandler getCallbackHandler()
-   {
-      return callbackHandler;
-   }
-   
-   public void setCallbackHandler(CallbackHandler callbackHandler)
-   {
-      this.callbackHandler = callbackHandler;
-   }
-   
-   /**
-    * Subclasses have to implement this method to actually validate the subject
-    * @return
-    * @throws AuthException
-    */
-   protected abstract boolean validate(Subject clientSubject, MessageInfo messageInfo) throws AuthException; 
-}

Copied: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/container/modules/AbstractServerAuthModule.java (from rev 93325, projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/security/auth/container/modules/AbstractServerAuthModule.java)
===================================================================
--- projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/container/modules/AbstractServerAuthModule.java	                        (rev 0)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/container/modules/AbstractServerAuthModule.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -0,0 +1,155 @@
+/*
+  * JBoss, Home of Professional Open Source
+  * Copyright 2005, JBoss Inc., and individual contributors as indicated
+  * by the @authors tag. See the copyright.txt in the distribution for a
+  * full listing of individual contributors.
+  *
+  * This is free software; you can redistribute it and/or modify it
+  * under the terms of the GNU Lesser General Public License as
+  * published by the Free Software Foundation; either version 2.1 of
+  * the License, or (at your option) any later version.
+  *
+  * This software is distributed in the hope that it will be useful,
+  * but WITHOUT ANY WARRANTY; without even the implied warranty of
+  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+  * Lesser General Public License for more details.
+  *
+  * You should have received a copy of the GNU Lesser General Public
+  * License along with this software; if not, write to the Free
+  * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+  * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+  */
+package org.jboss.security.auth.container.modules;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.security.auth.Subject;
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.message.AuthException;
+import javax.security.auth.message.AuthStatus;
+import javax.security.auth.message.MessageInfo;
+import javax.security.auth.message.MessagePolicy;
+import javax.security.auth.message.module.ServerAuthModule;
+import javax.security.auth.spi.LoginModule;
+
+import org.jboss.logging.Logger;
+
+//$Id$
+
+/**
+ *  Superclass of all ServerAuthModules
+ *  Can be a container for common functionality and custom methods
+ *  <p>
+ *  The ServerAuthModule can delegate to a login module passed
+ *  via the module option "login-module-delegate"
+ *  </p>
+ *  @author <a href="mailto:Anil.Saldhana at jboss.org">Anil Saldhana</a>
+ *  @since  Jan 9, 2006 
+ *  @version $Revision$
+ */
+ at SuppressWarnings("unchecked")
+public abstract class AbstractServerAuthModule implements ServerAuthModule
+{  
+   /**
+    * Call back handler  
+    */
+   protected CallbackHandler callbackHandler = null;
+   
+   protected MessagePolicy requestPolicy = null;
+   
+   protected MessagePolicy responsePolicy = null; 
+   
+   protected Map options = null;   
+   
+   protected ArrayList<Class> supportedTypes = new ArrayList<Class>();
+   
+   protected Logger log;
+   protected boolean trace = false;
+
+   /**
+    * @see ServerAuthModule#initialize(MessagePolicy, MessagePolicy, CallbackHandler, Map, boolean)
+    */ 
+   public void initialize(MessagePolicy requestPolicy, MessagePolicy responsePolicy, 
+         CallbackHandler handler, Map options )
+         throws AuthException
+   {
+     this.requestPolicy = requestPolicy;
+     this.responsePolicy = responsePolicy;
+     this.callbackHandler = handler;
+     if(options == null)
+        options = new HashMap();
+     this.options = options; 
+   }  
+
+   public void cleanSubject(MessageInfo messageInfo, Subject subject) throws AuthException
+   {
+      //Clear out the principals and credentials
+      subject.getPrincipals().clear();
+      subject.getPublicCredentials().clear();
+      subject.getPrivateCredentials().clear();
+   }
+
+   /**
+    * This method delegates to a login module if configured in the module options.
+    * The sub classes will need to validate the request 
+    */
+   public AuthStatus validateRequest(MessageInfo messageInfo, Subject clientSubject, 
+         Subject serviceSubject) 
+   throws AuthException
+   {
+      String loginModuleName = (String) options.get("login-module-delegate");
+      if(loginModuleName != null)
+      {
+         ClassLoader tcl = SecurityActions.getContextClassLoader();
+         try
+         {
+            Class clazz = tcl.loadClass(loginModuleName);
+            LoginModule lm = (LoginModule) clazz.newInstance();
+            lm.initialize(clientSubject, callbackHandler, new HashMap(), options);
+            lm.login();
+            lm.commit();
+         }
+         catch (Exception e)
+         {
+            throw new AuthException(e.getLocalizedMessage());
+         }
+      } 
+      else
+      {
+         return validate(clientSubject, messageInfo) ? AuthStatus.SUCCESS : AuthStatus.FAILURE;
+      } 
+      
+      return AuthStatus.SUCCESS;
+   }
+   
+   /**
+    * @see ServerAuthModule#getSupportedMessageTypes()
+    */
+   public Class[] getSupportedMessageTypes()
+   { 
+      Class[] clsarr = new Class[this.supportedTypes.size()];
+      supportedTypes.toArray(clsarr);
+      return clsarr;
+   } 
+   
+    
+   //Value Added Methods 
+   public CallbackHandler getCallbackHandler()
+   {
+      return callbackHandler;
+   }
+   
+   public void setCallbackHandler(CallbackHandler callbackHandler)
+   {
+      this.callbackHandler = callbackHandler;
+   }
+   
+   /**
+    * Subclasses have to implement this method to actually validate the subject
+    * @return
+    * @throws AuthException
+    */
+   protected abstract boolean validate(Subject clientSubject, MessageInfo messageInfo) throws AuthException; 
+}

Deleted: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/container/modules/DelegatingServerAuthModule.java
===================================================================
--- projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/security/auth/container/modules/DelegatingServerAuthModule.java	2009-07-21 21:59:08 UTC (rev 91524)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/container/modules/DelegatingServerAuthModule.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -1,111 +0,0 @@
-/*
-  * JBoss, Home of Professional Open Source
-  * Copyright 2007, JBoss Inc., and individual contributors as indicated
-  * by the @authors tag. See the copyright.txt in the distribution for a
-  * full listing of individual contributors.
-  *
-  * This is free software; you can redistribute it and/or modify it
-  * under the terms of the GNU Lesser General Public License as
-  * published by the Free Software Foundation; either version 2.1 of
-  * the License, or (at your option) any later version.
-  *
-  * This software is distributed in the hope that it will be useful,
-  * but WITHOUT ANY WARRANTY; without even the implied warranty of
-  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-  * Lesser General Public License for more details.
-  *
-  * You should have received a copy of the GNU Lesser General Public
-  * License along with this software; if not, write to the Free
-  * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-  * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
-  */
-package org.jboss.security.auth.container.modules;
-
-import javax.security.auth.Subject;
-import javax.security.auth.login.LoginContext;
-import javax.security.auth.login.LoginException;
-import javax.security.auth.message.AuthException;
-import javax.security.auth.message.AuthStatus;
-import javax.security.auth.message.MessageInfo;
-
-import org.jboss.logging.Logger;
- 
-/**
- *  Server Auth Module that delegates work to a login context 
- *  @author Anil.Saldhana at redhat.com
- *  @since  Jul 25, 2007 
- *  @version $Revision$
- */
- at SuppressWarnings("unchecked")
-public class DelegatingServerAuthModule extends AbstractServerAuthModule
-{  
-   private LoginContext loginContext = null;
-   private String loginContextName = null;
-
-   public DelegatingServerAuthModule()
-   {  
-      log = Logger.getLogger(DelegatingServerAuthModule.class);
-      this.supportedTypes.add(Object.class);
-   }
-   
-   public DelegatingServerAuthModule(String loginModuleStackHolderName)
-   {
-      this();
-      this.loginContextName = loginModuleStackHolderName;
-   }
-   
-   public Class[] getSupportedMessageTypes()
-   { 
-      Class[] clarr = new Class[this.supportedTypes.size()];
-      this.supportedTypes.toArray(clarr);
-      return clarr;
-   }
-
-   public void cleanSubject(MessageInfo messageInfo, Subject subject) throws AuthException
-   {
-      if(loginContext != null)
-         try
-         {
-            loginContext.logout();
-         }
-         catch (LoginException e)
-         {
-            throw new AuthException(e.getLocalizedMessage());
-         } 
-   }
-
-   public AuthStatus secureResponse(MessageInfo messageInfo, Subject arg1) throws AuthException
-   { 
-      throw new RuntimeException("Not Implemented");
-   } 
-   
-   @Override
-   protected boolean validate(Subject clientSubject, MessageInfo messageInfo) throws AuthException
-   {
-      try
-      {
-         loginContext = SecurityActions.createLoginContext(getSecurityDomainName(), clientSubject, this.callbackHandler);
-         loginContext.login();
-         return true;
-      }
-      catch (Exception e)
-      {
-         log.trace("Exception in validate:",e);
-         throw new AuthException(e.getLocalizedMessage());
-      }   
-   }
-
-   private String getSecurityDomainName()
-   {
-      if(loginContextName != null)
-         return loginContextName;
-      
-      //Check if it is passed in the options
-      String domainName = (String) options.get("javax.security.auth.login.LoginContext");
-      if(domainName == null)
-      {
-         domainName = getClass().getName();  
-      }
-      return domainName;
-   }
-}

Copied: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/container/modules/DelegatingServerAuthModule.java (from rev 93325, projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/security/auth/container/modules/DelegatingServerAuthModule.java)
===================================================================
--- projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/container/modules/DelegatingServerAuthModule.java	                        (rev 0)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/container/modules/DelegatingServerAuthModule.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -0,0 +1,113 @@
+/*
+  * JBoss, Home of Professional Open Source
+  * Copyright 2007, JBoss Inc., and individual contributors as indicated
+  * by the @authors tag. See the copyright.txt in the distribution for a
+  * full listing of individual contributors.
+  *
+  * This is free software; you can redistribute it and/or modify it
+  * under the terms of the GNU Lesser General Public License as
+  * published by the Free Software Foundation; either version 2.1 of
+  * the License, or (at your option) any later version.
+  *
+  * This software is distributed in the hope that it will be useful,
+  * but WITHOUT ANY WARRANTY; without even the implied warranty of
+  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+  * Lesser General Public License for more details.
+  *
+  * You should have received a copy of the GNU Lesser General Public
+  * License along with this software; if not, write to the Free
+  * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+  * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+  */
+package org.jboss.security.auth.container.modules;
+
+import javax.security.auth.Subject;
+import javax.security.auth.login.LoginContext;
+import javax.security.auth.login.LoginException;
+import javax.security.auth.message.AuthException;
+import javax.security.auth.message.AuthStatus;
+import javax.security.auth.message.MessageInfo;
+
+import org.jboss.logging.Logger;
+ 
+/**
+ *  Server Auth Module that delegates work to a login context 
+ *  @author Anil.Saldhana at redhat.com
+ *  @since  Jul 25, 2007 
+ *  @version $Revision$
+ */
+ at SuppressWarnings("unchecked")
+public class DelegatingServerAuthModule extends AbstractServerAuthModule
+{  
+   private LoginContext loginContext = null;
+   private String loginContextName = null;
+
+   public DelegatingServerAuthModule()
+   {  
+      log = Logger.getLogger(DelegatingServerAuthModule.class);
+      trace = log.isTraceEnabled();
+      this.supportedTypes.add(Object.class);
+   }
+   
+   public DelegatingServerAuthModule(String loginModuleStackHolderName)
+   {
+      this();
+      this.loginContextName = loginModuleStackHolderName;
+   }
+   
+   public Class[] getSupportedMessageTypes()
+   { 
+      Class[] clarr = new Class[this.supportedTypes.size()];
+      this.supportedTypes.toArray(clarr);
+      return clarr;
+   }
+
+   public void cleanSubject(MessageInfo messageInfo, Subject subject) throws AuthException
+   {
+      if(loginContext != null)
+         try
+         {
+            loginContext.logout();
+         }
+         catch (LoginException e)
+         {
+            throw new AuthException(e.getLocalizedMessage());
+         } 
+   }
+
+   public AuthStatus secureResponse(MessageInfo messageInfo, Subject arg1) throws AuthException
+   { 
+      throw new RuntimeException("Not Implemented");
+   } 
+   
+   @Override
+   protected boolean validate(Subject clientSubject, MessageInfo messageInfo) throws AuthException
+   {
+      try
+      {
+         loginContext = SecurityActions.createLoginContext(getSecurityDomainName(), clientSubject, this.callbackHandler);
+         loginContext.login();
+         return true;
+      }
+      catch (Exception e)
+      {
+         if(trace)
+            log.trace("Exception in validate:",e);
+         throw new AuthException(e.getLocalizedMessage());
+      }   
+   }
+
+   private String getSecurityDomainName()
+   {
+      if(loginContextName != null)
+         return loginContextName;
+      
+      //Check if it is passed in the options
+      String domainName = (String) options.get("javax.security.auth.login.LoginContext");
+      if(domainName == null)
+      {
+         domainName = getClass().getName();  
+      }
+      return domainName;
+   }
+}
\ No newline at end of file

Deleted: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/login/XMLLoginConfigImpl.java
===================================================================
--- projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/security/auth/login/XMLLoginConfigImpl.java	2009-07-21 21:59:08 UTC (rev 91524)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/login/XMLLoginConfigImpl.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -1,445 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source
- * Copyright 2005, JBoss Inc., and individual contributors as indicated
- * by the @authors tag. See the copyright.txt in the distribution for a
- * full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jboss.security.auth.login;
-
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.Serializable;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
-import java.util.ArrayList;
-
-import javax.security.auth.AuthPermission;
-import javax.security.auth.login.AppConfigurationEntry;
-import javax.security.auth.login.Configuration;
-
-import org.jboss.logging.Logger;
-import org.jboss.security.config.ApplicationPolicy;
-import org.jboss.security.config.ApplicationPolicyRegistration;
-import org.jboss.security.config.PolicyConfig;
-import org.jboss.security.config.SecurityConfiguration;
-
-/**
- * An concrete implementation of the javax.security.auth.login.Configuration class that parses an xml configuration of
- * the form:
- * 
- * <policy> <application-policy name = "test-domain"> <authentication> <login-module code =
- * "org.jboss.security.plugins.samples.IdentityLoginModule" flag = "required"> <module-option name = "principal">starksm</module-option>
- * </login-module> </authentication> </application-policy> </policy>
- * 
- * @see javax.security.auth.login.Configuration
- * 
- * @author Scott.Stark at jboss.org
- * @author Anil.Saldhana at jboss.org
- * @version $Revision: 57482 $
- */
-public class XMLLoginConfigImpl extends Configuration implements Serializable, ApplicationPolicyRegistration
-{
-   /** The serialVersionUID */
-   private static final long serialVersionUID = -8965860493224188277L;
-
-   private static final String DEFAULT_APP_CONFIG_NAME = "other";
-
-   private static final AuthPermission REFRESH_PERM = new AuthPermission("refreshLoginConfiguration");
-
-   private static Logger log = Logger.getLogger(XMLLoginConfigImpl.class);
-
-   transient PolicyConfig appConfigs = new PolicyConfig();
-
-   /** The URL to the XML or Sun login configuration */
-   protected URL loginConfigURL;
-
-   /** The inherited configuration we delegate to */
-   protected Configuration parentConfig;
-
-   /** A flag indicating if XML configs should be validated */
-   private boolean validateDTD = true;
-
-   private static final XMLLoginConfigImpl instance = new XMLLoginConfigImpl();
-
-   /**
-    * <p>
-    * Private constructor to implement the singleton pattern.
-    * </p>
-    */
-   private XMLLoginConfigImpl()
-   {
-   }
-
-   /**
-    * <p>
-    * Obtains a reference to the singleton.
-    * </p>
-    * 
-    * @return a reference to the singleton {@code XMLLoginConfigImpl} instance.
-    */
-   public static XMLLoginConfigImpl getInstance()
-   {
-      return instance;
-   }
-
-   // --- Begin Configuration method overrrides
-   @Override
-   public void refresh()
-   {
-      SecurityManager sm = System.getSecurityManager();
-      if (sm != null)
-         sm.checkPermission(REFRESH_PERM);
-      if (log.isTraceEnabled())
-         log.trace("Begin refresh");
-      appConfigs.clear();
-      loadConfig();
-      if (log.isTraceEnabled())
-         log.trace("End refresh");
-   }
-
-   @Override
-   public AppConfigurationEntry[] getAppConfigurationEntry(String appName)
-   {
-      if (log.isTraceEnabled())
-         log.trace("Begin getAppConfigurationEntry(" + appName + "), size=" + appConfigs.size());
-
-      // Load the config if PolicyConfig is empty
-      if (this.appConfigs.size() == 0)
-         this.loadConfig();
-
-      AppConfigurationEntry[] entry = null;
-      ApplicationPolicy aPolicy = this.getApplicationPolicy(appName);
-      BaseAuthenticationInfo authInfo = null;
-      if (aPolicy != null)
-         authInfo = aPolicy.getAuthenticationInfo();
-
-      if (authInfo == null)
-      {
-         if (log.isTraceEnabled())
-            log.trace("getAppConfigurationEntry(" + appName + "), no entry in appConfigs, tyring parentCont: "
-                  + parentConfig);
-         if (parentConfig != null)
-            entry = parentConfig.getAppConfigurationEntry(appName);
-         if (entry == null)
-         {
-            if (log.isTraceEnabled())
-               log.trace("getAppConfigurationEntry(" + appName + "), no entry in parentConfig, trying: "
-                     + DEFAULT_APP_CONFIG_NAME);
-         }
-         ApplicationPolicy defPolicy = appConfigs.get(DEFAULT_APP_CONFIG_NAME);
-         authInfo = defPolicy != null ? (AuthenticationInfo) defPolicy.getAuthenticationInfo() : null;
-      }
-
-      if (authInfo != null)
-      {
-         if (log.isTraceEnabled())
-            log.trace("End getAppConfigurationEntry(" + appName + "), authInfo=" + authInfo);
-         // Make a copy of the authInfo object
-         final BaseAuthenticationInfo theAuthInfo = authInfo;
-         PrivilegedAction<AppConfigurationEntry[]> action = new PrivilegedAction<AppConfigurationEntry[]>()
-         {
-            public AppConfigurationEntry[] run()
-            {
-               return theAuthInfo.copyAppConfigurationEntry();
-            }
-         };
-         entry = AccessController.doPrivileged(action);
-      }
-      else
-      {
-         if (log.isTraceEnabled())
-            log.trace("End getAppConfigurationEntry(" + appName + "), failed to find entry");
-      }
-
-      return entry;
-   }
-
-   // --- End Configuration method overrrides
-
-   /**
-    * Set the URL of the XML login configuration file that should be loaded by this mbean on startup.
-    */
-   public URL getConfigURL()
-   {
-      return loginConfigURL;
-   }
-
-   /**
-    * Set the URL of the XML login configuration file that should be loaded by this mbean on startup.
-    */
-   public void setConfigURL(URL loginConfigURL)
-   {
-      this.loginConfigURL = loginConfigURL;
-   }
-
-   public void setConfigResource(String resourceName) throws IOException
-   {
-      ClassLoader tcl = SecurityActions.getContextClassLoader();
-      loginConfigURL = tcl.getResource(resourceName);
-      if (loginConfigURL == null)
-         throw new IOException("Failed to find resource: " + resourceName);
-   }
-
-   public void setParentConfig(Configuration parentConfig)
-   {
-      this.parentConfig = parentConfig;
-   }
-
-   /**
-    * Get whether the login config xml document is validated againsts its DTD
-    */
-   public boolean getValidateDTD()
-   {
-      return this.validateDTD;
-   }
-
-   /**
-    * Set whether the login config xml document is validated againsts its DTD
-    */
-   public void setValidateDTD(boolean flag)
-   {
-      this.validateDTD = flag;
-   }
-
-   /**
-    * @see ApplicationPolicyRegistration#addApplicationPolicy(String, ApplicationPolicy)
-    */
-   public void addApplicationPolicy(String appName, ApplicationPolicy aPolicy)
-   {
-      SecurityManager sm = System.getSecurityManager();
-      if (sm != null)
-         sm.checkPermission(REFRESH_PERM);
-      appConfigs.add(aPolicy);
-      handleJASPIDelegation(aPolicy);
-      SecurityConfiguration.addApplicationPolicy(aPolicy);
-   }
-
-   /**
-    * Add an application configuration
-    */
-   public void addAppConfig(String appName, AppConfigurationEntry[] entries)
-   {
-      SecurityManager sm = System.getSecurityManager();
-      if (sm != null)
-         sm.checkPermission(REFRESH_PERM);
-      AuthenticationInfo authInfo = new AuthenticationInfo(appName);
-      authInfo.setAppConfigurationEntry(entries);
-      if (log.isTraceEnabled())
-         log.trace("addAppConfig(" + appName + "), authInfo=" + authInfo);
-      ApplicationPolicy aPolicy = new ApplicationPolicy(appName, authInfo);
-      appConfigs.add(aPolicy);
-      SecurityConfiguration.addApplicationPolicy(aPolicy);
-   }
-   
-   public void copy(PolicyConfig policyConfig)
-   {
-      this.appConfigs.copy(policyConfig);
-   }
-
-   /**
-    * @deprecated
-    * @see #removeApplicationPolicy(String)
-    * @param appName
-    */
-   @Deprecated
-   public void removeAppConfig(String appName)
-   {
-      SecurityManager sm = System.getSecurityManager();
-      if (sm != null)
-         sm.checkPermission(REFRESH_PERM);
-      if (log.isTraceEnabled())
-         log.trace("removeAppConfig, appName=" + appName);
-      appConfigs.remove(appName);
-      SecurityConfiguration.removeApplicationPolicy(appName);
-   }
-
-   /**
-    * @see ApplicationPolicyRegistration#getApplicationPolicy(String)
-    */
-   public ApplicationPolicy getApplicationPolicy(String domainName)
-   {
-      if (appConfigs == null || appConfigs.size() == 0)
-         loadConfig();
-      ApplicationPolicy aPolicy = null;
-      if(appConfigs != null )
-         aPolicy = appConfigs.get(domainName);
-      if (aPolicy != null)
-         SecurityConfiguration.addApplicationPolicy(aPolicy);
-      return aPolicy;
-   }
-
-   /**
-    * @see ApplicationPolicyRegistration#removeApplicationPolicy(String)
-    */
-   public boolean removeApplicationPolicy(String appName)
-   {
-      SecurityManager sm = System.getSecurityManager();
-      if (sm != null)
-         sm.checkPermission(REFRESH_PERM);
-      if (log.isTraceEnabled())
-         log.trace("removeAppConfig, appName=" + appName);
-      appConfigs.remove(appName);
-      SecurityConfiguration.removeApplicationPolicy(appName);
-      return true;
-   }
-
-   /**
-    * Method that returns the parsed AuthenticationInfo needed by the JASPI framework until a seperate Configuration
-    * mechanism for JASPI is established
-    * 
-    * @return the parsed AuthenticationInfo object
-    */
-   public BaseAuthenticationInfo getAuthenticationInfo(String domainName)
-   {
-      ApplicationPolicy aPolicy = getApplicationPolicy(domainName);
-      return aPolicy != null ? aPolicy.getAuthenticationInfo() : null;
-   }
-
-   public void clear()
-   {
-
-   }
-
-   /**
-    * Called to try to load the config from the java.security.auth.login.config property value when there is no
-    * loginConfigURL.
-    */
-   public void loadConfig()
-   {
-      // Try to load the java.security.auth.login.config property
-      String loginConfig = System.getProperty("java.security.auth.login.config");
-      if (loginConfig == null)
-         loginConfig = "login-config.xml";
-
-      // If there is no loginConfigURL build it from the loginConfig
-      if (loginConfigURL == null)
-      {
-         try
-         {
-            // Try as a URL
-            loginConfigURL = new URL(loginConfig);
-         }
-         catch (MalformedURLException e)
-         {
-            // Try as a resource
-            try
-            {
-               setConfigResource(loginConfig);
-            }
-            catch (IOException ignore)
-            {
-               // Try as a file
-               File configFile = new File(loginConfig);
-               try
-               {
-                  setConfigURL(configFile.toURL());
-               }
-               catch (MalformedURLException ignore2)
-               {
-               }
-            }
-         }
-      }
-
-      if (loginConfigURL == null)
-      {
-         log.warn("Failed to find config: " + loginConfig);
-         return;
-      }
-
-      if (log.isTraceEnabled())
-         log.trace("Begin loadConfig, loginConfigURL=" + loginConfigURL);
-      // Try to load the config if found
-      try
-      {
-         loadConfig(loginConfigURL);
-         if (log.isTraceEnabled())
-            log.trace("End loadConfig, loginConfigURL=" + loginConfigURL);
-      }
-      catch (Exception e)
-      {
-         log.warn("End loadConfig, failed to load config: " + loginConfigURL, e);
-      }
-   }
-
-   @SuppressWarnings("unchecked")
-   protected String[] loadConfig(URL config) throws Exception
-   {
-      SecurityManager sm = System.getSecurityManager();
-      if (sm != null)
-         sm.checkPermission(REFRESH_PERM);
-
-      ArrayList configNames = new ArrayList();
-      log.debug("Try loading config as XML, url=" + config);
-      try
-      {
-         loadXMLConfig(config, configNames);
-      }
-      catch (Throwable e)
-      {
-         log.debug("Failed to load config as XML", e);
-         log.debug("Try loading config as Sun format, url=" + config);
-         loadSunConfig(config, configNames);
-      }
-      String[] names = new String[configNames.size()];
-      configNames.toArray(names);
-      return names;
-   }
-
-   /**
-    * Handle the case when JASPI Info may have login module stack holder which delegates to a login module stack
-    * 
-    * @param aPolicy
-    */
-   private void handleJASPIDelegation(ApplicationPolicy aPolicy)
-   {
-      BaseAuthenticationInfo bai = aPolicy.getAuthenticationInfo();
-      if (bai instanceof JASPIAuthenticationInfo)
-      {
-         JASPIAuthenticationInfo jai = (JASPIAuthenticationInfo) bai;
-         LoginModuleStackHolder[] lmsharr = jai.getLoginModuleStackHolder();
-         for (LoginModuleStackHolder lmsh : lmsharr)
-         {
-            this.addAppConfig(lmsh.getName(), lmsh.getAppConfigurationEntry());
-         }
-      }
-   }
-
-   @SuppressWarnings("unchecked")
-   private void loadSunConfig(URL sunConfig, ArrayList configNames) throws Exception
-   {
-      InputStream is = sunConfig.openStream();
-      if (is == null)
-         throw new IOException("InputStream is null for: " + sunConfig);
-
-      InputStreamReader configFile = new InputStreamReader(is);
-      boolean trace = log.isTraceEnabled();
-      SunConfigParser.doParse(configFile, this, trace);
-   }
-
-   @SuppressWarnings("unchecked")
-   private void loadXMLConfig(URL loginConfigURL, ArrayList configNames) throws Exception
-   {
-      JBossXBParsingUtil xbUtil = new JBossXBParsingUtil();
-      xbUtil.parse(loginConfigURL, configNames); 
-   }  
-}

Copied: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/login/XMLLoginConfigImpl.java (from rev 93325, projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/security/auth/login/XMLLoginConfigImpl.java)
===================================================================
--- projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/login/XMLLoginConfigImpl.java	                        (rev 0)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/login/XMLLoginConfigImpl.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -0,0 +1,449 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005, JBoss Inc., and individual contributors as indicated
+ * by the @authors tag. See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.security.auth.login;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.Serializable;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.security.AccessController;
+import java.security.PrivilegedAction;
+import java.util.ArrayList;
+
+import javax.security.auth.AuthPermission;
+import javax.security.auth.login.AppConfigurationEntry;
+import javax.security.auth.login.Configuration;
+
+import org.jboss.logging.Logger;
+import org.jboss.security.config.ApplicationPolicy;
+import org.jboss.security.config.ApplicationPolicyRegistration;
+import org.jboss.security.config.PolicyConfig;
+import org.jboss.security.config.SecurityConfiguration;
+
+/**
+ * An concrete implementation of the javax.security.auth.login.Configuration class that parses an xml configuration of
+ * the form:
+ * 
+ * <policy> <application-policy name = "test-domain"> <authentication> <login-module code =
+ * "org.jboss.security.plugins.samples.IdentityLoginModule" flag = "required"> <module-option name = "principal">starksm</module-option>
+ * </login-module> </authentication> </application-policy> </policy>
+ * 
+ * @see javax.security.auth.login.Configuration
+ * 
+ * @author Scott.Stark at jboss.org
+ * @author Anil.Saldhana at jboss.org
+ * @version $Revision: 57482 $
+ */
+public class XMLLoginConfigImpl extends Configuration implements Serializable, ApplicationPolicyRegistration
+{
+   /** The serialVersionUID */
+   private static final long serialVersionUID = -8965860493224188277L;
+
+   private static final String DEFAULT_APP_CONFIG_NAME = "other";
+
+   private static final AuthPermission REFRESH_PERM = new AuthPermission("refreshLoginConfiguration");
+
+   private static Logger log = Logger.getLogger(XMLLoginConfigImpl.class);
+   private boolean trace = log.isTraceEnabled();
+
+   transient PolicyConfig appConfigs = new PolicyConfig();
+
+   /** The URL to the XML or Sun login configuration */
+   protected URL loginConfigURL;
+
+   /** The inherited configuration we delegate to */
+   protected Configuration parentConfig;
+
+   /** A flag indicating if XML configs should be validated */
+   private boolean validateDTD = true;
+
+   private static final XMLLoginConfigImpl instance = new XMLLoginConfigImpl();
+
+   /**
+    * <p>
+    * Private constructor to implement the singleton pattern.
+    * </p>
+    */
+   private XMLLoginConfigImpl()
+   {
+   }
+
+   /**
+    * <p>
+    * Obtains a reference to the singleton.
+    * </p>
+    * 
+    * @return a reference to the singleton {@code XMLLoginConfigImpl} instance.
+    */
+   public static XMLLoginConfigImpl getInstance()
+   {
+      return instance;
+   }
+
+   // --- Begin Configuration method overrrides
+   @Override
+   public void refresh()
+   {
+      SecurityManager sm = System.getSecurityManager();
+      if (sm != null)
+         sm.checkPermission(REFRESH_PERM);
+      if (log.isTraceEnabled())
+         log.trace("Begin refresh");
+      appConfigs.clear();
+      loadConfig();
+      if (log.isTraceEnabled())
+         log.trace("End refresh");
+   }
+
+   @Override
+   public AppConfigurationEntry[] getAppConfigurationEntry(String appName)
+   {
+      if (log.isTraceEnabled())
+         log.trace("Begin getAppConfigurationEntry(" + appName + "), size=" + appConfigs.size());
+
+      // Load the config if PolicyConfig is empty
+      if (this.appConfigs.size() == 0)
+         this.loadConfig();
+
+      AppConfigurationEntry[] entry = null;
+      ApplicationPolicy aPolicy = this.getApplicationPolicy(appName);
+      BaseAuthenticationInfo authInfo = null;
+      if (aPolicy != null)
+         authInfo = aPolicy.getAuthenticationInfo();
+
+      if (authInfo == null)
+      {
+         if (log.isTraceEnabled())
+            log.trace("getAppConfigurationEntry(" + appName + "), no entry in appConfigs, tyring parentCont: "
+                  + parentConfig);
+         if (parentConfig != null)
+            entry = parentConfig.getAppConfigurationEntry(appName);
+         if (entry == null)
+         {
+            if (log.isTraceEnabled())
+               log.trace("getAppConfigurationEntry(" + appName + "), no entry in parentConfig, trying: "
+                     + DEFAULT_APP_CONFIG_NAME);
+         }
+         ApplicationPolicy defPolicy = appConfigs.get(DEFAULT_APP_CONFIG_NAME);
+         authInfo = defPolicy != null ? (AuthenticationInfo) defPolicy.getAuthenticationInfo() : null;
+      }
+
+      if (authInfo != null)
+      {
+         if (log.isTraceEnabled())
+            log.trace("End getAppConfigurationEntry(" + appName + "), authInfo=" + authInfo);
+         // Make a copy of the authInfo object
+         final BaseAuthenticationInfo theAuthInfo = authInfo;
+         PrivilegedAction<AppConfigurationEntry[]> action = new PrivilegedAction<AppConfigurationEntry[]>()
+         {
+            public AppConfigurationEntry[] run()
+            {
+               return theAuthInfo.copyAppConfigurationEntry();
+            }
+         };
+         entry = AccessController.doPrivileged(action);
+      }
+      else
+      {
+         if (log.isTraceEnabled())
+            log.trace("End getAppConfigurationEntry(" + appName + "), failed to find entry");
+      }
+
+      return entry;
+   }
+
+   // --- End Configuration method overrrides
+
+   /**
+    * Set the URL of the XML login configuration file that should be loaded by this mbean on startup.
+    */
+   public URL getConfigURL()
+   {
+      return loginConfigURL;
+   }
+
+   /**
+    * Set the URL of the XML login configuration file that should be loaded by this mbean on startup.
+    */
+   public void setConfigURL(URL loginConfigURL)
+   {
+      this.loginConfigURL = loginConfigURL;
+   }
+
+   public void setConfigResource(String resourceName) throws IOException
+   {
+      ClassLoader tcl = SecurityActions.getContextClassLoader();
+      loginConfigURL = tcl.getResource(resourceName);
+      if (loginConfigURL == null)
+         throw new IOException("Failed to find resource: " + resourceName);
+   }
+
+   public void setParentConfig(Configuration parentConfig)
+   {
+      this.parentConfig = parentConfig;
+   }
+
+   /**
+    * Get whether the login config xml document is validated againsts its DTD
+    */
+   public boolean getValidateDTD()
+   {
+      return this.validateDTD;
+   }
+
+   /**
+    * Set whether the login config xml document is validated againsts its DTD
+    */
+   public void setValidateDTD(boolean flag)
+   {
+      this.validateDTD = flag;
+   }
+
+   /**
+    * @see ApplicationPolicyRegistration#addApplicationPolicy(String, ApplicationPolicy)
+    */
+   public void addApplicationPolicy(String appName, ApplicationPolicy aPolicy)
+   {
+      SecurityManager sm = System.getSecurityManager();
+      if (sm != null)
+         sm.checkPermission(REFRESH_PERM);
+      appConfigs.add(aPolicy);
+      handleJASPIDelegation(aPolicy);
+      SecurityConfiguration.addApplicationPolicy(aPolicy);
+   }
+
+   /**
+    * Add an application configuration
+    */
+   public void addAppConfig(String appName, AppConfigurationEntry[] entries)
+   {
+      SecurityManager sm = System.getSecurityManager();
+      if (sm != null)
+         sm.checkPermission(REFRESH_PERM);
+      AuthenticationInfo authInfo = new AuthenticationInfo(appName);
+      authInfo.setAppConfigurationEntry(entries);
+      if (log.isTraceEnabled())
+         log.trace("addAppConfig(" + appName + "), authInfo=" + authInfo);
+      ApplicationPolicy aPolicy = new ApplicationPolicy(appName, authInfo);
+      appConfigs.add(aPolicy);
+      SecurityConfiguration.addApplicationPolicy(aPolicy);
+   }
+   
+   public void copy(PolicyConfig policyConfig)
+   {
+      this.appConfigs.copy(policyConfig);
+   }
+
+   /**
+    * @deprecated
+    * @see #removeApplicationPolicy(String)
+    * @param appName
+    */
+   @Deprecated
+   public void removeAppConfig(String appName)
+   {
+      SecurityManager sm = System.getSecurityManager();
+      if (sm != null)
+         sm.checkPermission(REFRESH_PERM);
+      if (log.isTraceEnabled())
+         log.trace("removeAppConfig, appName=" + appName);
+      appConfigs.remove(appName);
+      SecurityConfiguration.removeApplicationPolicy(appName);
+   }
+
+   /**
+    * @see ApplicationPolicyRegistration#getApplicationPolicy(String)
+    */
+   public ApplicationPolicy getApplicationPolicy(String domainName)
+   {
+      if (appConfigs == null || appConfigs.size() == 0)
+         loadConfig();
+      ApplicationPolicy aPolicy = null;
+      if(appConfigs != null )
+         aPolicy = appConfigs.get(domainName);
+      if (aPolicy != null)
+         SecurityConfiguration.addApplicationPolicy(aPolicy);
+      return aPolicy;
+   }
+
+   /**
+    * @see ApplicationPolicyRegistration#removeApplicationPolicy(String)
+    */
+   public boolean removeApplicationPolicy(String appName)
+   {
+      SecurityManager sm = System.getSecurityManager();
+      if (sm != null)
+         sm.checkPermission(REFRESH_PERM);
+      if (log.isTraceEnabled())
+         log.trace("removeAppConfig, appName=" + appName);
+      appConfigs.remove(appName);
+      SecurityConfiguration.removeApplicationPolicy(appName);
+      return true;
+   }
+
+   /**
+    * Method that returns the parsed AuthenticationInfo needed by the JASPI framework until a seperate Configuration
+    * mechanism for JASPI is established
+    * 
+    * @return the parsed AuthenticationInfo object
+    */
+   public BaseAuthenticationInfo getAuthenticationInfo(String domainName)
+   {
+      ApplicationPolicy aPolicy = getApplicationPolicy(domainName);
+      return aPolicy != null ? aPolicy.getAuthenticationInfo() : null;
+   }
+
+   public void clear()
+   {
+
+   }
+
+   /**
+    * Called to try to load the config from the java.security.auth.login.config property value when there is no
+    * loginConfigURL.
+    */
+   public void loadConfig()
+   {
+      // Try to load the java.security.auth.login.config property
+      String loginConfig = System.getProperty("java.security.auth.login.config");
+      if (loginConfig == null)
+         loginConfig = "login-config.xml";
+
+      // If there is no loginConfigURL build it from the loginConfig
+      if (loginConfigURL == null)
+      {
+         try
+         {
+            // Try as a URL
+            loginConfigURL = new URL(loginConfig);
+         }
+         catch (MalformedURLException e)
+         {
+            // Try as a resource
+            try
+            {
+               setConfigResource(loginConfig);
+            }
+            catch (IOException ignore)
+            {
+               // Try as a file
+               File configFile = new File(loginConfig);
+               try
+               {
+                  setConfigURL(configFile.toURL());
+               }
+               catch (MalformedURLException ignore2)
+               {
+               }
+            }
+         }
+      }
+
+      if (loginConfigURL == null)
+      {
+         log.warn("Failed to find config: " + loginConfig);
+         return;
+      }
+
+      if (log.isTraceEnabled())
+         log.trace("Begin loadConfig, loginConfigURL=" + loginConfigURL);
+      // Try to load the config if found
+      try
+      {
+         loadConfig(loginConfigURL);
+         if (log.isTraceEnabled())
+            log.trace("End loadConfig, loginConfigURL=" + loginConfigURL);
+      }
+      catch (Exception e)
+      {
+         log.warn("End loadConfig, failed to load config: " + loginConfigURL, e);
+      }
+   }
+
+   @SuppressWarnings("unchecked")
+   protected String[] loadConfig(URL config) throws Exception
+   {
+      SecurityManager sm = System.getSecurityManager();
+      if (sm != null)
+         sm.checkPermission(REFRESH_PERM);
+
+      ArrayList configNames = new ArrayList();
+      log.debug("Try loading config as XML, url=" + config);
+      try
+      {
+         loadXMLConfig(config, configNames);
+      }
+      catch (Throwable e)
+      {
+         if(trace)
+         {
+            log.debug("Failed to load config as XML", e);
+            log.debug("Try loading config as Sun format, url=" + config);
+         }
+         loadSunConfig(config, configNames);
+      }
+      String[] names = new String[configNames.size()];
+      configNames.toArray(names);
+      return names;
+   }
+
+   /**
+    * Handle the case when JASPI Info may have login module stack holder which delegates to a login module stack
+    * 
+    * @param aPolicy
+    */
+   private void handleJASPIDelegation(ApplicationPolicy aPolicy)
+   {
+      BaseAuthenticationInfo bai = aPolicy.getAuthenticationInfo();
+      if (bai instanceof JASPIAuthenticationInfo)
+      {
+         JASPIAuthenticationInfo jai = (JASPIAuthenticationInfo) bai;
+         LoginModuleStackHolder[] lmsharr = jai.getLoginModuleStackHolder();
+         for (LoginModuleStackHolder lmsh : lmsharr)
+         {
+            this.addAppConfig(lmsh.getName(), lmsh.getAppConfigurationEntry());
+         }
+      }
+   }
+
+   @SuppressWarnings("unchecked")
+   private void loadSunConfig(URL sunConfig, ArrayList configNames) throws Exception
+   {
+      InputStream is = sunConfig.openStream();
+      if (is == null)
+         throw new IOException("InputStream is null for: " + sunConfig);
+
+      InputStreamReader configFile = new InputStreamReader(is);
+      boolean trace = log.isTraceEnabled();
+      SunConfigParser.doParse(configFile, this, trace);
+   }
+
+   @SuppressWarnings("unchecked")
+   private void loadXMLConfig(URL loginConfigURL, ArrayList configNames) throws Exception
+   {
+      JBossXBParsingUtil xbUtil = new JBossXBParsingUtil();
+      xbUtil.parse(loginConfigURL, configNames); 
+   }  
+}
\ No newline at end of file

Deleted: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/AbstractServerLoginModule.java
===================================================================
--- projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/security/auth/spi/AbstractServerLoginModule.java	2009-07-21 21:59:08 UTC (rev 91524)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/AbstractServerLoginModule.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -1,342 +0,0 @@
-/*
-* JBoss, Home of Professional Open Source
-* Copyright 2005, JBoss Inc., and individual contributors as indicated
-* by the @authors tag. See the copyright.txt in the distribution for a
-* full listing of individual contributors.
-*
-* This is free software; you can redistribute it and/or modify it
-* under the terms of the GNU Lesser General Public License as
-* published by the Free Software Foundation; either version 2.1 of
-* the License, or (at your option) any later version.
-*
-* This software is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-* Lesser General Public License for more details.
-*
-* You should have received a copy of the GNU Lesser General Public
-* License along with this software; if not, write to the Free
-* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
-*/
-package org.jboss.security.auth.spi;
-
-
-import java.lang.reflect.Constructor;
-import java.security.Principal;
-import java.security.acl.Group;
-import java.util.Enumeration;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Set;
-
-import javax.security.auth.Subject;
-import javax.security.auth.callback.CallbackHandler;
-import javax.security.auth.login.LoginException;
-import javax.security.auth.spi.LoginModule;
-
-import org.jboss.logging.Logger;
-import org.jboss.security.NestableGroup;
-import org.jboss.security.SecurityConstants;
-import org.jboss.security.SimpleGroup;
-import org.jboss.security.SimplePrincipal;
-
-/**
- * This class implements the common functionality required for a JAAS
- * server side LoginModule and implements the JBossSX standard Subject usage
- * pattern of storing identities and roles. Subclass this module to create your
- * own custom LoginModule and override the login(), getRoleSets() and getIdentity()
- * methods.
- * <p>
- * You may also wish to override
- * <pre>
- *    public void initialize(Subject subject, CallbackHandler callbackHandler, Map sharedState, Map options)
- * </pre>
- * In which case the first line of your initialize() method should be:
- * <pre>
- *    super.initialize(subject, callbackHandler, sharedState, options);
- * </pre>
- * <p>
- * You may also wish to override
- * <pre>
- *    public boolean login() throws LoginException
- * </pre>
- * In which case the last line of your login() method should be
- * <pre>
- *    return super.login();
- * </pre>
- *
- *@author <a href="edward.kenworthy at crispgroup.co.uk">Edward Kenworthy</a>, 12th Dec 2000
- *@author Scott.Stark at jboss.org
- *@version $Revision$
- */
-public abstract class AbstractServerLoginModule implements LoginModule
-{
-   protected Subject subject;
-   protected CallbackHandler callbackHandler;
-   @SuppressWarnings("unchecked")
-   protected Map sharedState;
-   @SuppressWarnings("unchecked")
-   protected Map options;
-   protected Logger log;
-   /** Flag indicating if the shared credential should be used */
-   protected boolean useFirstPass;
-   /** Flag indicating if the login phase succeeded. Subclasses that override
-    the login method must set this to true on successful completion of login
-    */
-   protected boolean loginOk;
-   /** An optional custom Principal class implementation */
-   protected String principalClassName;
-   /** the principal to use when a null username and password are seen */
-   protected Principal unauthenticatedIdentity;
-
-//--- Begin LoginModule interface methods
-   /** Initialize the login module. This stores the subject, callbackHandler
-    * and sharedState and options for the login session. Subclasses should override
-    * if they need to process their own options. A call to super.initialize(...)
-    * must be made in the case of an override.
-    * <p>
-    * @option password-stacking: If this is set to "useFirstPass", the login
-    * identity will be taken from the <code>javax.security.auth.login.name</code>
-    * value of the sharedState map, and the proof of identity from the
-    * <code>javax.security.auth.login.password</code> value of the sharedState
-    * map.
-    * @option principalClass: A Principal implementation that support a ctor
-    *   taking a String argument for the princpal name.
-    * @option unauthenticatedIdentity: the name of the principal to asssign
-    * and authenticate when a null username and password are seen.
-    * 
-    * @param subject the Subject to update after a successful login.
-    * @param callbackHandler the CallbackHandler that will be used to obtain the
-    *    the user identity and credentials.
-    * @param sharedState a Map shared between all configured login module instances
-    * @param options the parameters passed to the login module.
-    */
-   public void initialize(Subject subject, CallbackHandler callbackHandler,
-      Map<String,?> sharedState, Map<String,?> options)
-   {
-      this.subject = subject;
-      this.callbackHandler = callbackHandler;
-      this.sharedState = sharedState;
-      this.options = options;
-      log = Logger.getLogger(getClass());
-      log.trace("initialize");
-
-      //log securityDomain, if set.
-      log.trace("Security domain: " + 
-		(String)options.get(SecurityConstants.SECURITY_DOMAIN_OPTION));
-
-      /* Check for password sharing options. Any non-null value for
-         password_stacking sets useFirstPass as this module has no way to
-         validate any shared password.
-      */
-      String passwordStacking = (String) options.get("password-stacking");
-      if( passwordStacking != null && passwordStacking.equalsIgnoreCase("useFirstPass") )
-         useFirstPass = true;
-
-      // Check for a custom Principal implementation
-      principalClassName = (String) options.get("principalClass");
-
-      // Check for unauthenticatedIdentity option.
-      String name = (String) options.get("unauthenticatedIdentity");
-      if( name != null )
-      {
-         try
-         {
-            unauthenticatedIdentity = createIdentity(name);
-            log.trace("Saw unauthenticatedIdentity="+name);
-         }
-         catch(Exception e)
-         {
-            log.warn("Failed to create custom unauthenticatedIdentity", e);
-         }
-      }
-   }
-
-   /** Looks for javax.security.auth.login.name and javax.security.auth.login.password
-    values in the sharedState map if the useFirstPass option was true and returns
-    true if they exist. If they do not or are null this method returns false.
-
-    Note that subclasses that override the login method must set the loginOk
-    ivar to true if the login succeeds in order for the commit phase to
-    populate the Subject. This implementation sets loginOk to true if the
-    login() method returns true, otherwise, it sets loginOk to false.
-    */
-   public boolean login() throws LoginException
-   {
-      log.trace("login");
-      loginOk = false;
-      // If useFirstPass is true, look for the shared password
-      if( useFirstPass == true )
-      {
-         try
-         {
-            Object identity = sharedState.get("javax.security.auth.login.name");
-            Object credential = sharedState.get("javax.security.auth.login.password");
-            if( identity != null && credential != null )
-            {
-               loginOk = true;
-               return true;
-            }
-            // Else, fall through and perform the login
-         }
-         catch(Exception e)
-         {   // Dump the exception and continue
-            log.error("login failed", e);
-         }
-      }
-      return false;
-   }
-
-   /** Method to commit the authentication process (phase 2). If the login
-    method completed successfully as indicated by loginOk == true, this
-    method adds the getIdentity() value to the subject getPrincipals() Set.
-    It also adds the members of each Group returned by getRoleSets()
-    to the subject getPrincipals() Set.
-    
-    @see javax.security.auth.Subject;
-    @see java.security.acl.Group;
-    @return true always.
-    */
-   public boolean commit() throws LoginException
-   {
-      log.trace("commit, loginOk="+loginOk);
-      if( loginOk == false )
-         return false;
-
-      Set<Principal> principals = subject.getPrincipals();
-      Principal identity = getIdentity();
-      principals.add(identity);
-      Group[] roleSets = getRoleSets();
-      for(int g = 0; g < roleSets.length; g ++)
-      {
-         Group group = roleSets[g];
-         String name = group.getName();
-         Group subjectGroup = createGroup(name, principals);
-         if( subjectGroup instanceof NestableGroup )
-         {
-            /* A NestableGroup only allows Groups to be added to it so we
-            need to add a SimpleGroup to subjectRoles to contain the roles
-            */
-            SimpleGroup tmp = new SimpleGroup("Roles");
-            subjectGroup.addMember(tmp);
-            subjectGroup = tmp;
-         }
-         // Copy the group members to the Subject group
-         Enumeration<? extends Principal> members = group.members();
-         while( members.hasMoreElements() )
-         {
-            Principal role = (Principal) members.nextElement();
-            subjectGroup.addMember(role);
-         }
-      }
-      return true;
-   }
-
-   /** Method to abort the authentication process (phase 2).
-    @return true alaways
-    */
-   public boolean abort() throws LoginException
-   {
-      log.trace("abort");
-      return true;
-   }
-   
-   /** Remove the user identity and roles added to the Subject during commit.
-    @return true always.
-    */
-   public boolean logout() throws LoginException
-   {
-      log.trace("logout");
-      // Remove the user identity
-      Principal identity = getIdentity();
-      Set<Principal> principals = subject.getPrincipals();
-      principals.remove(identity);
-      // Remove any added Groups...
-      return true;
-   }
-   //--- End LoginModule interface methods
-   
-   // --- Protected methods
-   
-   /** Overriden by subclasses to return the Principal that corresponds to
-    the user primary identity.
-    */
-   abstract protected Principal getIdentity();
-   /** Overriden by subclasses to return the Groups that correspond to the
-    to the role sets assigned to the user. Subclasses should create at
-    least a Group named "Roles" that contains the roles assigned to the user.
-    A second common group is "CallerPrincipal" that provides the application
-    identity of the user rather than the security domain identity.
-    @return Group[] containing the sets of roles
-    */
-   abstract protected Group[] getRoleSets() throws LoginException;
-   
-   protected boolean getUseFirstPass()
-   {
-      return useFirstPass;
-   }
-   protected Principal getUnauthenticatedIdentity()
-   {
-      return unauthenticatedIdentity;
-   }
-
-   /** Find or create a Group with the given name. Subclasses should use this
-    method to locate the 'Roles' group or create additional types of groups.
-    @return A named Group from the principals set.
-    */
-   protected Group createGroup(String name, Set<Principal> principals)
-   {
-      Group roles = null;
-      Iterator<Principal> iter = principals.iterator();
-      while( iter.hasNext() )
-      {
-         Object next = iter.next();
-         if( (next instanceof Group) == false )
-            continue;
-         Group grp = (Group) next;
-         if( grp.getName().equals(name) )
-         {
-            roles = grp;
-            break;
-         }
-      }
-      // If we did not find a group create one
-      if( roles == null )
-      {
-         roles = new SimpleGroup(name);
-         principals.add(roles);
-      }
-      return roles;
-   }
-
-   /** Utility method to create a Principal for the given username. This
-    * creates an instance of the principalClassName type if this option was
-    * specified using the class constructor matching: ctor(String). If
-    * principalClassName was not specified, a SimplePrincipal is created.
-    *
-    * @param username the name of the principal
-    * @return the principal instance
-    * @throws java.lang.Exception thrown if the custom principal type cannot be created.
-    */ 
-   @SuppressWarnings("unchecked")
-   protected Principal createIdentity(String username)
-      throws Exception
-   {
-      Principal p = null;
-      if( principalClassName == null )
-      {
-         p = new SimplePrincipal(username);
-      }
-      else
-      {
-            ClassLoader loader = SecurityActions.getContextClassLoader();
-            Class clazz = loader.loadClass(principalClassName);
-            Class[] ctorSig = {String.class};
-            Constructor ctor = clazz.getConstructor(ctorSig);
-            Object[] ctorArgs = {username};
-            p = (Principal) ctor.newInstance(ctorArgs);
-      }
-      return p;
-   }
-}

Copied: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/AbstractServerLoginModule.java (from rev 93325, projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/security/auth/spi/AbstractServerLoginModule.java)
===================================================================
--- projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/AbstractServerLoginModule.java	                        (rev 0)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/AbstractServerLoginModule.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -0,0 +1,354 @@
+/*
+* JBoss, Home of Professional Open Source
+* Copyright 2005, JBoss Inc., and individual contributors as indicated
+* by the @authors tag. See the copyright.txt in the distribution for a
+* full listing of individual contributors.
+*
+* This is free software; you can redistribute it and/or modify it
+* under the terms of the GNU Lesser General Public License as
+* published by the Free Software Foundation; either version 2.1 of
+* the License, or (at your option) any later version.
+*
+* This software is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+* Lesser General Public License for more details.
+*
+* You should have received a copy of the GNU Lesser General Public
+* License along with this software; if not, write to the Free
+* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+*/
+package org.jboss.security.auth.spi;
+
+
+import java.lang.reflect.Constructor;
+import java.security.Principal;
+import java.security.acl.Group;
+import java.util.Enumeration;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Set;
+
+import javax.security.auth.Subject;
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.login.LoginException;
+import javax.security.auth.spi.LoginModule;
+
+import org.jboss.logging.Logger;
+import org.jboss.security.NestableGroup;
+import org.jboss.security.SecurityConstants;
+import org.jboss.security.SimpleGroup;
+import org.jboss.security.SimplePrincipal;
+
+/**
+ * This class implements the common functionality required for a JAAS
+ * server side LoginModule and implements the JBossSX standard Subject usage
+ * pattern of storing identities and roles. Subclass this module to create your
+ * own custom LoginModule and override the login(), getRoleSets() and getIdentity()
+ * methods.
+ * <p>
+ * You may also wish to override
+ * <pre>
+ *    public void initialize(Subject subject, CallbackHandler callbackHandler, Map sharedState, Map options)
+ * </pre>
+ * In which case the first line of your initialize() method should be:
+ * <pre>
+ *    super.initialize(subject, callbackHandler, sharedState, options);
+ * </pre>
+ * <p>
+ * You may also wish to override
+ * <pre>
+ *    public boolean login() throws LoginException
+ * </pre>
+ * In which case the last line of your login() method should be
+ * <pre>
+ *    return super.login();
+ * </pre>
+ *
+ *@author <a href="edward.kenworthy at crispgroup.co.uk">Edward Kenworthy</a>, 12th Dec 2000
+ *@author Scott.Stark at jboss.org
+ *@version $Revision$
+ */
+public abstract class AbstractServerLoginModule implements LoginModule
+{
+   protected Subject subject;
+   protected CallbackHandler callbackHandler;
+   @SuppressWarnings("unchecked")
+   protected Map sharedState;
+   @SuppressWarnings("unchecked")
+   protected Map options;
+   protected Logger log;
+   protected boolean trace = false;
+   
+   /** Flag indicating if the shared credential should be used */
+   protected boolean useFirstPass;
+   /** Flag indicating if the login phase succeeded. Subclasses that override
+    the login method must set this to true on successful completion of login
+    */
+   protected boolean loginOk;
+   /** An optional custom Principal class implementation */
+   protected String principalClassName;
+   /** the principal to use when a null username and password are seen */
+   protected Principal unauthenticatedIdentity;
+
+//--- Begin LoginModule interface methods
+   /** Initialize the login module. This stores the subject, callbackHandler
+    * and sharedState and options for the login session. Subclasses should override
+    * if they need to process their own options. A call to super.initialize(...)
+    * must be made in the case of an override.
+    * <p>
+    * @option password-stacking: If this is set to "useFirstPass", the login
+    * identity will be taken from the <code>javax.security.auth.login.name</code>
+    * value of the sharedState map, and the proof of identity from the
+    * <code>javax.security.auth.login.password</code> value of the sharedState
+    * map.
+    * @option principalClass: A Principal implementation that support a ctor
+    *   taking a String argument for the princpal name.
+    * @option unauthenticatedIdentity: the name of the principal to asssign
+    * and authenticate when a null username and password are seen.
+    * 
+    * @param subject the Subject to update after a successful login.
+    * @param callbackHandler the CallbackHandler that will be used to obtain the
+    *    the user identity and credentials.
+    * @param sharedState a Map shared between all configured login module instances
+    * @param options the parameters passed to the login module.
+    */
+   public void initialize(Subject subject, CallbackHandler callbackHandler,
+      Map<String,?> sharedState, Map<String,?> options)
+   {
+      this.subject = subject;
+      this.callbackHandler = callbackHandler;
+      this.sharedState = sharedState;
+      this.options = options;
+      log = Logger.getLogger(getClass());
+      trace = log.isTraceEnabled();
+      
+      if(trace)
+      {
+         log.trace("initialize");
+
+         //log securityDomain, if set.
+         log.trace("Security domain: " + 
+           (String)options.get(SecurityConstants.SECURITY_DOMAIN_OPTION));         
+      }
+      
+      /* Check for password sharing options. Any non-null value for
+         password_stacking sets useFirstPass as this module has no way to
+         validate any shared password.
+      */
+      String passwordStacking = (String) options.get("password-stacking");
+      if( passwordStacking != null && passwordStacking.equalsIgnoreCase("useFirstPass") )
+         useFirstPass = true;
+
+      // Check for a custom Principal implementation
+      principalClassName = (String) options.get("principalClass");
+
+      // Check for unauthenticatedIdentity option.
+      String name = (String) options.get("unauthenticatedIdentity");
+      if( name != null )
+      {
+         try
+         {
+            unauthenticatedIdentity = createIdentity(name);
+            if(trace)
+               log.trace("Saw unauthenticatedIdentity="+name);
+         }
+         catch(Exception e)
+         {
+            log.warn("Failed to create custom unauthenticatedIdentity", e);
+         }
+      }
+   }
+
+   /** Looks for javax.security.auth.login.name and javax.security.auth.login.password
+    values in the sharedState map if the useFirstPass option was true and returns
+    true if they exist. If they do not or are null this method returns false.
+
+    Note that subclasses that override the login method must set the loginOk
+    ivar to true if the login succeeds in order for the commit phase to
+    populate the Subject. This implementation sets loginOk to true if the
+    login() method returns true, otherwise, it sets loginOk to false.
+    */
+   public boolean login() throws LoginException
+   {
+      if(trace)
+         log.trace("login");
+      loginOk = false;
+      // If useFirstPass is true, look for the shared password
+      if( useFirstPass == true )
+      {
+         try
+         {
+            Object identity = sharedState.get("javax.security.auth.login.name");
+            Object credential = sharedState.get("javax.security.auth.login.password");
+            if( identity != null && credential != null )
+            {
+               loginOk = true;
+               return true;
+            }
+            // Else, fall through and perform the login
+         }
+         catch(Exception e)
+         {   // Dump the exception and continue
+            log.error("login failed", e);
+         }
+      }
+      return false;
+   }
+
+   /** Method to commit the authentication process (phase 2). If the login
+    method completed successfully as indicated by loginOk == true, this
+    method adds the getIdentity() value to the subject getPrincipals() Set.
+    It also adds the members of each Group returned by getRoleSets()
+    to the subject getPrincipals() Set.
+    
+    @see javax.security.auth.Subject;
+    @see java.security.acl.Group;
+    @return true always.
+    */
+   public boolean commit() throws LoginException
+   {
+      if(trace)
+         log.trace("commit, loginOk="+loginOk);
+      if( loginOk == false )
+         return false;
+
+      Set<Principal> principals = subject.getPrincipals();
+      Principal identity = getIdentity();
+      principals.add(identity);
+      Group[] roleSets = getRoleSets();
+      for(int g = 0; g < roleSets.length; g ++)
+      {
+         Group group = roleSets[g];
+         String name = group.getName();
+         Group subjectGroup = createGroup(name, principals);
+         if( subjectGroup instanceof NestableGroup )
+         {
+            /* A NestableGroup only allows Groups to be added to it so we
+            need to add a SimpleGroup to subjectRoles to contain the roles
+            */
+            SimpleGroup tmp = new SimpleGroup("Roles");
+            subjectGroup.addMember(tmp);
+            subjectGroup = tmp;
+         }
+         // Copy the group members to the Subject group
+         Enumeration<? extends Principal> members = group.members();
+         while( members.hasMoreElements() )
+         {
+            Principal role = (Principal) members.nextElement();
+            subjectGroup.addMember(role);
+         }
+      }
+      return true;
+   }
+
+   /** Method to abort the authentication process (phase 2).
+    @return true alaways
+    */
+   public boolean abort() throws LoginException
+   {
+      if(trace)
+         log.trace("abort");
+      return true;
+   }
+   
+   /** Remove the user identity and roles added to the Subject during commit.
+    @return true always.
+    */
+   public boolean logout() throws LoginException
+   {
+      if(trace)
+         log.trace("logout");
+      // Remove the user identity
+      Principal identity = getIdentity();
+      Set<Principal> principals = subject.getPrincipals();
+      principals.remove(identity);
+      // Remove any added Groups...
+      return true;
+   }
+   //--- End LoginModule interface methods
+   
+   // --- Protected methods
+   
+   /** Overriden by subclasses to return the Principal that corresponds to
+    the user primary identity.
+    */
+   abstract protected Principal getIdentity();
+   /** Overriden by subclasses to return the Groups that correspond to the
+    to the role sets assigned to the user. Subclasses should create at
+    least a Group named "Roles" that contains the roles assigned to the user.
+    A second common group is "CallerPrincipal" that provides the application
+    identity of the user rather than the security domain identity.
+    @return Group[] containing the sets of roles
+    */
+   abstract protected Group[] getRoleSets() throws LoginException;
+   
+   protected boolean getUseFirstPass()
+   {
+      return useFirstPass;
+   }
+   protected Principal getUnauthenticatedIdentity()
+   {
+      return unauthenticatedIdentity;
+   }
+
+   /** Find or create a Group with the given name. Subclasses should use this
+    method to locate the 'Roles' group or create additional types of groups.
+    @return A named Group from the principals set.
+    */
+   protected Group createGroup(String name, Set<Principal> principals)
+   {
+      Group roles = null;
+      Iterator<Principal> iter = principals.iterator();
+      while( iter.hasNext() )
+      {
+         Object next = iter.next();
+         if( (next instanceof Group) == false )
+            continue;
+         Group grp = (Group) next;
+         if( grp.getName().equals(name) )
+         {
+            roles = grp;
+            break;
+         }
+      }
+      // If we did not find a group create one
+      if( roles == null )
+      {
+         roles = new SimpleGroup(name);
+         principals.add(roles);
+      }
+      return roles;
+   }
+
+   /** Utility method to create a Principal for the given username. This
+    * creates an instance of the principalClassName type if this option was
+    * specified using the class constructor matching: ctor(String). If
+    * principalClassName was not specified, a SimplePrincipal is created.
+    *
+    * @param username the name of the principal
+    * @return the principal instance
+    * @throws java.lang.Exception thrown if the custom principal type cannot be created.
+    */ 
+   @SuppressWarnings("unchecked")
+   protected Principal createIdentity(String username)
+      throws Exception
+   {
+      Principal p = null;
+      if( principalClassName == null )
+      {
+         p = new SimplePrincipal(username);
+      }
+      else
+      {
+            ClassLoader loader = SecurityActions.getContextClassLoader();
+            Class clazz = loader.loadClass(principalClassName);
+            Class[] ctorSig = {String.class};
+            Constructor ctor = clazz.getConstructor(ctorSig);
+            Object[] ctorArgs = {username};
+            p = (Principal) ctor.newInstance(ctorArgs);
+      }
+      return p;
+   }
+}
\ No newline at end of file

Deleted: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/BaseCertLoginModule.java
===================================================================
--- projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/security/auth/spi/BaseCertLoginModule.java	2009-07-21 21:59:08 UTC (rev 91524)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/BaseCertLoginModule.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -1,429 +0,0 @@
-/*
-* JBoss, Home of Professional Open Source
-* Copyright 2005, JBoss Inc., and individual contributors as indicated
-* by the @authors tag. See the copyright.txt in the distribution for a
-* full listing of individual contributors.
-*
-* This is free software; you can redistribute it and/or modify it
-* under the terms of the GNU Lesser General Public License as
-* published by the Free Software Foundation; either version 2.1 of
-* the License, or (at your option) any later version.
-*
-* This software is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-* Lesser General Public License for more details.
-*
-* You should have received a copy of the GNU Lesser General Public
-* License along with this software; if not, write to the Free
-* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
-*/
-package org.jboss.security.auth.spi;
-
-import java.io.IOException;
-import java.security.KeyStore;
-import java.security.KeyStoreException;
-import java.security.Principal;
-import java.security.acl.Group;
-import java.security.cert.X509Certificate;
-import java.util.ArrayList;
-import java.util.Enumeration;
-import java.util.Map;
-
-import javax.naming.InitialContext;
-import javax.naming.NamingException;
-import javax.security.auth.Subject;
-import javax.security.auth.callback.Callback;
-import javax.security.auth.callback.CallbackHandler;
-import javax.security.auth.callback.NameCallback;
-import javax.security.auth.callback.UnsupportedCallbackException;
-import javax.security.auth.login.FailedLoginException;
-import javax.security.auth.login.LoginException;
-
-import org.jboss.security.SecurityDomain;
-import org.jboss.security.auth.callback.ObjectCallback;
-import org.jboss.security.auth.certs.X509CertificateVerifier;
-
-/**
- * Base Login Module that uses X509Certificates as credentials for
- * authentication.
- *
- * This login module uses X509Certificates as a
- * credential. It takes the cert as an object and checks to see if the alias in
- * the truststore/keystore contains the same certificate. Subclasses of this
- * module should implement the getRoleSets() method defined by
- * AbstractServerLoginModule. Much of this module was patterned after the
- * UserNamePasswordLoginModule.
- *
- * @author <a href="mailto:jasone at greenrivercomputing.com">Jason Essington</a>
- * @author Scott.Stark at jboss.org
- * @version $Revision$
- */
-public class BaseCertLoginModule extends AbstractServerLoginModule
-{
-   /** A principal derived from the certificate alias */
-   private Principal identity;
-   /** The client certificate */
-   private X509Certificate credential;
-   /** The SecurityDomain to obtain the KeyStore/TrustStore from */
-   private SecurityDomain domain = null;
-   /** An option certificate verifier */
-   private X509CertificateVerifier verifier;
-   /** The trace level log flag */
-   private boolean trace;
-
-   /** Override the super version to pickup the following options after first
-    * calling the super method.
-    *
-    * option: securityDomain - the name of the SecurityDomain to obtain the
-    *    trust and keystore from.
-    * option: verifier - the class name of the X509CertificateVerifier to use
-    *    for verification of the login certificate
-    *
-    * @see SecurityDomain
-    * @see X509CertificateVerifier
-    *
-    * @param subject the Subject to update after a successful login.
-    * @param callbackHandler the CallbackHandler that will be used to obtain the
-    *    the user identity and credentials.
-    * @param sharedState a Map shared between all configured login module instances
-    * @param options the parameters passed to the login module.
-    */
-   public void initialize(Subject subject, CallbackHandler callbackHandler,
-      Map<String,?> sharedState, Map<String,?> options)
-   {
-      super.initialize(subject, callbackHandler, sharedState, options);
-      trace = log.isTraceEnabled();
-
-      // Get the security domain and default to "other"
-      String sd = (String) options.get("securityDomain");
-      if (sd == null)
-         sd = "java:/jaas/other";
-
-      if( trace )
-         log.trace("securityDomain=" + sd);
-
-      try
-      {
-         Object tempDomain = new InitialContext().lookup(sd);
-         if (tempDomain instanceof SecurityDomain)
-         {
-            domain = (SecurityDomain) tempDomain;
-            if( trace )
-            {
-               if (domain != null)
-                  log.trace("found domain: " + domain.getClass().getName());
-               else
-                  log.trace("the domain " + sd + " is null!");
-            }
-         }
-         else
-         {
-            log.error("The domain " + sd + " is not a SecurityDomain. All authentication using this module will fail!");
-         }
-      }
-      catch (NamingException e)
-      {
-         log.error("Unable to find the securityDomain named: " + sd, e);
-      }
-
-      String option = (String) options.get("verifier");
-      if( option != null )
-      {
-         try
-         {
-            ClassLoader loader = SecurityActions.getContextClassLoader();
-            Class<?> verifierClass = loader.loadClass(option);
-            verifier = (X509CertificateVerifier) verifierClass.newInstance();
-         }
-         catch(Throwable e)
-         {
-            if( trace )
-               log.trace("Failed to create X509CertificateVerifier", e);
-            IllegalArgumentException ex = new IllegalArgumentException("Invalid verifier: "+option);
-            ex.initCause(e);
-         }
-      }
-
-      if( trace )
-         log.trace("exit: initialize(Subject, CallbackHandler, Map, Map)");
-   }
-
-   /**
-    * Perform the authentication of the username and password.
-    */
-   @SuppressWarnings("unchecked")
-   public boolean login() throws LoginException
-   {
-      if( trace )
-         log.trace("enter: login()");
-      // See if shared credentials exist
-      if (super.login() == true)
-      {
-         // Setup our view of the user
-         Object username = sharedState.get("javax.security.auth.login.name");
-         if( username instanceof Principal )
-            identity = (Principal) username;
-         else
-         {
-            String name = username.toString();
-            try
-            {
-               identity = createIdentity(name);
-            }
-            catch(Exception e)
-            {
-               log.debug("Failed to create principal", e);
-               throw new LoginException("Failed to create principal: "+ e.getMessage());
-            }
-         }
-
-         Object password = sharedState.get("javax.security.auth.login.password");
-         if (password instanceof X509Certificate)
-            credential = (X509Certificate) password;
-         else if (password != null)
-         {
-            log.debug("javax.security.auth.login.password is not X509Certificate");
-            super.loginOk = false;
-            return false;
-         }
-         return true;
-      }
-
-      super.loginOk = false;
-      Object[] info = getAliasAndCert();
-      String alias = (String) info[0];
-      credential = (X509Certificate) info[1];
-
-      if (alias == null && credential == null)
-      {
-         identity = unauthenticatedIdentity;
-         super.log.trace("Authenticating as unauthenticatedIdentity=" + identity);
-      }
-
-      if (identity == null)
-      {
-         try
-         {
-            identity = createIdentity(alias);
-         }
-         catch(Exception e)
-         {
-            log.debug("Failed to create identity for alias:"+alias, e);
-         }
-
-         if (!validateCredential(alias, credential))
-         {
-            log.debug("Bad credential for alias=" + alias);
-            throw new FailedLoginException("Supplied Credential did not match existing credential for " + alias);
-         }
-      }
-
-      if (getUseFirstPass() == true)
-      {
-         // Add authentication info to shared state map
-         sharedState.put("javax.security.auth.login.name", alias);
-         sharedState.put("javax.security.auth.login.password", credential);
-      }
-      super.loginOk = true;
-      if( trace )
-      {
-         log.trace("User '" + identity + "' authenticated, loginOk=" + loginOk);
-         log.debug("exit: login()");
-      }
-      return true;
-   }
-
-   /** Override to add the X509Certificate to the public credentials
-    * @return
-    * @throws LoginException
-    */
-   public boolean commit() throws LoginException
-   {
-      boolean ok = super.commit();
-      if( ok == true )
-      {
-         // Add the cert to the public credentials
-         if (credential != null)
-         {
-            subject.getPublicCredentials().add(credential);
-         }
-      }
-      return ok;
-   }
-
-   /** Subclasses need to override this to provide the roles for authorization
-    * @return
-    * @throws LoginException
-    */
-   protected Group[] getRoleSets() throws LoginException
-   {
-      return new Group[0];
-   }
-
-   protected Principal getIdentity()
-   {
-      return identity;
-   }
-   protected Object getCredentials()
-   {
-      return credential;
-   }
-   protected String getUsername()
-   {
-      String username = null;
-      if (getIdentity() != null)
-         username = getIdentity().getName();
-      return username;
-   }
-
-   protected Object[] getAliasAndCert() throws LoginException
-   {
-      if( trace )
-         log.trace("enter: getAliasAndCert()");
-      Object[] info = { null, null };
-      // prompt for a username and password
-      if (callbackHandler == null)
-      {
-         throw new LoginException("Error: no CallbackHandler available to collect authentication information");
-      }
-      NameCallback nc = new NameCallback("Alias: ");
-      ObjectCallback oc = new ObjectCallback("Certificate: ");
-      Callback[] callbacks = { nc, oc };
-      String alias = null;
-      X509Certificate cert = null;
-      X509Certificate[] certChain;
-      try
-      {
-         callbackHandler.handle(callbacks);
-         alias = nc.getName();
-         Object tmpCert = oc.getCredential();
-         if (tmpCert != null)
-         {
-            if (tmpCert instanceof X509Certificate)
-            {
-               cert = (X509Certificate) tmpCert;
-               if( trace )
-                  log.trace("found cert " + cert.getSerialNumber().toString(16) + ":" + cert.getSubjectDN().getName());
-            }
-            else if( tmpCert instanceof X509Certificate[] )
-            {
-               certChain = (X509Certificate[]) tmpCert;
-               if( certChain.length > 0 )
-                  cert = certChain[0];
-            }
-            else
-            {
-               String msg = "Don't know how to obtain X509Certificate from: "
-                  +tmpCert.getClass();
-               log.warn(msg);
-               throw new LoginException(msg);
-            }
-         }
-         else
-         {
-            log.warn("CallbackHandler did not provide a certificate");
-         }
-      }
-      catch (IOException e)
-      {
-         log.debug("Failed to invoke callback", e);
-         throw new LoginException("Failed to invoke callback: "+e.toString());
-      }
-      catch (UnsupportedCallbackException uce)
-      {
-         throw new LoginException("CallbackHandler does not support: "
-            + uce.getCallback());
-      }
-
-      info[0] = alias;
-      info[1] = cert;
-      if( trace )
-         log.trace("exit: getAliasAndCert()");
-      return info;
-   }
-
-   protected boolean validateCredential(String alias, X509Certificate cert)
-   {
-      if( trace )
-         log.trace("enter: validateCredentail(String, X509Certificate)");
-      boolean isValid = false;
-
-      // if we don't have a trust store, we'll just use the key store.
-      KeyStore keyStore = null;
-      KeyStore trustStore = null;
-      if( domain != null )
-      {
-         keyStore = domain.getKeyStore();
-         trustStore = domain.getTrustStore();
-      }
-      if( trustStore == null )
-         trustStore = keyStore;
-
-      if( verifier != null )
-      {
-         // Have the verifier validate the cert
-         if( trace )
-            log.trace("Validating cert using: "+verifier);
-         isValid = verifier.verify(cert, alias, keyStore, trustStore);
-      }
-      else if (keyStore != null && cert != null)
-      {
-         // Look for the cert in the keystore using the alias
-         X509Certificate storeCert = null;
-         try
-         {
-            storeCert = (X509Certificate) keyStore.getCertificate(alias);
-            if( trace )
-            {
-               StringBuffer buf = new StringBuffer("\n\tSupplied Credential: ");
-               buf.append(cert.getSerialNumber().toString(16));
-               buf.append("\n\t\t");
-               buf.append(cert.getSubjectDN().getName());
-               buf.append("\n\n\tExisting Credential: ");
-               if( storeCert != null )
-               {
-                  buf.append(storeCert.getSerialNumber().toString(16));
-                  buf.append("\n\t\t");
-                  buf.append(storeCert.getSubjectDN().getName());
-                  buf.append("\n");
-               }
-               else
-               {
-                  ArrayList<String> aliases = new ArrayList<String>();
-                  Enumeration<String> en = keyStore.aliases();
-                  while (en.hasMoreElements())
-                  {
-                     aliases.add(en.nextElement());
-                  }
-                  buf.append("No match for alias: "+alias+", we have aliases " + aliases);
-               }
-               log.trace(buf.toString());
-            }
-         }
-         catch (KeyStoreException e)
-         {
-            log.warn("failed to find the certificate for " + alias, e);
-         }
-         // Ensure that the two certs are equal
-         if (cert.equals(storeCert))
-            isValid = true;
-      }
-      else
-      {
-         log.warn("Domain, KeyStore, or cert is null. Unable to validate the certificate.");
-      }
-
-      if( trace )
-      {
-         log.trace("The supplied certificate "
-               + (isValid ? "matched" : "DID NOT match")
-               + " the certificate in the keystore.");
-
-         log.trace("exit: validateCredentail(String, X509Certificate)");
-      }
-      return isValid;
-   }
-
-}

Copied: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/BaseCertLoginModule.java (from rev 93325, projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/security/auth/spi/BaseCertLoginModule.java)
===================================================================
--- projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/BaseCertLoginModule.java	                        (rev 0)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/BaseCertLoginModule.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -0,0 +1,427 @@
+/*
+* JBoss, Home of Professional Open Source
+* Copyright 2005, JBoss Inc., and individual contributors as indicated
+* by the @authors tag. See the copyright.txt in the distribution for a
+* full listing of individual contributors.
+*
+* This is free software; you can redistribute it and/or modify it
+* under the terms of the GNU Lesser General Public License as
+* published by the Free Software Foundation; either version 2.1 of
+* the License, or (at your option) any later version.
+*
+* This software is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+* Lesser General Public License for more details.
+*
+* You should have received a copy of the GNU Lesser General Public
+* License along with this software; if not, write to the Free
+* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+*/
+package org.jboss.security.auth.spi;
+
+import java.io.IOException;
+import java.security.KeyStore;
+import java.security.KeyStoreException;
+import java.security.Principal;
+import java.security.acl.Group;
+import java.security.cert.X509Certificate;
+import java.util.ArrayList;
+import java.util.Enumeration;
+import java.util.Map;
+
+import javax.naming.InitialContext;
+import javax.naming.NamingException;
+import javax.security.auth.Subject;
+import javax.security.auth.callback.Callback;
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.callback.NameCallback;
+import javax.security.auth.callback.UnsupportedCallbackException;
+import javax.security.auth.login.FailedLoginException;
+import javax.security.auth.login.LoginException;
+
+import org.jboss.security.SecurityDomain;
+import org.jboss.security.auth.callback.ObjectCallback;
+import org.jboss.security.auth.certs.X509CertificateVerifier;
+
+/**
+ * Base Login Module that uses X509Certificates as credentials for
+ * authentication.
+ *
+ * This login module uses X509Certificates as a
+ * credential. It takes the cert as an object and checks to see if the alias in
+ * the truststore/keystore contains the same certificate. Subclasses of this
+ * module should implement the getRoleSets() method defined by
+ * AbstractServerLoginModule. Much of this module was patterned after the
+ * UserNamePasswordLoginModule.
+ *
+ * @author <a href="mailto:jasone at greenrivercomputing.com">Jason Essington</a>
+ * @author Scott.Stark at jboss.org
+ * @version $Revision$
+ */
+public class BaseCertLoginModule extends AbstractServerLoginModule
+{
+   /** A principal derived from the certificate alias */
+   private Principal identity;
+   /** The client certificate */
+   private X509Certificate credential;
+   /** The SecurityDomain to obtain the KeyStore/TrustStore from */
+   private SecurityDomain domain = null;
+   /** An option certificate verifier */
+   private X509CertificateVerifier verifier; 
+
+   /** Override the super version to pickup the following options after first
+    * calling the super method.
+    *
+    * option: securityDomain - the name of the SecurityDomain to obtain the
+    *    trust and keystore from.
+    * option: verifier - the class name of the X509CertificateVerifier to use
+    *    for verification of the login certificate
+    *
+    * @see SecurityDomain
+    * @see X509CertificateVerifier
+    *
+    * @param subject the Subject to update after a successful login.
+    * @param callbackHandler the CallbackHandler that will be used to obtain the
+    *    the user identity and credentials.
+    * @param sharedState a Map shared between all configured login module instances
+    * @param options the parameters passed to the login module.
+    */
+   public void initialize(Subject subject, CallbackHandler callbackHandler,
+      Map<String,?> sharedState, Map<String,?> options)
+   {
+      super.initialize(subject, callbackHandler, sharedState, options);
+      trace = log.isTraceEnabled();
+
+      // Get the security domain and default to "other"
+      String sd = (String) options.get("securityDomain");
+      if (sd == null)
+         sd = "java:/jaas/other";
+
+      if( trace )
+         log.trace("securityDomain=" + sd);
+
+      try
+      {
+         Object tempDomain = new InitialContext().lookup(sd);
+         if (tempDomain instanceof SecurityDomain)
+         {
+            domain = (SecurityDomain) tempDomain;
+            if( trace )
+            {
+               if (domain != null)
+                  log.trace("found domain: " + domain.getClass().getName());
+               else
+                  log.trace("the domain " + sd + " is null!");
+            }
+         }
+         else
+         {
+            log.error("The domain " + sd + " is not a SecurityDomain. All authentication using this module will fail!");
+         }
+      }
+      catch (NamingException e)
+      {
+         log.error("Unable to find the securityDomain named: " + sd, e);
+      }
+
+      String option = (String) options.get("verifier");
+      if( option != null )
+      {
+         try
+         {
+            ClassLoader loader = SecurityActions.getContextClassLoader();
+            Class<?> verifierClass = loader.loadClass(option);
+            verifier = (X509CertificateVerifier) verifierClass.newInstance();
+         }
+         catch(Throwable e)
+         {
+            if( trace )
+               log.trace("Failed to create X509CertificateVerifier", e);
+            IllegalArgumentException ex = new IllegalArgumentException("Invalid verifier: "+option);
+            ex.initCause(e);
+         }
+      }
+
+      if( trace )
+         log.trace("exit: initialize(Subject, CallbackHandler, Map, Map)");
+   }
+
+   /**
+    * Perform the authentication of the username and password.
+    */
+   @SuppressWarnings("unchecked")
+   public boolean login() throws LoginException
+   {
+      if( trace )
+         log.trace("enter: login()");
+      // See if shared credentials exist
+      if (super.login() == true)
+      {
+         // Setup our view of the user
+         Object username = sharedState.get("javax.security.auth.login.name");
+         if( username instanceof Principal )
+            identity = (Principal) username;
+         else
+         {
+            String name = username.toString();
+            try
+            {
+               identity = createIdentity(name);
+            }
+            catch(Exception e)
+            {
+               log.debug("Failed to create principal", e);
+               throw new LoginException("Failed to create principal: "+ e.getMessage());
+            }
+         }
+
+         Object password = sharedState.get("javax.security.auth.login.password");
+         if (password instanceof X509Certificate)
+            credential = (X509Certificate) password;
+         else if (password != null)
+         {
+            log.debug("javax.security.auth.login.password is not X509Certificate");
+            super.loginOk = false;
+            return false;
+         }
+         return true;
+      }
+
+      super.loginOk = false;
+      Object[] info = getAliasAndCert();
+      String alias = (String) info[0];
+      credential = (X509Certificate) info[1];
+
+      if (alias == null && credential == null)
+      {
+         identity = unauthenticatedIdentity;
+         super.log.trace("Authenticating as unauthenticatedIdentity=" + identity);
+      }
+
+      if (identity == null)
+      {
+         try
+         {
+            identity = createIdentity(alias);
+         }
+         catch(Exception e)
+         {
+            log.debug("Failed to create identity for alias:"+alias, e);
+         }
+
+         if (!validateCredential(alias, credential))
+         {
+            log.debug("Bad credential for alias=" + alias);
+            throw new FailedLoginException("Supplied Credential did not match existing credential for " + alias);
+         }
+      }
+
+      if (getUseFirstPass() == true)
+      {
+         // Add authentication info to shared state map
+         sharedState.put("javax.security.auth.login.name", alias);
+         sharedState.put("javax.security.auth.login.password", credential);
+      }
+      super.loginOk = true;
+      if( trace )
+      {
+         log.trace("User '" + identity + "' authenticated, loginOk=" + loginOk);
+         log.debug("exit: login()");
+      }
+      return true;
+   }
+
+   /** Override to add the X509Certificate to the public credentials
+    * @return
+    * @throws LoginException
+    */
+   public boolean commit() throws LoginException
+   {
+      boolean ok = super.commit();
+      if( ok == true )
+      {
+         // Add the cert to the public credentials
+         if (credential != null)
+         {
+            subject.getPublicCredentials().add(credential);
+         }
+      }
+      return ok;
+   }
+
+   /** Subclasses need to override this to provide the roles for authorization
+    * @return
+    * @throws LoginException
+    */
+   protected Group[] getRoleSets() throws LoginException
+   {
+      return new Group[0];
+   }
+
+   protected Principal getIdentity()
+   {
+      return identity;
+   }
+   protected Object getCredentials()
+   {
+      return credential;
+   }
+   protected String getUsername()
+   {
+      String username = null;
+      if (getIdentity() != null)
+         username = getIdentity().getName();
+      return username;
+   }
+
+   protected Object[] getAliasAndCert() throws LoginException
+   {
+      if( trace )
+         log.trace("enter: getAliasAndCert()");
+      Object[] info = { null, null };
+      // prompt for a username and password
+      if (callbackHandler == null)
+      {
+         throw new LoginException("Error: no CallbackHandler available to collect authentication information");
+      }
+      NameCallback nc = new NameCallback("Alias: ");
+      ObjectCallback oc = new ObjectCallback("Certificate: ");
+      Callback[] callbacks = { nc, oc };
+      String alias = null;
+      X509Certificate cert = null;
+      X509Certificate[] certChain;
+      try
+      {
+         callbackHandler.handle(callbacks);
+         alias = nc.getName();
+         Object tmpCert = oc.getCredential();
+         if (tmpCert != null)
+         {
+            if (tmpCert instanceof X509Certificate)
+            {
+               cert = (X509Certificate) tmpCert;
+               if( trace )
+                  log.trace("found cert " + cert.getSerialNumber().toString(16) + ":" + cert.getSubjectDN().getName());
+            }
+            else if( tmpCert instanceof X509Certificate[] )
+            {
+               certChain = (X509Certificate[]) tmpCert;
+               if( certChain.length > 0 )
+                  cert = certChain[0];
+            }
+            else
+            {
+               String msg = "Don't know how to obtain X509Certificate from: "
+                  +tmpCert.getClass();
+               log.warn(msg);
+               throw new LoginException(msg);
+            }
+         }
+         else
+         {
+            log.warn("CallbackHandler did not provide a certificate");
+         }
+      }
+      catch (IOException e)
+      {
+         log.debug("Failed to invoke callback", e);
+         throw new LoginException("Failed to invoke callback: "+e.toString());
+      }
+      catch (UnsupportedCallbackException uce)
+      {
+         throw new LoginException("CallbackHandler does not support: "
+            + uce.getCallback());
+      }
+
+      info[0] = alias;
+      info[1] = cert;
+      if( trace )
+         log.trace("exit: getAliasAndCert()");
+      return info;
+   }
+
+   protected boolean validateCredential(String alias, X509Certificate cert)
+   {
+      if( trace )
+         log.trace("enter: validateCredentail(String, X509Certificate)");
+      boolean isValid = false;
+
+      // if we don't have a trust store, we'll just use the key store.
+      KeyStore keyStore = null;
+      KeyStore trustStore = null;
+      if( domain != null )
+      {
+         keyStore = domain.getKeyStore();
+         trustStore = domain.getTrustStore();
+      }
+      if( trustStore == null )
+         trustStore = keyStore;
+
+      if( verifier != null )
+      {
+         // Have the verifier validate the cert
+         if( trace )
+            log.trace("Validating cert using: "+verifier);
+         isValid = verifier.verify(cert, alias, keyStore, trustStore);
+      }
+      else if (keyStore != null && cert != null)
+      {
+         // Look for the cert in the keystore using the alias
+         X509Certificate storeCert = null;
+         try
+         {
+            storeCert = (X509Certificate) keyStore.getCertificate(alias);
+            if( trace )
+            {
+               StringBuffer buf = new StringBuffer("\n\tSupplied Credential: ");
+               buf.append(cert.getSerialNumber().toString(16));
+               buf.append("\n\t\t");
+               buf.append(cert.getSubjectDN().getName());
+               buf.append("\n\n\tExisting Credential: ");
+               if( storeCert != null )
+               {
+                  buf.append(storeCert.getSerialNumber().toString(16));
+                  buf.append("\n\t\t");
+                  buf.append(storeCert.getSubjectDN().getName());
+                  buf.append("\n");
+               }
+               else
+               {
+                  ArrayList<String> aliases = new ArrayList<String>();
+                  Enumeration<String> en = keyStore.aliases();
+                  while (en.hasMoreElements())
+                  {
+                     aliases.add(en.nextElement());
+                  }
+                  buf.append("No match for alias: "+alias+", we have aliases " + aliases);
+               }
+               log.trace(buf.toString());
+            }
+         }
+         catch (KeyStoreException e)
+         {
+            log.warn("failed to find the certificate for " + alias, e);
+         }
+         // Ensure that the two certs are equal
+         if (cert.equals(storeCert))
+            isValid = true;
+      }
+      else
+      {
+         log.warn("Domain, KeyStore, or cert is null. Unable to validate the certificate.");
+      }
+
+      if( trace )
+      {
+         log.trace("The supplied certificate "
+               + (isValid ? "matched" : "DID NOT match")
+               + " the certificate in the keystore.");
+
+         log.trace("exit: validateCredentail(String, X509Certificate)");
+      }
+      return isValid;
+   }
+
+}
\ No newline at end of file

Deleted: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/CertRolesLoginModule.java
===================================================================
--- projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/security/auth/spi/CertRolesLoginModule.java	2009-07-21 21:59:08 UTC (rev 91524)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/CertRolesLoginModule.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -1,145 +0,0 @@
-/*
-* JBoss, Home of Professional Open Source
-* Copyright 2005, JBoss Inc., and individual contributors as indicated
-* by the @authors tag. See the copyright.txt in the distribution for a
-* full listing of individual contributors.
-*
-* This is free software; you can redistribute it and/or modify it
-* under the terms of the GNU Lesser General Public License as
-* published by the Free Software Foundation; either version 2.1 of
-* the License, or (at your option) any later version.
-*
-* This software is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-* Lesser General Public License for more details.
-*
-* You should have received a copy of the GNU Lesser General Public
-* License along with this software; if not, write to the Free
-* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
-*/
-package org.jboss.security.auth.spi;
-
-import java.io.IOException;
-import java.security.acl.Group;
-import java.util.Map;
-import java.util.Properties;
-
-import javax.security.auth.Subject;
-import javax.security.auth.callback.CallbackHandler;
-import javax.security.auth.login.LoginException;
-
-/**
- * Certificate Login Module that uses a properties file to store role information.
- * This works just like the UsersRolesLoginModule, only without the users.properties
- * file. In fact, all the role handling code was borrowed directly from that
- * class.
- * 
- * @author <a href="mailto:jasone at greenrivercomputing.com">Jason Essington</a>
- * @author Scott.Stark at jboss.org
- * @version $Revision$
- * @see org.jboss.security.auth.spi.BaseCertLoginModule
- */
-public class CertRolesLoginModule extends BaseCertLoginModule
-{
-   /** The name of the default properties resource containing user/roles */
-   private String defaultRolesRsrcName = "defaultRoles.properties";
-   /**
-    * The name of the properties resource containing user/roles
-    */
-   private String rolesRsrcName = "roles.properties";
-   /**
-    * The roles.properties mappings
-    */
-   private Properties roles;
-   /** The character used to seperate the role group name from the username
-    * e.g., '.' in jduke.CallerPrincipal=...
-    */
-   private char roleGroupSeperator = '.';
-   /** Logging trace flag */
-   private boolean trace;
-
-   /**
-    * Initialize this LoginModule.
-    * 
-    * @param options - the login module option map. Supported options include:
-    rolesProperties: The name of the properties resource containing user/roles
-      the default is "roles.properties".
-    roleGroupSeperator: The character used to seperate the role group name from
-      the username e.g., '.' in jduke.CallerPrincipal=... . The default = '.'.
-  
-    defaultRolesProperties=string: The name of the properties resource containing
-      the username to roles mappings that will be used as the defaults
-      Properties passed to the usersProperties Properties. This defaults to
-      defaultRoles.properties.
-    */
-   public void initialize(Subject subject, CallbackHandler callbackHandler,
-      Map<String,?> sharedState, Map<String,?> options)
-   {
-      super.initialize(subject, callbackHandler, sharedState, options);
-      trace = log.isTraceEnabled();
-      if( trace )
-         log.trace("enter: initialize(Subject, CallbackHandler, Map, Map)");
-
-      try
-      {
-         String option = (String) options.get("rolesProperties");
-         if (option != null)
-            rolesRsrcName = option;
-         option = (String) options.get("defaultRolesProperties");
-         if (option != null)
-            defaultRolesRsrcName = option;
-         option = (String) options.get("roleGroupSeperator");
-         if( option != null )
-            roleGroupSeperator = option.charAt(0);
-         // Load the properties file that contains the list of users and passwords
-         loadRoles();
-      }
-      catch (Exception e)
-      {
-         // Note that although this exception isn't passed on, users or roles will be null
-         // so that any call to login will throw a LoginException.
-         super.log.error("Failed to load users/passwords/role files", e);
-      }
-
-      if( trace )
-         log.trace("exit: initialize(Subject, CallbackHandler, Map, Map)");
-   }
-
-   public boolean login() throws LoginException
-   {
-      if( trace )
-         log.trace("enter: login()");
-
-      if (roles == null)
-         throw new LoginException("Missing roles.properties file.");
-      boolean wasSuccessful = super.login();
-
-      if( trace )
-         log.trace("exit: login()");
-
-      return wasSuccessful;
-   }
-
-   /**
-    * This method is pretty much straight from the UsersRolesLoginModule.
-    * @see org.jboss.security.auth.spi.UsersRolesLoginModule#getRoleSets
-    */
-   protected Group[] getRoleSets() throws LoginException
-   {
-      if( trace )
-         log.trace("enter: getRoleSets()");
-      String targetUser = getUsername();
-      Group[] roleSets = Util.getRoleSets(targetUser, roles, roleGroupSeperator, this);
-      if( trace )
-         log.trace("exit: getRoleSets()");
-      return roleSets;
-   }
-
-   private void loadRoles() throws IOException
-   {
-      roles = Util.loadProperties(defaultRolesRsrcName, rolesRsrcName, log);
-   }
-
-}

Copied: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/CertRolesLoginModule.java (from rev 93325, projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/security/auth/spi/CertRolesLoginModule.java)
===================================================================
--- projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/CertRolesLoginModule.java	                        (rev 0)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/CertRolesLoginModule.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -0,0 +1,143 @@
+/*
+* JBoss, Home of Professional Open Source
+* Copyright 2005, JBoss Inc., and individual contributors as indicated
+* by the @authors tag. See the copyright.txt in the distribution for a
+* full listing of individual contributors.
+*
+* This is free software; you can redistribute it and/or modify it
+* under the terms of the GNU Lesser General Public License as
+* published by the Free Software Foundation; either version 2.1 of
+* the License, or (at your option) any later version.
+*
+* This software is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+* Lesser General Public License for more details.
+*
+* You should have received a copy of the GNU Lesser General Public
+* License along with this software; if not, write to the Free
+* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+*/
+package org.jboss.security.auth.spi;
+
+import java.io.IOException;
+import java.security.acl.Group;
+import java.util.Map;
+import java.util.Properties;
+
+import javax.security.auth.Subject;
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.login.LoginException;
+
+/**
+ * Certificate Login Module that uses a properties file to store role information.
+ * This works just like the UsersRolesLoginModule, only without the users.properties
+ * file. In fact, all the role handling code was borrowed directly from that
+ * class.
+ * 
+ * @author <a href="mailto:jasone at greenrivercomputing.com">Jason Essington</a>
+ * @author Scott.Stark at jboss.org
+ * @version $Revision$
+ * @see org.jboss.security.auth.spi.BaseCertLoginModule
+ */
+public class CertRolesLoginModule extends BaseCertLoginModule
+{
+   /** The name of the default properties resource containing user/roles */
+   private String defaultRolesRsrcName = "defaultRoles.properties";
+   /**
+    * The name of the properties resource containing user/roles
+    */
+   private String rolesRsrcName = "roles.properties";
+   /**
+    * The roles.properties mappings
+    */
+   private Properties roles;
+   /** The character used to seperate the role group name from the username
+    * e.g., '.' in jduke.CallerPrincipal=...
+    */
+   private char roleGroupSeperator = '.'; 
+
+   /**
+    * Initialize this LoginModule.
+    * 
+    * @param options - the login module option map. Supported options include:
+    rolesProperties: The name of the properties resource containing user/roles
+      the default is "roles.properties".
+    roleGroupSeperator: The character used to seperate the role group name from
+      the username e.g., '.' in jduke.CallerPrincipal=... . The default = '.'.
+  
+    defaultRolesProperties=string: The name of the properties resource containing
+      the username to roles mappings that will be used as the defaults
+      Properties passed to the usersProperties Properties. This defaults to
+      defaultRoles.properties.
+    */
+   public void initialize(Subject subject, CallbackHandler callbackHandler,
+      Map<String,?> sharedState, Map<String,?> options)
+   {
+      super.initialize(subject, callbackHandler, sharedState, options);
+      trace = log.isTraceEnabled();
+      if( trace )
+         log.trace("enter: initialize(Subject, CallbackHandler, Map, Map)");
+
+      try
+      {
+         String option = (String) options.get("rolesProperties");
+         if (option != null)
+            rolesRsrcName = option;
+         option = (String) options.get("defaultRolesProperties");
+         if (option != null)
+            defaultRolesRsrcName = option;
+         option = (String) options.get("roleGroupSeperator");
+         if( option != null )
+            roleGroupSeperator = option.charAt(0);
+         // Load the properties file that contains the list of users and passwords
+         loadRoles();
+      }
+      catch (Exception e)
+      {
+         // Note that although this exception isn't passed on, users or roles will be null
+         // so that any call to login will throw a LoginException.
+         super.log.error("Failed to load users/passwords/role files", e);
+      }
+
+      if( trace )
+         log.trace("exit: initialize(Subject, CallbackHandler, Map, Map)");
+   }
+
+   public boolean login() throws LoginException
+   {
+      if( trace )
+         log.trace("enter: login()");
+
+      if (roles == null)
+         throw new LoginException("Missing roles.properties file.");
+      boolean wasSuccessful = super.login();
+
+      if( trace )
+         log.trace("exit: login()");
+
+      return wasSuccessful;
+   }
+
+   /**
+    * This method is pretty much straight from the UsersRolesLoginModule.
+    * @see org.jboss.security.auth.spi.UsersRolesLoginModule#getRoleSets
+    */
+   protected Group[] getRoleSets() throws LoginException
+   {
+      if( trace )
+         log.trace("enter: getRoleSets()");
+      String targetUser = getUsername();
+      Group[] roleSets = Util.getRoleSets(targetUser, roles, roleGroupSeperator, this);
+      if( trace )
+         log.trace("exit: getRoleSets()");
+      return roleSets;
+   }
+
+   private void loadRoles() throws IOException
+   {
+      roles = Util.loadProperties(defaultRolesRsrcName, rolesRsrcName, log);
+   }
+
+}
\ No newline at end of file

Deleted: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/DatabaseCertLoginModule.java
===================================================================
--- projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/security/auth/spi/DatabaseCertLoginModule.java	2009-07-21 21:59:08 UTC (rev 91524)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/DatabaseCertLoginModule.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -1,93 +0,0 @@
-/*
-* JBoss, Home of Professional Open Source
-* Copyright 2005, JBoss Inc., and individual contributors as indicated
-* by the @authors tag. See the copyright.txt in the distribution for a
-* full listing of individual contributors.
-*
-* This is free software; you can redistribute it and/or modify it
-* under the terms of the GNU Lesser General Public License as
-* published by the Free Software Foundation; either version 2.1 of
-* the License, or (at your option) any later version.
-*
-* This software is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-* Lesser General Public License for more details.
-*
-* You should have received a copy of the GNU Lesser General Public
-* License along with this software; if not, write to the Free
-* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
-*/
-package org.jboss.security.auth.spi;
-
-import java.security.acl.Group;
-import java.util.Map;
-
-import javax.security.auth.Subject;
-import javax.security.auth.callback.CallbackHandler;
-import javax.security.auth.login.LoginException;
-
-/**
- * A Certificate Login Module that gets its role information from a database.
- * 
- * This module is the functional equivelant of the 
- * {@link org.jboss.security.auth.spi.DatabaseServerLoginModule} minus the
- * usersQuery.
- * @see org.jboss.security.auth.spi.DatabaseServerLoginModule
- *
- * @author <a href="mailto:jasone at greenrivercomputing.com">Jason Essington</a>
- * @author Scott.Stark at jboss.org
- * @version $Revision$
- */
-public class DatabaseCertLoginModule extends BaseCertLoginModule
-{
-   /** The JNDI name of the DataSource to use */
-   private String dsJndiName;
-   /** The sql query to obtain the user roles */
-   private String rolesQuery = "select Role, RoleGroup from Roles where PrincipalID=?";
-   /** Whether to suspend resume transactions during database operations */
-   protected boolean suspendResume = true;
-
-   /**
-    * @param options -
-    * dsJndiName: The name of the DataSource of the database containing the
-    *    Principals, Roles tables
-    * rolesQuery: The prepared statement query, equivalent to:
-    *    "select Role, RoleGroup from Roles where PrincipalID=?"
-    */
-   public void initialize(Subject subject, CallbackHandler callbackHandler,
-      Map<String,?> sharedState, Map<String,?> options)
-   {
-      super.initialize(subject, callbackHandler, sharedState, options);
-      dsJndiName = (String) options.get("dsJndiName");
-      if( dsJndiName == null )
-         dsJndiName = "java:/DefaultDS";
-      
-      Object tmp = options.get("rolesQuery");
-      if( tmp != null )
-         rolesQuery = tmp.toString();
-
-      tmp = options.get("suspendResume");
-      if( tmp != null )
-         suspendResume = Boolean.valueOf(tmp.toString()).booleanValue();
-
-      if (log.isTraceEnabled())
-      {
-         log.trace("DatabaseServerLoginModule, dsJndiName="+dsJndiName);
-         log.trace("rolesQuery="+rolesQuery);
-         log.trace("suspendResume="+suspendResume);
-      }
-   }
-
-   /**
-    * @see org.jboss.security.auth.spi.DatabaseServerLoginModule#getRoleSets
-    */
-   protected Group[] getRoleSets() throws LoginException
-   {
-      String username = getUsername();
-      Group[] roleSets = Util.getRoleSets(username, dsJndiName, rolesQuery, this, suspendResume);
-      return roleSets;
-   }
-   
-}

Copied: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/DatabaseCertLoginModule.java (from rev 93325, projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/security/auth/spi/DatabaseCertLoginModule.java)
===================================================================
--- projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/DatabaseCertLoginModule.java	                        (rev 0)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/DatabaseCertLoginModule.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -0,0 +1,93 @@
+/*
+* JBoss, Home of Professional Open Source
+* Copyright 2005, JBoss Inc., and individual contributors as indicated
+* by the @authors tag. See the copyright.txt in the distribution for a
+* full listing of individual contributors.
+*
+* This is free software; you can redistribute it and/or modify it
+* under the terms of the GNU Lesser General Public License as
+* published by the Free Software Foundation; either version 2.1 of
+* the License, or (at your option) any later version.
+*
+* This software is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+* Lesser General Public License for more details.
+*
+* You should have received a copy of the GNU Lesser General Public
+* License along with this software; if not, write to the Free
+* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+*/
+package org.jboss.security.auth.spi;
+
+import java.security.acl.Group;
+import java.util.Map;
+
+import javax.security.auth.Subject;
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.login.LoginException;
+
+/**
+ * A Certificate Login Module that gets its role information from a database.
+ * 
+ * This module is the functional equivelant of the 
+ * {@link org.jboss.security.auth.spi.DatabaseServerLoginModule} minus the
+ * usersQuery.
+ * @see org.jboss.security.auth.spi.DatabaseServerLoginModule
+ *
+ * @author <a href="mailto:jasone at greenrivercomputing.com">Jason Essington</a>
+ * @author Scott.Stark at jboss.org
+ * @version $Revision$
+ */
+public class DatabaseCertLoginModule extends BaseCertLoginModule
+{
+   /** The JNDI name of the DataSource to use */
+   private String dsJndiName;
+   /** The sql query to obtain the user roles */
+   private String rolesQuery = "select Role, RoleGroup from Roles where PrincipalID=?";
+   /** Whether to suspend resume transactions during database operations */
+   protected boolean suspendResume = true;
+
+   /**
+    * @param options -
+    * dsJndiName: The name of the DataSource of the database containing the
+    *    Principals, Roles tables
+    * rolesQuery: The prepared statement query, equivalent to:
+    *    "select Role, RoleGroup from Roles where PrincipalID=?"
+    */
+   public void initialize(Subject subject, CallbackHandler callbackHandler,
+      Map<String,?> sharedState, Map<String,?> options)
+   {
+      super.initialize(subject, callbackHandler, sharedState, options);
+      dsJndiName = (String) options.get("dsJndiName");
+      if( dsJndiName == null )
+         dsJndiName = "java:/DefaultDS";
+      
+      Object tmp = options.get("rolesQuery");
+      if( tmp != null )
+         rolesQuery = tmp.toString();
+
+      tmp = options.get("suspendResume");
+      if( tmp != null )
+         suspendResume = Boolean.valueOf(tmp.toString()).booleanValue();
+
+      if (trace)
+      {
+         log.trace("DatabaseServerLoginModule, dsJndiName="+dsJndiName);
+         log.trace("rolesQuery="+rolesQuery);
+         log.trace("suspendResume="+suspendResume);
+      }
+   }
+
+   /**
+    * @see org.jboss.security.auth.spi.DatabaseServerLoginModule#getRoleSets
+    */
+   protected Group[] getRoleSets() throws LoginException
+   {
+      String username = getUsername();
+      Group[] roleSets = Util.getRoleSets(username, dsJndiName, rolesQuery, this, suspendResume);
+      return roleSets;
+   }
+   
+}
\ No newline at end of file

Deleted: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/DatabaseServerLoginModule.java
===================================================================
--- projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/security/auth/spi/DatabaseServerLoginModule.java	2009-07-21 21:59:08 UTC (rev 91524)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/DatabaseServerLoginModule.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -1,282 +0,0 @@
-/*
-* JBoss, Home of Professional Open Source
-* Copyright 2005, JBoss Inc., and individual contributors as indicated
-* by the @authors tag. See the copyright.txt in the distribution for a
-* full listing of individual contributors.
-*
-* This is free software; you can redistribute it and/or modify it
-* under the terms of the GNU Lesser General Public License as
-* published by the Free Software Foundation; either version 2.1 of
-* the License, or (at your option) any later version.
-*
-* This software is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-* Lesser General Public License for more details.
-*
-* You should have received a copy of the GNU Lesser General Public
-* License along with this software; if not, write to the Free
-* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
-*/
-package org.jboss.security.auth.spi;
-
-import java.security.acl.Group;
-import java.sql.Connection;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.util.Map;
-
-import javax.naming.InitialContext;
-import javax.naming.NamingException;
-import javax.security.auth.Subject;
-import javax.security.auth.callback.CallbackHandler;
-import javax.security.auth.login.FailedLoginException;
-import javax.security.auth.login.LoginException;
-import javax.sql.DataSource;
-import javax.transaction.SystemException;
-import javax.transaction.Transaction;
-import javax.transaction.TransactionManager;
-
-import org.jboss.security.plugins.TransactionManagerLocator;
-
-
-/**
- * A JDBC based login module that supports authentication and role mapping.
- * It is based on two logical tables:
- * <ul>
- * <li>Principals(PrincipalID text, Password text)
- * <li>Roles(PrincipalID text, Role text, RoleGroup text)
- * </ul>
- * <p>
- * LoginModule options:
- * <ul>
- * <li><em>dsJndiName</em>: The name of the DataSource of the database
- * containing the Principals, Roles tables
- * <li><em>principalsQuery</em>: The prepared statement query, equivalent to:
- * <pre>
- *    "select Password from Principals where PrincipalID=?"
- * </pre>
- * <li><em>rolesQuery</em>: The prepared statement query, equivalent to:
- * <pre>
- *    "select Role, RoleGroup from Roles where PrincipalID=?"
- * </pre>
- * </ul>
- *
- * @author <a href="mailto:on at ibis.odessa.ua">Oleg Nitz</a>
- * @author Scott.Stark at jboss.org
- * @version $Revision$
- */
-public class DatabaseServerLoginModule extends UsernamePasswordLoginModule
-{
-   /** The JNDI name of the DataSource to use */
-   protected String dsJndiName;
-   /** The sql query to obtain the user password */
-   protected String principalsQuery = "select Password from Principals where PrincipalID=?";
-   /** The sql query to obtain the user roles */
-   protected String rolesQuery = "select Role, RoleGroup from Roles where PrincipalID=?";
-   /** Whether to suspend resume transactions during database operations */
-   protected boolean suspendResume = true;
-   
-   protected String TX_MGR_JNDI_NAME = "java:/TransactionManager";
-   
-   protected TransactionManager tm = null;
-
-   /**
-    * Initialize this LoginModule.
-    * 
-    * @param options -
-    * dsJndiName: The name of the DataSource of the database containing the
-    *    Principals, Roles tables
-    * principalsQuery: The prepared statement query, equivalent to:
-    *    "select Password from Principals where PrincipalID=?"
-    * rolesQuery: The prepared statement query, equivalent to:
-    *    "select Role, RoleGroup from Roles where PrincipalID=?"
-    */
-   public void initialize(Subject subject, CallbackHandler callbackHandler,
-      Map<String,?> sharedState, Map<String,?> options)
-   {
-      super.initialize(subject, callbackHandler, sharedState, options);
-      dsJndiName = (String) options.get("dsJndiName");
-      if( dsJndiName == null )
-         dsJndiName = "java:/DefaultDS";
-      Object tmp = options.get("principalsQuery");
-      if( tmp != null )
-         principalsQuery = tmp.toString();
-      tmp = options.get("rolesQuery");
-      if( tmp != null )
-         rolesQuery = tmp.toString();
-      tmp = options.get("suspendResume");
-      if( tmp != null )
-         suspendResume = Boolean.valueOf(tmp.toString()).booleanValue();
-      if (log.isTraceEnabled())
-      {
-         log.trace("DatabaseServerLoginModule, dsJndiName="+dsJndiName);
-         log.trace("principalsQuery="+principalsQuery);
-         log.trace("rolesQuery="+rolesQuery);
-         log.trace("suspendResume="+suspendResume);
-      }
-      //Get the Transaction Manager JNDI Name
-      String jname = (String) options.get("transactionManagerJndiName");
-      if(jname != null)
-         this.TX_MGR_JNDI_NAME = jname;
-      
-      try
-      {
-         if(this.suspendResume)
-            tm = this.getTransactionManager();
-      }
-      catch (NamingException e)
-      {
-         throw new RuntimeException("Unable to get Transaction Manager", e);
-      }
-   }
-
-   /** Get the expected password for the current username available via
-    * the getUsername() method. This is called from within the login()
-    * method after the CallbackHandler has returned the username and
-    * candidate password.
-    * @return the valid password String
-    */
-   protected String getUsersPassword() throws LoginException
-   {
-      boolean trace = log.isTraceEnabled();
-      String username = getUsername();
-      String password = null;
-      Connection conn = null;
-      PreparedStatement ps = null;
-      ResultSet rs = null;
-      
-      Transaction tx = null;
-      if (suspendResume)
-      {
-         //tx = TransactionDemarcationSupport.suspendAnyTransaction();
-         try
-         {
-            if(tm == null)
-               throw new IllegalStateException("Transaction Manager is null");
-            tx = tm.suspend();
-         }
-         catch (SystemException e)
-         {
-            throw new RuntimeException(e);
-         }
-         if (trace)
-            log.trace("suspendAnyTransaction");
-      }
-
-      try
-      {
-         InitialContext ctx = new InitialContext();
-         DataSource ds = (DataSource) ctx.lookup(dsJndiName);
-         conn = ds.getConnection();
-         // Get the password
-         if (trace)
-            log.trace("Excuting query: "+principalsQuery+", with username: "+username);
-         ps = conn.prepareStatement(principalsQuery);
-         ps.setString(1, username);
-         rs = ps.executeQuery();
-         if( rs.next() == false )
-         {
-            if(trace)
-               log.trace("Query returned no matches from db");
-            throw new FailedLoginException("No matching username found in Principals");
-         }
-         
-         password = rs.getString(1);
-         password = convertRawPassword(password);
-         if(trace)
-            log.trace("Obtained user password");
-      }
-      catch(NamingException ex)
-      {
-         LoginException le = new LoginException("Error looking up DataSource from: "+dsJndiName);
-         le.initCause(ex);
-         throw le;
-      }
-      catch(SQLException ex)
-      {
-         LoginException le = new LoginException("Query failed");
-         le.initCause(ex);
-         throw le;
-      }
-      finally
-      {
-         if (rs != null)
-         {
-            try
-            {
-               rs.close();
-            }
-            catch(SQLException e)
-            {}
-         }
-         if( ps != null )
-         {
-            try
-            {
-               ps.close();
-            }
-            catch(SQLException e)
-            {}
-         }
-         if( conn != null )
-         {
-            try
-            {
-               conn.close();
-            }
-            catch (SQLException ex)
-            {}
-         }
-         if (suspendResume)
-         {
-            //TransactionDemarcationSupport.resumeAnyTransaction(tx);
-            try
-            {
-               tm.resume(tx);
-            }
-            catch (Exception e)
-            {
-               throw new RuntimeException(e);
-            } 
-            if (log.isTraceEnabled())
-               log.trace("resumeAnyTransaction");
-         }
-      }
-      return password;
-   }
-
-   /** Execute the rolesQuery against the dsJndiName to obtain the roles for
-    the authenticated user.
-     
-    @return Group[] containing the sets of roles
-    */
-   protected Group[] getRoleSets() throws LoginException
-   {
-      String username = getUsername();
-      if (log.isTraceEnabled())
-         log.trace("getRoleSets using rolesQuery: "+rolesQuery+", username: "+username);
-      Group[] roleSets = Util.getRoleSets(username, dsJndiName, rolesQuery, this,
-         suspendResume);
-      return roleSets;
-   }
-   
-   /** A hook to allow subclasses to convert a password from the database
-    into a plain text string or whatever form is used for matching against
-    the user input. It is called from within the getUsersPassword() method.
-    @param rawPassword - the password as obtained from the database
-    @return the argument rawPassword
-    */
-   protected String convertRawPassword(String rawPassword)
-   {
-      return rawPassword;
-   }
-   
-   protected TransactionManager getTransactionManager() throws NamingException
-   {
-      TransactionManagerLocator tml = new TransactionManagerLocator();
-      return tml.getTM(this.TX_MGR_JNDI_NAME);
-   } 
-}

Copied: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/DatabaseServerLoginModule.java (from rev 93325, projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/security/auth/spi/DatabaseServerLoginModule.java)
===================================================================
--- projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/DatabaseServerLoginModule.java	                        (rev 0)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/DatabaseServerLoginModule.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -0,0 +1,282 @@
+/*
+* JBoss, Home of Professional Open Source
+* Copyright 2005, JBoss Inc., and individual contributors as indicated
+* by the @authors tag. See the copyright.txt in the distribution for a
+* full listing of individual contributors.
+*
+* This is free software; you can redistribute it and/or modify it
+* under the terms of the GNU Lesser General Public License as
+* published by the Free Software Foundation; either version 2.1 of
+* the License, or (at your option) any later version.
+*
+* This software is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+* Lesser General Public License for more details.
+*
+* You should have received a copy of the GNU Lesser General Public
+* License along with this software; if not, write to the Free
+* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+*/
+package org.jboss.security.auth.spi;
+
+import java.security.acl.Group;
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.Map;
+
+import javax.naming.InitialContext;
+import javax.naming.NamingException;
+import javax.security.auth.Subject;
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.login.FailedLoginException;
+import javax.security.auth.login.LoginException;
+import javax.sql.DataSource;
+import javax.transaction.SystemException;
+import javax.transaction.Transaction;
+import javax.transaction.TransactionManager;
+
+import org.jboss.security.plugins.TransactionManagerLocator;
+
+
+/**
+ * A JDBC based login module that supports authentication and role mapping.
+ * It is based on two logical tables:
+ * <ul>
+ * <li>Principals(PrincipalID text, Password text)
+ * <li>Roles(PrincipalID text, Role text, RoleGroup text)
+ * </ul>
+ * <p>
+ * LoginModule options:
+ * <ul>
+ * <li><em>dsJndiName</em>: The name of the DataSource of the database
+ * containing the Principals, Roles tables
+ * <li><em>principalsQuery</em>: The prepared statement query, equivalent to:
+ * <pre>
+ *    "select Password from Principals where PrincipalID=?"
+ * </pre>
+ * <li><em>rolesQuery</em>: The prepared statement query, equivalent to:
+ * <pre>
+ *    "select Role, RoleGroup from Roles where PrincipalID=?"
+ * </pre>
+ * </ul>
+ *
+ * @author <a href="mailto:on at ibis.odessa.ua">Oleg Nitz</a>
+ * @author Scott.Stark at jboss.org
+ * @version $Revision$
+ */
+public class DatabaseServerLoginModule extends UsernamePasswordLoginModule
+{
+   /** The JNDI name of the DataSource to use */
+   protected String dsJndiName;
+   /** The sql query to obtain the user password */
+   protected String principalsQuery = "select Password from Principals where PrincipalID=?";
+   /** The sql query to obtain the user roles */
+   protected String rolesQuery = "select Role, RoleGroup from Roles where PrincipalID=?";
+   /** Whether to suspend resume transactions during database operations */
+   protected boolean suspendResume = true;
+   
+   protected String TX_MGR_JNDI_NAME = "java:/TransactionManager";
+   
+   protected TransactionManager tm = null;
+
+   /**
+    * Initialize this LoginModule.
+    * 
+    * @param options -
+    * dsJndiName: The name of the DataSource of the database containing the
+    *    Principals, Roles tables
+    * principalsQuery: The prepared statement query, equivalent to:
+    *    "select Password from Principals where PrincipalID=?"
+    * rolesQuery: The prepared statement query, equivalent to:
+    *    "select Role, RoleGroup from Roles where PrincipalID=?"
+    */
+   public void initialize(Subject subject, CallbackHandler callbackHandler,
+      Map<String,?> sharedState, Map<String,?> options)
+   {
+      super.initialize(subject, callbackHandler, sharedState, options);
+      dsJndiName = (String) options.get("dsJndiName");
+      if( dsJndiName == null )
+         dsJndiName = "java:/DefaultDS";
+      Object tmp = options.get("principalsQuery");
+      if( tmp != null )
+         principalsQuery = tmp.toString();
+      tmp = options.get("rolesQuery");
+      if( tmp != null )
+         rolesQuery = tmp.toString();
+      tmp = options.get("suspendResume");
+      if( tmp != null )
+         suspendResume = Boolean.valueOf(tmp.toString()).booleanValue();
+      if (trace)
+      {
+         log.trace("DatabaseServerLoginModule, dsJndiName="+dsJndiName);
+         log.trace("principalsQuery="+principalsQuery);
+         log.trace("rolesQuery="+rolesQuery);
+         log.trace("suspendResume="+suspendResume);
+      }
+      //Get the Transaction Manager JNDI Name
+      String jname = (String) options.get("transactionManagerJndiName");
+      if(jname != null)
+         this.TX_MGR_JNDI_NAME = jname;
+      
+      try
+      {
+         if(this.suspendResume)
+            tm = this.getTransactionManager();
+      }
+      catch (NamingException e)
+      {
+         throw new RuntimeException("Unable to get Transaction Manager", e);
+      }
+   }
+
+   /** Get the expected password for the current username available via
+    * the getUsername() method. This is called from within the login()
+    * method after the CallbackHandler has returned the username and
+    * candidate password.
+    * @return the valid password String
+    */
+   protected String getUsersPassword() throws LoginException
+   {
+      boolean trace = log.isTraceEnabled();
+      String username = getUsername();
+      String password = null;
+      Connection conn = null;
+      PreparedStatement ps = null;
+      ResultSet rs = null;
+      
+      Transaction tx = null;
+      if (suspendResume)
+      {
+         //tx = TransactionDemarcationSupport.suspendAnyTransaction();
+         try
+         {
+            if(tm == null)
+               throw new IllegalStateException("Transaction Manager is null");
+            tx = tm.suspend();
+         }
+         catch (SystemException e)
+         {
+            throw new RuntimeException(e);
+         }
+         if (trace)
+            log.trace("suspendAnyTransaction");
+      }
+
+      try
+      {
+         InitialContext ctx = new InitialContext();
+         DataSource ds = (DataSource) ctx.lookup(dsJndiName);
+         conn = ds.getConnection();
+         // Get the password
+         if (trace)
+            log.trace("Excuting query: "+principalsQuery+", with username: "+username);
+         ps = conn.prepareStatement(principalsQuery);
+         ps.setString(1, username);
+         rs = ps.executeQuery();
+         if( rs.next() == false )
+         {
+            if(trace)
+               log.trace("Query returned no matches from db");
+            throw new FailedLoginException("No matching username found in Principals");
+         }
+         
+         password = rs.getString(1);
+         password = convertRawPassword(password);
+         if(trace)
+            log.trace("Obtained user password");
+      }
+      catch(NamingException ex)
+      {
+         LoginException le = new LoginException("Error looking up DataSource from: "+dsJndiName);
+         le.initCause(ex);
+         throw le;
+      }
+      catch(SQLException ex)
+      {
+         LoginException le = new LoginException("Query failed");
+         le.initCause(ex);
+         throw le;
+      }
+      finally
+      {
+         if (rs != null)
+         {
+            try
+            {
+               rs.close();
+            }
+            catch(SQLException e)
+            {}
+         }
+         if( ps != null )
+         {
+            try
+            {
+               ps.close();
+            }
+            catch(SQLException e)
+            {}
+         }
+         if( conn != null )
+         {
+            try
+            {
+               conn.close();
+            }
+            catch (SQLException ex)
+            {}
+         }
+         if (suspendResume)
+         {
+            //TransactionDemarcationSupport.resumeAnyTransaction(tx);
+            try
+            {
+               tm.resume(tx);
+            }
+            catch (Exception e)
+            {
+               throw new RuntimeException(e);
+            } 
+            if (log.isTraceEnabled())
+               log.trace("resumeAnyTransaction");
+         }
+      }
+      return password;
+   }
+
+   /** Execute the rolesQuery against the dsJndiName to obtain the roles for
+    the authenticated user.
+     
+    @return Group[] containing the sets of roles
+    */
+   protected Group[] getRoleSets() throws LoginException
+   {
+      String username = getUsername();
+      if (log.isTraceEnabled())
+         log.trace("getRoleSets using rolesQuery: "+rolesQuery+", username: "+username);
+      Group[] roleSets = Util.getRoleSets(username, dsJndiName, rolesQuery, this,
+         suspendResume);
+      return roleSets;
+   }
+   
+   /** A hook to allow subclasses to convert a password from the database
+    into a plain text string or whatever form is used for matching against
+    the user input. It is called from within the getUsersPassword() method.
+    @param rawPassword - the password as obtained from the database
+    @return the argument rawPassword
+    */
+   protected String convertRawPassword(String rawPassword)
+   {
+      return rawPassword;
+   }
+   
+   protected TransactionManager getTransactionManager() throws NamingException
+   {
+      TransactionManagerLocator tml = new TransactionManagerLocator();
+      return tml.getTM(this.TX_MGR_JNDI_NAME);
+   } 
+}

Deleted: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/DecodeAction.java
===================================================================
--- projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/security/auth/spi/DecodeAction.java	2009-07-21 21:59:08 UTC (rev 91524)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/DecodeAction.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -1,110 +0,0 @@
-/*
-* JBoss, Home of Professional Open Source
-* Copyright 2005, JBoss Inc., and individual contributors as indicated
-* by the @authors tag. See the copyright.txt in the distribution for a
-* full listing of individual contributors.
-*
-* This is free software; you can redistribute it and/or modify it
-* under the terms of the GNU Lesser General Public License as
-* published by the Free Software Foundation; either version 2.1 of
-* the License, or (at your option) any later version.
-*
-* This software is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-* Lesser General Public License for more details.
-*
-* You should have received a copy of the GNU Lesser General Public
-* License along with this software; if not, write to the Free
-* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
-*/
-package org.jboss.security.auth.spi;
-
-import java.security.AccessController;
-import java.security.PrivilegedActionException;
-import java.security.PrivilegedExceptionAction;
-
-import javax.crypto.Cipher;
-import javax.management.ObjectName;
-
-import org.jboss.security.config.SecurityConfiguration;
-
-/**
- * PriviledgedActions used by login modules for decoding passwords
- * 
- * @author Scott.Stark at jboss.org
- * @version $Revision$
- */
-class DecodeAction implements PrivilegedExceptionAction<Object>
-{
-   /** The permission required to access decode, decode64 */
-   private static final RuntimePermission decodePermission =
-      new RuntimePermission("org.jboss.security.auth.spi.DecodeAction.decode"); 
-   
-   String password;
-   ObjectName serviceName;
-
-   DecodeAction(String password, ObjectName serviceName)
-   {
-      this.password = password;
-      this.serviceName = serviceName;
-   }
-
-   /**
-    * 
-    * @return
-    * @throws Exception
-    */
-   public Object run() throws Exception
-   {  
-      // Invoke the decodeb64 op
-      byte[] secret = decode64(password);
-      // Convert to UTF-8 base char array
-      String secretPassword = new String(secret, "UTF-8");
-      return secretPassword.toCharArray();
-   }
-   
-   private byte[] decode64(String secret)
-   throws Exception
-   {
-     byte[] encoding = Util.fromb64(secret);
-     byte[] decode = decode(encoding);
-     return decode;
-   }
-   
-   /** Decrypt the secret using the cipherKey.
-   *
-   * @param secret - the encrypted secret to decrypt.
-   * @return the decrypted secret
-   * @throws Exception
-   */
-  private byte[] decode(byte[] secret)
-     throws Exception
-  {
-     SecurityManager sm = System.getSecurityManager();
-     if( sm != null )
-        sm.checkPermission(decodePermission);
-
-     Cipher cipher = Cipher.getInstance(SecurityConfiguration.getCipherAlgorithm());
-     cipher.init(Cipher.DECRYPT_MODE, SecurityConfiguration.getCipherKey(), 
-           SecurityConfiguration.getCipherSpec());
-     byte[] decode = cipher.doFinal(secret);
-     return decode;
-  }
-  
-   static char[] decode(String password, ObjectName serviceName)
-      throws Exception
-   {
-      DecodeAction action = new DecodeAction(password, serviceName);
-      try
-      {
-         char[] decode = (char[]) AccessController.doPrivileged(action);
-         return decode;
-      }
-      catch(PrivilegedActionException e)
-      {
-         throw e.getException();
-      }
-   }
-}

Copied: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/DecodeAction.java (from rev 91979, projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/security/auth/spi/DecodeAction.java)
===================================================================
--- projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/DecodeAction.java	                        (rev 0)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/DecodeAction.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -0,0 +1,109 @@
+/*
+* JBoss, Home of Professional Open Source
+* Copyright 2005, JBoss Inc., and individual contributors as indicated
+* by the @authors tag. See the copyright.txt in the distribution for a
+* full listing of individual contributors.
+*
+* This is free software; you can redistribute it and/or modify it
+* under the terms of the GNU Lesser General Public License as
+* published by the Free Software Foundation; either version 2.1 of
+* the License, or (at your option) any later version.
+*
+* This software is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+* Lesser General Public License for more details.
+*
+* You should have received a copy of the GNU Lesser General Public
+* License along with this software; if not, write to the Free
+* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+*/
+package org.jboss.security.auth.spi;
+
+import java.security.AccessController;
+import java.security.PrivilegedActionException;
+import java.security.PrivilegedExceptionAction;
+
+import javax.management.MBeanServer;
+import javax.management.ObjectName;
+
+import org.jboss.crypto.CryptoUtil;
+import org.jboss.mx.util.MBeanServerLocator;
+
+/**
+ * PriviledgedActions used by login modules for decoding passwords
+ * 
+ * @author Scott.Stark at jboss.org
+ * @version $Revision$
+ */
+class DecodeAction implements PrivilegedExceptionAction<Object>
+{
+   /** The permission required to access decode, decode64 */
+   private static final RuntimePermission decodePermission =
+      new RuntimePermission("org.jboss.security.auth.spi.DecodeAction.decode"); 
+   
+   String password;
+   ObjectName serviceName;
+
+   DecodeAction(String password, ObjectName serviceName)
+   {
+      this.password = password;
+      this.serviceName = serviceName;
+   }
+
+   /**
+    * 
+    * @return
+    * @throws Exception
+    */
+   public Object run() throws Exception
+   {  
+      // Invoke the decodeb64 op
+      byte[] secret = decode64(password);
+      // Convert to UTF-8 base char array
+      String secretPassword = new String(secret, "UTF-8");
+      return secretPassword.toCharArray();
+   }
+   
+   private byte[] decode64(String secret)
+   throws Exception
+   {
+     byte[] encoding = CryptoUtil.fromb64(secret);
+     byte[] decode = decode(encoding);
+     return decode;
+   }
+   
+   /** Decrypt the secret using the cipherKey.
+   *
+   * @param secret - the encrypted secret to decrypt.
+   * @return the decrypted secret
+   * @throws Exception
+   */
+  private byte[] decode(byte[] passw)
+     throws Exception
+  {
+     SecurityManager sm = System.getSecurityManager();
+     if( sm != null )
+        sm.checkPermission(decodePermission);
+
+     MBeanServer server = MBeanServerLocator.locateJBoss();
+     return (byte[]) server.invoke(serviceName, "decode64", new Object[] {passw}, 
+           new String[] {byte[].class.getName()});  
+  }
+  
+   static char[] decode(String password, ObjectName serviceName)
+      throws Exception
+   {
+      DecodeAction action = new DecodeAction(password, serviceName);
+      try
+      {
+         char[] decode = (char[]) AccessController.doPrivileged(action);
+         return decode;
+      }
+      catch(PrivilegedActionException e)
+      {
+         throw e.getException();
+      }
+   }
+}

Deleted: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/LdapExtLoginModule.java
===================================================================
--- projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/security/auth/spi/LdapExtLoginModule.java	2009-07-21 21:59:08 UTC (rev 91524)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/LdapExtLoginModule.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -1,632 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * Copyright 2006, Red Hat Middleware LLC, and individual contributors
- * as indicated by the @author tags. See the copyright.txt file in the
- * distribution for a full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jboss.security.auth.spi;
-
-import java.security.Principal;
-import java.security.acl.Group;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Properties;
-import java.util.Map.Entry;
-
-import javax.management.ObjectName;
-import javax.naming.Context;
-import javax.naming.NamingEnumeration;
-import javax.naming.NamingException;
-import javax.naming.directory.Attribute;
-import javax.naming.directory.Attributes;
-import javax.naming.directory.SearchControls;
-import javax.naming.directory.SearchResult;
-import javax.naming.ldap.InitialLdapContext;
-import javax.security.auth.Subject;
-import javax.security.auth.callback.CallbackHandler;
-import javax.security.auth.login.LoginException;
-
-import org.jboss.security.SimpleGroup;
-import org.jboss.security.Util;
-
-/**
- The org.jboss.security.auth.spi.LdapExtLoginModule, added in jboss-4.0.3, is an
- alternate ldap login module implementation that uses searches for locating both
- the user to bind as for authentication as well as the associated roles. The
- roles query will recursively follow distinguished names (DNs) to navigate a
- hierarchical role structure.
-
- The LoginModule options include whatever options your LDAP JNDI provider
- supports. Examples of standard property names are:
-
- * Context.INITIAL_CONTEXT_FACTORY = "java.naming.factory.initial"
- * Context.SECURITY_PROTOCOL = "java.naming.security.protocol"
- * Context.PROVIDER_URL = "java.naming.provider.url"
- * Context.SECURITY_AUTHENTICATION = "java.naming.security.authentication"
-
- The authentication happens in 2 steps:
- # An initial bind to the ldap server is done using the __bindDN__ and
- __bindCredential__ options. The __bindDN__ is some user with the ability to
- search both the __baseDN__ and __rolesCtxDN__ trees for the user and roles. The
- user DN to authenticate against is queried using the filter specified by the
- __baseFilter__ attribute (see the __baseFilter__ option description for its
- syntax). 
- # The resulting user DN is then authenticated by binding to ldap server using
- the user DN as the InitialLdapContext environment Context.SECURITY_PRINCIPAL.
-
- The Context.SECURITY_CREDENTIALS property is either set to the String password
- obtained by the callback handler.
-
- If this is successful, the associated user roles are queried using the
- __rolesCtxDN__, __roleAttributeID__, __roleAttributeIsDN__,
- __roleNameAttributeID__, and __roleFilter__ options.
-
- The full odule properties include:
- * __baseCtxDN__ : The fixed DN of the context to start the user search from.
- * __bindDN__ : The DN used to bind against the ldap server for the user and
- roles queries. This is some DN with read/search permissions on the baseCtxDN and
- rolesCtxDN values.
- * __bindCredential__ : The password for the bindDN. This can be encrypted if the
- jaasSecurityDomain is specified.
- * __jaasSecurityDomain__ : The JMX ObjectName of the JaasSecurityDomain to use
- to decrypt the java.naming.security.principal. The encrypted form of the
- password is that returned by the JaasSecurityDomain#encrypt64(byte[]) method.
- The org.jboss.security.plugins.PBEUtils can also be used to generate the
- encrypted form.
- * __baseFilter__ : A search filter used to locate the context of the user to
- authenticate. The input username/userDN as obtained from the login module
- callback will be substituted into the filter anywhere a "{0}" expression is
- seen. This substituion behavior comes from the standard
- __DirContext.search(Name, String, Object[], SearchControls cons)__ method. An
- common example search filter is "(uid={0})".
- * __rolesCtxDN__ : The fixed DN of the context to search for user roles.
- Consider that this is not the Distinguished Name of where the actual roles are;
- rather, this is the DN of where the objects containing the user roles are (e.g.
- for active directory, this is the DN where the user account is)
- * __roleFilter__ : A search filter used to locate the roles associated with the
- authenticated user. The input username/userDN as obtained from the login module
- callback will be substituted into the filter anywhere a "{0}" expression is
- seen. The authenticated userDN will be substituted into the filter anywhere a
- "{1}" is seen.  An example search filter that matches on the input username is:
- "(member={0})". An alternative that matches on the authenticated userDN is:
- "(member={1})".
- * __roleAttributeIsDN__ : A flag indicating whether the user's role attribute
- contains the fully distinguished name of a role object, or the users's role
- attribute contains the role name. If false, the role name is taken from the
- value of the user's role attribute. If true, the role attribute represents the
- distinguished name of a role object.  The role name is taken from the value of
- the roleNameAttributeId` attribute of the corresponding object.  In certain
- directory schemas (e.g., Microsoft Active Directory), role (group)attributes in
- the user object are stored as DNs to role objects instead of as simple names, in
- which case, this property should be set to true. The default value of this
- property is false.
- * __roleNameAttributeID__ : The name of the attribute of the role object which
- corresponds to the name of the role.  If the __roleAttributeIsDN__ property is
- set to true, this property is used to find the role object's name attribute. If
- the __roleAttributeIsDN__ property is set to false, this property is ignored.
- * __roleRecursion__ : How deep the role search will go below a given matching
- context. Disable with 0, which is the default.
- * __searchTimeLimit__ : The timeout in milliseconds for the user/role searches.
- Defaults to 10000 (10 seconds).
- * __searchScope__ : Sets the search scope to one of the strings. The default is
- SUBTREE_SCOPE.
- ** OBJECT_SCOPE : only search the named roles context.
- ** ONELEVEL_SCOPE : search directly under the named roles context.
- ** SUBTREE_SCOPE :  If the roles context is not a DirContext, search only the
- object. If the roles context is a DirContext, search the subtree rooted at the
- named object, including the named object itself
- * __allowEmptyPasswords__ : A flag indicating if empty(length==0) passwords
- should be passed to the ldap server. An empty password is treated as an
- anonymous login by some ldap servers and this may not be a desirable feature.
- Set this to false to reject empty passwords, true to have the ldap server
- validate the empty password. The default is true.
- 
- @author Andy Oliver
- @author Scott.Stark at jboss.org
- @version $Revision$ */
-public class LdapExtLoginModule extends UsernamePasswordLoginModule
-{
-   private static final String ROLES_CTX_DN_OPT = "rolesCtxDN";
-
-   private static final String ROLE_ATTRIBUTE_ID_OPT = "roleAttributeID";
-
-   private static final String ROLE_ATTRIBUTE_IS_DN_OPT = "roleAttributeIsDN";
-
-   private static final String ROLE_NAME_ATTRIBUTE_ID_OPT = "roleNameAttributeID";
-
-   private static final String BIND_DN = "bindDN";
-
-   private static final String BIND_CREDENTIAL = "bindCredential";
-
-   private static final String BASE_CTX_DN = "baseCtxDN";
-
-   private static final String BASE_FILTER_OPT = "baseFilter";
-
-   private static final String ROLE_FILTER_OPT = "roleFilter";
-
-   private static final String ROLE_RECURSION = "roleRecursion";
-
-   private static final String DEFAULT_ROLE = "defaultRole";
-
-   private static final String SEARCH_TIME_LIMIT_OPT = "searchTimeLimit";
-
-   private static final String SEARCH_SCOPE_OPT = "searchScope";
-
-   private static final String SECURITY_DOMAIN_OPT = "jaasSecurityDomain";
-
-   protected String bindDN;
-
-   protected String bindCredential;
-
-   protected String baseDN;
-
-   protected String baseFilter;
-
-   protected String rolesCtxDN;
-
-   protected String roleFilter;
-
-   protected String roleAttributeID;
-
-   protected String roleNameAttributeID;
-
-   protected boolean roleAttributeIsDN;
-
-   protected int recursion = 0;
-
-   protected int searchTimeLimit = 10000;
-
-   protected int searchScope = SearchControls.SUBTREE_SCOPE;
-
-   protected boolean trace;
-   
-   // simple flag to indicate is the validatePassword method was called
-   protected boolean isPasswordValidated = false;
-
-   public LdapExtLoginModule()
-   {
-   }
-
-   private transient SimpleGroup userRoles = new SimpleGroup("Roles");
-   
-   public void initialize(Subject subject, CallbackHandler callbackHandler, Map sharedState, Map options)
-   {
-      super.initialize(subject, callbackHandler, sharedState, options);
-      trace = log.isTraceEnabled();
-   }
-
-   /**
-    Overridden to return an empty password string as typically one cannot obtain a
-    user's password. We also override the validatePassword so this is ok.
-    @return and empty password String
-    */
-   protected String getUsersPassword() throws LoginException
-   {
-      return "";
-   }
-
-   /**
-    Overridden by subclasses to return the Groups that correspond to the to the
-    role sets assigned to the user. Subclasses should create at least a Group
-    named "Roles" that contains the roles assigned to the user. A second common
-    group is "CallerPrincipal" that provides the application identity of the user
-    rather than the security domain identity.
-    @return Group[] containing the sets of roles
-    */
-   protected Group[] getRoleSets() throws LoginException
-   {
-      // SECURITY-225: check if authentication was already done in a previous login module
-      // and perform role mapping
-      if (!isPasswordValidated)
-      {
-         try
-         {
-            String username = getUsername();
-            createLdapInitContext(username, null);
-            defaultRole();
-         }
-         catch (Exception e)
-         {
-            LoginException le = new LoginException();
-            le.initCause(e);
-            throw le;
-         }
-      }
-
-      Group[] roleSets = {userRoles};
-      return roleSets;
-   }
-
-   /**
-    Validate the inputPassword by creating a LDAP InitialContext with the
-    SECURITY_CREDENTIALS set to the password.
-    @param inputPassword the password to validate.
-    @param expectedPassword ignored
-    */
-   protected boolean validatePassword(String inputPassword, String expectedPassword)
-   {
-      isPasswordValidated = true;
-      boolean isValid = false;
-      if (inputPassword != null)
-      {
-         // See if this is an empty password that should be disallowed
-         if (inputPassword.length() == 0)
-         {
-            // Check for an allowEmptyPasswords option
-            boolean allowEmptyPasswords = true;
-            String flag = (String) options.get("allowEmptyPasswords");
-            if (flag != null)
-               allowEmptyPasswords = Boolean.valueOf(flag).booleanValue();
-            if (allowEmptyPasswords == false)
-            {
-               log.trace("Rejecting empty password due to allowEmptyPasswords");
-               return false;
-            }
-         }
-
-         try
-         {
-            // Validate the password by trying to create an initial context
-            String username = getUsername();
-            isValid = createLdapInitContext(username, inputPassword);
-            defaultRole();
-            isValid = true;
-         }
-         catch (Throwable e)
-         {
-            super.setValidateError(e);
-         }
-      }
-      return isValid;
-   }
-
-   /**
-    @todo move to a generic role mapping function at the base login module
-    */
-   private void defaultRole()
-   {
-      try
-      {
-         String defaultRole = (String) options.get(DEFAULT_ROLE);
-         if (defaultRole == null || defaultRole.equals(""))
-         {
-            return;
-         }
-         Principal p = super.createIdentity(defaultRole);
-         log.trace("Assign user to role " + defaultRole);
-         userRoles.addMember(p);
-      }
-      catch (Exception e)
-      {
-         super.log.debug("could not add default role to user", e);
-      }
-   }
-
-   /**
-    Bind to the LDAP server for authentication. 
-    
-    @param username
-    @param credential
-    @return true if the bind for authentication succeeded
-    @throws NamingException
-    */
-   private boolean createLdapInitContext(String username, Object credential) throws Exception
-   {
-      bindDN = (String) options.get(BIND_DN);
-      bindCredential = (String) options.get(BIND_CREDENTIAL);
-      if (bindCredential.startsWith("{EXT}"))
-         bindCredential = new String(Util.loadPassword(bindCredential));
-      String securityDomain = (String) options.get(SECURITY_DOMAIN_OPT);
-      if (securityDomain != null)
-      {
-         ObjectName serviceName = new ObjectName(securityDomain);
-         char[] tmp = DecodeAction.decode(bindCredential, serviceName);
-         bindCredential = new String(tmp);
-      }
-
-      baseDN = (String) options.get(BASE_CTX_DN);
-      baseFilter = (String) options.get(BASE_FILTER_OPT);
-      roleFilter = (String) options.get(ROLE_FILTER_OPT);
-      roleAttributeID = (String) options.get(ROLE_ATTRIBUTE_ID_OPT);
-      if (roleAttributeID == null)
-         roleAttributeID = "role";
-      // Is user's role attribute a DN or the role name
-      String roleAttributeIsDNOption = (String) options.get(ROLE_ATTRIBUTE_IS_DN_OPT);
-      roleAttributeIsDN = Boolean.valueOf(roleAttributeIsDNOption).booleanValue();
-      roleNameAttributeID = (String) options.get(ROLE_NAME_ATTRIBUTE_ID_OPT);
-      if (roleNameAttributeID == null)
-         roleNameAttributeID = "name";
-      rolesCtxDN = (String) options.get(ROLES_CTX_DN_OPT);
-      String strRecursion = (String) options.get(ROLE_RECURSION);
-      try
-      {
-         recursion = Integer.parseInt(strRecursion);
-      }
-      catch (Exception e)
-      {
-         if (trace)
-            log.trace("Failed to parse: " + strRecursion + ", disabling recursion", e);
-         // its okay for this to be 0 as this just disables recursion
-         recursion = 0;
-      }
-      String timeLimit = (String) options.get(SEARCH_TIME_LIMIT_OPT);
-      if (timeLimit != null)
-      {
-         try
-         {
-            searchTimeLimit = Integer.parseInt(timeLimit);
-         }
-         catch (NumberFormatException e)
-         {
-            if (trace)
-               log.trace("Failed to parse: " + timeLimit + ", using searchTimeLimit=" + searchTimeLimit, e);
-         }
-      }
-      String scope = (String) options.get(SEARCH_SCOPE_OPT);
-      if ("OBJECT_SCOPE".equalsIgnoreCase(scope))
-         searchScope = SearchControls.OBJECT_SCOPE;
-      else if ("ONELEVEL_SCOPE".equalsIgnoreCase(scope))
-         searchScope = SearchControls.ONELEVEL_SCOPE;
-      if ("SUBTREE_SCOPE".equalsIgnoreCase(scope))
-         searchScope = SearchControls.SUBTREE_SCOPE;
-
-      // Get the admin context for searching
-      InitialLdapContext ctx = null;
-      try
-      {
-         ctx = constructInitialLdapContext(bindDN, bindCredential);
-         // Validate the user by binding against the userDN
-         String userDN = bindDNAuthentication(ctx, username, credential, baseDN, baseFilter);
-
-         // Query for roles matching the role filter
-         SearchControls constraints = new SearchControls();
-         constraints.setSearchScope(searchScope);
-         constraints.setReturningAttributes(new String[0]);
-         constraints.setTimeLimit(searchTimeLimit);
-         rolesSearch(ctx, constraints, username, userDN, recursion, 0);
-      }
-      finally
-      {
-         if (ctx != null)
-            ctx.close();
-      }
-      return true;
-   }
-
-   /**
-    @param ctx - the context to search from
-    @param user - the input username
-    @param credential - the bind credential
-    @param baseDN - base DN to search the ctx from
-    @param filter - the search filter string
-    @return the userDN string for the successful authentication 
-    @throws NamingException
-    */
-   @SuppressWarnings("unchecked")
-   protected String bindDNAuthentication(InitialLdapContext ctx, String user, Object credential, String baseDN,
-         String filter) throws NamingException
-   {
-      SearchControls constraints = new SearchControls();
-      constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
-      constraints.setReturningAttributes(new String[0]);
-      constraints.setTimeLimit(searchTimeLimit);
-
-      NamingEnumeration results = null;
-
-      Object[] filterArgs = {user};
-      results = ctx.search(baseDN, filter, filterArgs, constraints);
-      if (results.hasMore() == false)
-      {
-         results.close();
-         throw new NamingException("Search of baseDN(" + baseDN + ") found no matches");
-      }
-
-      SearchResult sr = (SearchResult) results.next();
-      String name = sr.getName();
-      String userDN = null;
-      if (sr.isRelative() == true)
-         userDN = name + "," + baseDN;
-      else
-         throw new NamingException("Can't follow referal for authentication: " + name);
-
-      results.close();
-      results = null;
-      // SECURITY-225: don't need to authenticate again
-      if (isPasswordValidated)
-      {
-         // Bind as the user dn to authenticate the user
-         InitialLdapContext userCtx = constructInitialLdapContext(userDN, credential);
-         userCtx.close();
-      }
-
-      return userDN;
-   }
-
-   /**
-    @param ctx
-    @param constraints
-    @param user
-    @param userDN
-    @param recursionMax
-    @param nesting
-    @throws NamingException
-    */
-   @SuppressWarnings("unchecked")
-   protected void rolesSearch(InitialLdapContext ctx, SearchControls constraints, String user, String userDN,
-         int recursionMax, int nesting) throws NamingException
-   {
-      Object[] filterArgs = {user, userDN};
-      NamingEnumeration results = ctx.search(rolesCtxDN, roleFilter, filterArgs, constraints);
-      try
-      {
-         while (results.hasMore())
-         {
-            SearchResult sr = (SearchResult) results.next();
-            String dn = canonicalize(sr.getName());
-            if (nesting == 0 && roleAttributeIsDN && roleNameAttributeID != null)
-            {
-               // Check the top context for role names
-               String[] attrNames = {roleNameAttributeID};
-               Attributes result2 = ctx.getAttributes(dn, attrNames);
-               Attribute roles2 = result2.get(roleNameAttributeID);
-               if (roles2 != null)
-               {
-                  for (int m = 0; m < roles2.size(); m++)
-                  {
-                     String roleName = (String) roles2.get(m);
-                     addRole(roleName);
-                  }
-               }
-            }
-
-            // Query the context for the roleDN values
-            String[] attrNames = {roleAttributeID};
-            Attributes result = ctx.getAttributes(dn, attrNames);
-            if (result != null && result.size() > 0)
-            {
-               Attribute roles = result.get(roleAttributeID);
-               for (int n = 0; n < roles.size(); n++)
-               {
-                  String roleName = (String) roles.get(n);
-                  if (roleAttributeIsDN)
-                  {
-                     // Query the roleDN location for the value of roleNameAttributeID
-                     String roleDN = roleName;
-                     String[] returnAttribute = {roleNameAttributeID};
-                     log.trace("Using roleDN: " + roleDN);
-                     try
-                     {
-                        Attributes result2 = ctx.getAttributes(roleDN, returnAttribute);
-                        Attribute roles2 = result2.get(roleNameAttributeID);
-                        if (roles2 != null)
-                        {
-                           for (int m = 0; m < roles2.size(); m++)
-                           {
-                              roleName = (String) roles2.get(m);
-                              addRole(roleName);
-                           }
-                        }
-                     }
-                     catch (NamingException e)
-                     {
-                        log.trace("Failed to query roleNameAttrName", e);
-                     }
-                  }
-                  else
-                  {
-                     // The role attribute value is the role name
-                     addRole(roleName);
-                  }
-               }
-            }
-
-            if (nesting < recursionMax)
-            {
-               rolesSearch(ctx, constraints, user, dn, recursionMax, nesting + 1);
-            }
-         }
-      }
-      finally
-      {
-         if (results != null)
-            results.close();
-      }
-
-   }
-
-   @SuppressWarnings("unchecked")
-   private InitialLdapContext constructInitialLdapContext(String dn, Object credential) throws NamingException
-   {
-      Properties env = new Properties();
-      Iterator iter = options.entrySet().iterator();
-      while (iter.hasNext())
-      {
-         Entry entry = (Entry) iter.next();
-         env.put(entry.getKey(), entry.getValue());
-      }
-
-      // Set defaults for key values if they are missing
-      String factoryName = env.getProperty(Context.INITIAL_CONTEXT_FACTORY);
-      if (factoryName == null)
-      {
-         factoryName = "com.sun.jndi.ldap.LdapCtxFactory";
-         env.setProperty(Context.INITIAL_CONTEXT_FACTORY, factoryName);
-      }
-      String authType = env.getProperty(Context.SECURITY_AUTHENTICATION);
-      if (authType == null)
-         env.setProperty(Context.SECURITY_AUTHENTICATION, "simple");
-      String protocol = env.getProperty(Context.SECURITY_PROTOCOL);
-      String providerURL = (String) options.get(Context.PROVIDER_URL);
-      if (providerURL == null)
-         providerURL = "ldap://localhost:" + ((protocol != null && protocol.equals("ssl")) ? "636" : "389");
-
-      env.setProperty(Context.PROVIDER_URL, providerURL);
-      // JBAS-3555, allow anonymous login with no bindDN and bindCredential
-      if (dn != null)
-         env.setProperty(Context.SECURITY_PRINCIPAL, dn);
-      if (credential != null)
-         env.put(Context.SECURITY_CREDENTIALS, credential);
-      traceLdapEnv(env);
-      return new InitialLdapContext(env, null);
-   }
-
-   private void traceLdapEnv(Properties env)
-   {
-      if (trace)
-      {
-         Properties tmp = new Properties();
-         tmp.putAll(env);
-         tmp.setProperty(Context.SECURITY_CREDENTIALS, "***");
-         log.trace("Logging into LDAP server, env=" + tmp.toString());
-      }
-   }
-
-   //JBAS-3438 : Handle "/" correctly
-   private String canonicalize(String searchResult)
-   {
-      String result = searchResult;
-      int len = searchResult.length();
-
-      if (searchResult.endsWith("\""))
-      {
-         result = searchResult.substring(0, len - 1) + "," + rolesCtxDN + "\"";
-      }
-      else
-      {
-         result = searchResult + "," + rolesCtxDN;
-      }
-      return result;
-   }
-
-   private void addRole(String roleName)
-   {
-      if (roleName != null)
-      {
-         try
-         {
-            Principal p = super.createIdentity(roleName);
-            log.trace("Assign user to role " + roleName);
-            userRoles.addMember(p);
-         }
-         catch (Exception e)
-         {
-            log.debug("Failed to create principal: " + roleName, e);
-         }
-      }
-   }
-}

Copied: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/LdapExtLoginModule.java (from rev 93325, projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/security/auth/spi/LdapExtLoginModule.java)
===================================================================
--- projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/LdapExtLoginModule.java	                        (rev 0)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/LdapExtLoginModule.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -0,0 +1,636 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2006, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.security.auth.spi;
+
+import java.security.Principal;
+import java.security.acl.Group;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Map.Entry;
+
+import javax.management.ObjectName;
+import javax.naming.Context;
+import javax.naming.NamingEnumeration;
+import javax.naming.NamingException;
+import javax.naming.directory.Attribute;
+import javax.naming.directory.Attributes;
+import javax.naming.directory.SearchControls;
+import javax.naming.directory.SearchResult;
+import javax.naming.ldap.InitialLdapContext;
+import javax.security.auth.Subject;
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.login.LoginException;
+
+import org.jboss.security.SimpleGroup;
+import org.jboss.security.Util;
+
+/**
+ The org.jboss.security.auth.spi.LdapExtLoginModule, added in jboss-4.0.3, is an
+ alternate ldap login module implementation that uses searches for locating both
+ the user to bind as for authentication as well as the associated roles. The
+ roles query will recursively follow distinguished names (DNs) to navigate a
+ hierarchical role structure.
+
+ The LoginModule options include whatever options your LDAP JNDI provider
+ supports. Examples of standard property names are:
+
+ * Context.INITIAL_CONTEXT_FACTORY = "java.naming.factory.initial"
+ * Context.SECURITY_PROTOCOL = "java.naming.security.protocol"
+ * Context.PROVIDER_URL = "java.naming.provider.url"
+ * Context.SECURITY_AUTHENTICATION = "java.naming.security.authentication"
+
+ The authentication happens in 2 steps:
+ # An initial bind to the ldap server is done using the __bindDN__ and
+ __bindCredential__ options. The __bindDN__ is some user with the ability to
+ search both the __baseDN__ and __rolesCtxDN__ trees for the user and roles. The
+ user DN to authenticate against is queried using the filter specified by the
+ __baseFilter__ attribute (see the __baseFilter__ option description for its
+ syntax). 
+ # The resulting user DN is then authenticated by binding to ldap server using
+ the user DN as the InitialLdapContext environment Context.SECURITY_PRINCIPAL.
+
+ The Context.SECURITY_CREDENTIALS property is either set to the String password
+ obtained by the callback handler.
+
+ If this is successful, the associated user roles are queried using the
+ __rolesCtxDN__, __roleAttributeID__, __roleAttributeIsDN__,
+ __roleNameAttributeID__, and __roleFilter__ options.
+
+ The full odule properties include:
+ * __baseCtxDN__ : The fixed DN of the context to start the user search from.
+ * __bindDN__ : The DN used to bind against the ldap server for the user and
+ roles queries. This is some DN with read/search permissions on the baseCtxDN and
+ rolesCtxDN values.
+ * __bindCredential__ : The password for the bindDN. This can be encrypted if the
+ jaasSecurityDomain is specified.
+ * __jaasSecurityDomain__ : The JMX ObjectName of the JaasSecurityDomain to use
+ to decrypt the java.naming.security.principal. The encrypted form of the
+ password is that returned by the JaasSecurityDomain#encrypt64(byte[]) method.
+ The org.jboss.security.plugins.PBEUtils can also be used to generate the
+ encrypted form.
+ * __baseFilter__ : A search filter used to locate the context of the user to
+ authenticate. The input username/userDN as obtained from the login module
+ callback will be substituted into the filter anywhere a "{0}" expression is
+ seen. This substituion behavior comes from the standard
+ __DirContext.search(Name, String, Object[], SearchControls cons)__ method. An
+ common example search filter is "(uid={0})".
+ * __rolesCtxDN__ : The fixed DN of the context to search for user roles.
+ Consider that this is not the Distinguished Name of where the actual roles are;
+ rather, this is the DN of where the objects containing the user roles are (e.g.
+ for active directory, this is the DN where the user account is)
+ * __roleFilter__ : A search filter used to locate the roles associated with the
+ authenticated user. The input username/userDN as obtained from the login module
+ callback will be substituted into the filter anywhere a "{0}" expression is
+ seen. The authenticated userDN will be substituted into the filter anywhere a
+ "{1}" is seen.  An example search filter that matches on the input username is:
+ "(member={0})". An alternative that matches on the authenticated userDN is:
+ "(member={1})".
+ * __roleAttributeIsDN__ : A flag indicating whether the user's role attribute
+ contains the fully distinguished name of a role object, or the users's role
+ attribute contains the role name. If false, the role name is taken from the
+ value of the user's role attribute. If true, the role attribute represents the
+ distinguished name of a role object.  The role name is taken from the value of
+ the roleNameAttributeId` attribute of the corresponding object.  In certain
+ directory schemas (e.g., Microsoft Active Directory), role (group)attributes in
+ the user object are stored as DNs to role objects instead of as simple names, in
+ which case, this property should be set to true. The default value of this
+ property is false.
+ * __roleNameAttributeID__ : The name of the attribute of the role object which
+ corresponds to the name of the role.  If the __roleAttributeIsDN__ property is
+ set to true, this property is used to find the role object's name attribute. If
+ the __roleAttributeIsDN__ property is set to false, this property is ignored.
+ * __roleRecursion__ : How deep the role search will go below a given matching
+ context. Disable with 0, which is the default.
+ * __searchTimeLimit__ : The timeout in milliseconds for the user/role searches.
+ Defaults to 10000 (10 seconds).
+ * __searchScope__ : Sets the search scope to one of the strings. The default is
+ SUBTREE_SCOPE.
+ ** OBJECT_SCOPE : only search the named roles context.
+ ** ONELEVEL_SCOPE : search directly under the named roles context.
+ ** SUBTREE_SCOPE :  If the roles context is not a DirContext, search only the
+ object. If the roles context is a DirContext, search the subtree rooted at the
+ named object, including the named object itself
+ * __allowEmptyPasswords__ : A flag indicating if empty(length==0) passwords
+ should be passed to the ldap server. An empty password is treated as an
+ anonymous login by some ldap servers and this may not be a desirable feature.
+ Set this to false to reject empty passwords, true to have the ldap server
+ validate the empty password. The default is true.
+ 
+ @author Andy Oliver
+ @author Scott.Stark at jboss.org
+ @version $Revision$ */
+public class LdapExtLoginModule extends UsernamePasswordLoginModule
+{
+   private static final String ROLES_CTX_DN_OPT = "rolesCtxDN";
+
+   private static final String ROLE_ATTRIBUTE_ID_OPT = "roleAttributeID";
+
+   private static final String ROLE_ATTRIBUTE_IS_DN_OPT = "roleAttributeIsDN";
+
+   private static final String ROLE_NAME_ATTRIBUTE_ID_OPT = "roleNameAttributeID";
+
+   private static final String BIND_DN = "bindDN";
+
+   private static final String BIND_CREDENTIAL = "bindCredential";
+
+   private static final String BASE_CTX_DN = "baseCtxDN";
+
+   private static final String BASE_FILTER_OPT = "baseFilter";
+
+   private static final String ROLE_FILTER_OPT = "roleFilter";
+
+   private static final String ROLE_RECURSION = "roleRecursion";
+
+   private static final String DEFAULT_ROLE = "defaultRole";
+
+   private static final String SEARCH_TIME_LIMIT_OPT = "searchTimeLimit";
+
+   private static final String SEARCH_SCOPE_OPT = "searchScope";
+
+   private static final String SECURITY_DOMAIN_OPT = "jaasSecurityDomain";
+
+   protected String bindDN;
+
+   protected String bindCredential;
+
+   protected String baseDN;
+
+   protected String baseFilter;
+
+   protected String rolesCtxDN;
+
+   protected String roleFilter;
+
+   protected String roleAttributeID;
+
+   protected String roleNameAttributeID;
+
+   protected boolean roleAttributeIsDN;
+
+   protected int recursion = 0;
+
+   protected int searchTimeLimit = 10000;
+
+   protected int searchScope = SearchControls.SUBTREE_SCOPE; 
+   
+   // simple flag to indicate is the validatePassword method was called
+   protected boolean isPasswordValidated = false;
+
+   public LdapExtLoginModule()
+   {
+   }
+
+   private transient SimpleGroup userRoles = new SimpleGroup("Roles");
+   
+   public void initialize(Subject subject, CallbackHandler callbackHandler, Map sharedState, Map options)
+   {
+      super.initialize(subject, callbackHandler, sharedState, options);
+      trace = log.isTraceEnabled();
+   }
+
+   /**
+    Overridden to return an empty password string as typically one cannot obtain a
+    user's password. We also override the validatePassword so this is ok.
+    @return and empty password String
+    */
+   protected String getUsersPassword() throws LoginException
+   {
+      return "";
+   }
+
+   /**
+    Overridden by subclasses to return the Groups that correspond to the to the
+    role sets assigned to the user. Subclasses should create at least a Group
+    named "Roles" that contains the roles assigned to the user. A second common
+    group is "CallerPrincipal" that provides the application identity of the user
+    rather than the security domain identity.
+    @return Group[] containing the sets of roles
+    */
+   protected Group[] getRoleSets() throws LoginException
+   {
+      // SECURITY-225: check if authentication was already done in a previous login module
+      // and perform role mapping
+      if (!isPasswordValidated)
+      {
+         try
+         {
+            String username = getUsername();
+            createLdapInitContext(username, null);
+            defaultRole();
+         }
+         catch (Exception e)
+         {
+            LoginException le = new LoginException();
+            le.initCause(e);
+            throw le;
+         }
+      }
+
+      Group[] roleSets = {userRoles};
+      return roleSets;
+   }
+
+   /**
+    Validate the inputPassword by creating a LDAP InitialContext with the
+    SECURITY_CREDENTIALS set to the password.
+    @param inputPassword the password to validate.
+    @param expectedPassword ignored
+    */
+   protected boolean validatePassword(String inputPassword, String expectedPassword)
+   {
+      isPasswordValidated = true;
+      boolean isValid = false;
+      if (inputPassword != null)
+      {
+         // See if this is an empty password that should be disallowed
+         if (inputPassword.length() == 0)
+         {
+            // Check for an allowEmptyPasswords option
+            boolean allowEmptyPasswords = true;
+            String flag = (String) options.get("allowEmptyPasswords");
+            if (flag != null)
+               allowEmptyPasswords = Boolean.valueOf(flag).booleanValue();
+            if (allowEmptyPasswords == false)
+            {
+               if(trace)
+                  log.trace("Rejecting empty password due to allowEmptyPasswords");
+               return false;
+            }
+         }
+
+         try
+         {
+            // Validate the password by trying to create an initial context
+            String username = getUsername();
+            isValid = createLdapInitContext(username, inputPassword);
+            defaultRole();
+            isValid = true;
+         }
+         catch (Throwable e)
+         {
+            super.setValidateError(e);
+         }
+      }
+      return isValid;
+   }
+
+   /**
+    @todo move to a generic role mapping function at the base login module
+    */
+   private void defaultRole()
+   {
+      try
+      {
+         String defaultRole = (String) options.get(DEFAULT_ROLE);
+         if (defaultRole == null || defaultRole.equals(""))
+         {
+            return;
+         }
+         Principal p = super.createIdentity(defaultRole);
+         if(trace)
+            log.trace("Assign user to role " + defaultRole);
+         userRoles.addMember(p);
+      }
+      catch (Exception e)
+      {
+         super.log.debug("could not add default role to user", e);
+      }
+   }
+
+   /**
+    Bind to the LDAP server for authentication. 
+    
+    @param username
+    @param credential
+    @return true if the bind for authentication succeeded
+    @throws NamingException
+    */
+   private boolean createLdapInitContext(String username, Object credential) throws Exception
+   {
+      bindDN = (String) options.get(BIND_DN);
+      bindCredential = (String) options.get(BIND_CREDENTIAL);
+      if (bindCredential.startsWith("{EXT}"))
+         bindCredential = new String(Util.loadPassword(bindCredential));
+      String securityDomain = (String) options.get(SECURITY_DOMAIN_OPT);
+      if (securityDomain != null)
+      {
+         ObjectName serviceName = new ObjectName(securityDomain);
+         char[] tmp = DecodeAction.decode(bindCredential, serviceName);
+         bindCredential = new String(tmp);
+      }
+
+      baseDN = (String) options.get(BASE_CTX_DN);
+      baseFilter = (String) options.get(BASE_FILTER_OPT);
+      roleFilter = (String) options.get(ROLE_FILTER_OPT);
+      roleAttributeID = (String) options.get(ROLE_ATTRIBUTE_ID_OPT);
+      if (roleAttributeID == null)
+         roleAttributeID = "role";
+      // Is user's role attribute a DN or the role name
+      String roleAttributeIsDNOption = (String) options.get(ROLE_ATTRIBUTE_IS_DN_OPT);
+      roleAttributeIsDN = Boolean.valueOf(roleAttributeIsDNOption).booleanValue();
+      roleNameAttributeID = (String) options.get(ROLE_NAME_ATTRIBUTE_ID_OPT);
+      if (roleNameAttributeID == null)
+         roleNameAttributeID = "name";
+      rolesCtxDN = (String) options.get(ROLES_CTX_DN_OPT);
+      String strRecursion = (String) options.get(ROLE_RECURSION);
+      try
+      {
+         recursion = Integer.parseInt(strRecursion);
+      }
+      catch (Exception e)
+      {
+         if (trace)
+            log.trace("Failed to parse: " + strRecursion + ", disabling recursion", e);
+         // its okay for this to be 0 as this just disables recursion
+         recursion = 0;
+      }
+      String timeLimit = (String) options.get(SEARCH_TIME_LIMIT_OPT);
+      if (timeLimit != null)
+      {
+         try
+         {
+            searchTimeLimit = Integer.parseInt(timeLimit);
+         }
+         catch (NumberFormatException e)
+         {
+            if (trace)
+               log.trace("Failed to parse: " + timeLimit + ", using searchTimeLimit=" + searchTimeLimit, e);
+         }
+      }
+      String scope = (String) options.get(SEARCH_SCOPE_OPT);
+      if ("OBJECT_SCOPE".equalsIgnoreCase(scope))
+         searchScope = SearchControls.OBJECT_SCOPE;
+      else if ("ONELEVEL_SCOPE".equalsIgnoreCase(scope))
+         searchScope = SearchControls.ONELEVEL_SCOPE;
+      if ("SUBTREE_SCOPE".equalsIgnoreCase(scope))
+         searchScope = SearchControls.SUBTREE_SCOPE;
+
+      // Get the admin context for searching
+      InitialLdapContext ctx = null;
+      try
+      {
+         ctx = constructInitialLdapContext(bindDN, bindCredential);
+         // Validate the user by binding against the userDN
+         String userDN = bindDNAuthentication(ctx, username, credential, baseDN, baseFilter);
+
+         // Query for roles matching the role filter
+         SearchControls constraints = new SearchControls();
+         constraints.setSearchScope(searchScope);
+         constraints.setReturningAttributes(new String[0]);
+         constraints.setTimeLimit(searchTimeLimit);
+         rolesSearch(ctx, constraints, username, userDN, recursion, 0);
+      }
+      finally
+      {
+         if (ctx != null)
+            ctx.close();
+      }
+      return true;
+   }
+
+   /**
+    @param ctx - the context to search from
+    @param user - the input username
+    @param credential - the bind credential
+    @param baseDN - base DN to search the ctx from
+    @param filter - the search filter string
+    @return the userDN string for the successful authentication 
+    @throws NamingException
+    */
+   @SuppressWarnings("unchecked")
+   protected String bindDNAuthentication(InitialLdapContext ctx, String user, Object credential, String baseDN,
+         String filter) throws NamingException
+   {
+      SearchControls constraints = new SearchControls();
+      constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
+      constraints.setReturningAttributes(new String[0]);
+      constraints.setTimeLimit(searchTimeLimit);
+
+      NamingEnumeration results = null;
+
+      Object[] filterArgs = {user};
+      results = ctx.search(baseDN, filter, filterArgs, constraints);
+      if (results.hasMore() == false)
+      {
+         results.close();
+         throw new NamingException("Search of baseDN(" + baseDN + ") found no matches");
+      }
+
+      SearchResult sr = (SearchResult) results.next();
+      String name = sr.getName();
+      String userDN = null;
+      if (sr.isRelative() == true)
+         userDN = name + "," + baseDN;
+      else
+         throw new NamingException("Can't follow referal for authentication: " + name);
+
+      results.close();
+      results = null;
+      // SECURITY-225: don't need to authenticate again
+      if (isPasswordValidated)
+      {
+         // Bind as the user dn to authenticate the user
+         InitialLdapContext userCtx = constructInitialLdapContext(userDN, credential);
+         userCtx.close();
+      }
+
+      return userDN;
+   }
+
+   /**
+    @param ctx
+    @param constraints
+    @param user
+    @param userDN
+    @param recursionMax
+    @param nesting
+    @throws NamingException
+    */
+   @SuppressWarnings("unchecked")
+   protected void rolesSearch(InitialLdapContext ctx, SearchControls constraints, String user, String userDN,
+         int recursionMax, int nesting) throws NamingException
+   {
+      Object[] filterArgs = {user, userDN};
+      NamingEnumeration results = ctx.search(rolesCtxDN, roleFilter, filterArgs, constraints);
+      try
+      {
+         while (results.hasMore())
+         {
+            SearchResult sr = (SearchResult) results.next();
+            String dn = canonicalize(sr.getName());
+            if (nesting == 0 && roleAttributeIsDN && roleNameAttributeID != null)
+            {
+               // Check the top context for role names
+               String[] attrNames = {roleNameAttributeID};
+               Attributes result2 = ctx.getAttributes(dn, attrNames);
+               Attribute roles2 = result2.get(roleNameAttributeID);
+               if (roles2 != null)
+               {
+                  for (int m = 0; m < roles2.size(); m++)
+                  {
+                     String roleName = (String) roles2.get(m);
+                     addRole(roleName);
+                  }
+               }
+            }
+
+            // Query the context for the roleDN values
+            String[] attrNames = {roleAttributeID};
+            Attributes result = ctx.getAttributes(dn, attrNames);
+            if (result != null && result.size() > 0)
+            {
+               Attribute roles = result.get(roleAttributeID);
+               for (int n = 0; n < roles.size(); n++)
+               {
+                  String roleName = (String) roles.get(n);
+                  if (roleAttributeIsDN)
+                  {
+                     // Query the roleDN location for the value of roleNameAttributeID
+                     String roleDN = roleName;
+                     String[] returnAttribute = {roleNameAttributeID};
+                     if(trace)
+                        log.trace("Using roleDN: " + roleDN);
+                     try
+                     {
+                        Attributes result2 = ctx.getAttributes(roleDN, returnAttribute);
+                        Attribute roles2 = result2.get(roleNameAttributeID);
+                        if (roles2 != null)
+                        {
+                           for (int m = 0; m < roles2.size(); m++)
+                           {
+                              roleName = (String) roles2.get(m);
+                              addRole(roleName);
+                           }
+                        }
+                     }
+                     catch (NamingException e)
+                     {
+                        if(trace)
+                           log.trace("Failed to query roleNameAttrName", e);
+                     }
+                  }
+                  else
+                  {
+                     // The role attribute value is the role name
+                     addRole(roleName);
+                  }
+               }
+            }
+
+            if (nesting < recursionMax)
+            {
+               rolesSearch(ctx, constraints, user, dn, recursionMax, nesting + 1);
+            }
+         }
+      }
+      finally
+      {
+         if (results != null)
+            results.close();
+      }
+
+   }
+
+   @SuppressWarnings("unchecked")
+   private InitialLdapContext constructInitialLdapContext(String dn, Object credential) throws NamingException
+   {
+      Properties env = new Properties();
+      Iterator iter = options.entrySet().iterator();
+      while (iter.hasNext())
+      {
+         Entry entry = (Entry) iter.next();
+         env.put(entry.getKey(), entry.getValue());
+      }
+
+      // Set defaults for key values if they are missing
+      String factoryName = env.getProperty(Context.INITIAL_CONTEXT_FACTORY);
+      if (factoryName == null)
+      {
+         factoryName = "com.sun.jndi.ldap.LdapCtxFactory";
+         env.setProperty(Context.INITIAL_CONTEXT_FACTORY, factoryName);
+      }
+      String authType = env.getProperty(Context.SECURITY_AUTHENTICATION);
+      if (authType == null)
+         env.setProperty(Context.SECURITY_AUTHENTICATION, "simple");
+      String protocol = env.getProperty(Context.SECURITY_PROTOCOL);
+      String providerURL = (String) options.get(Context.PROVIDER_URL);
+      if (providerURL == null)
+         providerURL = "ldap://localhost:" + ((protocol != null && protocol.equals("ssl")) ? "636" : "389");
+
+      env.setProperty(Context.PROVIDER_URL, providerURL);
+      // JBAS-3555, allow anonymous login with no bindDN and bindCredential
+      if (dn != null)
+         env.setProperty(Context.SECURITY_PRINCIPAL, dn);
+      if (credential != null)
+         env.put(Context.SECURITY_CREDENTIALS, credential);
+      traceLdapEnv(env);
+      return new InitialLdapContext(env, null);
+   }
+
+   private void traceLdapEnv(Properties env)
+   {
+      if (trace)
+      {
+         Properties tmp = new Properties();
+         tmp.putAll(env);
+         tmp.setProperty(Context.SECURITY_CREDENTIALS, "***");
+         log.trace("Logging into LDAP server, env=" + tmp.toString());
+      }
+   }
+
+   //JBAS-3438 : Handle "/" correctly
+   private String canonicalize(String searchResult)
+   {
+      String result = searchResult;
+      int len = searchResult.length();
+
+      if (searchResult.endsWith("\""))
+      {
+         result = searchResult.substring(0, len - 1) + "," + rolesCtxDN + "\"";
+      }
+      else
+      {
+         result = searchResult + "," + rolesCtxDN;
+      }
+      return result;
+   }
+
+   private void addRole(String roleName)
+   {
+      if (roleName != null)
+      {
+         try
+         {
+            Principal p = super.createIdentity(roleName);
+            if(trace)
+               log.trace("Assign user to role " + roleName);
+            userRoles.addMember(p);
+         }
+         catch (Exception e)
+         {
+            if(trace)
+               log.debug("Failed to create principal: " + roleName, e);
+         }
+      }
+   }
+}
\ No newline at end of file

Deleted: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/SimpleServerLoginModule.java
===================================================================
--- projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/security/auth/spi/SimpleServerLoginModule.java	2009-07-21 21:59:08 UTC (rev 91524)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/SimpleServerLoginModule.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -1,90 +0,0 @@
-/*
-* JBoss, Home of Professional Open Source
-* Copyright 2005, JBoss Inc., and individual contributors as indicated
-* by the @authors tag. See the copyright.txt in the distribution for a
-* full listing of individual contributors.
-*
-* This is free software; you can redistribute it and/or modify it
-* under the terms of the GNU Lesser General Public License as
-* published by the Free Software Foundation; either version 2.1 of
-* the License, or (at your option) any later version.
-*
-* This software is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-* Lesser General Public License for more details.
-*
-* You should have received a copy of the GNU Lesser General Public
-* License along with this software; if not, write to the Free
-* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
-*/
-package org.jboss.security.auth.spi;
-
-import java.security.Principal;
-import java.security.acl.Group;
-
-import javax.security.auth.login.LoginException;
-
-import org.jboss.security.SimpleGroup;
-import org.jboss.security.SimplePrincipal;
-
-/**
- * A simple server login module useful to quick setup of security for testing
- * purposes. It implements the following simple algorithm:
- * <ul>
- * <li> if password is null, authenticate the user and assign an identity of "guest"
- *        and a role of "guest".
- * <li> else if password is equal to the user name, assign an identity equal to
- *        the username and both "user" and "guest" roles
- * <li> else authentication fails.
- * </ul>
- *
- * @author <a href="on at ibis.odessa.ua">Oleg Nitz</a>
- * @author Scott.Stark at jboss.org
- * @version $Revision$
- */
-public class SimpleServerLoginModule extends UsernamePasswordLoginModule
-{
-   private SimplePrincipal user;
-   private boolean guestOnly;
-
-   protected Principal getIdentity()
-   {
-      Principal principal = user;
-      if( principal == null )
-         principal = super.getIdentity();
-      return principal;
-   }
-
-   protected boolean validatePassword(String inputPassword, String expectedPassword)
-   {
-      boolean isValid = false;
-      if( inputPassword == null )
-      {
-         guestOnly = true;
-         isValid = true;
-         user = new SimplePrincipal("guest");
-      }
-      else
-      {
-         isValid = inputPassword.equals(expectedPassword);
-      }
-      return isValid;
-   }
-
-   protected Group[] getRoleSets() throws LoginException
-   {
-      Group[] roleSets = {new SimpleGroup("Roles")};
-      if( guestOnly == false )
-         roleSets[0].addMember(new SimplePrincipal("user"));
-      roleSets[0].addMember(new SimplePrincipal("guest"));
-      return roleSets;
-   }
-
-   protected String getUsersPassword() throws LoginException
-   {
-      return getUsername();
-   }
-
-}

Copied: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/SimpleServerLoginModule.java (from rev 92165, projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/security/auth/spi/SimpleServerLoginModule.java)
===================================================================
--- projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/SimpleServerLoginModule.java	                        (rev 0)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/SimpleServerLoginModule.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -0,0 +1,98 @@
+/*
+* JBoss, Home of Professional Open Source
+* Copyright 2005, JBoss Inc., and individual contributors as indicated
+* by the @authors tag. See the copyright.txt in the distribution for a
+* full listing of individual contributors.
+*
+* This is free software; you can redistribute it and/or modify it
+* under the terms of the GNU Lesser General Public License as
+* published by the Free Software Foundation; either version 2.1 of
+* the License, or (at your option) any later version.
+*
+* This software is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+* Lesser General Public License for more details.
+*
+* You should have received a copy of the GNU Lesser General Public
+* License along with this software; if not, write to the Free
+* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+*/
+package org.jboss.security.auth.spi;
+
+import java.security.Principal;
+import java.security.acl.Group;
+import java.util.Set;
+
+import javax.security.auth.login.LoginException;
+
+import org.jboss.security.SimpleGroup;
+import org.jboss.security.SimplePrincipal;
+
+/**
+ * A simple server login module useful to quick setup of security for testing
+ * purposes. It implements the following simple algorithm:
+ * <ul>
+ * <li> if password is null, authenticate the user and assign an identity of "guest"
+ *        and a role of "guest".
+ * <li> else if password is equal to the user name, assign an identity equal to
+ *        the username and both "user" and "guest" roles
+ * <li> else authentication fails.
+ * </ul>
+ *
+ * @author <a href="on at ibis.odessa.ua">Oleg Nitz</a>
+ * @author Scott.Stark at jboss.org
+ * @version $Revision$
+ */
+public class SimpleServerLoginModule extends UsernamePasswordLoginModule
+{
+   private SimplePrincipal user;
+   private boolean guestOnly;
+
+   protected Principal getIdentity()
+   {
+      Principal principal = user;
+      if( principal == null )
+         principal = super.getIdentity();
+      return principal;
+   }
+
+   protected boolean validatePassword(String inputPassword, String expectedPassword)
+   {
+      boolean isValid = false;
+      if( inputPassword == null )
+      {
+         guestOnly = true;
+         isValid = true;
+         user = new SimplePrincipal("guest");
+      }
+      else
+      {
+         isValid = inputPassword.equals(expectedPassword);
+      }
+      return isValid;
+   }
+
+   protected Group[] getRoleSets() throws LoginException
+   {
+      Group[] roleSets = {new SimpleGroup("Roles")};
+      if( guestOnly == false )
+         roleSets[0].addMember(new SimplePrincipal("user"));
+      roleSets[0].addMember(new SimplePrincipal("guest"));
+      return roleSets;
+   }
+
+   protected String getUsersPassword() throws LoginException
+   {
+      return getUsername();
+   }
+   
+   @Override
+   public boolean logout() throws LoginException
+   {
+      Group[] groups = this.getRoleSets();
+      subject.getPrincipals().remove(groups[0]); 
+      return super.logout();
+   }  
+}
\ No newline at end of file

Deleted: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/UsersObjectModelFactory.java
===================================================================
--- projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/security/auth/spi/UsersObjectModelFactory.java	2009-07-21 21:59:08 UTC (rev 91524)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/UsersObjectModelFactory.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -1,100 +0,0 @@
-/*
-* JBoss, Home of Professional Open Source
-* Copyright 2005, JBoss Inc., and individual contributors as indicated
-* by the @authors tag. See the copyright.txt in the distribution for a
-* full listing of individual contributors.
-*
-* This is free software; you can redistribute it and/or modify it
-* under the terms of the GNU Lesser General Public License as
-* published by the Free Software Foundation; either version 2.1 of
-* the License, or (at your option) any later version.
-*
-* This software is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-* Lesser General Public License for more details.
-*
-* You should have received a copy of the GNU Lesser General Public
-* License along with this software; if not, write to the Free
-* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
-*/
-package org.jboss.security.auth.spi;
-
-import org.jboss.logging.Logger;
-import org.jboss.xb.binding.ObjectModelFactory;
-import org.jboss.xb.binding.UnmarshallingContext;
-import org.xml.sax.Attributes;
-
-/** A JBossXB object factory for parsing the 
- * @author Scott.Stark at jboss.org
- * @version $Revision$
- */
-public class UsersObjectModelFactory implements ObjectModelFactory
-{
-   private static Logger log = Logger.getLogger(UsersObjectModelFactory.class);
-
-   public Object newRoot(Object root, UnmarshallingContext navigator,
-      String namespaceURI, String localName, Attributes attrs)
-   {
-      if (!localName.equals("users"))
-      {
-         throw new IllegalStateException("Unexpected root element: was expecting 'users' but got '" + localName + "'");
-      }
-      log.trace("newRoot, root="+root);
-      return new Users();
-   }
-
-   public Object completeRoot(Object root, UnmarshallingContext ctx, String uri, String name)
-   {
-      return root;
-   }
-   
-   public void setValue(Users users, UnmarshallingContext navigator,
-      String namespaceUri, String localName, String value)
-   {
-   }
-
-   public Object newChild(Users users, UnmarshallingContext navigator,
-      String namespaceUri, String localName, Attributes attrs)
-   {
-      Users.User child = null;
-      if("user".equals(localName))
-      {
-         String name = attrs.getValue("name");
-         child = new Users.User(name);
-         String password = attrs.getValue("password");
-         child.setPassword(password);
-         String encoding = attrs.getValue("encoding");
-         child.setEncoding(encoding);
-         log.trace("newChild, user="+child);
-      }
-      return child;
-   }
-
-   public void addChild(Users users, Users.User user,
-      UnmarshallingContext navigator, String namespaceURI, String localName)
-   {
-      users.addUser(user);
-   }
-
-   public Object newChild(Users.User user, UnmarshallingContext navigator,
-      String namespaceUri, String localName, Attributes attrs)
-   {
-      String[] roleInfo = {null, "Roles"};
-      if("role".equals(localName))
-      {
-         roleInfo[0] = attrs.getValue("name");
-         roleInfo[1] = attrs.getValue("group");
-         if( roleInfo[1] == null )
-            roleInfo[1] = "Roles";
-      }
-      return roleInfo;
-   }
-
-   public void addChild(Users.User user, String[] roleInfo,
-      UnmarshallingContext navigator, String namespaceURI, String localName)
-   {
-      user.addRole(roleInfo[0], roleInfo[1]);
-   }
-}

Copied: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/UsersObjectModelFactory.java (from rev 93325, projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/security/auth/spi/UsersObjectModelFactory.java)
===================================================================
--- projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/UsersObjectModelFactory.java	                        (rev 0)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/UsersObjectModelFactory.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -0,0 +1,103 @@
+/*
+* JBoss, Home of Professional Open Source
+* Copyright 2005, JBoss Inc., and individual contributors as indicated
+* by the @authors tag. See the copyright.txt in the distribution for a
+* full listing of individual contributors.
+*
+* This is free software; you can redistribute it and/or modify it
+* under the terms of the GNU Lesser General Public License as
+* published by the Free Software Foundation; either version 2.1 of
+* the License, or (at your option) any later version.
+*
+* This software is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+* Lesser General Public License for more details.
+*
+* You should have received a copy of the GNU Lesser General Public
+* License along with this software; if not, write to the Free
+* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+*/
+package org.jboss.security.auth.spi;
+
+import org.jboss.logging.Logger;
+import org.jboss.xb.binding.ObjectModelFactory;
+import org.jboss.xb.binding.UnmarshallingContext;
+import org.xml.sax.Attributes;
+
+/** A JBossXB object factory for parsing the 
+ * @author Scott.Stark at jboss.org
+ * @version $Revision$
+ */
+public class UsersObjectModelFactory implements ObjectModelFactory
+{
+   private static Logger log = Logger.getLogger(UsersObjectModelFactory.class);
+   private boolean trace = log.isTraceEnabled();
+   
+   public Object newRoot(Object root, UnmarshallingContext navigator,
+      String namespaceURI, String localName, Attributes attrs)
+   {
+      if (!localName.equals("users"))
+      {
+         throw new IllegalStateException("Unexpected root element: was expecting 'users' but got '" + localName + "'");
+      }
+      if(trace)
+         log.trace("newRoot, root="+root);
+      return new Users();
+   }
+
+   public Object completeRoot(Object root, UnmarshallingContext ctx, String uri, String name)
+   {
+      return root;
+   }
+   
+   public void setValue(Users users, UnmarshallingContext navigator,
+      String namespaceUri, String localName, String value)
+   {
+   }
+
+   public Object newChild(Users users, UnmarshallingContext navigator,
+      String namespaceUri, String localName, Attributes attrs)
+   {
+      Users.User child = null;
+      if("user".equals(localName))
+      {
+         String name = attrs.getValue("name");
+         child = new Users.User(name);
+         String password = attrs.getValue("password");
+         child.setPassword(password);
+         String encoding = attrs.getValue("encoding");
+         child.setEncoding(encoding);
+         if(trace)
+            log.trace("newChild, user="+child);
+      }
+      return child;
+   }
+
+   public void addChild(Users users, Users.User user,
+      UnmarshallingContext navigator, String namespaceURI, String localName)
+   {
+      users.addUser(user);
+   }
+
+   public Object newChild(Users.User user, UnmarshallingContext navigator,
+      String namespaceUri, String localName, Attributes attrs)
+   {
+      String[] roleInfo = {null, "Roles"};
+      if("role".equals(localName))
+      {
+         roleInfo[0] = attrs.getValue("name");
+         roleInfo[1] = attrs.getValue("group");
+         if( roleInfo[1] == null )
+            roleInfo[1] = "Roles";
+      }
+      return roleInfo;
+   }
+
+   public void addChild(Users.User user, String[] roleInfo,
+      UnmarshallingContext navigator, String namespaceURI, String localName)
+   {
+      user.addRole(roleInfo[0], roleInfo[1]);
+   }
+}
\ No newline at end of file

Deleted: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/Util.java
===================================================================
--- projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/security/auth/spi/Util.java	2009-07-21 21:59:08 UTC (rev 91524)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/Util.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -1,515 +0,0 @@
-/*
-* JBoss, Home of Professional Open Source
-* Copyright 2005, JBoss Inc., and individual contributors as indicated
-* by the @authors tag. See the copyright.txt in the distribution for a
-* full listing of individual contributors.
-*
-* This is free software; you can redistribute it and/or modify it
-* under the terms of the GNU Lesser General Public License as
-* published by the Free Software Foundation; either version 2.1 of
-* the License, or (at your option) any later version.
-*
-* This software is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-* Lesser General Public License for more details.
-*
-* You should have received a copy of the GNU Lesser General Public
-* License along with this software; if not, write to the Free
-* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
-*/
-package org.jboss.security.auth.spi;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.UnsupportedEncodingException;
-import java.net.URL;
-import java.net.URLClassLoader;
-import java.security.MessageDigest;
-import java.security.Principal;
-import java.security.PrivilegedActionException;
-import java.security.acl.Group;
-import java.util.ArrayList;
-import java.util.Enumeration;
-import java.util.Properties;
-import java.util.StringTokenizer;
-
-import javax.security.auth.login.LoginException;
-
-import org.jboss.crypto.digest.DigestCallback;
-import org.jboss.logging.Logger;
-import org.jboss.security.Base64Encoder;
-import org.jboss.security.Base64Utils;
-import org.jboss.security.SimpleGroup;
-
-/**
- * Common login module utility methods
- * 
- * @author Scott.Stark at jboss.org
- * @version $Revision$
- */
-public class Util
-{
-   private static Logger log = Logger.getLogger(Util.class);  
-
-   public static final String BASE64_ENCODING = "BASE64";
-   public static final String BASE16_ENCODING = "HEX";
-   public static final String RFC2617_ENCODING = "RFC2617";
-   /**
-    The ASCII printable characters the MD5 digest maps to for RFC2617
-    */
-   private static char[] MD5_HEX = "0123456789abcdef".toCharArray();
-
-   
-   
-   /** Create the set of roles the user belongs to by parsing the roles.properties
-    data for username=role1,role2,... and username.XXX=role1,role2,...
-    patterns.
-    * 
-    * @param targetUser - the username to obtain roles for
-    * @param roles - the Properties containing the user=roles mappings
-    * @param roleGroupSeperator - the character that seperates a username
-    *    from a group name, e.g., targetUser[.GroupName]=roles
-    * @param aslm - the login module to use for Principal creation
-    * @return Group[] containing the sets of roles
-    */ 
-   static Group[] getRoleSets(String targetUser, Properties roles,
-      char roleGroupSeperator, AbstractServerLoginModule aslm)
-   {
-      Logger log = aslm.log;      
-      boolean trace = log.isTraceEnabled();
-      Enumeration<?> users = roles.propertyNames();
-      SimpleGroup rolesGroup = new SimpleGroup("Roles");
-      ArrayList<Group> groups = new ArrayList<Group>();
-      groups.add(rolesGroup);
-      while (users.hasMoreElements() && targetUser != null)
-      {
-         String user = (String) users.nextElement();
-         String value = roles.getProperty(user);
-         if( trace )
-            log.trace("Checking user: "+user+", roles string: "+value);
-         // See if this entry is of the form targetUser[.GroupName]=roles
-         //JBAS-3742 - skip potential '.' in targetUser
-         int index = user.indexOf(roleGroupSeperator, targetUser.length());
-         boolean isRoleGroup = false;
-         boolean userMatch = false;
-         if (index > 0 && targetUser.regionMatches(0, user, 0, index) == true)
-            isRoleGroup = true;
-         else
-            userMatch = targetUser.equals(user);
-
-         // Check for username.RoleGroup pattern
-         if (isRoleGroup == true)
-         {
-            String groupName = user.substring(index + 1);
-            if (groupName.equals("Roles"))
-            {
-               if( trace )
-                  log.trace("Adding to Roles: "+value);
-               parseGroupMembers(rolesGroup, value, aslm);
-            }
-            else
-            {
-               if( trace )
-                  log.trace("Adding to "+groupName+": "+value);
-               SimpleGroup group = new SimpleGroup(groupName);
-               parseGroupMembers(group, value, aslm);
-               groups.add(group);
-            }
-         }
-         else if (userMatch == true)
-         {
-            if( trace )
-               log.trace("Adding to Roles: "+value);
-            // Place these roles into the Default "Roles" group
-            parseGroupMembers(rolesGroup, value, aslm);
-         }
-      }
-      Group[] roleSets = new Group[groups.size()];
-      groups.toArray(roleSets);
-      return roleSets;
-   }
-
-   /** Execute the rolesQuery against the dsJndiName to obtain the roles for
-    the authenticated user.
-     
-    @return Group[] containing the sets of roles
-    */
-   static Group[] getRoleSets(String username, String dsJndiName,
-      String rolesQuery, AbstractServerLoginModule aslm)
-      throws LoginException
-   {
-      return getRoleSets(username, dsJndiName, rolesQuery, aslm, false);
-   }
-
-   /** Execute the rolesQuery against the dsJndiName to obtain the roles for
-    the authenticated user.
-     
-    @return Group[] containing the sets of roles
-    */
-   static Group[] getRoleSets(String username, String dsJndiName,
-      String rolesQuery, AbstractServerLoginModule aslm, boolean suspendResume)
-      throws LoginException
-   {
-      return DbUtil.getRoleSets(username, dsJndiName, rolesQuery, aslm, suspendResume); 
-   }
-
-   /** Utility method which loads the given properties file and returns a
-    * Properties object containing the key,value pairs in that file.
-    * The properties files should be in the class path as this method looks
-    * to the thread context class loader (TCL) to locate the resource. If the
-    * TCL is a URLClassLoader the findResource(String) method is first tried.
-    * If this fails or the TCL is not a URLClassLoader getResource(String) is
-    * tried.
-    * @param defaultsName - the name of the default properties file resource
-    *    that will be used as the default Properties to the ctor of the
-    *    propertiesName Properties instance.
-    * @param propertiesName - the name of the properties file resource
-    * @param log - the logger used for trace level messages
-    * @return the loaded properties file if found
-    * @exception java.io.IOException thrown if the properties file cannot be found
-    *    or loaded 
-    */
-   static Properties loadProperties(String defaultsName, String propertiesName, Logger log)
-      throws IOException
-   {
-      Properties bundle = null;
-      ClassLoader loader = SecurityActions.getContextClassLoader();
-      URL defaultUrl = null;
-      URL url = null;
-      // First check for local visibility via a URLClassLoader.findResource
-      if( loader instanceof URLClassLoader )
-      {
-         URLClassLoader ucl = (URLClassLoader) loader;
-         defaultUrl = SecurityActions.findResource(ucl,defaultsName);
-         url = SecurityActions.findResource(ucl,propertiesName);
-         log.trace("findResource: "+url);
-      }
-      // Do a general resource search
-      if( defaultUrl == null )
-         defaultUrl = loader.getResource(defaultsName);
-      if( url == null )
-         url = loader.getResource(propertiesName);
-      if( url == null && defaultUrl == null )
-      {
-         String msg = "No properties file: " + propertiesName
-            + " or defaults: " +defaultsName+ " found";
-         throw new IOException(msg);
-      }
-
-      log.trace("Properties file=" + url+", defaults="+defaultUrl);
-      Properties defaults = new Properties();
-      if( defaultUrl != null )
-      {
-         try
-         {
-            InputStream is = defaultUrl.openStream();
-            defaults.load(is);
-            is.close();
-            log.debug("Loaded defaults, users="+defaults.keySet());
-         }
-         catch(Throwable e)
-         {
-            log.debug("Failed to load defaults", e);
-         }
-      }
-
-      bundle = new Properties(defaults);
-      if( url != null )
-      {
-         InputStream is = null;
-         try
-         {
-            is = SecurityActions.openStream(url);
-         }
-         catch (PrivilegedActionException e)
-         {
-            log.trace("Open stream error", e);
-            throw new IOException(e.getLocalizedMessage());
-         }
-         if (is != null)
-         {
-            bundle.load(is);
-            is.close();
-         }
-         else
-         {
-            throw new IOException("Properties file " + propertiesName + " not avilable");
-         }
-         log.debug("Loaded properties, users="+bundle.keySet());
-      }
-
-      return bundle;
-   }
-
-   /** Utility method which loads the given properties file and returns a
-    * Properties object containing the key,value pairs in that file.
-    * The properties files should be in the class path as this method looks
-    * to the thread context class loader (TCL) to locate the resource. If the
-    * TCL is a URLClassLoader the findResource(String) method is first tried.
-    * If this fails or the TCL is not a URLClassLoader getResource(String) is
-    * tried. If not, an absolute path is tried.
-    * @param propertiesName - the name of the properties file resource
-    * @param log - the logger used for trace level messages
-    * @return the loaded properties file if found
-    * @exception java.io.IOException thrown if the properties file cannot be found
-    *    or loaded 
-    */
-   static Properties loadProperties(String propertiesName, Logger log)
-      throws IOException
-   { 
-      ClassLoader loader = SecurityActions.getContextClassLoader(); 
-      URL url = null;
-      // First check for local visibility via a URLClassLoader.findResource
-      if( loader instanceof URLClassLoader )
-      {
-         URLClassLoader ucl = (URLClassLoader) loader; 
-         url = SecurityActions.findResource(ucl,propertiesName);
-         log.trace("findResource: "+url);
-      } 
-      if( url == null )
-         url = loader.getResource(propertiesName);
-      if( url == null)
-      {
-         url = new URL(propertiesName); 
-      }
-
-      log.trace("Properties file=" + url ); 
-
-      Properties bundle = new Properties();
-      if( url != null )
-      {
-         InputStream is = null;
-         try
-         {
-            is = SecurityActions.openStream(url);
-         }
-         catch (PrivilegedActionException e)
-         {
-            log.trace("open stream error:", e);
-            throw new IOException(e.getLocalizedMessage());
-         }
-         if (is != null)
-         {
-            bundle.load(is);
-            is.close();
-         }
-         else
-         {
-            throw new IOException("Properties file " + propertiesName + " not available");
-         }
-         log.debug("Loaded properties, users="+bundle.keySet());
-      }
-
-      return bundle;
-   }
-
-
-   /** Parse the comma delimited roles names given by value and add them to
-    * group. The type of Principal created for each name is determined by
-    * the createIdentity method.
-    *
-    * @see AbstractServerLoginModule#createIdentity(String)
-    * 
-    * @param group - the Group to add the roles to.
-    * @param roles - the comma delimited role names.
-    */ 
-   static void parseGroupMembers(Group group, String roles,
-      AbstractServerLoginModule aslm)
-   {
-      StringTokenizer tokenizer = new StringTokenizer(roles, ",");
-      while (tokenizer.hasMoreTokens())
-      {
-         String token = tokenizer.nextToken();
-         try
-         {
-            Principal p = aslm.createIdentity(token);
-            group.addMember(p);
-         }
-         catch (Exception e)
-         {
-            aslm.log.warn("Failed to create principal for: "+token, e);
-         }
-      }
-   }
-   
-   /**
-    * Calculate a password hash using a MessageDigest.
-    *
-    * @param hashAlgorithm - the MessageDigest algorithm name
-    * @param hashEncoding - either base64 or hex to specify the type of
-       encoding the MessageDigest as a string.
-    * @param hashCharset - the charset used to create the byte[] passed to the
-    *  MessageDigestfrom the password String. If null the platform default is
-    *  used.
-    * @param username - ignored in default version
-    * @param password - the password string to be hashed
-    * @return the hashed string if successful, null if there is a digest exception
-    */
-    public static String createPasswordHash(String hashAlgorithm, String hashEncoding,
-       String hashCharset, String username, String password)
-   {
-      return createPasswordHash(hashAlgorithm, hashEncoding,
-       hashCharset, username, password, null);
-   }
-    /**
-     * Calculate a password hash using a MessageDigest.
-     *
-     * @param hashAlgorithm - the MessageDigest algorithm name
-     * @param hashEncoding - either base64 or hex to specify the type of
-        encoding the MessageDigest as a string.
-     * @param hashCharset - the charset used to create the byte[] passed to the
-     *  MessageDigestfrom the password String. If null the platform default is
-     *  used.
-     * @param username - ignored in default version
-     * @param password - the password string to be hashed
-     * @param callback - the callback used to allow customization of the hash
-     *    to occur. The preDigest method is called before the password is added
-     *    and the postDigest method is called after the password has been added.
-     * @return the hashed string if successful, null if there is a digest exception
-     */ 
-    public static String createPasswordHash(String hashAlgorithm, String hashEncoding,
-       String hashCharset, String username, String password, DigestCallback callback)
-    {
-       byte[] passBytes;
-       String passwordHash = null;
-
-       // convert password to byte data
-       try
-       {
-          if(hashCharset == null)
-             passBytes = password.getBytes();
-          else
-             passBytes = password.getBytes(hashCharset);
-       }
-       catch(UnsupportedEncodingException uee)
-       {
-          log.error("charset " + hashCharset + " not found. Using platform default.", uee);
-          passBytes = password.getBytes();
-       }
-
-       // calculate the hash and apply the encoding.
-       try
-       {
-          MessageDigest md = MessageDigest.getInstance(hashAlgorithm);
-          if( callback != null )
-             callback.preDigest(md);
-          md.update(passBytes);
-          if( callback != null )
-             callback.postDigest(md);
-          byte[] hash = md.digest();
-          if(hashEncoding.equalsIgnoreCase(BASE64_ENCODING))
-          {
-             passwordHash = Util.encodeBase64(hash);
-          }
-          else if(hashEncoding.equalsIgnoreCase(BASE16_ENCODING))
-          {
-             passwordHash = Util.encodeBase16(hash);
-          }
-          else if(hashEncoding.equalsIgnoreCase(RFC2617_ENCODING))
-          {
-             passwordHash = Util.encodeRFC2617(hash);
-          }
-          else
-          {
-             log.error("Unsupported hash encoding format " + hashEncoding);
-          }
-       }
-       catch(Exception e)
-       {
-          log.error("Password hash calculation failed ", e);
-       }
-       return passwordHash;
-    }
-    
-    /**
-    3.1.3 Representation of digest values
-
-    An optional header allows the server to specify the algorithm used to create
-    the checksum or digest. By default the MD5 algorithm is used and that is the
-    only algorithm described in this document.
-
-    For the purposes of this document, an MD5 digest of 128 bits is represented
-    as 32 ASCII printable characters. The bits in the 128 bit digest are
-    converted from most significant to least significant bit, four bits at a time
-    to their ASCII presentation as follows. Each four bits is represented by its
-    familiar hexadecimal notation from the characters 0123456789abcdef. That is,
-    binary 0000 getInfos represented by the character '0', 0001, by '1', and so
-    on up to the representation of 1111 as 'f'.
-    
-    @param data - the raw MD5 hash data
-    @return the encoded MD5 representation
-    */
-   public static String encodeRFC2617(byte[] data)
-   {
-      char[] hash = new char[32];
-      for (int i = 0; i < 16; i++)
-      {
-         int j = (data[i] >> 4) & 0xf;
-         hash[i * 2] = MD5_HEX[j];
-         j = data[i] & 0xf;
-         hash[i * 2 + 1] = MD5_HEX[j];
-      }
-      return new String(hash);
-   } 
-   
-    /**
-     * Hex encoding of hashes, as used by Catalina. Each byte is converted to
-     * the corresponding two hex characters.
-     */
-    public static String encodeBase16(byte[] bytes)
-    {
-       StringBuffer sb = new StringBuffer(bytes.length * 2);
-       for (int i = 0; i < bytes.length; i++)
-       {
-          byte b = bytes[i];
-          // top 4 bits
-          char c = (char)((b >> 4) & 0xf);
-          if(c > 9)
-             c = (char)((c - 10) + 'a');
-          else
-             c = (char)(c + '0');
-          sb.append(c);
-          // bottom 4 bits
-          c = (char)(b & 0xf);
-          if (c > 9)
-             c = (char)((c - 10) + 'a');
-          else
-             c = (char)(c + '0');
-          sb.append(c);
-       }
-       return sb.toString();
-    }
-
-    /**
-     * BASE64 encoder implementation.
-     * Provides encoding methods, using the BASE64 encoding rules, as defined
-     * in the MIME specification, <a href="http://ietf.org/rfc/rfc1521.txt">rfc1521</a>.
-     */
-    public static String encodeBase64(byte[] bytes)
-    {
-       String base64 = null;
-       try
-       {
-          base64 = Base64Encoder.encode(bytes);
-       }
-       catch(Exception e)
-       {
-       }
-       return base64;
-    }
-    
-    // These functions assume that the byte array has MSB at 0, LSB at end.
-    // Reverse the byte array (not the String) if this is not the case.
-    // All base64 strings are in natural order, least significant digit last.
-    public static String tob64(byte[] buffer)
-    {
-       return Base64Utils.tob64(buffer);  
-    }
-
-    public static byte[] fromb64(String str) throws NumberFormatException
-    {
-       return Base64Utils.fromb64(str); 
-    } 
-}

Copied: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/Util.java (from rev 93325, projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/security/auth/spi/Util.java)
===================================================================
--- projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/Util.java	                        (rev 0)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/auth/spi/Util.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -0,0 +1,528 @@
+/*
+* JBoss, Home of Professional Open Source
+* Copyright 2005, JBoss Inc., and individual contributors as indicated
+* by the @authors tag. See the copyright.txt in the distribution for a
+* full listing of individual contributors.
+*
+* This is free software; you can redistribute it and/or modify it
+* under the terms of the GNU Lesser General Public License as
+* published by the Free Software Foundation; either version 2.1 of
+* the License, or (at your option) any later version.
+*
+* This software is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+* Lesser General Public License for more details.
+*
+* You should have received a copy of the GNU Lesser General Public
+* License along with this software; if not, write to the Free
+* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+*/
+package org.jboss.security.auth.spi;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.UnsupportedEncodingException;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.security.MessageDigest;
+import java.security.Principal;
+import java.security.PrivilegedActionException;
+import java.security.acl.Group;
+import java.util.ArrayList;
+import java.util.Enumeration;
+import java.util.Properties;
+import java.util.StringTokenizer;
+
+import javax.security.auth.login.LoginException;
+
+import org.jboss.crypto.digest.DigestCallback;
+import org.jboss.logging.Logger;
+import org.jboss.security.Base64Encoder;
+import org.jboss.security.Base64Utils;
+import org.jboss.security.SimpleGroup;
+
+/**
+ * Common login module utility methods
+ * 
+ * @author Scott.Stark at jboss.org
+ * @version $Revision$
+ */
+public class Util
+{
+   private static Logger log = Logger.getLogger(Util.class); 
+
+   public static final String BASE64_ENCODING = "BASE64";
+   public static final String BASE16_ENCODING = "HEX";
+   public static final String RFC2617_ENCODING = "RFC2617";
+   /**
+    The ASCII printable characters the MD5 digest maps to for RFC2617
+    */
+   private static char[] MD5_HEX = "0123456789abcdef".toCharArray();
+
+   
+   
+   /** Create the set of roles the user belongs to by parsing the roles.properties
+    data for username=role1,role2,... and username.XXX=role1,role2,...
+    patterns.
+    * 
+    * @param targetUser - the username to obtain roles for
+    * @param roles - the Properties containing the user=roles mappings
+    * @param roleGroupSeperator - the character that seperates a username
+    *    from a group name, e.g., targetUser[.GroupName]=roles
+    * @param aslm - the login module to use for Principal creation
+    * @return Group[] containing the sets of roles
+    */ 
+   static Group[] getRoleSets(String targetUser, Properties roles,
+      char roleGroupSeperator, AbstractServerLoginModule aslm)
+   {
+      Logger log = aslm.log;      
+      boolean trace = log.isTraceEnabled();
+      Enumeration<?> users = roles.propertyNames();
+      SimpleGroup rolesGroup = new SimpleGroup("Roles");
+      ArrayList<Group> groups = new ArrayList<Group>();
+      groups.add(rolesGroup);
+      while (users.hasMoreElements() && targetUser != null)
+      {
+         String user = (String) users.nextElement();
+         String value = roles.getProperty(user);
+         if( trace )
+            log.trace("Checking user: "+user+", roles string: "+value);
+         // See if this entry is of the form targetUser[.GroupName]=roles
+         //JBAS-3742 - skip potential '.' in targetUser
+         int index = user.indexOf(roleGroupSeperator, targetUser.length());
+         boolean isRoleGroup = false;
+         boolean userMatch = false;
+         if (index > 0 && targetUser.regionMatches(0, user, 0, index) == true)
+            isRoleGroup = true;
+         else
+            userMatch = targetUser.equals(user);
+
+         // Check for username.RoleGroup pattern
+         if (isRoleGroup == true)
+         {
+            String groupName = user.substring(index + 1);
+            if (groupName.equals("Roles"))
+            {
+               if( trace )
+                  log.trace("Adding to Roles: "+value);
+               parseGroupMembers(rolesGroup, value, aslm);
+            }
+            else
+            {
+               if( trace )
+                  log.trace("Adding to "+groupName+": "+value);
+               SimpleGroup group = new SimpleGroup(groupName);
+               parseGroupMembers(group, value, aslm);
+               groups.add(group);
+            }
+         }
+         else if (userMatch == true)
+         {
+            if( trace )
+               log.trace("Adding to Roles: "+value);
+            // Place these roles into the Default "Roles" group
+            parseGroupMembers(rolesGroup, value, aslm);
+         }
+      }
+      Group[] roleSets = new Group[groups.size()];
+      groups.toArray(roleSets);
+      return roleSets;
+   }
+
+   /** Execute the rolesQuery against the dsJndiName to obtain the roles for
+    the authenticated user.
+     
+    @return Group[] containing the sets of roles
+    */
+   static Group[] getRoleSets(String username, String dsJndiName,
+      String rolesQuery, AbstractServerLoginModule aslm)
+      throws LoginException
+   {
+      return getRoleSets(username, dsJndiName, rolesQuery, aslm, false);
+   }
+
+   /** Execute the rolesQuery against the dsJndiName to obtain the roles for
+    the authenticated user.
+     
+    @return Group[] containing the sets of roles
+    */
+   static Group[] getRoleSets(String username, String dsJndiName,
+      String rolesQuery, AbstractServerLoginModule aslm, boolean suspendResume)
+      throws LoginException
+   {
+      return DbUtil.getRoleSets(username, dsJndiName, rolesQuery, aslm, suspendResume); 
+   }
+
+   /** Utility method which loads the given properties file and returns a
+    * Properties object containing the key,value pairs in that file.
+    * The properties files should be in the class path as this method looks
+    * to the thread context class loader (TCL) to locate the resource. If the
+    * TCL is a URLClassLoader the findResource(String) method is first tried.
+    * If this fails or the TCL is not a URLClassLoader getResource(String) is
+    * tried.
+    * @param defaultsName - the name of the default properties file resource
+    *    that will be used as the default Properties to the ctor of the
+    *    propertiesName Properties instance.
+    * @param propertiesName - the name of the properties file resource
+    * @param log - the logger used for trace level messages
+    * @return the loaded properties file if found
+    * @exception java.io.IOException thrown if the properties file cannot be found
+    *    or loaded 
+    */
+   static Properties loadProperties(String defaultsName, String propertiesName, Logger log)
+      throws IOException
+   {
+      boolean trace = log.isTraceEnabled();
+      
+      Properties bundle = null;
+      ClassLoader loader = SecurityActions.getContextClassLoader();
+      URL defaultUrl = null;
+      URL url = null;
+      // First check for local visibility via a URLClassLoader.findResource
+      if( loader instanceof URLClassLoader )
+      {
+         URLClassLoader ucl = (URLClassLoader) loader;
+         defaultUrl = SecurityActions.findResource(ucl,defaultsName);
+         url = SecurityActions.findResource(ucl,propertiesName);
+         if(log.isTraceEnabled())
+            log.trace("findResource: "+url);
+      }
+      // Do a general resource search
+      if( defaultUrl == null )
+         defaultUrl = loader.getResource(defaultsName);
+      if( url == null )
+         url = loader.getResource(propertiesName);
+      if( url == null && defaultUrl == null )
+      {
+         String msg = "No properties file: " + propertiesName
+            + " or defaults: " +defaultsName+ " found";
+         throw new IOException(msg);
+      }
+
+      if(log.isTraceEnabled())
+         log.trace("Properties file=" + url+", defaults="+defaultUrl);
+      Properties defaults = new Properties();
+      if( defaultUrl != null )
+      {
+         try
+         {
+            InputStream is = defaultUrl.openStream();
+            defaults.load(is);
+            is.close();
+            if(trace)
+               log.debug("Loaded defaults, users="+defaults.keySet());
+         }
+         catch(Throwable e)
+         {
+            if(trace)
+               log.debug("Failed to load defaults", e);
+         }
+      }
+
+      bundle = new Properties(defaults);
+      if( url != null )
+      {
+         InputStream is = null;
+         try
+         {
+            is = SecurityActions.openStream(url);
+         }
+         catch (PrivilegedActionException e)
+         {
+            if(trace)
+               log.trace("Open stream error", e);
+            throw new IOException(e.getLocalizedMessage());
+         }
+         if (is != null)
+         {
+            bundle.load(is);
+            is.close();
+         }
+         else
+         {
+            throw new IOException("Properties file " + propertiesName + " not avilable");
+         }
+         if(trace)
+            log.debug("Loaded properties, users="+bundle.keySet());
+      }
+
+      return bundle;
+   }
+
+   /** Utility method which loads the given properties file and returns a
+    * Properties object containing the key,value pairs in that file.
+    * The properties files should be in the class path as this method looks
+    * to the thread context class loader (TCL) to locate the resource. If the
+    * TCL is a URLClassLoader the findResource(String) method is first tried.
+    * If this fails or the TCL is not a URLClassLoader getResource(String) is
+    * tried. If not, an absolute path is tried.
+    * @param propertiesName - the name of the properties file resource
+    * @param log - the logger used for trace level messages
+    * @return the loaded properties file if found
+    * @exception java.io.IOException thrown if the properties file cannot be found
+    *    or loaded 
+    */
+   static Properties loadProperties(String propertiesName, Logger log)
+      throws IOException
+   { 
+      boolean trace = log.isTraceEnabled();
+      
+      ClassLoader loader = SecurityActions.getContextClassLoader(); 
+      URL url = null;
+      // First check for local visibility via a URLClassLoader.findResource
+      if( loader instanceof URLClassLoader )
+      {
+         URLClassLoader ucl = (URLClassLoader) loader; 
+         url = SecurityActions.findResource(ucl,propertiesName);
+         if(trace)
+            log.trace("findResource: "+url);
+      } 
+      if( url == null )
+         url = loader.getResource(propertiesName);
+      if( url == null)
+      {
+         url = new URL(propertiesName); 
+      }
+
+      if(trace)
+         log.trace("Properties file=" + url ); 
+
+      Properties bundle = new Properties();
+      if( url != null )
+      {
+         InputStream is = null;
+         try
+         {
+            is = SecurityActions.openStream(url);
+         }
+         catch (PrivilegedActionException e)
+         {
+            if(trace)
+               log.trace("open stream error:", e);
+            throw new IOException(e.getLocalizedMessage());
+         }
+         if (is != null)
+         {
+            bundle.load(is);
+            is.close();
+         }
+         else
+         {
+            throw new IOException("Properties file " + propertiesName + " not available");
+         }
+         log.debug("Loaded properties, users="+bundle.keySet());
+      }
+
+      return bundle;
+   }
+
+
+   /** Parse the comma delimited roles names given by value and add them to
+    * group. The type of Principal created for each name is determined by
+    * the createIdentity method.
+    *
+    * @see AbstractServerLoginModule#createIdentity(String)
+    * 
+    * @param group - the Group to add the roles to.
+    * @param roles - the comma delimited role names.
+    */ 
+   static void parseGroupMembers(Group group, String roles,
+      AbstractServerLoginModule aslm)
+   {
+      StringTokenizer tokenizer = new StringTokenizer(roles, ",");
+      while (tokenizer.hasMoreTokens())
+      {
+         String token = tokenizer.nextToken();
+         try
+         {
+            Principal p = aslm.createIdentity(token);
+            group.addMember(p);
+         }
+         catch (Exception e)
+         {
+            aslm.log.warn("Failed to create principal for: "+token, e);
+         }
+      }
+   }
+   
+   /**
+    * Calculate a password hash using a MessageDigest.
+    *
+    * @param hashAlgorithm - the MessageDigest algorithm name
+    * @param hashEncoding - either base64 or hex to specify the type of
+       encoding the MessageDigest as a string.
+    * @param hashCharset - the charset used to create the byte[] passed to the
+    *  MessageDigestfrom the password String. If null the platform default is
+    *  used.
+    * @param username - ignored in default version
+    * @param password - the password string to be hashed
+    * @return the hashed string if successful, null if there is a digest exception
+    */
+    public static String createPasswordHash(String hashAlgorithm, String hashEncoding,
+       String hashCharset, String username, String password)
+   {
+      return createPasswordHash(hashAlgorithm, hashEncoding,
+       hashCharset, username, password, null);
+   }
+    /**
+     * Calculate a password hash using a MessageDigest.
+     *
+     * @param hashAlgorithm - the MessageDigest algorithm name
+     * @param hashEncoding - either base64 or hex to specify the type of
+        encoding the MessageDigest as a string.
+     * @param hashCharset - the charset used to create the byte[] passed to the
+     *  MessageDigestfrom the password String. If null the platform default is
+     *  used.
+     * @param username - ignored in default version
+     * @param password - the password string to be hashed
+     * @param callback - the callback used to allow customization of the hash
+     *    to occur. The preDigest method is called before the password is added
+     *    and the postDigest method is called after the password has been added.
+     * @return the hashed string if successful, null if there is a digest exception
+     */ 
+    public static String createPasswordHash(String hashAlgorithm, String hashEncoding,
+       String hashCharset, String username, String password, DigestCallback callback)
+    {
+       byte[] passBytes;
+       String passwordHash = null;
+
+       // convert password to byte data
+       try
+       {
+          if(hashCharset == null)
+             passBytes = password.getBytes();
+          else
+             passBytes = password.getBytes(hashCharset);
+       }
+       catch(UnsupportedEncodingException uee)
+       {
+          log.error("charset " + hashCharset + " not found. Using platform default.", uee);
+          passBytes = password.getBytes();
+       }
+
+       // calculate the hash and apply the encoding.
+       try
+       {
+          MessageDigest md = MessageDigest.getInstance(hashAlgorithm);
+          if( callback != null )
+             callback.preDigest(md);
+          md.update(passBytes);
+          if( callback != null )
+             callback.postDigest(md);
+          byte[] hash = md.digest();
+          if(hashEncoding.equalsIgnoreCase(BASE64_ENCODING))
+          {
+             passwordHash = Util.encodeBase64(hash);
+          }
+          else if(hashEncoding.equalsIgnoreCase(BASE16_ENCODING))
+          {
+             passwordHash = Util.encodeBase16(hash);
+          }
+          else if(hashEncoding.equalsIgnoreCase(RFC2617_ENCODING))
+          {
+             passwordHash = Util.encodeRFC2617(hash);
+          }
+          else
+          {
+             log.error("Unsupported hash encoding format " + hashEncoding);
+          }
+       }
+       catch(Exception e)
+       {
+          log.error("Password hash calculation failed ", e);
+       }
+       return passwordHash;
+    }
+    
+    /**
+    3.1.3 Representation of digest values
+
+    An optional header allows the server to specify the algorithm used to create
+    the checksum or digest. By default the MD5 algorithm is used and that is the
+    only algorithm described in this document.
+
+    For the purposes of this document, an MD5 digest of 128 bits is represented
+    as 32 ASCII printable characters. The bits in the 128 bit digest are
+    converted from most significant to least significant bit, four bits at a time
+    to their ASCII presentation as follows. Each four bits is represented by its
+    familiar hexadecimal notation from the characters 0123456789abcdef. That is,
+    binary 0000 getInfos represented by the character '0', 0001, by '1', and so
+    on up to the representation of 1111 as 'f'.
+    
+    @param data - the raw MD5 hash data
+    @return the encoded MD5 representation
+    */
+   public static String encodeRFC2617(byte[] data)
+   {
+      char[] hash = new char[32];
+      for (int i = 0; i < 16; i++)
+      {
+         int j = (data[i] >> 4) & 0xf;
+         hash[i * 2] = MD5_HEX[j];
+         j = data[i] & 0xf;
+         hash[i * 2 + 1] = MD5_HEX[j];
+      }
+      return new String(hash);
+   } 
+   
+    /**
+     * Hex encoding of hashes, as used by Catalina. Each byte is converted to
+     * the corresponding two hex characters.
+     */
+    public static String encodeBase16(byte[] bytes)
+    {
+       StringBuffer sb = new StringBuffer(bytes.length * 2);
+       for (int i = 0; i < bytes.length; i++)
+       {
+          byte b = bytes[i];
+          // top 4 bits
+          char c = (char)((b >> 4) & 0xf);
+          if(c > 9)
+             c = (char)((c - 10) + 'a');
+          else
+             c = (char)(c + '0');
+          sb.append(c);
+          // bottom 4 bits
+          c = (char)(b & 0xf);
+          if (c > 9)
+             c = (char)((c - 10) + 'a');
+          else
+             c = (char)(c + '0');
+          sb.append(c);
+       }
+       return sb.toString();
+    }
+
+    /**
+     * BASE64 encoder implementation.
+     * Provides encoding methods, using the BASE64 encoding rules, as defined
+     * in the MIME specification, <a href="http://ietf.org/rfc/rfc1521.txt">rfc1521</a>.
+     */
+    public static String encodeBase64(byte[] bytes)
+    {
+       String base64 = null;
+       try
+       {
+          base64 = Base64Encoder.encode(bytes);
+       }
+       catch(Exception e)
+       {
+       }
+       return base64;
+    }
+    
+    // These functions assume that the byte array has MSB at 0, LSB at end.
+    // Reverse the byte array (not the String) if this is not the case.
+    // All base64 strings are in natural order, least significant digit last.
+    public static String tob64(byte[] buffer)
+    {
+       return Base64Utils.tob64(buffer);  
+    }
+
+    public static byte[] fromb64(String str) throws NumberFormatException
+    {
+       return Base64Utils.fromb64(str); 
+    } 
+}
\ No newline at end of file

Deleted: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/config/ApplicationPolicy.java
===================================================================
--- projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/security/config/ApplicationPolicy.java	2009-07-21 21:59:08 UTC (rev 91524)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/config/ApplicationPolicy.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -1,362 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source
- * Copyright 2005, JBoss Inc., and individual contributors as indicated
- * by the @authors tag. See the copyright.txt in the distribution for a
- * full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jboss.security.config;
-
-import java.security.Principal;
-import java.util.HashMap;
-import java.util.Map;
-
-import org.jboss.security.auth.login.BaseAuthenticationInfo;
-import org.jboss.security.identity.RoleGroup;
-
-// $Id$
-
-/**
- * Application Policy Information Holder - Authentication - Authorization - Audit - Mapping
- * 
- * @author <a href="mailto:Anil.Saldhana at jboss.org">Anil Saldhana</a>
- * @since Jun 9, 2006
- * @version $Revision$
- */
-public class ApplicationPolicy
-{
-   private final String name;
-
-   private BaseAuthenticationInfo authenticationInfo;
-
-   private ACLInfo aclInfo;
-
-   private AuthorizationInfo authorizationInfo;
-
-   private AuditInfo auditInfo;
-
-   private final Map<String, MappingInfo> mappingInfos = new HashMap<String, MappingInfo>();
-
-   private IdentityTrustInfo identityTrustInfo;
-
-   // Base application policy (if any)
-   private String baseApplicationPolicyName;
-
-   // Parent PolicyConfig
-   private PolicyConfig policyConfig;
-
-   public ApplicationPolicy(String theName)
-   {
-      if (theName == null)
-         throw new IllegalArgumentException("name is null");
-      this.name = theName;
-   }
-
-   public ApplicationPolicy(String theName, BaseAuthenticationInfo info)
-   {
-      this(theName);
-      authenticationInfo = info;
-   }
-
-   public ApplicationPolicy(String theName, AuthorizationInfo info)
-   {
-      this(theName);
-      authorizationInfo = info;
-   }
-
-   public ApplicationPolicy(String theName, BaseAuthenticationInfo info, AuthorizationInfo info2)
-   {
-      this(theName);
-      authenticationInfo = info;
-      authorizationInfo = info2;
-   }
-
-   public ACLInfo getAclInfo()
-   {
-      ACLInfo info = null;
-      ApplicationPolicy basePolicy = this.getBaseApplicationPolicy();
-      if (basePolicy != null)
-         info = basePolicy.getAclInfo();
-      if (info != null && this.aclInfo == null)
-         return info;
-      else if (info != null)
-         return (ACLInfo) this.aclInfo.merge(info);
-      else
-         return aclInfo;
-   }
-
-   public void setAclInfo(ACLInfo aclInfo)
-   {
-      this.aclInfo = aclInfo;
-   }
-
-   public BaseAuthenticationInfo getAuthenticationInfo()
-   {
-      BaseAuthenticationInfo bai = null;
-      ApplicationPolicy ap = this.getBaseApplicationPolicy();
-      if (ap != null)
-         bai = ap.getAuthenticationInfo();
-      if (bai != null && authenticationInfo == null)
-         return bai;
-      else if (bai != null)
-         return (BaseAuthenticationInfo) authenticationInfo.merge(bai);
-      else
-         return authenticationInfo;
-   }
-
-   public void setAuthenticationInfo(BaseAuthenticationInfo authenticationInfo)
-   {
-      this.authenticationInfo = authenticationInfo;
-   }
-
-   public AuthorizationInfo getAuthorizationInfo()
-   {
-      AuthorizationInfo bai = null;
-      ApplicationPolicy ap = this.getBaseApplicationPolicy();
-      if (ap != null)
-         bai = ap.getAuthorizationInfo();
-      if (bai != null && authorizationInfo == null)
-         return bai;
-      else if (bai != null)
-         return (AuthorizationInfo) authorizationInfo.merge(bai);
-      else
-         return authorizationInfo;
-   }
-
-   public void setAuthorizationInfo(AuthorizationInfo authorizationInfo)
-   {
-      this.authorizationInfo = authorizationInfo;
-   }
-
-   /**
-    * <p>
-    * Gets the {@code MappingInfo} object that contains the entries that will be used to map roles.
-    * </p>
-    * 
-    * @return the {@code MappingInfo} that must be used when mapping roles.
-    * @deprecated use {@link ApplicationPolicy#getMappingInfo("role")} instead.
-    */
-   @Deprecated
-   public MappingInfo getRoleMappingInfo()
-   {
-      return this.getMappingInfo("role");
-   }
-
-   /**
-    * <p>
-    * Sets the {@code MappingInfo} object that must be used when mapping roles.
-    * </p>
-    * 
-    * @param roleMappingInfo the {@code MappingInfo} instance to be set.
-    * @deprecated use {@link ApplicationPolicy#setMappingInfo("role", MappingInfo)} instead.
-    */
-   @Deprecated
-   public void setRoleMappingInfo(MappingInfo roleMappingInfo)
-   {
-      this.setMappingInfo("role", roleMappingInfo);
-   }
-
-   /**
-    * <p>
-    * Gets the {@code MappingInfo} object that contains the entries that will be used to map principals.
-    * </p>
-    * 
-    * @return the {@code MappingInfo} that must be used when mapping principals.
-    * @deprecated use {@link ApplicationPolicy#getMappingInfo("principal")} instead.
-    */
-   @Deprecated
-   public MappingInfo getPrincipalMappingInfo()
-   {
-      return this.getMappingInfo("principal");
-   }
-
-   /**
-    * <p>
-    * Sets the {@code MappingInfo} object that must be used when mapping principals.
-    * </p>
-    * 
-    * @param roleMappingInfo the {@code MappingInfo} instance to be set.
-    * @deprecated use {@link ApplicationPolicy#setMappingInfo("principal", MappingInfo)} instead.
-    */
-   @Deprecated
-   public void setPrincipalMappingInfo(MappingInfo principalMappingInfo)
-   {
-      this.setMappingInfo("principal", principalMappingInfo);
-   }
-
-   /**
-    * <p>
-    * Gets the {@code MappingInfo} instance that can map objects of the specified class. 
-    * </p>
-    * 
-    * @param t the class of the objects that are to be mapped.
-    * @return the {@code MappingInfo} instance that must be used to map objects of the specified class.
-    * @deprecated use {@link ApplicationPolicy#getMappingInfo(String)} instead.
-    */
-   @Deprecated
-   public <T> MappingInfo getMappingInfo(Class<T> t)
-   {
-      if (t == RoleGroup.class)
-         return this.getRoleMappingInfo();
-      if (t == Principal.class)
-         return this.getPrincipalMappingInfo();
-      throw new IllegalStateException("No mapping information available for type:" + t);
-   }
-
-   /**
-    * <p>
-    * Gets the {@code MappingInfo} instance that can perform the mappings of the specified type.
-    * </p>
-    * 
-    * @param mappingType a {@code String} representing the type of the mappings that are to be performed. This
-    *            {@code String} must match the value of the {@code type} attribute of the {@code mapping-module} that
-    *            has been configured in the application policy. For example, consider the following mapping policy:
-    * 
-    * <pre>
-    * &lt;application-policy name=&quot;test&quot;&gt;
-    *    &lt;authentication&gt;
-    *    ...
-    *    &lt;/authentication&gt;
-    *    &lt;mapping&gt;
-    *       &lt;mapping-module code = &quot;org.jboss.test.mapping.MappingModule1&quot; type=&quot;role&quot;&gt;
-    *          &lt;module-option name = &quot;option1&quot;&gt;value1&lt;/module-option&gt;
-    *       &lt;/mapping-module&gt;
-    *       &lt;mapping-module code = &quot;org.jboss.test.mapping.MappingModule2&quot; type=&quot;principal&quot;&gt;
-    *          &lt;module-option name = &quot;option2&quot;&gt;value2&lt;/module-option&gt;
-    *       &lt;/mapping-module&gt;
-    *    &lt;/mapping&gt; while a
-    * &lt;/application-policy&gt;
-    * </pre>
-    * 
-    * Executing this method with {@code "role"} as parameter would return a {@code MappingInfo} that is capable of
-    * mapping roles using the {@code MappingModule1}. Likewise, executing this method with {@code "principal"} as
-    * parameter would return a {@code MappingInfo} that can map principals using the {@code MappingModule2}.
-    * @return the {@code MappingInfo} instance that can perform the mappings of the specified type, or {@code null} if
-    *         no suitable {@code MappingInfo} can be found.
-    */
-   public MappingInfo getMappingInfo(String mappingType)
-   {
-      mappingType = mappingType.toLowerCase();
-      MappingInfo bai = null;
-      ApplicationPolicy ap = this.getBaseApplicationPolicy();
-      if (ap != null)
-         bai = ap.getMappingInfo(mappingType);
-
-      MappingInfo mappings = this.mappingInfos.get(mappingType);
-      if (bai != null && mappings == null)
-         return bai;
-      else if (bai != null)
-         return (MappingInfo) mappings.merge(bai);
-      else
-         return mappings;
-   }
-
-   /**
-    * <p>
-    * Sets the {@code MappingInfo} that must be used to perform the mappings of the specified type.
-    * </p>
-    * 
-    * @param mappingType the type of mappings that can be performed by the {@code MappingInfo}.
-    * @param info a reference to the {@code MappingInfo} instance to be set.
-    */
-   public void setMappingInfo(String mappingType, MappingInfo info)
-   {
-      // if there is a registered info for the specified type, merge the modules.
-      if(this.mappingInfos.containsKey(mappingType))
-         this.mappingInfos.get(mappingType).add(info.getModuleEntries());
-      else
-         this.mappingInfos.put(mappingType, info);
-   }
-
-   public AuditInfo getAuditInfo()
-   {
-      AuditInfo bai = null;
-      ApplicationPolicy ap = this.getBaseApplicationPolicy();
-      if (ap != null)
-         bai = ap.getAuditInfo();
-
-      if (bai != null && auditInfo == null)
-         return bai;
-      else if (bai != null)
-         return (AuditInfo) auditInfo.merge(bai);
-      else
-         return auditInfo;
-   }
-
-   public void setAuditInfo(AuditInfo auditInfo)
-   {
-      this.auditInfo = auditInfo;
-   }
-
-   public IdentityTrustInfo getIdentityTrustInfo()
-   {
-      IdentityTrustInfo bai = null;
-      ApplicationPolicy ap = this.getBaseApplicationPolicy();
-      if (ap != null)
-         bai = ap.getIdentityTrustInfo();
-
-      if (bai != null && identityTrustInfo == null)
-         return bai;
-      else if (bai != null)
-         return (IdentityTrustInfo) identityTrustInfo.merge(bai);
-      else
-         return identityTrustInfo;
-   }
-
-   public void setIdentityTrustInfo(IdentityTrustInfo identityTrustInfo)
-   {
-      this.identityTrustInfo = identityTrustInfo;
-   }
-
-   public String getBaseApplicationPolicyName()
-   {
-      return baseApplicationPolicyName;
-   }
-
-   public void setBaseApplicationPolicyName(String baseApplicationPolicy)
-   {
-      this.baseApplicationPolicyName = baseApplicationPolicy;
-   }
-
-   public String getName()
-   {
-      return name;
-   }
-
-   public PolicyConfig getPolicyConfig()
-   {
-      return policyConfig;
-   }
-
-   public void setPolicyConfig(PolicyConfig policyConfig)
-   {
-      this.policyConfig = policyConfig;
-   }
-
-   private ApplicationPolicy getBaseApplicationPolicy()
-   {
-      ApplicationPolicy ap = null;
-      if (this.baseApplicationPolicyName != null)
-      {
-         ap = this.policyConfig.get(this.baseApplicationPolicyName);
-         // The base application policy may exist in a different location
-         if (ap == null)
-            ap = SecurityConfiguration.getApplicationPolicy(this.baseApplicationPolicyName);
-      }
-      return ap;
-   }
-}
\ No newline at end of file

Copied: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/config/ApplicationPolicy.java (from rev 92039, projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/security/config/ApplicationPolicy.java)
===================================================================
--- projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/config/ApplicationPolicy.java	                        (rev 0)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/config/ApplicationPolicy.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -0,0 +1,363 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005, JBoss Inc., and individual contributors as indicated
+ * by the @authors tag. See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.security.config;
+
+import java.security.Principal;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.jboss.security.auth.login.BaseAuthenticationInfo;
+import org.jboss.security.identity.RoleGroup;
+
+// $Id$
+
+/**
+ * Application Policy Information Holder - Authentication - Authorization - Audit - Mapping
+ * 
+ * @author <a href="mailto:Anil.Saldhana at jboss.org">Anil Saldhana</a>
+ * @since Jun 9, 2006
+ * @version $Revision$
+ */
+public class ApplicationPolicy
+{
+   private final String name;
+
+   private BaseAuthenticationInfo authenticationInfo;
+
+   private ACLInfo aclInfo;
+
+   private AuthorizationInfo authorizationInfo;
+
+   private AuditInfo auditInfo;
+
+   private final Map<String, MappingInfo> mappingInfos = new HashMap<String, MappingInfo>();
+
+   private IdentityTrustInfo identityTrustInfo;
+
+   // Base application policy (if any)
+   private String baseApplicationPolicyName;
+
+   // Parent PolicyConfig
+   private PolicyConfig policyConfig;
+
+   public ApplicationPolicy(String theName)
+   {
+      if (theName == null)
+         throw new IllegalArgumentException("name is null");
+      this.name = theName;
+   }
+
+   public ApplicationPolicy(String theName, BaseAuthenticationInfo info)
+   {
+      this(theName);
+      authenticationInfo = info;
+   }
+
+   public ApplicationPolicy(String theName, AuthorizationInfo info)
+   {
+      this(theName);
+      authorizationInfo = info;
+   }
+
+   public ApplicationPolicy(String theName, BaseAuthenticationInfo info, AuthorizationInfo info2)
+   {
+      this(theName);
+      authenticationInfo = info;
+      authorizationInfo = info2;
+   }
+
+   public ACLInfo getAclInfo()
+   {
+      ACLInfo info = null;
+      ApplicationPolicy basePolicy = this.getBaseApplicationPolicy();
+      if (basePolicy != null)
+         info = basePolicy.getAclInfo();
+      if (info != null && this.aclInfo == null)
+         return info;
+      else if (info != null)
+         return (ACLInfo) this.aclInfo.merge(info);
+      else
+         return aclInfo;
+   }
+
+   public void setAclInfo(ACLInfo aclInfo)
+   {
+      this.aclInfo = aclInfo;
+   }
+
+   public BaseAuthenticationInfo getAuthenticationInfo()
+   {
+      BaseAuthenticationInfo bai = null;
+      ApplicationPolicy ap = this.getBaseApplicationPolicy();
+      if (ap != null)
+         bai = ap.getAuthenticationInfo();
+      if (bai != null && authenticationInfo == null)
+         return bai;
+      else if (bai != null)
+         return (BaseAuthenticationInfo) authenticationInfo.merge(bai);
+      else
+         return authenticationInfo;
+   }
+
+   public void setAuthenticationInfo(BaseAuthenticationInfo authenticationInfo)
+   {
+      this.authenticationInfo = authenticationInfo;
+   }
+
+   public AuthorizationInfo getAuthorizationInfo()
+   {
+      AuthorizationInfo bai = null;
+      ApplicationPolicy ap = this.getBaseApplicationPolicy();
+      if (ap != null)
+         bai = ap.getAuthorizationInfo();
+      if (bai != null && authorizationInfo == null)
+         return bai;
+      else if (bai != null)
+         return (AuthorizationInfo) authorizationInfo.merge(bai);
+      else
+         return authorizationInfo;
+   }
+
+   public void setAuthorizationInfo(AuthorizationInfo authorizationInfo)
+   {
+      this.authorizationInfo = authorizationInfo;
+   }
+
+   /**
+    * <p>
+    * Gets the {@code MappingInfo} object that contains the entries that will be used to map roles.
+    * </p>
+    * 
+    * @return the {@code MappingInfo} that must be used when mapping roles.
+    * @deprecated use {@link ApplicationPolicy#getMappingInfo("role")} instead.
+    */
+   @Deprecated
+   public MappingInfo getRoleMappingInfo()
+   {
+      return this.getMappingInfo("role");
+   }
+
+   /**
+    * <p>
+    * Sets the {@code MappingInfo} object that must be used when mapping roles.
+    * </p>
+    * 
+    * @param roleMappingInfo the {@code MappingInfo} instance to be set.
+    * @deprecated use {@link ApplicationPolicy#setMappingInfo("role", MappingInfo)} instead.
+    */
+   @Deprecated
+   public void setRoleMappingInfo(MappingInfo roleMappingInfo)
+   {
+      this.setMappingInfo("role", roleMappingInfo);
+   }
+
+   /**
+    * <p>
+    * Gets the {@code MappingInfo} object that contains the entries that will be used to map principals.
+    * </p>
+    * 
+    * @return the {@code MappingInfo} that must be used when mapping principals.
+    * @deprecated use {@link ApplicationPolicy#getMappingInfo("principal")} instead.
+    */
+   @Deprecated
+   public MappingInfo getPrincipalMappingInfo()
+   {
+      return this.getMappingInfo("principal");
+   }
+
+   /**
+    * <p>
+    * Sets the {@code MappingInfo} object that must be used when mapping principals.
+    * </p>
+    * 
+    * @param roleMappingInfo the {@code MappingInfo} instance to be set.
+    * @deprecated use {@link ApplicationPolicy#setMappingInfo("principal", MappingInfo)} instead.
+    */
+   @Deprecated
+   public void setPrincipalMappingInfo(MappingInfo principalMappingInfo)
+   {
+      this.setMappingInfo("principal", principalMappingInfo);
+   }
+
+   /**
+    * <p>
+    * Gets the {@code MappingInfo} instance that can map objects of the specified class. 
+    * </p>
+    * 
+    * @param t the class of the objects that are to be mapped.
+    * @return the {@code MappingInfo} instance that must be used to map objects of the specified class.
+    * @deprecated use {@link ApplicationPolicy#getMappingInfo(String)} instead.
+    */
+   @Deprecated
+   public <T> MappingInfo getMappingInfo(Class<T> t)
+   {
+      if (t == RoleGroup.class)
+         return this.getRoleMappingInfo();
+      if (t == Principal.class)
+         return this.getPrincipalMappingInfo();
+      throw new IllegalStateException("No mapping information available for type:" + t);
+   }
+
+   /**
+    * <p>
+    * Gets the {@code MappingInfo} instance that can perform the mappings of the specified type.
+    * </p>
+    * 
+    * @param mappingType a {@code String} representing the type of the mappings that are to be performed. This
+    *            {@code String} must match the value of the {@code type} attribute of the {@code mapping-module} that
+    *            has been configured in the application policy. For example, consider the following mapping policy:
+    * 
+    * <pre>
+    * &lt;application-policy name=&quot;test&quot;&gt;
+    *    &lt;authentication&gt;
+    *    ...
+    *    &lt;/authentication&gt;
+    *    &lt;mapping&gt;
+    *       &lt;mapping-module code = &quot;org.jboss.test.mapping.MappingModule1&quot; type=&quot;role&quot;&gt;
+    *          &lt;module-option name = &quot;option1&quot;&gt;value1&lt;/module-option&gt;
+    *       &lt;/mapping-module&gt;
+    *       &lt;mapping-module code = &quot;org.jboss.test.mapping.MappingModule2&quot; type=&quot;principal&quot;&gt;
+    *          &lt;module-option name = &quot;option2&quot;&gt;value2&lt;/module-option&gt;
+    *       &lt;/mapping-module&gt;
+    *    &lt;/mapping&gt; while a
+    * &lt;/application-policy&gt;
+    * </pre>
+    * 
+    * Executing this method with {@code "role"} as parameter would return a {@code MappingInfo} that is capable of
+    * mapping roles using the {@code MappingModule1}. Likewise, executing this method with {@code "principal"} as
+    * parameter would return a {@code MappingInfo} that can map principals using the {@code MappingModule2}.
+    * @return the {@code MappingInfo} instance that can perform the mappings of the specified type, or {@code null} if
+    *         no suitable {@code MappingInfo} can be found.
+    */
+   public MappingInfo getMappingInfo(String mappingType)
+   {
+      mappingType = mappingType.toLowerCase();
+      MappingInfo bai = null;
+      ApplicationPolicy ap = this.getBaseApplicationPolicy();
+      if (ap != null)
+         bai = ap.getMappingInfo(mappingType);
+
+      MappingInfo mappings = this.mappingInfos.get(mappingType);
+      if (bai != null && mappings == null)
+         return bai;
+      else if (bai != null)
+         return (MappingInfo) mappings.merge(bai);
+      else
+         return mappings;
+   }
+
+   /**
+    * <p>
+    * Sets the {@code MappingInfo} that must be used to perform the mappings of the specified type.
+    * </p>
+    * 
+    * @param mappingType the type of mappings that can be performed by the {@code MappingInfo}.
+    * @param info a reference to the {@code MappingInfo} instance to be set.
+    */
+   public void setMappingInfo(String mappingType, MappingInfo info)
+   {
+      mappingType = mappingType.toLowerCase();
+      // if there is a registered info for the specified type, merge the modules.
+      if(this.mappingInfos.containsKey(mappingType))
+         this.mappingInfos.get(mappingType).add(info.getModuleEntries());
+      else
+         this.mappingInfos.put(mappingType, info);
+   }
+
+   public AuditInfo getAuditInfo()
+   {
+      AuditInfo bai = null;
+      ApplicationPolicy ap = this.getBaseApplicationPolicy();
+      if (ap != null)
+         bai = ap.getAuditInfo();
+
+      if (bai != null && auditInfo == null)
+         return bai;
+      else if (bai != null)
+         return (AuditInfo) auditInfo.merge(bai);
+      else
+         return auditInfo;
+   }
+
+   public void setAuditInfo(AuditInfo auditInfo)
+   {
+      this.auditInfo = auditInfo;
+   }
+
+   public IdentityTrustInfo getIdentityTrustInfo()
+   {
+      IdentityTrustInfo bai = null;
+      ApplicationPolicy ap = this.getBaseApplicationPolicy();
+      if (ap != null)
+         bai = ap.getIdentityTrustInfo();
+
+      if (bai != null && identityTrustInfo == null)
+         return bai;
+      else if (bai != null)
+         return (IdentityTrustInfo) identityTrustInfo.merge(bai);
+      else
+         return identityTrustInfo;
+   }
+
+   public void setIdentityTrustInfo(IdentityTrustInfo identityTrustInfo)
+   {
+      this.identityTrustInfo = identityTrustInfo;
+   }
+
+   public String getBaseApplicationPolicyName()
+   {
+      return baseApplicationPolicyName;
+   }
+
+   public void setBaseApplicationPolicyName(String baseApplicationPolicy)
+   {
+      this.baseApplicationPolicyName = baseApplicationPolicy;
+   }
+
+   public String getName()
+   {
+      return name;
+   }
+
+   public PolicyConfig getPolicyConfig()
+   {
+      return policyConfig;
+   }
+
+   public void setPolicyConfig(PolicyConfig policyConfig)
+   {
+      this.policyConfig = policyConfig;
+   }
+
+   private ApplicationPolicy getBaseApplicationPolicy()
+   {
+      ApplicationPolicy ap = null;
+      if (this.baseApplicationPolicyName != null)
+      {
+         ap = this.policyConfig.get(this.baseApplicationPolicyName);
+         // The base application policy may exist in a different location
+         if (ap == null)
+            ap = SecurityConfiguration.getApplicationPolicy(this.baseApplicationPolicyName);
+      }
+      return ap;
+   }
+}
\ No newline at end of file

Copied: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/config/AttributeMappingInfo.java (from rev 92039, projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/security/config/AttributeMappingInfo.java)
===================================================================
--- projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/config/AttributeMappingInfo.java	                        (rev 0)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/config/AttributeMappingInfo.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -0,0 +1,34 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors. 
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.security.config;
+
+/**
+ * Mapping Info for Attributes
+ * @author Anil.Saldhana at redhat.com
+ */
+public class AttributeMappingInfo extends MappingInfo
+{ 
+   public AttributeMappingInfo(String name)
+   {
+      super(name); 
+   } 
+}

Deleted: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/identitytrust/JBossIdentityTrustContext.java
===================================================================
--- projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/security/identitytrust/JBossIdentityTrustContext.java	2009-07-21 21:59:08 UTC (rev 91524)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/identitytrust/JBossIdentityTrustContext.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -1,246 +0,0 @@
-/*
-  * JBoss, Home of Professional Open Source
-  * Copyright 2007, JBoss Inc., and individual contributors as indicated
-  * by the @authors tag. See the copyright.txt in the distribution for a
-  * full listing of individual contributors.
-  *
-  * This is free software; you can redistribute it and/or modify it
-  * under the terms of the GNU Lesser General Public License as
-  * published by the Free Software Foundation; either version 2.1 of
-  * the License, or (at your option) any later version.
-  *
-  * This software is distributed in the hope that it will be useful,
-  * but WITHOUT ANY WARRANTY; without even the implied warranty of
-  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-  * Lesser General Public License for more details.
-  *
-  * You should have received a copy of the GNU Lesser General Public
-  * License along with this software; if not, write to the Free
-  * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-  * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
-  */
-package org.jboss.security.identitytrust;
-
-import java.security.AccessController;
-import java.security.PrivilegedActionException;
-import java.security.PrivilegedExceptionAction;
-import java.util.Map;
-
-import org.jboss.logging.Logger;
-import org.jboss.security.SecurityContext;
-import org.jboss.security.config.ApplicationPolicy;
-import org.jboss.security.config.ControlFlag;
-import org.jboss.security.config.IdentityTrustInfo;
-import org.jboss.security.config.SecurityConfiguration;
-import org.jboss.security.identitytrust.IdentityTrustManager.TrustDecision;
-import org.jboss.security.identitytrust.config.IdentityTrustModuleEntry;
- 
-/**
- *  Implementation of the Identity Trust Context
- *  @author Anil.Saldhana at redhat.com
- *  @since  Aug 2, 2007 
- *  @version $Revision$
- */
-public class JBossIdentityTrustContext extends IdentityTrustContext
-{ 
-   protected Logger log = Logger.getLogger(JBossIdentityTrustContext.class); 
-   
-   public JBossIdentityTrustContext(String secDomain, SecurityContext sc)
-   {
-      this.securityDomain = secDomain;
-      this.securityContext = sc;
-   }
-   
-   @Override
-   public TrustDecision isTrusted() throws IdentityTrustException
-   { 
-      TrustDecision decision = NOTAPPLICABLE;
-         
-      try
-      {
-         initializeModules();
-      }
-      catch (Exception e)
-      {
-         throw new IdentityTrustException(e);
-      }
-      //Do a PrivilegedAction
-      try
-      {
-         decision = AccessController.doPrivileged(new PrivilegedExceptionAction<TrustDecision>() 
-         {
-            public TrustDecision run() throws IdentityTrustException 
-            {
-               TrustDecision result = invokeTrusted();
-               if(result == PERMIT)
-                  invokeCommit();
-               if(result == DENY || result == NOTAPPLICABLE)
-               {
-                  invokeAbort();  
-               } 
-               return result;
-            }
-         });
-      }
-      catch (PrivilegedActionException e)
-      {
-         Exception exc = e.getException();
-         log.trace("Error in isAuthorize:", exc); 
-         invokeAbort();
-         throw ((IdentityTrustException)exc);
-      }
-      return decision; 
-   } 
-   
-   private void initializeModules() throws Exception
-   {
-      //Clear the modules
-      modules.clear();
-      //Get the Configuration
-      ApplicationPolicy aPolicy = SecurityConfiguration.getApplicationPolicy( securityDomain);
-      if(aPolicy == null)
-         throw new IllegalStateException("ApplicationPolicy not found for "+ securityDomain);
-      
-      IdentityTrustInfo iti = aPolicy.getIdentityTrustInfo();
-      if(iti == null)
-         return;
-      IdentityTrustModuleEntry[] itmearr = iti.getIdentityTrustModuleEntry();
-      for(IdentityTrustModuleEntry itme: itmearr)
-      { 
-         ControlFlag cf = itme.getControlFlag();
-         if(cf == null)
-            cf = ControlFlag.REQUIRED;
-         
-         this.controlFlags.add(cf); 
-         modules.add(instantiateModule(itme.getName(), itme.getOptions())); 
-      }
-   }
-   
-   @SuppressWarnings("unchecked")
-   private IdentityTrustModule instantiateModule(String name, Map map) throws Exception
-   {
-      IdentityTrustModule im = null;
-      ClassLoader tcl = SecurityActions.getContextClassLoader();
-      try
-      {
-         Class clazz = tcl.loadClass(name);
-         im = (IdentityTrustModule)clazz.newInstance();
-      }
-      catch ( Exception e)
-      {
-         log.debug("Error instantiating IdentityTrustModule:",e);
-      } 
-      if(im == null)
-         throw new IllegalStateException("IdentityTrustModule has not " +
-               "been instantiated"); 
-      im.initialize(this.securityContext, this.callbackHandler, this.sharedState,map); 
-      return im;
-   }
-   
-   private TrustDecision invokeTrusted() 
-   throws IdentityTrustException
-   { 
-      //Control Flag behavior
-      boolean encounteredRequiredDeny = false; 
-      boolean encounteredRequiredNotApplicable = false;
-      boolean encounteredOptionalError = false; 
-      IdentityTrustException moduleException = null;
-      TrustDecision overallDecision = TrustDecision.NotApplicable;
-      boolean encounteredRequiredPermit = false;
-      
-      TrustDecision decision = NOTAPPLICABLE;
-      int length = modules.size();
-     
-      if(length == 0)
-         return decision;
-      
-      for(int i = 0; i < length; i++)
-      {
-         IdentityTrustModule module = (IdentityTrustModule)modules.get(i);
-         ControlFlag flag = (ControlFlag)this.controlFlags.get(i); 
-         try
-         {
-            decision = module.isTrusted();
-         }
-         catch(Exception ae)
-         {
-            decision = NOTAPPLICABLE;
-            if(moduleException == null)
-               moduleException = new IdentityTrustException(ae);
-         }
-         
-         if(decision == PERMIT)
-         { 
-            overallDecision =  PERMIT;
-            if(flag == ControlFlag.REQUIRED)
-               encounteredRequiredPermit = true;
-            //SUFFICIENT case
-            if(flag == ControlFlag.SUFFICIENT && encounteredRequiredDeny == false)
-               return PERMIT;
-            continue; //Continue with the other modules
-         }
-         
-         if(decision == NOTAPPLICABLE && flag == ControlFlag.REQUIRED)
-         {  
-            encounteredRequiredNotApplicable = true;
-            continue; //Continue with the other modules
-         }
-         //Go through the failure cases 
-         //REQUISITE case
-         if(flag == ControlFlag.REQUISITE)
-         {
-            log.trace("REQUISITE failed for " + module); 
-            if(moduleException == null)
-               moduleException = new IdentityTrustException("Identity Trust Validation failed");
-            else
-               throw moduleException;
-         }
-         //REQUIRED Case
-         if(flag == ControlFlag.REQUIRED)
-         {
-            log.trace("REQUIRED failed for " + module);
-            encounteredRequiredDeny = true;
-         }
-         if(flag == ControlFlag.OPTIONAL)
-            encounteredOptionalError = true; 
-      }
-      
-      //All the identity trust modules have been visited.
-      if(encounteredRequiredDeny)
-         return DENY;
-      if(overallDecision == DENY && encounteredOptionalError)
-         return DENY;
-      if(overallDecision == DENY)
-         return DENY;
-      
-      if(encounteredRequiredNotApplicable && !encounteredRequiredPermit)
-         return NOTAPPLICABLE;
-      return PERMIT;
-   }
-   
-   private void invokeCommit()
-   throws IdentityTrustException
-   {
-      int length = modules.size();
-      for(int i = 0; i < length; i++)
-      {
-         IdentityTrustModule module = (IdentityTrustModule)modules.get(i); 
-         boolean bool = module.commit();
-         if(!bool)
-            throw new IdentityTrustException("commit on modules failed");
-      } 
-   }
-   
-   private void invokeAbort()
-   throws IdentityTrustException
-   {
-      int length = modules.size();
-      for(int i = 0; i < length; i++)
-      {
-         IdentityTrustModule module = (IdentityTrustModule)modules.get(i); 
-         boolean bool = module.abort(); 
-         if(!bool)
-            throw new IdentityTrustException("abort on modules failed");
-      } 
-   }
-}

Copied: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/identitytrust/JBossIdentityTrustContext.java (from rev 93325, projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/security/identitytrust/JBossIdentityTrustContext.java)
===================================================================
--- projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/identitytrust/JBossIdentityTrustContext.java	                        (rev 0)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/identitytrust/JBossIdentityTrustContext.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -0,0 +1,251 @@
+/*
+  * JBoss, Home of Professional Open Source
+  * Copyright 2007, JBoss Inc., and individual contributors as indicated
+  * by the @authors tag. See the copyright.txt in the distribution for a
+  * full listing of individual contributors.
+  *
+  * This is free software; you can redistribute it and/or modify it
+  * under the terms of the GNU Lesser General Public License as
+  * published by the Free Software Foundation; either version 2.1 of
+  * the License, or (at your option) any later version.
+  *
+  * This software is distributed in the hope that it will be useful,
+  * but WITHOUT ANY WARRANTY; without even the implied warranty of
+  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+  * Lesser General Public License for more details.
+  *
+  * You should have received a copy of the GNU Lesser General Public
+  * License along with this software; if not, write to the Free
+  * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+  * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+  */
+package org.jboss.security.identitytrust;
+
+import java.security.AccessController;
+import java.security.PrivilegedActionException;
+import java.security.PrivilegedExceptionAction;
+import java.util.Map;
+
+import org.jboss.logging.Logger;
+import org.jboss.security.SecurityContext;
+import org.jboss.security.config.ApplicationPolicy;
+import org.jboss.security.config.ControlFlag;
+import org.jboss.security.config.IdentityTrustInfo;
+import org.jboss.security.config.SecurityConfiguration;
+import org.jboss.security.identitytrust.IdentityTrustManager.TrustDecision;
+import org.jboss.security.identitytrust.config.IdentityTrustModuleEntry;
+ 
+/**
+ *  Implementation of the Identity Trust Context
+ *  @author Anil.Saldhana at redhat.com
+ *  @since  Aug 2, 2007 
+ *  @version $Revision$
+ */
+public class JBossIdentityTrustContext extends IdentityTrustContext
+{ 
+   protected Logger log = Logger.getLogger(JBossIdentityTrustContext.class); 
+   protected boolean trace = log.isTraceEnabled();
+   
+   public JBossIdentityTrustContext(String secDomain, SecurityContext sc)
+   {
+      this.securityDomain = secDomain;
+      this.securityContext = sc;
+   }
+   
+   @Override
+   public TrustDecision isTrusted() throws IdentityTrustException
+   { 
+      TrustDecision decision = NOTAPPLICABLE;
+         
+      try
+      {
+         initializeModules();
+      }
+      catch (Exception e)
+      {
+         throw new IdentityTrustException(e);
+      }
+      //Do a PrivilegedAction
+      try
+      {
+         decision = AccessController.doPrivileged(new PrivilegedExceptionAction<TrustDecision>() 
+         {
+            public TrustDecision run() throws IdentityTrustException 
+            {
+               TrustDecision result = invokeTrusted();
+               if(result == PERMIT)
+                  invokeCommit();
+               if(result == DENY || result == NOTAPPLICABLE)
+               {
+                  invokeAbort();  
+               } 
+               return result;
+            }
+         });
+      }
+      catch (PrivilegedActionException e)
+      {
+         Exception exc = e.getException();
+         if(trace)
+            log.trace("Error in isAuthorize:", exc); 
+         invokeAbort();
+         throw ((IdentityTrustException)exc);
+      }
+      return decision; 
+   } 
+   
+   private void initializeModules() throws Exception
+   {
+      //Clear the modules
+      modules.clear();
+      //Get the Configuration
+      ApplicationPolicy aPolicy = SecurityConfiguration.getApplicationPolicy( securityDomain);
+      if(aPolicy == null)
+         throw new IllegalStateException("ApplicationPolicy not found for "+ securityDomain);
+      
+      IdentityTrustInfo iti = aPolicy.getIdentityTrustInfo();
+      if(iti == null)
+         return;
+      IdentityTrustModuleEntry[] itmearr = iti.getIdentityTrustModuleEntry();
+      for(IdentityTrustModuleEntry itme: itmearr)
+      { 
+         ControlFlag cf = itme.getControlFlag();
+         if(cf == null)
+            cf = ControlFlag.REQUIRED;
+         
+         this.controlFlags.add(cf); 
+         modules.add(instantiateModule(itme.getName(), itme.getOptions())); 
+      }
+   }
+   
+   @SuppressWarnings("unchecked")
+   private IdentityTrustModule instantiateModule(String name, Map map) throws Exception
+   {
+      IdentityTrustModule im = null;
+      ClassLoader tcl = SecurityActions.getContextClassLoader();
+      try
+      {
+         Class clazz = tcl.loadClass(name);
+         im = (IdentityTrustModule)clazz.newInstance();
+      }
+      catch ( Exception e)
+      {
+         if(trace)
+            log.debug("Error instantiating IdentityTrustModule:",e);
+      } 
+      if(im == null)
+         throw new IllegalStateException("IdentityTrustModule has not " +
+               "been instantiated"); 
+      im.initialize(this.securityContext, this.callbackHandler, this.sharedState,map); 
+      return im;
+   }
+   
+   private TrustDecision invokeTrusted() 
+   throws IdentityTrustException
+   { 
+      //Control Flag behavior
+      boolean encounteredRequiredDeny = false; 
+      boolean encounteredRequiredNotApplicable = false;
+      boolean encounteredOptionalError = false; 
+      IdentityTrustException moduleException = null;
+      TrustDecision overallDecision = TrustDecision.NotApplicable;
+      boolean encounteredRequiredPermit = false;
+      
+      TrustDecision decision = NOTAPPLICABLE;
+      int length = modules.size();
+     
+      if(length == 0)
+         return decision;
+      
+      for(int i = 0; i < length; i++)
+      {
+         IdentityTrustModule module = (IdentityTrustModule)modules.get(i);
+         ControlFlag flag = (ControlFlag)this.controlFlags.get(i); 
+         try
+         {
+            decision = module.isTrusted();
+         }
+         catch(Exception ae)
+         {
+            decision = NOTAPPLICABLE;
+            if(moduleException == null)
+               moduleException = new IdentityTrustException(ae);
+         }
+         
+         if(decision == PERMIT)
+         { 
+            overallDecision =  PERMIT;
+            if(flag == ControlFlag.REQUIRED)
+               encounteredRequiredPermit = true;
+            //SUFFICIENT case
+            if(flag == ControlFlag.SUFFICIENT && encounteredRequiredDeny == false)
+               return PERMIT;
+            continue; //Continue with the other modules
+         }
+         
+         if(decision == NOTAPPLICABLE && flag == ControlFlag.REQUIRED)
+         {  
+            encounteredRequiredNotApplicable = true;
+            continue; //Continue with the other modules
+         }
+         //Go through the failure cases 
+         //REQUISITE case
+         if(flag == ControlFlag.REQUISITE)
+         {
+            if(trace)
+               log.trace("REQUISITE failed for " + module); 
+            if(moduleException == null)
+               moduleException = new IdentityTrustException("Identity Trust Validation failed");
+            else
+               throw moduleException;
+         }
+         //REQUIRED Case
+         if(flag == ControlFlag.REQUIRED)
+         {
+            if(trace)
+               log.trace("REQUIRED failed for " + module);
+            encounteredRequiredDeny = true;
+         }
+         if(flag == ControlFlag.OPTIONAL)
+            encounteredOptionalError = true; 
+      }
+      
+      //All the identity trust modules have been visited.
+      if(encounteredRequiredDeny)
+         return DENY;
+      if(overallDecision == DENY && encounteredOptionalError)
+         return DENY;
+      if(overallDecision == DENY)
+         return DENY;
+      
+      if(encounteredRequiredNotApplicable && !encounteredRequiredPermit)
+         return NOTAPPLICABLE;
+      return PERMIT;
+   }
+   
+   private void invokeCommit()
+   throws IdentityTrustException
+   {
+      int length = modules.size();
+      for(int i = 0; i < length; i++)
+      {
+         IdentityTrustModule module = (IdentityTrustModule)modules.get(i); 
+         boolean bool = module.commit();
+         if(!bool)
+            throw new IdentityTrustException("commit on modules failed");
+      } 
+   }
+   
+   private void invokeAbort()
+   throws IdentityTrustException
+   {
+      int length = modules.size();
+      for(int i = 0; i < length; i++)
+      {
+         IdentityTrustModule module = (IdentityTrustModule)modules.get(i); 
+         boolean bool = module.abort(); 
+         if(!bool)
+            throw new IdentityTrustException("abort on modules failed");
+      } 
+   }
+}
\ No newline at end of file

Deleted: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/jacc/ContextPolicy.java
===================================================================
--- projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/security/jacc/ContextPolicy.java	2009-07-21 21:59:08 UTC (rev 91524)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/jacc/ContextPolicy.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -1,331 +0,0 @@
-/*
-* JBoss, Home of Professional Open Source
-* Copyright 2005, JBoss Inc., and individual contributors as indicated
-* by the @authors tag. See the copyright.txt in the distribution for a
-* full listing of individual contributors.
-*
-* This is free software; you can redistribute it and/or modify it
-* under the terms of the GNU Lesser General Public License as
-* published by the Free Software Foundation; either version 2.1 of
-* the License, or (at your option) any later version.
-*
-* This software is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-* Lesser General Public License for more details.
-*
-* You should have received a copy of the GNU Lesser General Public
-* License along with this software; if not, write to the Free
-* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
-*/
-package org.jboss.security.jacc;
-
-import java.security.Permission;
-import java.security.PermissionCollection;
-import java.security.Permissions;
-import java.security.Principal;
-import java.security.ProtectionDomain;
-import java.security.acl.Group;
-import java.util.ArrayList;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.Iterator;
-
-import javax.security.jacc.PolicyContextException;
-
-import org.jboss.logging.Logger;
-
-/** The permissions for a JACC context id. This implementation is based on
- * the 3.2.x model of associating the declarative roles with the Subject of
- * the authenticated caller. This allows the 3.2.x login modules to be used
- * as the source of the authentication and authorization information.
- * 
- * @author Scott.Stark at jboss.org
- * @author Anil.Saldhana at jboss.org
- * @version $Revison:$
- */
-public class ContextPolicy
-{
-   private static Logger log = Logger.getLogger(ContextPolicy.class);
-   private String contextID;
-   private Permissions excludedPermissions = new Permissions();
-   private Permissions uncheckedPermissions = new Permissions();
-   /** HashMap<String, Permissions> role name to permissions mapping */
-   private HashMap<String, Permissions> rolePermissions = new HashMap<String, Permissions>();
-   /** Flag indicating if our category is at trace level for logging */
-   private boolean trace;
-
-   ContextPolicy(String contextID)
-   {
-      this.contextID = contextID;
-      this.trace = log.isTraceEnabled();
-   }
-
-   Permissions getPermissions()
-   {
-      Permissions perms = new Permissions();
-      Enumeration<Permission> eter = uncheckedPermissions.elements();
-      while( eter.hasMoreElements() )
-      {
-         Permission p = (Permission) eter.nextElement();
-         perms.add(p);
-      }
-      Iterator<Permissions> iter = rolePermissions.values().iterator();
-      while( iter.hasNext() )
-      {
-         Permissions rp = (Permissions) iter.next();
-         eter = rp.elements();
-         while( eter.hasMoreElements() )
-         {
-            Permission p = (Permission) eter.nextElement();
-            perms.add(p);
-         }
-      }
-      return perms;
-   }
-
-   boolean implies(ProtectionDomain domain, Permission permission)
-   {
-      boolean implied = false;
-      // First check the excluded permissions
-      if( excludedPermissions.implies(permission) )
-      {
-         if( trace )
-            log.trace("Denied: Matched excluded set, permission="+permission);
-         return false;
-      }
-
-      // Next see if this matches an unchecked permission
-      if( uncheckedPermissions.implies(permission) )
-      {
-         if( trace )
-            log.trace("Allowed: Matched unchecked set, permission="+permission);
-         return true;         
-      }
-
-      // Check principal to role permissions
-      Principal[] principals = domain.getPrincipals();
-      int length = principals != null ? principals.length : 0;
-      ArrayList<String> principalNames = new ArrayList<String>();
-      for(int n = 0; n < length; n ++)
-      {
-         Principal p = principals[n];
-         if( p instanceof Group )
-         {
-            Group g = (Group) p;
-            Enumeration<? extends Principal> iter = g.members();
-            while( iter.hasMoreElements() )
-            {
-               p = (Principal) iter.nextElement();
-               String name = p.getName();
-               principalNames.add(name);
-            }
-         }
-         else
-         {
-            String name = p.getName();
-            principalNames.add(name);
-         }
-      }
-      if( principalNames.size() > 0 )
-      { 
-         log.trace("ProtectionDomain principals="+principalNames);
-         for(int n = 0; implied == false && n < principalNames.size(); n ++)
-         {
-            String name = (String) principalNames.get(n);
-            Permissions perms = (Permissions) rolePermissions.get(name);
-            if( trace )
-               log.trace("Checking role="+name+" perms="+perms);
-            if( perms == null )
-               continue;
-            implied = perms.implies(permission);
-            if( trace )
-               log.trace((implied ? "Allowed: " : "Denied: ")+" permission="+permission);
-         }
-      }
-      else
-      {
-         if( trace )
-            log.trace("No principals found in domain: "+domain);
-      }
-
-      return implied;
-   }
-
-   void clear()
-   {
-      excludedPermissions = new Permissions();
-      uncheckedPermissions = new Permissions();
-      rolePermissions.clear();
-   }
-
-   void addToExcludedPolicy(Permission permission)
-      throws PolicyContextException
-   {
-      excludedPermissions.add(permission);
-   }
-   
-   void addToExcludedPolicy(PermissionCollection permissions)
-      throws PolicyContextException
-   {
-      Enumeration<Permission> iter = permissions.elements();
-      while( iter.hasMoreElements() )
-      {
-         Permission p = (Permission) iter.nextElement();
-         excludedPermissions.add(p);
-      }
-   }
-
-   void addToRole(String roleName, Permission permission)
-      throws PolicyContextException
-   {
-      Permissions perms = (Permissions) rolePermissions.get(roleName);
-      if( perms == null )
-      {
-         perms = new Permissions();
-         rolePermissions.put(roleName, perms);
-      }
-      perms.add(permission);
-   }
-
-   void addToRole(String roleName, PermissionCollection permissions)
-      throws PolicyContextException
-   {
-      Permissions perms = (Permissions) rolePermissions.get(roleName);
-      if( perms == null )
-      {
-         perms = new Permissions();
-         rolePermissions.put(roleName, perms);
-      }
-      Enumeration<Permission> iter = permissions.elements();
-      while( iter.hasMoreElements() )
-      {
-         Permission p = (Permission) iter.nextElement();
-         perms.add(p);
-      }
-   }
-
-   void addToUncheckedPolicy(Permission permission)
-      throws PolicyContextException
-   {
-      uncheckedPermissions.add(permission);
-   }
-
-   void addToUncheckedPolicy(PermissionCollection permissions)
-      throws PolicyContextException
-   {
-      Enumeration<Permission> iter = permissions.elements();
-      while( iter.hasMoreElements() )
-      {
-         Permission p = (Permission) iter.nextElement();
-         uncheckedPermissions.add(p);
-      }
-   }
-
-   void commit()
-      throws PolicyContextException
-   {
-   }
-
-   void delete()
-      throws PolicyContextException
-   {
-      clear();
-   }
-
-   String getContextID()
-      throws PolicyContextException
-   {
-      return contextID;
-   }
-
-   void linkConfiguration(ContextPolicy link)
-      throws PolicyContextException
-   {
-   }
-
-   void removeExcludedPolicy()
-      throws PolicyContextException
-   {
-      excludedPermissions = new Permissions();
-   }
-
-   void removeRole(String roleName)
-      throws PolicyContextException
-   {
-      rolePermissions.remove(roleName);
-   }
-
-   void removeUncheckedPolicy()
-      throws PolicyContextException
-   {
-      uncheckedPermissions = new Permissions();
-   }
-   
-   Permissions getPermissionsForRole(String role)
-   { 
-      return (Permissions) this.rolePermissions.get(role);
-   }
-
-   public String toString()
-   {
-      StringBuffer tmp = new StringBuffer("<ContextPolicy contextID='");
-      tmp.append(contextID);
-      tmp.append("'>\n");
-      tmp.append("\t<ExcludedPermissions>\n");
-      Enumeration<Permission> iter = excludedPermissions.elements();
-      while( iter.hasMoreElements() )
-      {
-         Permission p = (Permission) iter.nextElement();
-         tmp.append("<Permission type='");
-         tmp.append(p.getClass());
-         tmp.append("' name='");
-         tmp.append(p.getName());
-         tmp.append("' actions='");
-         tmp.append(p.getActions());
-         tmp.append("' />\n");
-      }
-      tmp.append("\t</ExcludedPermissions>\n");
-
-      tmp.append("\t<UncheckedPermissions>\n");
-      iter = uncheckedPermissions.elements();
-      while( iter.hasMoreElements() )
-      {
-         Permission p = (Permission) iter.nextElement();
-         tmp.append("<Permission type='");
-         tmp.append(p.getClass());
-         tmp.append(" name='");
-         tmp.append(p.getName());
-         tmp.append("' actions='");
-         tmp.append(p.getActions());
-         tmp.append("' />\n");
-      }
-      tmp.append("\t</UncheckedPermissions>\n");
-
-      tmp.append("\t<RolePermssions>\n");
-      Iterator<String> roles = rolePermissions.keySet().iterator();
-      while( roles.hasNext() )
-      {
-         String role = (String) roles.next();
-         Permissions perms = (Permissions) rolePermissions.get(role);
-         iter = perms.elements();
-         tmp.append("\t\t<Role name='"+role+"'>\n");
-         while( iter.hasMoreElements() )
-         {
-            Permission p = (Permission) iter.nextElement();
-            tmp.append("<Permission type='");
-            tmp.append(p.getClass());
-            tmp.append(" name='");
-            tmp.append(p.getName());
-            tmp.append("' actions='");
-            tmp.append(p.getActions());
-            tmp.append("' />\n");
-         }
-         tmp.append("\t\t</Role>\n");
-      }
-      tmp.append("\t</RolePermssions>");
-      tmp.append("</ContextPolicy>\n");
-      return tmp.toString();
-   }
-}

Copied: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/jacc/ContextPolicy.java (from rev 93325, projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/security/jacc/ContextPolicy.java)
===================================================================
--- projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/jacc/ContextPolicy.java	                        (rev 0)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/jacc/ContextPolicy.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -0,0 +1,332 @@
+/*
+* JBoss, Home of Professional Open Source
+* Copyright 2005, JBoss Inc., and individual contributors as indicated
+* by the @authors tag. See the copyright.txt in the distribution for a
+* full listing of individual contributors.
+*
+* This is free software; you can redistribute it and/or modify it
+* under the terms of the GNU Lesser General Public License as
+* published by the Free Software Foundation; either version 2.1 of
+* the License, or (at your option) any later version.
+*
+* This software is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+* Lesser General Public License for more details.
+*
+* You should have received a copy of the GNU Lesser General Public
+* License along with this software; if not, write to the Free
+* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+*/
+package org.jboss.security.jacc;
+
+import java.security.Permission;
+import java.security.PermissionCollection;
+import java.security.Permissions;
+import java.security.Principal;
+import java.security.ProtectionDomain;
+import java.security.acl.Group;
+import java.util.ArrayList;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.Iterator;
+
+import javax.security.jacc.PolicyContextException;
+
+import org.jboss.logging.Logger;
+
+/** The permissions for a JACC context id. This implementation is based on
+ * the 3.2.x model of associating the declarative roles with the Subject of
+ * the authenticated caller. This allows the 3.2.x login modules to be used
+ * as the source of the authentication and authorization information.
+ * 
+ * @author Scott.Stark at jboss.org
+ * @author Anil.Saldhana at jboss.org
+ * @version $Revison:$
+ */
+public class ContextPolicy
+{
+   private static Logger log = Logger.getLogger(ContextPolicy.class);
+   private String contextID;
+   private Permissions excludedPermissions = new Permissions();
+   private Permissions uncheckedPermissions = new Permissions();
+   /** HashMap<String, Permissions> role name to permissions mapping */
+   private HashMap<String, Permissions> rolePermissions = new HashMap<String, Permissions>();
+   /** Flag indicating if our category is at trace level for logging */
+   private boolean trace;
+
+   ContextPolicy(String contextID)
+   {
+      this.contextID = contextID;
+      this.trace = log.isTraceEnabled();
+   }
+
+   Permissions getPermissions()
+   {
+      Permissions perms = new Permissions();
+      Enumeration<Permission> eter = uncheckedPermissions.elements();
+      while( eter.hasMoreElements() )
+      {
+         Permission p = (Permission) eter.nextElement();
+         perms.add(p);
+      }
+      Iterator<Permissions> iter = rolePermissions.values().iterator();
+      while( iter.hasNext() )
+      {
+         Permissions rp = (Permissions) iter.next();
+         eter = rp.elements();
+         while( eter.hasMoreElements() )
+         {
+            Permission p = (Permission) eter.nextElement();
+            perms.add(p);
+         }
+      }
+      return perms;
+   }
+
+   boolean implies(ProtectionDomain domain, Permission permission)
+   {
+      boolean implied = false;
+      // First check the excluded permissions
+      if( excludedPermissions.implies(permission) )
+      {
+         if( trace )
+            log.trace("Denied: Matched excluded set, permission="+permission);
+         return false;
+      }
+
+      // Next see if this matches an unchecked permission
+      if( uncheckedPermissions.implies(permission) )
+      {
+         if( trace )
+            log.trace("Allowed: Matched unchecked set, permission="+permission);
+         return true;         
+      }
+
+      // Check principal to role permissions
+      Principal[] principals = domain.getPrincipals();
+      int length = principals != null ? principals.length : 0;
+      ArrayList<String> principalNames = new ArrayList<String>();
+      for(int n = 0; n < length; n ++)
+      {
+         Principal p = principals[n];
+         if( p instanceof Group )
+         {
+            Group g = (Group) p;
+            Enumeration<? extends Principal> iter = g.members();
+            while( iter.hasMoreElements() )
+            {
+               p = (Principal) iter.nextElement();
+               String name = p.getName();
+               principalNames.add(name);
+            }
+         }
+         else
+         {
+            String name = p.getName();
+            principalNames.add(name);
+         }
+      }
+      if( principalNames.size() > 0 )
+      { 
+         if(trace)
+            log.trace("ProtectionDomain principals="+principalNames);
+         for(int n = 0; implied == false && n < principalNames.size(); n ++)
+         {
+            String name = (String) principalNames.get(n);
+            Permissions perms = (Permissions) rolePermissions.get(name);
+            if( trace )
+               log.trace("Checking role="+name+" perms="+perms);
+            if( perms == null )
+               continue;
+            implied = perms.implies(permission);
+            if( trace )
+               log.trace((implied ? "Allowed: " : "Denied: ")+" permission="+permission);
+         }
+      }
+      else
+      {
+         if( trace )
+            log.trace("No principals found in domain: "+domain);
+      }
+
+      return implied;
+   }
+
+   void clear()
+   {
+      excludedPermissions = new Permissions();
+      uncheckedPermissions = new Permissions();
+      rolePermissions.clear();
+   }
+
+   void addToExcludedPolicy(Permission permission)
+      throws PolicyContextException
+   {
+      excludedPermissions.add(permission);
+   }
+   
+   void addToExcludedPolicy(PermissionCollection permissions)
+      throws PolicyContextException
+   {
+      Enumeration<Permission> iter = permissions.elements();
+      while( iter.hasMoreElements() )
+      {
+         Permission p = (Permission) iter.nextElement();
+         excludedPermissions.add(p);
+      }
+   }
+
+   void addToRole(String roleName, Permission permission)
+      throws PolicyContextException
+   {
+      Permissions perms = (Permissions) rolePermissions.get(roleName);
+      if( perms == null )
+      {
+         perms = new Permissions();
+         rolePermissions.put(roleName, perms);
+      }
+      perms.add(permission);
+   }
+
+   void addToRole(String roleName, PermissionCollection permissions)
+      throws PolicyContextException
+   {
+      Permissions perms = (Permissions) rolePermissions.get(roleName);
+      if( perms == null )
+      {
+         perms = new Permissions();
+         rolePermissions.put(roleName, perms);
+      }
+      Enumeration<Permission> iter = permissions.elements();
+      while( iter.hasMoreElements() )
+      {
+         Permission p = (Permission) iter.nextElement();
+         perms.add(p);
+      }
+   }
+
+   void addToUncheckedPolicy(Permission permission)
+      throws PolicyContextException
+   {
+      uncheckedPermissions.add(permission);
+   }
+
+   void addToUncheckedPolicy(PermissionCollection permissions)
+      throws PolicyContextException
+   {
+      Enumeration<Permission> iter = permissions.elements();
+      while( iter.hasMoreElements() )
+      {
+         Permission p = (Permission) iter.nextElement();
+         uncheckedPermissions.add(p);
+      }
+   }
+
+   void commit()
+      throws PolicyContextException
+   {
+   }
+
+   void delete()
+      throws PolicyContextException
+   {
+      clear();
+   }
+
+   String getContextID()
+      throws PolicyContextException
+   {
+      return contextID;
+   }
+
+   void linkConfiguration(ContextPolicy link)
+      throws PolicyContextException
+   {
+   }
+
+   void removeExcludedPolicy()
+      throws PolicyContextException
+   {
+      excludedPermissions = new Permissions();
+   }
+
+   void removeRole(String roleName)
+      throws PolicyContextException
+   {
+      rolePermissions.remove(roleName);
+   }
+
+   void removeUncheckedPolicy()
+      throws PolicyContextException
+   {
+      uncheckedPermissions = new Permissions();
+   }
+   
+   Permissions getPermissionsForRole(String role)
+   { 
+      return (Permissions) this.rolePermissions.get(role);
+   }
+
+   public String toString()
+   {
+      StringBuffer tmp = new StringBuffer("<ContextPolicy contextID='");
+      tmp.append(contextID);
+      tmp.append("'>\n");
+      tmp.append("\t<ExcludedPermissions>\n");
+      Enumeration<Permission> iter = excludedPermissions.elements();
+      while( iter.hasMoreElements() )
+      {
+         Permission p = (Permission) iter.nextElement();
+         tmp.append("<Permission type='");
+         tmp.append(p.getClass());
+         tmp.append("' name='");
+         tmp.append(p.getName());
+         tmp.append("' actions='");
+         tmp.append(p.getActions());
+         tmp.append("' />\n");
+      }
+      tmp.append("\t</ExcludedPermissions>\n");
+
+      tmp.append("\t<UncheckedPermissions>\n");
+      iter = uncheckedPermissions.elements();
+      while( iter.hasMoreElements() )
+      {
+         Permission p = (Permission) iter.nextElement();
+         tmp.append("<Permission type='");
+         tmp.append(p.getClass());
+         tmp.append(" name='");
+         tmp.append(p.getName());
+         tmp.append("' actions='");
+         tmp.append(p.getActions());
+         tmp.append("' />\n");
+      }
+      tmp.append("\t</UncheckedPermissions>\n");
+
+      tmp.append("\t<RolePermssions>\n");
+      Iterator<String> roles = rolePermissions.keySet().iterator();
+      while( roles.hasNext() )
+      {
+         String role = (String) roles.next();
+         Permissions perms = (Permissions) rolePermissions.get(role);
+         iter = perms.elements();
+         tmp.append("\t\t<Role name='"+role+"'>\n");
+         while( iter.hasMoreElements() )
+         {
+            Permission p = (Permission) iter.nextElement();
+            tmp.append("<Permission type='");
+            tmp.append(p.getClass());
+            tmp.append(" name='");
+            tmp.append(p.getName());
+            tmp.append("' actions='");
+            tmp.append(p.getActions());
+            tmp.append("' />\n");
+         }
+         tmp.append("\t\t</Role>\n");
+      }
+      tmp.append("\t</RolePermssions>");
+      tmp.append("</ContextPolicy>\n");
+      return tmp.toString();
+   }
+}

Deleted: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/jacc/DelegatingPolicy.java
===================================================================
--- projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/security/jacc/DelegatingPolicy.java	2009-07-21 21:59:08 UTC (rev 91524)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/jacc/DelegatingPolicy.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -1,466 +0,0 @@
-/*
-* JBoss, Home of Professional Open Source
-* Copyright 2005, JBoss Inc., and individual contributors as indicated
-* by the @authors tag. See the copyright.txt in the distribution for a
-* full listing of individual contributors.
-*
-* This is free software; you can redistribute it and/or modify it
-* under the terms of the GNU Lesser General Public License as
-* published by the Free Software Foundation; either version 2.1 of
-* the License, or (at your option) any later version.
-*
-* This software is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-* Lesser General Public License for more details.
-*
-* You should have received a copy of the GNU Lesser General Public
-* License along with this software; if not, write to the Free
-* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
-*/
-package org.jboss.security.jacc;
-
-import java.security.CodeSource;
-import java.security.Permission;
-import java.security.PermissionCollection;
-import java.security.Permissions;
-import java.security.Policy;
-import java.security.ProtectionDomain;
-import java.util.Enumeration;
-import java.util.Iterator;
-import java.util.concurrent.ConcurrentHashMap;
-
-import javax.security.jacc.EJBMethodPermission;
-import javax.security.jacc.EJBRoleRefPermission;
-import javax.security.jacc.PolicyConfiguration;
-import javax.security.jacc.PolicyContext;
-import javax.security.jacc.PolicyContextException;
-import javax.security.jacc.WebResourcePermission;
-import javax.security.jacc.WebRoleRefPermission;
-import javax.security.jacc.WebUserDataPermission;
-
-import org.jboss.logging.Logger;
- 
-/**
- * A JAAC Policy provider implementation that delegates any non-JACC permissions
- * to the java.security.Policy either passed in to the ctor, or the pre existing
- * Policy.getPolicy value.
- * @author Scott.Stark at jboss.org
- * @version $Revision$
- */
-public class DelegatingPolicy extends Policy
-{
-   private static Logger log = Logger.getLogger(DelegatingPolicy.class);
-   private static DelegatingPolicy instance;
-
-   /**
-    * The system Policy we delegate non-JACC checks to
-    */
-   private Policy delegate;
-   /**
-    * Map<String, ContextPolicy> for the JACC context IDs that have been
-    * committed.
-    */
-   private ConcurrentHashMap<String,ContextPolicy> activePolicies = new ConcurrentHashMap<String,ContextPolicy>();
-   /**
-    * Map<String, ContextPolicy> for the JACC policies that are in the open
-    * state and should be excluded from the active permission set.
-    */ 
-   private ConcurrentHashMap<String,ContextPolicy> openPolicies = new ConcurrentHashMap<String,ContextPolicy>(); 
-   /**
-    * Flag indicating if our category is at trace level for logging
-    */
-   private boolean trace;
-   /**
-    * The Policy proxy returned via the PolicyProxy attribute
-    */
-   private PolicyProxy policyProxy = new PolicyProxy(this);
-
-   /**
-    The types of permissions which should be treated as JACC permission types
-    in terms of whether this policy should validate the permission.
-    */
-   private Class<?>[] externalPermissionTypes = {};
-
-   public synchronized static DelegatingPolicy getInstance()
-   {
-      if (instance == null)
-      {
-         instance = new DelegatingPolicy();
-      }
-      return instance;
-   }
-
-   public DelegatingPolicy()
-   {
-      this(null);
-   }
-
-   public DelegatingPolicy(Policy delegate)
-   {
-      if (delegate == null)
-         delegate = Policy.getPolicy();
-      this.delegate = delegate;
-      this.trace = log.isTraceEnabled();
-      if (instance == null)
-         instance = this;
-      /* When run with a security manager the act of class loading can trigger
-      security checks which in turn causes this classes implies method to be
-      called as soon as the this class is installed as the Policy implementation.
-      The implies method cannot cause class loading to occur before there is
-      the delegation to the non-JACC Policy provider or else an infinite
-      recursion scenario arises where entrance into implies triggers class
-      loading which recurses into implies. Here we load the JACC permission
-      classes to ensure we get to the point of being able to delegate non-JACC
-      permission to the delegate policy. This is the same type of statement
-      performed at the start of implies which was causing the JACC permissions
-      to be loaded. See [JBAS-1363].
-      */
-      Permission permission = new RuntimePermission("test");
-      boolean loadedPerms = !(permission instanceof EJBMethodPermission
-         || permission instanceof EJBRoleRefPermission
-         || permission instanceof WebResourcePermission
-         || permission instanceof WebRoleRefPermission
-         || permission instanceof WebUserDataPermission);
-      if (trace)
-         log.trace("Loaded JACC permissions: " + loadedPerms);
-      // Load PolicyContext as this also can trigger permission checks in implies
-      Class<?> c = PolicyContext.class;
-      log.trace("loaded policy context class"+c);
-   }
-
-   public Class<?>[] getExternalPermissionTypes()
-   {
-      return externalPermissionTypes;
-   }
-   public void setExternalPermissionTypes(Class<?>[] externalPermissionTypes)
-   {
-      if( externalPermissionTypes == null )
-         externalPermissionTypes = new Class[0];
-      this.externalPermissionTypes = externalPermissionTypes;
-   }
-
-   public PermissionCollection getPermissions(ProtectionDomain domain)
-   {
-      PermissionCollection pc = super.getPermissions(domain);
-      PermissionCollection delegated = delegate.getPermissions(domain);
-      for (Enumeration<Permission> e = delegated.elements(); e.hasMoreElements();)
-      {
-         Permission p = (Permission) e.nextElement();
-         pc.add(p);
-      }
-      return pc;
-   }
-
-   public boolean implies(ProtectionDomain domain, Permission permission)
-   {
-      boolean isJaccPermission = permission instanceof EJBMethodPermission
-         || permission instanceof EJBRoleRefPermission
-         || permission instanceof WebResourcePermission
-         || permission instanceof WebRoleRefPermission
-         || permission instanceof WebUserDataPermission;
-      boolean implied = false;
-      // If there are external permission types check them
-      if( isJaccPermission == false && externalPermissionTypes.length > 0 )
-      {
-         Class<?> pc = permission.getClass();
-         for(int n = 0; n < externalPermissionTypes.length; n ++)
-         {
-            Class<?> epc = externalPermissionTypes[n];
-            if( epc.isAssignableFrom(pc) )
-            {
-               isJaccPermission = true;
-               break;
-            }
-         }
-      }
-
-      if (isJaccPermission == false)
-      {
-         // Let the delegate policy handle the check
-         implied = delegate.implies(domain, permission);
-      }
-      else
-      { 
-         String contextID = PolicyContext.getContextID();
-         ContextPolicy contextPolicy = (ContextPolicy) activePolicies.get(contextID);
-         if (contextPolicy != null)
-            implied = contextPolicy.implies(domain, permission);
-         else if (trace)
-            log.trace("No PolicyContext found for contextID=" + contextID);
-      }
-      if (trace)
-      {
-         log.trace("implied=" + implied);
-      }
-      return implied;
-   }
-
-   /**
-    * Return the permission collection associated with the cs.
-    * If there is no active JACC PolicyContext then the delegate value for 
-    * getPermissions(CodeSource) is returned. Otherwise the JACC policy context
-    * permissions are returned. 
-    * 
-    * @param cs - the CodeSource  
-    * @return the associated permission collection
-    */ 
-   public PermissionCollection getPermissions(CodeSource cs)
-   {
-      PermissionCollection pc = null;
-      String contextID = PolicyContext.getContextID();
-      if (contextID == null)
-      {
-         pc = delegate.getPermissions(cs);
-      }
-      else
-      {
-         ContextPolicy policy = (ContextPolicy) activePolicies.get(contextID);
-         if (policy != null)
-         {
-            pc = policy.getPermissions();
-            PermissionCollection delegatePerms = delegate.getPermissions(cs);
-            for(Enumeration<Permission> e = delegatePerms.elements();e.hasMoreElements();)
-            {
-               pc.add(e.nextElement());
-            } 
-         }
-         else
-         {
-            pc = delegate.getPermissions(cs);
-         }
-      }
-      return pc;
-   }
-   
-   
-
-   /**
-    * We dynamically manage the active policies on commit so refresh is a noop.
-    * Its not clear from the spec whether committed policies should not be visible
-    * until a refresh.
-    */
-   public void refresh()
-   {
-      
-   }
-
-   /**
-    * @return A proxy for our Policy interface
-    */
-   public Policy getPolicyProxy()
-   {
-      return policyProxy;
-   }
-
-   // Policy configuration methods used by the PolicyConfiguration impl
-
-   /**
-    * Access the current ContextPolicy instances
-    * @return Map<String, ContextPolicy> of the contextID to policy mappings
-    */
-   public String listContextPolicies()
-   {
-      StringBuffer tmp = new StringBuffer("<ActiveContextPolicies>");
-      Iterator<String> iter = activePolicies.keySet().iterator();
-      while (iter.hasNext())
-      {
-         String contextID = (String) iter.next();
-         ContextPolicy cp = (ContextPolicy) activePolicies.get(contextID);
-         tmp.append(cp);
-         tmp.append('\n');
-      }
-      tmp.append("</ActiveContextPolicies>");
-
-      tmp.append("<OpenContextPolicies>");
-      iter = openPolicies.keySet().iterator();
-      while (iter.hasNext())
-      {
-         String contextID = (String) iter.next();
-         ContextPolicy cp = (ContextPolicy) openPolicies.get(contextID);
-         tmp.append(cp);
-         tmp.append('\n');
-      }
-      tmp.append("</OpenContextPolicies>");
-
-      return tmp.toString();
-   }
-
-   synchronized ContextPolicy getContextPolicy(String contextID)
-      throws PolicyContextException
-   {
-      ContextPolicy policy = (ContextPolicy) openPolicies.get(contextID);
-      if (policy == null)
-         throw new PolicyContextException("No ContextPolicy exists for contextID=" + contextID);
-      return policy;
-   }
-
-   /**
-    * Create or update a ContextPolicy for contextID. This moves any active
-    * policy to the openPolicies map until its committed.
-    * 
-    * @param contextID
-    * @param remove
-    * @throws PolicyContextException
-    */
-   synchronized void initPolicyConfiguration(String contextID, boolean remove)
-      throws PolicyContextException
-   {
-      // Remove from the active policy map
-      ContextPolicy policy = (ContextPolicy) activePolicies.remove(contextID);
-      if( policy == null )
-         policy = (ContextPolicy) openPolicies.get(contextID);
-      if (policy == null)
-      {
-         policy = new ContextPolicy(contextID);
-      }
-      // Add to the open policy map
-      openPolicies.put(contextID, policy);
-      if (remove == true)
-         policy.clear();
-   }
-
-   void addToExcludedPolicy(String contextID, Permission permission)
-      throws PolicyContextException
-   {
-      ContextPolicy policy = getContextPolicy(contextID);
-      policy.addToExcludedPolicy(permission);
-   }
-
-   void addToExcludedPolicy(String contextID, PermissionCollection permissions)
-      throws PolicyContextException
-   {
-      ContextPolicy policy = getContextPolicy(contextID);
-      policy.addToExcludedPolicy(permissions);
-   }
-
-   void addToRole(String contextID, String roleName, Permission permission)
-      throws PolicyContextException
-   {
-      ContextPolicy policy = getContextPolicy(contextID);
-      policy.addToRole(roleName, permission);
-   }
-
-   void addToRole(String contextID, String roleName, PermissionCollection permissions)
-      throws PolicyContextException
-   {
-      ContextPolicy policy = getContextPolicy(contextID);
-      policy.addToRole(roleName, permissions);
-   }
-
-   void addToUncheckedPolicy(String contextID, Permission permission)
-      throws PolicyContextException
-   {
-      ContextPolicy policy = getContextPolicy(contextID);
-      policy.addToUncheckedPolicy(permission);
-   }
-
-   void addToUncheckedPolicy(String contextID, PermissionCollection permissions)
-      throws PolicyContextException
-   {
-      ContextPolicy policy = getContextPolicy(contextID);
-      policy.addToUncheckedPolicy(permissions);
-   }
-
-   void linkConfiguration(String contextID, PolicyConfiguration link)
-      throws PolicyContextException
-   {
-      ContextPolicy policy = getContextPolicy(contextID);
-      ContextPolicy linkPolicy = getContextPolicy(link.getContextID());
-      policy.linkConfiguration(linkPolicy);
-   }
-
-   /**
-    * May need to make this synchronized to allow the move from the open to
-    * active policy map atomic. Right now the assumption is that a single thread
-    * is active for a given contextID.
-    * 
-    * @param contextID
-    * @throws PolicyContextException
-    */ 
-   public void commit(String contextID)
-      throws PolicyContextException
-   {
-      ContextPolicy policy = getContextPolicy(contextID);
-      openPolicies.remove(contextID);
-      activePolicies.put(contextID, policy);
-      policy.commit();
-   }
-
-   public void delete(String contextID)
-      throws PolicyContextException
-   {
-      ContextPolicy policy = (ContextPolicy) activePolicies.remove(contextID);
-      if( policy == null )
-         policy = (ContextPolicy) openPolicies.remove(contextID);
-      if( policy != null )
-         policy.delete();
-   }
-   
-   void removeExcludedPolicy(String contextID)
-      throws PolicyContextException
-   {
-      ContextPolicy policy = getContextPolicy(contextID);
-      policy.removeExcludedPolicy();
-   }
-
-   void removeRole(String contextID, String roleName)
-      throws PolicyContextException
-   {
-      ContextPolicy policy = getContextPolicy(contextID);
-      policy.removeRole(roleName);
-   }
-
-   void removeUncheckedPolicy(String contextID)
-      throws PolicyContextException
-   {
-      ContextPolicy policy = getContextPolicy(contextID);
-      policy.removeUncheckedPolicy();
-   }
-   
-   //Methods used by subclasses
-   protected Permissions getPermissionsForRole(String role) throws PolicyContextException
-   {
-      Permissions perms = null;
-      String contextID = PolicyContext.getContextID();
-      ContextPolicy contextPolicy = (ContextPolicy) activePolicies.get(contextID);
-      if (contextPolicy != null)  
-         perms = contextPolicy.getPermissionsForRole(role);
-      return perms;
-   }
-
-   /**
-    * This proxy wrapper restricts the visible methods to only those from the
-    * Policy base class.
-    */ 
-   private static class PolicyProxy extends Policy
-   {
-      private Policy delegate;
-
-      PolicyProxy(Policy delegate)
-      {
-         this.delegate = delegate;
-      }
-
-      public void refresh()
-      {
-         delegate.refresh();
-      }
-
-      public PermissionCollection getPermissions(CodeSource codesource)
-      {
-         return delegate.getPermissions(codesource);
-      }
-
-      public boolean implies(ProtectionDomain domain, Permission permission)
-      {
-         return delegate.implies(domain, permission);
-      }
-
-      public PermissionCollection getPermissions(ProtectionDomain domain)
-      {
-         return delegate.getPermissions(domain);
-      }
-   }
-}

Copied: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/jacc/DelegatingPolicy.java (from rev 93325, projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/security/jacc/DelegatingPolicy.java)
===================================================================
--- projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/jacc/DelegatingPolicy.java	                        (rev 0)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/jacc/DelegatingPolicy.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -0,0 +1,467 @@
+/*
+* JBoss, Home of Professional Open Source
+* Copyright 2005, JBoss Inc., and individual contributors as indicated
+* by the @authors tag. See the copyright.txt in the distribution for a
+* full listing of individual contributors.
+*
+* This is free software; you can redistribute it and/or modify it
+* under the terms of the GNU Lesser General Public License as
+* published by the Free Software Foundation; either version 2.1 of
+* the License, or (at your option) any later version.
+*
+* This software is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+* Lesser General Public License for more details.
+*
+* You should have received a copy of the GNU Lesser General Public
+* License along with this software; if not, write to the Free
+* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+*/
+package org.jboss.security.jacc;
+
+import java.security.CodeSource;
+import java.security.Permission;
+import java.security.PermissionCollection;
+import java.security.Permissions;
+import java.security.Policy;
+import java.security.ProtectionDomain;
+import java.util.Enumeration;
+import java.util.Iterator;
+import java.util.concurrent.ConcurrentHashMap;
+
+import javax.security.jacc.EJBMethodPermission;
+import javax.security.jacc.EJBRoleRefPermission;
+import javax.security.jacc.PolicyConfiguration;
+import javax.security.jacc.PolicyContext;
+import javax.security.jacc.PolicyContextException;
+import javax.security.jacc.WebResourcePermission;
+import javax.security.jacc.WebRoleRefPermission;
+import javax.security.jacc.WebUserDataPermission;
+
+import org.jboss.logging.Logger;
+ 
+/**
+ * A JAAC Policy provider implementation that delegates any non-JACC permissions
+ * to the java.security.Policy either passed in to the ctor, or the pre existing
+ * Policy.getPolicy value.
+ * @author Scott.Stark at jboss.org
+ * @version $Revision$
+ */
+public class DelegatingPolicy extends Policy
+{
+   private static Logger log = Logger.getLogger(DelegatingPolicy.class);
+   private static DelegatingPolicy instance;
+
+   /**
+    * The system Policy we delegate non-JACC checks to
+    */
+   private Policy delegate;
+   /**
+    * Map<String, ContextPolicy> for the JACC context IDs that have been
+    * committed.
+    */
+   private ConcurrentHashMap<String,ContextPolicy> activePolicies = new ConcurrentHashMap<String,ContextPolicy>();
+   /**
+    * Map<String, ContextPolicy> for the JACC policies that are in the open
+    * state and should be excluded from the active permission set.
+    */ 
+   private ConcurrentHashMap<String,ContextPolicy> openPolicies = new ConcurrentHashMap<String,ContextPolicy>(); 
+   /**
+    * Flag indicating if our category is at trace level for logging
+    */
+   private boolean trace;
+   /**
+    * The Policy proxy returned via the PolicyProxy attribute
+    */
+   private PolicyProxy policyProxy = new PolicyProxy(this);
+
+   /**
+    The types of permissions which should be treated as JACC permission types
+    in terms of whether this policy should validate the permission.
+    */
+   private Class<?>[] externalPermissionTypes = {};
+
+   public synchronized static DelegatingPolicy getInstance()
+   {
+      if (instance == null)
+      {
+         instance = new DelegatingPolicy();
+      }
+      return instance;
+   }
+
+   public DelegatingPolicy()
+   {
+      this(null);
+   }
+
+   public DelegatingPolicy(Policy delegate)
+   {
+      if (delegate == null)
+         delegate = Policy.getPolicy();
+      this.delegate = delegate;
+      this.trace = log.isTraceEnabled();
+      if (instance == null)
+         instance = this;
+      /* When run with a security manager the act of class loading can trigger
+      security checks which in turn causes this classes implies method to be
+      called as soon as the this class is installed as the Policy implementation.
+      The implies method cannot cause class loading to occur before there is
+      the delegation to the non-JACC Policy provider or else an infinite
+      recursion scenario arises where entrance into implies triggers class
+      loading which recurses into implies. Here we load the JACC permission
+      classes to ensure we get to the point of being able to delegate non-JACC
+      permission to the delegate policy. This is the same type of statement
+      performed at the start of implies which was causing the JACC permissions
+      to be loaded. See [JBAS-1363].
+      */
+      Permission permission = new RuntimePermission("test");
+      boolean loadedPerms = !(permission instanceof EJBMethodPermission
+         || permission instanceof EJBRoleRefPermission
+         || permission instanceof WebResourcePermission
+         || permission instanceof WebRoleRefPermission
+         || permission instanceof WebUserDataPermission);
+      if (trace)
+         log.trace("Loaded JACC permissions: " + loadedPerms);
+      // Load PolicyContext as this also can trigger permission checks in implies
+      Class<?> c = PolicyContext.class;
+      if(trace)
+         log.trace("loaded policy context class"+c);
+   }
+
+   public Class<?>[] getExternalPermissionTypes()
+   {
+      return externalPermissionTypes;
+   }
+   public void setExternalPermissionTypes(Class<?>[] externalPermissionTypes)
+   {
+      if( externalPermissionTypes == null )
+         externalPermissionTypes = new Class[0];
+      this.externalPermissionTypes = externalPermissionTypes;
+   }
+
+   public PermissionCollection getPermissions(ProtectionDomain domain)
+   {
+      PermissionCollection pc = super.getPermissions(domain);
+      PermissionCollection delegated = delegate.getPermissions(domain);
+      for (Enumeration<Permission> e = delegated.elements(); e.hasMoreElements();)
+      {
+         Permission p = (Permission) e.nextElement();
+         pc.add(p);
+      }
+      return pc;
+   }
+
+   public boolean implies(ProtectionDomain domain, Permission permission)
+   {
+      boolean isJaccPermission = permission instanceof EJBMethodPermission
+         || permission instanceof EJBRoleRefPermission
+         || permission instanceof WebResourcePermission
+         || permission instanceof WebRoleRefPermission
+         || permission instanceof WebUserDataPermission;
+      boolean implied = false;
+      // If there are external permission types check them
+      if( isJaccPermission == false && externalPermissionTypes.length > 0 )
+      {
+         Class<?> pc = permission.getClass();
+         for(int n = 0; n < externalPermissionTypes.length; n ++)
+         {
+            Class<?> epc = externalPermissionTypes[n];
+            if( epc.isAssignableFrom(pc) )
+            {
+               isJaccPermission = true;
+               break;
+            }
+         }
+      }
+
+      if (isJaccPermission == false)
+      {
+         // Let the delegate policy handle the check
+         implied = delegate.implies(domain, permission);
+      }
+      else
+      { 
+         String contextID = PolicyContext.getContextID();
+         ContextPolicy contextPolicy = (ContextPolicy) activePolicies.get(contextID);
+         if (contextPolicy != null)
+            implied = contextPolicy.implies(domain, permission);
+         else if (trace)
+            log.trace("No PolicyContext found for contextID=" + contextID);
+      }
+      if (trace)
+      {
+         log.trace("implied=" + implied);
+      }
+      return implied;
+   }
+
+   /**
+    * Return the permission collection associated with the cs.
+    * If there is no active JACC PolicyContext then the delegate value for 
+    * getPermissions(CodeSource) is returned. Otherwise the JACC policy context
+    * permissions are returned. 
+    * 
+    * @param cs - the CodeSource  
+    * @return the associated permission collection
+    */ 
+   public PermissionCollection getPermissions(CodeSource cs)
+   {
+      PermissionCollection pc = null;
+      String contextID = PolicyContext.getContextID();
+      if (contextID == null)
+      {
+         pc = delegate.getPermissions(cs);
+      }
+      else
+      {
+         ContextPolicy policy = (ContextPolicy) activePolicies.get(contextID);
+         if (policy != null)
+         {
+            pc = policy.getPermissions();
+            PermissionCollection delegatePerms = delegate.getPermissions(cs);
+            for(Enumeration<Permission> e = delegatePerms.elements();e.hasMoreElements();)
+            {
+               pc.add(e.nextElement());
+            } 
+         }
+         else
+         {
+            pc = delegate.getPermissions(cs);
+         }
+      }
+      return pc;
+   }
+   
+   
+
+   /**
+    * We dynamically manage the active policies on commit so refresh is a noop.
+    * Its not clear from the spec whether committed policies should not be visible
+    * until a refresh.
+    */
+   public void refresh()
+   {
+      
+   }
+
+   /**
+    * @return A proxy for our Policy interface
+    */
+   public Policy getPolicyProxy()
+   {
+      return policyProxy;
+   }
+
+   // Policy configuration methods used by the PolicyConfiguration impl
+
+   /**
+    * Access the current ContextPolicy instances
+    * @return Map<String, ContextPolicy> of the contextID to policy mappings
+    */
+   public String listContextPolicies()
+   {
+      StringBuffer tmp = new StringBuffer("<ActiveContextPolicies>");
+      Iterator<String> iter = activePolicies.keySet().iterator();
+      while (iter.hasNext())
+      {
+         String contextID = (String) iter.next();
+         ContextPolicy cp = (ContextPolicy) activePolicies.get(contextID);
+         tmp.append(cp);
+         tmp.append('\n');
+      }
+      tmp.append("</ActiveContextPolicies>");
+
+      tmp.append("<OpenContextPolicies>");
+      iter = openPolicies.keySet().iterator();
+      while (iter.hasNext())
+      {
+         String contextID = (String) iter.next();
+         ContextPolicy cp = (ContextPolicy) openPolicies.get(contextID);
+         tmp.append(cp);
+         tmp.append('\n');
+      }
+      tmp.append("</OpenContextPolicies>");
+
+      return tmp.toString();
+   }
+
+   synchronized ContextPolicy getContextPolicy(String contextID)
+      throws PolicyContextException
+   {
+      ContextPolicy policy = (ContextPolicy) openPolicies.get(contextID);
+      if (policy == null)
+         throw new PolicyContextException("No ContextPolicy exists for contextID=" + contextID);
+      return policy;
+   }
+
+   /**
+    * Create or update a ContextPolicy for contextID. This moves any active
+    * policy to the openPolicies map until its committed.
+    * 
+    * @param contextID
+    * @param remove
+    * @throws PolicyContextException
+    */
+   synchronized void initPolicyConfiguration(String contextID, boolean remove)
+      throws PolicyContextException
+   {
+      // Remove from the active policy map
+      ContextPolicy policy = (ContextPolicy) activePolicies.remove(contextID);
+      if( policy == null )
+         policy = (ContextPolicy) openPolicies.get(contextID);
+      if (policy == null)
+      {
+         policy = new ContextPolicy(contextID);
+      }
+      // Add to the open policy map
+      openPolicies.put(contextID, policy);
+      if (remove == true)
+         policy.clear();
+   }
+
+   void addToExcludedPolicy(String contextID, Permission permission)
+      throws PolicyContextException
+   {
+      ContextPolicy policy = getContextPolicy(contextID);
+      policy.addToExcludedPolicy(permission);
+   }
+
+   void addToExcludedPolicy(String contextID, PermissionCollection permissions)
+      throws PolicyContextException
+   {
+      ContextPolicy policy = getContextPolicy(contextID);
+      policy.addToExcludedPolicy(permissions);
+   }
+
+   void addToRole(String contextID, String roleName, Permission permission)
+      throws PolicyContextException
+   {
+      ContextPolicy policy = getContextPolicy(contextID);
+      policy.addToRole(roleName, permission);
+   }
+
+   void addToRole(String contextID, String roleName, PermissionCollection permissions)
+      throws PolicyContextException
+   {
+      ContextPolicy policy = getContextPolicy(contextID);
+      policy.addToRole(roleName, permissions);
+   }
+
+   void addToUncheckedPolicy(String contextID, Permission permission)
+      throws PolicyContextException
+   {
+      ContextPolicy policy = getContextPolicy(contextID);
+      policy.addToUncheckedPolicy(permission);
+   }
+
+   void addToUncheckedPolicy(String contextID, PermissionCollection permissions)
+      throws PolicyContextException
+   {
+      ContextPolicy policy = getContextPolicy(contextID);
+      policy.addToUncheckedPolicy(permissions);
+   }
+
+   void linkConfiguration(String contextID, PolicyConfiguration link)
+      throws PolicyContextException
+   {
+      ContextPolicy policy = getContextPolicy(contextID);
+      ContextPolicy linkPolicy = getContextPolicy(link.getContextID());
+      policy.linkConfiguration(linkPolicy);
+   }
+
+   /**
+    * May need to make this synchronized to allow the move from the open to
+    * active policy map atomic. Right now the assumption is that a single thread
+    * is active for a given contextID.
+    * 
+    * @param contextID
+    * @throws PolicyContextException
+    */ 
+   public void commit(String contextID)
+      throws PolicyContextException
+   {
+      ContextPolicy policy = getContextPolicy(contextID);
+      openPolicies.remove(contextID);
+      activePolicies.put(contextID, policy);
+      policy.commit();
+   }
+
+   public void delete(String contextID)
+      throws PolicyContextException
+   {
+      ContextPolicy policy = (ContextPolicy) activePolicies.remove(contextID);
+      if( policy == null )
+         policy = (ContextPolicy) openPolicies.remove(contextID);
+      if( policy != null )
+         policy.delete();
+   }
+   
+   void removeExcludedPolicy(String contextID)
+      throws PolicyContextException
+   {
+      ContextPolicy policy = getContextPolicy(contextID);
+      policy.removeExcludedPolicy();
+   }
+
+   void removeRole(String contextID, String roleName)
+      throws PolicyContextException
+   {
+      ContextPolicy policy = getContextPolicy(contextID);
+      policy.removeRole(roleName);
+   }
+
+   void removeUncheckedPolicy(String contextID)
+      throws PolicyContextException
+   {
+      ContextPolicy policy = getContextPolicy(contextID);
+      policy.removeUncheckedPolicy();
+   }
+   
+   //Methods used by subclasses
+   protected Permissions getPermissionsForRole(String role) throws PolicyContextException
+   {
+      Permissions perms = null;
+      String contextID = PolicyContext.getContextID();
+      ContextPolicy contextPolicy = (ContextPolicy) activePolicies.get(contextID);
+      if (contextPolicy != null)  
+         perms = contextPolicy.getPermissionsForRole(role);
+      return perms;
+   }
+
+   /**
+    * This proxy wrapper restricts the visible methods to only those from the
+    * Policy base class.
+    */ 
+   private static class PolicyProxy extends Policy
+   {
+      private Policy delegate;
+
+      PolicyProxy(Policy delegate)
+      {
+         this.delegate = delegate;
+      }
+
+      public void refresh()
+      {
+         delegate.refresh();
+      }
+
+      public PermissionCollection getPermissions(CodeSource codesource)
+      {
+         return delegate.getPermissions(codesource);
+      }
+
+      public boolean implies(ProtectionDomain domain, Permission permission)
+      {
+         return delegate.implies(domain, permission);
+      }
+
+      public PermissionCollection getPermissions(ProtectionDomain domain)
+      {
+         return delegate.getPermissions(domain);
+      }
+   }
+}

Copied: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/mapping/providers/attribute (from rev 92039, projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/security/mapping/providers/attribute)

Deleted: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/mapping/providers/attribute/LdapAttributeMappingProvider.java
===================================================================
--- projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/security/mapping/providers/attribute/LdapAttributeMappingProvider.java	2009-08-05 22:02:36 UTC (rev 92039)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/mapping/providers/attribute/LdapAttributeMappingProvider.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -1,343 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * Copyright 2008, Red Hat Middleware LLC, and individual contributors
- * as indicated by the @author tags. See the copyright.txt file in the
- * distribution for a full listing of individual contributors. 
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jboss.security.mapping.providers.attribute;
-
-import java.security.Principal;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Properties;
-import java.util.StringTokenizer;
-import java.util.Map.Entry;
-
-import javax.management.ObjectName;
-import javax.naming.Context;
-import javax.naming.NamingEnumeration;
-import javax.naming.NamingException;
-import javax.naming.directory.Attributes;
-import javax.naming.directory.SearchControls;
-import javax.naming.directory.SearchResult;
-import javax.naming.ldap.InitialLdapContext;
-
-import org.jboss.logging.Logger;
-import org.jboss.security.SecurityConstants;
-import org.jboss.security.identity.Attribute;
-import org.jboss.security.identity.AttributeFactory;
-import org.jboss.security.mapping.MappingProvider;
-import org.jboss.security.mapping.MappingResult;
-
-/**
- * Maps attributes from LDAP
- * 
- * The options include whatever options your LDAP JNDI provider
- supports. Examples of standard property names are:
-
- * Context.INITIAL_CONTEXT_FACTORY = "java.naming.factory.initial"
- * Context.SECURITY_PROTOCOL = "java.naming.security.protocol"
- * Context.PROVIDER_URL = "java.naming.provider.url"
- * Context.SECURITY_AUTHENTICATION = "java.naming.security.authentication"
- * 
- * Other Module Options:-
- * 
- * bindDN:The DN used to bind against the ldap server for the user and
- roles queries. This is some DN with read/search permissions on the baseCtxDN and
- rolesCtxDN values.
- * 
- * bindCredential: The password for the bindDN. This can be encrypted if the
- jaasSecurityDomain is specified.
- * 
- * baseCtxDN: The fixed DN of the context to start the user search from.
- * 
- * baseFilter:A search filter used to locate the context of the user to
- authenticate. The input username/userDN as obtained from the login module
- callback will be substituted into the filter anywhere a "{0}" expression is
- seen. This substituion behavior comes from the standard
- __DirContext.search(Name, String, Object[], SearchControls cons)__ method. An
- common example search filter is "(uid={0})".
- 
- * searchTimeLimit:The timeout in milliseconds for the user/role searches.
- Defaults to 10000 (10 seconds).
- 
- * attributeList: A comma-separated list of attributes for the user 
- * (Example:  mail,cn,sn,employeeType,employeeNumber)
- * 
- * jaasSecurityDomain: The JMX ObjectName of the JaasSecurityDomain to use
- to decrypt the java.naming.security.principal. The encrypted form of the
- password is that returned by the JaasSecurityDomain#encrypt64(byte[]) method.
- The org.jboss.security.plugins.PBEUtils can also be used to generate the
- encrypted form.
- * 
- * @author Anil.Saldhana at redhat.com
- * @since August 5, 2009
- */
-public class LdapAttributeMappingProvider implements MappingProvider<List<Attribute<String>>>
-{
-   private Map<String, Object> options;
-   
-   private static Logger log = Logger.getLogger(LdapAttributeMappingProvider.class);
-   private boolean trace = log.isTraceEnabled();
-   
-   protected int searchTimeLimit = 10000;
-   
-   private static final String BIND_DN = "bindDN";
-
-   private static final String BIND_CREDENTIAL = "bindCredential";
-
-   private static final String BASE_CTX_DN = "baseCtxDN";
-
-   private static final String BASE_FILTER_OPT = "baseFilter"; 
-
-   private static final String SEARCH_TIME_LIMIT_OPT = "searchTimeLimit";
-   
-   private static final String ATTRIBUTE_LIST_OPT = "attributeList"; 
-
-   private static final String SECURITY_DOMAIN_OPT = "jaasSecurityDomain";
-
-   private MappingResult<List<Attribute<String>>> mappingResult;
-
-   public void init(Map<String, Object> options)
-   {
-      this.options = options;
-   }
-
-   @SuppressWarnings("unchecked")
-   public void performMapping(Map<String, Object> map, List<Attribute<String>> mappedObject)
-   {
-      List<Attribute<String>> attributeList = new ArrayList<Attribute<String>>();
-      
-      Principal principal = (Principal) map.get(SecurityConstants.PRINCIPAL_IDENTIFIER);
-      if(principal != null)
-      {
-         String user = principal.getName();
-         
-         String bindDN = (String) options.get(BIND_DN);
-         if(bindDN == null || bindDN.length() == 0)
-         {
-            log.trace("bindDN is not found");
-            return;
-         }
-         String bindCredential = (String) options.get(BIND_CREDENTIAL);
-         if (bindCredential.startsWith("{EXT}"))
-            try
-            {
-               bindCredential = new String(org.jboss.security.Util.loadPassword(bindCredential));
-            }
-            catch (Exception e1)
-            {
-               log.error("Exception in decrypting bindCredential:",e1);
-               return;
-            }
-         String securityDomain = (String) options.get(SECURITY_DOMAIN_OPT);
-         if (securityDomain != null)
-         {
-            try
-            {
-               ObjectName serviceName = new ObjectName(securityDomain);
-               char[] tmp = MappingProvidersDecodeAction.decode(bindCredential, serviceName);
-               bindCredential = new String(tmp);
-            } 
-            catch (Exception e)
-            {
-               log.error("Exception in decrypting bindCredential:",e);
-               return;
-            }
-         }
-         
-         InitialLdapContext ctx;
-         try
-         {
-            ctx = this.constructInitialLdapContext(bindDN, bindCredential);
-         }
-         catch (NamingException e)
-         {
-            throw new RuntimeException(e);
-         } 
-         
-         String timeLimit = (String) options.get(SEARCH_TIME_LIMIT_OPT);
-         if (timeLimit != null)
-         {
-            try
-            {
-               searchTimeLimit = Integer.parseInt(timeLimit);
-            }
-            catch (NumberFormatException e)
-            {
-               if (trace)
-                  log.trace("Failed to parse: " + timeLimit + ", using searchTimeLimit=" + searchTimeLimit, e);
-            }
-         }
-         if(searchTimeLimit == 0)
-            searchTimeLimit = 10000;
-         
-         String baseDN = (String) options.get(BASE_CTX_DN); 
-         String baseFilter = (String) options.get(BASE_FILTER_OPT);
-         
-         SearchControls constraints = new SearchControls();
-         constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
-         
-         constraints.setTimeLimit(searchTimeLimit);
-         
-         String attributePattern = (String) options.get(ATTRIBUTE_LIST_OPT);
-         
-         //Take care of the attributes we want
-         String neededAttributes[] = getNeededAttributes(attributePattern);
-         
-         constraints.setReturningAttributes(neededAttributes);
-
-         NamingEnumeration results = null;
-
-         Object[] filterArgs = {user};
-         try
-         {
-            if(baseDN == null)
-               throw new NamingException(BASE_CTX_DN + " is null");
-            results = ctx.search(baseDN, baseFilter, filterArgs, constraints);
-            if (results.hasMore() == false)
-            {
-               results.close();
-               throw new NamingException("Search of baseDN(" + baseDN + ") found no matches");
-            } 
-            SearchResult sr = (SearchResult) results.next();
-            String name = sr.getName();
-            String userDN = null;
-            if (sr.isRelative() == true)
-               userDN = name + "," + baseDN;
-            else
-               throw new NamingException("Can't follow referal for authentication: " + name);
-
-            results.close();
-            
-            //Finished Authentication.  Lets look for the attributes
-            filterArgs = new Object[]{user, userDN};
-            results = ctx.search(userDN, baseFilter, filterArgs, constraints);
-            try
-            {
-               while (results.hasMore())
-               {
-                  sr = (SearchResult) results.next(); 
-                  Attributes attributes = sr.getAttributes();
-                  NamingEnumeration<? extends javax.naming.directory.Attribute> ne = attributes.getAll();
-                  
-                  while(ne != null && ne.hasMoreElements())
-                  {
-                     javax.naming.directory.Attribute ldapAtt = ne.next();
-                     if("mail".equalsIgnoreCase(ldapAtt.getID()))
-                     {
-                        attributeList.add(AttributeFactory.createEmailAddress((String) ldapAtt.get()));   
-                     }
-                     else
-                        attributeList.add(AttributeFactory.createAttribute(ldapAtt.getID(), 
-                              (String)ldapAtt.get())); 
-                  } 
-               }       
-            }
-            finally
-            {
-               if (results != null)
-                  results.close();
-            }            
-         }catch(NamingException ne)
-         {
-            log.error(ne);
-            return;
-         } 
-         results = null;
-      }
-      
-      mappedObject.addAll(attributeList);
-      mappingResult.setMappedObject(mappedObject);   
-   }
-
-   public void setMappingResult(MappingResult<List<Attribute<String>>> result)
-   {
-      this.mappingResult = result;
-   }
-
-   public boolean supports(Class<?> clazz)
-   { 
-      if(Attribute.class.isAssignableFrom(clazz))
-        return true;
-      
-      return false;
-   } 
-   
-   
-   @SuppressWarnings("unchecked")
-   private InitialLdapContext constructInitialLdapContext(String dn, Object credential) throws NamingException
-   {
-      Properties env = new Properties();
-      Iterator iter = options.entrySet().iterator();
-      while (iter.hasNext())
-      {
-         Entry entry = (Entry) iter.next();
-         env.put(entry.getKey(), entry.getValue());
-      }
-
-      // Set defaults for key values if they are missing
-      String factoryName = env.getProperty(Context.INITIAL_CONTEXT_FACTORY);
-      if (factoryName == null)
-      {
-         factoryName = "com.sun.jndi.ldap.LdapCtxFactory";
-         env.setProperty(Context.INITIAL_CONTEXT_FACTORY, factoryName);
-      }
-      String authType = env.getProperty(Context.SECURITY_AUTHENTICATION);
-      if (authType == null)
-         env.setProperty(Context.SECURITY_AUTHENTICATION, "simple");
-      String protocol = env.getProperty(Context.SECURITY_PROTOCOL);
-      String providerURL = (String) options.get(Context.PROVIDER_URL);
-      if (providerURL == null)
-         providerURL = "ldap://localhost:" + ((protocol != null && protocol.equals("ssl")) ? "636" : "389");
-
-      env.setProperty(Context.PROVIDER_URL, providerURL);
-      // JBAS-3555, allow anonymous login with no bindDN and bindCredential
-      if (dn != null)
-         env.setProperty(Context.SECURITY_PRINCIPAL, dn);
-      if (credential != null)
-         env.put(Context.SECURITY_CREDENTIALS, credential);
-      traceLdapEnv(env);
-      return new InitialLdapContext(env, null);
-   }
-   
-   private void traceLdapEnv(Properties env)
-   {
-      if (trace)
-      {
-         Properties tmp = new Properties();
-         tmp.putAll(env);
-         tmp.setProperty(Context.SECURITY_CREDENTIALS, "***");
-         log.trace("Logging into LDAP server, env=" + tmp.toString());
-      }
-   }
-   
-   private String[] getNeededAttributes(String commaSeparatedList)
-   {
-      ArrayList<String> arrayList = new ArrayList<String>();
-      StringTokenizer st = new StringTokenizer(commaSeparatedList,",");
-      while(st.hasMoreTokens())
-      {
-         arrayList.add(st.nextToken());
-      }
-      String[] strArr = new String[arrayList.size()];
-      return arrayList.toArray(strArr); 
-   }
-}
\ No newline at end of file

Copied: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/mapping/providers/attribute/LdapAttributeMappingProvider.java (from rev 93325, projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/security/mapping/providers/attribute/LdapAttributeMappingProvider.java)
===================================================================
--- projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/mapping/providers/attribute/LdapAttributeMappingProvider.java	                        (rev 0)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/mapping/providers/attribute/LdapAttributeMappingProvider.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -0,0 +1,344 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors. 
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.security.mapping.providers.attribute;
+
+import java.security.Principal;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import java.util.StringTokenizer;
+import java.util.Map.Entry;
+
+import javax.management.ObjectName;
+import javax.naming.Context;
+import javax.naming.NamingEnumeration;
+import javax.naming.NamingException;
+import javax.naming.directory.Attributes;
+import javax.naming.directory.SearchControls;
+import javax.naming.directory.SearchResult;
+import javax.naming.ldap.InitialLdapContext;
+
+import org.jboss.logging.Logger;
+import org.jboss.security.SecurityConstants;
+import org.jboss.security.identity.Attribute;
+import org.jboss.security.identity.AttributeFactory;
+import org.jboss.security.mapping.MappingProvider;
+import org.jboss.security.mapping.MappingResult;
+
+/**
+ * Maps attributes from LDAP
+ * 
+ * The options include whatever options your LDAP JNDI provider
+ supports. Examples of standard property names are:
+
+ * Context.INITIAL_CONTEXT_FACTORY = "java.naming.factory.initial"
+ * Context.SECURITY_PROTOCOL = "java.naming.security.protocol"
+ * Context.PROVIDER_URL = "java.naming.provider.url"
+ * Context.SECURITY_AUTHENTICATION = "java.naming.security.authentication"
+ * 
+ * Other Module Options:-
+ * 
+ * bindDN:The DN used to bind against the ldap server for the user and
+ roles queries. This is some DN with read/search permissions on the baseCtxDN and
+ rolesCtxDN values.
+ * 
+ * bindCredential: The password for the bindDN. This can be encrypted if the
+ jaasSecurityDomain is specified.
+ * 
+ * baseCtxDN: The fixed DN of the context to start the user search from.
+ * 
+ * baseFilter:A search filter used to locate the context of the user to
+ authenticate. The input username/userDN as obtained from the login module
+ callback will be substituted into the filter anywhere a "{0}" expression is
+ seen. This substituion behavior comes from the standard
+ __DirContext.search(Name, String, Object[], SearchControls cons)__ method. An
+ common example search filter is "(uid={0})".
+ 
+ * searchTimeLimit:The timeout in milliseconds for the user/role searches.
+ Defaults to 10000 (10 seconds).
+ 
+ * attributeList: A comma-separated list of attributes for the user 
+ * (Example:  mail,cn,sn,employeeType,employeeNumber)
+ * 
+ * jaasSecurityDomain: The JMX ObjectName of the JaasSecurityDomain to use
+ to decrypt the java.naming.security.principal. The encrypted form of the
+ password is that returned by the JaasSecurityDomain#encrypt64(byte[]) method.
+ The org.jboss.security.plugins.PBEUtils can also be used to generate the
+ encrypted form.
+ * 
+ * @author Anil.Saldhana at redhat.com
+ * @since August 5, 2009
+ */
+public class LdapAttributeMappingProvider implements MappingProvider<List<Attribute<String>>>
+{
+   private Map<String, Object> options;
+   
+   private static Logger log = Logger.getLogger(LdapAttributeMappingProvider.class);
+   private boolean trace = log.isTraceEnabled();
+   
+   protected int searchTimeLimit = 10000;
+   
+   private static final String BIND_DN = "bindDN";
+
+   private static final String BIND_CREDENTIAL = "bindCredential";
+
+   private static final String BASE_CTX_DN = "baseCtxDN";
+
+   private static final String BASE_FILTER_OPT = "baseFilter"; 
+
+   private static final String SEARCH_TIME_LIMIT_OPT = "searchTimeLimit";
+   
+   private static final String ATTRIBUTE_LIST_OPT = "attributeList"; 
+
+   private static final String SECURITY_DOMAIN_OPT = "jaasSecurityDomain";
+
+   private MappingResult<List<Attribute<String>>> mappingResult;
+
+   public void init(Map<String, Object> options)
+   {
+      this.options = options;
+   }
+
+   @SuppressWarnings("unchecked")
+   public void performMapping(Map<String, Object> map, List<Attribute<String>> mappedObject)
+   {
+      List<Attribute<String>> attributeList = new ArrayList<Attribute<String>>();
+      
+      Principal principal = (Principal) map.get(SecurityConstants.PRINCIPAL_IDENTIFIER);
+      if(principal != null)
+      {
+         String user = principal.getName();
+         
+         String bindDN = (String) options.get(BIND_DN);
+         if(bindDN == null || bindDN.length() == 0)
+         {
+            if(trace)
+               log.trace("bindDN is not found");
+            return;
+         }
+         String bindCredential = (String) options.get(BIND_CREDENTIAL);
+         if (bindCredential.startsWith("{EXT}"))
+            try
+            {
+               bindCredential = new String(org.jboss.security.Util.loadPassword(bindCredential));
+            }
+            catch (Exception e1)
+            {
+               log.error("Exception in decrypting bindCredential:",e1);
+               return;
+            }
+         String securityDomain = (String) options.get(SECURITY_DOMAIN_OPT);
+         if (securityDomain != null)
+         {
+            try
+            {
+               ObjectName serviceName = new ObjectName(securityDomain);
+               char[] tmp = MappingProvidersDecodeAction.decode(bindCredential, serviceName);
+               bindCredential = new String(tmp);
+            } 
+            catch (Exception e)
+            {
+               log.error("Exception in decrypting bindCredential:",e);
+               return;
+            }
+         }
+         
+         InitialLdapContext ctx;
+         try
+         {
+            ctx = this.constructInitialLdapContext(bindDN, bindCredential);
+         }
+         catch (NamingException e)
+         {
+            throw new RuntimeException(e);
+         } 
+         
+         String timeLimit = (String) options.get(SEARCH_TIME_LIMIT_OPT);
+         if (timeLimit != null)
+         {
+            try
+            {
+               searchTimeLimit = Integer.parseInt(timeLimit);
+            }
+            catch (NumberFormatException e)
+            {
+               if (trace)
+                  log.trace("Failed to parse: " + timeLimit + ", using searchTimeLimit=" + searchTimeLimit, e);
+            }
+         }
+         if(searchTimeLimit == 0)
+            searchTimeLimit = 10000;
+         
+         String baseDN = (String) options.get(BASE_CTX_DN); 
+         String baseFilter = (String) options.get(BASE_FILTER_OPT);
+         
+         SearchControls constraints = new SearchControls();
+         constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
+         
+         constraints.setTimeLimit(searchTimeLimit);
+         
+         String attributePattern = (String) options.get(ATTRIBUTE_LIST_OPT);
+         
+         //Take care of the attributes we want
+         String neededAttributes[] = getNeededAttributes(attributePattern);
+         
+         constraints.setReturningAttributes(neededAttributes);
+
+         NamingEnumeration results = null;
+
+         Object[] filterArgs = {user};
+         try
+         {
+            if(baseDN == null)
+               throw new NamingException(BASE_CTX_DN + " is null");
+            results = ctx.search(baseDN, baseFilter, filterArgs, constraints);
+            if (results.hasMore() == false)
+            {
+               results.close();
+               throw new NamingException("Search of baseDN(" + baseDN + ") found no matches");
+            } 
+            SearchResult sr = (SearchResult) results.next();
+            String name = sr.getName();
+            String userDN = null;
+            if (sr.isRelative() == true)
+               userDN = name + "," + baseDN;
+            else
+               throw new NamingException("Can't follow referal for authentication: " + name);
+
+            results.close();
+            
+            //Finished Authentication.  Lets look for the attributes
+            filterArgs = new Object[]{user, userDN};
+            results = ctx.search(userDN, baseFilter, filterArgs, constraints);
+            try
+            {
+               while (results.hasMore())
+               {
+                  sr = (SearchResult) results.next(); 
+                  Attributes attributes = sr.getAttributes();
+                  NamingEnumeration<? extends javax.naming.directory.Attribute> ne = attributes.getAll();
+                  
+                  while(ne != null && ne.hasMoreElements())
+                  {
+                     javax.naming.directory.Attribute ldapAtt = ne.next();
+                     if("mail".equalsIgnoreCase(ldapAtt.getID()))
+                     {
+                        attributeList.add(AttributeFactory.createEmailAddress((String) ldapAtt.get()));   
+                     }
+                     else
+                        attributeList.add(AttributeFactory.createAttribute(ldapAtt.getID(), 
+                              (String)ldapAtt.get())); 
+                  } 
+               }       
+            }
+            finally
+            {
+               if (results != null)
+                  results.close();
+            }            
+         }catch(NamingException ne)
+         {
+            log.error(ne);
+            return;
+         } 
+         results = null;
+      }
+      
+      mappedObject.addAll(attributeList);
+      mappingResult.setMappedObject(mappedObject);   
+   }
+
+   public void setMappingResult(MappingResult<List<Attribute<String>>> result)
+   {
+      this.mappingResult = result;
+   }
+
+   public boolean supports(Class<?> clazz)
+   { 
+      if(Attribute.class.isAssignableFrom(clazz))
+        return true;
+      
+      return false;
+   } 
+   
+   
+   @SuppressWarnings("unchecked")
+   private InitialLdapContext constructInitialLdapContext(String dn, Object credential) throws NamingException
+   {
+      Properties env = new Properties();
+      Iterator iter = options.entrySet().iterator();
+      while (iter.hasNext())
+      {
+         Entry entry = (Entry) iter.next();
+         env.put(entry.getKey(), entry.getValue());
+      }
+
+      // Set defaults for key values if they are missing
+      String factoryName = env.getProperty(Context.INITIAL_CONTEXT_FACTORY);
+      if (factoryName == null)
+      {
+         factoryName = "com.sun.jndi.ldap.LdapCtxFactory";
+         env.setProperty(Context.INITIAL_CONTEXT_FACTORY, factoryName);
+      }
+      String authType = env.getProperty(Context.SECURITY_AUTHENTICATION);
+      if (authType == null)
+         env.setProperty(Context.SECURITY_AUTHENTICATION, "simple");
+      String protocol = env.getProperty(Context.SECURITY_PROTOCOL);
+      String providerURL = (String) options.get(Context.PROVIDER_URL);
+      if (providerURL == null)
+         providerURL = "ldap://localhost:" + ((protocol != null && protocol.equals("ssl")) ? "636" : "389");
+
+      env.setProperty(Context.PROVIDER_URL, providerURL);
+      // JBAS-3555, allow anonymous login with no bindDN and bindCredential
+      if (dn != null)
+         env.setProperty(Context.SECURITY_PRINCIPAL, dn);
+      if (credential != null)
+         env.put(Context.SECURITY_CREDENTIALS, credential);
+      traceLdapEnv(env);
+      return new InitialLdapContext(env, null);
+   }
+   
+   private void traceLdapEnv(Properties env)
+   {
+      if (trace)
+      {
+         Properties tmp = new Properties();
+         tmp.putAll(env);
+         tmp.setProperty(Context.SECURITY_CREDENTIALS, "***");
+         log.trace("Logging into LDAP server, env=" + tmp.toString());
+      }
+   }
+   
+   private String[] getNeededAttributes(String commaSeparatedList)
+   {
+      ArrayList<String> arrayList = new ArrayList<String>();
+      StringTokenizer st = new StringTokenizer(commaSeparatedList,",");
+      while(st.hasMoreTokens())
+      {
+         arrayList.add(st.nextToken());
+      }
+      String[] strArr = new String[arrayList.size()];
+      return arrayList.toArray(strArr); 
+   }
+}
\ No newline at end of file

Deleted: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/plugins/JBossAuthorizationManager.java
===================================================================
--- projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/security/plugins/JBossAuthorizationManager.java	2009-07-21 21:59:08 UTC (rev 91524)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/plugins/JBossAuthorizationManager.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -1,530 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source
- * Copyright 2005, JBoss Inc., and individual contributors as indicated
- * by the @authors tag. See the copyright.txt in the distribution for a
- * full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jboss.security.plugins;
- 
-import static org.jboss.security.SecurityConstants.ROLES_IDENTIFIER;
-
-import java.security.Principal;
-import java.security.acl.Group;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.locks.Lock;
-import java.util.concurrent.locks.ReentrantLock;
-
-import javax.security.auth.Subject;
-import javax.security.auth.callback.Callback;
-import javax.security.auth.callback.CallbackHandler;
-
-import org.jboss.logging.Logger;
-import org.jboss.security.AnybodyPrincipal;
-import org.jboss.security.AuthorizationManager;
-import org.jboss.security.NobodyPrincipal;
-import org.jboss.security.RunAs;
-import org.jboss.security.SecurityConstants;
-import org.jboss.security.SecurityContext;
-import org.jboss.security.SecurityRolesAssociation;
-import org.jboss.security.SimplePrincipal;
-import org.jboss.security.acl.ACLContext;
-import org.jboss.security.authorization.AuthorizationContext;
-import org.jboss.security.authorization.AuthorizationException;
-import org.jboss.security.authorization.EntitlementHolder;
-import org.jboss.security.authorization.Permission;
-import org.jboss.security.authorization.Resource;
-import org.jboss.security.callbacks.SecurityContextCallback;
-import org.jboss.security.identity.Identity;
-import org.jboss.security.identity.Role;
-import org.jboss.security.identity.RoleGroup;
-import org.jboss.security.identity.plugins.SimpleRole;
-import org.jboss.security.identity.plugins.SimpleRoleGroup;
-import org.jboss.security.mapping.MappingContext;
-import org.jboss.security.mapping.MappingManager;
-import org.jboss.security.plugins.acl.JBossACLContext;
-import org.jboss.security.plugins.authorization.JBossAuthorizationContext;
-import org.jboss.util.NotImplementedException;
-
-//$Id$
-
-/**
- *  Authorization Manager implementation
- *  @author <a href="mailto:Anil.Saldhana at jboss.org">Anil Saldhana</a>
- *  @since  Jan 3, 2006 
- *  @version $Revision$
- */
-public class JBossAuthorizationManager 
-implements AuthorizationManager 
-{  
-   private final String securityDomain;  
-   
-   private static Logger log = Logger.getLogger(JBossAuthorizationManager.class);
-   
-   protected boolean trace = log.isTraceEnabled(); 
-   
-   private AuthorizationContext authorizationContext = null;
-   
-   private ACLContext aclContext = null;
-   
-   //Lock deals with synchronization of authorizationContext usage
-   private final Lock lock = new ReentrantLock();
-   
-   public JBossAuthorizationManager(String securityDomainName)
-   {
-      this.securityDomain = securityDomainName;
-   } 
-   
-   /**
-    * @see AuthorizationManager#authorize(Resource)
-    */
-   public int authorize(Resource resource) throws AuthorizationException
-   {
-      validateResource(resource);
-      Subject subject = SubjectActions.getActiveSubject();
-      return internalAuthorization(resource,subject, null);
-   }
-   
-   /**
-    * @see AuthorizationManager#authorize(Resource, Subject)
-    */
-   public int authorize(Resource resource, Subject subject)
-   throws AuthorizationException
-   {
-      return internalAuthorization(resource, subject, null);
-   }
-   
-   /**
-    * @see AuthorizationManager#authorize(Resource, Subject, RoleGroup) 
-    */
-   public int authorize(Resource resource, Subject subject,
-         RoleGroup role) throws AuthorizationException
-   {
-      this.validateResource(resource);
-      return internalAuthorization(resource, subject, role);
-   }
-
-   /**
-    * @see AuthorizationManager#authorize(Resource, Subject, Group)
-    */
-   public int authorize(Resource resource, Subject subject, 
-         Group roleGroup) throws AuthorizationException
-   { 
-      this.validateResource(resource);
-      return internalAuthorization(resource, subject, getRoleGroup(roleGroup));
-   }
-
-   /*
-    * (non-Javadoc)
-    * 
-    * @see org.jboss.security.AuthorizationManager#authorize(org.jboss.security.authorization.Resource, 
-    *               org.jboss.security.identity.Identity, org.jboss.security.authorization.Permission)
-    */
-   public int authorize(Resource resource, Identity identity, Permission permission) 
-      throws AuthorizationException
-   {
-      if(this.aclContext == null)
-         this.aclContext = new JBossACLContext(this.securityDomain);
-      return aclContext.authorize(resource, identity, permission);
-   }
-
-   /**
-    * @see AuthorizationManager#entitlements(Class, Resource, Identity)
-    */
-   public <T> EntitlementHolder<T> getEntitlements(Class<T> clazz,
-         Resource resource, Identity identity)
-   throws AuthorizationException
-   {
-      if(this.aclContext == null)
-         this.aclContext = new JBossACLContext(this.securityDomain);
-      return aclContext.getEntitlements(clazz, resource, identity);
-   }
-
-   
-   /** Does the current Subject have a role(a Principal) that equates to one
-    of the role names. This method obtains the Group named 'Roles' from
-    the principal set of the currently authenticated Subject as determined
-    by the SecurityAssociation.getSubject() method and then creates a
-    SimplePrincipal for each name in roleNames. If the role is a member of the
-    Roles group, then the user has the role. This requires that the caller
-    establish the correct SecurityAssociation subject prior to calling this
-    method. In the past this was done as a side-effect of an isValid() call,
-    but this is no longer the case.
-    
-    @param principal - ignored. The current authenticated Subject determines
-    the active user and assigned user roles.
-    @param rolePrincipals - a Set of Principals for the roles to check.
-    
-    @see java.security.acl.Group;
-    @see Subject#getPrincipals()
-    */
-   public boolean doesUserHaveRole(Principal principal, Set<Principal> rolePrincipals)
-   {
-      boolean hasRole = false;
-      RoleGroup roles = this.getCurrentRoles(principal);
-      if( trace )
-         log.trace("doesUserHaveRole(Set), roles: "+roles);
-      if(roles != null)
-      {
-         Iterator<Principal> iter = rolePrincipals.iterator();
-         while( hasRole == false && iter.hasNext() )
-         {
-            Principal role = iter.next();
-            hasRole = doesRoleGroupHaveRole(role, roles);
-            if( trace )
-               log.trace("hasRole("+role+")="+hasRole);
-         }
-         if( trace )
-            log.trace("hasRole="+hasRole);
-      } 
-      return hasRole;
-   }
-   
-   /** Does the current Subject have a role(a Principal) that equates to one
-    of the role names.
-    
-    @see #doesUserHaveRole(Principal, Set)
-    
-    @param principal - ignored. The current authenticated Subject determines
-    the active user and assigned user roles.
-    @param role - the application domain role that the principal is to be
-    validated against.
-    @return true if the active principal has the role, false otherwise.
-    */
-   public boolean doesUserHaveRole(Principal principal, Principal role)
-   {
-      boolean hasRole = false;
-      RoleGroup roles = this.getCurrentRoles(principal);
-      hasRole = doesRoleGroupHaveRole(role, roles); 
-      return hasRole;
-   } 
-   
-   /** Return the set of domain roles the current active Subject 'Roles' group
-    found in the subject Principals set.
-    
-    @param principal - ignored. The current authenticated Subject determines
-    the active user and assigned user roles.
-    @return The Set<Principal> for the application domain roles that the
-    principal has been assigned.
-    */
-   public Set<Principal> getUserRoles(Principal principal)
-   { 
-      RoleGroup userRoles = getCurrentRoles(principal);
-      return this.getRolesAsSet(userRoles); 
-   }  
-     
-   
-   /** Check that the indicated application domain role is a member of the
-    user's assigned roles. This handles the special AnybodyPrincipal and
-    NobodyPrincipal independent of the Group implementation.
-    
-    @param role , the application domain role required for access
-    @param userRoles , the set of roles assigned to the user
-    @return true if role is in userRoles or an AnybodyPrincipal instance, false
-    if role is a NobodyPrincipal or no a member of userRoles
-    */
-   protected boolean doesRoleGroupHaveRole(Principal role, RoleGroup userRoles)
-   {
-      // First check that role is not a NobodyPrincipal
-      if (role instanceof NobodyPrincipal)
-         return false;
-      
-      // Check for inclusion in the user's role set
-      boolean isMember = userRoles.containsRole(new SimpleRole(role.getName())); 
-      if (isMember == false)
-      {   // Check the AnybodyPrincipal special cases
-         isMember = (role instanceof AnybodyPrincipal);
-      }
-      
-      return isMember;
-   } 
-   
-   @Override
-   public String toString()
-   {
-      StringBuffer buf = new StringBuffer();
-      buf.append("[AuthorizationManager:class=").append(getClass().getName());
-      buf.append(":").append(this.securityDomain).append(":");
-      buf.append("]");
-      return buf.toString();
-   } 
-   
-   //Value added methods
-   /**
-    * Set the AuthorizationContext
-    */
-   public void setAuthorizationContext(AuthorizationContext ac)
-   {
-      if(ac == null)
-         throw new IllegalArgumentException("AuthorizationContext is null");
-      lock.lock();
-      try
-      {  
-         String sc = ac.getSecurityDomain();
-         if(this.securityDomain.equals(sc) == false)
-            throw new IllegalArgumentException("The Security Domain "+ sc 
-                  + " does not match with " + this.securityDomain);
-         this.authorizationContext = ac;  
-      }
-      finally
-      {
-         lock.unlock();
-      }
-   }
-   
-   public String getSecurityDomain()
-   {
-      return this.securityDomain;
-   }
-   
-
-   /**
-    * @see AuthorizationManager#getTargetRoles(Principal, Map)
-    */
-   public Group getTargetRoles(Principal targetPrincipal, Map<String,Object> contextMap)
-   {
-      throw new NotImplementedException();
-   }
-
-   //Private Methods
-   private HashSet<Principal> getRolesAsSet(RoleGroup roles)
-   {
-      HashSet<Principal> userRoles = null;
-      if( roles != null )
-      {
-         userRoles = new HashSet<Principal>();
-         List<Role> rolesList = roles.getRoles();
-         for(Role r: rolesList)
-         {
-            userRoles.add(new SimplePrincipal(r.getRoleName()));
-         } 
-      }
-      return userRoles;
-   } 
-
-   /**
-    * @see AuthorizationManager#getSubjectRoles(Subject, CallbackHandler)
-    */
-   public RoleGroup getSubjectRoles(Subject authenticatedSubject, CallbackHandler cbh)
-   {
-      if(authenticatedSubject == null)
-         return null;
-      
-      //Ask the CBH for the SecurityContext
-      SecurityContextCallback scb = new SecurityContextCallback();
-      try
-      {
-         cbh.handle(new Callback[]{scb});
-      }
-      catch (Exception e)
-      {
-         log.trace("Exception in getSubjectRoles:",e); 
-         throw new RuntimeException(e);
-      } 
-      SecurityContext sc = scb.getSecurityContext();
-      
-      //Handle the case of Incoming RunAs
-      Principal callerPrincipal = null;
-      RunAs callerRunAs = sc.getIncomingRunAs();
-      if(callerRunAs != null)
-      {
-         callerPrincipal = new SimplePrincipal(callerRunAs.getName()); 
-      }
-      
-      RoleGroup roles = this.getCurrentRoles(callerPrincipal, authenticatedSubject, sc);
-      if(roles == null)
-         roles = new SimpleRoleGroup(SecurityConstants.ROLES_IDENTIFIER);
-      return roles; 
-   }  
-   
-   /*
-    * Get the current role group from the security context or
-    * the Subject
-    * @param principal The Principal in question
-    */
-   private RoleGroup getCurrentRoles(Principal principal)
-   { 
-      //Check that the caller is authenticated to the current thread
-      Subject subject = SubjectActions.getActiveSubject();  
-      
-      //Deal with the security context
-      SecurityContext sc = SubjectActions.getSecurityContext(); 
-      if(sc == null)
-      {
-         sc = new JBossSecurityContext(securityDomain); 
-         SubjectActions.setSecurityContext(sc);   
-      } 
-      
-      return getCurrentRoles(principal,subject,sc); 
-   } 
-   
-   private RoleGroup getCurrentRoles(Principal principal, Subject subject, SecurityContext sc)
-   {
-      if(subject == null)
-         throw new IllegalArgumentException("Subject passed is null");
-      if(sc == null)
-         throw new IllegalArgumentException("Sec Ctx sc passed is null");
-      
-      Group subjectRoles = getGroupFromSubject(subject);
-      
-      boolean emptyContextRoles = false;
-      
-      RoleGroup userRoles = sc.getUtil().getRoles();
-      //Group userRoles = (Group)sc.getData().get(ROLES_IDENTIFIER);
-      if(userRoles == null || "true".equalsIgnoreCase(SubjectActions.getRefreshSecurityContextRoles()))
-         emptyContextRoles = true;
-      userRoles = copyGroups(userRoles, subjectRoles); 
-      
-      /**
-       * Update the roles in the SecurityContext and
-       * allow mapping rules be applied only if the SC roles
-       * and the subject roles are not the same
-       */
-      if(subjectRoles != userRoles || emptyContextRoles)
-      { 
-         MappingManager mm = sc.getMappingManager();
-         MappingContext<RoleGroup> mc = mm.getMappingContext(RoleGroup.class);
-        
-         RoleGroup mappedUserRoles = userRoles;
-         if(mc != null && mc.hasModules())
-         {
-            Map<String,Object> contextMap = new HashMap<String,Object>();
-            contextMap.put(SecurityConstants.ROLES_IDENTIFIER, userRoles);
-            if(principal != null)
-              contextMap.put(SecurityConstants.PRINCIPAL_IDENTIFIER, principal);
-            //Append any deployment role->principals configuration done by the user
-            contextMap.put(SecurityConstants.DEPLOYMENT_PRINCIPAL_ROLES_MAP,
-                  SecurityRolesAssociation.getSecurityRoles());
-            
-            //Append the principals also
-            contextMap.put(SecurityConstants.PRINCIPALS_SET_IDENTIFIER, subject.getPrincipals());
-            if(trace)
-               log.trace("Roles before mapping:"+ userRoles);
-            
-            if(userRoles == null)
-               userRoles = this.getEmptyRoleGroup();
-            
-            mc.performMapping(contextMap, userRoles);
-            mappedUserRoles = mc.getMappingResult().getMappedObject();
-            if(trace)
-               log.trace("Roles after mapping:"+ userRoles);
-         } 
-         sc.getData().put(ROLES_IDENTIFIER, mappedUserRoles); 
-      } 
-      
-      //Ensure that the security context has the roles
-      if(sc.getUtil().getRoles() == null)
-         sc.getUtil().setRoles(userRoles);
-
-      //Send the final processed (mapping applied) roles
-      return userRoles;   
-   }
-   
-   /**
-    * Copy the principals from the second group into the first.
-    * If the first group is null and the second group is not, the
-    * first group will be made equal to the second group
-    * @param source
-    * @param toCopy
-    */
-   private RoleGroup copyGroups(RoleGroup source, Group toCopy)
-   {
-      if(toCopy == null)
-         return source;
-      if(source == null && toCopy != null) 
-         source = this.getEmptyRoleGroup();
-      Enumeration<? extends Principal> en = toCopy.members();
-      while(en.hasMoreElements())
-      {
-         source.addRole(new SimpleRole(en.nextElement().getName())); 
-      }
-       
-      return source;
-   }
-   
-   private int internalAuthorization(final Resource resource, Subject subject,
-         RoleGroup role)
-   throws AuthorizationException
-   {
-      lock.lock();
-      try
-      {
-         if(this.authorizationContext == null)
-            this.authorizationContext = new JBossAuthorizationContext(this.securityDomain);
-         return this.authorizationContext.authorize(resource, subject, role); 
-      }
-      finally
-      {
-         lock.unlock();
-      } 
-   }
-   
-   /**
-    * Get the Subject roles by looking for a Group called 'Roles'
-    * @param theSubject - the Subject to search for roles
-    * @return the Group contain the subject roles if found, null otherwise
-    */
-   private Group getGroupFromSubject(Subject theSubject)
-   {
-      if(theSubject == null)
-         throw new IllegalArgumentException("Subject is null");
-      Set<Group> subjectGroups = theSubject.getPrincipals(Group.class);
-      Iterator<Group> iter = subjectGroups.iterator();
-      Group roles = null;
-      while( iter.hasNext() )
-      {
-         Group grp = iter.next();
-         String name = grp.getName();
-         if( name.equals(ROLES_IDENTIFIER) )
-            roles = grp;
-      }
-      return roles;
-   } 
-   
-   private RoleGroup getRoleGroup(Group roleGroup)
-   {
-      if(roleGroup == null)
-         throw new IllegalArgumentException("roleGroup is null");
-      SimpleRoleGroup srg = new SimpleRoleGroup(roleGroup.getName());
-      Enumeration<? extends Principal> principals = roleGroup.members();
-      while(principals.hasMoreElements())
-      {
-         srg.getRoles().add(new SimpleRole(principals.nextElement().getName()));
-      }
-      return srg;  
-   }
-   
-
-   private void validateResource(Resource resource)
-   {
-      if(resource == null)
-         throw new IllegalArgumentException("resource is null");
-      if(resource.getMap() == null)
-         throw new IllegalArgumentException("resource has null context map");
-   }
-   
-   private RoleGroup getEmptyRoleGroup()
-   {
-      return new SimpleRoleGroup(SecurityConstants.ROLES_IDENTIFIER);
-   }
-}
\ No newline at end of file

Copied: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/plugins/JBossAuthorizationManager.java (from rev 92162, projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/security/plugins/JBossAuthorizationManager.java)
===================================================================
--- projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/plugins/JBossAuthorizationManager.java	                        (rev 0)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/plugins/JBossAuthorizationManager.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -0,0 +1,531 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005, JBoss Inc., and individual contributors as indicated
+ * by the @authors tag. See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.security.plugins;
+ 
+import static org.jboss.security.SecurityConstants.ROLES_IDENTIFIER;
+
+import java.security.Principal;
+import java.security.acl.Group;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
+
+import javax.security.auth.Subject;
+import javax.security.auth.callback.Callback;
+import javax.security.auth.callback.CallbackHandler;
+
+import org.jboss.logging.Logger;
+import org.jboss.security.AnybodyPrincipal;
+import org.jboss.security.AuthorizationManager;
+import org.jboss.security.NobodyPrincipal;
+import org.jboss.security.RunAs;
+import org.jboss.security.SecurityConstants;
+import org.jboss.security.SecurityContext;
+import org.jboss.security.SecurityRolesAssociation;
+import org.jboss.security.SimplePrincipal;
+import org.jboss.security.acl.ACLContext;
+import org.jboss.security.authorization.AuthorizationContext;
+import org.jboss.security.authorization.AuthorizationException;
+import org.jboss.security.authorization.EntitlementHolder;
+import org.jboss.security.authorization.Permission;
+import org.jboss.security.authorization.Resource;
+import org.jboss.security.callbacks.SecurityContextCallback;
+import org.jboss.security.identity.Identity;
+import org.jboss.security.identity.Role;
+import org.jboss.security.identity.RoleGroup;
+import org.jboss.security.identity.plugins.SimpleRole;
+import org.jboss.security.identity.plugins.SimpleRoleGroup;
+import org.jboss.security.mapping.MappingContext;
+import org.jboss.security.mapping.MappingManager;
+import org.jboss.security.mapping.MappingType;
+import org.jboss.security.plugins.acl.JBossACLContext;
+import org.jboss.security.plugins.authorization.JBossAuthorizationContext;
+import org.jboss.util.NotImplementedException;
+
+//$Id$
+
+/**
+ *  Authorization Manager implementation
+ *  @author <a href="mailto:Anil.Saldhana at jboss.org">Anil Saldhana</a>
+ *  @since  Jan 3, 2006 
+ *  @version $Revision$
+ */
+public class JBossAuthorizationManager 
+implements AuthorizationManager 
+{  
+   private final String securityDomain;  
+   
+   private static Logger log = Logger.getLogger(JBossAuthorizationManager.class);
+   
+   protected boolean trace = log.isTraceEnabled(); 
+   
+   private AuthorizationContext authorizationContext = null;
+   
+   private ACLContext aclContext = null;
+   
+   //Lock deals with synchronization of authorizationContext usage
+   private final Lock lock = new ReentrantLock();
+   
+   public JBossAuthorizationManager(String securityDomainName)
+   {
+      this.securityDomain = securityDomainName;
+   } 
+   
+   /**
+    * @see AuthorizationManager#authorize(Resource)
+    */
+   public int authorize(Resource resource) throws AuthorizationException
+   {
+      validateResource(resource);
+      Subject subject = SubjectActions.getActiveSubject();
+      return internalAuthorization(resource,subject, null);
+   }
+   
+   /**
+    * @see AuthorizationManager#authorize(Resource, Subject)
+    */
+   public int authorize(Resource resource, Subject subject)
+   throws AuthorizationException
+   {
+      return internalAuthorization(resource, subject, null);
+   }
+   
+   /**
+    * @see AuthorizationManager#authorize(Resource, Subject, RoleGroup) 
+    */
+   public int authorize(Resource resource, Subject subject,
+         RoleGroup role) throws AuthorizationException
+   {
+      this.validateResource(resource);
+      return internalAuthorization(resource, subject, role);
+   }
+
+   /**
+    * @see AuthorizationManager#authorize(Resource, Subject, Group)
+    */
+   public int authorize(Resource resource, Subject subject, 
+         Group roleGroup) throws AuthorizationException
+   { 
+      this.validateResource(resource);
+      return internalAuthorization(resource, subject, getRoleGroup(roleGroup));
+   }
+
+   /*
+    * (non-Javadoc)
+    * 
+    * @see org.jboss.security.AuthorizationManager#authorize(org.jboss.security.authorization.Resource, 
+    *               org.jboss.security.identity.Identity, org.jboss.security.authorization.Permission)
+    */
+   public int authorize(Resource resource, Identity identity, Permission permission) 
+      throws AuthorizationException
+   {
+      if(this.aclContext == null)
+         this.aclContext = new JBossACLContext(this.securityDomain);
+      return aclContext.authorize(resource, identity, permission);
+   }
+
+   /**
+    * @see AuthorizationManager#entitlements(Class, Resource, Identity)
+    */
+   public <T> EntitlementHolder<T> getEntitlements(Class<T> clazz,
+         Resource resource, Identity identity)
+   throws AuthorizationException
+   {
+      if(this.aclContext == null)
+         this.aclContext = new JBossACLContext(this.securityDomain);
+      return aclContext.getEntitlements(clazz, resource, identity);
+   }
+
+   
+   /** Does the current Subject have a role(a Principal) that equates to one
+    of the role names. This method obtains the Group named 'Roles' from
+    the principal set of the currently authenticated Subject as determined
+    by the SecurityAssociation.getSubject() method and then creates a
+    SimplePrincipal for each name in roleNames. If the role is a member of the
+    Roles group, then the user has the role. This requires that the caller
+    establish the correct SecurityAssociation subject prior to calling this
+    method. In the past this was done as a side-effect of an isValid() call,
+    but this is no longer the case.
+    
+    @param principal - ignored. The current authenticated Subject determines
+    the active user and assigned user roles.
+    @param rolePrincipals - a Set of Principals for the roles to check.
+    
+    @see java.security.acl.Group;
+    @see Subject#getPrincipals()
+    */
+   public boolean doesUserHaveRole(Principal principal, Set<Principal> rolePrincipals)
+   {
+      boolean hasRole = false;
+      RoleGroup roles = this.getCurrentRoles(principal);
+      if( trace )
+         log.trace("doesUserHaveRole(Set), roles: "+roles);
+      if(roles != null)
+      {
+         Iterator<Principal> iter = rolePrincipals.iterator();
+         while( hasRole == false && iter.hasNext() )
+         {
+            Principal role = iter.next();
+            hasRole = doesRoleGroupHaveRole(role, roles);
+            if( trace )
+               log.trace("hasRole("+role+")="+hasRole);
+         }
+         if( trace )
+            log.trace("hasRole="+hasRole);
+      } 
+      return hasRole;
+   }
+   
+   /** Does the current Subject have a role(a Principal) that equates to one
+    of the role names.
+    
+    @see #doesUserHaveRole(Principal, Set)
+    
+    @param principal - ignored. The current authenticated Subject determines
+    the active user and assigned user roles.
+    @param role - the application domain role that the principal is to be
+    validated against.
+    @return true if the active principal has the role, false otherwise.
+    */
+   public boolean doesUserHaveRole(Principal principal, Principal role)
+   {
+      boolean hasRole = false;
+      RoleGroup roles = this.getCurrentRoles(principal);
+      hasRole = doesRoleGroupHaveRole(role, roles); 
+      return hasRole;
+   } 
+   
+   /** Return the set of domain roles the current active Subject 'Roles' group
+    found in the subject Principals set.
+    
+    @param principal - ignored. The current authenticated Subject determines
+    the active user and assigned user roles.
+    @return The Set<Principal> for the application domain roles that the
+    principal has been assigned.
+    */
+   public Set<Principal> getUserRoles(Principal principal)
+   { 
+      RoleGroup userRoles = getCurrentRoles(principal);
+      return this.getRolesAsSet(userRoles); 
+   }  
+     
+   
+   /** Check that the indicated application domain role is a member of the
+    user's assigned roles. This handles the special AnybodyPrincipal and
+    NobodyPrincipal independent of the Group implementation.
+    
+    @param role , the application domain role required for access
+    @param userRoles , the set of roles assigned to the user
+    @return true if role is in userRoles or an AnybodyPrincipal instance, false
+    if role is a NobodyPrincipal or no a member of userRoles
+    */
+   protected boolean doesRoleGroupHaveRole(Principal role, RoleGroup userRoles)
+   {
+      // First check that role is not a NobodyPrincipal
+      if (role instanceof NobodyPrincipal)
+         return false;
+      
+      // Check for inclusion in the user's role set
+      boolean isMember = userRoles.containsRole(new SimpleRole(role.getName())); 
+      if (isMember == false)
+      {   // Check the AnybodyPrincipal special cases
+         isMember = (role instanceof AnybodyPrincipal);
+      }
+      
+      return isMember;
+   } 
+   
+   @Override
+   public String toString()
+   {
+      StringBuffer buf = new StringBuffer();
+      buf.append("[AuthorizationManager:class=").append(getClass().getName());
+      buf.append(":").append(this.securityDomain).append(":");
+      buf.append("]");
+      return buf.toString();
+   } 
+   
+   //Value added methods
+   /**
+    * Set the AuthorizationContext
+    */
+   public void setAuthorizationContext(AuthorizationContext ac)
+   {
+      if(ac == null)
+         throw new IllegalArgumentException("AuthorizationContext is null");
+      lock.lock();
+      try
+      {  
+         String sc = ac.getSecurityDomain();
+         if(this.securityDomain.equals(sc) == false)
+            throw new IllegalArgumentException("The Security Domain "+ sc 
+                  + " does not match with " + this.securityDomain);
+         this.authorizationContext = ac;  
+      }
+      finally
+      {
+         lock.unlock();
+      }
+   }
+   
+   public String getSecurityDomain()
+   {
+      return this.securityDomain;
+   }
+   
+
+   /**
+    * @see AuthorizationManager#getTargetRoles(Principal, Map)
+    */
+   public Group getTargetRoles(Principal targetPrincipal, Map<String,Object> contextMap)
+   {
+      throw new NotImplementedException();
+   }
+
+   //Private Methods
+   private HashSet<Principal> getRolesAsSet(RoleGroup roles)
+   {
+      HashSet<Principal> userRoles = null;
+      if( roles != null )
+      {
+         userRoles = new HashSet<Principal>();
+         List<Role> rolesList = roles.getRoles();
+         for(Role r: rolesList)
+         {
+            userRoles.add(new SimplePrincipal(r.getRoleName()));
+         } 
+      }
+      return userRoles;
+   } 
+
+   /**
+    * @see AuthorizationManager#getSubjectRoles(Subject, CallbackHandler)
+    */
+   public RoleGroup getSubjectRoles(Subject authenticatedSubject, CallbackHandler cbh)
+   {
+      if(authenticatedSubject == null)
+         return null;
+      
+      //Ask the CBH for the SecurityContext
+      SecurityContextCallback scb = new SecurityContextCallback();
+      try
+      {
+         cbh.handle(new Callback[]{scb});
+      }
+      catch (Exception e)
+      {
+         log.trace("Exception in getSubjectRoles:",e); 
+         throw new RuntimeException(e);
+      } 
+      SecurityContext sc = scb.getSecurityContext();
+      
+      //Handle the case of Incoming RunAs
+      Principal callerPrincipal = null;
+      RunAs callerRunAs = sc.getIncomingRunAs();
+      if(callerRunAs != null)
+      {
+         callerPrincipal = new SimplePrincipal(callerRunAs.getName()); 
+      }
+      
+      RoleGroup roles = this.getCurrentRoles(callerPrincipal, authenticatedSubject, sc);
+      if(roles == null)
+         roles = new SimpleRoleGroup(SecurityConstants.ROLES_IDENTIFIER);
+      return roles; 
+   }  
+   
+   /*
+    * Get the current role group from the security context or
+    * the Subject
+    * @param principal The Principal in question
+    */
+   private RoleGroup getCurrentRoles(Principal principal)
+   { 
+      //Check that the caller is authenticated to the current thread
+      Subject subject = SubjectActions.getActiveSubject();  
+      
+      //Deal with the security context
+      SecurityContext sc = SubjectActions.getSecurityContext(); 
+      if(sc == null)
+      {
+         sc = new JBossSecurityContext(securityDomain); 
+         SubjectActions.setSecurityContext(sc);   
+      } 
+      
+      return getCurrentRoles(principal,subject,sc); 
+   } 
+   
+   private RoleGroup getCurrentRoles(Principal principal, Subject subject, SecurityContext sc)
+   {
+      if(subject == null)
+         throw new IllegalArgumentException("Subject passed is null");
+      if(sc == null)
+         throw new IllegalArgumentException("Sec Ctx sc passed is null");
+      
+      Group subjectRoles = getGroupFromSubject(subject);
+      
+      boolean emptyContextRoles = false;
+      
+      RoleGroup userRoles = sc.getUtil().getRoles();
+      //Group userRoles = (Group)sc.getData().get(ROLES_IDENTIFIER);
+      if(userRoles == null || "true".equalsIgnoreCase(SubjectActions.getRefreshSecurityContextRoles()))
+         emptyContextRoles = true;
+      userRoles = copyGroups(userRoles, subjectRoles); 
+      
+      /**
+       * Update the roles in the SecurityContext and
+       * allow mapping rules be applied only if the SC roles
+       * and the subject roles are not the same
+       */
+      if(subjectRoles != userRoles || emptyContextRoles)
+      { 
+         MappingManager mm = sc.getMappingManager();
+         MappingContext<RoleGroup> mc = mm.getMappingContext(MappingType.ROLE.name());
+        
+         RoleGroup mappedUserRoles = userRoles;
+         if(mc != null && mc.hasModules())
+         {
+            Map<String,Object> contextMap = new HashMap<String,Object>();
+            contextMap.put(SecurityConstants.ROLES_IDENTIFIER, userRoles);
+            if(principal != null)
+              contextMap.put(SecurityConstants.PRINCIPAL_IDENTIFIER, principal);
+            //Append any deployment role->principals configuration done by the user
+            contextMap.put(SecurityConstants.DEPLOYMENT_PRINCIPAL_ROLES_MAP,
+                  SecurityRolesAssociation.getSecurityRoles());
+            
+            //Append the principals also
+            contextMap.put(SecurityConstants.PRINCIPALS_SET_IDENTIFIER, subject.getPrincipals());
+            if(trace)
+               log.trace("Roles before mapping:"+ userRoles);
+            
+            if(userRoles == null)
+               userRoles = this.getEmptyRoleGroup();
+            
+            mc.performMapping(contextMap, userRoles);
+            mappedUserRoles = mc.getMappingResult().getMappedObject();
+            if(trace)
+               log.trace("Roles after mapping:"+ userRoles);
+         } 
+         sc.getData().put(ROLES_IDENTIFIER, mappedUserRoles); 
+      } 
+      
+      //Ensure that the security context has the roles
+      if(sc.getUtil().getRoles() == null)
+         sc.getUtil().setRoles(userRoles);
+
+      //Send the final processed (mapping applied) roles
+      return userRoles;   
+   }
+   
+   /**
+    * Copy the principals from the second group into the first.
+    * If the first group is null and the second group is not, the
+    * first group will be made equal to the second group
+    * @param source
+    * @param toCopy
+    */
+   private RoleGroup copyGroups(RoleGroup source, Group toCopy)
+   {
+      if(toCopy == null)
+         return source;
+      if(source == null && toCopy != null) 
+         source = this.getEmptyRoleGroup();
+      Enumeration<? extends Principal> en = toCopy.members();
+      while(en.hasMoreElements())
+      {
+         source.addRole(new SimpleRole(en.nextElement().getName())); 
+      }
+       
+      return source;
+   }
+   
+   private int internalAuthorization(final Resource resource, Subject subject,
+         RoleGroup role)
+   throws AuthorizationException
+   {
+      lock.lock();
+      try
+      {
+         if(this.authorizationContext == null)
+            this.authorizationContext = new JBossAuthorizationContext(this.securityDomain);
+         return this.authorizationContext.authorize(resource, subject, role); 
+      }
+      finally
+      {
+         lock.unlock();
+      } 
+   }
+   
+   /**
+    * Get the Subject roles by looking for a Group called 'Roles'
+    * @param theSubject - the Subject to search for roles
+    * @return the Group contain the subject roles if found, null otherwise
+    */
+   private Group getGroupFromSubject(Subject theSubject)
+   {
+      if(theSubject == null)
+         throw new IllegalArgumentException("Subject is null");
+      Set<Group> subjectGroups = theSubject.getPrincipals(Group.class);
+      Iterator<Group> iter = subjectGroups.iterator();
+      Group roles = null;
+      while( iter.hasNext() )
+      {
+         Group grp = iter.next();
+         String name = grp.getName();
+         if( name.equals(ROLES_IDENTIFIER) )
+            roles = grp;
+      }
+      return roles;
+   } 
+   
+   private RoleGroup getRoleGroup(Group roleGroup)
+   {
+      if(roleGroup == null)
+         throw new IllegalArgumentException("roleGroup is null");
+      SimpleRoleGroup srg = new SimpleRoleGroup(roleGroup.getName());
+      Enumeration<? extends Principal> principals = roleGroup.members();
+      while(principals.hasMoreElements())
+      {
+         srg.getRoles().add(new SimpleRole(principals.nextElement().getName()));
+      }
+      return srg;  
+   }
+   
+
+   private void validateResource(Resource resource)
+   {
+      if(resource == null)
+         throw new IllegalArgumentException("resource is null");
+      if(resource.getMap() == null)
+         throw new IllegalArgumentException("resource has null context map");
+   }
+   
+   private RoleGroup getEmptyRoleGroup()
+   {
+      return new SimpleRoleGroup(SecurityConstants.ROLES_IDENTIFIER);
+   }
+}
\ No newline at end of file

Deleted: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/plugins/JBossPolicyRegistration.java
===================================================================
--- projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/security/plugins/JBossPolicyRegistration.java	2009-07-21 21:59:08 UTC (rev 91524)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/plugins/JBossPolicyRegistration.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -1,247 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source
- * Copyright 2007, JBoss Inc., and individual contributors as indicated
- * by the @authors tag. See the copyright.txt in the distribution for a
- * full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jboss.security.plugins;
-
-import java.io.InputStream;
-import java.io.Serializable;
-import java.net.URL;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Set;
-
-import javax.xml.bind.JAXBElement;
-
-import org.jboss.logging.Logger;
-import org.jboss.security.acl.ACL;
-import org.jboss.security.acl.ACLImpl;
-import org.jboss.security.acl.config.ACLConfiguration;
-import org.jboss.security.acl.config.ACLConfigurationFactory;
-import org.jboss.security.authorization.PolicyRegistration;
-import org.jboss.security.xacml.core.JBossPDP;
-import org.jboss.security.xacml.factories.PolicyFactory;
-import org.jboss.security.xacml.interfaces.XACMLPolicy;
-
-/**
- * Default implementation of Policy Registration interface
- * 
- * @author Anil.Saldhana at redhat.com
- * @since Mar 31, 2008
- * @version $Revision$
- */
-public class JBossPolicyRegistration implements PolicyRegistration, Serializable
-{
-   private static final long serialVersionUID = 1L;
-
-   private static Logger log = Logger.getLogger(JBossPolicyRegistration.class);
-
-   protected boolean trace = log.isTraceEnabled();
-
-   private final Map<String, Set<XACMLPolicy>> contextIdToXACMLPolicy = new HashMap<String, Set<XACMLPolicy>>();
-
-   /**
-    * When the policy configuration file is registered, we directly store a copy of the JBossPDP that has read in the
-    * config file
-    */
-   private final Map<String, JBossPDP> contextIDToJBossPDP = new HashMap<String, JBossPDP>();
-
-   /** Map to keep track of the ACLs that have been configured in each context. */
-   private final Map<String, Set<ACL>> contextIDToACLs = new HashMap<String, Set<ACL>>();
-
-   /** Global map that keeps all the configured ACLs keyed by their resource */
-   private final Map<String, ACL> configuredACLs = new HashMap<String, ACL>();
-
-   public void deRegisterPolicy(String contextID, String type)
-   {
-      if (PolicyRegistration.XACML.equalsIgnoreCase(type))
-      {
-         this.contextIdToXACMLPolicy.remove(contextID);
-         if (trace)
-            log.trace("DeRegistered policy for contextId:" + contextID + ":type=" + type);
-      }
-      else if (PolicyRegistration.ACL.equalsIgnoreCase(type))
-      {
-         Set<ACL> acls = this.contextIDToACLs.remove(contextID);
-         if (acls != null)
-         {
-            for (ACL acl : acls)
-            {
-               ACLImpl impl = (ACLImpl) acl;
-               this.configuredACLs.remove(impl.getResourceAsString());
-            }
-         }
-         if (trace)
-            log.trace("Deregistered ACLs for contextId:" + contextID);
-      }
-   }
-
-   @SuppressWarnings("unchecked")
-   public <T> T getPolicy(String contextID, String type, Map<String, Object> contextMap)
-   {
-      if (PolicyRegistration.XACML.equalsIgnoreCase(type))
-      {
-         if (contextMap != null)
-         {
-            String pdp = (String) contextMap.get("PDP");
-            if (pdp != null)
-               return (T) this.contextIDToJBossPDP.get(contextID);
-         }
-         return (T) this.contextIdToXACMLPolicy.get(contextID);
-      }
-      else if (PolicyRegistration.ACL.equalsIgnoreCase(type))
-      {
-         if (contextMap != null)
-         {
-            String query = (String) contextMap.get("resource");
-            if ("ALL".equalsIgnoreCase(query))
-            {
-               // return all the ACLs that have been registered.
-               return (T) this.configuredACLs.values();
-            }
-            else if (query != null)
-            {
-               // we are looking for an ACL for an specific resource.
-               return (T) this.configuredACLs.get(query);
-            }
-         }
-         return (T) this.contextIDToACLs.get(contextID);
-      }
-      throw new RuntimeException("Unsupported type:" + type);
-   }
-
-   /**
-    * @see PolicyRegistration#registerPolicy(String, String, URL)
-    */
-   public void registerPolicy(String contextID, String type, URL location)
-   {
-      try
-      {
-         if (trace)
-            log.trace("Registering policy for contextId:" + contextID + " type: " + type + "and location:"
-                  + location.getPath());
-         registerPolicy(contextID, type, location.openStream());
-      }
-      catch (Exception e)
-      {
-         log.debug("Error in registering policy:", e);
-      }
-   }
-
-   /**
-    * @see PolicyRegistration#registerPolicy(String, String, InputStream)
-    */
-   public void registerPolicy(String contextID, String type, InputStream stream)
-   {
-      if (PolicyRegistration.XACML.equalsIgnoreCase(type))
-      {
-         try
-         {
-            XACMLPolicy policy = PolicyFactory.createPolicy(stream);
-
-            Set<XACMLPolicy> policySet = this.contextIdToXACMLPolicy.get(contextID);
-            if (policySet == null)
-            {
-               policySet = new HashSet<XACMLPolicy>();
-            }
-            policySet.add(policy);
-            this.contextIdToXACMLPolicy.put(contextID, policySet);
-         }
-         catch (Exception e)
-         {
-            log.debug("Error in registering xacml policy:", e);
-         }
-      }
-      else if (PolicyRegistration.ACL.equalsIgnoreCase(type))
-      {
-         ACLConfiguration configuration = ACLConfigurationFactory.getConfiguration(stream);
-         Set<ACL> configuredACLs = configuration.getConfiguredACLs();
-         // register the configured ACLs
-         this.contextIDToACLs.put(contextID, configuredACLs);
-         for (ACL acl : configuredACLs)
-         {
-            ACLImpl impl = (ACLImpl) acl;
-            if (trace)
-               log.trace("Registering ACL for resource " + impl.getResourceAsString());
-            this.configuredACLs.put(impl.getResourceAsString(), acl);
-         }
-      }
-   }
-
-   /**
-    * @see PolicyRegistration#registerPolicyConfig(String, String, Object)
-    */
-   public <P> void registerPolicyConfig(String contextId, String type, P objectModel)
-   {
-      if (PolicyRegistration.XACML.equalsIgnoreCase(type))
-      {
-         if(objectModel instanceof JAXBElement == false)
-            throw new IllegalArgumentException("Unsupported model:" + objectModel);
-         
-         try
-         {
-            JAXBElement<?> jaxbModel = (JAXBElement<?>) objectModel;
-            JBossPDP pdp = new JBossPDP(jaxbModel);
-            this.contextIDToJBossPDP.put(contextId, pdp);
-         }
-         catch (Exception e)
-         {
-            throw new RuntimeException(e);
-         }
-      }
-      else if (PolicyRegistration.ACL.equalsIgnoreCase(type))
-      {
-         if(objectModel instanceof ACLConfiguration == false)
-            throw new IllegalArgumentException("Unsupported model:" + objectModel);
-         
-         ACLConfiguration configuration = (ACLConfiguration) objectModel;
-         Set<ACL> configuredACLs = configuration.getConfiguredACLs();
-         // register the configured ACLs
-         this.contextIDToACLs.put(contextId, configuredACLs);
-         for (ACL acl : configuredACLs)
-         {
-            ACLImpl impl = (ACLImpl) acl;
-            if (trace)
-               log.trace("Registering ACL for resource " + impl.getResourceAsString());
-            this.configuredACLs.put(impl.getResourceAsString(), acl);
-         }
-      }
-   }
-   
-   /**
-    * @see PolicyRegistration#registerPolicyConfigFile(String, String, InputStream)
-    */
-   public void registerPolicyConfigFile(String contextId, String type, InputStream stream)
-   {
-      if (PolicyRegistration.XACML.equalsIgnoreCase(type))
-      {
-         try
-         {
-            JBossPDP pdp = new JBossPDP(stream);
-            this.contextIDToJBossPDP.put(contextId, pdp);
-         }
-         catch (Exception e)
-         {
-            throw new RuntimeException(e);
-         }
-      }
-   }
-}
\ No newline at end of file

Copied: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/plugins/JBossPolicyRegistration.java (from rev 93325, projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/security/plugins/JBossPolicyRegistration.java)
===================================================================
--- projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/plugins/JBossPolicyRegistration.java	                        (rev 0)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/plugins/JBossPolicyRegistration.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -0,0 +1,248 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2007, JBoss Inc., and individual contributors as indicated
+ * by the @authors tag. See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.security.plugins;
+
+import java.io.InputStream;
+import java.io.Serializable;
+import java.net.URL;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+
+import javax.xml.bind.JAXBElement;
+
+import org.jboss.logging.Logger;
+import org.jboss.security.acl.ACL;
+import org.jboss.security.acl.ACLImpl;
+import org.jboss.security.acl.config.ACLConfiguration;
+import org.jboss.security.acl.config.ACLConfigurationFactory;
+import org.jboss.security.authorization.PolicyRegistration;
+import org.jboss.security.xacml.core.JBossPDP;
+import org.jboss.security.xacml.factories.PolicyFactory;
+import org.jboss.security.xacml.interfaces.XACMLPolicy;
+
+/**
+ * Default implementation of Policy Registration interface
+ * 
+ * @author Anil.Saldhana at redhat.com
+ * @since Mar 31, 2008
+ * @version $Revision$
+ */
+public class JBossPolicyRegistration implements PolicyRegistration, Serializable
+{
+   private static final long serialVersionUID = 1L;
+
+   private static Logger log = Logger.getLogger(JBossPolicyRegistration.class);
+
+   protected boolean trace = log.isTraceEnabled();
+
+   private final Map<String, Set<XACMLPolicy>> contextIdToXACMLPolicy = new HashMap<String, Set<XACMLPolicy>>();
+
+   /**
+    * When the policy configuration file is registered, we directly store a copy of the JBossPDP that has read in the
+    * config file
+    */
+   private final Map<String, JBossPDP> contextIDToJBossPDP = new HashMap<String, JBossPDP>();
+
+   /** Map to keep track of the ACLs that have been configured in each context. */
+   private final Map<String, Set<ACL>> contextIDToACLs = new HashMap<String, Set<ACL>>();
+
+   /** Global map that keeps all the configured ACLs keyed by their resource */
+   private final Map<String, ACL> configuredACLs = new HashMap<String, ACL>();
+
+   public void deRegisterPolicy(String contextID, String type)
+   {
+      if (PolicyRegistration.XACML.equalsIgnoreCase(type))
+      {
+         this.contextIdToXACMLPolicy.remove(contextID);
+         if (trace)
+            log.trace("DeRegistered policy for contextId:" + contextID + ":type=" + type);
+      }
+      else if (PolicyRegistration.ACL.equalsIgnoreCase(type))
+      {
+         Set<ACL> acls = this.contextIDToACLs.remove(contextID);
+         if (acls != null)
+         {
+            for (ACL acl : acls)
+            {
+               ACLImpl impl = (ACLImpl) acl;
+               this.configuredACLs.remove(impl.getResourceAsString());
+            }
+         }
+         if (trace)
+            log.trace("Deregistered ACLs for contextId:" + contextID);
+      }
+   }
+
+   @SuppressWarnings("unchecked")
+   public <T> T getPolicy(String contextID, String type, Map<String, Object> contextMap)
+   {
+      if (PolicyRegistration.XACML.equalsIgnoreCase(type))
+      {
+         if (contextMap != null)
+         {
+            String pdp = (String) contextMap.get("PDP");
+            if (pdp != null)
+               return (T) this.contextIDToJBossPDP.get(contextID);
+         }
+         return (T) this.contextIdToXACMLPolicy.get(contextID);
+      }
+      else if (PolicyRegistration.ACL.equalsIgnoreCase(type))
+      {
+         if (contextMap != null)
+         {
+            String query = (String) contextMap.get("resource");
+            if ("ALL".equalsIgnoreCase(query))
+            {
+               // return all the ACLs that have been registered.
+               return (T) this.configuredACLs.values();
+            }
+            else if (query != null)
+            {
+               // we are looking for an ACL for an specific resource.
+               return (T) this.configuredACLs.get(query);
+            }
+         }
+         return (T) this.contextIDToACLs.get(contextID);
+      }
+      throw new RuntimeException("Unsupported type:" + type);
+   }
+
+   /**
+    * @see PolicyRegistration#registerPolicy(String, String, URL)
+    */
+   public void registerPolicy(String contextID, String type, URL location)
+   {
+      try
+      {
+         if (trace)
+            log.trace("Registering policy for contextId:" + contextID + " type: " + type + "and location:"
+                  + location.getPath());
+         registerPolicy(contextID, type, location.openStream());
+      }
+      catch (Exception e)
+      {
+         log.debug("Error in registering policy:", e);
+      }
+   }
+
+   /**
+    * @see PolicyRegistration#registerPolicy(String, String, InputStream)
+    */
+   public void registerPolicy(String contextID, String type, InputStream stream)
+   {
+      if (PolicyRegistration.XACML.equalsIgnoreCase(type))
+      {
+         try
+         {
+            XACMLPolicy policy = PolicyFactory.createPolicy(stream);
+
+            Set<XACMLPolicy> policySet = this.contextIdToXACMLPolicy.get(contextID);
+            if (policySet == null)
+            {
+               policySet = new HashSet<XACMLPolicy>();
+            }
+            policySet.add(policy);
+            this.contextIdToXACMLPolicy.put(contextID, policySet);
+         }
+         catch (Exception e)
+         {
+            if(trace)
+               log.debug("Error in registering xacml policy:", e);
+         }
+      }
+      else if (PolicyRegistration.ACL.equalsIgnoreCase(type))
+      {
+         ACLConfiguration configuration = ACLConfigurationFactory.getConfiguration(stream);
+         Set<ACL> configuredACLs = configuration.getConfiguredACLs();
+         // register the configured ACLs
+         this.contextIDToACLs.put(contextID, configuredACLs);
+         for (ACL acl : configuredACLs)
+         {
+            ACLImpl impl = (ACLImpl) acl;
+            if (trace)
+               log.trace("Registering ACL for resource " + impl.getResourceAsString());
+            this.configuredACLs.put(impl.getResourceAsString(), acl);
+         }
+      }
+   }
+
+   /**
+    * @see PolicyRegistration#registerPolicyConfig(String, String, Object)
+    */
+   public <P> void registerPolicyConfig(String contextId, String type, P objectModel)
+   {
+      if (PolicyRegistration.XACML.equalsIgnoreCase(type))
+      {
+         if(objectModel instanceof JAXBElement == false)
+            throw new IllegalArgumentException("Unsupported model:" + objectModel);
+         
+         try
+         {
+            JAXBElement<?> jaxbModel = (JAXBElement<?>) objectModel;
+            JBossPDP pdp = new JBossPDP(jaxbModel);
+            this.contextIDToJBossPDP.put(contextId, pdp);
+         }
+         catch (Exception e)
+         {
+            throw new RuntimeException(e);
+         }
+      }
+      else if (PolicyRegistration.ACL.equalsIgnoreCase(type))
+      {
+         if(objectModel instanceof ACLConfiguration == false)
+            throw new IllegalArgumentException("Unsupported model:" + objectModel);
+         
+         ACLConfiguration configuration = (ACLConfiguration) objectModel;
+         Set<ACL> configuredACLs = configuration.getConfiguredACLs();
+         // register the configured ACLs
+         this.contextIDToACLs.put(contextId, configuredACLs);
+         for (ACL acl : configuredACLs)
+         {
+            ACLImpl impl = (ACLImpl) acl;
+            if (trace)
+               log.trace("Registering ACL for resource " + impl.getResourceAsString());
+            this.configuredACLs.put(impl.getResourceAsString(), acl);
+         }
+      }
+   }
+   
+   /**
+    * @see PolicyRegistration#registerPolicyConfigFile(String, String, InputStream)
+    */
+   public void registerPolicyConfigFile(String contextId, String type, InputStream stream)
+   {
+      if (PolicyRegistration.XACML.equalsIgnoreCase(type))
+      {
+         try
+         {
+            JBossPDP pdp = new JBossPDP(stream);
+            this.contextIDToJBossPDP.put(contextId, pdp);
+         }
+         catch (Exception e)
+         {
+            throw new RuntimeException(e);
+         }
+      }
+   }
+}
\ No newline at end of file

Deleted: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/plugins/SubjectActions.java
===================================================================
--- projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/security/plugins/SubjectActions.java	2009-07-21 21:59:08 UTC (rev 91524)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/plugins/SubjectActions.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -1,448 +0,0 @@
-/*
-* JBoss, Home of Professional Open Source
-* Copyright 2005, JBoss Inc., and individual contributors as indicated
-* by the @authors tag. See the copyright.txt in the distribution for a
-* full listing of individual contributors.
-*
-* This is free software; you can redistribute it and/or modify it
-* under the terms of the GNU Lesser General Public License as
-* published by the Free Software Foundation; either version 2.1 of
-* the License, or (at your option) any later version.
-*
-* This software is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-* Lesser General Public License for more details.
-*
-* You should have received a copy of the GNU Lesser General Public
-* License along with this software; if not, write to the Free
-* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
-*/
-package org.jboss.security.plugins;
-
-import java.lang.reflect.Method;
-import java.security.AccessController;
-import java.security.Principal;
-import java.security.PrivilegedAction;
-import java.security.PrivilegedActionException;
-import java.security.PrivilegedExceptionAction;
-import java.util.Iterator;
-import java.util.Set;
-
-import javax.security.auth.Subject;
-import javax.security.auth.callback.CallbackHandler;
-import javax.security.auth.login.LoginContext;
-import javax.security.auth.login.LoginException;
-import javax.security.jacc.PolicyContext;
-import javax.security.jacc.PolicyContextException;
-
-import org.jboss.logging.Logger;
-import org.jboss.security.SecurityAssociation;
-import org.jboss.security.SecurityConstants;
-import org.jboss.security.SecurityContext;
-import org.jboss.security.SecurityContextAssociation;
-import org.jboss.security.SecurityContextFactory;
-
-/** Common PrivilegedAction used by classes in this package.
- * 
- * @author Scott.Stark at jboss.org
- * @author Anil.Saldhana at redhat.com
- * @version $Revision$
- */
-class SubjectActions
-{
-   private static Logger log = Logger.getLogger(SubjectActions.class);
-   
-   private static class ToStringSubjectAction implements PrivilegedAction<String>
-   {
-      Subject subject;
-      ToStringSubjectAction(Subject subject)
-      {
-         this.subject = subject;
-      }
-      public String run()
-      {
-         StringBuffer tmp = new StringBuffer();
-         tmp.append("Subject(");
-         tmp.append(System.identityHashCode(subject));
-         tmp.append(").principals=");
-         Iterator<Principal> principals = subject.getPrincipals().iterator();
-         while( principals.hasNext() )
-         {
-            Object p = principals.next();
-            Class<?> c = p.getClass();
-            tmp.append(c.getName());
-            tmp.append('@');
-            tmp.append(System.identityHashCode(c));
-            tmp.append('(');
-            tmp.append(p);
-            tmp.append(')');
-         }
-         return tmp.toString();
-      }
-   }
-
-   private static class GetSubjectAction implements PrivilegedAction<Subject>
-   {
-      static PrivilegedAction<Subject> ACTION = new GetSubjectAction();
-      public Subject run()
-      {
-         Subject subject = null;
-         try
-         {
-            subject = (Subject) PolicyContext.getContext(SecurityConstants.SUBJECT_CONTEXT_KEY);
-         }
-         catch(PolicyContextException pce)
-         {
-            log.trace("Error obtaining subject:", pce);
-            SecurityContext sc = getSecurityContext();
-            subject = sc.getUtil().getSubject();
-         }
-         return subject;
-      }
-   }
-
-   private static class CopySubjectAction implements PrivilegedAction<Object>
-   {
-      Subject fromSubject;
-      Subject toSubject;
-      boolean setReadOnly;
-      boolean deepCopy;
-      
-      CopySubjectAction(Subject fromSubject, Subject toSubject, boolean setReadOnly)
-      {
-         this.fromSubject = fromSubject;
-         this.toSubject = toSubject;
-         this.setReadOnly = setReadOnly;
-      }
-      public void setDeepCopy(boolean flag)
-      {
-         this.deepCopy = flag;
-      }
-      
-      public Object run()
-      {
-         Set<Principal> principals = fromSubject.getPrincipals();
-         Set<Principal> principals2 = toSubject.getPrincipals();
-         Iterator<Principal> iter = principals.iterator();
-         while( iter.hasNext() )
-            principals2.add((Principal) getCloneIfNeeded(iter.next()));  
-         Set<Object> privateCreds = fromSubject.getPrivateCredentials();
-         Set<Object> privateCreds2 = toSubject.getPrivateCredentials();
-         Iterator<Object> iterCred = privateCreds.iterator();
-         while( iterCred.hasNext() )
-            privateCreds2.add(getCloneIfNeeded(iter.next()));
-         Set<Object> publicCreds = fromSubject.getPublicCredentials();
-         Set<Object> publicCreds2 = toSubject.getPublicCredentials();
-         iterCred = publicCreds.iterator();
-         while( iterCred.hasNext() )
-            publicCreds2.add(getCloneIfNeeded(iter.next()));
-         if( setReadOnly == true )
-            toSubject.setReadOnly();
-         return null;
-      }
-      
-      /** Check if the deepCopy flag is ON &&
-       *  Object implements Cloneable and return cloned object */
-      private Object getCloneIfNeeded(Object obj)
-      {
-         Object clonedObject = null;
-         if(this.deepCopy && obj instanceof Cloneable)
-         {
-            Class<?> clazz = obj.getClass();
-            try
-            {
-               Method cloneMethod = clazz.getMethod("clone", (Class[])null);
-               clonedObject = cloneMethod.invoke(obj, (Object[])null);
-   }
-            catch (Exception e)
-            {//Ignore non-cloneable issues 
-            } 
-         }
-         if(clonedObject == null)
-            clonedObject = obj;
-         return clonedObject;
-      }
-   }
-
-   private static class LoginContextAction implements PrivilegedExceptionAction<LoginContext>
-   {
-      String securityDomain;
-      Subject subject;
-      CallbackHandler handler;
-      LoginContextAction(String securityDomain, Subject subject,
-         CallbackHandler handler)
-      {
-         this.securityDomain = securityDomain;
-         this.subject = subject;
-         this.handler = handler;
-      }
-      public LoginContext run() throws Exception
-      {
-         LoginContext lc = new LoginContext(securityDomain, subject, handler);
-         return lc;
-      }
-   }
-
-   private static class GetTCLAction implements PrivilegedAction<ClassLoader>
-   {
-      static PrivilegedAction<ClassLoader> ACTION = new GetTCLAction();
-      public ClassLoader run()
-      {
-         ClassLoader loader = Thread.currentThread().getContextClassLoader();
-         return loader;
-      }
-   }
-
-   private static class SetContextInfoAction implements PrivilegedAction<Object>
-   {
-      String key;
-      Object value;
-      SetContextInfoAction(String key, Object value)
-      {
-         this.key = key;
-         this.value = value;
-      }
-      public Object run()
-      {
-         //Set it on the current security context also
-         SecurityContext sc = SecurityContextAssociation.getSecurityContext();
-         if(sc != null)
-         {
-            sc.getData().put(key, value);
-         }
-         return SecurityAssociation.setContextInfo(key, value);
-      }
-   }
-
-   interface PrincipalInfoAction
-   {
-      PrincipalInfoAction PRIVILEGED = new PrincipalInfoAction()
-      {
-         public void push(final Principal principal, final Object credential,
-            final Subject subject, final String securityDomain) 
-         {
-            AccessController.doPrivileged(
-               new PrivilegedAction<Object>()
-               {
-                  public Object run()
-                  {
-                     //SecurityAssociation.pushSubjectContext(subject, principal, credential);
-                     SecurityContext sc = SecurityContextAssociation.getSecurityContext();
-                     if(sc == null)
-                     {
-                        try
-                        {
-                           sc = SecurityContextFactory.createSecurityContext(principal, credential,
-                                 subject, securityDomain);
-                        }
-                        catch (Exception e)
-                        {
-                           throw new RuntimeException(e);
-                        }
-                     }
-                     SecurityContextAssociation.setSecurityContext(sc);
-                     return null;
-                  }
-               }
-            );
-         }
-         public void pop()
-         {
-            AccessController.doPrivileged(
-               new PrivilegedAction<Object>()
-               {
-                  public Object run()
-                  {
-                     //SecurityAssociation.popSubjectContext();
-                     SecurityContextAssociation.clearSecurityContext();
-                     return null;
-                  }
-               }
-            );
-         }
-      };
-
-      PrincipalInfoAction NON_PRIVILEGED = new PrincipalInfoAction()
-      {
-         public void push(Principal principal, Object credential, Subject subject,
-               String securityDomain)
-         {
-            //SecurityAssociation.pushSubjectContext(subject, principal, credential);
-            SecurityContext sc = SecurityContextAssociation.getSecurityContext();
-            if(sc == null)
-            {
-               try
-               {
-                  sc = SecurityContextFactory.createSecurityContext(principal, credential,
-                        subject, securityDomain);
-               }
-               catch (Exception e)
-               {
-                  throw new RuntimeException(e);
-               }
-            }
-            else
-            {
-               sc.getUtil().createSubjectInfo(principal, credential, subject); 
-            }
-            SecurityContextAssociation.setSecurityContext(sc); 
-         }
-         public void pop()
-         {
-            //SecurityAssociation.popSubjectContext();
-            SecurityContextAssociation.clearSecurityContext();
-         }
-      };
-
-      void push(Principal principal, Object credential, Subject subject, String securityDomain);
-      void pop();
-   }
-
-   static Subject getActiveSubject()
-   {
-      Subject subject = (Subject) AccessController.doPrivileged(GetSubjectAction.ACTION);
-      return subject;
-   }
-   static void copySubject(Subject fromSubject, Subject toSubject)
-   {
-      copySubject(fromSubject, toSubject, false);
-   }
-   static void copySubject(Subject fromSubject, Subject toSubject, boolean setReadOnly)
-   {
-      CopySubjectAction action = new CopySubjectAction(fromSubject, toSubject, setReadOnly);
-      if( System.getSecurityManager() != null )
-         AccessController.doPrivileged(action);
-      else
-         action.run();
-   }
-
-   static void copySubject(Subject fromSubject, Subject toSubject, boolean setReadOnly,
-         boolean deepCopy)
-   {
-      CopySubjectAction action = new CopySubjectAction(fromSubject, toSubject, setReadOnly);
-      action.setDeepCopy(deepCopy);
-      if( System.getSecurityManager() != null )
-         AccessController.doPrivileged(action);
-      else
-         action.run();
-   }
-
-   static LoginContext createLoginContext(String securityDomain, Subject subject,
-      CallbackHandler handler)
-      throws LoginException
-   {
-      LoginContextAction action = new LoginContextAction(securityDomain, subject, handler);
-      try
-      {
-         LoginContext lc = (LoginContext) AccessController.doPrivileged(action);
-         return lc;
-      }
-      catch(PrivilegedActionException e)
-      {
-         Exception ex = e.getException();
-         if( ex instanceof LoginException )
-            throw (LoginException) ex;
-         else
-            throw new LoginException(ex.getMessage());
-      }
-   } 
-   
-   static ClassLoader getContextClassLoader()
-   {
-      ClassLoader loader = (ClassLoader) AccessController.doPrivileged(GetTCLAction.ACTION);
-      return loader;
-   }
-
-   static Object setContextInfo(String key, Object value)
-   {
-      SetContextInfoAction action = new SetContextInfoAction(key, value);
-      Object prevInfo = AccessController.doPrivileged(action);
-      return prevInfo;
-   }
-
-   static void pushSubjectContext(Principal principal, Object credential,
-      Subject subject, String securityDomain)
-   {
-      if(System.getSecurityManager() == null)
-      {
-         PrincipalInfoAction.NON_PRIVILEGED.push(principal, credential, subject, securityDomain);
-      }
-      else
-      {
-         PrincipalInfoAction.PRIVILEGED.push(principal, credential, subject, securityDomain);
-      }
-   }
-   static void popSubjectContext()
-   {
-      if(System.getSecurityManager() == null)
-      {
-         PrincipalInfoAction.NON_PRIVILEGED.pop();
-      }
-      else
-      {
-         PrincipalInfoAction.PRIVILEGED.pop();
-      }
-   }
-
-   
-   static String toString(Subject subject)
-   {
-      ToStringSubjectAction action = new ToStringSubjectAction(subject);
-      String info = (String) AccessController.doPrivileged(action);
-      return info;
-   }
-   
-   static SecurityContext getSecurityContext()
-   { 
-      return AccessController.doPrivileged(new PrivilegedAction<SecurityContext>(){
-
-         public SecurityContext run()
-         {   
-            return SecurityContextAssociation.getSecurityContext();
-         }});
-   }
-   
-   static void setSecurityContext(final SecurityContext sc)
-   { 
-      AccessController.doPrivileged(new PrivilegedAction<SecurityContext>(){
-
-         public SecurityContext run()
-         { 
-            SecurityContextAssociation.setSecurityContext(sc);
-            return null;
-         }});
-   }
-   
-   /**
-    * Indicates whether the user has requested a refresh of the security context roles
-    * via a system property ("jbosssx.context.roles.refresh") which is either "true"
-    * or "false". default is "false"
-    * TODO: Externalize this system property setting such that it is passed as a map of
-    * options on the AuthorizationManagerService to be passed to AuthorizationManagers via
-    * the optional setOptions(Properties props) method
-    * @return
-    */
-   static String getRefreshSecurityContextRoles()
-   {
-      return  AccessController.doPrivileged(new PrivilegedAction<String>()
-      { 
-         public String run()
-         {
-            return System.getProperty("jbosssx.context.roles.refresh","false"); 
-         }}
-      );
-   }
-   
-   static String getSystemProperty(final String key, final String defaultValue)
-   {
-      return AccessController.doPrivileged(new PrivilegedAction<String>()
-      { 
-         public String run()
-         {
-            return System.getProperty(key,defaultValue); 
-         }}
-      );
-   } 
-}

Copied: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/plugins/SubjectActions.java (from rev 93325, projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/security/plugins/SubjectActions.java)
===================================================================
--- projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/plugins/SubjectActions.java	                        (rev 0)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/plugins/SubjectActions.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -0,0 +1,449 @@
+/*
+* JBoss, Home of Professional Open Source
+* Copyright 2005, JBoss Inc., and individual contributors as indicated
+* by the @authors tag. See the copyright.txt in the distribution for a
+* full listing of individual contributors.
+*
+* This is free software; you can redistribute it and/or modify it
+* under the terms of the GNU Lesser General Public License as
+* published by the Free Software Foundation; either version 2.1 of
+* the License, or (at your option) any later version.
+*
+* This software is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+* Lesser General Public License for more details.
+*
+* You should have received a copy of the GNU Lesser General Public
+* License along with this software; if not, write to the Free
+* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+*/
+package org.jboss.security.plugins;
+
+import java.lang.reflect.Method;
+import java.security.AccessController;
+import java.security.Principal;
+import java.security.PrivilegedAction;
+import java.security.PrivilegedActionException;
+import java.security.PrivilegedExceptionAction;
+import java.util.Iterator;
+import java.util.Set;
+
+import javax.security.auth.Subject;
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.login.LoginContext;
+import javax.security.auth.login.LoginException;
+import javax.security.jacc.PolicyContext;
+import javax.security.jacc.PolicyContextException;
+
+import org.jboss.logging.Logger;
+import org.jboss.security.SecurityAssociation;
+import org.jboss.security.SecurityConstants;
+import org.jboss.security.SecurityContext;
+import org.jboss.security.SecurityContextAssociation;
+import org.jboss.security.SecurityContextFactory;
+
+/** Common PrivilegedAction used by classes in this package.
+ * 
+ * @author Scott.Stark at jboss.org
+ * @author Anil.Saldhana at redhat.com
+ * @version $Revision$
+ */
+class SubjectActions
+{
+   private static Logger log = Logger.getLogger(SubjectActions.class);
+   
+   private static class ToStringSubjectAction implements PrivilegedAction<String>
+   {
+      Subject subject;
+      ToStringSubjectAction(Subject subject)
+      {
+         this.subject = subject;
+      }
+      public String run()
+      {
+         StringBuffer tmp = new StringBuffer();
+         tmp.append("Subject(");
+         tmp.append(System.identityHashCode(subject));
+         tmp.append(").principals=");
+         Iterator<Principal> principals = subject.getPrincipals().iterator();
+         while( principals.hasNext() )
+         {
+            Object p = principals.next();
+            Class<?> c = p.getClass();
+            tmp.append(c.getName());
+            tmp.append('@');
+            tmp.append(System.identityHashCode(c));
+            tmp.append('(');
+            tmp.append(p);
+            tmp.append(')');
+         }
+         return tmp.toString();
+      }
+   }
+
+   private static class GetSubjectAction implements PrivilegedAction<Subject>
+   {
+      static PrivilegedAction<Subject> ACTION = new GetSubjectAction();
+      public Subject run()
+      {
+         Subject subject = null;
+         try
+         {
+            subject = (Subject) PolicyContext.getContext(SecurityConstants.SUBJECT_CONTEXT_KEY);
+         }
+         catch(PolicyContextException pce)
+         {
+            if(log.isTraceEnabled())
+               log.trace("Error obtaining subject:", pce);
+            SecurityContext sc = getSecurityContext();
+            subject = sc.getUtil().getSubject();
+         }
+         return subject;
+      }
+   }
+
+   private static class CopySubjectAction implements PrivilegedAction<Object>
+   {
+      Subject fromSubject;
+      Subject toSubject;
+      boolean setReadOnly;
+      boolean deepCopy;
+      
+      CopySubjectAction(Subject fromSubject, Subject toSubject, boolean setReadOnly)
+      {
+         this.fromSubject = fromSubject;
+         this.toSubject = toSubject;
+         this.setReadOnly = setReadOnly;
+      }
+      public void setDeepCopy(boolean flag)
+      {
+         this.deepCopy = flag;
+      }
+      
+      public Object run()
+      {
+         Set<Principal> principals = fromSubject.getPrincipals();
+         Set<Principal> principals2 = toSubject.getPrincipals();
+         Iterator<Principal> iter = principals.iterator();
+         while( iter.hasNext() )
+            principals2.add((Principal) getCloneIfNeeded(iter.next()));  
+         Set<Object> privateCreds = fromSubject.getPrivateCredentials();
+         Set<Object> privateCreds2 = toSubject.getPrivateCredentials();
+         Iterator<Object> iterCred = privateCreds.iterator();
+         while( iterCred.hasNext() )
+            privateCreds2.add(getCloneIfNeeded(iter.next()));
+         Set<Object> publicCreds = fromSubject.getPublicCredentials();
+         Set<Object> publicCreds2 = toSubject.getPublicCredentials();
+         iterCred = publicCreds.iterator();
+         while( iterCred.hasNext() )
+            publicCreds2.add(getCloneIfNeeded(iter.next()));
+         if( setReadOnly == true )
+            toSubject.setReadOnly();
+         return null;
+      }
+      
+      /** Check if the deepCopy flag is ON &&
+       *  Object implements Cloneable and return cloned object */
+      private Object getCloneIfNeeded(Object obj)
+      {
+         Object clonedObject = null;
+         if(this.deepCopy && obj instanceof Cloneable)
+         {
+            Class<?> clazz = obj.getClass();
+            try
+            {
+               Method cloneMethod = clazz.getMethod("clone", (Class[])null);
+               clonedObject = cloneMethod.invoke(obj, (Object[])null);
+   }
+            catch (Exception e)
+            {//Ignore non-cloneable issues 
+            } 
+         }
+         if(clonedObject == null)
+            clonedObject = obj;
+         return clonedObject;
+      }
+   }
+
+   private static class LoginContextAction implements PrivilegedExceptionAction<LoginContext>
+   {
+      String securityDomain;
+      Subject subject;
+      CallbackHandler handler;
+      LoginContextAction(String securityDomain, Subject subject,
+         CallbackHandler handler)
+      {
+         this.securityDomain = securityDomain;
+         this.subject = subject;
+         this.handler = handler;
+      }
+      public LoginContext run() throws Exception
+      {
+         LoginContext lc = new LoginContext(securityDomain, subject, handler);
+         return lc;
+      }
+   }
+
+   private static class GetTCLAction implements PrivilegedAction<ClassLoader>
+   {
+      static PrivilegedAction<ClassLoader> ACTION = new GetTCLAction();
+      public ClassLoader run()
+      {
+         ClassLoader loader = Thread.currentThread().getContextClassLoader();
+         return loader;
+      }
+   }
+
+   private static class SetContextInfoAction implements PrivilegedAction<Object>
+   {
+      String key;
+      Object value;
+      SetContextInfoAction(String key, Object value)
+      {
+         this.key = key;
+         this.value = value;
+      }
+      public Object run()
+      {
+         //Set it on the current security context also
+         SecurityContext sc = SecurityContextAssociation.getSecurityContext();
+         if(sc != null)
+         {
+            sc.getData().put(key, value);
+         }
+         return SecurityAssociation.setContextInfo(key, value);
+      }
+   }
+
+   interface PrincipalInfoAction
+   {
+      PrincipalInfoAction PRIVILEGED = new PrincipalInfoAction()
+      {
+         public void push(final Principal principal, final Object credential,
+            final Subject subject, final String securityDomain) 
+         {
+            AccessController.doPrivileged(
+               new PrivilegedAction<Object>()
+               {
+                  public Object run()
+                  {
+                     //SecurityAssociation.pushSubjectContext(subject, principal, credential);
+                     SecurityContext sc = SecurityContextAssociation.getSecurityContext();
+                     if(sc == null)
+                     {
+                        try
+                        {
+                           sc = SecurityContextFactory.createSecurityContext(principal, credential,
+                                 subject, securityDomain);
+                        }
+                        catch (Exception e)
+                        {
+                           throw new RuntimeException(e);
+                        }
+                     }
+                     SecurityContextAssociation.setSecurityContext(sc);
+                     return null;
+                  }
+               }
+            );
+         }
+         public void pop()
+         {
+            AccessController.doPrivileged(
+               new PrivilegedAction<Object>()
+               {
+                  public Object run()
+                  {
+                     //SecurityAssociation.popSubjectContext();
+                     SecurityContextAssociation.clearSecurityContext();
+                     return null;
+                  }
+               }
+            );
+         }
+      };
+
+      PrincipalInfoAction NON_PRIVILEGED = new PrincipalInfoAction()
+      {
+         public void push(Principal principal, Object credential, Subject subject,
+               String securityDomain)
+         {
+            //SecurityAssociation.pushSubjectContext(subject, principal, credential);
+            SecurityContext sc = SecurityContextAssociation.getSecurityContext();
+            if(sc == null)
+            {
+               try
+               {
+                  sc = SecurityContextFactory.createSecurityContext(principal, credential,
+                        subject, securityDomain);
+               }
+               catch (Exception e)
+               {
+                  throw new RuntimeException(e);
+               }
+            }
+            else
+            {
+               sc.getUtil().createSubjectInfo(principal, credential, subject); 
+            }
+            SecurityContextAssociation.setSecurityContext(sc); 
+         }
+         public void pop()
+         {
+            //SecurityAssociation.popSubjectContext();
+            SecurityContextAssociation.clearSecurityContext();
+         }
+      };
+
+      void push(Principal principal, Object credential, Subject subject, String securityDomain);
+      void pop();
+   }
+
+   static Subject getActiveSubject()
+   {
+      Subject subject = (Subject) AccessController.doPrivileged(GetSubjectAction.ACTION);
+      return subject;
+   }
+   static void copySubject(Subject fromSubject, Subject toSubject)
+   {
+      copySubject(fromSubject, toSubject, false);
+   }
+   static void copySubject(Subject fromSubject, Subject toSubject, boolean setReadOnly)
+   {
+      CopySubjectAction action = new CopySubjectAction(fromSubject, toSubject, setReadOnly);
+      if( System.getSecurityManager() != null )
+         AccessController.doPrivileged(action);
+      else
+         action.run();
+   }
+
+   static void copySubject(Subject fromSubject, Subject toSubject, boolean setReadOnly,
+         boolean deepCopy)
+   {
+      CopySubjectAction action = new CopySubjectAction(fromSubject, toSubject, setReadOnly);
+      action.setDeepCopy(deepCopy);
+      if( System.getSecurityManager() != null )
+         AccessController.doPrivileged(action);
+      else
+         action.run();
+   }
+
+   static LoginContext createLoginContext(String securityDomain, Subject subject,
+      CallbackHandler handler)
+      throws LoginException
+   {
+      LoginContextAction action = new LoginContextAction(securityDomain, subject, handler);
+      try
+      {
+         LoginContext lc = (LoginContext) AccessController.doPrivileged(action);
+         return lc;
+      }
+      catch(PrivilegedActionException e)
+      {
+         Exception ex = e.getException();
+         if( ex instanceof LoginException )
+            throw (LoginException) ex;
+         else
+            throw new LoginException(ex.getMessage());
+      }
+   } 
+   
+   static ClassLoader getContextClassLoader()
+   {
+      ClassLoader loader = (ClassLoader) AccessController.doPrivileged(GetTCLAction.ACTION);
+      return loader;
+   }
+
+   static Object setContextInfo(String key, Object value)
+   {
+      SetContextInfoAction action = new SetContextInfoAction(key, value);
+      Object prevInfo = AccessController.doPrivileged(action);
+      return prevInfo;
+   }
+
+   static void pushSubjectContext(Principal principal, Object credential,
+      Subject subject, String securityDomain)
+   {
+      if(System.getSecurityManager() == null)
+      {
+         PrincipalInfoAction.NON_PRIVILEGED.push(principal, credential, subject, securityDomain);
+      }
+      else
+      {
+         PrincipalInfoAction.PRIVILEGED.push(principal, credential, subject, securityDomain);
+      }
+   }
+   static void popSubjectContext()
+   {
+      if(System.getSecurityManager() == null)
+      {
+         PrincipalInfoAction.NON_PRIVILEGED.pop();
+      }
+      else
+      {
+         PrincipalInfoAction.PRIVILEGED.pop();
+      }
+   }
+
+   
+   static String toString(Subject subject)
+   {
+      ToStringSubjectAction action = new ToStringSubjectAction(subject);
+      String info = (String) AccessController.doPrivileged(action);
+      return info;
+   }
+   
+   static SecurityContext getSecurityContext()
+   { 
+      return AccessController.doPrivileged(new PrivilegedAction<SecurityContext>(){
+
+         public SecurityContext run()
+         {   
+            return SecurityContextAssociation.getSecurityContext();
+         }});
+   }
+   
+   static void setSecurityContext(final SecurityContext sc)
+   { 
+      AccessController.doPrivileged(new PrivilegedAction<SecurityContext>(){
+
+         public SecurityContext run()
+         { 
+            SecurityContextAssociation.setSecurityContext(sc);
+            return null;
+         }});
+   }
+   
+   /**
+    * Indicates whether the user has requested a refresh of the security context roles
+    * via a system property ("jbosssx.context.roles.refresh") which is either "true"
+    * or "false". default is "false"
+    * TODO: Externalize this system property setting such that it is passed as a map of
+    * options on the AuthorizationManagerService to be passed to AuthorizationManagers via
+    * the optional setOptions(Properties props) method
+    * @return
+    */
+   static String getRefreshSecurityContextRoles()
+   {
+      return  AccessController.doPrivileged(new PrivilegedAction<String>()
+      { 
+         public String run()
+         {
+            return System.getProperty("jbosssx.context.roles.refresh","false"); 
+         }}
+      );
+   }
+   
+   static String getSystemProperty(final String key, final String defaultValue)
+   {
+      return AccessController.doPrivileged(new PrivilegedAction<String>()
+      { 
+         public String run()
+         {
+            return System.getProperty(key,defaultValue); 
+         }}
+      );
+   } 
+}

Deleted: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/plugins/TransactionManagerLocator.java
===================================================================
--- projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/security/plugins/TransactionManagerLocator.java	2009-07-21 21:59:08 UTC (rev 91524)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/plugins/TransactionManagerLocator.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -1,87 +0,0 @@
-/*
-  * JBoss, Home of Professional Open Source
-  * Copyright 2007, JBoss Inc., and individual contributors as indicated
-  * by the @authors tag. See the copyright.txt in the distribution for a
-  * full listing of individual contributors.
-  *
-  * This is free software; you can redistribute it and/or modify it
-  * under the terms of the GNU Lesser General Public License as
-  * published by the Free Software Foundation; either version 2.1 of
-  * the License, or (at your option) any later version.
-  *
-  * This software is distributed in the hope that it will be useful,
-  * but WITHOUT ANY WARRANTY; without even the implied warranty of
-  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-  * Lesser General Public License for more details.
-  *
-  * You should have received a copy of the GNU Lesser General Public
-  * License along with this software; if not, write to the Free
-  * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-  * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
-  */
-package org.jboss.security.plugins;
-
-import java.lang.reflect.Method;
-
-import javax.naming.InitialContext;
-import javax.naming.NameNotFoundException;
-import javax.naming.NamingException;
-import javax.transaction.TransactionManager;
-
-import org.jboss.logging.Logger;
-
-//$Id$
-
-/**
- *  Locate a Transaction Manager
- *  @author Anil.Saldhana at redhat.com
- *  @since  May 13, 2007 
- *  @version $Revision$
- */
-public class TransactionManagerLocator
-{
-   private static Logger log = Logger.getLogger(TransactionManagerLocator.class);
-   
-   public TransactionManagerLocator()
-   {   
-   }
-   
-   /**
-    * Get the TransactionManager provided a JNDI Name for the
-    * Transaction Manager <br/>
-    * Note: If the TM is not bound to JNDI, an attempt is made
-    * to obtain the JBoss TxManager instance via reflection
-    * @param jndiName
-    * @return
-    * @throws NamingException
-    */
-   public TransactionManager getTM(String jndiName) throws NamingException
-   {
-      TransactionManager tm = null;
-      InitialContext ctx = new InitialContext();
-      try
-      { 
-         tm = (TransactionManager) ctx.lookup(jndiName);
-      }
-      catch(NameNotFoundException nfe)
-      {
-         try
-         {
-            tm = this.getJBossTM();
-         }
-         catch (Exception ignore)
-         { 
-            log.trace("Exception in getJBossTM:", ignore);
-         }
-      } 
-      return tm;
-   } 
-   
-   private TransactionManager getJBossTM() throws Exception
-   {
-      ClassLoader tcl = SubjectActions.getContextClassLoader();
-      Class<?> clz = tcl.loadClass("org.jboss.tm.TransactionManagerLocator");
-      Method m = clz.getMethod("locate", new Class[]{});
-      return (TransactionManager) m.invoke(null, new Object[0]); 
-   }
-}

Copied: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/plugins/TransactionManagerLocator.java (from rev 93325, projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/security/plugins/TransactionManagerLocator.java)
===================================================================
--- projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/plugins/TransactionManagerLocator.java	                        (rev 0)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/plugins/TransactionManagerLocator.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -0,0 +1,87 @@
+/*
+  * JBoss, Home of Professional Open Source
+  * Copyright 2007, JBoss Inc., and individual contributors as indicated
+  * by the @authors tag. See the copyright.txt in the distribution for a
+  * full listing of individual contributors.
+  *
+  * This is free software; you can redistribute it and/or modify it
+  * under the terms of the GNU Lesser General Public License as
+  * published by the Free Software Foundation; either version 2.1 of
+  * the License, or (at your option) any later version.
+  *
+  * This software is distributed in the hope that it will be useful,
+  * but WITHOUT ANY WARRANTY; without even the implied warranty of
+  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+  * Lesser General Public License for more details.
+  *
+  * You should have received a copy of the GNU Lesser General Public
+  * License along with this software; if not, write to the Free
+  * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+  * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+  */
+package org.jboss.security.plugins;
+
+import java.lang.reflect.Method;
+
+import javax.naming.InitialContext;
+import javax.naming.NameNotFoundException;
+import javax.naming.NamingException;
+import javax.transaction.TransactionManager;
+
+import org.jboss.logging.Logger;
+
+/**
+ *  Locate a Transaction Manager
+ *  @author Anil.Saldhana at redhat.com
+ *  @since  May 13, 2007 
+ *  @version $Revision$
+ */
+public class TransactionManagerLocator
+{
+   private static Logger log = Logger.getLogger(TransactionManagerLocator.class);
+   private boolean trace = log.isTraceEnabled();
+   
+   public TransactionManagerLocator()
+   {   
+   }
+   
+   /**
+    * Get the TransactionManager provided a JNDI Name for the
+    * Transaction Manager <br/>
+    * Note: If the TM is not bound to JNDI, an attempt is made
+    * to obtain the JBoss TxManager instance via reflection
+    * @param jndiName
+    * @return
+    * @throws NamingException
+    */
+   public TransactionManager getTM(String jndiName) throws NamingException
+   {
+      TransactionManager tm = null;
+      InitialContext ctx = new InitialContext();
+      try
+      { 
+         tm = (TransactionManager) ctx.lookup(jndiName);
+      }
+      catch(NameNotFoundException nfe)
+      {
+         try
+         {
+            tm = this.getJBossTM();
+         }
+         catch (Exception ignore)
+         { 
+            if(trace)
+               log.trace("Exception in getJBossTM:", ignore);
+         }
+      } 
+      return tm;
+   } 
+   
+   private TransactionManager getJBossTM() throws Exception
+   {
+      ClassLoader tcl = SubjectActions.getContextClassLoader();
+      Class<?> clz = tcl.loadClass("org.jboss.tm.TransactionManagerLocator");
+      Method m = clz.getMethod("locate", new Class[]{});
+      return (TransactionManager) m.invoke(null, new Object[0]); 
+   }
+}
\ No newline at end of file

Deleted: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/plugins/auth/JASPIServerAuthenticationManager.java
===================================================================
--- projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/security/plugins/auth/JASPIServerAuthenticationManager.java	2009-07-21 21:59:08 UTC (rev 91524)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/plugins/auth/JASPIServerAuthenticationManager.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -1,89 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * Copyright 2008, Red Hat Middleware LLC, and individual contributors
- * as indicated by the @author tags. See the copyright.txt file in the
- * distribution for a full listing of individual contributors. 
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jboss.security.plugins.auth;
-
-import java.util.HashMap;
-
-import javax.security.auth.Subject;
-import javax.security.auth.callback.CallbackHandler;
-import javax.security.auth.message.AuthException;
-import javax.security.auth.message.AuthStatus;
-import javax.security.auth.message.MessageInfo;
-import javax.security.auth.message.config.AuthConfigFactory;
-import javax.security.auth.message.config.AuthConfigProvider;
-import javax.security.auth.message.config.ServerAuthConfig;
-import javax.security.auth.message.config.ServerAuthContext;
-import javax.security.jacc.PolicyContext;
-
-import org.jboss.security.AuthenticationManager;
-import org.jboss.security.ServerAuthenticationManager;
-
-/**
- * @author Anil.Saldhana at redhat.com
- */
-public class JASPIServerAuthenticationManager 
-extends JaasSecurityManagerBase implements ServerAuthenticationManager
-{   
-   public JASPIServerAuthenticationManager()
-   {
-      super(); 
-   }
-
-   public JASPIServerAuthenticationManager(String securityDomain, CallbackHandler handler)
-   {
-      super(securityDomain, handler); 
-   }
-
-   /**
-    * @see AuthenticationManager#isValid(MessageInfo, Subject, String, CallbackHandler)
-    */
-   @SuppressWarnings("unchecked")
-   public boolean isValid(MessageInfo requestMessage,Subject clientSubject, String layer,
-         CallbackHandler handler)
-   { 
-      AuthStatus status = AuthStatus.FAILURE;
-      
-      try
-      {
-         String contextID = PolicyContext.getContextID();
-         AuthConfigFactory factory = AuthConfigFactory.getFactory();
-         AuthConfigProvider provider = factory.getConfigProvider(layer,contextID,null); 
-         if(provider == null)
-            throw new IllegalStateException("Provider is null for "+ layer + " for "+ contextID);
-         
-         ServerAuthConfig serverConfig = provider.getServerAuthConfig(layer,contextID,handler);  
-         ServerAuthContext sctx = serverConfig.getAuthContext(contextID, 
-               new Subject(), new HashMap());
-         if(clientSubject == null)
-            clientSubject = new Subject();
-         Subject serviceSubject = new Subject();
-         status = sctx.validateRequest(requestMessage, clientSubject, serviceSubject); 
-         //TODO: Add caching
-      }
-      catch(AuthException ae)
-      {
-         log.trace("AuthException:",ae);
-      } 
-      return AuthStatus.SUCCESS == status ;
-   }
-   
-}
\ No newline at end of file

Copied: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/plugins/auth/JASPIServerAuthenticationManager.java (from rev 93325, projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/security/plugins/auth/JASPIServerAuthenticationManager.java)
===================================================================
--- projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/plugins/auth/JASPIServerAuthenticationManager.java	                        (rev 0)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/plugins/auth/JASPIServerAuthenticationManager.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -0,0 +1,90 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors. 
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.security.plugins.auth;
+
+import java.util.HashMap;
+
+import javax.security.auth.Subject;
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.message.AuthException;
+import javax.security.auth.message.AuthStatus;
+import javax.security.auth.message.MessageInfo;
+import javax.security.auth.message.config.AuthConfigFactory;
+import javax.security.auth.message.config.AuthConfigProvider;
+import javax.security.auth.message.config.ServerAuthConfig;
+import javax.security.auth.message.config.ServerAuthContext;
+import javax.security.jacc.PolicyContext;
+
+import org.jboss.security.AuthenticationManager;
+import org.jboss.security.ServerAuthenticationManager;
+
+/**
+ * @author Anil.Saldhana at redhat.com
+ */
+public class JASPIServerAuthenticationManager 
+extends JaasSecurityManagerBase implements ServerAuthenticationManager
+{   
+   public JASPIServerAuthenticationManager()
+   {
+      super(); 
+   }
+
+   public JASPIServerAuthenticationManager(String securityDomain, CallbackHandler handler)
+   {
+      super(securityDomain, handler); 
+   }
+
+   /**
+    * @see AuthenticationManager#isValid(MessageInfo, Subject, String, CallbackHandler)
+    */
+   @SuppressWarnings("unchecked")
+   public boolean isValid(MessageInfo requestMessage,Subject clientSubject, String layer,
+         CallbackHandler handler)
+   { 
+      AuthStatus status = AuthStatus.FAILURE;
+      
+      try
+      {
+         String contextID = PolicyContext.getContextID();
+         AuthConfigFactory factory = AuthConfigFactory.getFactory();
+         AuthConfigProvider provider = factory.getConfigProvider(layer,contextID,null); 
+         if(provider == null)
+            throw new IllegalStateException("Provider is null for "+ layer + " for "+ contextID);
+         
+         ServerAuthConfig serverConfig = provider.getServerAuthConfig(layer,contextID,handler);  
+         ServerAuthContext sctx = serverConfig.getAuthContext(contextID, 
+               new Subject(), new HashMap());
+         if(clientSubject == null)
+            clientSubject = new Subject();
+         Subject serviceSubject = new Subject();
+         status = sctx.validateRequest(requestMessage, clientSubject, serviceSubject); 
+         //TODO: Add caching
+      }
+      catch(AuthException ae)
+      {
+         if(trace)
+            log.trace("AuthException:",ae);
+      } 
+      return AuthStatus.SUCCESS == status ;
+   }
+   
+}
\ No newline at end of file

Deleted: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/plugins/auth/JaasSecurityManagerBase.java
===================================================================
--- projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/security/plugins/auth/JaasSecurityManagerBase.java	2009-07-21 21:59:08 UTC (rev 91524)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/plugins/auth/JaasSecurityManagerBase.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -1,757 +0,0 @@
-/*
-* JBoss, Home of Professional Open Source
-* Copyright 2005, JBoss Inc., and individual contributors as indicated
-* by the @authors tag. See the copyright.txt in the distribution for a
-* full listing of individual contributors.
-*
-* This is free software; you can redistribute it and/or modify it
-* under the terms of the GNU Lesser General Public License as
-* published by the Free Software Foundation; either version 2.1 of
-* the License, or (at your option) any later version.
-*
-* This software is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-* Lesser General Public License for more details.
-*
-* You should have received a copy of the GNU Lesser General Public
-* License along with this software; if not, write to the Free
-* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
-*/
-package org.jboss.security.plugins.auth;
-
-import java.lang.reflect.Method;
-import java.lang.reflect.UndeclaredThrowableException;
-import java.security.Principal;
-import java.security.acl.Group;
-import java.util.Arrays;
-import java.util.Enumeration;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Set;
-
-import javax.security.auth.Subject;
-import javax.security.auth.callback.CallbackHandler;
-import javax.security.auth.login.LoginContext;
-import javax.security.auth.login.LoginException;
-
-import org.jboss.logging.Logger;
-import org.jboss.security.AuthenticationManager;
-import org.jboss.security.AuthorizationManager;
-import org.jboss.security.RealmMapping;
-import org.jboss.security.SecurityConstants;
-import org.jboss.security.SecurityContext;
-import org.jboss.security.SecurityContextAssociation;
-import org.jboss.security.SecurityUtil;
-import org.jboss.security.SubjectSecurityManager;
-import org.jboss.security.auth.callback.JBossCallbackHandler;
-import org.jboss.util.CachePolicy;
-import org.jboss.util.TimedCachePolicy;
-
-/** The JaasSecurityManager is responsible both for authenticating credentials
- associated with principals and for role mapping. This implementation relies
- on the JAAS LoginContext/LoginModules associated with the security
- domain name associated with the class for authentication,
- and the context JAAS Subject object for role mapping.
- 
- @see #isValid(Principal, Object, Subject)
- @see #getPrincipal(Principal)
- @see #doesUserHaveRole(Principal, Set)
- 
- @author <a href="on at ibis.odessa.ua">Oleg Nitz</a>
- @author Scott.Stark at jboss.org
- @author Anil.Saldhana at jboss.org
- @version $Revision: 62860 $
-*/
-public class JaasSecurityManagerBase 
-   implements SubjectSecurityManager, RealmMapping
-{
-   /** The authentication cache object.
-    */
-   public static class DomainInfo implements TimedCachePolicy.TimedEntry
-   {
-      private static Logger log = Logger.getLogger(DomainInfo.class);
-      private static boolean trace = log.isTraceEnabled();
-      protected LoginContext loginCtx;
-      protected Subject subject;
-      protected Object credential;
-      protected Principal callerPrincipal;
-      private long expirationTime;
-      /** Is there an active authentication in process */
-      private boolean needsDestroy;
-      /** The number of users sharing this DomainInfo */
-      private int activeUsers;
-
-      /**
-       Create a cache entry with the given lifetime in seconds. Since this comes
-       from the TimedCachePolicy, its expected to be <= Integer.MAX_VALUE.
-       
-       @param lifetime - lifetime in seconds. A lifetime <= 0 means no caching
-         with the exception of -1 which indicates that the cache entry never
-         expires.
-       */
-      public DomainInfo(long lifetime)
-      {
-         expirationTime = lifetime;
-         if( expirationTime != -1 )
-            expirationTime *= 1000;
-      }
-
-      synchronized int acquire()
-      {
-         return activeUsers ++;
-      }
-      synchronized int release()
-      {
-         int users = activeUsers --;
-         if( needsDestroy == true && users == 0 )
-         {
-            if( trace )
-               log.trace("needsDestroy is true, doing logout");
-            logout();
-         }
-         return users;
-      }
-      synchronized void logout()
-      {
-         if( trace )
-            log.trace("logout, subject="+subject+", this="+this);
-         try
-         {
-            if( loginCtx != null )
-               loginCtx.logout();
-         }
-         catch(Throwable e)
-         {
-            if( trace )
-               log.trace("Cache entry logout failed", e);
-         }
-      }
-
-      public void init(long now)
-      {
-         expirationTime += now;
-      }
-      public boolean isCurrent(long now)
-      {
-         boolean isCurrent = expirationTime == -1;
-         if( isCurrent == false )
-            isCurrent = expirationTime > now;
-         return isCurrent;
-      }
-      public boolean refresh()
-      {
-         return false;
-      }
-      /**
-       * This 
-       */ 
-      public void destroy()
-      {
-         if( trace )
-         {
-            log.trace("destroy, subject="+subject+", this="+this
-               +", activeUsers="+activeUsers);
-         }
-
-         synchronized( this )
-         {
-            if( activeUsers == 0 )
-               logout();
-            else
-            {
-               if( trace )
-                  log.trace("destroy saw activeUsers="+activeUsers);
-               needsDestroy = true;
-            }
-         }
-      }
-      public Object getValue()
-      {
-         return this;
-      }
-      public String toString()
-      {
-         StringBuffer tmp = new StringBuffer(super.toString());
-         tmp.append('[');
-         tmp.append(SubjectActions.toString(subject));
-         tmp.append(",credential.class=");
-         if( credential != null )
-         {
-            Class<?> c = credential.getClass();
-            tmp.append(c.getName());
-            tmp.append('@');
-            tmp.append(System.identityHashCode(c));
-         }
-         else
-         {
-            tmp.append("null");
-         }
-         tmp.append(",expirationTime=");
-         tmp.append(expirationTime);
-         tmp.append(']');
-
-         return tmp.toString();
-      }
-   }
-
-   /** The name of the domain this instance is securing. It is used as
-    the appName into the SecurityPolicy.
-    */
-   private String securityDomain;
-   /** A cache of DomainInfo objects keyd by Principal. This is now
-    always set externally by our security manager service.
-    */
-   private CachePolicy domainCache;
-   /** The JAAS callback handler to use in defaultLogin */
-   private CallbackHandler handler;
-   /** The setSecurityInfo(Principal, Object) method of the handler obj */
-   private transient Method setSecurityInfo;
-   /** The flag to indicate that the Subject sets need to be deep copied*/
-   private boolean deepCopySubjectOption = false; 
-   
-   /** The log4j category for the security manager domain
-    */
-   protected Logger log;
-   protected boolean trace;
-   private AuthorizationManager authorizationManager;
-
-   /** Creates a default JaasSecurityManager for with a securityDomain
-    name of 'other'.
-    */
-   public JaasSecurityManagerBase()
-   {
-      this("other", new JBossCallbackHandler());
-   }
-   /** Creates a JaasSecurityManager for with a securityDomain
-    name of that given by the 'securityDomain' argument.
-    @param securityDomain the name of the security domain
-    @param handler the JAAS callback handler instance to use
-    @exception UndeclaredThrowableException thrown if handler does not
-      implement a setSecurityInfo(Princpal, Object) method
-    */
-   public JaasSecurityManagerBase(String securityDomain, CallbackHandler handler)
-   {
-      this.securityDomain = securityDomain;
-      this.handler = handler;
-      String categoryName = getClass().getName()+'.'+securityDomain;
-      this.log = Logger.getLogger(categoryName);
-      this.trace = log.isTraceEnabled();
-
-      // Get the setSecurityInfo(Principal principal, Object credential) method
-      Class<?>[] sig = {Principal.class, Object.class};
-      try
-      {
-         setSecurityInfo = handler.getClass().getMethod("setSecurityInfo", sig);
-      }
-      catch (Exception e)
-      {
-         String msg = "Failed to find setSecurityInfo(Princpal, Object) method in handler";
-         throw new UndeclaredThrowableException(e, msg);
-      } 
-      log.debug("CallbackHandler: "+handler);
-   }
-
-   /** The domainCache is typically a shared object that is populated
-    by the login code(LoginModule, etc.) and read by this class in the
-    isValid() method.
-    @see #isValid(Principal, Object, Subject)
-    */
-   public void setCachePolicy(CachePolicy domainCache)
-   {
-      this.domainCache = domainCache;
-      log.debug("CachePolicy set to: "+domainCache);
-   }
-
-   /**
-    * Flag to specify if deep copy of subject sets needs to be 
-    * enabled
-    * 
-    * @param flag
-    */
-   public void setDeepCopySubjectOption(Boolean flag)
-   {
-      log.debug("setDeepCopySubjectOption="+ flag);
-      this.deepCopySubjectOption = (flag == Boolean.TRUE) ;
-   } 
-   
-   /**
-    * Set an AuthorizationManager
-    * @param authorizationManager
-    */
-   public void setAuthorizationManager(AuthorizationManager authorizationManager)
-   {
-      this.authorizationManager = authorizationManager;
-   }
-   
-   /** Not really used anymore as the security manager service manages the
-    security domain authentication caches.
-    */
-   public void flushCache()
-   {
-      if( domainCache != null )
-         domainCache.flush();
-   }
-
-   /** Get the name of the security domain associated with this security mgr.
-    @return Name of the security manager security domain.
-    */
-   public String getSecurityDomain()
-   {
-      return securityDomain;
-   }
-
-   /** Get the currently authenticated Subject. This is a thread local
-    property shared across all JaasSecurityManager instances.
-    @return The Subject authenticated in the current thread if one
-    exists, null otherwise.
-    */
-   public Subject getActiveSubject()
-   {
-      /* This does not use SubjectActions.getActiveSubject since the caller
-         must have the correct permissions to access the
-         SecurityAssociation.getSubject method.
-      */
-      //return SecurityAssociation.getSubject();
-      Subject subj = null;
-      SecurityContext sc = SecurityContextAssociation.getSecurityContext();
-      if(sc != null)
-      {
-         subj = sc.getUtil().getSubject();
-      }
-      return subj;
-   }
-
-   /** Validate that the given credential is correct for principal. This
-    returns the value from invoking isValid(principal, credential, null).
-    @param principal - the security domain principal attempting access
-    @param credential - the proof of identity offered by the principal
-    @return true if the principal was authenticated, false otherwise.
-    */
-   public boolean isValid(Principal principal, Object credential)
-   {
-      return isValid(principal, credential, null);
-   }
-
-   /** Validate that the given credential is correct for principal. This first
-    will check the current CachePolicy object if one exists to see if the
-    user's cached credentials match the given credential. If there is no
-    credential cache or the cache information is invalid or does not match,
-    the user is authenticated against the JAAS login modules configured for
-    the security domain.
-    @param principal - the security domain principal attempting access
-    @param credential  the proof of identity offered by the principal
-    @param activeSubject - if not null, a Subject that will be populated with
-      the state of the authenticated Subject.
-    @return true if the principal was authenticated, false otherwise.
-    */
-   public boolean isValid(Principal principal, Object credential,
-      Subject activeSubject)
-   {
-      // Check the cache first
-      DomainInfo cacheInfo = getCacheInfo(principal, true);
-      if( trace )
-         log.trace("Begin isValid, principal:"+principal+", cache info: "+cacheInfo);
-
-      boolean isValid = false;
-      if( cacheInfo != null )
-      {
-         isValid = validateCache(cacheInfo, credential, activeSubject);
-         if( cacheInfo != null )
-            cacheInfo.release();
-      }
-      if( isValid == false )
-         isValid = authenticate(principal, credential, activeSubject);
-      if( trace )
-         log.trace("End isValid, "+isValid); 
-      return isValid;
-   } 
-
-   
-   /** Map the argument principal from the deployment environment principal
-    to the developer environment. This is called by the EJB context
-    getCallerPrincipal() to return the Principal as described by
-    the EJB developer domain.
-    @return a Principal object that is valid in the deployment environment
-    if one exists. If no Subject exists or the Subject has no principals
-    then the argument principal is returned.
-    */
-   public Principal getPrincipal(Principal principal)
-   {
-      if(domainCache == null)
-         return principal;
-      Principal result = principal; 
-      // Get the CallerPrincipal group member
-      synchronized( domainCache )
-      {
-         DomainInfo info = getCacheInfo(principal, false);
-         if( trace )
-            log.trace("getPrincipal, cache info: "+info);
-         if( info != null )
-         {
-            result = info.callerPrincipal;
-            // If the mapping did not have a callerPrincipal just use principal
-            if( result == null )
-               result = principal;
-            info.release();
-         }
-      }
-
-      return result;
-   }
-
-   /** Does the current Subject have a role(a Principal) that equates to one
-    of the role names. This method obtains the Group named 'Roles' from
-    the principal set of the currently authenticated Subject as determined
-    by the SecurityAssociation.getSubject() method and then creates a
-    SimplePrincipal for each name in roleNames. If the role is a member of the
-    Roles group, then the user has the role. This requires that the caller
-    establish the correct SecurityAssociation subject prior to calling this
-    method. In the past this was done as a side-effect of an isValid() call,
-    but this is no longer the case.
-
-    @param principal - ignored. The current authenticated Subject determines
-    the active user and assigned user roles.
-    @param rolePrincipals - a Set of Principals for the roles to check.
-    
-    @see java.security.acl.Group;
-    @see Subject#getPrincipals()
-    */
-   public boolean doesUserHaveRole(Principal principal, Set<Principal> rolePrincipals)
-   { 
-      if(this.authorizationManager == null)
-      {
-         this.authorizationManager = SecurityUtil.getAuthorizationManager(securityDomain, 
-               SecurityConstants.JAAS_CONTEXT_ROOT); 
-      }
-      if(this.authorizationManager == null)
-      {
-         log.trace("doesUserHaveRole:AuthorizationManager is null");
-         return false;
-      }
-      return authorizationManager.doesUserHaveRole(principal, rolePrincipals); 
-   } 
-
-   /** Return the set of domain roles the current active Subject 'Roles' group
-      found in the subject Principals set.
-
-    @param principal - ignored. The current authenticated Subject determines
-    the active user and assigned user roles.
-    @return The Set<Principal> for the application domain roles that the
-    principal has been assigned.
-   */
-   @SuppressWarnings("deprecation")
-   public Set<Principal> getUserRoles(Principal principal)
-   {
-      if(this.authorizationManager == null)
-      {
-         this.authorizationManager = SecurityUtil.getAuthorizationManager(securityDomain, 
-               SecurityConstants.JAAS_CONTEXT_ROOT); 
-      }
-      if(this.authorizationManager == null)
-      {
-         log.trace("doesUserHaveRole:AuthorizationManager is null");
-         return null;
-      }
-      return authorizationManager.getUserRoles(principal);
-   } 
-   
-   /**
-    * @see AuthenticationManager#getTargetPrincipal(Principal,Map)
-    */
-   public Principal getTargetPrincipal(Principal anotherDomainPrincipal, 
-         Map<String,Object> contextMap)
-   {
-      throw new RuntimeException("Not implemented yet");
-   }
-
-   /** Currently this simply calls defaultLogin() to do a JAAS login using the
-    security domain name as the login module configuration name.
-    
-    * @param principal - the user id to authenticate
-    * @param credential - an opaque credential.
-    * @return false on failure, true on success.
-    */
-   private boolean authenticate(Principal principal, Object credential,
-      Subject theSubject)
-   {
-      Subject subject = null;
-      boolean authenticated = false;
-      LoginException authException = null;
-
-      try
-      {
-         // Validate the principal using the login configuration for this domain
-         LoginContext lc = defaultLogin(principal, credential);
-         subject = lc.getSubject();
-
-         // Set the current subject if login was successful
-         if( subject != null )
-         {
-            // Copy the current subject into theSubject
-            if( theSubject != null )
-            {
-               SubjectActions.copySubject(subject, theSubject, false,this.deepCopySubjectOption);
-            }
-            else
-            {
-               theSubject = subject;
-            }
-
-            authenticated = true;
-            // Build the Subject based DomainInfo cache value
-            updateCache(lc, subject, principal, credential);
-         }
-      }
-      catch(LoginException e)
-      {
-         // Don't log anonymous user failures unless trace level logging is on
-         if( principal != null && principal.getName() != null || trace )
-            log.trace("Login failure", e);
-         authException = e;
-      }
-      // Set the security association thread context info exception
-      SubjectActions.setContextInfo("org.jboss.security.exception", authException);
-
-      return authenticated;
-   }
-
-   /** Pass the security info to the login modules configured for
-    this security domain using our SecurityAssociationHandler.
-    @return The authenticated Subject if successful.
-    @exception LoginException throw if login fails for any reason.
-    */
-   private LoginContext defaultLogin(Principal principal, Object credential)
-      throws LoginException
-   {
-      /* We use our internal CallbackHandler to provide the security info. A
-      copy must be made to ensure there is a unique handler per active
-      login since there can be multiple active logins.
-      */
-      Object[] securityInfo = {principal, credential};
-      CallbackHandler theHandler = null;
-      try
-      {
-         theHandler = (CallbackHandler) handler.getClass().newInstance();
-         setSecurityInfo.invoke(theHandler, securityInfo);
-      }
-      catch (Throwable e)
-      {
-         if( trace )
-            log.trace("Failed to create/setSecurityInfo on handler", e);
-         LoginException le = new LoginException("Failed to setSecurityInfo on handler");
-         le.initCause(e);
-         throw le;
-      }
-      Subject subject = new Subject();
-      LoginContext lc = null;
-      if( trace )
-         log.trace("defaultLogin, principal="+principal);
-      lc = SubjectActions.createLoginContext(securityDomain, subject, theHandler);
-      lc.login();
-      if( trace )
-         log.trace("defaultLogin, lc="+lc+", subject="+SubjectActions.toString(subject));
-      return lc;
-   }
-
-   /** Validate the cache credential value against the provided credential
-    */
-   @SuppressWarnings("unchecked")
-   private boolean validateCache(DomainInfo info, Object credential,
-      Subject theSubject)
-   {
-      if( trace )
-      {
-         StringBuffer tmp = new StringBuffer("Begin validateCache, info=");
-         tmp.append(info.toString());
-         tmp.append(";credential.class=");
-         if( credential != null )
-         {
-            Class c = credential.getClass();
-            tmp.append(c.getName());
-            tmp.append('@');
-            tmp.append(System.identityHashCode(c));
-         }
-         else
-         {
-            tmp.append("null");
-         }
-         log.trace(tmp.toString());
-      }
-
-      Object subjectCredential = info.credential;
-      boolean isValid = false;
-      // Check for a null credential as can be the case for an anonymous user
-      if( credential == null || subjectCredential == null )
-      {
-         // Both credentials must be null
-         isValid = (credential == null) && (subjectCredential == null);
-      }
-      // See if the credential is assignable to the cache value
-      else if( subjectCredential.getClass().isAssignableFrom(credential.getClass()) )
-      {
-        /* Validate the credential by trying Comparable, char[], byte[],
-         Object[], and finally Object.equals()
-         */
-         if( subjectCredential instanceof Comparable )
-         {
-            Comparable c = (Comparable) subjectCredential;
-            isValid = c.compareTo(credential) == 0;
-         }
-         else if( subjectCredential instanceof char[] )
-         {
-            char[] a1 = (char[]) subjectCredential;
-            char[] a2 = (char[]) credential;
-            isValid = Arrays.equals(a1, a2);
-         }
-         else if( subjectCredential instanceof byte[] )
-         {
-            byte[] a1 = (byte[]) subjectCredential;
-            byte[] a2 = (byte[]) credential;
-            isValid = Arrays.equals(a1, a2);
-         }
-         else if( subjectCredential.getClass().isArray() )
-         {
-            Object[] a1 = (Object[]) subjectCredential;
-            Object[] a2 = (Object[]) credential;
-            isValid = Arrays.equals(a1, a2);
-         }
-         else
-         {
-            isValid = subjectCredential.equals(credential);
-         }
-      }
-      else if( subjectCredential instanceof char[] && credential instanceof String )
-      {
-         char[] a1 = (char[]) subjectCredential;
-         char[] a2 = ((String) credential).toCharArray();
-         isValid = Arrays.equals(a1, a2);
-      }
-      else if( subjectCredential instanceof String && credential instanceof char[] )
-      {
-         char[] a1 = ((String) subjectCredential).toCharArray();
-         char[] a2 = (char[]) credential;
-         isValid = Arrays.equals(a1, a2);         
-      }
-
-      // If the credentials match, set the thread's active Subject
-      if( isValid )
-      {
-         // Copy the current subject into theSubject
-         if( theSubject != null )
-         {
-            SubjectActions.copySubject(info.subject, theSubject, false,this.deepCopySubjectOption);
-         }
-      }
-      if( trace )
-         log.trace("End validateCache, isValid="+isValid);
-
-      return isValid;
-   }
- 
-   /** An accessor method that synchronizes access on the domainCache
-    to avoid a race condition that can occur when the cache entry expires
-    in the presence of multi-threaded access. The allowRefresh flag should
-    be true for authentication accesses and false for other accesses.
-    Previously the other accesses included authorization and caller principal
-    mapping. Now the only use of the 
-
-    @param principal - the caller identity whose cached credentials are to
-    be accessed.
-    @param allowRefresh - a flag indicating if the cache access should flush
-    any expired entries.
-    */
-   private DomainInfo getCacheInfo(Principal principal, boolean allowRefresh)
-   {
-      if( domainCache == null )
-         return null;
-
-      DomainInfo cacheInfo = null;
-      synchronized( domainCache )
-      {
-          if( allowRefresh == true )
-            cacheInfo = (DomainInfo) domainCache.get(principal);
-          else
-            cacheInfo = (DomainInfo) domainCache.peek(principal);
-         if( cacheInfo != null )
-            cacheInfo.acquire();
-      }
-      return cacheInfo;
-   }
-
-   private Subject updateCache(LoginContext lc, Subject subject,
-      Principal principal, Object credential)
-   {
-      // If we don't have a cache there is nothing to update
-      if( domainCache == null )
-         return subject;
-
-      long lifetime = 0;
-      if( domainCache instanceof TimedCachePolicy )
-      {
-         TimedCachePolicy cache = (TimedCachePolicy) domainCache;
-         lifetime = cache.getDefaultLifetime();
-      }
-      DomainInfo info = new DomainInfo(lifetime);
-      info.loginCtx = lc;
-      info.subject = new Subject();
-      SubjectActions.copySubject(subject, info.subject, true, this.deepCopySubjectOption);
-      info.credential = credential;
-
-      if( trace )
-      {
-         log.trace("updateCache, inputSubject="+SubjectActions.toString(subject)
-            +", cacheSubject="+SubjectActions.toString(info.subject));
-      }
-
-     /* Get the Subject callerPrincipal by looking for a Group called
-        'CallerPrincipal'
-      */
-      Set<Group> subjectGroups = subject.getPrincipals(Group.class);
-      Iterator<Group> iter = subjectGroups.iterator();
-      while( iter.hasNext() )
-      {
-         Group grp = iter.next();
-         String name = grp.getName();
-         if( name.equals("CallerPrincipal") )
-         {
-            Enumeration<? extends Principal> members = grp.members();
-            if( members.hasMoreElements() )
-               info.callerPrincipal = members.nextElement();
-         }
-      }
-      
-     /* Handle null principals with no callerPrincipal. This is an indication
-        of an user that has not provided any authentication info, but
-        has been authenticated by the domain login module stack. Here we look
-        for the first non-Group Principal and use that.
-      */
-      if( principal == null && info.callerPrincipal == null )
-      {
-         Set<Principal> subjectPrincipals = subject.getPrincipals(Principal.class);
-         Iterator<? extends Principal> iterPrincipals = subjectPrincipals.iterator();
-         while( iterPrincipals.hasNext() )
-         {
-            Principal p = iterPrincipals.next();
-            if( (p instanceof Group) == false )
-               info.callerPrincipal = p;
-         }
-      }
-
-     /* If the user already exists another login is active. Currently
-        only one is allowed so remove the old and insert the new. Synchronize
-        on the domainCache to ensure the removal and addition are an atomic
-        operation so that getCacheInfo cannot see stale data.
-      */
-      synchronized( domainCache )
-      {
-         if( domainCache.peek(principal) != null )
-            domainCache.remove(principal);
-         domainCache.insert(principal, info);
-         if( trace )
-            log.trace("Inserted cache info: "+info);
-      }
-      return info.subject;
-   } 
-}
\ No newline at end of file

Copied: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/plugins/auth/JaasSecurityManagerBase.java (from rev 93325, projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/security/plugins/auth/JaasSecurityManagerBase.java)
===================================================================
--- projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/plugins/auth/JaasSecurityManagerBase.java	                        (rev 0)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/plugins/auth/JaasSecurityManagerBase.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -0,0 +1,758 @@
+/*
+* JBoss, Home of Professional Open Source
+* Copyright 2005, JBoss Inc., and individual contributors as indicated
+* by the @authors tag. See the copyright.txt in the distribution for a
+* full listing of individual contributors.
+*
+* This is free software; you can redistribute it and/or modify it
+* under the terms of the GNU Lesser General Public License as
+* published by the Free Software Foundation; either version 2.1 of
+* the License, or (at your option) any later version.
+*
+* This software is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+* Lesser General Public License for more details.
+*
+* You should have received a copy of the GNU Lesser General Public
+* License along with this software; if not, write to the Free
+* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+*/
+package org.jboss.security.plugins.auth;
+
+import java.lang.reflect.Method;
+import java.lang.reflect.UndeclaredThrowableException;
+import java.security.Principal;
+import java.security.acl.Group;
+import java.util.Arrays;
+import java.util.Enumeration;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Set;
+
+import javax.security.auth.Subject;
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.login.LoginContext;
+import javax.security.auth.login.LoginException;
+
+import org.jboss.logging.Logger;
+import org.jboss.security.AuthenticationManager;
+import org.jboss.security.AuthorizationManager;
+import org.jboss.security.RealmMapping;
+import org.jboss.security.SecurityConstants;
+import org.jboss.security.SecurityContext;
+import org.jboss.security.SecurityContextAssociation;
+import org.jboss.security.SecurityUtil;
+import org.jboss.security.SubjectSecurityManager;
+import org.jboss.security.auth.callback.JBossCallbackHandler;
+import org.jboss.util.CachePolicy;
+import org.jboss.util.TimedCachePolicy;
+
+/** The JaasSecurityManager is responsible both for authenticating credentials
+ associated with principals and for role mapping. This implementation relies
+ on the JAAS LoginContext/LoginModules associated with the security
+ domain name associated with the class for authentication,
+ and the context JAAS Subject object for role mapping.
+ 
+ @see #isValid(Principal, Object, Subject)
+ @see #getPrincipal(Principal)
+ @see #doesUserHaveRole(Principal, Set)
+ 
+ @author <a href="on at ibis.odessa.ua">Oleg Nitz</a>
+ @author Scott.Stark at jboss.org
+ @author Anil.Saldhana at jboss.org
+ @version $Revision: 62860 $
+*/
+public class JaasSecurityManagerBase 
+   implements SubjectSecurityManager, RealmMapping
+{
+   /** The authentication cache object.
+    */
+   public static class DomainInfo implements TimedCachePolicy.TimedEntry
+   {
+      private static Logger log = Logger.getLogger(DomainInfo.class);
+      private static boolean trace = log.isTraceEnabled();
+      protected LoginContext loginCtx;
+      protected Subject subject;
+      protected Object credential;
+      protected Principal callerPrincipal;
+      private long expirationTime;
+      /** Is there an active authentication in process */
+      private boolean needsDestroy;
+      /** The number of users sharing this DomainInfo */
+      private int activeUsers;
+
+      /**
+       Create a cache entry with the given lifetime in seconds. Since this comes
+       from the TimedCachePolicy, its expected to be <= Integer.MAX_VALUE.
+       
+       @param lifetime - lifetime in seconds. A lifetime <= 0 means no caching
+         with the exception of -1 which indicates that the cache entry never
+         expires.
+       */
+      public DomainInfo(long lifetime)
+      {
+         expirationTime = lifetime;
+         if( expirationTime != -1 )
+            expirationTime *= 1000;
+      }
+
+      synchronized int acquire()
+      {
+         return activeUsers ++;
+      }
+      synchronized int release()
+      {
+         int users = activeUsers --;
+         if( needsDestroy == true && users == 0 )
+         {
+            if( trace )
+               log.trace("needsDestroy is true, doing logout");
+            logout();
+         }
+         return users;
+      }
+      synchronized void logout()
+      {
+         if( trace )
+            log.trace("logout, subject="+subject+", this="+this);
+         try
+         {
+            if( loginCtx != null )
+               loginCtx.logout();
+         }
+         catch(Throwable e)
+         {
+            if( trace )
+               log.trace("Cache entry logout failed", e);
+         }
+      }
+
+      public void init(long now)
+      {
+         expirationTime += now;
+      }
+      public boolean isCurrent(long now)
+      {
+         boolean isCurrent = expirationTime == -1;
+         if( isCurrent == false )
+            isCurrent = expirationTime > now;
+         return isCurrent;
+      }
+      public boolean refresh()
+      {
+         return false;
+      }
+      /**
+       * This 
+       */ 
+      public void destroy()
+      {
+         if( trace )
+         {
+            log.trace("destroy, subject="+subject+", this="+this
+               +", activeUsers="+activeUsers);
+         }
+
+         synchronized( this )
+         {
+            if( activeUsers == 0 )
+               logout();
+            else
+            {
+               if( trace )
+                  log.trace("destroy saw activeUsers="+activeUsers);
+               needsDestroy = true;
+            }
+         }
+      }
+      public Object getValue()
+      {
+         return this;
+      }
+      public String toString()
+      {
+         StringBuffer tmp = new StringBuffer(super.toString());
+         tmp.append('[');
+         tmp.append(SubjectActions.toString(subject));
+         tmp.append(",credential.class=");
+         if( credential != null )
+         {
+            Class<?> c = credential.getClass();
+            tmp.append(c.getName());
+            tmp.append('@');
+            tmp.append(System.identityHashCode(c));
+         }
+         else
+         {
+            tmp.append("null");
+         }
+         tmp.append(",expirationTime=");
+         tmp.append(expirationTime);
+         tmp.append(']');
+
+         return tmp.toString();
+      }
+   }
+
+   /** The name of the domain this instance is securing. It is used as
+    the appName into the SecurityPolicy.
+    */
+   private String securityDomain;
+   /** A cache of DomainInfo objects keyd by Principal. This is now
+    always set externally by our security manager service.
+    */
+   private CachePolicy domainCache;
+   /** The JAAS callback handler to use in defaultLogin */
+   private CallbackHandler handler;
+   /** The setSecurityInfo(Principal, Object) method of the handler obj */
+   private transient Method setSecurityInfo;
+   /** The flag to indicate that the Subject sets need to be deep copied*/
+   private boolean deepCopySubjectOption = false; 
+   
+   /** The log4j category for the security manager domain
+    */
+   protected Logger log;
+   protected boolean trace;
+   private AuthorizationManager authorizationManager;
+
+   /** Creates a default JaasSecurityManager for with a securityDomain
+    name of 'other'.
+    */
+   public JaasSecurityManagerBase()
+   {
+      this("other", new JBossCallbackHandler());
+   }
+   /** Creates a JaasSecurityManager for with a securityDomain
+    name of that given by the 'securityDomain' argument.
+    @param securityDomain the name of the security domain
+    @param handler the JAAS callback handler instance to use
+    @exception UndeclaredThrowableException thrown if handler does not
+      implement a setSecurityInfo(Princpal, Object) method
+    */
+   public JaasSecurityManagerBase(String securityDomain, CallbackHandler handler)
+   {
+      this.securityDomain = securityDomain;
+      this.handler = handler;
+      String categoryName = getClass().getName()+'.'+securityDomain;
+      this.log = Logger.getLogger(categoryName);
+      this.trace = log.isTraceEnabled();
+
+      // Get the setSecurityInfo(Principal principal, Object credential) method
+      Class<?>[] sig = {Principal.class, Object.class};
+      try
+      {
+         setSecurityInfo = handler.getClass().getMethod("setSecurityInfo", sig);
+      }
+      catch (Exception e)
+      {
+         String msg = "Failed to find setSecurityInfo(Princpal, Object) method in handler";
+         throw new UndeclaredThrowableException(e, msg);
+      } 
+      log.debug("CallbackHandler: "+handler);
+   }
+
+   /** The domainCache is typically a shared object that is populated
+    by the login code(LoginModule, etc.) and read by this class in the
+    isValid() method.
+    @see #isValid(Principal, Object, Subject)
+    */
+   public void setCachePolicy(CachePolicy domainCache)
+   {
+      this.domainCache = domainCache;
+      log.debug("CachePolicy set to: "+domainCache);
+   }
+
+   /**
+    * Flag to specify if deep copy of subject sets needs to be 
+    * enabled
+    * 
+    * @param flag
+    */
+   public void setDeepCopySubjectOption(Boolean flag)
+   {
+      log.debug("setDeepCopySubjectOption="+ flag);
+      this.deepCopySubjectOption = (flag == Boolean.TRUE) ;
+   } 
+   
+   /**
+    * Set an AuthorizationManager
+    * @param authorizationManager
+    */
+   public void setAuthorizationManager(AuthorizationManager authorizationManager)
+   {
+      this.authorizationManager = authorizationManager;
+   }
+   
+   /** Not really used anymore as the security manager service manages the
+    security domain authentication caches.
+    */
+   public void flushCache()
+   {
+      if( domainCache != null )
+         domainCache.flush();
+   }
+
+   /** Get the name of the security domain associated with this security mgr.
+    @return Name of the security manager security domain.
+    */
+   public String getSecurityDomain()
+   {
+      return securityDomain;
+   }
+
+   /** Get the currently authenticated Subject. This is a thread local
+    property shared across all JaasSecurityManager instances.
+    @return The Subject authenticated in the current thread if one
+    exists, null otherwise.
+    */
+   public Subject getActiveSubject()
+   {
+      /* This does not use SubjectActions.getActiveSubject since the caller
+         must have the correct permissions to access the
+         SecurityAssociation.getSubject method.
+      */
+      //return SecurityAssociation.getSubject();
+      Subject subj = null;
+      SecurityContext sc = SecurityContextAssociation.getSecurityContext();
+      if(sc != null)
+      {
+         subj = sc.getUtil().getSubject();
+      }
+      return subj;
+   }
+
+   /** Validate that the given credential is correct for principal. This
+    returns the value from invoking isValid(principal, credential, null).
+    @param principal - the security domain principal attempting access
+    @param credential - the proof of identity offered by the principal
+    @return true if the principal was authenticated, false otherwise.
+    */
+   public boolean isValid(Principal principal, Object credential)
+   {
+      return isValid(principal, credential, null);
+   }
+
+   /** Validate that the given credential is correct for principal. This first
+    will check the current CachePolicy object if one exists to see if the
+    user's cached credentials match the given credential. If there is no
+    credential cache or the cache information is invalid or does not match,
+    the user is authenticated against the JAAS login modules configured for
+    the security domain.
+    @param principal - the security domain principal attempting access
+    @param credential  the proof of identity offered by the principal
+    @param activeSubject - if not null, a Subject that will be populated with
+      the state of the authenticated Subject.
+    @return true if the principal was authenticated, false otherwise.
+    */
+   public boolean isValid(Principal principal, Object credential,
+      Subject activeSubject)
+   {
+      // Check the cache first
+      DomainInfo cacheInfo = getCacheInfo(principal, true);
+      if( trace )
+         log.trace("Begin isValid, principal:"+principal+", cache info: "+cacheInfo);
+
+      boolean isValid = false;
+      if( cacheInfo != null )
+      {
+         isValid = validateCache(cacheInfo, credential, activeSubject);
+         if( cacheInfo != null )
+            cacheInfo.release();
+      }
+      if( isValid == false )
+         isValid = authenticate(principal, credential, activeSubject);
+      if( trace )
+         log.trace("End isValid, "+isValid); 
+      return isValid;
+   } 
+
+   
+   /** Map the argument principal from the deployment environment principal
+    to the developer environment. This is called by the EJB context
+    getCallerPrincipal() to return the Principal as described by
+    the EJB developer domain.
+    @return a Principal object that is valid in the deployment environment
+    if one exists. If no Subject exists or the Subject has no principals
+    then the argument principal is returned.
+    */
+   public Principal getPrincipal(Principal principal)
+   {
+      if(domainCache == null)
+         return principal;
+      Principal result = principal; 
+      // Get the CallerPrincipal group member
+      synchronized( domainCache )
+      {
+         DomainInfo info = getCacheInfo(principal, false);
+         if( trace )
+            log.trace("getPrincipal, cache info: "+info);
+         if( info != null )
+         {
+            result = info.callerPrincipal;
+            // If the mapping did not have a callerPrincipal just use principal
+            if( result == null )
+               result = principal;
+            info.release();
+         }
+      }
+
+      return result;
+   }
+
+   /** Does the current Subject have a role(a Principal) that equates to one
+    of the role names. This method obtains the Group named 'Roles' from
+    the principal set of the currently authenticated Subject as determined
+    by the SecurityAssociation.getSubject() method and then creates a
+    SimplePrincipal for each name in roleNames. If the role is a member of the
+    Roles group, then the user has the role. This requires that the caller
+    establish the correct SecurityAssociation subject prior to calling this
+    method. In the past this was done as a side-effect of an isValid() call,
+    but this is no longer the case.
+
+    @param principal - ignored. The current authenticated Subject determines
+    the active user and assigned user roles.
+    @param rolePrincipals - a Set of Principals for the roles to check.
+    
+    @see java.security.acl.Group;
+    @see Subject#getPrincipals()
+    */
+   public boolean doesUserHaveRole(Principal principal, Set<Principal> rolePrincipals)
+   { 
+      if(this.authorizationManager == null)
+      {
+         this.authorizationManager = SecurityUtil.getAuthorizationManager(securityDomain, 
+               SecurityConstants.JAAS_CONTEXT_ROOT); 
+      }
+      if(this.authorizationManager == null)
+      {
+         if(trace)
+            log.trace("doesUserHaveRole:AuthorizationManager is null");
+         return false;
+      }
+      return authorizationManager.doesUserHaveRole(principal, rolePrincipals); 
+   } 
+
+   /** Return the set of domain roles the current active Subject 'Roles' group
+      found in the subject Principals set.
+
+    @param principal - ignored. The current authenticated Subject determines
+    the active user and assigned user roles.
+    @return The Set<Principal> for the application domain roles that the
+    principal has been assigned.
+   */
+   @SuppressWarnings("deprecation")
+   public Set<Principal> getUserRoles(Principal principal)
+   {
+      if(this.authorizationManager == null)
+      {
+         this.authorizationManager = SecurityUtil.getAuthorizationManager(securityDomain, 
+               SecurityConstants.JAAS_CONTEXT_ROOT); 
+      }
+      if(this.authorizationManager == null)
+      {
+         log.trace("doesUserHaveRole:AuthorizationManager is null");
+         return null;
+      }
+      return authorizationManager.getUserRoles(principal);
+   } 
+   
+   /**
+    * @see AuthenticationManager#getTargetPrincipal(Principal,Map)
+    */
+   public Principal getTargetPrincipal(Principal anotherDomainPrincipal, 
+         Map<String,Object> contextMap)
+   {
+      throw new RuntimeException("Not implemented yet");
+   }
+
+   /** Currently this simply calls defaultLogin() to do a JAAS login using the
+    security domain name as the login module configuration name.
+    
+    * @param principal - the user id to authenticate
+    * @param credential - an opaque credential.
+    * @return false on failure, true on success.
+    */
+   private boolean authenticate(Principal principal, Object credential,
+      Subject theSubject)
+   {
+      Subject subject = null;
+      boolean authenticated = false;
+      LoginException authException = null;
+
+      try
+      {
+         // Validate the principal using the login configuration for this domain
+         LoginContext lc = defaultLogin(principal, credential);
+         subject = lc.getSubject();
+
+         // Set the current subject if login was successful
+         if( subject != null )
+         {
+            // Copy the current subject into theSubject
+            if( theSubject != null )
+            {
+               SubjectActions.copySubject(subject, theSubject, false,this.deepCopySubjectOption);
+            }
+            else
+            {
+               theSubject = subject;
+            }
+
+            authenticated = true;
+            // Build the Subject based DomainInfo cache value
+            updateCache(lc, subject, principal, credential);
+         }
+      }
+      catch(LoginException e)
+      {
+         // Don't log anonymous user failures unless trace level logging is on
+         if( principal != null && principal.getName() != null || trace )
+            log.trace("Login failure", e);
+         authException = e;
+      }
+      // Set the security association thread context info exception
+      SubjectActions.setContextInfo("org.jboss.security.exception", authException);
+
+      return authenticated;
+   }
+
+   /** Pass the security info to the login modules configured for
+    this security domain using our SecurityAssociationHandler.
+    @return The authenticated Subject if successful.
+    @exception LoginException throw if login fails for any reason.
+    */
+   private LoginContext defaultLogin(Principal principal, Object credential)
+      throws LoginException
+   {
+      /* We use our internal CallbackHandler to provide the security info. A
+      copy must be made to ensure there is a unique handler per active
+      login since there can be multiple active logins.
+      */
+      Object[] securityInfo = {principal, credential};
+      CallbackHandler theHandler = null;
+      try
+      {
+         theHandler = (CallbackHandler) handler.getClass().newInstance();
+         setSecurityInfo.invoke(theHandler, securityInfo);
+      }
+      catch (Throwable e)
+      {
+         if( trace )
+            log.trace("Failed to create/setSecurityInfo on handler", e);
+         LoginException le = new LoginException("Failed to setSecurityInfo on handler");
+         le.initCause(e);
+         throw le;
+      }
+      Subject subject = new Subject();
+      LoginContext lc = null;
+      if( trace )
+         log.trace("defaultLogin, principal="+principal);
+      lc = SubjectActions.createLoginContext(securityDomain, subject, theHandler);
+      lc.login();
+      if( trace )
+         log.trace("defaultLogin, lc="+lc+", subject="+SubjectActions.toString(subject));
+      return lc;
+   }
+
+   /** Validate the cache credential value against the provided credential
+    */
+   @SuppressWarnings("unchecked")
+   private boolean validateCache(DomainInfo info, Object credential,
+      Subject theSubject)
+   {
+      if( trace )
+      {
+         StringBuffer tmp = new StringBuffer("Begin validateCache, info=");
+         tmp.append(info.toString());
+         tmp.append(";credential.class=");
+         if( credential != null )
+         {
+            Class c = credential.getClass();
+            tmp.append(c.getName());
+            tmp.append('@');
+            tmp.append(System.identityHashCode(c));
+         }
+         else
+         {
+            tmp.append("null");
+         }
+         log.trace(tmp.toString());
+      }
+
+      Object subjectCredential = info.credential;
+      boolean isValid = false;
+      // Check for a null credential as can be the case for an anonymous user
+      if( credential == null || subjectCredential == null )
+      {
+         // Both credentials must be null
+         isValid = (credential == null) && (subjectCredential == null);
+      }
+      // See if the credential is assignable to the cache value
+      else if( subjectCredential.getClass().isAssignableFrom(credential.getClass()) )
+      {
+        /* Validate the credential by trying Comparable, char[], byte[],
+         Object[], and finally Object.equals()
+         */
+         if( subjectCredential instanceof Comparable )
+         {
+            Comparable c = (Comparable) subjectCredential;
+            isValid = c.compareTo(credential) == 0;
+         }
+         else if( subjectCredential instanceof char[] )
+         {
+            char[] a1 = (char[]) subjectCredential;
+            char[] a2 = (char[]) credential;
+            isValid = Arrays.equals(a1, a2);
+         }
+         else if( subjectCredential instanceof byte[] )
+         {
+            byte[] a1 = (byte[]) subjectCredential;
+            byte[] a2 = (byte[]) credential;
+            isValid = Arrays.equals(a1, a2);
+         }
+         else if( subjectCredential.getClass().isArray() )
+         {
+            Object[] a1 = (Object[]) subjectCredential;
+            Object[] a2 = (Object[]) credential;
+            isValid = Arrays.equals(a1, a2);
+         }
+         else
+         {
+            isValid = subjectCredential.equals(credential);
+         }
+      }
+      else if( subjectCredential instanceof char[] && credential instanceof String )
+      {
+         char[] a1 = (char[]) subjectCredential;
+         char[] a2 = ((String) credential).toCharArray();
+         isValid = Arrays.equals(a1, a2);
+      }
+      else if( subjectCredential instanceof String && credential instanceof char[] )
+      {
+         char[] a1 = ((String) subjectCredential).toCharArray();
+         char[] a2 = (char[]) credential;
+         isValid = Arrays.equals(a1, a2);         
+      }
+
+      // If the credentials match, set the thread's active Subject
+      if( isValid )
+      {
+         // Copy the current subject into theSubject
+         if( theSubject != null )
+         {
+            SubjectActions.copySubject(info.subject, theSubject, false,this.deepCopySubjectOption);
+         }
+      }
+      if( trace )
+         log.trace("End validateCache, isValid="+isValid);
+
+      return isValid;
+   }
+ 
+   /** An accessor method that synchronizes access on the domainCache
+    to avoid a race condition that can occur when the cache entry expires
+    in the presence of multi-threaded access. The allowRefresh flag should
+    be true for authentication accesses and false for other accesses.
+    Previously the other accesses included authorization and caller principal
+    mapping. Now the only use of the 
+
+    @param principal - the caller identity whose cached credentials are to
+    be accessed.
+    @param allowRefresh - a flag indicating if the cache access should flush
+    any expired entries.
+    */
+   private DomainInfo getCacheInfo(Principal principal, boolean allowRefresh)
+   {
+      if( domainCache == null )
+         return null;
+
+      DomainInfo cacheInfo = null;
+      synchronized( domainCache )
+      {
+          if( allowRefresh == true )
+            cacheInfo = (DomainInfo) domainCache.get(principal);
+          else
+            cacheInfo = (DomainInfo) domainCache.peek(principal);
+         if( cacheInfo != null )
+            cacheInfo.acquire();
+      }
+      return cacheInfo;
+   }
+
+   private Subject updateCache(LoginContext lc, Subject subject,
+      Principal principal, Object credential)
+   {
+      // If we don't have a cache there is nothing to update
+      if( domainCache == null )
+         return subject;
+
+      long lifetime = 0;
+      if( domainCache instanceof TimedCachePolicy )
+      {
+         TimedCachePolicy cache = (TimedCachePolicy) domainCache;
+         lifetime = cache.getDefaultLifetime();
+      }
+      DomainInfo info = new DomainInfo(lifetime);
+      info.loginCtx = lc;
+      info.subject = new Subject();
+      SubjectActions.copySubject(subject, info.subject, true, this.deepCopySubjectOption);
+      info.credential = credential;
+
+      if( trace )
+      {
+         log.trace("updateCache, inputSubject="+SubjectActions.toString(subject)
+            +", cacheSubject="+SubjectActions.toString(info.subject));
+      }
+
+     /* Get the Subject callerPrincipal by looking for a Group called
+        'CallerPrincipal'
+      */
+      Set<Group> subjectGroups = subject.getPrincipals(Group.class);
+      Iterator<Group> iter = subjectGroups.iterator();
+      while( iter.hasNext() )
+      {
+         Group grp = iter.next();
+         String name = grp.getName();
+         if( name.equals("CallerPrincipal") )
+         {
+            Enumeration<? extends Principal> members = grp.members();
+            if( members.hasMoreElements() )
+               info.callerPrincipal = members.nextElement();
+         }
+      }
+      
+     /* Handle null principals with no callerPrincipal. This is an indication
+        of an user that has not provided any authentication info, but
+        has been authenticated by the domain login module stack. Here we look
+        for the first non-Group Principal and use that.
+      */
+      if( principal == null && info.callerPrincipal == null )
+      {
+         Set<Principal> subjectPrincipals = subject.getPrincipals(Principal.class);
+         Iterator<? extends Principal> iterPrincipals = subjectPrincipals.iterator();
+         while( iterPrincipals.hasNext() )
+         {
+            Principal p = iterPrincipals.next();
+            if( (p instanceof Group) == false )
+               info.callerPrincipal = p;
+         }
+      }
+
+     /* If the user already exists another login is active. Currently
+        only one is allowed so remove the old and insert the new. Synchronize
+        on the domainCache to ensure the removal and addition are an atomic
+        operation so that getCacheInfo cannot see stale data.
+      */
+      synchronized( domainCache )
+      {
+         if( domainCache.peek(principal) != null )
+            domainCache.remove(principal);
+         domainCache.insert(principal, info);
+         if( trace )
+            log.trace("Inserted cache info: "+info);
+      }
+      return info.subject;
+   } 
+}
\ No newline at end of file

Deleted: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/plugins/authorization/JBossAuthorizationContext.java
===================================================================
--- projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/security/plugins/authorization/JBossAuthorizationContext.java	2009-07-21 21:59:08 UTC (rev 91524)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/plugins/authorization/JBossAuthorizationContext.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -1,380 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source
- * Copyright 2005, JBoss Inc., and individual contributors as indicated
- * by the @authors tag. See the copyright.txt in the distribution for a
- * full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jboss.security.plugins.authorization;
- 
-import java.security.AccessController;
-import java.security.PrivilegedActionException;
-import java.security.PrivilegedExceptionAction;
-import java.util.Map;
-
-import javax.security.auth.Subject;
-import javax.security.auth.callback.CallbackHandler;
-
-import org.jboss.logging.Logger;
-import org.jboss.security.SecurityConstants;
-import org.jboss.security.authorization.AuthorizationContext;
-import org.jboss.security.authorization.AuthorizationException;
-import org.jboss.security.authorization.AuthorizationModule;
-import org.jboss.security.authorization.Resource;
-import org.jboss.security.authorization.ResourceKeys;
-import org.jboss.security.authorization.ResourceType;
-import org.jboss.security.authorization.config.AuthorizationModuleEntry;
-import org.jboss.security.authorization.modules.DelegatingAuthorizationModule;
-import org.jboss.security.config.ApplicationPolicy;
-import org.jboss.security.config.AuthorizationInfo;
-import org.jboss.security.config.ControlFlag;
-import org.jboss.security.config.SecurityConfiguration;
-import org.jboss.security.identity.Role;
-import org.jboss.security.identity.RoleGroup;
-
-//$Id: JBossAuthorizationContext.java 62954 2007-05-10 04:12:18Z anil.saldhana at jboss.com $
-
-/**
- *  JBAS-3374: Authorization Framework for Policy Decision Modules
- *  For information on the behavior of the Authorization Modules,
- *  For Authorization Modules behavior(Required, Requisite, Sufficient and Optional)
- *  please refer to the javadoc for @see javax.security.auth.login.Configuration
- *  
- *  The AuthorizationContext derives the AuthorizationInfo(configuration for the modules)
- *  in the following way:
- *  a) If there has been an injection of ApplicationPolicy, then it will be used.
- *  b) Util.getApplicationPolicy will be used(which relies on SecurityConfiguration static class).
- *  c) Flag an error that there is no available Application Policy
- *  
- *  @author <a href="mailto:Anil.Saldhana at jboss.org">Anil Saldhana</a>
- *  @since  Jun 11, 2006 
- *  @version $Revision: 62954 $
- */
-public class JBossAuthorizationContext extends AuthorizationContext
-{
-   private static Logger log = Logger.getLogger(JBossAuthorizationContext.class);
-   private boolean trace = log.isTraceEnabled(); 
-   
-   private final String EJB = SecurityConstants.DEFAULT_EJB_APPLICATION_POLICY;
-   private final String WEB = SecurityConstants.DEFAULT_WEB_APPLICATION_POLICY;
-   
-   private Subject authenticatedSubject = null;
-    
-   //Application Policy can be injected
-   private ApplicationPolicy applicationPolicy = null; 
-   
-   public JBossAuthorizationContext(String name)
-   {
-      this.securityDomainName = name;
-   }
-   
-   public JBossAuthorizationContext(String name, CallbackHandler handler)
-   {
-      this(name);
-      this.callbackHandler = handler; 
-   }
-   
-   public JBossAuthorizationContext(String name, Subject subject, CallbackHandler handler)
-   {
-      this(name,handler); 
-      this.authenticatedSubject = subject; 
-   }
-   
-   /**
-    * Inject an ApplicationPolicy that contains AuthorizationInfo
-    * @param aPolicy
-    * @throws IllegalArgumentException if ApplicationPolicy is null or
-    *    does not contain AuthorizationInfo or domain name does not match
-    */
-   public void setApplicationPolicy(ApplicationPolicy aPolicy)
-   {
-      if(aPolicy == null)
-         throw new IllegalArgumentException("Application Policy is null:domain="+this.securityDomainName);
-      AuthorizationInfo authzInfo = aPolicy.getAuthorizationInfo();
-      if( authzInfo == null)
-         throw new IllegalArgumentException("Application Policy has no AuthorizationInfo");
-      if(!authzInfo.getName().equals(securityDomainName))
-         throw new IllegalArgumentException("Application Policy ->AuthorizationInfo:" + authzInfo.getName()
-               + " does not match required domain name=" + this.securityDomainName); 
-      this.applicationPolicy = aPolicy; 
-   }
-    
-   
-   /**
-    * Authorize the Resource
-    * @param resource
-    * @return AuthorizationContext.PERMIT or AuthorizationContext.DENY
-    * @throws AuthorizationException
-    */
-   public int authorize(final Resource resource) throws AuthorizationException
-   { 
-      return this.authorize(resource, this.authenticatedSubject, 
-            (RoleGroup)resource.getMap().get(ResourceKeys.SECURITY_CONTEXT_ROLES)); 
-  } 
-   
-   /**
-    * @see AuthorizationContext#authorize(Resource, Role)
-    */
-   public int authorize(final Resource resource, 
-         final Subject subject, 
-         final RoleGroup callerRoles) throws AuthorizationException
-   {   
-      try
-      {
-         this.authenticatedSubject = subject;
-         initializeModules(resource, callerRoles);
-      }
-      catch (PrivilegedActionException e1)
-      {
-         throw new RuntimeException(e1);
-      } 
-      //Do a PrivilegedAction
-      try
-      {
-         AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() 
-         {
-            public Object run() throws AuthorizationException 
-            {
-               int result = invokeAuthorize(resource);
-               if(result == PERMIT)
-                  invokeCommit();
-               if(result == DENY)
-               {
-                  invokeAbort();
-                  throw new AuthorizationException("Denied"); 
-               } 
-               return null;
-            }
-         });
-      }
-      catch (PrivilegedActionException e)
-      {
-         Exception exc = e.getException(); 
-         if(trace)
-           log.trace("Error in authorize:", exc); 
-         invokeAbort();
-         throw ((AuthorizationException)exc);
-      }
-      return PERMIT;
-      //return authorize(resource);
-   }
-   
-   //Private Methods  
-   private void initializeModules(Resource resource, RoleGroup role) throws PrivilegedActionException
-   { 
-      AuthorizationInfo authzInfo = getAuthorizationInfo(securityDomainName, resource); 
-      if(authzInfo == null)
-         throw new IllegalStateException("Authorization Info is null");
-      AuthorizationModuleEntry[] entries = authzInfo.getAuthorizationModuleEntry();
-      int len = entries != null ? entries.length : 0;
-      for(int i = 0 ; i < len; i++)
-      {
-         AuthorizationModuleEntry entry = entries[i];
-         ControlFlag flag = entry.getControlFlag();
-         if(flag == null)
-         {
-            if(trace)
-               log.trace("Null Control flag for entry:"+entry+". Defaults to REQUIRED!");
-            flag = ControlFlag.REQUIRED;
-         }
-         else
-            if(trace)
-               log.trace("Control flag for entry:"+entry+"is:["+flag+"]");
-            
-         this.controlFlags.add(flag);
-         modules.add(instantiateModule(entry.getPolicyModuleName(), entry.getOptions(), role)); 
-      }
-   }
-   
-   private int invokeAuthorize(Resource resource) 
-   throws AuthorizationException
-   {
-      //Control Flag behavior
-      boolean encounteredRequiredError = false; 
-      boolean encounteredOptionalError = false; 
-      AuthorizationException moduleException = null;
-      int overallDecision = DENY;
-      
-      int length = modules.size();
-      for(int i = 0; i < length; i++)
-      {
-         AuthorizationModule module = (AuthorizationModule)modules.get(i);
-         ControlFlag flag = (ControlFlag)this.controlFlags.get(i); 
-         int decision = DENY;
-         try
-         {
-            decision = module.authorize(resource);
-         }
-         catch(Exception ae)
-         { 
-            decision = DENY;
-            if(moduleException == null)
-               moduleException = new AuthorizationException(ae.getMessage());
-         }
-         
-         if(decision == PERMIT)
-         { 
-            overallDecision =  PERMIT;
-            //SUFFICIENT case
-            if(flag == ControlFlag.SUFFICIENT && encounteredRequiredError == false)
-               return PERMIT;
-            continue; //Continue with the other modules
-         }
-         //Go through the failure cases 
-         //REQUISITE case
-         if(flag == ControlFlag.REQUISITE)
-         {
-            if(trace)
-               log.trace("REQUISITE failed for " + module); 
-            if(moduleException == null)
-               moduleException = new AuthorizationException("Authorization failed");
-            else
-               throw moduleException;
-         }
-         //REQUIRED Case
-         if(flag == ControlFlag.REQUIRED)
-         {
-            if(trace)
-               log.trace("REQUIRED failed for " + module);
-            if(encounteredRequiredError == false)
-               encounteredRequiredError = true;
-         }
-         if(flag == ControlFlag.OPTIONAL)
-            encounteredOptionalError = true; 
-      }
-      
-      //All the authorization modules have been visited.
-      String msg = getAdditionalErrorMessage(moduleException);
-      if(encounteredRequiredError)
-         throw new AuthorizationException("Authorization Failed:"+ msg);
-      if(overallDecision == DENY && encounteredOptionalError)
-         throw new AuthorizationException("Authorization Failed:" + msg);
-      if(overallDecision == DENY)
-         throw new AuthorizationException("Authorization Failed:Denied.");
-      return PERMIT;
-   }
-   
-   private void invokeCommit()
-   throws AuthorizationException
-   {
-      int length = modules.size();
-      for(int i = 0; i < length; i++)
-      {
-         AuthorizationModule module = (AuthorizationModule)modules.get(i); 
-         boolean bool = module.commit();
-         if(!bool)
-            throw new AuthorizationException("commit on modules failed:"+module.getClass());
-      } 
-      modules.clear();
-   }
-   
-   private void invokeAbort()
-   throws AuthorizationException
-   {
-      int length = modules.size();
-      for(int i = 0; i < length; i++)
-      {
-         AuthorizationModule module = (AuthorizationModule)modules.get(i); 
-         boolean bool = module.abort(); 
-         if(!bool)
-            throw new AuthorizationException("abort on modules failed:"+module.getClass());
-      } 
-      modules.clear();
-   }
-   
-   private AuthorizationModule instantiateModule(String name, 
-         Map<String,Object> map, RoleGroup subjectRoles) 
-   throws PrivilegedActionException
-   {
-      AuthorizationModule am = null;
-      ClassLoader tcl = SecurityActions.getContextClassLoader();
-      try
-      {
-         Class<?> clazz = tcl.loadClass(name);
-         am = (AuthorizationModule)clazz.newInstance();
-      }
-      catch ( Exception e)
-      {
-         log.debug("Error instantiating AuthorizationModule:",e);
-      } 
-      if(am == null)
-         throw new IllegalStateException("AuthorizationModule has not " +
-               "been instantiated"); 
-      am.initialize(this.authenticatedSubject, this.callbackHandler, 
-            this.sharedState,map, subjectRoles); 
-      return am;
-   }
-   
-   private AuthorizationInfo getAuthorizationInfo(String domainName, Resource resource)
-   {
-      ResourceType layer = resource.getLayer();
-      
-      //Check if an instance of ApplicationPolicy is available 
-      if(this.applicationPolicy != null)
-         return applicationPolicy.getAuthorizationInfo();
-       
-      ApplicationPolicy aPolicy = SecurityConfiguration.getApplicationPolicy(domainName); 
-      
-      if(aPolicy == null)
-      {
-         if(trace)
-            log.trace("Application Policy not obtained for domain="+ domainName +
-                         ". Trying to obtain the App policy for the default domain of the layer:" 
-                  + layer);
-         if(layer == ResourceType.EJB)
-            aPolicy = SecurityConfiguration.getApplicationPolicy(EJB); 
-         else
-            if(layer == ResourceType.WEB)
-               aPolicy = SecurityConfiguration.getApplicationPolicy(WEB); 
-      }
-      if(aPolicy == null)
-         throw new IllegalStateException("Application Policy is null for domain:"+ domainName);
-      
-      AuthorizationInfo ai = aPolicy.getAuthorizationInfo();
-      if(ai == null)
-         return getAuthorizationInfo(layer);
-      else 
-         return aPolicy.getAuthorizationInfo();
-   } 
-   
-   private AuthorizationInfo getAuthorizationInfo(ResourceType layer)
-   {
-      AuthorizationInfo ai = null;
-      
-      if(layer == ResourceType.EJB)
-         ai = SecurityConfiguration.getApplicationPolicy(EJB).getAuthorizationInfo();
-      else
-         if(layer == ResourceType.WEB)
-            ai = SecurityConfiguration.getApplicationPolicy(WEB).getAuthorizationInfo();
-         else
-         {
-            if(log.isTraceEnabled())
-               log.trace("AuthorizationInfo not found. Providing default authorization info");
-            ai = new AuthorizationInfo(SecurityConstants.DEFAULT_APPLICATION_POLICY);
-            ai.add(new AuthorizationModuleEntry(DelegatingAuthorizationModule.class.getName()));
-         }
-      return ai;
-   }
-   
-   private String getAdditionalErrorMessage(Exception e)
-   {
-      StringBuilder msg = new StringBuilder(" ");
-      if(e != null)
-         msg.append(e.getLocalizedMessage());
-      return msg.toString();
-   }
-}
\ No newline at end of file

Copied: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/plugins/authorization/JBossAuthorizationContext.java (from rev 93325, projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/security/plugins/authorization/JBossAuthorizationContext.java)
===================================================================
--- projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/plugins/authorization/JBossAuthorizationContext.java	                        (rev 0)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/plugins/authorization/JBossAuthorizationContext.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -0,0 +1,381 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005, JBoss Inc., and individual contributors as indicated
+ * by the @authors tag. See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.security.plugins.authorization;
+ 
+import java.security.AccessController;
+import java.security.PrivilegedActionException;
+import java.security.PrivilegedExceptionAction;
+import java.util.Map;
+
+import javax.security.auth.Subject;
+import javax.security.auth.callback.CallbackHandler;
+
+import org.jboss.logging.Logger;
+import org.jboss.security.SecurityConstants;
+import org.jboss.security.authorization.AuthorizationContext;
+import org.jboss.security.authorization.AuthorizationException;
+import org.jboss.security.authorization.AuthorizationModule;
+import org.jboss.security.authorization.Resource;
+import org.jboss.security.authorization.ResourceKeys;
+import org.jboss.security.authorization.ResourceType;
+import org.jboss.security.authorization.config.AuthorizationModuleEntry;
+import org.jboss.security.authorization.modules.DelegatingAuthorizationModule;
+import org.jboss.security.config.ApplicationPolicy;
+import org.jboss.security.config.AuthorizationInfo;
+import org.jboss.security.config.ControlFlag;
+import org.jboss.security.config.SecurityConfiguration;
+import org.jboss.security.identity.Role;
+import org.jboss.security.identity.RoleGroup;
+
+//$Id: JBossAuthorizationContext.java 62954 2007-05-10 04:12:18Z anil.saldhana at jboss.com $
+
+/**
+ *  JBAS-3374: Authorization Framework for Policy Decision Modules
+ *  For information on the behavior of the Authorization Modules,
+ *  For Authorization Modules behavior(Required, Requisite, Sufficient and Optional)
+ *  please refer to the javadoc for @see javax.security.auth.login.Configuration
+ *  
+ *  The AuthorizationContext derives the AuthorizationInfo(configuration for the modules)
+ *  in the following way:
+ *  a) If there has been an injection of ApplicationPolicy, then it will be used.
+ *  b) Util.getApplicationPolicy will be used(which relies on SecurityConfiguration static class).
+ *  c) Flag an error that there is no available Application Policy
+ *  
+ *  @author <a href="mailto:Anil.Saldhana at jboss.org">Anil Saldhana</a>
+ *  @since  Jun 11, 2006 
+ *  @version $Revision: 62954 $
+ */
+public class JBossAuthorizationContext extends AuthorizationContext
+{
+   private static Logger log = Logger.getLogger(JBossAuthorizationContext.class);
+   private boolean trace = log.isTraceEnabled(); 
+   
+   private final String EJB = SecurityConstants.DEFAULT_EJB_APPLICATION_POLICY;
+   private final String WEB = SecurityConstants.DEFAULT_WEB_APPLICATION_POLICY;
+   
+   private Subject authenticatedSubject = null;
+    
+   //Application Policy can be injected
+   private ApplicationPolicy applicationPolicy = null; 
+   
+   public JBossAuthorizationContext(String name)
+   {
+      this.securityDomainName = name;
+   }
+   
+   public JBossAuthorizationContext(String name, CallbackHandler handler)
+   {
+      this(name);
+      this.callbackHandler = handler; 
+   }
+   
+   public JBossAuthorizationContext(String name, Subject subject, CallbackHandler handler)
+   {
+      this(name,handler); 
+      this.authenticatedSubject = subject; 
+   }
+   
+   /**
+    * Inject an ApplicationPolicy that contains AuthorizationInfo
+    * @param aPolicy
+    * @throws IllegalArgumentException if ApplicationPolicy is null or
+    *    does not contain AuthorizationInfo or domain name does not match
+    */
+   public void setApplicationPolicy(ApplicationPolicy aPolicy)
+   {
+      if(aPolicy == null)
+         throw new IllegalArgumentException("Application Policy is null:domain="+this.securityDomainName);
+      AuthorizationInfo authzInfo = aPolicy.getAuthorizationInfo();
+      if( authzInfo == null)
+         throw new IllegalArgumentException("Application Policy has no AuthorizationInfo");
+      if(!authzInfo.getName().equals(securityDomainName))
+         throw new IllegalArgumentException("Application Policy ->AuthorizationInfo:" + authzInfo.getName()
+               + " does not match required domain name=" + this.securityDomainName); 
+      this.applicationPolicy = aPolicy; 
+   }
+    
+   
+   /**
+    * Authorize the Resource
+    * @param resource
+    * @return AuthorizationContext.PERMIT or AuthorizationContext.DENY
+    * @throws AuthorizationException
+    */
+   public int authorize(final Resource resource) throws AuthorizationException
+   { 
+      return this.authorize(resource, this.authenticatedSubject, 
+            (RoleGroup)resource.getMap().get(ResourceKeys.SECURITY_CONTEXT_ROLES)); 
+  } 
+   
+   /**
+    * @see AuthorizationContext#authorize(Resource, Role)
+    */
+   public int authorize(final Resource resource, 
+         final Subject subject, 
+         final RoleGroup callerRoles) throws AuthorizationException
+   {   
+      try
+      {
+         this.authenticatedSubject = subject;
+         initializeModules(resource, callerRoles);
+      }
+      catch (PrivilegedActionException e1)
+      {
+         throw new RuntimeException(e1);
+      } 
+      //Do a PrivilegedAction
+      try
+      {
+         AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() 
+         {
+            public Object run() throws AuthorizationException 
+            {
+               int result = invokeAuthorize(resource);
+               if(result == PERMIT)
+                  invokeCommit();
+               if(result == DENY)
+               {
+                  invokeAbort();
+                  throw new AuthorizationException("Denied"); 
+               } 
+               return null;
+            }
+         });
+      }
+      catch (PrivilegedActionException e)
+      {
+         Exception exc = e.getException(); 
+         if(trace)
+           log.trace("Error in authorize:", exc); 
+         invokeAbort();
+         throw ((AuthorizationException)exc);
+      }
+      return PERMIT;
+      //return authorize(resource);
+   }
+   
+   //Private Methods  
+   private void initializeModules(Resource resource, RoleGroup role) throws PrivilegedActionException
+   { 
+      AuthorizationInfo authzInfo = getAuthorizationInfo(securityDomainName, resource); 
+      if(authzInfo == null)
+         throw new IllegalStateException("Authorization Info is null");
+      AuthorizationModuleEntry[] entries = authzInfo.getAuthorizationModuleEntry();
+      int len = entries != null ? entries.length : 0;
+      for(int i = 0 ; i < len; i++)
+      {
+         AuthorizationModuleEntry entry = entries[i];
+         ControlFlag flag = entry.getControlFlag();
+         if(flag == null)
+         {
+            if(trace)
+               log.trace("Null Control flag for entry:"+entry+". Defaults to REQUIRED!");
+            flag = ControlFlag.REQUIRED;
+         }
+         else
+            if(trace)
+               log.trace("Control flag for entry:"+entry+"is:["+flag+"]");
+            
+         this.controlFlags.add(flag);
+         modules.add(instantiateModule(entry.getPolicyModuleName(), entry.getOptions(), role)); 
+      }
+   }
+   
+   private int invokeAuthorize(Resource resource) 
+   throws AuthorizationException
+   {
+      //Control Flag behavior
+      boolean encounteredRequiredError = false; 
+      boolean encounteredOptionalError = false; 
+      AuthorizationException moduleException = null;
+      int overallDecision = DENY;
+      
+      int length = modules.size();
+      for(int i = 0; i < length; i++)
+      {
+         AuthorizationModule module = (AuthorizationModule)modules.get(i);
+         ControlFlag flag = (ControlFlag)this.controlFlags.get(i); 
+         int decision = DENY;
+         try
+         {
+            decision = module.authorize(resource);
+         }
+         catch(Exception ae)
+         { 
+            decision = DENY;
+            if(moduleException == null)
+               moduleException = new AuthorizationException(ae.getMessage());
+         }
+         
+         if(decision == PERMIT)
+         { 
+            overallDecision =  PERMIT;
+            //SUFFICIENT case
+            if(flag == ControlFlag.SUFFICIENT && encounteredRequiredError == false)
+               return PERMIT;
+            continue; //Continue with the other modules
+         }
+         //Go through the failure cases 
+         //REQUISITE case
+         if(flag == ControlFlag.REQUISITE)
+         {
+            if(trace)
+               log.trace("REQUISITE failed for " + module); 
+            if(moduleException == null)
+               moduleException = new AuthorizationException("Authorization failed");
+            else
+               throw moduleException;
+         }
+         //REQUIRED Case
+         if(flag == ControlFlag.REQUIRED)
+         {
+            if(trace)
+               log.trace("REQUIRED failed for " + module);
+            if(encounteredRequiredError == false)
+               encounteredRequiredError = true;
+         }
+         if(flag == ControlFlag.OPTIONAL)
+            encounteredOptionalError = true; 
+      }
+      
+      //All the authorization modules have been visited.
+      String msg = getAdditionalErrorMessage(moduleException);
+      if(encounteredRequiredError)
+         throw new AuthorizationException("Authorization Failed:"+ msg);
+      if(overallDecision == DENY && encounteredOptionalError)
+         throw new AuthorizationException("Authorization Failed:" + msg);
+      if(overallDecision == DENY)
+         throw new AuthorizationException("Authorization Failed:Denied.");
+      return PERMIT;
+   }
+   
+   private void invokeCommit()
+   throws AuthorizationException
+   {
+      int length = modules.size();
+      for(int i = 0; i < length; i++)
+      {
+         AuthorizationModule module = (AuthorizationModule)modules.get(i); 
+         boolean bool = module.commit();
+         if(!bool)
+            throw new AuthorizationException("commit on modules failed:"+module.getClass());
+      } 
+      modules.clear();
+   }
+   
+   private void invokeAbort()
+   throws AuthorizationException
+   {
+      int length = modules.size();
+      for(int i = 0; i < length; i++)
+      {
+         AuthorizationModule module = (AuthorizationModule)modules.get(i); 
+         boolean bool = module.abort(); 
+         if(!bool)
+            throw new AuthorizationException("abort on modules failed:"+module.getClass());
+      } 
+      modules.clear();
+   }
+   
+   private AuthorizationModule instantiateModule(String name, 
+         Map<String,Object> map, RoleGroup subjectRoles) 
+   throws PrivilegedActionException
+   {
+      AuthorizationModule am = null;
+      ClassLoader tcl = SecurityActions.getContextClassLoader();
+      try
+      {
+         Class<?> clazz = tcl.loadClass(name);
+         am = (AuthorizationModule)clazz.newInstance();
+      }
+      catch ( Exception e)
+      {
+         if(trace)
+            log.debug("Error instantiating AuthorizationModule:",e);
+      } 
+      if(am == null)
+         throw new IllegalStateException("AuthorizationModule has not " +
+               "been instantiated"); 
+      am.initialize(this.authenticatedSubject, this.callbackHandler, 
+            this.sharedState,map, subjectRoles); 
+      return am;
+   }
+   
+   private AuthorizationInfo getAuthorizationInfo(String domainName, Resource resource)
+   {
+      ResourceType layer = resource.getLayer();
+      
+      //Check if an instance of ApplicationPolicy is available 
+      if(this.applicationPolicy != null)
+         return applicationPolicy.getAuthorizationInfo();
+       
+      ApplicationPolicy aPolicy = SecurityConfiguration.getApplicationPolicy(domainName); 
+      
+      if(aPolicy == null)
+      {
+         if(trace)
+            log.trace("Application Policy not obtained for domain="+ domainName +
+                         ". Trying to obtain the App policy for the default domain of the layer:" 
+                  + layer);
+         if(layer == ResourceType.EJB)
+            aPolicy = SecurityConfiguration.getApplicationPolicy(EJB); 
+         else
+            if(layer == ResourceType.WEB)
+               aPolicy = SecurityConfiguration.getApplicationPolicy(WEB); 
+      }
+      if(aPolicy == null)
+         throw new IllegalStateException("Application Policy is null for domain:"+ domainName);
+      
+      AuthorizationInfo ai = aPolicy.getAuthorizationInfo();
+      if(ai == null)
+         return getAuthorizationInfo(layer);
+      else 
+         return aPolicy.getAuthorizationInfo();
+   } 
+   
+   private AuthorizationInfo getAuthorizationInfo(ResourceType layer)
+   {
+      AuthorizationInfo ai = null;
+      
+      if(layer == ResourceType.EJB)
+         ai = SecurityConfiguration.getApplicationPolicy(EJB).getAuthorizationInfo();
+      else
+         if(layer == ResourceType.WEB)
+            ai = SecurityConfiguration.getApplicationPolicy(WEB).getAuthorizationInfo();
+         else
+         {
+            if(log.isTraceEnabled())
+               log.trace("AuthorizationInfo not found. Providing default authorization info");
+            ai = new AuthorizationInfo(SecurityConstants.DEFAULT_APPLICATION_POLICY);
+            ai.add(new AuthorizationModuleEntry(DelegatingAuthorizationModule.class.getName()));
+         }
+      return ai;
+   }
+   
+   private String getAdditionalErrorMessage(Exception e)
+   {
+      StringBuilder msg = new StringBuilder(" ");
+      if(e != null)
+         msg.append(e.getLocalizedMessage());
+      return msg.toString();
+   }
+}
\ No newline at end of file

Deleted: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/plugins/identitytrust/JBossIdentityTrustManager.java
===================================================================
--- projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/security/plugins/identitytrust/JBossIdentityTrustManager.java	2009-07-21 21:59:08 UTC (rev 91524)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/plugins/identitytrust/JBossIdentityTrustManager.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -1,85 +0,0 @@
-/*
-  * JBoss, Home of Professional Open Source
-  * Copyright 2007, JBoss Inc., and individual contributors as indicated
-  * by the @authors tag. See the copyright.txt in the distribution for a
-  * full listing of individual contributors.
-  *
-  * This is free software; you can redistribute it and/or modify it
-  * under the terms of the GNU Lesser General Public License as
-  * published by the Free Software Foundation; either version 2.1 of
-  * the License, or (at your option) any later version.
-  *
-  * This software is distributed in the hope that it will be useful,
-  * but WITHOUT ANY WARRANTY; without even the implied warranty of
-  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-  * Lesser General Public License for more details.
-  *
-  * You should have received a copy of the GNU Lesser General Public
-  * License along with this software; if not, write to the Free
-  * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-  * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
-  */
-package org.jboss.security.plugins.identitytrust;
-
-import org.jboss.logging.Logger;
-import org.jboss.security.SecurityContext;
-import org.jboss.security.identitytrust.IdentityTrustContext;
-import org.jboss.security.identitytrust.IdentityTrustException;
-import org.jboss.security.identitytrust.IdentityTrustManager;
-import org.jboss.security.identitytrust.JBossIdentityTrustContext;
-
-//$Id$
-
-/**
- *  Identity Trust Manager default implementation
- *  @author Anil.Saldhana at redhat.com
- *  @since  Aug 2, 2007 
- *  @version $Revision$
- */
-public class JBossIdentityTrustManager implements IdentityTrustManager
-{ 
-   protected static Logger log = Logger.getLogger(JBossIdentityTrustManager.class);
-   private String securityDomain = null; 
-   private IdentityTrustContext identityTrustContext = null;
-   
-   public JBossIdentityTrustManager(String securityDomain)
-   {
-      this.securityDomain = securityDomain; 
-   }
-   
-   public void setIdentityTrustContext(IdentityTrustContext itc)
-   {
-     if(itc == null)
-        throw new IllegalArgumentException("null Identity Trust Context");
-     this.identityTrustContext = itc;
-   }
-   
-   /**
-    * @see IdentityTrustManager#isTrusted()
-    */
-   public TrustDecision isTrusted(SecurityContext securityContext)
-   {  
-      if(securityContext == null)
-         throw new IllegalArgumentException("Security Context is null");
-      if(this.identityTrustContext == null)
-         this.identityTrustContext = new JBossIdentityTrustContext(securityDomain, securityContext);
-      TrustDecision td = TrustDecision.NotApplicable;
-      if(this.identityTrustContext == null)
-         throw new IllegalStateException("IdentityTrustContext is null");
-       
-      try
-      {
-         td = this.identityTrustContext.isTrusted();
-      }
-      catch (IdentityTrustException e)
-      { 
-         log.trace("Trust Exception:",e);
-      } 
-      return td;
-   }
-
-   public String getSecurityDomain()
-   { 
-      return this.securityDomain;
-   }
-}

Copied: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/plugins/identitytrust/JBossIdentityTrustManager.java (from rev 93325, projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/security/plugins/identitytrust/JBossIdentityTrustManager.java)
===================================================================
--- projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/plugins/identitytrust/JBossIdentityTrustManager.java	                        (rev 0)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/plugins/identitytrust/JBossIdentityTrustManager.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -0,0 +1,88 @@
+/*
+  * JBoss, Home of Professional Open Source
+  * Copyright 2007, JBoss Inc., and individual contributors as indicated
+  * by the @authors tag. See the copyright.txt in the distribution for a
+  * full listing of individual contributors.
+  *
+  * This is free software; you can redistribute it and/or modify it
+  * under the terms of the GNU Lesser General Public License as
+  * published by the Free Software Foundation; either version 2.1 of
+  * the License, or (at your option) any later version.
+  *
+  * This software is distributed in the hope that it will be useful,
+  * but WITHOUT ANY WARRANTY; without even the implied warranty of
+  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+  * Lesser General Public License for more details.
+  *
+  * You should have received a copy of the GNU Lesser General Public
+  * License along with this software; if not, write to the Free
+  * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+  * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+  */
+package org.jboss.security.plugins.identitytrust;
+
+import org.jboss.logging.Logger;
+import org.jboss.security.SecurityContext;
+import org.jboss.security.identitytrust.IdentityTrustContext;
+import org.jboss.security.identitytrust.IdentityTrustException;
+import org.jboss.security.identitytrust.IdentityTrustManager;
+import org.jboss.security.identitytrust.JBossIdentityTrustContext;
+
+//$Id$
+
+/**
+ *  Identity Trust Manager default implementation
+ *  @author Anil.Saldhana at redhat.com
+ *  @since  Aug 2, 2007 
+ *  @version $Revision$
+ */
+public class JBossIdentityTrustManager implements IdentityTrustManager
+{ 
+   protected static Logger log = Logger.getLogger(JBossIdentityTrustManager.class);
+   protected boolean trace = log.isTraceEnabled();
+   
+   private String securityDomain = null; 
+   private IdentityTrustContext identityTrustContext = null;
+   
+   public JBossIdentityTrustManager(String securityDomain)
+   {
+      this.securityDomain = securityDomain; 
+   }
+   
+   public void setIdentityTrustContext(IdentityTrustContext itc)
+   {
+     if(itc == null)
+        throw new IllegalArgumentException("null Identity Trust Context");
+     this.identityTrustContext = itc;
+   }
+   
+   /**
+    * @see IdentityTrustManager#isTrusted()
+    */
+   public TrustDecision isTrusted(SecurityContext securityContext)
+   {  
+      if(securityContext == null)
+         throw new IllegalArgumentException("Security Context is null");
+      if(this.identityTrustContext == null)
+         this.identityTrustContext = new JBossIdentityTrustContext(securityDomain, securityContext);
+      TrustDecision td = TrustDecision.NotApplicable;
+      if(this.identityTrustContext == null)
+         throw new IllegalStateException("IdentityTrustContext is null");
+       
+      try
+      {
+         td = this.identityTrustContext.isTrusted();
+      }
+      catch (IdentityTrustException e)
+      { 
+         if(trace)
+            log.trace("Trust Exception:",e);
+      } 
+      return td;
+   }
+
+   public String getSecurityDomain()
+   { 
+      return this.securityDomain;
+   }
+}
\ No newline at end of file

Deleted: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/plugins/mapping/JBossMappingManager.java
===================================================================
--- projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/security/plugins/mapping/JBossMappingManager.java	2009-07-21 21:59:08 UTC (rev 91524)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/plugins/mapping/JBossMappingManager.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -1,121 +0,0 @@
-/*
-  * JBoss, Home of Professional Open Source
-  * Copyright 2007, JBoss Inc., and individual contributors as indicated
-  * by the @authors tag. See the copyright.txt in the distribution for a
-  * full listing of individual contributors.
-  *
-  * This is free software; you can redistribute it and/or modify it
-  * under the terms of the GNU Lesser General Public License as
-  * published by the Free Software Foundation; either version 2.1 of
-  * the License, or (at your option) any later version.
-  *
-  * This software is distributed in the hope that it will be useful,
-  * but WITHOUT ANY WARRANTY; without even the implied warranty of
-  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-  * Lesser General Public License for more details.
-  *
-  * You should have received a copy of the GNU Lesser General Public
-  * License along with this software; if not, write to the Free
-  * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-  * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
-  */
-package org.jboss.security.plugins.mapping;
-
-import java.util.ArrayList;
-
-import org.jboss.logging.Logger;
-import org.jboss.security.SecurityConstants;
-import org.jboss.security.SecurityContext;
-import org.jboss.security.config.ApplicationPolicy;
-import org.jboss.security.config.MappingInfo;
-import org.jboss.security.config.SecurityConfiguration;
-import org.jboss.security.mapping.MappingContext;
-import org.jboss.security.mapping.MappingManager;
-import org.jboss.security.mapping.MappingProvider;
-import org.jboss.security.mapping.config.MappingModuleEntry;
-import org.jboss.security.plugins.JBossSecurityContext;
-
-
-/**
- *  JBoss implementation of Mapping Manager 
- *  @author Anil.Saldhana at redhat.com
- *  @since  Mar 9, 2007 
- *  @version $Revision$
- */
-public class JBossMappingManager implements MappingManager
-{   
-   protected static final Logger log = Logger.getLogger(JBossSecurityContext.class); 
-   protected boolean trace = log.isTraceEnabled();  
-   
-   private String securityDomain;
-
-   public JBossMappingManager(String domain)
-   {
-     this.securityDomain = domain;   
-   }
-   
-   /**
-    * @see SecurityContext#getMappingContext(String)
-    */
-   public <T> MappingContext<T> getMappingContext(Class<T> mappingType)
-   { 
-      //Apply Mapping Logic  
-      ApplicationPolicy aPolicy = SecurityConfiguration.getApplicationPolicy(securityDomain);
-      
-      if(aPolicy == null)
-      {
-         String defaultDomain = SecurityConstants.DEFAULT_APPLICATION_POLICY;
-         if(trace)
-            log.trace("Application Policy not found for domain=" + securityDomain +
-                  ".Mapping framework will use the default domain:" + defaultDomain);
-         aPolicy = SecurityConfiguration.getApplicationPolicy(defaultDomain); 
-      } 
-      if(aPolicy == null )
-         throw new IllegalStateException("Application Policy is null for the security domain:" 
-               + securityDomain);
-      
-      MappingContext<T> mc = null;
-      MappingInfo rmi = aPolicy.getMappingInfo(mappingType); 
-      
-      if(rmi != null)
-      {
-         MappingModuleEntry[] mpe = rmi.getMappingModuleEntry();
-         ArrayList<MappingProvider<T>> al = new ArrayList<MappingProvider<T>>();
-         
-         for(int i = 0 ; i < mpe.length; i++)
-         { 
-            MappingProvider<T> mp = getMappingProvider(mpe[i]);
-            if(mp != null)
-               al.add(mp); 
-         }
-         mc = new MappingContext<T>(al); 
-      }
-      
-      return mc; 
-   } 
-    
-   public String getSecurityDomain()
-   { 
-      return this.securityDomain;
-   }
-
-   @SuppressWarnings("unchecked")
-   private <T> MappingProvider<T> getMappingProvider(MappingModuleEntry mme)
-   {
-      ClassLoader tcl = SecurityActions.getContextClassLoader();
-      MappingProvider<T> mp = null;
-      try
-      {
-         String fqn = mme.getMappingModuleName();
-         Class<?> cl = SecurityActions.loadClass(fqn,tcl);
-         mp = (MappingProvider<T>) cl.newInstance();
-         mp.init(mme.getOptions());
-      }
-      catch(Exception e)
-      {
-         if(trace)
-            log.trace("Error in getting Mapping Provider",e);
-      } 
-      return mp; 
-   }
-}

Copied: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/plugins/mapping/JBossMappingManager.java (from rev 93325, projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/main/java/org/jboss/security/plugins/mapping/JBossMappingManager.java)
===================================================================
--- projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/plugins/mapping/JBossMappingManager.java	                        (rev 0)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/main/java/org/jboss/security/plugins/mapping/JBossMappingManager.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -0,0 +1,153 @@
+/*
+  * JBoss, Home of Professional Open Source
+  * Copyright 2007, JBoss Inc., and individual contributors as indicated
+  * by the @authors tag. See the copyright.txt in the distribution for a
+  * full listing of individual contributors.
+  *
+  * This is free software; you can redistribute it and/or modify it
+  * under the terms of the GNU Lesser General Public License as
+  * published by the Free Software Foundation; either version 2.1 of
+  * the License, or (at your option) any later version.
+  *
+  * This software is distributed in the hope that it will be useful,
+  * but WITHOUT ANY WARRANTY; without even the implied warranty of
+  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+  * Lesser General Public License for more details.
+  *
+  * You should have received a copy of the GNU Lesser General Public
+  * License along with this software; if not, write to the Free
+  * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+  * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+  */
+package org.jboss.security.plugins.mapping;
+
+import java.util.ArrayList;
+
+import org.jboss.logging.Logger;
+import org.jboss.security.SecurityConstants;
+import org.jboss.security.SecurityContext;
+import org.jboss.security.config.ApplicationPolicy;
+import org.jboss.security.config.MappingInfo;
+import org.jboss.security.config.SecurityConfiguration;
+import org.jboss.security.mapping.MappingContext;
+import org.jboss.security.mapping.MappingManager;
+import org.jboss.security.mapping.MappingProvider;
+import org.jboss.security.mapping.config.MappingModuleEntry;
+import org.jboss.security.plugins.JBossSecurityContext;
+
+
+/**
+ *  JBoss implementation of Mapping Manager 
+ *  @author Anil.Saldhana at redhat.com
+ *  @since  Mar 9, 2007 
+ *  @version $Revision$
+ */
+public class JBossMappingManager implements MappingManager
+{   
+   protected static final Logger log = Logger.getLogger(JBossSecurityContext.class); 
+   protected boolean trace = log.isTraceEnabled();  
+   
+   private String securityDomain;
+
+   public JBossMappingManager(String domain)
+   {
+     this.securityDomain = domain;   
+   }
+   
+   
+   public <T> MappingContext<T> getMappingContext(String mappingType)
+   {
+      //Apply Mapping Logic  
+      ApplicationPolicy aPolicy = SecurityConfiguration.getApplicationPolicy(securityDomain);
+      
+      if(aPolicy == null)
+      {
+         String defaultDomain = SecurityConstants.DEFAULT_APPLICATION_POLICY;
+         if(trace)
+            log.trace("Application Policy not found for domain=" + securityDomain +
+                  ".Mapping framework will use the default domain:" + defaultDomain);
+         aPolicy = SecurityConfiguration.getApplicationPolicy(defaultDomain); 
+      } 
+      if(aPolicy == null )
+         throw new IllegalStateException("Application Policy is null for the security domain:" 
+               + securityDomain);
+      
+      MappingContext<T> mc = null;
+      MappingInfo rmi = aPolicy.getMappingInfo(mappingType);  
+
+      if( rmi != null)
+         mc = generateMappingContext(mc, rmi);
+      
+      return mc; 
+   }
+   
+   
+   /**
+    * @see SecurityContext#getMappingContext(String)
+    */
+   @SuppressWarnings("deprecation")
+   public <T> MappingContext<T> getMappingContext(Class<T> mappingType)
+   { 
+      //Apply Mapping Logic  
+      ApplicationPolicy aPolicy = SecurityConfiguration.getApplicationPolicy(securityDomain);
+      
+      if(aPolicy == null)
+      {
+         String defaultDomain = SecurityConstants.DEFAULT_APPLICATION_POLICY;
+         if(trace)
+            log.trace("Application Policy not found for domain=" + securityDomain +
+                  ".Mapping framework will use the default domain:" + defaultDomain);
+         aPolicy = SecurityConfiguration.getApplicationPolicy(defaultDomain); 
+      } 
+      if(aPolicy == null )
+         throw new IllegalStateException("Application Policy is null for the security domain:" 
+               + securityDomain);
+      
+      MappingContext<T> mc = null;
+      MappingInfo rmi = aPolicy.getMappingInfo(mappingType); 
+      if( rmi != null)
+        mc = generateMappingContext(mc, rmi);
+      
+      return mc; 
+   }
+
+
+   private <T> MappingContext<T> generateMappingContext(MappingContext<T> mc, MappingInfo rmi)
+   {
+      MappingModuleEntry[] mpe = rmi.getMappingModuleEntry();
+      ArrayList<MappingProvider<T>> al = new ArrayList<MappingProvider<T>>();
+
+      for(int i = 0 ; i < mpe.length; i++)
+      { 
+         MappingProvider<T> mp = getMappingProvider(mpe[i]);
+         if(mp != null)
+            al.add(mp); 
+      }
+      return new MappingContext<T>(al); 
+   } 
+    
+   public String getSecurityDomain()
+   { 
+      return this.securityDomain;
+   }
+
+   @SuppressWarnings("unchecked")
+   private <T> MappingProvider<T> getMappingProvider(MappingModuleEntry mme)
+   {
+      ClassLoader tcl = SecurityActions.getContextClassLoader();
+      MappingProvider<T> mp = null;
+      try
+      {
+         String fqn = mme.getMappingModuleName();
+         Class<?> cl = SecurityActions.loadClass(fqn,tcl);
+         mp = (MappingProvider<T>) cl.newInstance();
+         mp.init(mme.getOptions());
+      }
+      catch(Exception e)
+      {
+         if(trace)
+            log.trace("Error in getting Mapping Provider",e);
+      } 
+      return mp; 
+   }
+}
\ No newline at end of file

Deleted: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/test/java/org/jboss/test/authentication/jaas/ClientLoginModuleUnitTestCase.java
===================================================================
--- projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/test/java/org/jboss/test/authentication/jaas/ClientLoginModuleUnitTestCase.java	2009-07-21 21:59:08 UTC (rev 91524)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/test/java/org/jboss/test/authentication/jaas/ClientLoginModuleUnitTestCase.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -1,448 +0,0 @@
-/*
-  * JBoss, Home of Professional Open Source
-  * Copyright 2005, JBoss Inc., and individual contributors as indicated
-  * by the @authors tag. See the copyright.txt in the distribution for a
-  * full listing of individual contributors.
-  *
-  * This is free software; you can redistribute it and/or modify it
-  * under the terms of the GNU Lesser General Public License as
-  * published by the Free Software Foundation; either version 2.1 of
-  * the License, or (at your option) any later version.
-  *
-  * This software is distributed in the hope that it will be useful,
-  * but WITHOUT ANY WARRANTY; without even the implied warranty of
-  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-  * Lesser General Public License for more details.
-  *
-  * You should have received a copy of the GNU Lesser General Public
-  * License along with this software; if not, write to the Free
-  * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-  * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
-  */
-package org.jboss.test.authentication.jaas;
-
-import java.lang.reflect.Method;
-import java.security.Principal;
-import java.util.Arrays;
-import java.util.HashMap;
-
-import javax.security.auth.Subject;
-import javax.security.auth.login.AppConfigurationEntry;
-import javax.security.auth.login.Configuration;
-import javax.security.auth.login.LoginContext;
-
-import junit.framework.Test;
-import junit.framework.TestCase;
-import junit.framework.TestSuite;
-
-import org.jboss.security.SecurityAssociation;
-import org.jboss.security.SecurityContextAssociation;
-import org.jboss.security.SimplePrincipal;
-import org.jboss.security.auth.callback.UsernamePasswordHandler;
-
-/**
- ClientLoginModuleUnitTestCase/SecurityAssociation interaction tests
- 
- @author Scott.Stark at jboss.org
- @version $Revision: 68075 $
-*/
-public class ClientLoginModuleUnitTestCase
-   extends TestCase
-{
-   static TestConfig jaasConfig = new TestConfig();
-
-   static class TestConfig extends Configuration
-   {
-      public void refresh()
-      {
-      }
-
-      public AppConfigurationEntry[] getAppConfigurationEntry(String name)
-      {
-         AppConfigurationEntry[] entry = null;
-         try
-         {
-            Class<?>[] parameterTypes = {};
-            Method m = getClass().getDeclaredMethod(name, parameterTypes);
-            Object[] args = {};
-            entry = (AppConfigurationEntry[]) m.invoke(this, args);
-         }
-         catch(Exception e)
-         {
-         }
-         return entry;
-      }
-      AppConfigurationEntry[] testSingleThreaded()
-      {
-         String name = "org.jboss.security.ClientLoginModule";
-         HashMap<String,String> options = new HashMap<String,String>();
-         options.put("multi-threaded", "false");
-         AppConfigurationEntry ace = new AppConfigurationEntry(name,
-         AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, options);
-         AppConfigurationEntry[] entry = {ace};
-         return entry;
-      }
-      AppConfigurationEntry[] testSingleThreadedRestoreIdentity()
-      {
-         String name = "org.jboss.security.ClientLoginModule";
-         HashMap<String,String> options = new HashMap<String,String>();
-         options.put("multi-threaded", "false");
-         options.put("restore-login-identity", "true");
-         AppConfigurationEntry ace = new AppConfigurationEntry(name,
-         AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, options);
-         AppConfigurationEntry[] entry = {ace};
-         return entry;
-      }
-      AppConfigurationEntry[] testSingleThreadedRestoreStack()
-      {
-         String name = "org.jboss.security.ClientLoginModule";
-         HashMap<String,String> options = new HashMap<String,String>();
-         options.put("multi-threaded", "false");
-         options.put("restore-login-identity", "true");
-         AppConfigurationEntry ace = new AppConfigurationEntry(name,
-         AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, options);
-         AppConfigurationEntry[] entry = {ace};
-         return entry;
-      }
-      AppConfigurationEntry[] testMultiThreaded()
-      {
-         String name = "org.jboss.security.ClientLoginModule";
-         HashMap<String,String> options = new HashMap<String,String>();
-         options.put("multi-threaded", "true");
-         AppConfigurationEntry ace = new AppConfigurationEntry(name,
-         AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, options);
-         AppConfigurationEntry[] entry = {ace};
-         return entry;
-      }
-      AppConfigurationEntry[] testMultiThreadedRestoreIdentity()
-      {
-         String name = "org.jboss.security.ClientLoginModule";
-         HashMap<String,String> options = new HashMap<String,String>();
-         options.put("multi-threaded", "true");
-         options.put("restore-login-identity", "true");
-         AppConfigurationEntry ace = new AppConfigurationEntry(name,
-         AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, options);
-         AppConfigurationEntry[] entry = {ace};
-         return entry;
-      }
-      AppConfigurationEntry[] testMultiThreadedRestoreStack()
-      {
-         String name = "org.jboss.security.ClientLoginModule";
-         HashMap<String,String> options = new HashMap<String,String>();
-         options.put("multi-threaded", "true");
-         options.put("restore-login-identity", "true");
-         AppConfigurationEntry ace = new AppConfigurationEntry(name,
-         AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, options);
-         AppConfigurationEntry[] entry = {ace};
-         return entry;
-      }
-      
-   }
-
-   public static Test suite() throws Exception
-   {
-      TestSuite suite = new TestSuite();
-      suite.addTest(new ClientLoginModuleUnitTestCase("testSingleThreaded"));
-      suite.addTest(new ClientLoginModuleUnitTestCase("testSingleThreadedRestoreIdentity"));
-      suite.addTest(new ClientLoginModuleUnitTestCase("testSingleThreadedRestoreStack"));
-      suite.addTest(new ClientLoginModuleUnitTestCase("testMultiThreaded"));
-      suite.addTest(new ClientLoginModuleUnitTestCase("testMultiThreadedRestoreIdentity"));
-      suite.addTest(new ClientLoginModuleUnitTestCase("testMultiThreadedRestoreStack"));
-      return suite;
-   }
-
-   public ClientLoginModuleUnitTestCase(String name)
-   {
-      super(name);
-   }
-
-   protected void setUp() throws Exception
-   {
-      Configuration.setConfiguration(jaasConfig);
-      //Clear SecurityAssociation
-      SecurityAssociation.clear();
-   }
-   protected void tearDown()
-   {
-   }
-
-   public void testSingleThreaded() throws Exception
-   {
-      System.out.println("+++ testSingleThreaded");
-      UsernamePasswordHandler handler = new UsernamePasswordHandler("jduke",
-         "theduke");
-      LoginContext lc = new LoginContext("testSingleThreaded", handler);
-      lc.login();
-      Subject subject = lc.getSubject();
-      System.out.println("LC.Subject: "+subject);
-      Principal theduke = new SimplePrincipal("jduke");
-      assertTrue("Principals contains theduke", subject.getPrincipals().contains(theduke));
-      Principal saPrincipal = SecurityAssociation.getPrincipal();
-      assertTrue("SecurityAssociation.getPrincipal == theduke", saPrincipal.equals(theduke));
-      char[] password = (char[]) SecurityAssociation.getCredential();
-      assertTrue("password == theduke",
-         Arrays.equals(password, "theduke".toCharArray()));
-      
-      assertTrue("Client side association?", SecurityContextAssociation.isClient());
-   }
-
-   public void testSingleThreadedRestoreIdentity() throws Exception
-   {
-      System.out.println("+++ testSingleThreadedRestoreIdentity");
-      
-      Principal jduke1 = new SimplePrincipal("jduke1");
-      SecurityAssociation.setPrincipal(jduke1);
-      SecurityAssociation.setCredential("theduke1");
-
-      UsernamePasswordHandler handler = new UsernamePasswordHandler("jduke2",
-         "theduke2");
-      LoginContext lc = new LoginContext("testSingleThreadedRestoreIdentity", handler);
-      lc.login();
-      Subject subject = lc.getSubject();
-      System.out.println("LC.Subject: "+subject);
-      
-      Principal jduke2 = new SimplePrincipal("jduke2");
-      assertTrue("Principals contains jduke2", subject.getPrincipals().contains(jduke2));
-      Principal saPrincipal = SecurityAssociation.getPrincipal();
-      assertTrue("SecurityAssociation.getPrincipal == jduke2", saPrincipal.equals(jduke2));
-      char[] password = (char[]) SecurityAssociation.getCredential();
-      assertTrue("password == theduke2",
-         Arrays.equals(password, "theduke2".toCharArray()));
-
-      lc.logout();
-      // Validate restored state
-      saPrincipal = SecurityAssociation.getPrincipal();
-      assertTrue("SecurityAssociation.getPrincipal == jduke1", saPrincipal.equals(jduke1));
-      String theduke1 = (String) SecurityAssociation.getCredential();
-      assertTrue("password == theduke1", theduke1.equals("theduke1"));
-      
-   }
-
-   @SuppressWarnings("deprecation")
-   public void testSingleThreadedRestoreStack() throws Exception
-   {
-      System.out.println("+++ testSingleThreadedRestoreStack");
- 
-      Principal jduke1 = new SimplePrincipal("jduke1");
-      Subject subject1 = new Subject();
-      SecurityAssociation.pushSubjectContext(subject1, jduke1, "theduke1");
-
-      Principal jduke2 = new SimplePrincipal("jduke2");
-      Subject subject2 = new Subject();
-      SecurityAssociation.pushSubjectContext(subject2, jduke2, "theduke2");
-
-      UsernamePasswordHandler handler = new UsernamePasswordHandler("jduke3",
-         "theduke3");
-      LoginContext lc = new LoginContext("testSingleThreadedRestoreIdentity", handler);
-      lc.login();
-      Subject subject = lc.getSubject();
-      System.out.println("LC.Subject: "+subject);
-      
-      Principal jduke3 = new SimplePrincipal("jduke3");
-      assertTrue("Principals contains jduke3", subject.getPrincipals().contains(jduke3));
-      Principal saPrincipal = SecurityAssociation.getPrincipal();
-      assertTrue("SecurityAssociation.getPrincipal == jduke3", saPrincipal.equals(jduke3));
-      char[] password = (char[]) SecurityAssociation.getCredential();
-      assertTrue("password == theduke3",
-         Arrays.equals(password, "theduke3".toCharArray()));
-      SecurityAssociation.SubjectContext sc3 = SecurityAssociation.peekSubjectContext();
-      System.out.println(sc3);
-      assertTrue("SecurityAssociation.peekSubjectContext == jduke3", sc3.getPrincipal().equals(jduke3));
-      char[] theduke3 = (char[]) sc3.getCredential();
-      assertTrue("password == theduke3",
-         Arrays.equals(theduke3, "theduke3".toCharArray()));
-
-      lc.logout();
-
-      // Validate restored state
-      SecurityAssociation.SubjectContext sc2 = SecurityAssociation.peekSubjectContext();
-      System.out.println(sc2);
-      assertTrue("SecurityAssociation.peekSubjectContext == jduke2", sc2.getPrincipal().equals(jduke2));
-      String theduke2 = (String) sc2.getCredential();
-      assertTrue("password == theduke2", theduke2.equals("theduke2"));
-
-      SecurityAssociation.popSubjectContext();
-      SecurityAssociation.SubjectContext sc1 = SecurityAssociation.peekSubjectContext();
-      System.out.println(sc1);
-      assertTrue("SecurityAssociation.peekSubjectContext == jduke1", sc1.getPrincipal().equals(jduke1));
-      String theduke1 = (String) sc1.getCredential();
-      assertTrue("password == theduke1", theduke1.equals("theduke1"));
-   }
-
-   public void testMultiThreaded() throws Exception
-   {
-      TestMultiThreaded r0 = new TestMultiThreaded();
-      Thread t0 = new Thread(r0, "testMultiThreaded#0");
-      t0.start();
-      TestMultiThreaded r1 = new TestMultiThreaded();
-      Thread t1 = new Thread(r1, "testMultiThreaded#1");
-      t1.start();
-
-      t0.join();
-      assertTrue(r0.failure == null);
-      t1.join();
-      assertTrue(r1.failure == null);
-   }
-   static class TestMultiThreaded implements Runnable
-   {
-      Exception failure;
-      public void run()
-      {
-         try
-         {
-            System.out.println("+++ testMultiThreadedRunnable");
-            UsernamePasswordHandler handler = new UsernamePasswordHandler("jduke",
-               "theduke");
-            LoginContext lc = new LoginContext("testSingleThreaded", handler);
-            lc.login();
-            Subject subject = lc.getSubject();
-            System.out.println("LC.Subject: "+subject);
-            Principal theduke = new SimplePrincipal("jduke");
-            assertTrue("Principals contains theduke", subject.getPrincipals().contains(theduke));
-            Principal saPrincipal = SecurityAssociation.getPrincipal();
-            assertTrue("SecurityAssociation.getPrincipal == theduke", saPrincipal.equals(theduke));
-            char[] password = (char[]) SecurityAssociation.getCredential();
-            assertTrue("password == theduke",
-               Arrays.equals(password, "theduke".toCharArray()));
-         }
-         catch(Exception e)
-         {
-            failure = e;
-         }
-      }
-   }
-
-   public void testMultiThreadedRestoreIdentity() throws Exception
-   {
-      TestMultiThreadedRestoreIdentity r0 = new TestMultiThreadedRestoreIdentity();
-      Thread t0 = new Thread(r0, "testMultiThreadedRestoreIdentity#0");
-      t0.start();
-      TestMultiThreadedRestoreIdentity r1 = new TestMultiThreadedRestoreIdentity();
-      Thread t1 = new Thread(r1, "testMultiThreadedRestoreIdentity#1");
-      t1.start();
-
-      t0.join();
-      assertTrue(r0.failure == null);
-      t1.join();
-      assertTrue(r1.failure == null);
-   }
-   static class TestMultiThreadedRestoreIdentity implements Runnable
-   {
-      Exception failure;
-      public void run()
-      {
-         try
-         {
-            System.out.println("+++ testMultiThreadedRestoreIdentity");
-      
-            Principal jduke1 = new SimplePrincipal("jduke1");
-            SecurityAssociation.setPrincipal(jduke1);
-            SecurityAssociation.setCredential("theduke1");
-      
-            UsernamePasswordHandler handler = new UsernamePasswordHandler("jduke2",
-               "theduke2");
-            LoginContext lc = new LoginContext("testSingleThreadedRestoreIdentity", handler);
-            lc.login();
-            Subject subject = lc.getSubject();
-            System.out.println("LC.Subject: "+subject);
-            
-            Principal jduke2 = new SimplePrincipal("jduke2");
-            assertTrue("Principals contains jduke2", subject.getPrincipals().contains(jduke2));
-            Principal saPrincipal = SecurityAssociation.getPrincipal();
-            assertTrue("SecurityAssociation.getPrincipal == jduke2", saPrincipal.equals(jduke2));
-            char[] password = (char[]) SecurityAssociation.getCredential();
-            assertTrue("password == theduke2",
-               Arrays.equals(password, "theduke2".toCharArray()));
-      
-            lc.logout();
-            // Validate restored state
-            saPrincipal = SecurityAssociation.getPrincipal();
-            assertTrue("SecurityAssociation.getPrincipal == jduke1", saPrincipal.equals(jduke1));
-            String theduke1 = (String) SecurityAssociation.getCredential();
-            assertTrue("password == theduke1", theduke1.equals("theduke1"));
-      
-         }
-         catch(Exception e)
-         {
-            failure = e;
-         }
-      }
-   }
-
-   public void testMultiThreadedRestoreStack() throws Exception
-   {
-      TestMultiThreadedRestoreStack r0 = new TestMultiThreadedRestoreStack();
-      Thread t0 = new Thread(r0, "testMultiThreadedRestoreIdentity#0");
-      t0.start();
-      TestMultiThreadedRestoreStack r1 = new TestMultiThreadedRestoreStack();
-      Thread t1 = new Thread(r1, "testMultiThreadedRestoreIdentity#1");
-      t1.start();
-
-      t0.join();
-      assertTrue(r0.failure == null);
-      t1.join();
-      assertTrue(r1.failure == null);
-   }
-   static class TestMultiThreadedRestoreStack implements Runnable
-   {
-      Exception failure;
-      @SuppressWarnings("deprecation")
-      public void run()
-      {
-         try
-         {
-            System.out.println("+++ testMultThreadedRestoreStack");
-
-            Principal jduke1 = new SimplePrincipal("jduke1");
-            Subject subject1 = new Subject();
-            SecurityAssociation.pushSubjectContext(subject1, jduke1, "theduke1");
-
-            Principal jduke2 = new SimplePrincipal("jduke2");
-            Subject subject2 = new Subject();
-            SecurityAssociation.pushSubjectContext(subject2, jduke2, "theduke2");
-
-            UsernamePasswordHandler handler = new UsernamePasswordHandler("jduke3",
-               "theduke3");
-            LoginContext lc = new LoginContext("testSingleThreadedRestoreIdentity", handler);
-            lc.login();
-            Subject subject = lc.getSubject();
-            System.out.println("LC.Subject: "+subject);
-      
-            Principal jduke3 = new SimplePrincipal("jduke3");
-            assertTrue("Principals contains jduke3", subject.getPrincipals().contains(jduke3));
-            Principal saPrincipal = SecurityAssociation.getPrincipal();
-            assertTrue("SecurityAssociation.getPrincipal == jduke3", saPrincipal.equals(jduke3));
-            char[] password = (char[]) SecurityAssociation.getCredential();
-            assertTrue("password == theduke3",
-               Arrays.equals(password, "theduke3".toCharArray()));
-            SecurityAssociation.SubjectContext sc3 = SecurityAssociation.peekSubjectContext();
-            System.out.println(sc3);
-            assertTrue("SecurityAssociation.peekSubjectContext == jduke3", sc3.getPrincipal().equals(jduke3));
-            char[] theduke3 = (char[]) sc3.getCredential();
-            assertTrue("password == theduke3",
-               Arrays.equals(theduke3, "theduke3".toCharArray()));
-
-            lc.logout();
-
-            // Validate restored state
-            SecurityAssociation.SubjectContext sc2 = SecurityAssociation.peekSubjectContext();
-            System.out.println(sc2);
-            assertTrue("SecurityAssociation.peekSubjectContext == jduke2", sc2.getPrincipal().equals(jduke2));
-            String theduke2 = (String) sc2.getCredential();
-            assertTrue("password == theduke2", theduke2.equals("theduke2"));
-
-            SecurityAssociation.popSubjectContext();
-            SecurityAssociation.SubjectContext sc1 = SecurityAssociation.peekSubjectContext();
-            System.out.println(sc1);
-            assertTrue("SecurityAssociation.peekSubjectContext == jduke1", sc1.getPrincipal().equals(jduke1));
-            String theduke1 = (String) sc1.getCredential();
-            assertTrue("password == theduke1", theduke1.equals("theduke1"));
-         }
-         catch(Exception e)
-         {
-            failure = e;
-         }
-      }
-   }
-
-}

Copied: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/test/java/org/jboss/test/authentication/jaas/ClientLoginModuleUnitTestCase.java (from rev 92165, projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/test/java/org/jboss/test/authentication/jaas/ClientLoginModuleUnitTestCase.java)
===================================================================
--- projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/test/java/org/jboss/test/authentication/jaas/ClientLoginModuleUnitTestCase.java	                        (rev 0)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/test/java/org/jboss/test/authentication/jaas/ClientLoginModuleUnitTestCase.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -0,0 +1,666 @@
+/*
+  * JBoss, Home of Professional Open Source
+  * Copyright 2005, JBoss Inc., and individual contributors as indicated
+  * by the @authors tag. See the copyright.txt in the distribution for a
+  * full listing of individual contributors.
+  *
+  * This is free software; you can redistribute it and/or modify it
+  * under the terms of the GNU Lesser General Public License as
+  * published by the Free Software Foundation; either version 2.1 of
+  * the License, or (at your option) any later version.
+  *
+  * This software is distributed in the hope that it will be useful,
+  * but WITHOUT ANY WARRANTY; without even the implied warranty of
+  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+  * Lesser General Public License for more details.
+  *
+  * You should have received a copy of the GNU Lesser General Public
+  * License along with this software; if not, write to the Free
+  * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+  * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+  */
+package org.jboss.test.authentication.jaas;
+
+import java.lang.reflect.Method;
+import java.security.Principal;
+import java.util.Arrays;
+import java.util.HashMap;
+
+import javax.security.auth.Subject;
+import javax.security.auth.login.AppConfigurationEntry;
+import javax.security.auth.login.Configuration;
+import javax.security.auth.login.LoginContext;
+import javax.security.auth.login.LoginException;
+
+import junit.framework.Test;
+import junit.framework.TestCase;
+import junit.framework.TestSuite;
+
+import org.jboss.security.SecurityAssociation;
+import org.jboss.security.SecurityContext;
+import org.jboss.security.SecurityContextAssociation;
+import org.jboss.security.SecurityContextFactory;
+import org.jboss.security.SimplePrincipal;
+import org.jboss.security.SubjectInfo;
+import org.jboss.security.auth.callback.UsernamePasswordHandler;
+
+/**
+ ClientLoginModuleUnitTestCase/SecurityAssociation interaction tests
+ 
+ @author Scott.Stark at jboss.org
+ @version $Revision: 68075 $
+*/
+public class ClientLoginModuleUnitTestCase
+   extends TestCase
+{
+   static TestConfig jaasConfig = new TestConfig();
+
+   static class TestConfig extends Configuration
+   {
+      public void refresh()
+      {
+      }
+
+      public AppConfigurationEntry[] getAppConfigurationEntry(String name)
+      {
+         AppConfigurationEntry[] entry = null;
+         try
+         {
+            Class<?>[] parameterTypes = {};
+            Method m = getClass().getDeclaredMethod(name, parameterTypes);
+            Object[] args = {};
+            entry = (AppConfigurationEntry[]) m.invoke(this, args);
+         }
+         catch(Exception e)
+         {
+         }
+         return entry;
+      }
+      AppConfigurationEntry[] testSingleThreaded()
+      {
+         String name = "org.jboss.security.ClientLoginModule";
+         HashMap<String,String> options = new HashMap<String,String>();
+         options.put("multi-threaded", "false");
+         AppConfigurationEntry ace = new AppConfigurationEntry(name,
+         AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, options);
+         AppConfigurationEntry[] entry = {ace};
+         return entry;
+      }
+      AppConfigurationEntry[] testSingleThreadedRestoreIdentity()
+      {
+         String name = "org.jboss.security.ClientLoginModule";
+         HashMap<String,String> options = new HashMap<String,String>();
+         options.put("multi-threaded", "false");
+         options.put("restore-login-identity", "true");
+         AppConfigurationEntry ace = new AppConfigurationEntry(name,
+         AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, options);
+         AppConfigurationEntry[] entry = {ace};
+         return entry;
+      }
+      AppConfigurationEntry[] testSingleThreadedRestoreStack()
+      {
+         String name = "org.jboss.security.ClientLoginModule";
+         HashMap<String,String> options = new HashMap<String,String>();
+         options.put("multi-threaded", "false");
+         options.put("restore-login-identity", "true");
+         AppConfigurationEntry ace = new AppConfigurationEntry(name,
+         AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, options);
+         AppConfigurationEntry[] entry = {ace};
+         return entry;
+      }
+      AppConfigurationEntry[] testMultiThreaded()
+      {
+         String name = "org.jboss.security.ClientLoginModule";
+         HashMap<String,String> options = new HashMap<String,String>();
+         options.put("multi-threaded", "true");
+         AppConfigurationEntry ace = new AppConfigurationEntry(name,
+         AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, options);
+         AppConfigurationEntry[] entry = {ace};
+         return entry;
+      }
+      AppConfigurationEntry[] testMultiThreadedRestoreIdentity()
+      {
+         String name = "org.jboss.security.ClientLoginModule";
+         HashMap<String,String> options = new HashMap<String,String>();
+         options.put("multi-threaded", "true");
+         options.put("restore-login-identity", "true");
+         AppConfigurationEntry ace = new AppConfigurationEntry(name,
+         AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, options);
+         AppConfigurationEntry[] entry = {ace};
+         return entry;
+      }
+      AppConfigurationEntry[] testMultiThreadedRestoreStack()
+      {
+         String name = "org.jboss.security.ClientLoginModule";
+         HashMap<String,String> options = new HashMap<String,String>();
+         options.put("multi-threaded", "true");
+         options.put("restore-login-identity", "true");
+         AppConfigurationEntry ace = new AppConfigurationEntry(name,
+         AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, options);
+         AppConfigurationEntry[] entry = {ace};
+         return entry;
+      }
+       
+      AppConfigurationEntry[] testAbortWithRestore()
+      {
+         String name1 = "org.jboss.security.auth.spi.SimpleServerLoginModule";
+         AppConfigurationEntry ace1 = new AppConfigurationEntry(name1,
+         AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, new HashMap<String,String>()); 
+         
+         
+         String name2 = "org.jboss.security.ClientLoginModule";
+         HashMap<String,String> options = new HashMap<String,String>();
+         options.put("multi-threaded", "true"); 
+         options.put("restore-login-identity", "true");
+         
+         
+         AppConfigurationEntry ace2 = new AppConfigurationEntry(name2,
+         AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, options);
+         
+         AppConfigurationEntry[] entry = {ace1,ace2};
+         return entry; 
+      }
+       
+      AppConfigurationEntry[] testAbortWithNoRestore()
+      {
+         String name1 = "org.jboss.security.auth.spi.SimpleServerLoginModule";
+         AppConfigurationEntry ace1 = new AppConfigurationEntry(name1,
+         AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, new HashMap<String,String>()); 
+         
+         
+         String name2 = "org.jboss.security.ClientLoginModule";
+         HashMap<String,String> options = new HashMap<String,String>();
+         options.put("multi-threaded", "true"); 
+         
+         AppConfigurationEntry ace2 = new AppConfigurationEntry(name2,
+         AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, options);
+         
+         AppConfigurationEntry[] entry = {ace1,ace2};
+         return entry; 
+      }
+      
+   }
+
+   public static Test suite() throws Exception
+   {
+      TestSuite suite = new TestSuite();
+      suite.addTest(new ClientLoginModuleUnitTestCase("testSingleThreaded"));
+      suite.addTest(new ClientLoginModuleUnitTestCase("testSingleThreadedRestoreIdentity"));
+      suite.addTest(new ClientLoginModuleUnitTestCase("testSingleThreadedRestoreStack"));
+      suite.addTest(new ClientLoginModuleUnitTestCase("testMultiThreaded"));
+      suite.addTest(new ClientLoginModuleUnitTestCase("testMultiThreadedRestoreIdentity"));
+      suite.addTest(new ClientLoginModuleUnitTestCase("testMultiThreadedRestoreStack"));
+      suite.addTest(new ClientLoginModuleUnitTestCase("testAbortWithRestore"));
+      suite.addTest(new ClientLoginModuleUnitTestCase("testAbortWithNoRestore"));
+      return suite;
+   }
+
+   public ClientLoginModuleUnitTestCase(String name)
+   {
+      super(name);
+   }
+
+   protected void setUp() throws Exception
+   {
+      Configuration.setConfiguration(jaasConfig);
+      //Clear SecurityAssociation
+      SecurityAssociation.clear();
+   }
+   protected void tearDown()
+   {
+   }
+
+   public void testSingleThreaded() throws Exception
+   {
+      System.out.println("+++ testSingleThreaded");
+      UsernamePasswordHandler handler = new UsernamePasswordHandler("jduke",
+         "theduke");
+      LoginContext lc = new LoginContext("testSingleThreaded", handler);
+      lc.login();
+      Subject subject = lc.getSubject();
+      System.out.println("LC.Subject: "+subject);
+      Principal theduke = new SimplePrincipal("jduke");
+      assertTrue("Principals contains theduke", subject.getPrincipals().contains(theduke));
+      Principal saPrincipal = SecurityAssociation.getPrincipal();
+      assertTrue("SecurityAssociation.getPrincipal == theduke", saPrincipal.equals(theduke));
+      char[] password = (char[]) SecurityAssociation.getCredential();
+      assertTrue("password == theduke",
+         Arrays.equals(password, "theduke".toCharArray()));
+      
+      assertTrue("Client side association?", SecurityContextAssociation.isClient());
+      
+      SecurityContext sc = SecurityContextAssociation.getSecurityContext();
+      assertNotNull("SecurityContext not null", sc);
+      assertEquals("jduke", sc.getUtil().getUserPrincipal().getName()); 
+   }
+
+   public void testSingleThreadedRestoreIdentity() throws Exception
+   {
+      System.out.println("+++ testSingleThreadedRestoreIdentity");
+      
+      Principal jduke1 = new SimplePrincipal("jduke1");
+      SecurityAssociation.setPrincipal(jduke1);
+      SecurityAssociation.setCredential("theduke1");
+
+      UsernamePasswordHandler handler = new UsernamePasswordHandler("jduke2",
+         "theduke2");
+      LoginContext lc = new LoginContext("testSingleThreadedRestoreIdentity", handler);
+      lc.login();
+      Subject subject = lc.getSubject();
+      System.out.println("LC.Subject: "+subject);
+      
+      Principal jduke2 = new SimplePrincipal("jduke2");
+      assertTrue("Principals contains jduke2", subject.getPrincipals().contains(jduke2));
+      Principal saPrincipal = SecurityAssociation.getPrincipal();
+      assertTrue("SecurityAssociation.getPrincipal == jduke2", saPrincipal.equals(jduke2));
+      char[] password = (char[]) SecurityAssociation.getCredential();
+      assertTrue("password == theduke2",
+         Arrays.equals(password, "theduke2".toCharArray()));
+
+      lc.logout();
+      // Validate restored state
+      saPrincipal = SecurityAssociation.getPrincipal();
+      assertTrue("SecurityAssociation.getPrincipal == jduke1", saPrincipal.equals(jduke1));
+      String theduke1 = (String) SecurityAssociation.getCredential();
+      assertTrue("password == theduke1", theduke1.equals("theduke1"));
+      
+   }
+
+   @SuppressWarnings("deprecation")
+   public void testSingleThreadedRestoreStack() throws Exception
+   {
+      System.out.println("+++ testSingleThreadedRestoreStack");
+ 
+      Principal jduke1 = new SimplePrincipal("jduke1");
+      Subject subject1 = new Subject();
+      SecurityAssociation.pushSubjectContext(subject1, jduke1, "theduke1");
+
+      Principal jduke2 = new SimplePrincipal("jduke2");
+      Subject subject2 = new Subject();
+      SecurityAssociation.pushSubjectContext(subject2, jduke2, "theduke2");
+
+      UsernamePasswordHandler handler = new UsernamePasswordHandler("jduke3",
+         "theduke3");
+      LoginContext lc = new LoginContext("testSingleThreadedRestoreIdentity", handler);
+      lc.login();
+      Subject subject = lc.getSubject();
+      System.out.println("LC.Subject: "+subject);
+      
+      Principal jduke3 = new SimplePrincipal("jduke3");
+      assertTrue("Principals contains jduke3", subject.getPrincipals().contains(jduke3));
+      Principal saPrincipal = SecurityAssociation.getPrincipal();
+      assertTrue("SecurityAssociation.getPrincipal == jduke3", saPrincipal.equals(jduke3));
+      char[] password = (char[]) SecurityAssociation.getCredential();
+      assertTrue("password == theduke3",
+         Arrays.equals(password, "theduke3".toCharArray()));
+      SecurityAssociation.SubjectContext sc3 = SecurityAssociation.peekSubjectContext();
+      System.out.println(sc3);
+      assertTrue("SecurityAssociation.peekSubjectContext == jduke3", sc3.getPrincipal().equals(jduke3));
+      char[] theduke3 = (char[]) sc3.getCredential();
+      assertTrue("password == theduke3",
+         Arrays.equals(theduke3, "theduke3".toCharArray()));
+
+      lc.logout();
+
+      // Validate restored state
+      SecurityAssociation.SubjectContext sc2 = SecurityAssociation.peekSubjectContext();
+      System.out.println(sc2);
+      assertTrue("SecurityAssociation.peekSubjectContext == jduke2", sc2.getPrincipal().equals(jduke2));
+      String theduke2 = (String) sc2.getCredential();
+      assertTrue("password == theduke2", theduke2.equals("theduke2"));
+
+      SecurityAssociation.popSubjectContext();
+      SecurityAssociation.SubjectContext sc1 = SecurityAssociation.peekSubjectContext();
+      System.out.println(sc1);
+      assertTrue("SecurityAssociation.peekSubjectContext == jduke1", sc1.getPrincipal().equals(jduke1));
+      String theduke1 = (String) sc1.getCredential();
+      assertTrue("password == theduke1", theduke1.equals("theduke1"));
+   }
+
+   public void testMultiThreaded() throws Exception
+   {
+      TestMultiThreaded r0 = new TestMultiThreaded();
+      Thread t0 = new Thread(r0, "testMultiThreaded#0");
+      t0.start();
+      TestMultiThreaded r1 = new TestMultiThreaded();
+      Thread t1 = new Thread(r1, "testMultiThreaded#1");
+      t1.start();
+
+      t0.join();
+      assertTrue(r0.failure == null);
+      t1.join();
+      assertTrue(r1.failure == null);
+   }
+   static class TestMultiThreaded implements Runnable
+   {
+      Exception failure;
+      public void run()
+      {
+         try
+         {
+            System.out.println("+++ testMultiThreadedRunnable");
+            UsernamePasswordHandler handler = new UsernamePasswordHandler("jduke",
+               "theduke");
+            LoginContext lc = new LoginContext("testSingleThreaded", handler);
+            lc.login();
+            Subject subject = lc.getSubject();
+            System.out.println("LC.Subject: "+subject);
+            Principal theduke = new SimplePrincipal("jduke");
+            assertTrue("Principals contains theduke", subject.getPrincipals().contains(theduke));
+            Principal saPrincipal = SecurityAssociation.getPrincipal();
+            assertTrue("SecurityAssociation.getPrincipal == theduke", saPrincipal.equals(theduke));
+            char[] password = (char[]) SecurityAssociation.getCredential();
+            assertTrue("password == theduke",
+               Arrays.equals(password, "theduke".toCharArray()));
+         }
+         catch(Exception e)
+         {
+            failure = e;
+         }
+      }
+   }
+
+   public void testMultiThreadedRestoreIdentity() throws Exception
+   {
+      TestMultiThreadedRestoreIdentity r0 = new TestMultiThreadedRestoreIdentity();
+      Thread t0 = new Thread(r0, "testMultiThreadedRestoreIdentity#0");
+      t0.start();
+      TestMultiThreadedRestoreIdentity r1 = new TestMultiThreadedRestoreIdentity();
+      Thread t1 = new Thread(r1, "testMultiThreadedRestoreIdentity#1");
+      t1.start();
+
+      t0.join();
+      assertTrue(r0.failure == null);
+      t1.join();
+      assertTrue(r1.failure == null);
+   }
+   static class TestMultiThreadedRestoreIdentity implements Runnable
+   {
+      Exception failure;
+      public void run()
+      {
+         try
+         {
+            System.out.println("+++ testMultiThreadedRestoreIdentity");
+      
+            Principal jduke1 = new SimplePrincipal("jduke1");
+            SecurityAssociation.setPrincipal(jduke1);
+            SecurityAssociation.setCredential("theduke1");
+      
+            UsernamePasswordHandler handler = new UsernamePasswordHandler("jduke2",
+               "theduke2");
+            LoginContext lc = new LoginContext("testSingleThreadedRestoreIdentity", handler);
+            lc.login();
+            Subject subject = lc.getSubject();
+            System.out.println("LC.Subject: "+subject);
+            
+            Principal jduke2 = new SimplePrincipal("jduke2");
+            assertTrue("Principals contains jduke2", subject.getPrincipals().contains(jduke2));
+            Principal saPrincipal = SecurityAssociation.getPrincipal();
+            assertTrue("SecurityAssociation.getPrincipal == jduke2", saPrincipal.equals(jduke2));
+            char[] password = (char[]) SecurityAssociation.getCredential();
+            assertTrue("password == theduke2",
+               Arrays.equals(password, "theduke2".toCharArray()));
+      
+            lc.logout();
+            // Validate restored state
+            saPrincipal = SecurityAssociation.getPrincipal();
+            assertTrue("SecurityAssociation.getPrincipal == jduke1", saPrincipal.equals(jduke1));
+            String theduke1 = (String) SecurityAssociation.getCredential();
+            assertTrue("password == theduke1", theduke1.equals("theduke1"));
+      
+         }
+         catch(Exception e)
+         {
+            failure = e;
+         }
+      }
+   }
+
+   public void testMultiThreadedRestoreStack() throws Exception
+   {
+      TestMultiThreadedRestoreStack r0 = new TestMultiThreadedRestoreStack();
+      Thread t0 = new Thread(r0, "testMultiThreadedRestoreIdentity#0");
+      t0.start();
+      TestMultiThreadedRestoreStack r1 = new TestMultiThreadedRestoreStack();
+      Thread t1 = new Thread(r1, "testMultiThreadedRestoreIdentity#1");
+      t1.start();
+
+      t0.join();
+      assertTrue(r0.failure == null);
+      t1.join();
+      assertTrue(r1.failure == null);
+   }
+   static class TestMultiThreadedRestoreStack implements Runnable
+   {
+      Exception failure;
+      @SuppressWarnings("deprecation")
+      public void run()
+      {
+         try
+         {
+            System.out.println("+++ testMultThreadedRestoreStack");
+
+            Principal jduke1 = new SimplePrincipal("jduke1");
+            Subject subject1 = new Subject();
+            SecurityAssociation.pushSubjectContext(subject1, jduke1, "theduke1");
+
+            Principal jduke2 = new SimplePrincipal("jduke2");
+            Subject subject2 = new Subject();
+            SecurityAssociation.pushSubjectContext(subject2, jduke2, "theduke2");
+
+            UsernamePasswordHandler handler = new UsernamePasswordHandler("jduke3",
+               "theduke3");
+            LoginContext lc = new LoginContext("testSingleThreadedRestoreIdentity", handler);
+            lc.login();
+            Subject subject = lc.getSubject();
+            System.out.println("LC.Subject: "+subject);
+      
+            Principal jduke3 = new SimplePrincipal("jduke3");
+            assertTrue("Principals contains jduke3", subject.getPrincipals().contains(jduke3));
+            Principal saPrincipal = SecurityAssociation.getPrincipal();
+            assertTrue("SecurityAssociation.getPrincipal == jduke3", saPrincipal.equals(jduke3));
+            char[] password = (char[]) SecurityAssociation.getCredential();
+            assertTrue("password == theduke3",
+               Arrays.equals(password, "theduke3".toCharArray()));
+            SecurityAssociation.SubjectContext sc3 = SecurityAssociation.peekSubjectContext();
+            System.out.println(sc3);
+            assertTrue("SecurityAssociation.peekSubjectContext == jduke3", sc3.getPrincipal().equals(jduke3));
+            char[] theduke3 = (char[]) sc3.getCredential();
+            assertTrue("password == theduke3",
+               Arrays.equals(theduke3, "theduke3".toCharArray()));
+
+            lc.logout(); 
+            
+            // Validate restored state
+            SecurityAssociation.SubjectContext sc2 = SecurityAssociation.peekSubjectContext();
+            System.out.println(sc2);
+            assertTrue("SecurityAssociation.peekSubjectContext == jduke2", sc2.getPrincipal().equals(jduke2));
+            String theduke2 = (String) sc2.getCredential();
+            assertTrue("password == theduke2", theduke2.equals("theduke2"));
+
+            SecurityAssociation.popSubjectContext();
+            SecurityAssociation.SubjectContext sc1 = SecurityAssociation.peekSubjectContext();
+            System.out.println(sc1);
+            assertTrue("SecurityAssociation.peekSubjectContext == jduke1", sc1.getPrincipal().equals(jduke1));
+            String theduke1 = (String) sc1.getCredential();
+            assertTrue("password == theduke1", theduke1.equals("theduke1"));
+         }
+         catch(Exception e)
+         {
+            failure = e;
+         }
+      }
+   }
+
+   //SECURITY-339: ClientLoginModule abort should not clear security context
+   public void testAbortWithRestore() throws Exception
+   {
+      SecurityContext sc = SecurityContextFactory.createSecurityContext("test");
+      SecurityContextAssociation.setSecurityContext(sc);
+      
+      //Start with successful login. Then a failed login
+      UsernamePasswordHandler handler = new UsernamePasswordHandler("jduke", "jduke");
+      LoginContext lc = new LoginContext("testAbortWithRestore", handler);
+      lc.login();
+      Subject subject = lc.getSubject();
+      assertNotNull("Subject is not null", subject);
+      
+      SecurityContext currentSC = SecurityContextAssociation.getSecurityContext();
+      assertNotNull("Current Security Context is not null", currentSC);
+      verifySubjectInfo(currentSC);
+      
+      //Failed Login
+      handler = new UsernamePasswordHandler("jduke", "BAD_PASSWORD");
+      lc = new LoginContext("testAbortWithRestore", handler);
+      try
+      {
+         lc.login(); 
+         fail("Should have failed");
+      }
+      catch(LoginException le)
+      {
+         //pass
+      }
+      subject = lc.getSubject();
+      assertNull("Subject from login context is null", subject);
+      
+      currentSC = SecurityContextAssociation.getSecurityContext();
+      assertNotNull("Current Security Context is not null", currentSC); 
+      verifySubjectInfo(currentSC);
+      
+      
+      //Successful Login
+      SecurityContextAssociation.setSecurityContext(sc);
+      handler = new UsernamePasswordHandler("jduke", "jduke");
+      lc = new LoginContext("testAbortWithRestore", handler);
+      lc.login();
+      subject = lc.getSubject();
+      assertNotNull("Subject is not null", subject);
+      
+      currentSC = SecurityContextAssociation.getSecurityContext();
+      assertNotNull("Current Security Context is not null", currentSC);
+      verifySubjectInfo(currentSC);
+      
+      //Failed Login
+      handler = new UsernamePasswordHandler("jduke", "BAD_PASSWORD");
+      lc = new LoginContext("testAbortWithRestore", handler);
+      try
+      {
+         lc.login(); 
+         fail("Should have failed");
+      }
+      catch(LoginException le)
+      {
+         //pass
+      }
+      subject = lc.getSubject();
+      assertNull("Subject is null", subject);
+      
+      currentSC = SecurityContextAssociation.getSecurityContext();
+      assertNotNull("Current Security Context is not null", currentSC);
+      verifySubjectInfo(currentSC);
+      
+      lc.logout();
+      subject = lc.getSubject();
+      assertNull("Subject from login context is null", subject);
+   }
+   
+   //SECURITY-339: ClientLoginModule abort should not clear security context
+   public void testAbortWithNoRestore() throws Exception
+   {
+      SecurityContext sc = SecurityContextFactory.createSecurityContext("test");
+      SecurityContextAssociation.setSecurityContext(sc);
+      
+      //Successful Login
+      SecurityContextAssociation.setSecurityContext(sc);
+      UsernamePasswordHandler handler = new UsernamePasswordHandler("jduke", "jduke");
+      LoginContext lc = new LoginContext("testAbortWithNoRestore", handler);
+      lc.login();
+      Subject subject = lc.getSubject();
+      assertNotNull("Subject is not null", subject);
+      
+      SecurityContext currentSC = SecurityContextAssociation.getSecurityContext();
+      assertNotNull("Current Security Context is not null", currentSC);
+      this.verifySubjectInfo(currentSC);
+      
+      //Failed Login - calls abort on the login modules
+      handler = new UsernamePasswordHandler("BAD_USER", "BAD_PASSWORD");
+      lc = new LoginContext("testAbortWithNoRestore", handler);
+      try
+      {
+         lc.login(); 
+         fail("Should have failed");
+      }
+      catch(LoginException le)
+      {
+         //pass
+      }
+      //Ensure that the failed login context does not return a subject
+      subject = lc.getSubject();
+      assertNull("Subject is null", subject);
+      
+      //We have to ensure that the first successful authentication has not been removed from the stack
+      currentSC = SecurityContextAssociation.getSecurityContext();
+      assertNotNull("Current Security Context is not null", currentSC);
+      this.verifySubjectInfo(currentSC);
+            
+      //Let us go through some logout cycles
+      handler = new UsernamePasswordHandler("jduke", "jduke");
+      lc = new LoginContext("testAbortWithNoRestore", handler);
+      lc.login();
+      subject = lc.getSubject();
+      assertNotNull("Subject is not null", subject);
+      
+      currentSC = SecurityContextAssociation.getSecurityContext();
+      assertNotNull("Current Security Context is not null", currentSC);
+      this.verifySubjectInfo(currentSC);
+      
+      lc.logout();
+
+      assertNull("Current Security Context is null", SecurityContextAssociation.getSecurityContext());
+      subject = lc.getSubject();
+      assertEquals("Subject from login context has no principals", 0, subject.getPrincipals().size());
+      
+      sc = SecurityContextFactory.createSecurityContext("test");
+      SecurityContextAssociation.setSecurityContext(sc);
+      
+      //Failed Login - calls abort on the login modules
+      handler = new UsernamePasswordHandler("BAD_USER", "BAD_PASSWORD");
+      lc = new LoginContext("testAbortWithNoRestore", handler);
+      try
+      {
+         lc.login(); 
+         fail("Should have failed");
+      }
+      catch(LoginException le)
+      {
+         //pass
+      }
+      //Ensure that the failed login context does not return a subject
+      subject = lc.getSubject();
+      assertNull("Subject is null", subject);
+      
+      //We have to ensure that the first successful authentication has not been removed from the stack
+      currentSC = SecurityContextAssociation.getSecurityContext();
+      assertNotNull("Current Security Context is not null", currentSC);
+      SubjectInfo subjectInfo = currentSC.getSubjectInfo();
+      assertNotNull("SubjectInfo", subjectInfo);
+      subject = subjectInfo.getAuthenticatedSubject();
+      assertNull("Subject is null", subject); 
+      assertNull("Principal on security context is null", currentSC.getUtil().getUserPrincipal());
+      assertNull("Principal on legacy security association is null", SecurityAssociation.getPrincipal());
+   }
+   
+   private void verifySubjectInfo(SecurityContext currentSC)
+   { 
+      SubjectInfo subjectInfo = currentSC.getSubjectInfo();
+      assertNotNull("SubjectInfo", subjectInfo);
+      Subject subject = subjectInfo.getAuthenticatedSubject();
+      assertNotNull("Subject is not null", subject); 
+      Principal jduke = new SimplePrincipal("jduke");
+      assertTrue("jduke exists in the subject",subject.getPrincipals().contains(jduke));
+      assertEquals("jduke exists", jduke, currentSC.getUtil().getUserPrincipal());
+      assertEquals("jduke exists", jduke, SecurityAssociation.getPrincipal());
+   }
+}
\ No newline at end of file

Copied: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/test/java/org/jboss/test/authentication/jaas/LdapLoginModuleDecodeActionUnitTestCase.java (from rev 91964, projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/test/java/org/jboss/test/authentication/jaas/LdapLoginModuleDecodeActionUnitTestCase.java)
===================================================================
--- projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/test/java/org/jboss/test/authentication/jaas/LdapLoginModuleDecodeActionUnitTestCase.java	                        (rev 0)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/test/java/org/jboss/test/authentication/jaas/LdapLoginModuleDecodeActionUnitTestCase.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -0,0 +1,139 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors. 
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.test.authentication.jaas;
+
+import java.io.File;
+import java.util.HashMap;
+
+import javax.management.MBeanServer;
+import javax.management.MBeanServerFactory;
+import javax.management.ObjectName;
+import javax.naming.Context;
+import javax.security.auth.login.AppConfigurationEntry;
+import javax.security.auth.login.Configuration;
+import javax.security.auth.login.LoginContext;
+
+import org.jboss.security.auth.callback.AppCallbackHandler;
+import org.jboss.security.auth.spi.LdapLoginModule;
+import org.jboss.test.security.ldap.OpenDSUnitTestCase;
+
+/**
+ * SECURITY-426: DecodeAction is not using JaasSecurityDomain MBean
+ * @author Anil.Saldhana at redhat.com
+ */
+public class LdapLoginModuleDecodeActionUnitTestCase extends OpenDSUnitTestCase
+{ 
+   private String oname = "jboss.test:service=jaasSecurityDomain";
+   
+   public LdapLoginModuleDecodeActionUnitTestCase(String name)
+   {
+      super(name); 
+   }
+
+
+   @Override
+   protected void setUp() throws Exception
+   {
+      super.setUp();
+      //load it up with example1.ldif
+      String fileName = targetDir + "ldap" + fs + "example1.ldif";
+      boolean op = util.addLDIF(serverHost, port, adminDN, adminPW, new File(fileName).toURL());
+      assertTrue(op);
+      
+      //Setup a configuration
+      Configuration.setConfiguration(new Configuration() 
+      {
+         @SuppressWarnings("unchecked")
+         @Override
+         public AppConfigurationEntry[] getAppConfigurationEntry(String cname)
+         {
+            String name = LdapLoginModule.class.getName();
+            HashMap options = new HashMap();
+            
+            options.put("java.naming.factory.initial", ldapCtxFactory);
+            options.put("java.naming.provider.url","ldap://localhost:10389/");
+            options.put("java.naming.security.authentication","simple");
+            options.put("principalDNPrefix","uid=");
+            options.put("uidAttributeID","userid");
+            options.put("roleAttributeID","roleName");
+            options.put("principalDNSuffix",",ou=People,dc=jboss,dc=org");
+            options.put("rolesCtxDN","cn=JBossSX Tests,ou=Roles,dc=jboss,dc=org");
+            options.put(Context.SECURITY_CREDENTIALS, "somecrazyencryptedstring");
+            options.put("jaasSecurityDomain", oname);
+            
+            
+            AppConfigurationEntry ace = new AppConfigurationEntry(name,
+            AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, options);
+            AppConfigurationEntry[] entry = {ace};
+            return entry; 
+         }
+
+         @Override
+         public void refresh()
+         {      
+         }
+      });
+      
+      //Setup MBeanServer
+      MBeanServer jbossMBeanServer = MBeanServerFactory.createMBeanServer("jboss");
+      try
+      {
+         Test test = new Test();
+         jbossMBeanServer.registerMBean(test, new ObjectName(oname));
+         //jbossMBeanServer.createMBean(Test.class.getName(), new ObjectName(oname), getClass().getClassLoader()); 
+      }
+      catch(Exception e)
+      {
+         e.printStackTrace();
+      }
+   }
+   
+   public void testLDAPAddDelete() throws Exception
+   {
+      //Ignore
+   }   
+   
+   public void testLDAPDecodeAction() throws Exception
+   {
+      LoginContext lc = new LoginContext("test", new AppCallbackHandler("jduke","theduke".toCharArray()));
+      lc.login();
+   }
+   
+   //We create a MBean that has just one operation for testing purposes
+   public interface TestMBean
+   {
+      byte[] decode64(byte[] secret) throws Exception;
+   }
+   
+   public class Test implements TestMBean
+   {
+      public Test() 
+      {   
+      }
+      
+      //In JBoss environment, the JaasSecurityDomain mbean will perform the decoding
+      public byte[] decode64(byte[] secret) throws Exception
+      {
+         return "theduke".getBytes();
+      }      
+   }
+}
\ No newline at end of file

Deleted: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/test/java/org/jboss/test/security/ldap/OpenDSUnitTestCase.java
===================================================================
--- projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/test/java/org/jboss/test/security/ldap/OpenDSUnitTestCase.java	2009-07-21 21:59:08 UTC (rev 91524)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/test/java/org/jboss/test/security/ldap/OpenDSUnitTestCase.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -1,153 +0,0 @@
-/*
-  * JBoss, Home of Professional Open Source
-  * Copyright 2007, JBoss Inc., and individual contributors as indicated
-  * by the @authors tag. See the copyright.txt in the distribution for a
-  * full listing of individual contributors.
-  *
-  * This is free software; you can redistribute it and/or modify it
-  * under the terms of the GNU Lesser General Public License as
-  * published by the Free Software Foundation; either version 2.1 of
-  * the License, or (at your option) any later version.
-  *
-  * This software is distributed in the hope that it will be useful,
-  * but WITHOUT ANY WARRANTY; without even the implied warranty of
-  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-  * Lesser General Public License for more details.
-  *
-  * You should have received a copy of the GNU Lesser General Public
-  * License along with this software; if not, write to the Free
-  * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-  * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
-  */
-package org.jboss.test.security.ldap;
-
-import java.io.File;
-import java.util.Hashtable;
-
-import javax.naming.Context;
-import javax.naming.NamingEnumeration;
-import javax.naming.directory.DirContext;
-import javax.naming.directory.InitialDirContext;
-import javax.naming.directory.SearchControls;
-import javax.naming.directory.SearchResult;
-
-import org.jboss.test.JBossTestCase;
-
-/**
- *  Test Basic OpenDS functionality
- *  @author Anil.Saldhana at redhat.com
- *  @since  Aug 23, 2007 
- *  @version $Revision$
- */
-public class OpenDSUnitTestCase extends JBossTestCase
-{   
-   private String serverHost;
-   private String port = "10389";
-   private String adminPW = "password";
-   private String dn = "dc=jboss,dc=org";
-   private String adminDN = "cn=Directory Manager";
-   private OpenDSUtil util = new OpenDSUtil();
-   
-   /**
-    * Use a different value for the system property on 
-    * a JVM that is not shipped by Sun
-    */
-   String ldapCtxFactory = System.getProperty("ldapctx.factory",
-         "com.sun.jndi.ldap.LdapCtxFactory");
-
-   String baseDir = System.getProperty("user.dir");
-   String fs = System.getProperty("file.separator");
-   
-   String targetDir = "target" + fs + "test-classes" + fs;
-   String openDSDir =   targetDir + "opends" ; 
-   
-   OpenDS opends = null;
-   
-   public OpenDSUnitTestCase(String name)
-   {
-      super(name); 
-   }
-
-   @Override
-   protected void setUp() throws Exception
-   {   
-      super.setUp();
-      serverHost = getServerHost(); 
-      
-      opends = new OpenDS();
-      opends.intialize(openDSDir);
-      opends.startServer();
-      assertTrue(opends.isRunning()); 
-   }
-   
-   @Override
-   protected void tearDown() throws Exception
-   {
-      super.tearDown(); 
-      assertTrue("DS is running",opends.isRunning());
-      shutdown();
-      assertFalse("DS is not running",opends.isRunning());
-   } 
-   
-   public void testLDAPAddDelete() throws Exception
-   {
-      String fileName = targetDir + "ldap" + fs + "example1.ldif";
-      boolean op = util.addLDIF(serverHost, port, adminDN, adminPW, new File(fileName).toURL());
-      assertTrue(op);
-      
-      DirContext dc = null;
-      NamingEnumeration<SearchResult> ne = null;
-      try
-      {
-         dc = this.getDirContext();
-         assertNotNull("DirContext exists?", dc);  
-
-         //Use JDK JNDI code for a search
-         SearchControls sc = new SearchControls();
-         sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
-         ne = dc.search(dn, "(objectclass=*)", sc);
-         while (ne.hasMore()) 
-         { 
-            SearchResult sr = ne.next(); 
-            assertTrue("Search Result exists?", sr != null); 
-         }
-
-         //We will delete the DIT just created
-         assertTrue(util.deleteDNRecursively(serverHost, port, adminDN, adminPW, dn)); 
-
-         assertFalse("The DIT does not exist", util.existsDN(serverHost, port, dn));
-      }
-      catch(Exception e)
-      {
-         System.err.println("Error in searching:");
-         e.printStackTrace();
-      } 
-
-      finally
-      {
-         if(ne != null)
-            ne.close();
-         if(dc != null)
-           dc.close(); 
-      }  
-   }
-    
-   private void shutdown() throws Exception
-   { 
-      //Check if the server is running
-      if(opends.isRunning())
-         opends.stopServer();
-   }
-   
-   private DirContext getDirContext() throws Exception
-   {
-      String url = "ldap://" + serverHost  + ":" + port;
-      Hashtable<String, String> env = new Hashtable<String,String>();
-      env.put(Context.INITIAL_CONTEXT_FACTORY, ldapCtxFactory);
-      env.put(Context.PROVIDER_URL, url);
-      env.put(Context.SECURITY_AUTHENTICATION, "simple");
-      env.put(Context.SECURITY_PRINCIPAL, adminDN);
-      env.put(Context.SECURITY_CREDENTIALS, adminPW);
-      return new InitialDirContext(env);   
-   } 
-}
\ No newline at end of file

Copied: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/test/java/org/jboss/test/security/ldap/OpenDSUnitTestCase.java (from rev 92039, projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/test/java/org/jboss/test/security/ldap/OpenDSUnitTestCase.java)
===================================================================
--- projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/test/java/org/jboss/test/security/ldap/OpenDSUnitTestCase.java	                        (rev 0)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/test/java/org/jboss/test/security/ldap/OpenDSUnitTestCase.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -0,0 +1,190 @@
+/*
+  * JBoss, Home of Professional Open Source
+  * Copyright 2007, JBoss Inc., and individual contributors as indicated
+  * by the @authors tag. See the copyright.txt in the distribution for a
+  * full listing of individual contributors.
+  *
+  * This is free software; you can redistribute it and/or modify it
+  * under the terms of the GNU Lesser General Public License as
+  * published by the Free Software Foundation; either version 2.1 of
+  * the License, or (at your option) any later version.
+  *
+  * This software is distributed in the hope that it will be useful,
+  * but WITHOUT ANY WARRANTY; without even the implied warranty of
+  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+  * Lesser General Public License for more details.
+  *
+  * You should have received a copy of the GNU Lesser General Public
+  * License along with this software; if not, write to the Free
+  * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+  * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+  */
+package org.jboss.test.security.ldap;
+
+import java.io.File;
+import java.util.Hashtable;
+
+import javax.naming.Context;
+import javax.naming.NamingEnumeration;
+import javax.naming.directory.DirContext;
+import javax.naming.directory.InitialDirContext;
+import javax.naming.directory.SearchControls;
+import javax.naming.directory.SearchResult;
+
+import org.jboss.test.JBossTestCase;
+
+/**
+ *  Test Basic OpenDS functionality
+ *  @author Anil.Saldhana at redhat.com
+ *  @since  Aug 23, 2007 
+ *  @version $Revision$
+ */
+public class OpenDSUnitTestCase extends JBossTestCase
+{   
+   protected String serverHost;
+   protected String port = "10389";
+   protected String adminPW = "password";
+   protected String dn = "dc=jboss,dc=org";
+   protected String adminDN = "cn=Directory Manager";
+   protected OpenDSUtil util = new OpenDSUtil();
+   
+   /**
+    * Use a different value for the system property on 
+    * a JVM that is not shipped by Sun
+    */
+   protected String ldapCtxFactory = System.getProperty("ldapctx.factory",
+         "com.sun.jndi.ldap.LdapCtxFactory");
+
+   protected String baseDir = System.getProperty("user.dir");
+   protected String fs = System.getProperty("file.separator");
+   
+   //System property when running in eclipse (-Declipse=jbosssx/ )
+   private String eclipsePath = System.getProperty("eclipse","");
+   
+   protected String targetDir = eclipsePath + "target" + fs + "test-classes" + fs;
+   protected String openDSDir =   targetDir + "opends" ; 
+   
+   protected OpenDS opends = null;
+   
+   public OpenDSUnitTestCase(String name)
+   {
+      super(name); 
+   }
+
+   @Override
+   protected void setUp() throws Exception
+   {   
+      super.setUp();
+      //Ensure openDSDir exists and recycle opends db dir
+      File openDSDirFile = new File(openDSDir);
+      if(openDSDirFile.exists())
+      {
+         File dbDir = new File(openDSDir + fs + "db");
+         assertTrue("Deletion of opendsDir db success", recursiveDeleteDir(dbDir));
+         assertTrue("Creation of opendsDir DB success", dbDir.mkdirs());
+      }   
+      
+      serverHost = getServerHost(); 
+      
+      opends = new OpenDS();
+      opends.intialize(openDSDir);
+      if(opends.isRunning())
+         opends.stopServer();
+      opends.startServer();
+      assertTrue(opends.isRunning()); 
+   }
+   
+   @Override
+   protected void tearDown() throws Exception
+   {
+      super.tearDown(); 
+      assertTrue("DS is running",opends.isRunning());
+      shutdown();
+      assertFalse("DS is not running",opends.isRunning());
+   } 
+   
+   public void testLDAPAddDelete() throws Exception
+   {
+      String fileName = targetDir + "ldap" + fs + "example1.ldif";
+      boolean op = util.addLDIF(serverHost, port, adminDN, adminPW, new File(fileName).toURL());
+      assertTrue(op);
+      
+      DirContext dc = null;
+      NamingEnumeration<SearchResult> ne = null;
+      try
+      {
+         dc = this.getDirContext();
+         assertNotNull("DirContext exists?", dc);  
+
+         //Use JDK JNDI code for a search
+         SearchControls sc = new SearchControls();
+         sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
+         ne = dc.search(dn, "(objectclass=*)", sc);
+         while (ne.hasMore()) 
+         { 
+            SearchResult sr = ne.next(); 
+            assertTrue("Search Result exists?", sr != null); 
+         }
+
+         //We will delete the DIT just created
+         assertTrue(util.deleteDNRecursively(serverHost, port, adminDN, adminPW, dn)); 
+
+         assertFalse("The DIT does not exist", util.existsDN(serverHost, port, dn));
+      }
+      catch(Exception e)
+      {
+         System.err.println("Error in searching:");
+         e.printStackTrace();
+      } 
+
+      finally
+      {
+         if(ne != null)
+            ne.close();
+         if(dc != null)
+           dc.close(); 
+      }  
+   }
+    
+   protected void shutdown() throws Exception
+   { 
+      //Check if the server is running
+      if(opends.isRunning())
+         opends.stopServer();
+   }
+   
+   private DirContext getDirContext() throws Exception
+   {
+      String url = "ldap://" + serverHost  + ":" + port;
+      Hashtable<String, String> env = new Hashtable<String,String>();
+      env.put(Context.INITIAL_CONTEXT_FACTORY, ldapCtxFactory);
+      env.put(Context.PROVIDER_URL, url);
+      env.put(Context.SECURITY_AUTHENTICATION, "simple");
+      env.put(Context.SECURITY_PRINCIPAL, adminDN);
+      env.put(Context.SECURITY_CREDENTIALS, adminPW);
+      return new InitialDirContext(env);   
+   }
+   
+   private boolean recursiveDeleteDir(File dirPath)
+   {
+      if( dirPath.exists() ) 
+      {
+         File[] files = dirPath.listFiles();
+         for(int i=0; i<files.length; i++) 
+         {
+            if(files[i].isDirectory()) 
+            {
+               recursiveDeleteDir(files[i]);
+            }
+            else 
+            {
+              files[i].delete();
+            }
+         }
+       }
+       if(dirPath.exists())
+          return dirPath.delete();
+       else
+          return true; 
+   }
+}
\ No newline at end of file

Copied: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/test/java/org/jboss/test/security/ldap/OpenDSUnitTestsAdapter.java (from rev 92039, projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/test/java/org/jboss/test/security/ldap/OpenDSUnitTestsAdapter.java)
===================================================================
--- projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/test/java/org/jboss/test/security/ldap/OpenDSUnitTestsAdapter.java	                        (rev 0)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/test/java/org/jboss/test/security/ldap/OpenDSUnitTestsAdapter.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -0,0 +1,41 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors. 
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.test.security.ldap;
+
+/**
+ * Adapter for the OpenDS unit tests
+ * @author Anil.Saldhana at redhat.com
+ */
+public class OpenDSUnitTestsAdapter extends OpenDSUnitTestCase
+{
+   public OpenDSUnitTestsAdapter(String name)
+   {
+      super(name);
+   }
+   
+
+   @Override
+   public void testLDAPAddDelete() throws Exception
+   {  
+   }  
+
+}
\ No newline at end of file

Copied: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/test/java/org/jboss/test/security/mapping/LdapAttributeMappingProviderUnitTestCase.java (from rev 92039, projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/test/java/org/jboss/test/security/mapping/LdapAttributeMappingProviderUnitTestCase.java)
===================================================================
--- projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/test/java/org/jboss/test/security/mapping/LdapAttributeMappingProviderUnitTestCase.java	                        (rev 0)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/test/java/org/jboss/test/security/mapping/LdapAttributeMappingProviderUnitTestCase.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -0,0 +1,138 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors. 
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.test.security.mapping;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+
+import junit.framework.Test;
+import junit.framework.TestSuite;
+
+import org.jboss.security.SecurityConstants;
+import org.jboss.security.SecurityContext;
+import org.jboss.security.SecurityContextFactory;
+import org.jboss.security.SimplePrincipal;
+import org.jboss.security.config.ApplicationPolicy;
+import org.jboss.security.config.MappingInfo;
+import org.jboss.security.config.ModuleOption;
+import org.jboss.security.config.SecurityConfiguration;
+import org.jboss.security.identity.Attribute;
+import org.jboss.security.mapping.MappingContext;
+import org.jboss.security.mapping.MappingManager;
+import org.jboss.security.mapping.MappingType;
+import org.jboss.security.mapping.config.MappingModuleEntry;
+import org.jboss.security.mapping.providers.attribute.LdapAttributeMappingProvider;
+import org.jboss.test.security.ldap.OpenDSUnitTestsAdapter;
+
+/**
+ * LdapAttributeMappingProvider tests
+ * @author Anil.Saldhana at redhat.com
+ */
+public class LdapAttributeMappingProviderUnitTestCase extends OpenDSUnitTestsAdapter
+{
+   public static Test suite() throws Exception
+   {
+      TestSuite suite = new TestSuite();
+      suite.addTest(new LdapAttributeMappingProviderUnitTestCase("testLDAPAttributes")); 
+      return suite;
+   }
+   
+   public LdapAttributeMappingProviderUnitTestCase(String name)
+   {
+      super(name); 
+   }
+
+   protected void setUp() throws Exception
+   {
+      super.setUp();
+      ApplicationPolicy ap = new ApplicationPolicy("test"); 
+      SecurityConfiguration.addApplicationPolicy(ap);
+      
+      //Let us add the ldapAttributes.ldif
+      String fileName = targetDir + "ldap" + fs + "ldapAttributes.ldif";
+      boolean op = util.addLDIF(serverHost, port, adminDN, adminPW, new File(fileName).toURL());
+      assertTrue(op);
+   }
+   
+   public void testLDAPAttributes() throws Exception
+   {  
+      ApplicationPolicy ap = SecurityConfiguration.getApplicationPolicy("test"); 
+      MappingModuleEntry mme = new MappingModuleEntry(LdapAttributeMappingProvider.class.getName());
+      
+      String attributeList = "mail,cn,commonname,givenname,surname,employeeType," +
+                       "employeeNumber,facsimileTelephoneNumber";
+      mme.add(new ModuleOption("bindDN",this.adminDN));
+      mme.add(new ModuleOption("bindCredential",this.adminPW));
+      mme.add(new ModuleOption("baseFilter","(uid={0})"));
+      mme.add(new ModuleOption("java.naming.provider.url", "ldap://" + serverHost  + ":" + port));
+      mme.add(new ModuleOption("baseCtxDN", "ou=People,dc=jboss,dc=org"));
+      mme.add(new ModuleOption("attributeList", attributeList));
+
+      MappingInfo attributeMappingInfo = new MappingInfo();
+      attributeMappingInfo.add(mme);
+      ap.setMappingInfo(MappingType.ATTRIBUTE.name(),attributeMappingInfo); 
+      
+      SecurityContext sc = SecurityContextFactory.createSecurityContext("test");
+      MappingManager mm = sc.getMappingManager();
+      assertNotNull("MappingManager != null", mm);
+      
+      MappingContext<List<Attribute<String>>> mc = mm.getMappingContext(MappingType.ATTRIBUTE.name());
+      assertNotNull("MappingContext != null", mc);
+      HashMap<String,Object> map = new HashMap<String,Object>();
+     
+      map.put(SecurityConstants.PRINCIPAL_IDENTIFIER, new SimplePrincipal("jduke"));
+      
+      List<Attribute<String>> attList = new ArrayList<Attribute<String>>();
+      
+      mc.performMapping(map, attList);
+      attList = (List<Attribute<String>>) mc.getMappingResult().getMappedObject(); 
+      
+      boolean foundEmail = false;
+      boolean foundEmployeeType = false;
+      boolean foundEmployeeNumber = false;
+      
+      for(Attribute<String> att: attList)
+      {
+         String attName = att.getName();
+         if(attName.equals(Attribute.TYPE.EMAIL_ADDRESS.get()))
+         {
+            assertEquals("theduke at somecastle.man",att.getValue());
+            foundEmail = true;
+         }
+         if(attName.equals("employeeType"))
+         {
+            assertEquals("permanent",att.getValue());
+            foundEmployeeType = true;
+         }
+         if(attName.equals("employeeNumber"))
+         {
+            assertEquals("007",att.getValue());
+            foundEmployeeNumber = true;
+         }
+      }
+      assertTrue("Found Email", foundEmail);
+      assertTrue("Found Emp Type", foundEmployeeType);
+      assertTrue("Found Emp Number", foundEmployeeNumber);
+   } 
+}
\ No newline at end of file

Deleted: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/test/java/org/jboss/test/securitycontext/MappingContextTestCase.java
===================================================================
--- projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/test/java/org/jboss/test/securitycontext/MappingContextTestCase.java	2009-07-21 21:59:08 UTC (rev 91524)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/test/java/org/jboss/test/securitycontext/MappingContextTestCase.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -1,72 +0,0 @@
-/*
-  * JBoss, Home of Professional Open Source
-  * Copyright 2005, JBoss Inc., and individual contributors as indicated
-  * by the @authors tag. See the copyright.txt in the distribution for a
-  * full listing of individual contributors.
-  *
-  * This is free software; you can redistribute it and/or modify it
-  * under the terms of the GNU Lesser General Public License as
-  * published by the Free Software Foundation; either version 2.1 of
-  * the License, or (at your option) any later version.
-  *
-  * This software is distributed in the hope that it will be useful,
-  * but WITHOUT ANY WARRANTY; without even the implied warranty of
-  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-  * Lesser General Public License for more details.
-  *
-  * You should have received a copy of the GNU Lesser General Public
-  * License along with this software; if not, write to the Free
-  * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-  * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
-  */
-package org.jboss.test.securitycontext; 
-
-import java.util.HashMap;
-import java.util.HashSet;
-
-import org.jboss.security.SecurityConstants;
-import org.jboss.security.SecurityContext;
-import org.jboss.security.config.SecurityConfiguration;
-import org.jboss.security.identity.RoleGroup;
-import org.jboss.security.identity.plugins.SimpleRole;
-import org.jboss.security.identity.plugins.SimpleRoleGroup;
-import org.jboss.security.mapping.MappingContext;
-
-//$Id$
-
-/**
- *  Test the various mapping providers
- *  @author <a href="mailto:Anil.Saldhana at jboss.org">Anil Saldhana</a>
- *  @since  Dec 26, 2006 
- *  @version $Revision$
- */
-public class MappingContextTestCase extends SecurityContextBaseTest
-{ 
-   public void testDeploymentRolesProvider()
-   {
-      SecurityConfiguration.addApplicationPolicy(createApplicationPolicy(securityDomain));
-      SecurityContext sc= getSC(securityDomain);
-      HashSet<String> hs = new HashSet<String>();
-      hs.add("t1");
-      hs.add("t2");
-      
-      HashMap<String,Object> rolesMap = new HashMap<String,Object>();
-      rolesMap.put(principal.getName(), hs );
-      
-      HashMap<String,Object> map = new HashMap<String,Object>();
-      map.put(SecurityConstants.PRINCIPAL_IDENTIFIER, principal);
-      map.put(SecurityConstants.DEPLOYMENT_PRINCIPAL_ROLES_MAP, rolesMap);
-      
-      RoleGroup grp = new SimpleRoleGroup(SecurityConstants.ROLES_IDENTIFIER);
-      grp.addRole(new SimpleRole("oldRole"));
-      //grp.addMember(new SimplePrincipal("oldRole"));
-      MappingContext<RoleGroup> mc = sc.getMappingManager().getMappingContext(RoleGroup.class);
-      mc.performMapping(map, grp);
-      
-      grp = (RoleGroup) mc.getMappingResult().getMappedObject();
-      
-      assertFalse("oldRole does not exist", grp.containsRole(new SimpleRole("oldRole")));
-      assertTrue("t1 exists?",grp.containsRole(new SimpleRole("t1")));
-      assertTrue("t2 exists?",grp.containsRole(new SimpleRole("t2")));
-   }
-}
\ No newline at end of file

Copied: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/test/java/org/jboss/test/securitycontext/MappingContextTestCase.java (from rev 92039, projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/test/java/org/jboss/test/securitycontext/MappingContextTestCase.java)
===================================================================
--- projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/test/java/org/jboss/test/securitycontext/MappingContextTestCase.java	                        (rev 0)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/test/java/org/jboss/test/securitycontext/MappingContextTestCase.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -0,0 +1,109 @@
+/*
+  * JBoss, Home of Professional Open Source
+  * Copyright 2005, JBoss Inc., and individual contributors as indicated
+  * by the @authors tag. See the copyright.txt in the distribution for a
+  * full listing of individual contributors.
+  *
+  * This is free software; you can redistribute it and/or modify it
+  * under the terms of the GNU Lesser General Public License as
+  * published by the Free Software Foundation; either version 2.1 of
+  * the License, or (at your option) any later version.
+  *
+  * This software is distributed in the hope that it will be useful,
+  * but WITHOUT ANY WARRANTY; without even the implied warranty of
+  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+  * Lesser General Public License for more details.
+  *
+  * You should have received a copy of the GNU Lesser General Public
+  * License along with this software; if not, write to the Free
+  * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+  * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+  */
+package org.jboss.test.securitycontext; 
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+
+import org.jboss.security.SecurityConstants;
+import org.jboss.security.SecurityContext;
+import org.jboss.security.config.SecurityConfiguration;
+import org.jboss.security.identity.Attribute;
+import org.jboss.security.identity.RoleGroup;
+import org.jboss.security.identity.plugins.SimpleRole;
+import org.jboss.security.identity.plugins.SimpleRoleGroup;
+import org.jboss.security.mapping.MappingContext;
+import org.jboss.security.mapping.MappingType;
+
+
+/**
+ *  Test the various mapping providers
+ *  @author <a href="mailto:Anil.Saldhana at jboss.org">Anil Saldhana</a>
+ *  @since  Dec 26, 2006 
+ *  @version $Revision$
+ */
+public class MappingContextTestCase extends SecurityContextBaseTest
+{ 
+   @SuppressWarnings("deprecation")
+   public void testDeploymentRolesProvider()
+   {
+      SecurityConfiguration.addApplicationPolicy(createApplicationPolicy(securityDomain));
+      SecurityContext sc= getSC(securityDomain);
+      HashSet<String> hs = new HashSet<String>();
+      hs.add("t1");
+      hs.add("t2");
+      
+      HashMap<String,Object> rolesMap = new HashMap<String,Object>();
+      rolesMap.put(principal.getName(), hs );
+      
+      HashMap<String,Object> map = new HashMap<String,Object>();
+      map.put(SecurityConstants.PRINCIPAL_IDENTIFIER, principal);
+      map.put(SecurityConstants.DEPLOYMENT_PRINCIPAL_ROLES_MAP, rolesMap);
+      
+      RoleGroup grp = new SimpleRoleGroup(SecurityConstants.ROLES_IDENTIFIER);
+      grp.addRole(new SimpleRole("oldRole"));
+
+      MappingContext<RoleGroup> mc = sc.getMappingManager().getMappingContext(RoleGroup.class);
+      assertNotNull("Mapping Context is not null", mc);
+      mc.performMapping(map, grp);
+      
+      grp = (RoleGroup) mc.getMappingResult().getMappedObject();
+      
+      assertFalse("oldRole does not exist", grp.containsRole(new SimpleRole("oldRole")));
+      assertTrue("t1 exists?",grp.containsRole(new SimpleRole("t1")));
+      assertTrue("t2 exists?",grp.containsRole(new SimpleRole("t2")));
+   }
+   
+   public void testAttributeProvider()
+   {
+      SecurityConfiguration.addApplicationPolicy(createApplicationPolicy(securityDomain));
+      SecurityContext sc= getSC(securityDomain);
+      HashSet<String> hs = new HashSet<String>();
+      hs.add("t1");
+      hs.add("t2");
+      
+      HashMap<String,Object> rolesMap = new HashMap<String,Object>();
+      rolesMap.put(principal.getName(), hs );
+      
+      HashMap<String,Object> map = new HashMap<String,Object>();
+      map.put(SecurityConstants.PRINCIPAL_IDENTIFIER, principal); 
+      
+      List<Attribute<String>> attrList = new ArrayList<Attribute<String>>(); 
+
+      MappingContext<List<Attribute<String>>> mc = sc.getMappingManager().getMappingContext(MappingType.ATTRIBUTE.name());
+      assertNotNull("Mapping Context is not null", mc);
+      mc.performMapping(map, attrList);
+      
+      attrList = (List<Attribute<String>>) mc.getMappingResult().getMappedObject();
+      
+      assertNotNull("Attribute List not null", attrList); 
+      
+      for(Attribute<?> att: attrList)
+      {
+         //Email address 
+         if(Attribute.TYPE.EMAIL_ADDRESS.get().equals(att.getName()))
+            assertEquals("anil at test", att.getValue());
+      }
+   }
+}
\ No newline at end of file

Deleted: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/test/java/org/jboss/test/securitycontext/SecurityContextBaseTest.java
===================================================================
--- projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/test/java/org/jboss/test/securitycontext/SecurityContextBaseTest.java	2009-07-21 21:59:08 UTC (rev 91524)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/test/java/org/jboss/test/securitycontext/SecurityContextBaseTest.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -1,96 +0,0 @@
-/*
-  * JBoss, Home of Professional Open Source
-  * Copyright 2005, JBoss Inc., and individual contributors as indicated
-  * by the @authors tag. See the copyright.txt in the distribution for a
-  * full listing of individual contributors.
-  *
-  * This is free software; you can redistribute it and/or modify it
-  * under the terms of the GNU Lesser General Public License as
-  * published by the Free Software Foundation; either version 2.1 of
-  * the License, or (at your option) any later version.
-  *
-  * This software is distributed in the hope that it will be useful,
-  * but WITHOUT ANY WARRANTY; without even the implied warranty of
-  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-  * Lesser General Public License for more details.
-  *
-  * You should have received a copy of the GNU Lesser General Public
-  * License along with this software; if not, write to the Free
-  * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-  * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
-  */
-package org.jboss.test.securitycontext;
- 
-import java.security.Principal;
-import java.util.List;
-
-import junit.framework.TestCase;
-
-import org.jboss.security.SimplePrincipal;
-import org.jboss.security.config.ApplicationPolicy;
-import org.jboss.security.config.RoleMappingInfo;
-import org.jboss.security.config.SecurityConfiguration;
-import org.jboss.security.mapping.config.MappingModuleEntry;
-import org.jboss.security.plugins.JBossSecurityContext;
-
-//$Id$
-
-/**
- *  Base test class with common methods
- *  @author <a href="mailto:Anil.Saldhana at jboss.org">Anil Saldhana</a>
- *  @since  Dec 26, 2006 
- *  @version $Revision$
- */
-public class SecurityContextBaseTest extends TestCase
-{ 
-   protected Principal principal = new SimplePrincipal("anil");
-   protected Object cred = "hello";
-   protected String securityDomain = "other";
-   
-   private String mappingModule = "org.jboss.security.mapping.providers.DeploymentRolesMappingProvider";
-   
-   public void testSecurityConfiguration()
-   {
-      ApplicationPolicy ap = createApplicationPolicy(securityDomain);
-      SecurityConfiguration.addApplicationPolicy(ap);
-      assertEquals(SecurityConfiguration.getApplicationPolicy(securityDomain), ap);
-   }
-   
-   protected JBossSecurityContext getSC(String domain)
-   {
-      if(domain == null)
-         domain = securityDomain;
-      return new JBossSecurityContext(securityDomain);
-   }
-   
-   protected ApplicationPolicy createApplicationPolicy(String domain)
-   {
-      ApplicationPolicy ap = new ApplicationPolicy(domain);
-      ap.setRoleMappingInfo(createRoleMappingInfo(domain));
-      return ap; 
-   }
-   
-   protected ApplicationPolicy createApplicationPolicy(String domain, RoleMappingInfo rmi)
-   {
-      ApplicationPolicy ap = new ApplicationPolicy(domain);
-      ap.setRoleMappingInfo(rmi);
-      return ap; 
-   }
-   
-   protected RoleMappingInfo createRoleMappingInfo(String domain)
-   { 
-      RoleMappingInfo rmi = new RoleMappingInfo(domain);
-      rmi.add(new MappingModuleEntry(this.mappingModule));
-      return rmi;
-   }
-   
-   protected RoleMappingInfo createRoleMappingInfo(String domain, List<String> moduleNames)
-   {
-      RoleMappingInfo rmi = new RoleMappingInfo(domain);
-      for(String mod:moduleNames)
-      { 
-         rmi.add(new MappingModuleEntry(mod));
-      }
-      return rmi;
-   }
-}

Copied: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/test/java/org/jboss/test/securitycontext/SecurityContextBaseTest.java (from rev 92039, projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/test/java/org/jboss/test/securitycontext/SecurityContextBaseTest.java)
===================================================================
--- projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/test/java/org/jboss/test/securitycontext/SecurityContextBaseTest.java	                        (rev 0)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/test/java/org/jboss/test/securitycontext/SecurityContextBaseTest.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -0,0 +1,114 @@
+/*
+  * JBoss, Home of Professional Open Source
+  * Copyright 2005, JBoss Inc., and individual contributors as indicated
+  * by the @authors tag. See the copyright.txt in the distribution for a
+  * full listing of individual contributors.
+  *
+  * This is free software; you can redistribute it and/or modify it
+  * under the terms of the GNU Lesser General Public License as
+  * published by the Free Software Foundation; either version 2.1 of
+  * the License, or (at your option) any later version.
+  *
+  * This software is distributed in the hope that it will be useful,
+  * but WITHOUT ANY WARRANTY; without even the implied warranty of
+  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+  * Lesser General Public License for more details.
+  *
+  * You should have received a copy of the GNU Lesser General Public
+  * License along with this software; if not, write to the Free
+  * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+  * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+  */
+package org.jboss.test.securitycontext;
+ 
+import java.security.Principal;
+import java.util.List;
+
+import junit.framework.TestCase;
+
+import org.jboss.security.SimplePrincipal;
+import org.jboss.security.config.ApplicationPolicy;
+import org.jboss.security.config.AttributeMappingInfo;
+import org.jboss.security.config.ModuleOption;
+import org.jboss.security.config.RoleMappingInfo;
+import org.jboss.security.config.SecurityConfiguration;
+import org.jboss.security.mapping.MappingType;
+import org.jboss.security.mapping.config.MappingModuleEntry;
+import org.jboss.security.mapping.providers.DeploymentRolesMappingProvider;
+import org.jboss.security.mapping.providers.attribute.DefaultAttributeMappingProvider;
+import org.jboss.security.plugins.JBossSecurityContext;
+
+//$Id$
+
+/**
+ *  Base test class with common methods
+ *  @author <a href="mailto:Anil.Saldhana at jboss.org">Anil Saldhana</a>
+ *  @since  Dec 26, 2006 
+ *  @version $Revision$
+ */
+public class SecurityContextBaseTest extends TestCase
+{ 
+   protected Principal principal = new SimplePrincipal("anil");
+   protected Object cred = "hello";
+   protected String securityDomain = "other";
+   
+   private String roleMappingModule = DeploymentRolesMappingProvider.class.getName();
+   private String attrMappingModule = DefaultAttributeMappingProvider.class.getName();
+   
+   public void testSecurityConfiguration()
+   {
+      ApplicationPolicy ap = createApplicationPolicy(securityDomain);
+      SecurityConfiguration.addApplicationPolicy(ap);
+      assertEquals(SecurityConfiguration.getApplicationPolicy(securityDomain), ap);
+   }
+   
+   protected JBossSecurityContext getSC(String domain)
+   {
+      if(domain == null)
+         domain = securityDomain;
+      return new JBossSecurityContext(securityDomain);
+   }
+   
+   protected ApplicationPolicy createApplicationPolicy(String domain)
+   {
+      ApplicationPolicy ap = new ApplicationPolicy(domain);
+      ap.setMappingInfo(MappingType.ROLE.name(), createRoleMappingInfo(domain)); 
+      ap.setMappingInfo(MappingType.ATTRIBUTE.name(), this.createAttributeMappingInfo(domain));
+      return ap; 
+   }
+   
+   protected ApplicationPolicy createApplicationPolicy(String domain, RoleMappingInfo rmi)
+   {
+      ApplicationPolicy ap = new ApplicationPolicy(domain);
+      ap.setMappingInfo(MappingType.ROLE.name(), rmi); 
+      return ap; 
+   }
+   
+   protected RoleMappingInfo createRoleMappingInfo(String domain)
+   { 
+      RoleMappingInfo rmi = new RoleMappingInfo(domain);
+      rmi.add(new MappingModuleEntry(this.roleMappingModule));
+      return rmi;
+   }
+   
+   protected AttributeMappingInfo createAttributeMappingInfo(String domain)
+   { 
+      AttributeMappingInfo rmi = new AttributeMappingInfo(domain);
+      MappingModuleEntry mme = new MappingModuleEntry(this.attrMappingModule); 
+      
+      ModuleOption option = new ModuleOption("anil.email", "anil at test");
+      mme.add(option);
+      rmi.add(mme);
+      return rmi;
+   }
+   
+   protected RoleMappingInfo createRoleMappingInfo(String domain, List<String> moduleNames)
+   {
+      RoleMappingInfo rmi = new RoleMappingInfo(domain);
+      for(String mod:moduleNames)
+      { 
+         rmi.add(new MappingModuleEntry(mod));
+      }
+      return rmi;
+   }
+}

Copied: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/test/resources/ldap/ldapAttributes.ldif (from rev 92039, projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx/src/test/resources/ldap/ldapAttributes.ldif)
===================================================================
--- projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/test/resources/ldap/ldapAttributes.ldif	                        (rev 0)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx/src/test/resources/ldap/ldapAttributes.ldif	2009-09-09 20:59:49 UTC (rev 93332)
@@ -0,0 +1,23 @@
+dn: dc=jboss,dc=org
+objectclass: dcObject
+objectclass: organization
+o: JBoss
+dc: JBoss
+
+dn: ou=People,dc=jboss,dc=org
+objectclass: top
+objectclass: organizationalUnit
+ou: People
+
+dn: uid=jduke,ou=People,dc=jboss,dc=org
+objectclass: top
+objectclass: uidObject
+objectclass: person
+objectclass: inetOrgPerson
+uid: jduke
+cn: Java Duke
+sn: Duke
+userPassword: theduke
+mail: theduke at somecastle.man
+employeeType:  permanent
+employeeNumber: 007

Deleted: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx-bridge-as4/pom.xml
===================================================================
--- projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx-bridge-as4/pom.xml	2009-07-21 21:59:08 UTC (rev 91524)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx-bridge-as4/pom.xml	2009-09-09 20:59:49 UTC (rev 93332)
@@ -1,62 +0,0 @@
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
-  <parent>
-    <groupId>org.jboss.security</groupId>
-    <artifactId>jbosssx-parent</artifactId>
-    <version>2.0.3.SP2-SNAPSHOT</version>
-  </parent>
-  <modelVersion>4.0.0</modelVersion>
-  <groupId>org.jboss.security</groupId>
-  <artifactId>jbosssx-bridge-as4</artifactId>
-  <packaging>pom</packaging>
-  <name>JBoss Security Implementation for the JBAS - Assembly build for AS 4.2.x</name>
-  <url>http://labs.jboss.org/portal/jbosssecurity/</url>
-  <description>JBoss Security is a cross cutting project that handles security for the JEMS projects</description>
-  <licenses>
-    <license>
-      <name>lgpl</name>
-      <url>http://repository.jboss.com/licenses/lgpl.txt</url>
-    </license>
-  </licenses>
-  <organization>
-    <name>JBoss Inc.</name>
-    <url>http://www.jboss.org</url>
-  </organization>
-    
-  <build>
-    <plugins>
-      <plugin>
-        <groupId>org.apache.maven.plugins</groupId>
-        <artifactId>maven-assembly-plugin</artifactId>
-        <version>2.1</version>
-        <executions>
-          <execution>
-            <phase>package</phase>
-            <goals>
-              <goal>attached</goal>
-            </goals>
-          </execution>
-        </executions>
-        <configuration>
-          <archive>
-            <manifestEntries>
-              <Specification-Title>JBoss Security Implementation for the JBAS</Specification-Title>
-              <Specification-Version>${project.version}</Specification-Version>
-              <Specification-Vendor>Red Hat Middleware LLC</Specification-Vendor>
-              <Implementation-Title>JBoss Security Implementation for the JBAS</Implementation-Title>
-              <Implementation-Version>${project.version}</Implementation-Version>
-              <Implementation-VendorId>org.jboss.security</Implementation-VendorId>
-              <Implementation-Vendor>Red Hat Middleware LLC</Implementation-Vendor>
-              <Implementation-URL>http://labs.jboss.org/portal/jbosssecurity/</Implementation-URL>
-            </manifestEntries>
-          </archive>
-          <descriptors>
-            <descriptor>bin.xml</descriptor>
-            <descriptor>sources.xml</descriptor>
-          </descriptors>
-        </configuration>
-        <inherited>false</inherited>
-      </plugin>
-    </plugins>
-  </build>
-  
-</project>

Copied: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx-bridge-as4/pom.xml (from rev 93331, projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx-bridge-as4/pom.xml)
===================================================================
--- projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx-bridge-as4/pom.xml	                        (rev 0)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx-bridge-as4/pom.xml	2009-09-09 20:59:49 UTC (rev 93332)
@@ -0,0 +1,62 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+  <parent>
+    <groupId>org.jboss.security</groupId>
+    <artifactId>jbosssx-parent</artifactId>
+    <version>2.0.4.SP1</version>
+  </parent>
+  <modelVersion>4.0.0</modelVersion>
+  <groupId>org.jboss.security</groupId>
+  <artifactId>jbosssx-bridge-as4</artifactId>
+  <packaging>pom</packaging>
+  <name>JBoss Security Implementation for the JBAS - Assembly build for AS 4.2.x</name>
+  <url>http://labs.jboss.org/portal/jbosssecurity/</url>
+  <description>JBoss Security is a cross cutting project that handles security for the JEMS projects</description>
+  <licenses>
+    <license>
+      <name>lgpl</name>
+      <url>http://repository.jboss.com/licenses/lgpl.txt</url>
+    </license>
+  </licenses>
+  <organization>
+    <name>JBoss Inc.</name>
+    <url>http://www.jboss.org</url>
+  </organization>
+    
+  <build>
+    <plugins>
+      <plugin>
+        <groupId>org.apache.maven.plugins</groupId>
+        <artifactId>maven-assembly-plugin</artifactId>
+        <version>2.1</version>
+        <executions>
+          <execution>
+            <phase>package</phase>
+            <goals>
+              <goal>attached</goal>
+            </goals>
+          </execution>
+        </executions>
+        <configuration>
+          <archive>
+            <manifestEntries>
+              <Specification-Title>JBoss Security Implementation for the JBAS</Specification-Title>
+              <Specification-Version>${project.version}</Specification-Version>
+              <Specification-Vendor>Red Hat Middleware LLC</Specification-Vendor>
+              <Implementation-Title>JBoss Security Implementation for the JBAS</Implementation-Title>
+              <Implementation-Version>${project.version}</Implementation-Version>
+              <Implementation-VendorId>org.jboss.security</Implementation-VendorId>
+              <Implementation-Vendor>Red Hat Middleware LLC</Implementation-Vendor>
+              <Implementation-URL>http://labs.jboss.org/portal/jbosssecurity/</Implementation-URL>
+            </manifestEntries>
+          </archive>
+          <descriptors>
+            <descriptor>bin.xml</descriptor>
+            <descriptor>sources.xml</descriptor>
+          </descriptors>
+        </configuration>
+        <inherited>false</inherited>
+      </plugin>
+    </plugins>
+  </build>
+  
+</project>

Deleted: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx-client/pom.xml
===================================================================
--- projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx-client/pom.xml	2009-07-21 21:59:08 UTC (rev 91524)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx-client/pom.xml	2009-09-09 20:59:49 UTC (rev 93332)
@@ -1,75 +0,0 @@
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
-   <parent>
-      <groupId>org.jboss</groupId>
-      <artifactId>jboss-parent</artifactId>
-      <version>3</version>
-   </parent>
-   <modelVersion>4.0.0</modelVersion>
-   <groupId>org.jboss.security</groupId>
-   <artifactId>jbosssx-client</artifactId>
-   <version>2.0.3.SP2-SNAPSHOT</version>
-   <packaging>jar</packaging>
-   <name>JBoss Security Client</name>
-   <url>http://www.jboss.org</url>
-   <description>JBoss Security Client Library</description>
-   <build>
-   <plugins>
-      <plugin>
-         <groupId>org.apache.maven.plugins</groupId>
-         <artifactId>maven-jar-plugin</artifactId>
-         <executions>
-            <execution>
-               <goals>
-                 <goal>jar</goal>
-               </goals>
-            </execution>
-         </executions>
-         <configuration>
-          <archive>
-             <manifest>
-               <addDefaultImplementationEntries>true</addDefaultImplementationEntries>
-               <addDefaultSpecificationEntries />
-             </manifest>
-          </archive>
-          <classesDirectory>../jbosssx/target/classes</classesDirectory>
-          <includes>
-             <include>JBossORG-EULA.txt</include>
-             <include>org/jboss/crypto/JBossSXProvider.class</include>
-             <include>org/jboss/crypto/CryptoUtil.class</include>
-             <include>org/jboss/crypto/digest/*</include>
-             <include>org/jboss/security/*</include>
-             <include>org/jboss/security/auth/callback/*</include>
-             <include>org/jboss/security/auth/login/*</include>
-             <include>org/jboss/security/client/*</include>
-             <include>org/jboss/security/auth/login/XMLLoginConfig.class</include>
-             <include>org/jboss/security/auth/login/XMLLoginConfigMBean.class</include>
-             <include>org/jboss/security/plugins/PBEUtils.class</include>
-             <include>org/jboss/security/ssl/ClientSocketFactory.class</include>
-             <include>org/jboss/security/ssl/RMISSLClientSocketFactory.class</include>
-             <include>org/jboss/security/plugins/*SecurityContext*.class</include>                              
-             <include>org/jboss/security/plugins/DefaultSecurityManagement.class</include>                              
-             <include>org/jboss/resource/security/*.class</include>                        </includes>
-         </configuration>
-     </plugin>
-     <plugin>
-       <groupId>org.jboss.maven.plugins</groupId>
-       <artifactId>maven-jboss-deploy-plugin</artifactId>
-       <version>1.4</version>
-       <executions>
-         <execution>
-           <id>jboss-deploy</id>
-           <goals>
-             <goal>jboss-deploy</goal>
-           </goals>
-           <phase>deploy</phase>
-         </execution>
-       </executions>
-       <configuration>
-         <groupId>jboss</groupId>
-         <jbossDeployRoot>${jboss.repository.root}</jbossDeployRoot>
-         <removeArtifactVersion>true</removeArtifactVersion>
-       </configuration>
-     </plugin>
-    </plugins>
- </build>
-</project>

Copied: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx-client/pom.xml (from rev 93331, projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx-client/pom.xml)
===================================================================
--- projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx-client/pom.xml	                        (rev 0)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx-client/pom.xml	2009-09-09 20:59:49 UTC (rev 93332)
@@ -0,0 +1,75 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+   <parent>
+      <groupId>org.jboss</groupId>
+      <artifactId>jboss-parent</artifactId>
+      <version>3</version>
+   </parent>
+   <modelVersion>4.0.0</modelVersion>
+   <groupId>org.jboss.security</groupId>
+   <artifactId>jbosssx-client</artifactId>
+   <version>2.0.4.SP1</version>
+   <packaging>jar</packaging>
+   <name>JBoss Security Client</name>
+   <url>http://www.jboss.org</url>
+   <description>JBoss Security Client Library</description>
+   <build>
+   <plugins>
+      <plugin>
+         <groupId>org.apache.maven.plugins</groupId>
+         <artifactId>maven-jar-plugin</artifactId>
+         <executions>
+            <execution>
+               <goals>
+                 <goal>jar</goal>
+               </goals>
+            </execution>
+         </executions>
+         <configuration>
+          <archive>
+             <manifest>
+               <addDefaultImplementationEntries>true</addDefaultImplementationEntries>
+               <addDefaultSpecificationEntries />
+             </manifest>
+          </archive>
+          <classesDirectory>../jbosssx/target/classes</classesDirectory>
+          <includes>
+             <include>JBossORG-EULA.txt</include>
+             <include>org/jboss/crypto/JBossSXProvider.class</include>
+             <include>org/jboss/crypto/CryptoUtil.class</include>
+             <include>org/jboss/crypto/digest/*</include>
+             <include>org/jboss/security/*</include>
+             <include>org/jboss/security/auth/callback/*</include>
+             <include>org/jboss/security/auth/login/*</include>
+             <include>org/jboss/security/client/*</include>
+             <include>org/jboss/security/auth/login/XMLLoginConfig.class</include>
+             <include>org/jboss/security/auth/login/XMLLoginConfigMBean.class</include>
+             <include>org/jboss/security/plugins/PBEUtils.class</include>
+             <include>org/jboss/security/ssl/ClientSocketFactory.class</include>
+             <include>org/jboss/security/ssl/RMISSLClientSocketFactory.class</include>
+             <include>org/jboss/security/plugins/*SecurityContext*.class</include>                              
+             <include>org/jboss/security/plugins/DefaultSecurityManagement.class</include>                              
+             <include>org/jboss/resource/security/*.class</include>                        </includes>
+         </configuration>
+     </plugin>
+     <plugin>
+       <groupId>org.jboss.maven.plugins</groupId>
+       <artifactId>maven-jboss-deploy-plugin</artifactId>
+       <version>1.4</version>
+       <executions>
+         <execution>
+           <id>jboss-deploy</id>
+           <goals>
+             <goal>jboss-deploy</goal>
+           </goals>
+           <phase>deploy</phase>
+         </execution>
+       </executions>
+       <configuration>
+         <groupId>jboss</groupId>
+         <jbossDeployRoot>${jboss.repository.root}</jbossDeployRoot>
+         <removeArtifactVersion>true</removeArtifactVersion>
+       </configuration>
+     </plugin>
+    </plugins>
+ </build>
+</project>

Deleted: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx-mc-int/pom.xml
===================================================================
--- projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx-mc-int/pom.xml	2009-07-21 21:59:08 UTC (rev 91524)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx-mc-int/pom.xml	2009-09-09 20:59:49 UTC (rev 93332)
@@ -1,125 +0,0 @@
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
-  
-  <parent>
-    <groupId>org.jboss.security</groupId>
-    <artifactId>jbosssx-parent</artifactId>
-    <version>2.0.3.SP2-SNAPSHOT</version>
-  </parent>
-  <modelVersion>4.0.0</modelVersion>
-  <artifactId>jbosssx-mc-int</artifactId>
-  <packaging>jar</packaging>
-  <name>JBoss Microcontainer Security Integration</name>
-  <url>http://labs.jboss.org/portal/jbosssecurity/</url>
-  <description>JBoss Security is a cross cutting project that handles security for the JEMS projects</description>
-
-  <build>
-    <finalName>${artifactId}</finalName>
-  </build>
-
-  <dependencies>
-    <!-- Global dependencies -->
-    <dependency>
-      <groupId>org.jboss.security</groupId>
-      <artifactId>jbosssx-bare</artifactId>
-      <version>${project.version}</version>
-      <scope>compile</scope>
-    </dependency>
-    <dependency>
-      <groupId>org.jboss.security</groupId>
-      <artifactId>jboss-security-spi</artifactId>
-      <scope>compile</scope>
-    </dependency>
-    <dependency>
-      <groupId>org.jboss.microcontainer</groupId>
-      <artifactId>jboss-kernel</artifactId>
-      <version>2.0.6.GA</version>
-      <scope>compile</scope>
-      <exclusions>
-        <exclusion>
-          <groupId>org.jboss</groupId>
-          <artifactId>jbossxb</artifactId>
-        </exclusion>
-      </exclusions>
-    </dependency>
-    <dependency>
-      <groupId>org.jboss.microcontainer</groupId>
-      <artifactId>jboss-dependency</artifactId>
-      <version>2.0.6.GA</version>
-      <scope>runtime</scope>
-      <exclusions>
-        <exclusion>
-          <groupId>org.jboss</groupId>
-          <artifactId>jbossxb</artifactId>
-        </exclusion>
-      </exclusions>
-    </dependency>
-    <dependency>
-      <groupId>org.jboss</groupId>
-      <artifactId>jboss-reflect</artifactId>
-      <version>2.0.2.GA</version>
-      <scope>runtime</scope>
-    </dependency>
-
-    <!-- Test dependencies -->
-    <dependency>
-      <groupId>jboss</groupId>
-      <artifactId>jboss-common-logging-log4j</artifactId>
-      <version>2.0.4.GA</version>
-      <scope>test</scope>
-      <exclusions>
-        <exclusion>
-          <groupId>jboss</groupId>
-          <artifactId>jboss-common-core</artifactId>
-        </exclusion>
-        <exclusion>
-          <groupId>jboss</groupId>
-          <artifactId>jboss-common-logging-spi</artifactId>
-        </exclusion>
-      </exclusions>
-    </dependency>
-    <dependency>
-      <groupId>junit</groupId>
-      <artifactId>junit</artifactId>
-      <scope>test</scope>
-    </dependency>
-    <dependency>
-      <groupId>org.jboss</groupId>
-      <artifactId>jboss-test</artifactId>
-      <scope>test</scope>
-      <exclusions>
-        <exclusion>
-          <groupId>org.jboss</groupId>
-          <artifactId>jboss-common-core</artifactId>
-        </exclusion>
-        <exclusion>
-          <groupId>jboss</groupId>
-          <artifactId>jboss-common-logging-spi</artifactId>
-        </exclusion>
-        <exclusion>
-          <groupId>jboss</groupId>
-          <artifactId>jboss-common-logging-log4j</artifactId>
-        </exclusion>
-        <exclusion>
-          <groupId>jboss.profiler.jvmti</groupId>
-          <artifactId>jboss-profiler-jvmti</artifactId>
-        </exclusion>
-        <exclusion>
-          <groupId>log4j</groupId>
-          <artifactId>log4j</artifactId>
-        </exclusion>
-        <exclusion>
-          <groupId>junit</groupId>
-          <artifactId>junit</artifactId>
-        </exclusion>
-        <exclusion>
-          <groupId>org.apache.ant</groupId>
-          <artifactId>ant</artifactId>
-        </exclusion>
-        <exclusion>
-          <groupId>org.apache.ant</groupId>
-          <artifactId>ant-junit</artifactId>
-        </exclusion>
-      </exclusions>
-    </dependency>
-  </dependencies>
-</project>

Copied: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx-mc-int/pom.xml (from rev 93331, projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx-mc-int/pom.xml)
===================================================================
--- projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx-mc-int/pom.xml	                        (rev 0)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx-mc-int/pom.xml	2009-09-09 20:59:49 UTC (rev 93332)
@@ -0,0 +1,125 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+  
+  <parent>
+    <groupId>org.jboss.security</groupId>
+    <artifactId>jbosssx-parent</artifactId>
+    <version>2.0.4.SP1</version>
+  </parent>
+  <modelVersion>4.0.0</modelVersion>
+  <artifactId>jbosssx-mc-int</artifactId>
+  <packaging>jar</packaging>
+  <name>JBoss Microcontainer Security Integration</name>
+  <url>http://labs.jboss.org/portal/jbosssecurity/</url>
+  <description>JBoss Security is a cross cutting project that handles security for the JEMS projects</description>
+
+  <build>
+    <finalName>${artifactId}</finalName>
+  </build>
+
+  <dependencies>
+    <!-- Global dependencies -->
+    <dependency>
+      <groupId>org.jboss.security</groupId>
+      <artifactId>jbosssx-bare</artifactId>
+      <version>${project.version}</version>
+      <scope>compile</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.jboss.security</groupId>
+      <artifactId>jboss-security-spi</artifactId>
+      <scope>compile</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.jboss.microcontainer</groupId>
+      <artifactId>jboss-kernel</artifactId>
+      <version>2.0.6.GA</version>
+      <scope>compile</scope>
+      <exclusions>
+        <exclusion>
+          <groupId>org.jboss</groupId>
+          <artifactId>jbossxb</artifactId>
+        </exclusion>
+      </exclusions>
+    </dependency>
+    <dependency>
+      <groupId>org.jboss.microcontainer</groupId>
+      <artifactId>jboss-dependency</artifactId>
+      <version>2.0.6.GA</version>
+      <scope>runtime</scope>
+      <exclusions>
+        <exclusion>
+          <groupId>org.jboss</groupId>
+          <artifactId>jbossxb</artifactId>
+        </exclusion>
+      </exclusions>
+    </dependency>
+    <dependency>
+      <groupId>org.jboss</groupId>
+      <artifactId>jboss-reflect</artifactId>
+      <version>2.0.2.GA</version>
+      <scope>runtime</scope>
+    </dependency>
+
+    <!-- Test dependencies -->
+    <dependency>
+      <groupId>jboss</groupId>
+      <artifactId>jboss-common-logging-log4j</artifactId>
+      <version>2.0.4.GA</version>
+      <scope>test</scope>
+      <exclusions>
+        <exclusion>
+          <groupId>jboss</groupId>
+          <artifactId>jboss-common-core</artifactId>
+        </exclusion>
+        <exclusion>
+          <groupId>jboss</groupId>
+          <artifactId>jboss-common-logging-spi</artifactId>
+        </exclusion>
+      </exclusions>
+    </dependency>
+    <dependency>
+      <groupId>junit</groupId>
+      <artifactId>junit</artifactId>
+      <scope>test</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.jboss</groupId>
+      <artifactId>jboss-test</artifactId>
+      <scope>test</scope>
+      <exclusions>
+        <exclusion>
+          <groupId>org.jboss</groupId>
+          <artifactId>jboss-common-core</artifactId>
+        </exclusion>
+        <exclusion>
+          <groupId>jboss</groupId>
+          <artifactId>jboss-common-logging-spi</artifactId>
+        </exclusion>
+        <exclusion>
+          <groupId>jboss</groupId>
+          <artifactId>jboss-common-logging-log4j</artifactId>
+        </exclusion>
+        <exclusion>
+          <groupId>jboss.profiler.jvmti</groupId>
+          <artifactId>jboss-profiler-jvmti</artifactId>
+        </exclusion>
+        <exclusion>
+          <groupId>log4j</groupId>
+          <artifactId>log4j</artifactId>
+        </exclusion>
+        <exclusion>
+          <groupId>junit</groupId>
+          <artifactId>junit</artifactId>
+        </exclusion>
+        <exclusion>
+          <groupId>org.apache.ant</groupId>
+          <artifactId>ant</artifactId>
+        </exclusion>
+        <exclusion>
+          <groupId>org.apache.ant</groupId>
+          <artifactId>ant-junit</artifactId>
+        </exclusion>
+      </exclusions>
+    </dependency>
+  </dependencies>
+</project>

Deleted: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx-mc-int/src/test/java/org/jboss/test/security/microcontainer/metadata/support/MockMappingManager.java
===================================================================
--- projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx-mc-int/src/test/java/org/jboss/test/security/microcontainer/metadata/support/MockMappingManager.java	2009-07-21 21:59:08 UTC (rev 91524)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx-mc-int/src/test/java/org/jboss/test/security/microcontainer/metadata/support/MockMappingManager.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -1,71 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * Copyright 2008, Red Hat Middleware LLC, and individual contributors
- * as indicated by the @author tags. See the copyright.txt file in the
- * distribution for a full listing of individual contributors. 
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jboss.test.security.microcontainer.metadata.support;
-
-import org.jboss.security.mapping.MappingContext;
-import org.jboss.security.mapping.MappingManager;
-
-/**
- * <p>
- * A mock {@code MappingManager} implementation used in the tests.
- * </p>
- * 
- * @author <a href="mailto:sguilhen at redhat.com">Stefan Guilhen</a>
- */
-public class MockMappingManager implements MappingManager
-{
-
-   private final String domainName;
-
-   /**
-    * <p>
-    * Creates an instance of {@code MockMappingManager} with the specified security domain name.
-    * </p>
-    * 
-    * @param domainName a {@code String} representing the name of the security domain.
-    */
-   public MockMappingManager(String domainName)
-   {
-      this.domainName = domainName;
-   }
-
-   /*
-    * (non-Javadoc)
-    * 
-    * @see org.jboss.security.mapping.MappingManager#getMappingContext(java.lang.Class)
-    */
-   public <T> MappingContext<T> getMappingContext(Class<T> clazz)
-   {
-      return null;
-   }
-
-   /*
-    * (non-Javadoc)
-    * 
-    * @see org.jboss.security.BaseSecurityManager#getSecurityDomain()
-    */
-   public String getSecurityDomain()
-   {
-      return this.domainName;
-   }
-
-}

Copied: projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx-mc-int/src/test/java/org/jboss/test/security/microcontainer/metadata/support/MockMappingManager.java (from rev 92039, projects/security/security-jboss-sx/branches/Branch_2_0/jbosssx-mc-int/src/test/java/org/jboss/test/security/microcontainer/metadata/support/MockMappingManager.java)
===================================================================
--- projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx-mc-int/src/test/java/org/jboss/test/security/microcontainer/metadata/support/MockMappingManager.java	                        (rev 0)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/jbosssx-mc-int/src/test/java/org/jboss/test/security/microcontainer/metadata/support/MockMappingManager.java	2009-09-09 20:59:49 UTC (rev 93332)
@@ -0,0 +1,81 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors. 
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.test.security.microcontainer.metadata.support;
+
+import org.jboss.security.mapping.MappingContext;
+import org.jboss.security.mapping.MappingManager;
+
+/**
+ * <p>
+ * A mock {@code MappingManager} implementation used in the tests.
+ * </p>
+ * 
+ * @author <a href="mailto:sguilhen at redhat.com">Stefan Guilhen</a>
+ */
+public class MockMappingManager implements MappingManager
+{
+
+   private final String domainName;
+
+   /**
+    * <p>
+    * Creates an instance of {@code MockMappingManager} with the specified security domain name.
+    * </p>
+    * 
+    * @param domainName a {@code String} representing the name of the security domain.
+    */
+   public MockMappingManager(String domainName)
+   {
+      this.domainName = domainName;
+   }
+
+   /*
+    * (non-Javadoc)
+    * 
+    * @see org.jboss.security.mapping.MappingManager#getMappingContext(java.lang.Class)
+    */
+   public <T> MappingContext<T> getMappingContext(Class<T> clazz)
+   {
+      return null;
+   }
+
+   /*
+    * (non-Javadoc)
+    * 
+    * @see org.jboss.security.mapping.MappingManager#getMappingContext(java.lang.Class)
+    */
+   public <T> MappingContext<T> getMappingContext(String type)
+   {
+      return null;
+   }
+   
+   /*
+    * (non-Javadoc)
+    * 
+    * @see org.jboss.security.BaseSecurityManager#getSecurityDomain()
+    */
+   public String getSecurityDomain()
+   {
+      return this.domainName;
+   }
+
+}

Deleted: projects/security/security-jboss-sx/tags/2.0.4.SP1/parent/pom.xml
===================================================================
--- projects/security/security-jboss-sx/branches/Branch_2_0/parent/pom.xml	2009-07-21 21:59:08 UTC (rev 91524)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/parent/pom.xml	2009-09-09 20:59:49 UTC (rev 93332)
@@ -1,155 +0,0 @@
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
-   <parent>
-      <groupId>org.jboss</groupId>
-      <artifactId>jboss-parent</artifactId>
-      <version>4</version>
-   </parent>
-   <modelVersion>4.0.0</modelVersion>
-   <groupId>org.jboss.security</groupId>
-   <artifactId>jbosssx-parent</artifactId>
-   <packaging>pom</packaging>
-   <version>2.0.3.SP2-SNAPSHOT</version>
-   <name>JBossSX - Parent</name>
-   <url>http://labs.jboss.org/portal/jbosssecurity/</url>
-   <description>JBoss Security is a cross cutting project that handles security for the JEMS projects</description>
-   <licenses>
-      <license>
-         <name>lgpl</name>
-         <url>http://repository.jboss.com/licenses/lgpl.txt</url>
-      </license>
-   </licenses>
-   <organization>
-      <name>JBoss Inc.</name>
-      <url>http://www.jboss.org</url>
-   </organization>
-   <scm>
-      <connection>scm:svn:http://anonsvn.jboss.org/repos/jbossas/projects/security/security-jboss-sx/branches/Branch_2_0</connection>
-      <developerConnection>scm:svn:https://svn.jboss.org/repos/jbossas/projects/security/security-jboss-sx/branches/Branch_2_0</developerConnection>
-   </scm>
-  
-   <build>
-     <plugins>
-        <plugin>
-          <artifactId>maven-release-plugin</artifactId>
-          <version>2.0-beta-6</version>
-          <configuration>
-            <tagBase>https://svn.jboss.org/repos/jbossas/projects/security/security-jboss-sx/tags</tagBase>
-          </configuration>
-        </plugin>
-     </plugins>
-     <pluginManagement>
-       <plugins>
-          <plugin>
-             <artifactId>maven-surefire-plugin</artifactId>
-             <version>2.4.3</version>
-             <configuration>
-               <printSummary>true</printSummary>
-               <disableXmlReport>false</disableXmlReport>
-               <testFailureIgnore>false</testFailureIgnore>
-               <includes>
-                 <include>**/**TestCase.java</include>
-               </includes>
-               <forkMode>pertest</forkMode>
-               <argLine>${surefire.jvm.args}</argLine>
-               <useFile>false</useFile>
-               <trimStackTrace>false</trimStackTrace>
-             </configuration>
-          </plugin>
-       </plugins>
-     </pluginManagement>
-   </build>
-  
-   <repositories>
-    <repository>
-      <id>repository.jboss.org</id>
-      <name>JBoss Repository</name>
-      <layout>default</layout>
-      <url>http://repository.jboss.org/maven2/</url>
-      <snapshots>
-        <enabled>false</enabled>
-      </snapshots>
-    </repository>
-
-    <repository>
-      <id>snapshots.jboss.org</id>
-      <name>JBoss Snapshots Repository</name>
-      <layout>default</layout>
-      <url>http://snapshots.jboss.org/maven2/</url>
-      <snapshots>
-         <enabled>true</enabled>
-      </snapshots>
-      <releases>
-         <enabled>false</enabled>
-      </releases>
-    </repository>
-  </repositories>
-  
-  <dependencyManagement>
-    <dependencies>
-      <dependency>
-        <groupId>jboss</groupId>
-        <artifactId>jboss-logging-log4j</artifactId>
-        <version>2.0.2.GA</version>
-        <scope>runtime</scope>
-      </dependency>
-      <dependency>
-         <groupId>org.jboss</groupId>
-         <artifactId>jbossxb</artifactId>
-         <version>2.0.1.GA</version>
-         <scope>compile</scope>
-      </dependency>
-      <dependency>
-         <groupId>org.jboss.javaee</groupId>
-         <artifactId>jboss-jacc-api</artifactId>
-         <version>1.1.0.${org.jboss.javaee.version}</version>
-         <scope>compile</scope>
-      </dependency>
-      <dependency>
-         <groupId>org.jboss.javaee</groupId>
-         <artifactId>jboss-jaspi-api</artifactId>
-         <version>1.0.0.${org.jboss.javaee.version}</version>
-         <scope>compile</scope>
-      </dependency>
-      <dependency>
-         <groupId>org.jboss.security</groupId>
-         <artifactId>jboss-security-spi</artifactId>
-         <version>${org.jboss.security.spi.version}</version>
-         <scope>compile</scope>
-      </dependency>
-      <dependency>
-         <groupId>stax</groupId>
-         <artifactId>stax-api</artifactId>
-         <version>1.0.1</version>
-      </dependency>
-      <dependency>
-         <groupId>sun-jaxb</groupId>
-         <artifactId>jaxb-api</artifactId>
-         <version>2.1.9</version>
-         <scope>compile</scope>
-      </dependency>
-      <dependency>
-         <groupId>sun-jaxb</groupId>
-         <artifactId>jaxb-impl</artifactId>
-         <version>2.1.9</version>
-         <scope>runtime</scope>
-      </dependency>
-      <dependency>
-         <groupId>junit</groupId>
-         <artifactId>junit</artifactId>
-         <version>3.8.1</version>
-         <scope>test</scope>
-      </dependency>
-      <dependency>
-         <groupId>org.jboss</groupId>
-         <artifactId>jboss-test</artifactId>
-         <version>1.0.4.GA</version>
-         <scope>test</scope>
-      </dependency>
-   </dependencies>
-  </dependencyManagement>
-
-  <properties>
-    <org.jboss.javaee.version>GA</org.jboss.javaee.version>
-    <org.jboss.security.spi.version>2.0.3.SP2</org.jboss.security.spi.version>
-  </properties>
-</project>

Copied: projects/security/security-jboss-sx/tags/2.0.4.SP1/parent/pom.xml (from rev 93331, projects/security/security-jboss-sx/branches/Branch_2_0/parent/pom.xml)
===================================================================
--- projects/security/security-jboss-sx/tags/2.0.4.SP1/parent/pom.xml	                        (rev 0)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/parent/pom.xml	2009-09-09 20:59:49 UTC (rev 93332)
@@ -0,0 +1,155 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+   <parent>
+      <groupId>org.jboss</groupId>
+      <artifactId>jboss-parent</artifactId>
+      <version>4</version>
+   </parent>
+   <modelVersion>4.0.0</modelVersion>
+   <groupId>org.jboss.security</groupId>
+   <artifactId>jbosssx-parent</artifactId>
+   <packaging>pom</packaging>
+   <version>2.0.4.SP1</version>
+   <name>JBossSX - Parent</name>
+   <url>http://labs.jboss.org/portal/jbosssecurity/</url>
+   <description>JBoss Security is a cross cutting project that handles security for the JEMS projects</description>
+   <licenses>
+      <license>
+         <name>lgpl</name>
+         <url>http://repository.jboss.com/licenses/lgpl.txt</url>
+      </license>
+   </licenses>
+   <organization>
+      <name>JBoss Inc.</name>
+      <url>http://www.jboss.org</url>
+   </organization>
+   <scm>
+      <connection>scm:svn:http://anonsvn.jboss.org/repos/jbossas/projects/security/security-jboss-sx/tags/2.0.4.SP1</connection>
+      <developerConnection>scm:svn:https://svn.jboss.org/repos/jbossas/projects/security/security-jboss-sx/tags/2.0.4.SP1</developerConnection>
+   </scm>
+  
+   <build>
+     <plugins>
+        <plugin>
+          <artifactId>maven-release-plugin</artifactId>
+          <version>2.0-beta-6</version>
+          <configuration>
+            <tagBase>https://svn.jboss.org/repos/jbossas/projects/security/security-jboss-sx/tags</tagBase>
+          </configuration>
+        </plugin>
+     </plugins>
+     <pluginManagement>
+       <plugins>
+          <plugin>
+             <artifactId>maven-surefire-plugin</artifactId>
+             <version>2.4.3</version>
+             <configuration>
+               <printSummary>true</printSummary>
+               <disableXmlReport>false</disableXmlReport>
+               <testFailureIgnore>false</testFailureIgnore>
+               <includes>
+                 <include>**/**TestCase.java</include>
+               </includes>
+               <forkMode>pertest</forkMode>
+               <argLine>${surefire.jvm.args}</argLine>
+               <useFile>false</useFile>
+               <trimStackTrace>false</trimStackTrace>
+             </configuration>
+          </plugin>
+       </plugins>
+     </pluginManagement>
+   </build>
+  
+   <repositories>
+    <repository>
+      <id>repository.jboss.org</id>
+      <name>JBoss Repository</name>
+      <layout>default</layout>
+      <url>http://repository.jboss.org/maven2/</url>
+      <snapshots>
+        <enabled>false</enabled>
+      </snapshots>
+    </repository>
+
+    <repository>
+      <id>snapshots.jboss.org</id>
+      <name>JBoss Snapshots Repository</name>
+      <layout>default</layout>
+      <url>http://snapshots.jboss.org/maven2/</url>
+      <snapshots>
+         <enabled>true</enabled>
+      </snapshots>
+      <releases>
+         <enabled>false</enabled>
+      </releases>
+    </repository>
+  </repositories>
+  
+  <dependencyManagement>
+    <dependencies>
+      <dependency>
+        <groupId>jboss</groupId>
+        <artifactId>jboss-logging-log4j</artifactId>
+        <version>2.0.2.GA</version>
+        <scope>runtime</scope>
+      </dependency>
+      <dependency>
+         <groupId>org.jboss</groupId>
+         <artifactId>jbossxb</artifactId>
+         <version>2.0.1.GA</version>
+         <scope>compile</scope>
+      </dependency>
+      <dependency>
+         <groupId>org.jboss.javaee</groupId>
+         <artifactId>jboss-jacc-api</artifactId>
+         <version>1.1.0.${org.jboss.javaee.version}</version>
+         <scope>compile</scope>
+      </dependency>
+      <dependency>
+         <groupId>org.jboss.javaee</groupId>
+         <artifactId>jboss-jaspi-api</artifactId>
+         <version>1.0.0.${org.jboss.javaee.version}</version>
+         <scope>compile</scope>
+      </dependency>
+      <dependency>
+         <groupId>org.jboss.security</groupId>
+         <artifactId>jboss-security-spi</artifactId>
+         <version>${org.jboss.security.spi.version}</version>
+         <scope>compile</scope>
+      </dependency>
+      <dependency>
+         <groupId>stax</groupId>
+         <artifactId>stax-api</artifactId>
+         <version>1.0.1</version>
+      </dependency>
+      <dependency>
+         <groupId>sun-jaxb</groupId>
+         <artifactId>jaxb-api</artifactId>
+         <version>2.1.9</version>
+         <scope>compile</scope>
+      </dependency>
+      <dependency>
+         <groupId>sun-jaxb</groupId>
+         <artifactId>jaxb-impl</artifactId>
+         <version>2.1.9</version>
+         <scope>runtime</scope>
+      </dependency>
+      <dependency>
+         <groupId>junit</groupId>
+         <artifactId>junit</artifactId>
+         <version>3.8.1</version>
+         <scope>test</scope>
+      </dependency>
+      <dependency>
+         <groupId>org.jboss</groupId>
+         <artifactId>jboss-test</artifactId>
+         <version>1.0.4.GA</version>
+         <scope>test</scope>
+      </dependency>
+   </dependencies>
+  </dependencyManagement>
+
+  <properties>
+    <org.jboss.javaee.version>GA</org.jboss.javaee.version>
+    <org.jboss.security.spi.version>2.0.4.SP1</org.jboss.security.spi.version>
+  </properties>
+</project>

Deleted: projects/security/security-jboss-sx/tags/2.0.4.SP1/pom.xml
===================================================================
--- projects/security/security-jboss-sx/branches/Branch_2_0/pom.xml	2009-07-21 21:59:08 UTC (rev 91524)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/pom.xml	2009-09-09 20:59:49 UTC (rev 93332)
@@ -1,95 +0,0 @@
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
-   <parent>
-      <groupId>org.jboss</groupId>
-      <artifactId>jboss-parent</artifactId>
-      <version>3</version>
-   </parent>
-   <modelVersion>4.0.0</modelVersion>
-   <groupId>org.jboss.security</groupId>
-   <artifactId>jbosssx-pom</artifactId>
-   <version>2.0.3.SP2-SNAPSHOT</version>
-   <packaging>pom</packaging>
-   <name>JBoss Security Implementation for the JBAS - Parent</name>
-   <url>http://labs.jboss.org/portal/jbosssecurity/</url>
-   <description>JBoss Security is a cross cutting project that handles security for the JEMS projects</description>
-   <licenses>
-      <license>
-         <name>lgpl</name>
-         <url>http://repository.jboss.com/licenses/lgpl.txt</url>
-      </license>
-   </licenses>
-   <organization>
-      <name>JBoss Inc.</name>
-      <url>http://www.jboss.org</url>
-   </organization>
-   <scm>
-      <connection>scm:svn:http://anonsvn.jboss.org/repos/jbossas/projects/security/security-jboss-sx/branches/Branch_2_0</connection>
-      <developerConnection>scm:svn:https://svn.jboss.org/repos/jbossas/projects/security/security-jboss-sx/branches/Branch_2_0</developerConnection>
-   </scm>
-   <repositories>
-    <repository>
-      <id>repository.jboss.org</id>
-      <name>JBoss Repository</name>
-      <layout>default</layout>
-      <url>http://repository.jboss.org/maven2/</url>
-      <snapshots>
-        <enabled>false</enabled>
-      </snapshots>
-    </repository>
-
-    <repository>
-      <id>snapshots.jboss.org</id>
-      <name>JBoss Snapshots Repository</name>
-      <layout>default</layout>
-      <url>http://snapshots.jboss.org/maven2/</url>
-      <snapshots>
-         <enabled>true</enabled>
-      </snapshots>
-      <releases>
-         <enabled>false</enabled>
-      </releases>
-    </repository>
-  </repositories>
-  
-   <modules>
-     <module>parent</module>
-     <module>identity</module>
-     <module>acl</module>
-     <module>jbosssx</module>
-     <module>jbosssx-client</module>
-     <module>jbosssx-mc-int</module>
-     <module>jbosssx-bridge-as4</module>
-     <module>assembly</module>
-   </modules>
-  
-   <profiles>
-    <!-- Specify heap size for ACL tests -->
-    <profile>
-      <id>acl-heap-profile</id>
-      <activation>
-         <activeByDefault>true</activeByDefault>
-      </activation>
-      <properties>
-         <surefire.jvm.args>-Xms512m -Xmx1024m</surefire.jvm.args>
-      </properties>
-      <modules>
-        <module>acl</module>
-      </modules>
-    </profile>
-   </profiles>
-  
-   <distributionManagement>
-    <repository>
-      <!-- Copy the distribution jar file to a local checkout of the maven repositry
-        -  This variable can be set in $MAVEN_HOME/conf/settings.xml -->
-      <id>repository.jboss.org</id>
-      <url>file://${maven.repository.root}</url>
-    </repository>
-    <snapshotRepository>
-      <id>snapshots.jboss.org</id>
-      <name>JBoss Inc. Repository</name>
-      <layout>default</layout>
-      <url>dav:https://snapshots.jboss.org/maven2/</url>
-    </snapshotRepository>
-   </distributionManagement>
-</project>

Copied: projects/security/security-jboss-sx/tags/2.0.4.SP1/pom.xml (from rev 93331, projects/security/security-jboss-sx/branches/Branch_2_0/pom.xml)
===================================================================
--- projects/security/security-jboss-sx/tags/2.0.4.SP1/pom.xml	                        (rev 0)
+++ projects/security/security-jboss-sx/tags/2.0.4.SP1/pom.xml	2009-09-09 20:59:49 UTC (rev 93332)
@@ -0,0 +1,95 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+   <parent>
+      <groupId>org.jboss</groupId>
+      <artifactId>jboss-parent</artifactId>
+      <version>3</version>
+   </parent>
+   <modelVersion>4.0.0</modelVersion>
+   <groupId>org.jboss.security</groupId>
+   <artifactId>jbosssx-pom</artifactId>
+   <version>2.0.4.SP1</version>
+   <packaging>pom</packaging>
+   <name>JBoss Security Implementation for the JBAS - Parent</name>
+   <url>http://labs.jboss.org/portal/jbosssecurity/</url>
+   <description>JBoss Security is a cross cutting project that handles security for the JEMS projects</description>
+   <licenses>
+      <license>
+         <name>lgpl</name>
+         <url>http://repository.jboss.com/licenses/lgpl.txt</url>
+      </license>
+   </licenses>
+   <organization>
+      <name>JBoss Inc.</name>
+      <url>http://www.jboss.org</url>
+   </organization>
+   <scm>
+      <connection>scm:svn:http://anonsvn.jboss.org/repos/jbossas/projects/security/security-jboss-sx/tags/2.0.4.SP1</connection>
+      <developerConnection>scm:svn:https://svn.jboss.org/repos/jbossas/projects/security/security-jboss-sx/tags/2.0.4.SP1</developerConnection>
+   </scm>
+   <repositories>
+    <repository>
+      <id>repository.jboss.org</id>
+      <name>JBoss Repository</name>
+      <layout>default</layout>
+      <url>http://repository.jboss.org/maven2/</url>
+      <snapshots>
+        <enabled>false</enabled>
+      </snapshots>
+    </repository>
+
+    <repository>
+      <id>snapshots.jboss.org</id>
+      <name>JBoss Snapshots Repository</name>
+      <layout>default</layout>
+      <url>http://snapshots.jboss.org/maven2/</url>
+      <snapshots>
+         <enabled>true</enabled>
+      </snapshots>
+      <releases>
+         <enabled>false</enabled>
+      </releases>
+    </repository>
+  </repositories>
+  
+   <modules>
+     <module>parent</module>
+     <module>identity</module>
+     <module>acl</module>
+     <module>jbosssx</module>
+     <module>jbosssx-client</module>
+     <module>jbosssx-mc-int</module>
+     <module>jbosssx-bridge-as4</module>
+     <module>assembly</module>
+   </modules>
+  
+   <profiles>
+    <!-- Specify heap size for ACL tests -->
+    <profile>
+      <id>acl-heap-profile</id>
+      <activation>
+         <activeByDefault>true</activeByDefault>
+      </activation>
+      <properties>
+         <surefire.jvm.args>-Xms512m -Xmx1024m</surefire.jvm.args>
+      </properties>
+      <modules>
+        <module>acl</module>
+      </modules>
+    </profile>
+   </profiles>
+  
+   <distributionManagement>
+    <repository>
+      <!-- Copy the distribution jar file to a local checkout of the maven repositry
+        -  This variable can be set in $MAVEN_HOME/conf/settings.xml -->
+      <id>repository.jboss.org</id>
+      <url>file://${maven.repository.root}</url>
+    </repository>
+    <snapshotRepository>
+      <id>snapshots.jboss.org</id>
+      <name>JBoss Inc. Repository</name>
+      <layout>default</layout>
+      <url>dav:https://snapshots.jboss.org/maven2/</url>
+    </snapshotRepository>
+   </distributionManagement>
+</project>




More information about the jboss-cvs-commits mailing list