[jboss-cvs] Picketlink SVN: r786 - in federation/trunk: picketlink-bindings/src/test/java/org/picketlink/test/identity/federation/bindings and 13 other directories.

jboss-cvs-commits at lists.jboss.org jboss-cvs-commits at lists.jboss.org
Tue Mar 1 14:10:17 EST 2011


Author: anil.saldhana at jboss.com
Date: 2011-03-01 14:10:15 -0500 (Tue, 01 Mar 2011)
New Revision: 786

Added:
   federation/trunk/picketlink-bindings/src/test/java/org/picketlink/test/identity/federation/bindings/authenticators/
   federation/trunk/picketlink-bindings/src/test/java/org/picketlink/test/identity/federation/bindings/authenticators/SPPostFormAuthenticatorUnitTestCase.java
   federation/trunk/picketlink-bindings/src/test/resources/config/test-idp-metadata-file-config.xml
   federation/trunk/picketlink-bindings/src/test/resources/metadata/
   federation/trunk/picketlink-bindings/src/test/resources/metadata/testshib.org.idp-metadata.xml
   federation/trunk/picketlink-fed-core/src/test/java/org/picketlink/test/identity/federation/core/config/MetadataToSPTypeUnitTestCase.java
Modified:
   federation/trunk/picketlink-bindings/src/main/java/org/picketlink/identity/federation/bindings/tomcat/sp/BaseFormAuthenticator.java
   federation/trunk/picketlink-bindings/src/main/java/org/picketlink/identity/federation/bindings/tomcat/sp/SPPostFormAuthenticator.java
   federation/trunk/picketlink-bindings/src/main/java/org/picketlink/identity/federation/bindings/tomcat/sp/SPRedirectFormAuthenticator.java
   federation/trunk/picketlink-bindings/src/test/java/org/picketlink/test/identity/federation/bindings/mock/MockCatalinaContextClassLoader.java
   federation/trunk/picketlink-fed-core/src/main/java/org/picketlink/identity/federation/core/config/SPType.java
   federation/trunk/picketlink-fed-core/src/main/java/org/picketlink/identity/federation/core/parsers/config/SAMLConfigParser.java
   federation/trunk/picketlink-fed-core/src/main/java/org/picketlink/identity/federation/core/saml/v2/constants/JBossSAMLURIConstants.java
   federation/trunk/picketlink-fed-core/src/main/java/org/picketlink/identity/federation/core/util/CoreConfigUtil.java
   federation/trunk/picketlink-fed-core/src/main/java/org/picketlink/identity/federation/core/util/XMLSignatureUtil.java
   federation/trunk/picketlink-fed-core/src/main/resources/schema/config/picketlink-fed.xsd
   federation/trunk/picketlink-web/src/main/java/org/picketlink/identity/federation/web/constants/GeneralConstants.java
   federation/trunk/picketlink-web/src/main/java/org/picketlink/identity/federation/web/util/ConfigurationUtil.java
Log:
PLFED-153: let the sp authenticators pick the identity url and idp x509 from a metadata file

Modified: federation/trunk/picketlink-bindings/src/main/java/org/picketlink/identity/federation/bindings/tomcat/sp/BaseFormAuthenticator.java
===================================================================
--- federation/trunk/picketlink-bindings/src/main/java/org/picketlink/identity/federation/bindings/tomcat/sp/BaseFormAuthenticator.java	2011-02-28 21:22:22 UTC (rev 785)
+++ federation/trunk/picketlink-bindings/src/main/java/org/picketlink/identity/federation/bindings/tomcat/sp/BaseFormAuthenticator.java	2011-03-01 19:10:15 UTC (rev 786)
@@ -24,7 +24,9 @@
 import java.io.IOException;
 import java.io.InputStream;
 import java.security.GeneralSecurityException;
+import java.security.cert.X509Certificate;
 import java.util.HashMap;
+import java.util.List;
 import java.util.Map;
 import java.util.Set;
 import java.util.concurrent.locks.Lock;
@@ -40,60 +42,77 @@
 import org.apache.catalina.connector.Response;
 import org.apache.catalina.deploy.LoginConfig;
 import org.apache.log4j.Logger;
+import org.picketlink.identity.federation.api.saml.v2.metadata.MetaDataExtractor;
 import org.picketlink.identity.federation.core.config.SPType;
 import org.picketlink.identity.federation.core.exceptions.ConfigurationException;
+import org.picketlink.identity.federation.core.exceptions.ParsingException;
 import org.picketlink.identity.federation.core.exceptions.ProcessingException;
 import org.picketlink.identity.federation.core.handler.config.Handlers;
+import org.picketlink.identity.federation.core.parsers.saml.SAMLParser;
+import org.picketlink.identity.federation.core.saml.v2.constants.JBossSAMLURIConstants;
 import org.picketlink.identity.federation.core.saml.v2.factories.SAML2HandlerChainFactory;
 import org.picketlink.identity.federation.core.saml.v2.impl.DefaultSAML2HandlerChainConfig;
 import org.picketlink.identity.federation.core.saml.v2.interfaces.SAML2Handler;
 import org.picketlink.identity.federation.core.saml.v2.interfaces.SAML2HandlerChain;
 import org.picketlink.identity.federation.core.saml.v2.interfaces.SAML2HandlerChainConfig;
 import org.picketlink.identity.federation.core.saml.v2.util.HandlerUtil;
+import org.picketlink.identity.federation.core.util.CoreConfigUtil;
 import org.picketlink.identity.federation.core.util.StringUtil;
 import org.picketlink.identity.federation.core.util.XMLSignatureUtil;
+import org.picketlink.identity.federation.newmodel.saml.v2.metadata.EndpointType;
+import org.picketlink.identity.federation.newmodel.saml.v2.metadata.EntitiesDescriptorType;
+import org.picketlink.identity.federation.newmodel.saml.v2.metadata.EntityDescriptorType;
+import org.picketlink.identity.federation.newmodel.saml.v2.metadata.IDPSSODescriptorType;
+import org.picketlink.identity.federation.newmodel.saml.v2.metadata.KeyDescriptorType;
 import org.picketlink.identity.federation.web.constants.GeneralConstants;
 import org.picketlink.identity.federation.web.util.ConfigurationUtil;
 
 /**
- * Base Class for Form Authenticators
+ * Base Class for Service Provider Form Authenticators
  * @author Anil.Saldhana at redhat.com
  * @since Jun 9, 2009
  */
-public class BaseFormAuthenticator extends FormAuthenticator
+public abstract class BaseFormAuthenticator extends FormAuthenticator
 {
    private static Logger log = Logger.getLogger(BaseFormAuthenticator.class);
-   private boolean trace = log.isTraceEnabled();
-   
+
+   private final boolean trace = log.isTraceEnabled();
+
    protected SPType spConfiguration = null;
-   
+
    protected String serviceURL = null;
+
    protected String identityURL = null;
-   
+
    protected String issuerID = null;
 
    protected String configFile = GeneralConstants.CONFIG_FILE_LOCATION;
-   
+
+   /**
+    * If the service provider is configured with an IDP metadata file,
+    * then this certificate can be picked up from the metadata
+    */
+   protected transient X509Certificate idpCertificate = null;
+
    protected transient SAML2HandlerChain chain = null;
-   
-   protected transient String samlHandlerChainClass = null; 
-   
+
+   protected transient String samlHandlerChainClass = null;
+
    protected Map<String, Object> chainConfigOptions = new HashMap<String, Object>();
-   
+
    //Whether the authenticator has to to save and restore request
    protected boolean saveRestoreRequest = true;
-   
+
    /**
     * A Lock for Handler operations in the chain
     */
    protected Lock chainLock = new ReentrantLock();
-   
 
    protected String canonicalizationMethod = CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS;
-    
+
    public BaseFormAuthenticator()
    {
-      super(); 
+      super();
    }
 
    public String getConfigFile()
@@ -105,18 +124,22 @@
    {
       this.configFile = configFile;
    }
-   
 
    public void setSamlHandlerChainClass(String samlHandlerChainClass)
    {
       this.samlHandlerChainClass = samlHandlerChainClass;
-   } 
-   
+   }
+
+   public void setServiceURL(String serviceURL)
+   {
+      this.serviceURL = serviceURL;
+   }
+
    public void setSaveRestoreRequest(boolean saveRestoreRequest)
    {
       this.saveRestoreRequest = saveRestoreRequest;
    }
-   
+
    /**
     * Set a separate issuer id
     * @param issuerID
@@ -135,9 +158,9 @@
     */
    protected boolean validate(Request request) throws IOException, GeneralSecurityException
    {
-      return request.getParameter("SAMLResponse") != null; 
+      return request.getParameter("SAMLResponse") != null;
    }
-   
+
    /**
     * Authenticate the request
     * @param request
@@ -147,104 +170,244 @@
     * @throws IOException
     * @throws {@link RuntimeException} when the response is not of type catalina response object
     */
-   public boolean authenticate( Request  request, HttpServletResponse response, LoginConfig config) throws IOException
+   public boolean authenticate(Request request, HttpServletResponse response, LoginConfig config) throws IOException
    {
-      if( response instanceof Response )
+      if (response instanceof Response)
       {
          Response catalinaResponse = (Response) response;
-         return authenticate(request, catalinaResponse, config); 
+         return authenticate(request, catalinaResponse, config);
       }
-      throw new RuntimeException( "Response was not of type catalina response" );
+      throw new RuntimeException("Response was not of type catalina response");
    }
-   
+
    @Override
    public void start() throws LifecycleException
    {
       super.start();
       processStart();
-   }  
-    
+   }
+
+   /**
+    * Get the Identity URL
+    * @return
+    */
+   public String getIdentityURL()
+   {
+      return identityURL;
+   }
+
+   /**
+    * Get the {@link X509Certificate} of the IDP
+    * if provided via the IDP metadata file
+    * @return {@link X509Certificate} or null
+    */
+   public X509Certificate getIdpCertificate()
+   {
+      return idpCertificate;
+   }
+
    //Mock test purpose
    public void testStart() throws LifecycleException
-   { 
+   {
       this.saveRestoreRequest = false;
+      if (context == null)
+         throw new RuntimeException("Catalina Context not set up");
       processStart();
-   }  
-   
+   }
+
    private void processStart() throws LifecycleException
    {
       Handlers handlers = null;
-      
+
+      //Get the chain from config 
+      if (StringUtil.isNullOrEmpty(samlHandlerChainClass))
+      {
+         chain = SAML2HandlerChainFactory.createChain();
+      }
+      else
+      {
+         try
+         {
+            chain = SAML2HandlerChainFactory.createChain(this.samlHandlerChainClass);
+         }
+         catch (ProcessingException e1)
+         {
+            throw new LifecycleException(e1);
+         }
+      }
+
       ServletContext servletContext = context.getServletContext();
+
+      this.processConfiguration();
+
+      try
+      {
+         //Get the handlers
+         String handlerConfigFileName = GeneralConstants.HANDLER_CONFIG_FILE_LOCATION;
+         handlers = ConfigurationUtil.getHandlers(servletContext.getResourceAsStream(handlerConfigFileName));
+         chain.addAll(HandlerUtil.getHandlers(handlers));
+
+         this.populateChainConfig();
+         this.initializeHandlerChain();
+      }
+      catch (Exception e)
+      {
+         throw new RuntimeException(e);
+      }
+   }
+
+   /**
+    * Return the SAML Binding that this authenticator supports
+    * @see {@link JBossSAMLURIConstants#SAML_HTTP_POST_BINDING}
+    * @see {@link JBossSAMLURIConstants#SAML_HTTP_REDIRECT_BINDING}
+    * @return
+    */
+   protected abstract String getBinding();
+
+   /**
+    * Attempt to process a metadata file available locally 
+    */
+   protected void processIDPMetadataFile(String idpMetadataFile)
+   {
+      ServletContext servletContext = context.getServletContext();
+      InputStream is = servletContext.getResourceAsStream(idpMetadataFile);
+      if (is == null)
+         return;
+
+      SAMLParser parser = new SAMLParser();
+      Object metadata = null;
+      try
+      {
+         metadata = parser.parse(is);
+      }
+      catch (ParsingException e)
+      {
+         throw new RuntimeException(e);
+      }
+      IDPSSODescriptorType idpSSO = null;
+      if (metadata instanceof EntitiesDescriptorType)
+      {
+         EntitiesDescriptorType entities = (EntitiesDescriptorType) metadata;
+         idpSSO = handleMetadata(entities);
+      }
+      else
+      {
+         idpSSO = handleMetadata((EntityDescriptorType) metadata);
+      }
+      if (idpSSO == null)
+      {
+         log.error("Unable to obtain the IDP SSO Descriptor from metadata");
+         return;
+      }
+      List<EndpointType> endpoints = idpSSO.getSingleSignOnService();
+      for (EndpointType endpoint : endpoints)
+      {
+         if (getBinding().equals(endpoint.getBinding().toString()))
+         {
+            identityURL = endpoint.getLocation().toString();
+            break;
+         }
+      }
+      List<KeyDescriptorType> keyDescriptors = idpSSO.getKeyDescriptor();
+      if (keyDescriptors.size() > 0)
+      {
+         this.idpCertificate = MetaDataExtractor.getCertificate(keyDescriptors.get(0));
+      }
+   }
+
+   /**
+    * Process the configuration from the configuration file
+    */
+   protected void processConfiguration()
+   {
+      ServletContext servletContext = context.getServletContext();
       InputStream is = servletContext.getResourceAsStream(configFile);
-      if(is == null)
+      if (is == null)
          throw new RuntimeException(configFile + " missing");
-      
-      //Get the chain from config 
-      if(StringUtil.isNullOrEmpty(samlHandlerChainClass))
-         chain = SAML2HandlerChainFactory.createChain();
-     else
-        try
-        {
-           chain = SAML2HandlerChainFactory.createChain(this.samlHandlerChainClass);
-        }
-        catch (ProcessingException e1)
-        {
-           throw new LifecycleException(e1);
-        }
-        
       try
       {
          spConfiguration = ConfigurationUtil.getSPConfiguration(is);
-         this.identityURL = spConfiguration.getIdentityURL();
+
+         if (StringUtil.isNotNull(spConfiguration.getIdpMetadataFile()))
+         {
+            processIDPMetadataFile(spConfiguration.getIdpMetadataFile());
+         }
+         else
+         {
+            this.identityURL = spConfiguration.getIdentityURL();
+         }
          this.serviceURL = spConfiguration.getServiceURL();
          this.canonicalizationMethod = spConfiguration.getCanonicalizationMethod();
 
-         log.info( "BaseFormAuthenticator:: Setting the CanonicalizationMethod on XMLSignatureUtil::"  + canonicalizationMethod );
+         log.info("BaseFormAuthenticator:: Setting the CanonicalizationMethod on XMLSignatureUtil::"
+               + canonicalizationMethod);
          XMLSignatureUtil.setCanonicalizationMethodType(canonicalizationMethod);
-         
-         if(trace) log.trace("Identity Provider URL=" + this.identityURL); 
+
+         if (trace)
+            log.trace("Identity Provider URL=" + this.identityURL);
       }
       catch (Exception e)
       {
          throw new RuntimeException(e);
       }
-       
-      try
+   }
+
+   protected IDPSSODescriptorType handleMetadata(EntitiesDescriptorType entities)
+   {
+      IDPSSODescriptorType idpSSO = null;
+
+      List<Object> entityDescs = entities.getEntityDescriptor();
+      for (Object entityDescriptor : entityDescs)
       {
-         //Get the handlers
-         String handlerConfigFileName = GeneralConstants.HANDLER_CONFIG_FILE_LOCATION;
-         handlers = ConfigurationUtil.getHandlers(servletContext.getResourceAsStream(handlerConfigFileName));
-         chain.addAll(HandlerUtil.getHandlers(handlers));
-         
-         this.populateChainConfig();
-         this.initializeHandlerChain();
+         if (entityDescriptor instanceof EntitiesDescriptorType)
+         {
+            idpSSO = getIDPSSODescriptor(entities);
+         }
+         else
+            idpSSO = handleMetadata((EntityDescriptorType) entityDescriptor);
+         if (idpSSO != null)
+            break;
       }
-      catch(Exception e)
+      return idpSSO;
+   }
+
+   protected IDPSSODescriptorType handleMetadata(EntityDescriptorType entityDescriptor)
+   {
+      return CoreConfigUtil.getIDPDescriptor(entityDescriptor);
+   }
+
+   protected IDPSSODescriptorType getIDPSSODescriptor(EntitiesDescriptorType entities)
+   {
+      List<Object> entityDescs = entities.getEntityDescriptor();
+      for (Object entityDescriptor : entityDescs)
       {
-         throw new RuntimeException(e);  
-      }  
-   } 
-   
-   protected void initializeHandlerChain() 
-   throws ConfigurationException, ProcessingException
+
+         if (entityDescriptor instanceof EntitiesDescriptorType)
+         {
+            return getIDPSSODescriptor((EntitiesDescriptorType) entityDescriptor);
+         }
+         return CoreConfigUtil.getIDPDescriptor((EntityDescriptorType) entityDescriptor);
+      }
+      return null;
+   }
+
+   protected void initializeHandlerChain() throws ConfigurationException, ProcessingException
    {
       populateChainConfig();
       SAML2HandlerChainConfig handlerChainConfig = new DefaultSAML2HandlerChainConfig(chainConfigOptions);
-      
+
       Set<SAML2Handler> samlHandlers = chain.handlers();
-      
-      for(SAML2Handler handler: samlHandlers)
+
+      for (SAML2Handler handler : samlHandlers)
       {
          handler.initChainConfig(handlerChainConfig);
       }
    }
-   
-   protected void populateChainConfig()
-   throws ConfigurationException, ProcessingException
+
+   protected void populateChainConfig() throws ConfigurationException, ProcessingException
    {
       chainConfigOptions.put(GeneralConstants.CONFIGURATION, spConfiguration);
-      chainConfigOptions.put( GeneralConstants.CANONICALIZATION_METHOD, canonicalizationMethod );
+      chainConfigOptions.put(GeneralConstants.CANONICALIZATION_METHOD, canonicalizationMethod);
       chainConfigOptions.put(GeneralConstants.ROLE_VALIDATOR_IGNORE, "false"); //No validator as tomcat realm does validn   
    }
 }
\ No newline at end of file

Modified: federation/trunk/picketlink-bindings/src/main/java/org/picketlink/identity/federation/bindings/tomcat/sp/SPPostFormAuthenticator.java
===================================================================
--- federation/trunk/picketlink-bindings/src/main/java/org/picketlink/identity/federation/bindings/tomcat/sp/SPPostFormAuthenticator.java	2011-02-28 21:22:22 UTC (rev 785)
+++ federation/trunk/picketlink-bindings/src/main/java/org/picketlink/identity/federation/bindings/tomcat/sp/SPPostFormAuthenticator.java	2011-03-01 19:10:15 UTC (rev 786)
@@ -44,11 +44,12 @@
 import org.picketlink.identity.federation.core.exceptions.ParsingException;
 import org.picketlink.identity.federation.core.exceptions.ProcessingException;
 import org.picketlink.identity.federation.core.interfaces.TrustKeyManager;
+import org.picketlink.identity.federation.core.saml.v2.constants.JBossSAMLURIConstants;
 import org.picketlink.identity.federation.core.saml.v2.exceptions.IssuerNotTrustedException;
 import org.picketlink.identity.federation.core.saml.v2.holders.DestinationInfoHolder;
 import org.picketlink.identity.federation.core.saml.v2.interfaces.SAML2Handler;
 import org.picketlink.identity.federation.core.saml.v2.interfaces.SAML2HandlerResponse;
-import org.picketlink.identity.federation.core.saml.v2.util.DocumentUtil; 
+import org.picketlink.identity.federation.core.saml.v2.util.DocumentUtil;
 import org.picketlink.identity.federation.newmodel.saml.v2.protocol.ResponseType;
 import org.picketlink.identity.federation.web.constants.GeneralConstants;
 import org.picketlink.identity.federation.web.core.HTTPContext;
@@ -67,58 +68,60 @@
  * @author Anil.Saldhana at redhat.com
  * @since Dec 12, 2008
  */
-public class SPPostFormAuthenticator extends BaseFormAuthenticator 
-{    
+public class SPPostFormAuthenticator extends BaseFormAuthenticator
+{
    private static Logger log = Logger.getLogger(SPPostFormAuthenticator.class);
-   private boolean trace = log.isTraceEnabled();
+
+   private final boolean trace = log.isTraceEnabled();
+
    private boolean jbossEnv = false;
-   
-   private String logOutPage = GeneralConstants.LOGOUT_PAGE_NAME;
-   
+
+   private final String logOutPage = GeneralConstants.LOGOUT_PAGE_NAME;
+
    protected boolean supportSignatures = false;
-   
-   protected TrustKeyManager keyManager;  
-   
+
+   protected TrustKeyManager keyManager;
+
    /**
     * A flag to indicate that we are going to validate signature
     * for saml responses from IDP
     */
    protected boolean validateSignature = false;
-   
+
    public SPPostFormAuthenticator()
    {
-      super(); 
-      ServerDetector detector = new ServerDetector(); 
+      super();
+      ServerDetector detector = new ServerDetector();
       jbossEnv = detector.isJboss();
-   }  
+   }
 
    @Override
    public boolean authenticate(Request request, Response response, LoginConfig loginConfig) throws IOException
    {
-      SPUtil spUtil = new SPUtil(); 
-      
+      SPUtil spUtil = new SPUtil();
+
       //Eagerly look for Global LogOut
       String gloStr = request.getParameter(GeneralConstants.GLOBAL_LOGOUT);
       boolean logOutRequest = isNotNull(gloStr) && "true".equalsIgnoreCase(gloStr);
-     
+
       String samlRequest = request.getParameter(GeneralConstants.SAML_REQUEST_KEY);
-      String samlResponse = request.getParameter(GeneralConstants.SAML_RESPONSE_KEY); 
-       
+      String samlResponse = request.getParameter(GeneralConstants.SAML_RESPONSE_KEY);
+
       Principal principal = request.getUserPrincipal();
-      
+
       //If we have already authenticated the user and there is no request from IDP or logout from user
-      if(principal != null && !(logOutRequest || isNotNull(samlRequest) || isNotNull(samlResponse) ) )
-         return true; 
-      
+      if (principal != null && !(logOutRequest || isNotNull(samlRequest) || isNotNull(samlResponse)))
+         return true;
+
       Session session = request.getSessionInternal(true);
       String relayState = request.getParameter(GeneralConstants.RELAY_STATE);
 
       boolean willSendRequest = false;
       HTTPContext httpContext = new HTTPContext(request, response, context.getServletContext());
       Set<SAML2Handler> handlers = chain.handlers();
-      
+
       //General User Request
-      if(!isNotNull(samlRequest) && !isNotNull(samlResponse))
+      if (!isNotNull(samlRequest) && !isNotNull(samlResponse))
       {
          //Neither saml request nor response from IDP
          //So this is a user request
@@ -126,14 +129,14 @@
          try
          {
             ServiceProviderBaseProcessor baseProcessor = new ServiceProviderBaseProcessor(true, serviceURL);
-            if( issuerID != null )
-               baseProcessor.setIssuer( issuerID );
-            
-            baseProcessor.setIdentityURL( identityURL );
-            
-            saml2HandlerResponse = baseProcessor.process(httpContext, handlers, chainLock); 
+            if (issuerID != null)
+               baseProcessor.setIssuer(issuerID);
+
+            baseProcessor.setIdentityURL(identityURL);
+
+            saml2HandlerResponse = baseProcessor.process(httpContext, handlers, chainLock);
          }
-         catch(ProcessingException pe)
+         catch (ProcessingException pe)
          {
             log.error("Processing Exception:", pe);
             throw new RuntimeException(pe);
@@ -147,39 +150,37 @@
          {
             log.error("Config Exception:", pe);
             throw new RuntimeException(pe);
-         } 
-         
+         }
+
          willSendRequest = saml2HandlerResponse.getSendRequest();
-         
+
          Document samlResponseDocument = saml2HandlerResponse.getResultingDocument();
          relayState = saml2HandlerResponse.getRelayState();
 
          String destination = saml2HandlerResponse.getDestination();
 
-         if(destination != null && 
-               samlResponseDocument != null)
+         if (destination != null && samlResponseDocument != null)
          {
             try
-            { 
-               if( saveRestoreRequest )
+            {
+               if (saveRestoreRequest)
                {
-                  this.saveRequest(request, session); 
+                  this.saveRequest(request, session);
                }
-               sendRequestToIDP(destination, samlResponseDocument, relayState, response,
-                     willSendRequest);
+               sendRequestToIDP(destination, samlResponseDocument, relayState, response, willSendRequest);
                return false;
             }
             catch (Exception e)
             {
-               if(trace)
-                  log.trace("Exception:",e);
+               if (trace)
+                  log.trace("Exception:", e);
                throw new IOException("Server Error");
-            } 
-         } 
+            }
+         }
       }
 
       //Handle a SAML Response from IDP
-      if(isNotNull(samlResponse) )
+      if (isNotNull(samlResponse))
       {
          boolean isValid = false;
          try
@@ -188,34 +189,31 @@
          }
          catch (Exception e)
          {
-            log.error("Exception:",e);
+            log.error("Exception:", e);
             throw new IOException();
          }
-         if(!isValid)
+         if (!isValid)
             throw new IOException("Validity check failed");
-         
-         
+
          //deal with SAML response from IDP 
          try
          {
-            ServiceProviderSAMLResponseProcessor responseProcessor =
-               new ServiceProviderSAMLResponseProcessor(true, serviceURL);
-            responseProcessor.setValidateSignature( validateSignature );
+            ServiceProviderSAMLResponseProcessor responseProcessor = new ServiceProviderSAMLResponseProcessor(true,
+                  serviceURL);
+            responseProcessor.setValidateSignature(validateSignature);
             responseProcessor.setTrustKeyManager(keyManager);
-            
-            SAML2HandlerResponse saml2HandlerResponse = 
-               responseProcessor.process(samlResponse, httpContext, handlers, chainLock);
 
+            SAML2HandlerResponse saml2HandlerResponse = responseProcessor.process(samlResponse, httpContext, handlers,
+                  chainLock);
+
             Document samlResponseDocument = saml2HandlerResponse.getResultingDocument();
             relayState = saml2HandlerResponse.getRelayState();
 
             String destination = saml2HandlerResponse.getDestination();
 
             willSendRequest = saml2HandlerResponse.getSendRequest();
-            
 
-            if(destination != null && 
-                  samlResponseDocument != null)
+            if (destination != null && samlResponseDocument != null)
             {
                sendRequestToIDP(destination, samlResponseDocument, relayState, response, willSendRequest);
             }
@@ -223,38 +221,38 @@
             {
                //See if the session has been invalidated
 
-               boolean sessionValidity = session.isValid(); 
-               if(!sessionValidity)
+               boolean sessionValidity = session.isValid();
+               if (!sessionValidity)
                {
                   //we are invalidated.
-                  RequestDispatcher dispatch = context.getServletContext().getRequestDispatcher(this.logOutPage); 
-                  if(dispatch == null)
+                  RequestDispatcher dispatch = context.getServletContext().getRequestDispatcher(this.logOutPage);
+                  if (dispatch == null)
                      log.error("Cannot dispatch to the logout page: no request dispatcher:" + this.logOutPage);
                   else
                      dispatch.forward(request, response);
-                  return false;  
-               }  
+                  return false;
+               }
 
                //We got a response with the principal
                List<String> roles = saml2HandlerResponse.getRoles();
-               if(principal == null)
+               if (principal == null)
                   principal = (Principal) session.getSession().getAttribute(GeneralConstants.PRINCIPAL_ID);
 
                String username = principal.getName();
                String password = ServiceProviderSAMLContext.EMPTY_PASSWORD;
-               if( trace )
-                  log.trace( "Roles determined for username=" + username + "=" + Arrays.toString( roles.toArray() ) );
-                
+               if (trace)
+                  log.trace("Roles determined for username=" + username + "=" + Arrays.toString(roles.toArray()));
+
                //Map to JBoss specific principal
-               if((new ServerDetector()).isJboss() || jbossEnv)
+               if ((new ServerDetector()).isJboss() || jbossEnv)
                {
                   //Push a context
                   ServiceProviderSAMLContext.push(username, roles);
-                  principal = context.getRealm().authenticate(username, password); 
+                  principal = context.getRealm().authenticate(username, password);
                   ServiceProviderSAMLContext.clear();
                }
                else
-               { 
+               {
                   //tomcat env    
                   principal = spUtil.createGenericPrincipal(request, username, roles);
                }
@@ -263,49 +261,55 @@
                session.setNote(Constants.SESS_PASSWORD_NOTE, password);
                request.setUserPrincipal(principal);
                //Get the original saved request
-               if( saveRestoreRequest )
+               if (saveRestoreRequest)
                {
-                  this.restoreRequest(request, session); 
+                  this.restoreRequest(request, session);
                }
-               register(request, response, principal, Constants.FORM_METHOD, username, password); 
+               register(request, response, principal, Constants.FORM_METHOD, username, password);
 
-               return true; 
-            }  
+               return true;
+            }
          }
          catch (Exception e)
          {
-            if(trace)
+            if (trace)
                log.trace("Server Exception:", e);
             throw new IOException("Server Exception");
-         }  
-      } 
-      
+         }
+      }
+
       //Handle SAML Requests from IDP
-      if(isNotNull(samlRequest))
-      { 
+      if (isNotNull(samlRequest))
+      {
          try
          {
-            ServiceProviderSAMLRequestProcessor requestProcessor = 
-               new ServiceProviderSAMLRequestProcessor(true, this.serviceURL);
+            ServiceProviderSAMLRequestProcessor requestProcessor = new ServiceProviderSAMLRequestProcessor(true,
+                  this.serviceURL);
             requestProcessor.setTrustKeyManager(keyManager);
             requestProcessor.setSupportSignatures(supportSignatures);
             boolean result = requestProcessor.process(samlRequest, httpContext, handlers, chainLock);
-            
-            if(result)
+
+            if (result)
                return result;
          }
          catch (Exception e)
          {
-            if(trace)
+            if (trace)
                log.trace("Server Exception:", e);
             throw new IOException("Server Exception");
-         }   
+         }
       }//end if   
 
       //fallback
-      return super.authenticate(request, response, loginConfig); 
-   }  
-   
+      return super.authenticate(request, response, loginConfig);
+   }
+
+   @Override
+   protected String getBinding()
+   {
+      return JBossSAMLURIConstants.SAML_HTTP_POST_BINDING.get();
+   }
+
    /**
     * Send the request to the IDP
     * @param destination idp url
@@ -316,18 +320,16 @@
     * @throws ProcessingException
     * @throws ConfigurationException
     * @throws IOException 
-    */ 
-   protected void sendRequestToIDP( 
-         String destination, Document samlDocument,String relayState, Response response,
-         boolean willSendRequest)
-   throws ProcessingException, ConfigurationException, IOException
+    */
+   protected void sendRequestToIDP(String destination, Document samlDocument, String relayState, Response response,
+         boolean willSendRequest) throws ProcessingException, ConfigurationException, IOException
    {
-      String samlMessage = DocumentUtil.getDocumentAsString(samlDocument); 
+      String samlMessage = DocumentUtil.getDocumentAsString(samlDocument);
       samlMessage = PostBindingUtil.base64Encode(samlMessage);
-      PostBindingUtil.sendPost(new DestinationInfoHolder(destination, samlMessage, relayState),
-            response, willSendRequest); 
+      PostBindingUtil.sendPost(new DestinationInfoHolder(destination, samlMessage, relayState), response,
+            willSendRequest);
    }
- 
+
    /**
     * Trust handling
     * @param issuer
@@ -338,20 +340,20 @@
       try
       {
          String issuerDomain = ValveUtil.getDomain(issuer);
-         TrustType idpTrust =  spConfiguration.getTrust();
-         if(idpTrust != null)
+         TrustType idpTrust = spConfiguration.getTrust();
+         if (idpTrust != null)
          {
             String domainsTrusted = idpTrust.getDomains();
-            if(domainsTrusted.indexOf(issuerDomain) < 0)
-               throw new IssuerNotTrustedException(issuer); 
+            if (domainsTrusted.indexOf(issuerDomain) < 0)
+               throw new IssuerNotTrustedException(issuer);
          }
       }
       catch (Exception e)
       {
-         throw new IssuerNotTrustedException(e.getLocalizedMessage(),e);
+         throw new IssuerNotTrustedException(e.getLocalizedMessage(), e);
       }
    }
-   
+
    /**
     * Subclasses should provide the implementation
     * @param responseType ResponseType that contains the encrypted assertion
@@ -360,5 +362,5 @@
    protected ResponseType decryptAssertion(ResponseType responseType)
    {
       throw new RuntimeException("This authenticator does not handle encryption");
-   }  
+   }
 }
\ No newline at end of file

Modified: federation/trunk/picketlink-bindings/src/main/java/org/picketlink/identity/federation/bindings/tomcat/sp/SPRedirectFormAuthenticator.java
===================================================================
--- federation/trunk/picketlink-bindings/src/main/java/org/picketlink/identity/federation/bindings/tomcat/sp/SPRedirectFormAuthenticator.java	2011-02-28 21:22:22 UTC (rev 785)
+++ federation/trunk/picketlink-bindings/src/main/java/org/picketlink/identity/federation/bindings/tomcat/sp/SPRedirectFormAuthenticator.java	2011-03-01 19:10:15 UTC (rev 786)
@@ -47,6 +47,7 @@
 import org.picketlink.identity.federation.core.exceptions.ConfigurationException;
 import org.picketlink.identity.federation.core.exceptions.ParsingException;
 import org.picketlink.identity.federation.core.exceptions.ProcessingException;
+import org.picketlink.identity.federation.core.saml.v2.constants.JBossSAMLURIConstants;
 import org.picketlink.identity.federation.core.saml.v2.exceptions.AssertionExpiredException;
 import org.picketlink.identity.federation.core.saml.v2.exceptions.IssuerNotTrustedException;
 import org.picketlink.identity.federation.core.saml.v2.interfaces.SAML2Handler;
@@ -73,21 +74,22 @@
  * @author Anil.Saldhana at redhat.com
  * @since Dec 12, 2008
  */
-public class SPRedirectFormAuthenticator extends BaseFormAuthenticator 
-{ 
+public class SPRedirectFormAuthenticator extends BaseFormAuthenticator
+{
    private static Logger log = Logger.getLogger(SPRedirectFormAuthenticator.class);
-   private boolean trace = log.isTraceEnabled();
-    
+
+   private final boolean trace = log.isTraceEnabled();
+
    private boolean jbossEnv = false;
-   
-   private String logOutPage = GeneralConstants.LOGOUT_PAGE_NAME;
-   
+
+   private final String logOutPage = GeneralConstants.LOGOUT_PAGE_NAME;
+
    public SPRedirectFormAuthenticator()
    {
       super();
-      ServerDetector detector = new ServerDetector(); 
+      ServerDetector detector = new ServerDetector();
       jbossEnv = detector.isJboss();
-   } 
+   }
 
    @Override
    public boolean authenticate(Request request, Response response, LoginConfig loginConfig) throws IOException
@@ -95,38 +97,38 @@
       //Eagerly look for Global LogOut
       String gloStr = request.getParameter(GeneralConstants.GLOBAL_LOGOUT);
       boolean logOutRequest = isNotNull(gloStr) && "true".equalsIgnoreCase(gloStr);
-     
+
       String samlRequest = request.getParameter(GeneralConstants.SAML_REQUEST_KEY);
-      String samlResponse = request.getParameter(GeneralConstants.SAML_RESPONSE_KEY); 
-       
-      Principal principal = request.getUserPrincipal(); 
+      String samlResponse = request.getParameter(GeneralConstants.SAML_RESPONSE_KEY);
 
+      Principal principal = request.getUserPrincipal();
+
       //If we have already authenticated the user and there is no request from IDP or logout from user
-      if(principal != null && !(logOutRequest || isNotNull(samlRequest) || isNotNull(samlResponse) ) )
+      if (principal != null && !(logOutRequest || isNotNull(samlRequest) || isNotNull(samlResponse)))
          return true;
 
       Session session = request.getSessionInternal(true);
       String relayState = request.getParameter(GeneralConstants.RELAY_STATE);
       HTTPContext httpContext = new HTTPContext(request, response, context.getServletContext());
-      
+
       Set<SAML2Handler> handlers = chain.handlers();
-      
+
       //General User Request
-      if(!isNotNull(samlRequest) && !isNotNull(samlResponse))
+      if (!isNotNull(samlRequest) && !isNotNull(samlResponse))
       {
          //Neither saml request nor response from IDP
          //So this is a user request
          SAML2HandlerResponse saml2HandlerResponse = null;
          try
          {
-            ServiceProviderBaseProcessor baseProcessor = new ServiceProviderBaseProcessor(false, serviceURL); 
-            
+            ServiceProviderBaseProcessor baseProcessor = new ServiceProviderBaseProcessor(false, serviceURL);
+
             initializeSAMLProcessor(baseProcessor);
-            
+
             saml2HandlerResponse = baseProcessor.process(httpContext, handlers, chainLock);
-            saml2HandlerResponse.setDestination(identityURL); 
+            saml2HandlerResponse.setDestination(identityURL);
          }
-         catch(ProcessingException pe)
+         catch (ProcessingException pe)
          {
             log.error("Processing Exception:", pe);
             throw new RuntimeException(pe);
@@ -140,57 +142,56 @@
          {
             log.error("Config Exception:", pe);
             throw new RuntimeException(pe);
-         }  
-          
+         }
+
          Document samlResponseDocument = saml2HandlerResponse.getResultingDocument();
          relayState = saml2HandlerResponse.getRelayState();
 
          String destination = saml2HandlerResponse.getDestination();
 
-         if(destination != null && 
-               samlResponseDocument != null)
+         if (destination != null && samlResponseDocument != null)
          {
             try
             {
                String samlMsg = DocumentUtil.getDocumentAsString(samlResponseDocument);
-               if(trace)
+               if (trace)
                   log.trace("SAML Document=" + samlMsg);
 
                boolean areWeSendingRequest = saml2HandlerResponse.getSendRequest();
-               
+
                String base64Request = RedirectBindingUtil.deflateBase64URLEncode(samlMsg.getBytes("UTF-8"));
-               
+
                String destinationQuery = getDestinationQueryString(base64Request, relayState, areWeSendingRequest);
-               
+
                RedirectBindingUtilDestHolder holder = new RedirectBindingUtilDestHolder();
                holder.setDestination(destination).setDestinationQueryString(destinationQuery);
-               
+
                String destinationURL = RedirectBindingUtil.getDestinationURL(holder);
-               
-               if(trace)
+
+               if (trace)
                {
                   log.trace("URL used for sending:" + destinationURL);
                }
 
-               if( saveRestoreRequest )
+               if (saveRestoreRequest)
                {
-                  this.saveRequest(request, session); 
+                  this.saveRequest(request, session);
                }
-               
-               HTTPRedirectUtil.sendRedirectForRequestor(destinationURL, response); 
+
+               HTTPRedirectUtil.sendRedirectForRequestor(destinationURL, response);
                return false;
             }
             catch (Exception e)
             {
-               if(trace)
-                  log.trace("Exception:",e);
+               if (trace)
+                  log.trace("Exception:", e);
                throw new IOException("Server Error");
-            } 
-         } 
+            }
+         }
       }
 
       //See if we got a response from IDP
-      if(isNotNull(samlResponse) )
+      if (isNotNull(samlResponse))
       {
          boolean isValid = false;
          try
@@ -199,35 +200,35 @@
          }
          catch (Exception e)
          {
-            log.error("Exception:",e);
+            log.error("Exception:", e);
             throw new IOException();
          }
-         if(!isValid)
+         if (!isValid)
             throw new IOException("Validity check failed");
-          
+
          try
          {
-            ServiceProviderSAMLResponseProcessor responseProcessor =
-               new ServiceProviderSAMLResponseProcessor(false, serviceURL);
+            ServiceProviderSAMLResponseProcessor responseProcessor = new ServiceProviderSAMLResponseProcessor(false,
+                  serviceURL);
             initializeSAMLProcessor(responseProcessor);
-            
+
             SAML2HandlerResponse saml2HandlerResponse = null;
-            
+
             try
             {
-               saml2HandlerResponse = responseProcessor.process(samlResponse, httpContext, handlers, chainLock);               
+               saml2HandlerResponse = responseProcessor.process(samlResponse, httpContext, handlers, chainLock);
             }
-            catch(ProcessingException pe)
+            catch (ProcessingException pe)
             {
                Throwable te = pe.getCause();
-               if(te instanceof AssertionExpiredException)
+               if (te instanceof AssertionExpiredException)
                {
                   //We need to reissue redirect to IDP
                   ServiceProviderBaseProcessor baseProcessor = new ServiceProviderBaseProcessor(false, serviceURL);
                   initializeSAMLProcessor(baseProcessor);
-                  
+
                   saml2HandlerResponse = baseProcessor.process(httpContext, handlers, chainLock);
-                  saml2HandlerResponse.setDestination(identityURL); 
+                  saml2HandlerResponse.setDestination(identityURL);
                }
                else
                   throw pe;
@@ -236,20 +237,19 @@
             relayState = saml2HandlerResponse.getRelayState();
 
             String destination = saml2HandlerResponse.getDestination();
-  
-            if(destination != null && 
-                  samlResponseDocument != null)
+
+            if (destination != null && samlResponseDocument != null)
             {
-               boolean areWeSendingRequest = saml2HandlerResponse.getSendRequest(); 
+               boolean areWeSendingRequest = saml2HandlerResponse.getSendRequest();
                String samlMsg = DocumentUtil.getDocumentAsString(samlResponseDocument);
 
-               String base64Request = RedirectBindingUtil.deflateBase64URLEncode(samlMsg.getBytes("UTF-8")); 
-               
+               String base64Request = RedirectBindingUtil.deflateBase64URLEncode(samlMsg.getBytes("UTF-8"));
+
                String destinationQuery = getDestinationQueryString(base64Request, relayState, areWeSendingRequest);
-               
+
                RedirectBindingUtilDestHolder holder = new RedirectBindingUtilDestHolder();
-               holder.setDestination(destination).setDestinationQueryString(destinationQuery); 
-               
+               holder.setDestination(destination).setDestinationQueryString(destinationQuery);
+
                String destinationURL = RedirectBindingUtil.getDestinationURL(holder);
 
                HTTPRedirectUtil.sendRedirectForRequestor(destinationURL, response);
@@ -257,32 +257,32 @@
             else
             {
                //See if the session has been invalidated 
-               boolean sessionValidity = session.isValid(); 
-               if(!sessionValidity)
+               boolean sessionValidity = session.isValid();
+               if (!sessionValidity)
                {
                   //we are invalidated.
-                  RequestDispatcher dispatch = context.getServletContext().getRequestDispatcher(this.logOutPage); 
-                  if(dispatch == null)
+                  RequestDispatcher dispatch = context.getServletContext().getRequestDispatcher(this.logOutPage);
+                  if (dispatch == null)
                      log.error("Cannot dispatch to the logout page: no request dispatcher:" + this.logOutPage);
                   else
                      dispatch.forward(request, response);
-                  return false;  
-               }  
+                  return false;
+               }
 
                //We got a response with the principal
                List<String> roles = saml2HandlerResponse.getRoles();
-               if(principal == null)
+               if (principal == null)
                   principal = (Principal) session.getSession().getAttribute(GeneralConstants.PRINCIPAL_ID);
 
                String username = principal.getName();
                String password = ServiceProviderSAMLContext.EMPTY_PASSWORD;
 
                //Map to JBoss specific principal
-               if((new ServerDetector()).isJboss() || jbossEnv)
-               { 
+               if ((new ServerDetector()).isJboss() || jbossEnv)
+               {
                   //Push a context
                   ServiceProviderSAMLContext.push(username, roles);
-                  principal = context.getRealm().authenticate(username, password); 
+                  principal = context.getRealm().authenticate(username, password);
                   ServiceProviderSAMLContext.clear();
                }
                else
@@ -295,138 +295,144 @@
                session.setNote(Constants.SESS_USERNAME_NOTE, username);
                session.setNote(Constants.SESS_PASSWORD_NOTE, password);
                request.setUserPrincipal(principal);
-               
-               if( saveRestoreRequest )
+
+               if (saveRestoreRequest)
                {
-                  this.restoreRequest(request, session); 
+                  this.restoreRequest(request, session);
                }
-               register(request, response, principal, Constants.FORM_METHOD, username, password); 
+               register(request, response, principal, Constants.FORM_METHOD, username, password);
 
-               return true; 
+               return true;
             }
          }
          catch (Exception e)
          {
             e.printStackTrace();
-            if(trace)
+            if (trace)
                log.trace("Server Exception:", e);
-            throw new IOException("Server Exception:"+ e.getLocalizedMessage());
-         }  
-      } 
+            throw new IOException("Server Exception:" + e.getLocalizedMessage());
+         }
+      }
 
       //Handle SAML Requests from IDP
-      if(isNotNull(samlRequest))
+      if (isNotNull(samlRequest))
       {
          //we got a logout request
          try
          {
-            ServiceProviderSAMLRequestProcessor requestProcessor = 
-               new ServiceProviderSAMLRequestProcessor(false, this.serviceURL);
+            ServiceProviderSAMLRequestProcessor requestProcessor = new ServiceProviderSAMLRequestProcessor(false,
+                  this.serviceURL);
             boolean result = requestProcessor.process(samlRequest, httpContext, handlers, chainLock);
 
-            if(result)
+            if (result)
                return result;
          }
          catch (Exception e)
          {
-            if(trace)
+            if (trace)
                log.trace("Server Exception:", e);
             throw new IOException("Server Exception");
-         }   
+         }
 
       }//end if
 
       //fallback
       return super.authenticate(request, response, loginConfig);
-   } 
+   }
 
-   protected String createSAMLRequestMessage(String relayState, Response response) 
-   throws ServletException, ConfigurationException,  IOException, ProcessingException
+   protected String createSAMLRequestMessage(String relayState, Response response) throws ServletException,
+         ConfigurationException, IOException, ProcessingException
    {
       //create a saml request
-      if(this.serviceURL == null)
+      if (this.serviceURL == null)
          throw new ServletException("serviceURL is not configured");
 
       SAML2Request saml2Request = new SAML2Request();
-      
+
       SPUtil spUtil = new SPUtil();
       AuthnRequestType authnRequest = spUtil.createSAMLRequest(serviceURL, identityURL);
-       
+
       ByteArrayOutputStream baos = new ByteArrayOutputStream();
       saml2Request.marshall(authnRequest, baos);
- 
+
       String base64Request = RedirectBindingUtil.deflateBase64URLEncode(baos.toByteArray());
       String destination = authnRequest.getDestination().toASCIIString();
-      
+
       String destinationQueryString = getDestinationQueryString(base64Request, relayState, true);
-      
+
       RedirectBindingUtilDestHolder holder = new RedirectBindingUtilDestHolder();
       holder.setDestinationQueryString(destinationQueryString).setDestination(destination);
-      return RedirectBindingUtil.getDestinationURL(holder); 
+      return RedirectBindingUtil.getDestinationURL(holder);
    }
-   
-   protected String getDestinationQueryString(String urlEncodedRequest, String urlEncodedRelayState,
-         boolean sendRequest)
+
+   @Override
+   protected String getBinding()
    {
-      return RedirectBindingUtil.getDestinationQueryString(urlEncodedRequest, 
-            urlEncodedRelayState, sendRequest); 
+      return JBossSAMLURIConstants.SAML_HTTP_REDIRECT_BINDING.get();
    }
-   
+
+   protected String getDestinationQueryString(String urlEncodedRequest, String urlEncodedRelayState, boolean sendRequest)
+   {
+      return RedirectBindingUtil.getDestinationQueryString(urlEncodedRequest, urlEncodedRelayState, sendRequest);
+   }
+
    protected void isTrusted(String issuer) throws IssuerNotTrustedException
    {
       try
       {
          String issuerDomain = ValveUtil.getDomain(issuer);
-         TrustType spTrust =  spConfiguration.getTrust();
-         if(spTrust != null)
+         TrustType spTrust = spConfiguration.getTrust();
+         if (spTrust != null)
          {
             String domainsTrusted = spTrust.getDomains();
-            if(trace) 
-               log.trace("Domains that SP trusts="+domainsTrusted + " and issuer domain="+issuerDomain);
-            if(domainsTrusted.indexOf(issuerDomain) < 0)
+            if (trace)
+               log.trace("Domains that SP trusts=" + domainsTrusted + " and issuer domain=" + issuerDomain);
+            if (domainsTrusted.indexOf(issuerDomain) < 0)
             {
                //Let us do string parts checking
                StringTokenizer st = new StringTokenizer(domainsTrusted, ",");
-               while(st != null && st.hasMoreTokens())
+               while (st != null && st.hasMoreTokens())
                {
                   String uriBit = st.nextToken();
-                  if(trace) log.trace("Matching uri bit="+ uriBit);
-                  if(issuerDomain.indexOf(uriBit) > 0)
+                  if (trace)
+                     log.trace("Matching uri bit=" + uriBit);
+                  if (issuerDomain.indexOf(uriBit) > 0)
                   {
-                     if(trace) log.trace("Matched " + uriBit + " trust for " + issuerDomain );
+                     if (trace)
+                        log.trace("Matched " + uriBit + " trust for " + issuerDomain);
                      return;
-                  } 
-               } 
+                  }
+               }
                throw new IssuerNotTrustedException(issuer);
-            } 
-         } 
+            }
+         }
       }
       catch (Exception e)
       {
-         throw new IssuerNotTrustedException(e.getLocalizedMessage(),e);
+         throw new IssuerNotTrustedException(e.getLocalizedMessage(), e);
       }
    }
-   
+
    /**
     * Initialize the {@code ServiceProviderBaseProcessor}
     * @param processor
     */
    protected void initializeSAMLProcessor(ServiceProviderBaseProcessor processor)
-   {  
-      if( issuerID != null )
-         processor.setIssuer( issuerID );
-      
+   {
+      if (issuerID != null)
+         processor.setIssuer(issuerID);
+
       processor.setConfiguration(spConfiguration);
    }
-   
+
    /**
     * Subclasses should provide the implementation
     * @param responseType ResponseType that contains the encrypted assertion
     * @return response type with the decrypted assertion
     */
-   protected ResponseType decryptAssertion(ResponseType responseType) 
-   throws IOException, GeneralSecurityException, ConfigurationException, ParsingException
+   protected ResponseType decryptAssertion(ResponseType responseType) throws IOException, GeneralSecurityException,
+         ConfigurationException, ParsingException
    {
       throw new RuntimeException("This authenticator does not handle encryption");
-   } 
+   }
 }
\ No newline at end of file

Added: federation/trunk/picketlink-bindings/src/test/java/org/picketlink/test/identity/federation/bindings/authenticators/SPPostFormAuthenticatorUnitTestCase.java
===================================================================
--- federation/trunk/picketlink-bindings/src/test/java/org/picketlink/test/identity/federation/bindings/authenticators/SPPostFormAuthenticatorUnitTestCase.java	                        (rev 0)
+++ federation/trunk/picketlink-bindings/src/test/java/org/picketlink/test/identity/federation/bindings/authenticators/SPPostFormAuthenticatorUnitTestCase.java	2011-03-01 19:10:15 UTC (rev 786)
@@ -0,0 +1,70 @@
+/*
+ * 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.picketlink.test.identity.federation.bindings.authenticators;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+import java.net.URL;
+import java.security.cert.X509Certificate;
+
+import org.junit.Test;
+import org.picketlink.identity.federation.bindings.tomcat.sp.SPPostFormAuthenticator;
+import org.picketlink.test.identity.federation.bindings.mock.MockCatalinaContext;
+import org.picketlink.test.identity.federation.bindings.mock.MockCatalinaContextClassLoader;
+
+/**
+ * Unit test the {@link SPPostFormAuthenticator}
+ * @author Anil.Saldhana at redhat.com
+ * @since Mar 1, 2011
+ */
+public class SPPostFormAuthenticatorUnitTestCase
+{
+   @Test
+   public void testIDPMetadataFile() throws Exception
+   {
+      MockCatalinaContext ctx = new MockCatalinaContext();
+      SPPostFormAuthenticator auth = new SPPostFormAuthenticator();
+      auth.setContainer(ctx);
+
+      ClassLoader tccl = Thread.currentThread().getContextClassLoader();
+      URL configURL = tccl.getResource("config/test-idp-metadata-file-config.xml");
+      URL[] urls = new URL[]
+      {configURL};
+      MockCatalinaContextClassLoader tcl = new MockCatalinaContextClassLoader(urls);
+      tcl.associate("/WEB-INF/picketlink-idfed.xml", configURL.openStream());
+      tcl.associate("/WEB-INF/picketlink-handlers.xml",
+            tccl.getResourceAsStream("saml2/post/sp/employee/WEB-INF/picketlink-handlers.xml"));
+      tcl.associate("/WEB-INF/testshib.org.idp-metadata.xml",
+            tccl.getResourceAsStream("metadata/testshib.org.idp-metadata.xml"));
+      tcl.setProfile("DUMMY");
+      tcl.setDelegate(tccl);
+
+      Thread.currentThread().setContextClassLoader(tcl);
+      auth.testStart();
+      assertEquals("https://idp.testshib.org/idp/profile/SAML2/POST/SSO", auth.getIdentityURL());
+      X509Certificate idpCert = auth.getIdpCertificate();
+      assertNotNull(idpCert);
+      assertEquals("CN=idp.testshib.org, O=TestShib, L=Pittsburgh, ST=Pennsylvania, C=US", idpCert.getIssuerDN()
+            .getName());
+   }
+}
\ No newline at end of file

Modified: federation/trunk/picketlink-bindings/src/test/java/org/picketlink/test/identity/federation/bindings/mock/MockCatalinaContextClassLoader.java
===================================================================
--- federation/trunk/picketlink-bindings/src/test/java/org/picketlink/test/identity/federation/bindings/mock/MockCatalinaContextClassLoader.java	2011-02-28 21:22:22 UTC (rev 785)
+++ federation/trunk/picketlink-bindings/src/test/java/org/picketlink/test/identity/federation/bindings/mock/MockCatalinaContextClassLoader.java	2011-03-01 19:10:15 UTC (rev 786)
@@ -24,6 +24,8 @@
 import java.io.InputStream;
 import java.net.URL;
 import java.net.URLClassLoader;
+import java.util.HashMap;
+import java.util.Map;
 
 /**
  * Mock TCL
@@ -31,33 +33,43 @@
  * @since Oct 7, 2009
  */
 public class MockCatalinaContextClassLoader extends URLClassLoader
-{ 
+{
    private String profile;
-   
+
    private ClassLoader delegate;
 
+   private final Map<String, InputStream> streams = new HashMap<String, InputStream>();
+
    public MockCatalinaContextClassLoader(URL[] urls)
    {
-      super(urls); 
+      super(urls);
    }
 
    public void setDelegate(ClassLoader tcl)
    {
       this.delegate = tcl;
    }
-   
+
    public void setProfile(String profile)
    {
       this.profile = profile;
    }
 
+   public void associate(String name, InputStream is)
+   {
+      this.streams.put(name, is);
+   }
+
    @Override
    public InputStream getResourceAsStream(String name)
    {
-      if(profile == null)
-         throw new RuntimeException("null profile");
+      if (streams.containsKey(name))
+         return streams.get(name);
+
+      if (profile == null)
+         throw new RuntimeException("null profile when seeking resource:" + name);
       InputStream is = delegate.getResourceAsStream(profile + "/" + name);
-      if( is == null )
+      if (is == null)
          is = super.getResourceAsStream(name);
       return is;
    }

Added: federation/trunk/picketlink-bindings/src/test/resources/config/test-idp-metadata-file-config.xml
===================================================================
--- federation/trunk/picketlink-bindings/src/test/resources/config/test-idp-metadata-file-config.xml	                        (rev 0)
+++ federation/trunk/picketlink-bindings/src/test/resources/config/test-idp-metadata-file-config.xml	2011-03-01 19:10:15 UTC (rev 786)
@@ -0,0 +1,6 @@
+<PicketLinkSP xmlns="urn:picketlink:identity-federation:config:2.0" 
+  AttributeManager="org.picketlink.identity.federation.core.impl.EmptyAttributeManager"> 
+<IDPMetadataFile>/WEB-INF/testshib.org.idp-metadata.xml</IDPMetadataFile>
+<ServiceURL>http://localhost:8080/sales/</ServiceURL>  
+
+</PicketLinkSP>
\ No newline at end of file

Added: federation/trunk/picketlink-bindings/src/test/resources/metadata/testshib.org.idp-metadata.xml
===================================================================
--- federation/trunk/picketlink-bindings/src/test/resources/metadata/testshib.org.idp-metadata.xml	                        (rev 0)
+++ federation/trunk/picketlink-bindings/src/test/resources/metadata/testshib.org.idp-metadata.xml	2011-03-01 19:10:15 UTC (rev 786)
@@ -0,0 +1,233 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<EntitiesDescriptor Name="urn:mace:shibboleth:testshib:two"
+	xmlns:shibmd="urn:mace:shibboleth:metadata:1.0" xmlns="urn:oasis:names:tc:SAML:2.0:metadata"
+	xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+	<EntityDescriptor entityID="https://idp.testshib.org/idp/shibboleth">
+		<IDPSSODescriptor
+			protocolSupportEnumeration="urn:oasis:names:tc:SAML:1.1:protocol urn:mace:shibboleth:1.0 urn:oasis:names:tc:SAML:2.0:protocol">
+			<Extensions>
+				<shibmd:Scope regexp="false">testshib.org</shibmd:Scope>
+			</Extensions>
+			<KeyDescriptor>
+				<ds:KeyInfo>
+					<ds:X509Data>
+						<ds:X509Certificate>MIIEDjCCAvagAwIBAgIBADANBgkqhkiG9w0BAQUFADBnMQswCQYDVQQGEwJVUzEV
+MBMGA1UECBMMUGVubnN5bHZhbmlhMRMwEQYDVQQHEwpQaXR0c2J1cmdoMREwDwYD
+VQQKEwhUZXN0U2hpYjEZMBcGA1UEAxMQaWRwLnRlc3RzaGliLm9yZzAeFw0wNjA4
+MzAyMTEyMjVaFw0xNjA4MjcyMTEyMjVaMGcxCzAJBgNVBAYTAlVTMRUwEwYDVQQI
+EwxQZW5uc3lsdmFuaWExEzARBgNVBAcTClBpdHRzYnVyZ2gxETAPBgNVBAoTCFRl
+c3RTaGliMRkwFwYDVQQDExBpZHAudGVzdHNoaWIub3JnMIIBIjANBgkqhkiG9w0B
+AQEFAAOCAQ8AMIIBCgKCAQEArYkCGuTmJp9eAOSGHwRJo1SNatB5ZOKqDM9ysg7C
+yVTDClcpu93gSP10nH4gkCZOlnESNgttg0r+MqL8tfJC6ybddEFB3YBo8PZajKSe
+3OQ01Ow3yT4I+Wdg1tsTpSge9gEz7SrC07EkYmHuPtd71CHiUaCWDv+xVfUQX0aT
+NPFmDixzUjoYzbGDrtAyCqA8f9CN2txIfJnpHE6q6CmKcoLADS4UrNPlhHSzd614
+kR/JYiks0K4kbRqCQF0Dv0P5Di+rEfefC6glV8ysC8dB5/9nb0yh/ojRuJGmgMWH
+gWk6h0ihjihqiu4jACovUZ7vVOCgSE5Ipn7OIwqd93zp2wIDAQABo4HEMIHBMB0G
+A1UdDgQWBBSsBQ869nh83KqZr5jArr4/7b+QazCBkQYDVR0jBIGJMIGGgBSsBQ86
+9nh83KqZr5jArr4/7b+Qa6FrpGkwZzELMAkGA1UEBhMCVVMxFTATBgNVBAgTDFBl
+bm5zeWx2YW5pYTETMBEGA1UEBxMKUGl0dHNidXJnaDERMA8GA1UEChMIVGVzdFNo
+aWIxGTAXBgNVBAMTEGlkcC50ZXN0c2hpYi5vcmeCAQAwDAYDVR0TBAUwAwEB/zAN
+BgkqhkiG9w0BAQUFAAOCAQEAjR29PhrCbk8qLN5MFfSVk98t3CT9jHZoYxd8QMRL
+I4j7iYQxXiGJTT1FXs1nd4Rha9un+LqTfeMMYqISdDDI6tv8iNpkOAvZZUosVkUo
+93pv1T0RPz35hcHHYq2yee59HJOco2bFlcsH8JBXRSRrJ3Q7Eut+z9uo80JdGNJ4
+/SJy5UorZ8KazGj16lfJhOBXldgrhppQBb0Nq6HKHguqmwRfJ+WkxemZXzhediAj
+Geka8nz8JjwxpUjAiSWYKLtJhGEaTqCYxCCX2Dw+dOTqUzHOZ7WKv4JXPK5G/Uhr
+8K/qhmFT2nIQi538n6rVYLeWj8Bbnl+ev0peYzxFyF5sQA==</ds:X509Certificate>
+					</ds:X509Data>
+				</ds:KeyInfo>
+			</KeyDescriptor>
+			<ArtifactResolutionService
+				Binding="urn:oasis:names:tc:SAML:1.0:bindings:SOAP-binding"
+				Location="https://idp.testshib.org:8443/idp/profile/SAML1/SOAP/ArtifactResolution"
+				index="1" />
+			<ArtifactResolutionService
+				Binding="urn:oasis:names:tc:SAML:2.0:bindings:SOAP"
+				Location="https://idp.testshib.org:8443/idp/profile/SAML2/SOAP/ArtifactResolution"
+				index="2" />
+			<NameIDFormat>urn:mace:shibboleth:1.0:nameIdentifier</NameIDFormat>
+			<NameIDFormat>urn:oasis:names:tc:SAML:2.0:nameid-format:transient
+			</NameIDFormat>
+			<SingleSignOnService Binding="urn:mace:shibboleth:1.0:profiles:AuthnRequest"
+				Location="https://idp.testshib.org/idp/profile/Shibboleth/SSO" />
+			<SingleSignOnService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"
+				Location="https://idp.testshib.org/idp/profile/SAML2/POST/SSO" />
+			<SingleSignOnService
+				Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect"
+				Location="https://idp.testshib.org/idp/profile/SAML2/Redirect/SSO" />
+		</IDPSSODescriptor>
+		<AttributeAuthorityDescriptor
+			protocolSupportEnumeration="urn:oasis:names:tc:SAML:1.1:protocol urn:oasis:names:tc:SAML:2.0:protocol">
+			<KeyDescriptor>
+				<ds:KeyInfo>
+					<ds:X509Data>
+						<ds:X509Certificate>MIIEKjCCAxKgAwIBAgIJAIgUuHL4QvkYMA0GCSqGSIb3DQEBBQUAMGsxCzAJBgNV
+							BAYTAkdCMRIwEAYDVQQIEwlCZXJrc2hpcmUxEDAOBgNVBAcTB05ld2J1cnkxFzAV
+							BgNVBAoTDk15IENvbXBhbnkgTHRkMR0wGwYDVQQDExRpZHAudHdvLnRlc3RzaGli
+							Lm9yZzAeFw0wNzEyMTcxOTE4NDFaFw0xNzEyMTQxOTE4NDFaMGsxCzAJBgNVBAYT
+							AkdCMRIwEAYDVQQIEwlCZXJrc2hpcmUxEDAOBgNVBAcTB05ld2J1cnkxFzAVBgNV
+							BAoTDk15IENvbXBhbnkgTHRkMR0wGwYDVQQDExRpZHAudHdvLnRlc3RzaGliLm9y
+							ZzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAK2JAhrk5iafXgDkhh8E
+							SaNUjWrQeWTiqgzPcrIOwslUwwpXKbvd4Ej9dJx+IJAmTpZxEjYLbYNK/jKi/LXy
+							Qusm3XRBQd2AaPD2WoykntzkNNTsN8k+CPlnYNbbE6UoHvYBM+0qwtOxJGJh7j7X
+							e9Qh4lGglg7/sVX1EF9GkzTxZg4sc1I6GM2xg67QMgqgPH/QjdrcSHyZ6RxOqugp
+							inKCwA0uFKzT5YR0s3eteJEfyWIpLNCuJG0agkBdA79D+Q4vqxH3nwuoJVfMrAvH
+							Qef/Z29Mof6I0biRpoDFh4FpOodIoY4oaoruIwAqL1Ge71TgoEhOSKZ+ziMKnfd8
+							6dsCAwEAAaOB0DCBzTAdBgNVHQ4EFgQUrAUPOvZ4fNyqma+YwK6+P+2/kGswgZ0G
+							A1UdIwSBlTCBkoAUrAUPOvZ4fNyqma+YwK6+P+2/kGuhb6RtMGsxCzAJBgNVBAYT
+							AkdCMRIwEAYDVQQIEwlCZXJrc2hpcmUxEDAOBgNVBAcTB05ld2J1cnkxFzAVBgNV
+							BAoTDk15IENvbXBhbnkgTHRkMR0wGwYDVQQDExRpZHAudHdvLnRlc3RzaGliLm9y
+							Z4IJAIgUuHL4QvkYMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADggEBAEti
+							KJki8WO2wGhpJc3oIAF7V0CYBR3303S37iqSodabyN/2nxFXTqd+ZSAdfe+14E/G
+							dyC9Dtbq4VL2lF0fbaNarCzfhMD7DExSANFkOPFk/lz54ccFdfIRHRVeLHvEtGAI
+							UTK+qEqaEl1vjZVKmvNSdDet06EQ+MGZf1MnW6jid4AMrSdboDHFW34qet+tr9gf
+							5k6bZx6oIiOILgXWHk7hK1ZuxK5w0bpbktNIfO35HoQSPBx6u6wuxt4yN/m6QLiq
+							nGEzsHlzsPFv1Iw+ccdALcqR0zor7GEJrKmp4Gcb/zH3oy1rQNZHUlz29emJhS/1
+							q1og9SGCUU2yRL1tC+Y=</ds:X509Certificate>
+					</ds:X509Data>
+				</ds:KeyInfo>
+			</KeyDescriptor>
+			<KeyDescriptor>
+				<ds:KeyInfo>
+					<ds:X509Data>
+						<ds:X509Certificate>MIIEDjCCAvagAwIBAgIBADANBgkqhkiG9w0BAQUFADBnMQswCQYDVQQGEwJVUzEV
+							MBMGA1UECBMMUGVubnN5bHZhbmlhMRMwEQYDVQQHEwpQaXR0c2J1cmdoMREwDwYD
+							VQQKEwhUZXN0U2hpYjEZMBcGA1UEAxMQaWRwLnRlc3RzaGliLm9yZzAeFw0wNjA4
+							MzAyMTEyMjVaFw0xNjA4MjcyMTEyMjVaMGcxCzAJBgNVBAYTAlVTMRUwEwYDVQQI
+							EwxQZW5uc3lsdmFuaWExEzARBgNVBAcTClBpdHRzYnVyZ2gxETAPBgNVBAoTCFRl
+							c3RTaGliMRkwFwYDVQQDExBpZHAudGVzdHNoaWIub3JnMIIBIjANBgkqhkiG9w0B
+							AQEFAAOCAQ8AMIIBCgKCAQEArYkCGuTmJp9eAOSGHwRJo1SNatB5ZOKqDM9ysg7C
+							yVTDClcpu93gSP10nH4gkCZOlnESNgttg0r+MqL8tfJC6ybddEFB3YBo8PZajKSe
+							3OQ01Ow3yT4I+Wdg1tsTpSge9gEz7SrC07EkYmHuPtd71CHiUaCWDv+xVfUQX0aT
+							NPFmDixzUjoYzbGDrtAyCqA8f9CN2txIfJnpHE6q6CmKcoLADS4UrNPlhHSzd614
+							kR/JYiks0K4kbRqCQF0Dv0P5Di+rEfefC6glV8ysC8dB5/9nb0yh/ojRuJGmgMWH
+							gWk6h0ihjihqiu4jACovUZ7vVOCgSE5Ipn7OIwqd93zp2wIDAQABo4HEMIHBMB0G
+							A1UdDgQWBBSsBQ869nh83KqZr5jArr4/7b+QazCBkQYDVR0jBIGJMIGGgBSsBQ86
+							9nh83KqZr5jArr4/7b+Qa6FrpGkwZzELMAkGA1UEBhMCVVMxFTATBgNVBAgTDFBl
+							bm5zeWx2YW5pYTETMBEGA1UEBxMKUGl0dHNidXJnaDERMA8GA1UEChMIVGVzdFNo
+							aWIxGTAXBgNVBAMTEGlkcC50ZXN0c2hpYi5vcmeCAQAwDAYDVR0TBAUwAwEB/zAN
+							BgkqhkiG9w0BAQUFAAOCAQEAjR29PhrCbk8qLN5MFfSVk98t3CT9jHZoYxd8QMRL
+							I4j7iYQxXiGJTT1FXs1nd4Rha9un+LqTfeMMYqISdDDI6tv8iNpkOAvZZUosVkUo
+							93pv1T0RPz35hcHHYq2yee59HJOco2bFlcsH8JBXRSRrJ3Q7Eut+z9uo80JdGNJ4
+							/SJy5UorZ8KazGj16lfJhOBXldgrhppQBb0Nq6HKHguqmwRfJ+WkxemZXzhediAj
+							Geka8nz8JjwxpUjAiSWYKLtJhGEaTqCYxCCX2Dw+dOTqUzHOZ7WKv4JXPK5G/Uhr
+							8K/qhmFT2nIQi538n6rVYLeWj8Bbnl+ev0peYzxFyF5sQA==
+						</ds:X509Certificate>
+					</ds:X509Data>
+				</ds:KeyInfo>
+			</KeyDescriptor>
+			<AttributeService Binding="urn:oasis:names:tc:SAML:1.0:bindings:SOAP-binding"
+				Location="https://idp.testshib.org:8443/idp/profile/SAML1/SOAP/AttributeQuery" />
+			<AttributeService Binding="urn:oasis:names:tc:SAML:2.0:bindings:SOAP"
+				Location="https://idp.testshib.org:8443/idp/profile/SAML2/SOAP/AttributeQuery" />
+			<NameIDFormat>urn:mace:shibboleth:1.0:nameIdentifier</NameIDFormat>
+			<NameIDFormat>urn:oasis:names:tc:SAML:2.0:nameid-format:transient
+			</NameIDFormat>
+		</AttributeAuthorityDescriptor>
+		<Organization>
+			<OrganizationName xmlns="urn:oasis:names:tc:SAML:2.0:metadata"
+				xml:lang="en">TestShib Two Identity Provider</OrganizationName>
+			<OrganizationDisplayName xmlns="urn:oasis:names:tc:SAML:2.0:metadata"
+				xml:lang="en">TestShib Two</OrganizationDisplayName>
+			<OrganizationURL xmlns="urn:oasis:names:tc:SAML:2.0:metadata"
+				xml:lang="en">http://www.testshib.org/testshib-two/</OrganizationURL>
+		</Organization>
+		<ContactPerson contactType="technical">
+			<GivenName>Nate</GivenName>
+			<SurName>Klingenstein</SurName>
+			<EmailAddress>ndk at internet2.edu</EmailAddress>
+		</ContactPerson>
+	</EntityDescriptor>
+	<EntityDescriptor entityID="https://sp.testshib.org/shibboleth-sp">
+		<SPSSODescriptor
+			protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol urn:oasis:names:tc:SAML:1.1:protocol http://schemas.xmlsoap.org/ws/2003/07/secext">
+			<Extensions>
+				<idpdisc:DiscoveryResponse
+					Binding="urn:oasis:names:tc:SAML:profiles:SSO:idp-discovery-protocol"
+					Location="https://sp.testshib.org/Shibboleth.sso/DS" index="1"
+					xmlns:idpdisc="urn:oasis:names:tc:SAML:profiles:SSO:idp-discovery-protocol" />
+			</Extensions>
+			<KeyDescriptor>
+				<ds:KeyInfo>
+					<ds:X509Data>
+						<ds:X509Certificate>MIIEPjCCAyagAwIBAgIBADANBgkqhkiG9w0BAQUFADB3MQswCQYDVQQGEwJVUzEV
+							MBMGA1UECBMMUGVubnN5bHZhbmlhMRMwEQYDVQQHEwpQaXR0c2J1cmdoMSIwIAYD
+							VQQKExlUZXN0U2hpYiBTZXJ2aWNlIFByb3ZpZGVyMRgwFgYDVQQDEw9zcC50ZXN0
+							c2hpYi5vcmcwHhcNMDYwODMwMjEyNDM5WhcNMTYwODI3MjEyNDM5WjB3MQswCQYD
+							VQQGEwJVUzEVMBMGA1UECBMMUGVubnN5bHZhbmlhMRMwEQYDVQQHEwpQaXR0c2J1
+							cmdoMSIwIAYDVQQKExlUZXN0U2hpYiBTZXJ2aWNlIFByb3ZpZGVyMRgwFgYDVQQD
+							Ew9zcC50ZXN0c2hpYi5vcmcwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIB
+							AQDJyR6ZP6MXkQ9z6RRziT0AuCabDd3x1m7nLO9ZRPbr0v1LsU+nnC363jO8nGEq
+							sqkgiZ/bSsO5lvjEt4ehff57ERio2Qk9cYw8XCgmYccVXKH9M+QVO1MQwErNobWb
+							AjiVkuhWcwLWQwTDBowfKXI87SA7KR7sFUymNx5z1aoRvk3GM++tiPY6u4shy8c7
+							vpWbVfisfTfvef/y+galxjPUQYHmegu7vCbjYP3On0V7/Ivzr+r2aPhp8egxt00Q
+							XpilNai12LBYV3Nv/lMsUzBeB7+CdXRVjZOHGuQ8mGqEbsj8MBXvcxIKbcpeK5Zi
+							JCVXPfarzuriM1G5y5QkKW+LAgMBAAGjgdQwgdEwHQYDVR0OBBYEFKB6wPDxwYrY
+							StNjU5P4b4AjBVQVMIGhBgNVHSMEgZkwgZaAFKB6wPDxwYrYStNjU5P4b4AjBVQV
+							oXukeTB3MQswCQYDVQQGEwJVUzEVMBMGA1UECBMMUGVubnN5bHZhbmlhMRMwEQYD
+							VQQHEwpQaXR0c2J1cmdoMSIwIAYDVQQKExlUZXN0U2hpYiBTZXJ2aWNlIFByb3Zp
+							ZGVyMRgwFgYDVQQDEw9zcC50ZXN0c2hpYi5vcmeCAQAwDAYDVR0TBAUwAwEB/zAN
+							BgkqhkiG9w0BAQUFAAOCAQEAc06Kgt7ZP6g2TIZgMbFxg6vKwvDL0+2dzF11Onpl
+							5sbtkPaNIcj24lQ4vajCrrGKdzHXo9m54BzrdRJ7xDYtw0dbu37l1IZVmiZr12eE
+							Iay/5YMU+aWP1z70h867ZQ7/7Y4HW345rdiS6EW663oH732wSYNt9kr7/0Uer3KD
+							9CuPuOidBacospDaFyfsaJruE99Kd6Eu/w5KLAGG+m0iqENCziDGzVA47TngKz2v
+							PVA+aokoOyoz3b53qeti77ijatSEoKjxheBWpO+eoJeGq/e49Um3M2ogIX/JAlMa
+							Inh+vYSYngQB2sx9LGkR9KHaMKNIGCDehk93Xla4pWJx1w==
+						</ds:X509Certificate>
+					</ds:X509Data>
+				</ds:KeyInfo>
+			</KeyDescriptor>
+			<SingleLogoutService Binding="urn:oasis:names:tc:SAML:2.0:bindings:SOAP"
+				Location="https://sp.testshib.org/Shibboleth.sso/SLO/SOAP" />
+			<SingleLogoutService
+				Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect"
+				Location="https://sp.testshib.org/Shibboleth.sso/SLO/Redirect" />
+			<SingleLogoutService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"
+				Location="https://sp.testshib.org/Shibboleth.sso/SLO/POST" />
+			<SingleLogoutService
+				Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Artifact"
+				Location="https://sp.testshib.org/Shibboleth.sso/SLO/Artifact" />
+			<NameIDFormat>urn:oasis:names:tc:SAML:2.0:nameid-format:transient
+			</NameIDFormat>
+			<NameIDFormat>urn:mace:shibboleth:1.0:nameIdentifier</NameIDFormat>
+			<AssertionConsumerService
+				Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" Location="https://sp.testshib.org/Shibboleth.sso/SAML2/POST"
+				index="1" isDefault="true" />
+			<AssertionConsumerService
+				Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST-SimpleSign"
+				Location="https://sp.testshib.org/Shibboleth.sso/SAML2/POST-SimpleSign"
+				index="2" />
+			<AssertionConsumerService
+				Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Artifact"
+				Location="https://sp.testshib.org/Shibboleth.sso/SAML2/Artifact"
+				index="3" />
+			<AssertionConsumerService
+				Binding="urn:oasis:names:tc:SAML:1.0:profiles:browser-post"
+				Location="https://sp.testshib.org/Shibboleth.sso/SAML/POST" index="4" />
+			<AssertionConsumerService
+				Binding="urn:oasis:names:tc:SAML:1.0:profiles:artifact-01" Location="https://sp.testshib.org/Shibboleth.sso/SAML/Artifact"
+				index="5" />
+			<AssertionConsumerService
+				Binding="http://schemas.xmlsoap.org/ws/2003/07/secext" Location="https://sp.testshib.org/Shibboleth.sso/ADFS"
+				index="6" />
+			<AssertionConsumerService
+				Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" Location="https://www.testshib.org/Shibboleth.sso/SAML2/POST"
+				index="7" />
+			<AssertionConsumerService
+				Binding="urn:oasis:names:tc:SAML:1.0:profiles:browser-post"
+				Location="https://www.testshib.org/Shibboleth.sso/SAML/POST" index="8" />
+		</SPSSODescriptor>
+		<Organization>
+			<OrganizationName xmlns="urn:oasis:names:tc:SAML:2.0:metadata"
+				xml:lang="en">TestShib Two Service Provider</OrganizationName>
+			<OrganizationDisplayName xmlns="urn:oasis:names:tc:SAML:2.0:metadata"
+				xml:lang="en">TestShib Two</OrganizationDisplayName>
+			<OrganizationURL xmlns="urn:oasis:names:tc:SAML:2.0:metadata"
+				xml:lang="en">http://www.testshib.org/testshib-two/</OrganizationURL>
+		</Organization>
+		<ContactPerson contactType="technical">
+			<GivenName>Nate</GivenName>
+			<SurName>Klingenstein</SurName>
+			<EmailAddress>ndk at internet2.edu</EmailAddress>
+		</ContactPerson>
+	</EntityDescriptor>
+</EntitiesDescriptor>
\ No newline at end of file

Modified: federation/trunk/picketlink-fed-core/src/main/java/org/picketlink/identity/federation/core/config/SPType.java
===================================================================
--- federation/trunk/picketlink-fed-core/src/main/java/org/picketlink/identity/federation/core/config/SPType.java	2011-02-28 21:22:22 UTC (rev 785)
+++ federation/trunk/picketlink-fed-core/src/main/java/org/picketlink/identity/federation/core/config/SPType.java	2011-03-01 19:10:15 UTC (rev 786)
@@ -47,6 +47,8 @@
 
    protected String serviceURL;
 
+   protected String idpMetadataFile;
+
    /**
     * Gets the value of the serviceURL property.
     * 
@@ -73,4 +75,21 @@
       this.serviceURL = value;
    }
 
-}
+   /**
+    * Get the IDP metadata file String
+    * @return
+    */
+   public String getIdpMetadataFile()
+   {
+      return idpMetadataFile;
+   }
+
+   /**
+    * Set the IDP Metadata file String
+    * @param idpMetadataFile
+    */
+   public void setIdpMetadataFile(String idpMetadataFile)
+   {
+      this.idpMetadataFile = idpMetadataFile;
+   }
+}
\ No newline at end of file

Modified: federation/trunk/picketlink-fed-core/src/main/java/org/picketlink/identity/federation/core/parsers/config/SAMLConfigParser.java
===================================================================
--- federation/trunk/picketlink-fed-core/src/main/java/org/picketlink/identity/federation/core/parsers/config/SAMLConfigParser.java	2011-02-28 21:22:22 UTC (rev 785)
+++ federation/trunk/picketlink-fed-core/src/main/java/org/picketlink/identity/federation/core/parsers/config/SAMLConfigParser.java	2011-03-01 19:10:15 UTC (rev 786)
@@ -49,45 +49,58 @@
 public class SAMLConfigParser extends AbstractParser
 {
    public static final String IDP = "PicketLinkIDP";
+
    public static final String SP = "PicketLinkSP";
 
    public static final String IDENTITY_URL = "IdentityURL";
+
    public static final String SERVICE_URL = "ServiceURL";
 
+   public static final String IDP_METADATA_FILE = "IDPMetadataFile";
+
    public static final String TRUST = "Trust";
 
    public static final String DOMAINS = "Domains";
 
    public static final String KEY_PROVIDER = "KeyProvider";
+
    public static final String META_PROVIDER = "MetaDataProvider";
-   public static final String CLASS_NAME = "ClassName"; 
-   public static final String CLASS = "class"; 
+
+   public static final String CLASS_NAME = "ClassName";
+
+   public static final String CLASS = "class";
+
    public static final String AUTH = "Auth";
+
    public static final String KEY = "Key";
+
    public static final String VALUE = "Value";
+
    public static final String VALIDATING_ALIAS = "ValidatingAlias";
+
    public static final String ASSERTION_VALIDITY = "AssertionValidity";
 
    public static final String ROLE_GENERATOR = "RoleGenerator";
 
    public static final String ENCRYPT = "Encrypt";
 
+   public static final String ATTRIBUTE_MANAGER = "AttributeManager";
 
-   public static final String ATTRIBUTE_MANAGER = "AttributeManager";
    public static final String CANONICALIZATION_METHOD = "CanonicalizationMethod";
 
    public static final String HANDLERS = "Handlers";
+
    public static final String HANDLER = "Handler";
+
    public static final String OPTION = "Option";
 
-
    public Object parse(XMLEventReader xmlEventReader) throws ParsingException
    {
-      StartElement startElement = StaxParserUtil.peekNextStartElement( xmlEventReader );
+      StartElement startElement = StaxParserUtil.peekNextStartElement(xmlEventReader);
 
-      if( StaxParserUtil.getStartElementName(startElement).equals( IDP ))
-         return parseIDPConfiguration( xmlEventReader );
-      if( StaxParserUtil.getStartElementName(startElement).equals( SP ))
+      if (StaxParserUtil.getStartElementName(startElement).equals(IDP))
+         return parseIDPConfiguration(xmlEventReader);
+      if (StaxParserUtil.getStartElementName(startElement).equals(SP))
          return parseSPConfiguration(xmlEventReader);
 
       return parseHandlers(xmlEventReader);
@@ -98,13 +111,13 @@
       return false;
    }
 
-   protected Handlers parseHandlers( XMLEventReader xmlEventReader ) throws ParsingException
+   protected Handlers parseHandlers(XMLEventReader xmlEventReader) throws ParsingException
    {
       Handlers handlers = new Handlers();
-      
-      StartElement startElement = StaxParserUtil.getNextStartElement( xmlEventReader );
-      StaxParserUtil.validate( startElement, HANDLERS );  
 
+      StartElement startElement = StaxParserUtil.getNextStartElement(xmlEventReader);
+      StaxParserUtil.validate(startElement, HANDLERS);
+
       while (xmlEventReader.hasNext())
       {
          XMLEvent xmlEvent = StaxParserUtil.peek(xmlEventReader);
@@ -114,59 +127,58 @@
          {
             EndElement endElement = (EndElement) StaxParserUtil.getNextEvent(xmlEventReader);
             String endElementName = StaxParserUtil.getEndElementName(endElement);
-            if (endElementName.equals( HANDLERS ))
+            if (endElementName.equals(HANDLERS))
                break;
             else
                throw new RuntimeException("Unknown End Element:" + endElementName);
          }
 
          startElement = StaxParserUtil.getNextStartElement(xmlEventReader);
-         if ( startElement == null)
+         if (startElement == null)
             break;
-         String elementName = StaxParserUtil.getStartElementName( startElement );
-         if( elementName.equals( HANDLER ))
+         String elementName = StaxParserUtil.getStartElementName(startElement);
+         if (elementName.equals(HANDLER))
          {
-            Handler handler = parseHandler(xmlEventReader, startElement); 
+            Handler handler = parseHandler(xmlEventReader, startElement);
             handlers.add(handler);
-         } 
-      } 
-      
+         }
+      }
+
       return handlers;
    }
 
-   protected IDPType parseIDPConfiguration( XMLEventReader xmlEventReader ) throws ParsingException
+   protected IDPType parseIDPConfiguration(XMLEventReader xmlEventReader) throws ParsingException
    {
       IDPType idp = new IDPType();
-      StartElement startElement = StaxParserUtil.getNextStartElement( xmlEventReader );
-      StaxParserUtil.validate( startElement, IDP );
+      StartElement startElement = StaxParserUtil.getNextStartElement(xmlEventReader);
+      StaxParserUtil.validate(startElement, IDP);
 
       // parse and set the root element attributes.
       QName attributeQName = new QName("", ASSERTION_VALIDITY);
       Attribute attribute = startElement.getAttributeByName(attributeQName);
       if (attribute != null)
-         idp.setAssertionValidity( Long.parseLong( StaxParserUtil.getAttributeValue( attribute )) );
+         idp.setAssertionValidity(Long.parseLong(StaxParserUtil.getAttributeValue(attribute)));
 
       attributeQName = new QName("", ROLE_GENERATOR);
       attribute = startElement.getAttributeByName(attributeQName);
       if (attribute != null)
-         idp.setRoleGenerator( StaxParserUtil.getAttributeValue( attribute )) ;
+         idp.setRoleGenerator(StaxParserUtil.getAttributeValue(attribute));
 
       attributeQName = new QName("", ENCRYPT);
       attribute = startElement.getAttributeByName(attributeQName);
       if (attribute != null)
-         idp.setEncrypt( Boolean.parseBoolean( StaxParserUtil.getAttributeValue( attribute )) ) ;
+         idp.setEncrypt(Boolean.parseBoolean(StaxParserUtil.getAttributeValue(attribute)));
 
-      attributeQName = new QName("", CANONICALIZATION_METHOD );
+      attributeQName = new QName("", CANONICALIZATION_METHOD);
       attribute = startElement.getAttributeByName(attributeQName);
       if (attribute != null)
-         idp.setCanonicalizationMethod( StaxParserUtil.getAttributeValue( attribute ));
+         idp.setCanonicalizationMethod(StaxParserUtil.getAttributeValue(attribute));
 
-      attributeQName = new QName("", ATTRIBUTE_MANAGER );
+      attributeQName = new QName("", ATTRIBUTE_MANAGER);
       attribute = startElement.getAttributeByName(attributeQName);
       if (attribute != null)
-         idp.setAttributeManager( StaxParserUtil.getAttributeValue( attribute ));
+         idp.setAttributeManager(StaxParserUtil.getAttributeValue(attribute));
 
-
       while (xmlEventReader.hasNext())
       {
          XMLEvent xmlEvent = StaxParserUtil.peek(xmlEventReader);
@@ -176,57 +188,55 @@
          {
             EndElement endElement = (EndElement) StaxParserUtil.getNextEvent(xmlEventReader);
             String endElementName = StaxParserUtil.getEndElementName(endElement);
-            if (endElementName.equals( IDP ))
+            if (endElementName.equals(IDP))
                break;
             else
                throw new RuntimeException("Unknown End Element:" + endElementName);
          }
 
          startElement = StaxParserUtil.getNextStartElement(xmlEventReader);
-         if ( startElement == null)
+         if (startElement == null)
             break;
-         String elementName = StaxParserUtil.getStartElementName( startElement );
-         if( elementName.equals( IDENTITY_URL ))
+         String elementName = StaxParserUtil.getStartElementName(startElement);
+         if (elementName.equals(IDENTITY_URL))
          {
-            idp.setIdentityURL( StaxParserUtil.getElementText(xmlEventReader) );
+            idp.setIdentityURL(StaxParserUtil.getElementText(xmlEventReader));
          }
-         else if( elementName.equals( TRUST ))
+         else if (elementName.equals(TRUST))
          {
             TrustType trustType = new TrustType();
             startElement = StaxParserUtil.getNextStartElement(xmlEventReader);
             StaxParserUtil.validate(startElement, DOMAINS);
-            trustType.setDomains( StaxParserUtil.getElementText(xmlEventReader) );
+            trustType.setDomains(StaxParserUtil.getElementText(xmlEventReader));
             EndElement endElement = StaxParserUtil.getNextEndElement(xmlEventReader);
             StaxParserUtil.validate(endElement, TRUST);
             idp.setTrust(trustType);
          }
-         else if( elementName.equals( KEY_PROVIDER) )
+         else if (elementName.equals(KEY_PROVIDER))
          {
             KeyProviderType keyProviderType = this.parseKeyProvider(xmlEventReader, startElement);
             idp.setKeyProvider(keyProviderType);
          }
-         else if( elementName.equals( META_PROVIDER) )
+         else if (elementName.equals(META_PROVIDER))
          {
-            MetadataProviderType mdProviderType =  parseMDProvider( xmlEventReader, startElement); 
-            idp.setMetaDataProvider( mdProviderType );
+            MetadataProviderType mdProviderType = parseMDProvider(xmlEventReader, startElement);
+            idp.setMetaDataProvider(mdProviderType);
          }
       }
-      return idp; 
+      return idp;
    }
 
-   protected SPType parseSPConfiguration( XMLEventReader xmlEventReader ) throws ParsingException
+   protected SPType parseSPConfiguration(XMLEventReader xmlEventReader) throws ParsingException
    {
       SPType sp = new SPType();
-      StartElement startElement = StaxParserUtil.getNextStartElement( xmlEventReader );
-      StaxParserUtil.validate( startElement, SP );
+      StartElement startElement = StaxParserUtil.getNextStartElement(xmlEventReader);
+      StaxParserUtil.validate(startElement, SP);
 
-
-      QName attributeQName = new QName("", CANONICALIZATION_METHOD );
+      QName attributeQName = new QName("", CANONICALIZATION_METHOD);
       Attribute attribute = startElement.getAttributeByName(attributeQName);
       if (attribute != null)
-         sp.setCanonicalizationMethod( StaxParserUtil.getAttributeValue( attribute ));
+         sp.setCanonicalizationMethod(StaxParserUtil.getAttributeValue(attribute));
 
-
       while (xmlEventReader.hasNext())
       {
          XMLEvent xmlEvent = StaxParserUtil.peek(xmlEventReader);
@@ -236,186 +246,191 @@
          {
             EndElement endElement = (EndElement) StaxParserUtil.getNextEvent(xmlEventReader);
             String endElementName = StaxParserUtil.getEndElementName(endElement);
-            if (endElementName.equals( SP ))
+            if (endElementName.equals(SP))
                break;
             else
                throw new RuntimeException("Unknown End Element:" + endElementName);
          }
 
          startElement = StaxParserUtil.getNextStartElement(xmlEventReader);
-         if ( startElement == null)
+         if (startElement == null)
             break;
-         String elementName = StaxParserUtil.getStartElementName( startElement );
-         if( elementName.equals( IDENTITY_URL ))
+         String elementName = StaxParserUtil.getStartElementName(startElement);
+         if (elementName.equals(IDENTITY_URL))
          {
-            sp.setIdentityURL( StaxParserUtil.getElementText(xmlEventReader) );
+            sp.setIdentityURL(StaxParserUtil.getElementText(xmlEventReader));
          }
-         else if( elementName.equals( SERVICE_URL ))
+         else if (elementName.equals(SERVICE_URL))
          {
-            sp.setServiceURL( StaxParserUtil.getElementText(xmlEventReader) );
+            sp.setServiceURL(StaxParserUtil.getElementText(xmlEventReader));
          }
-         else if( elementName.equals( TRUST ))
+         else if (elementName.equals(IDP_METADATA_FILE))
          {
+            sp.setIdpMetadataFile(StaxParserUtil.getElementText(xmlEventReader));
+         }
+         else if (elementName.equals(TRUST))
+         {
             TrustType trustType = new TrustType();
             startElement = StaxParserUtil.getNextStartElement(xmlEventReader);
             StaxParserUtil.validate(startElement, DOMAINS);
-            trustType.setDomains( StaxParserUtil.getElementText(xmlEventReader) );
+            trustType.setDomains(StaxParserUtil.getElementText(xmlEventReader));
             EndElement endElement = StaxParserUtil.getNextEndElement(xmlEventReader);
             StaxParserUtil.validate(endElement, TRUST);
             sp.setTrust(trustType);
          }
-         else if( elementName.equals( KEY_PROVIDER) )
+         else if (elementName.equals(KEY_PROVIDER))
          {
-            KeyProviderType keyProviderType =  parseKeyProvider(xmlEventReader, startElement); 
+            KeyProviderType keyProviderType = parseKeyProvider(xmlEventReader, startElement);
             sp.setKeyProvider(keyProviderType);
          }
-         else if( elementName.equals( META_PROVIDER) )
+         else if (elementName.equals(META_PROVIDER))
          {
-            MetadataProviderType mdProviderType =  parseMDProvider( xmlEventReader, startElement); 
-            sp.setMetaDataProvider( mdProviderType );
+            MetadataProviderType mdProviderType = parseMDProvider(xmlEventReader, startElement);
+            sp.setMetaDataProvider(mdProviderType);
          }
       }
       return sp;
    }
 
-   protected KeyProviderType parseKeyProvider(XMLEventReader xmlEventReader, StartElement startElement ) throws ParsingException
+   protected KeyProviderType parseKeyProvider(XMLEventReader xmlEventReader, StartElement startElement)
+         throws ParsingException
    {
       XMLEvent xmlEvent = null;
       KeyProviderType keyProviderType = new KeyProviderType();
 
       // parse and set the ClassName element attributes.
-      QName attributeQName = new QName("", CLASS_NAME );
+      QName attributeQName = new QName("", CLASS_NAME);
       Attribute attribute = startElement.getAttributeByName(attributeQName);
       if (attribute != null)
-         keyProviderType.setClassName( StaxParserUtil.getAttributeValue( attribute ) );
+         keyProviderType.setClassName(StaxParserUtil.getAttributeValue(attribute));
 
-      while( xmlEventReader.hasNext() )
+      while (xmlEventReader.hasNext())
       {
          xmlEvent = StaxParserUtil.peek(xmlEventReader);
-         if( xmlEvent == null )
+         if (xmlEvent == null)
             break;
-         if( xmlEvent instanceof EndElement )
+         if (xmlEvent instanceof EndElement)
          {
             EndElement endElement = StaxParserUtil.getNextEndElement(xmlEventReader);
-            String endElementName = StaxParserUtil.getEndElementName( endElement );
-            if( endElementName.equals( KEY_PROVIDER ))
+            String endElementName = StaxParserUtil.getEndElementName(endElement);
+            if (endElementName.equals(KEY_PROVIDER))
                break;
             else
                continue;
          }
          startElement = StaxParserUtil.getNextStartElement(xmlEventReader);
          String startElementName = StaxParserUtil.getStartElementName(startElement);
-         if( startElementName.equals( AUTH ))
+         if (startElementName.equals(AUTH))
          {
             AuthPropertyType auth = new AuthPropertyType();
             populateKeyValueType(auth, startElement);
 
             keyProviderType.add(auth);
          }
-         else if( startElementName.equals( VALIDATING_ALIAS ))
+         else if (startElementName.equals(VALIDATING_ALIAS))
          {
             KeyValueType auth = new KeyValueType();
             populateKeyValueType(auth, startElement);
 
             keyProviderType.add(auth);
          }
-      } 
-      return keyProviderType;  
+      }
+      return keyProviderType;
    }
-   
-   protected Handler parseHandler(XMLEventReader xmlEventReader, StartElement startElement ) throws ParsingException
+
+   protected Handler parseHandler(XMLEventReader xmlEventReader, StartElement startElement) throws ParsingException
    {
       XMLEvent xmlEvent = null;
       Handler handlerType = new Handler();
 
       // parse and set the ClassName element attributes.
-      QName attributeQName = new QName("", CLASS );
+      QName attributeQName = new QName("", CLASS);
       Attribute attribute = startElement.getAttributeByName(attributeQName);
       if (attribute != null)
-         handlerType.setClazz( StaxParserUtil.getAttributeValue( attribute ) );
+         handlerType.setClazz(StaxParserUtil.getAttributeValue(attribute));
 
-      while( xmlEventReader.hasNext() )
+      while (xmlEventReader.hasNext())
       {
          xmlEvent = StaxParserUtil.peek(xmlEventReader);
-         if( xmlEvent == null )
+         if (xmlEvent == null)
             break;
-         if( xmlEvent instanceof EndElement )
+         if (xmlEvent instanceof EndElement)
          {
             EndElement endElement = StaxParserUtil.getNextEndElement(xmlEventReader);
-            String endElementName = StaxParserUtil.getEndElementName( endElement );
-            if( endElementName.equals( HANDLER ))
+            String endElementName = StaxParserUtil.getEndElementName(endElement);
+            if (endElementName.equals(HANDLER))
                break;
             else
                continue;
          }
          startElement = StaxParserUtil.getNextStartElement(xmlEventReader);
          String startElementName = StaxParserUtil.getStartElementName(startElement);
-          
-         if( startElementName.equals( OPTION ))
+
+         if (startElementName.equals(OPTION))
          {
             KeyValueType auth = new KeyValueType();
             populateKeyValueType(auth, startElement);
 
             handlerType.add(auth);
          }
-      } 
-      return handlerType;  
+      }
+      return handlerType;
    }
 
-   protected MetadataProviderType parseMDProvider(XMLEventReader xmlEventReader, StartElement startElement ) throws ParsingException
+   protected MetadataProviderType parseMDProvider(XMLEventReader xmlEventReader, StartElement startElement)
+         throws ParsingException
    {
       XMLEvent xmlEvent = null;
       MetadataProviderType metaProviderType = new MetadataProviderType();
 
       // parse and set the ClassName element attributes.
-      QName attributeQName = new QName("", CLASS_NAME );
+      QName attributeQName = new QName("", CLASS_NAME);
       Attribute attribute = startElement.getAttributeByName(attributeQName);
       if (attribute != null)
-         metaProviderType.setClassName( StaxParserUtil.getAttributeValue( attribute ) );
+         metaProviderType.setClassName(StaxParserUtil.getAttributeValue(attribute));
 
-      while( xmlEventReader.hasNext() )
+      while (xmlEventReader.hasNext())
       {
          xmlEvent = StaxParserUtil.peek(xmlEventReader);
-         if( xmlEvent == null )
+         if (xmlEvent == null)
             break;
-         if( xmlEvent instanceof EndElement )
+         if (xmlEvent instanceof EndElement)
          {
             EndElement endElement = StaxParserUtil.getNextEndElement(xmlEventReader);
-            String endElementName = StaxParserUtil.getEndElementName( endElement );
-            if( endElementName.equals( META_PROVIDER ))
+            String endElementName = StaxParserUtil.getEndElementName(endElement);
+            if (endElementName.equals(META_PROVIDER))
                break;
             else
                continue;
          }
          startElement = StaxParserUtil.getNextStartElement(xmlEventReader);
          String startElementName = StaxParserUtil.getStartElementName(startElement);
-         if( startElementName.equals( OPTION ))
+         if (startElementName.equals(OPTION))
          {
             KeyValueType auth = new KeyValueType();
             populateKeyValueType(auth, startElement);
 
             metaProviderType.add(auth);
-         } 
-      } 
-      return metaProviderType;  
+         }
+      }
+      return metaProviderType;
    }
 
-   protected void populateKeyValueType( KeyValueType kvt, StartElement startElement )
+   protected void populateKeyValueType(KeyValueType kvt, StartElement startElement)
    {
-      QName attributeQName = new QName("", KEY );
+      QName attributeQName = new QName("", KEY);
       Attribute attribute = startElement.getAttributeByName(attributeQName);
       if (attribute != null)
-         kvt.setKey( StaxParserUtil.getAttributeValue( attribute ) );
+         kvt.setKey(StaxParserUtil.getAttributeValue(attribute));
 
-      attributeQName = new QName("", OPTION );
+      attributeQName = new QName("", OPTION);
       attribute = startElement.getAttributeByName(attributeQName);
       if (attribute != null)
-         kvt.setKey( StaxParserUtil.getAttributeValue( attribute ) );
+         kvt.setKey(StaxParserUtil.getAttributeValue(attribute));
 
-      
-      attributeQName = new QName("", VALUE );
+      attributeQName = new QName("", VALUE);
       attribute = startElement.getAttributeByName(attributeQName);
       if (attribute != null)
-         kvt.setValue( StaxParserUtil.getAttributeValue( attribute ) );  
+         kvt.setValue(StaxParserUtil.getAttributeValue(attribute));
    }
 }
\ No newline at end of file

Modified: federation/trunk/picketlink-fed-core/src/main/java/org/picketlink/identity/federation/core/saml/v2/constants/JBossSAMLURIConstants.java
===================================================================
--- federation/trunk/picketlink-fed-core/src/main/java/org/picketlink/identity/federation/core/saml/v2/constants/JBossSAMLURIConstants.java	2011-02-28 21:22:22 UTC (rev 785)
+++ federation/trunk/picketlink-fed-core/src/main/java/org/picketlink/identity/federation/core/saml/v2/constants/JBossSAMLURIConstants.java	2011-03-01 19:10:15 UTC (rev 786)
@@ -64,6 +64,9 @@
    SIGNATURE_DSA_SHA1("http://www.w3.org/2000/09/xmldsig#dsa-sha1"),
    SIGNATURE_RSA_SHA1("http://www.w3.org/2000/09/xmldsig#rsa-sha1"),
    
+   SAML_HTTP_POST_BINDING("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"),
+   SAML_HTTP_REDIRECT_BINDING("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect"),
+   
    SUBJECT_CONFIRMATION_BEARER("urn:oasis:names:tc:SAML:2.0:cm:bearer"),
    
    

Modified: federation/trunk/picketlink-fed-core/src/main/java/org/picketlink/identity/federation/core/util/CoreConfigUtil.java
===================================================================
--- federation/trunk/picketlink-fed-core/src/main/java/org/picketlink/identity/federation/core/util/CoreConfigUtil.java	2011-02-28 21:22:22 UTC (rev 785)
+++ federation/trunk/picketlink-fed-core/src/main/java/org/picketlink/identity/federation/core/util/CoreConfigUtil.java	2011-03-01 19:10:15 UTC (rev 786)
@@ -38,11 +38,17 @@
 import org.picketlink.identity.federation.core.config.KeyProviderType;
 import org.picketlink.identity.federation.core.config.KeyValueType;
 import org.picketlink.identity.federation.core.config.ProviderType;
+import org.picketlink.identity.federation.core.config.SPType;
 import org.picketlink.identity.federation.core.config.TokenProviderType;
 import org.picketlink.identity.federation.core.constants.PicketLinkFederationConstants;
 import org.picketlink.identity.federation.core.exceptions.ConfigurationException;
 import org.picketlink.identity.federation.core.exceptions.ProcessingException;
 import org.picketlink.identity.federation.core.interfaces.TrustKeyManager;
+import org.picketlink.identity.federation.newmodel.saml.v2.metadata.EndpointType;
+import org.picketlink.identity.federation.newmodel.saml.v2.metadata.EntityDescriptorType;
+import org.picketlink.identity.federation.newmodel.saml.v2.metadata.EntityDescriptorType.EDTChoiceType;
+import org.picketlink.identity.federation.newmodel.saml.v2.metadata.EntityDescriptorType.EDTDescriptorChoiceType;
+import org.picketlink.identity.federation.newmodel.saml.v2.metadata.IDPSSODescriptorType;
 
 /**
  * Utility for configuration
@@ -62,9 +68,9 @@
    public static TrustKeyManager getTrustKeyManager(ProviderType idpOrSPConfiguration)
    {
       KeyProviderType keyProvider = idpOrSPConfiguration.getKeyProvider();
-      return getTrustKeyManager(keyProvider); 
+      return getTrustKeyManager(keyProvider);
    }
-   
+
    /**
     * Once the {@code KeyProviderType} is derived, get
     * the {@code TrustKeyManager}
@@ -73,24 +79,24 @@
     */
    public static TrustKeyManager getTrustKeyManager(KeyProviderType keyProvider)
    {
-      TrustKeyManager trustKeyManager = null; 
+      TrustKeyManager trustKeyManager = null;
       try
       {
          ClassLoader tcl = SecurityActions.getContextClassLoader();
          String keyManagerClassName = keyProvider.getClassName();
-         if(keyManagerClassName == null)
+         if (keyManagerClassName == null)
             throw new RuntimeException("KeyManager class name is null");
 
          Class<?> clazz = tcl.loadClass(keyManagerClassName);
          trustKeyManager = (TrustKeyManager) clazz.newInstance();
       }
-      catch(Exception e)
+      catch (Exception e)
       {
-         log.error("Exception in getting TrustKeyManager:",e); 
-      } 
-      return trustKeyManager; 
+         log.error("Exception in getting TrustKeyManager:", e);
+      }
+      return trustKeyManager;
    }
-   
+
    /**
     * Get the validating key
     * @param idpSpConfiguration
@@ -100,13 +106,13 @@
     * @throws ProcessingException
     */
    public static PublicKey getValidatingKey(ProviderType idpSpConfiguration, String domain)
-   throws ConfigurationException, ProcessingException
+         throws ConfigurationException, ProcessingException
    {
-      TrustKeyManager trustKeyManager = getTrustKeyManager(idpSpConfiguration); 
-      
-      return getValidatingKey(trustKeyManager, domain); 
-   } 
-   
+      TrustKeyManager trustKeyManager = getTrustKeyManager(idpSpConfiguration);
+
+      return getValidatingKey(trustKeyManager, domain);
+   }
+
    /**
     * Get the validating key given the trust key manager
     * @param trustKeyManager
@@ -115,16 +121,15 @@
     * @throws ConfigurationException
     * @throws ProcessingException
     */
-   public static PublicKey getValidatingKey(TrustKeyManager trustKeyManager, 
-         String domain)
-   throws ConfigurationException, ProcessingException
-   {   
-      if(trustKeyManager == null)
+   public static PublicKey getValidatingKey(TrustKeyManager trustKeyManager, String domain)
+         throws ConfigurationException, ProcessingException
+   {
+      if (trustKeyManager == null)
          throw new IllegalArgumentException("Trust Key Manager is null");
-      
-      return trustKeyManager.getValidatingKey(domain); 
-   } 
-   
+
+      return trustKeyManager.getValidatingKey(domain);
+   }
+
    /**
     * Given a {@code KeyProviderType}, return the list of auth properties that have been decrypted for any
     * masked password
@@ -133,15 +138,16 @@
     * @throws GeneralSecurityException
     */
    @SuppressWarnings("unchecked")
-   public static List<AuthPropertyType> getKeyProviderProperties( KeyProviderType keyProviderType ) throws GeneralSecurityException
+   public static List<AuthPropertyType> getKeyProviderProperties(KeyProviderType keyProviderType)
+         throws GeneralSecurityException
    {
       List<AuthPropertyType> authProperties = keyProviderType.getAuth();
-      if( decryptionNeeded( authProperties ))
+      if (decryptionNeeded(authProperties))
          authProperties = decryptPasswords(authProperties);
-          
+
       return authProperties;
    }
-   
+
    /**
     * Given a {@code TokenProviderType}, return the list of properties that have been decrypted for
     * any masked property value
@@ -150,15 +156,15 @@
     * @throws GeneralSecurityException
     */
    @SuppressWarnings("unchecked")
-   public static List<KeyValueType> getProperties( TokenProviderType tokenProviderType ) throws GeneralSecurityException
+   public static List<KeyValueType> getProperties(TokenProviderType tokenProviderType) throws GeneralSecurityException
    {
       List<KeyValueType> keyValueTypeList = tokenProviderType.getProperty();
-      if( decryptionNeeded( keyValueTypeList ))
-         keyValueTypeList = decryptPasswords( keyValueTypeList );
-          
+      if (decryptionNeeded(keyValueTypeList))
+         keyValueTypeList = decryptPasswords(keyValueTypeList);
+
       return keyValueTypeList;
    }
-   
+
    /**
     * Given a {@code ClaimsProcessorType}, return the list of properties that have been decrypted for
     * any masked property value
@@ -167,37 +173,38 @@
     * @throws GeneralSecurityException
     */
    @SuppressWarnings("unchecked")
-   public static List<KeyValueType> getProperties( ClaimsProcessorType claimsProcessorType ) throws GeneralSecurityException
+   public static List<KeyValueType> getProperties(ClaimsProcessorType claimsProcessorType)
+         throws GeneralSecurityException
    {
       List<KeyValueType> keyValueTypeList = claimsProcessorType.getProperty();
-      if( decryptionNeeded( keyValueTypeList ))
-         keyValueTypeList = decryptPasswords( keyValueTypeList );
-          
+      if (decryptionNeeded(keyValueTypeList))
+         keyValueTypeList = decryptPasswords(keyValueTypeList);
+
       return keyValueTypeList;
    }
-   
+
    /**
     * Given a key value list, check if decrypt of any properties is needed. 
     * Unless one of the keys is "salt", we cannot figure out is decrypt is needed
     * @param keyValueList
     * @return
     */
-   public static boolean decryptionNeeded( List<? extends KeyValueType> keyValueList )
-   { 
+   public static boolean decryptionNeeded(List<? extends KeyValueType> keyValueList)
+   {
       int length = keyValueList.size();
-      
+
       //Let us run through the list to see if there is any salt
-      for( int i = 0 ; i < length; i++ )
+      for (int i = 0; i < length; i++)
       {
-         KeyValueType kvt = keyValueList.get( i );
-         
+         KeyValueType kvt = keyValueList.get(i);
+
          String key = kvt.getKey();
-         if(PicketLinkFederationConstants.SALT.equalsIgnoreCase( key ) )
-            return true;  
+         if (PicketLinkFederationConstants.SALT.equalsIgnoreCase(key))
+            return true;
       }
-      return false; 
+      return false;
    }
-   
+
    /**
     * Given a key value pair read from PicketLink configuration, ensure
     * that we replace the masked passwords with the decoded passwords
@@ -207,75 +214,130 @@
     * @return
     * @throws GeneralSecurityException 
     * @throws Exception
-    */ 
+    */
    @SuppressWarnings("rawtypes")
-   private static List decryptPasswords( List keyValueList ) throws GeneralSecurityException
+   private static List decryptPasswords(List keyValueList) throws GeneralSecurityException
    {
       String pbeAlgo = PicketLinkFederationConstants.PBE_ALGORITHM;
-      
+
       String salt = null;
       int iterationCount = 0;
-      
+
       int length = keyValueList.size();
-      
+
       //Let us run through the list to see if there is any salt
-      for( int i = 0 ; i < length; i++ )
+      for (int i = 0; i < length; i++)
       {
-         KeyValueType kvt = (KeyValueType) keyValueList.get( i );
-         
+         KeyValueType kvt = (KeyValueType) keyValueList.get(i);
+
          String key = kvt.getKey();
-         if(PicketLinkFederationConstants.SALT.equalsIgnoreCase( key ) )
+         if (PicketLinkFederationConstants.SALT.equalsIgnoreCase(key))
             salt = kvt.getValue();
-         if(PicketLinkFederationConstants.ITERATION_COUNT.equalsIgnoreCase( key ) )
-            iterationCount = Integer.parseInt( kvt.getValue() ); 
+         if (PicketLinkFederationConstants.ITERATION_COUNT.equalsIgnoreCase(key))
+            iterationCount = Integer.parseInt(kvt.getValue());
       }
-      
-      if( salt == null )
+
+      if (salt == null)
          return keyValueList;
-      
+
       //Ok. there is a salt configured. So we have some properties with masked values
-      List<KeyValueType>  returningList = new ArrayList<KeyValueType>();
-       
+      List<KeyValueType> returningList = new ArrayList<KeyValueType>();
+
       // Create the PBE secret key 
-      SecretKeyFactory factory = SecretKeyFactory.getInstance( pbeAlgo );
+      SecretKeyFactory factory = SecretKeyFactory.getInstance(pbeAlgo);
 
       char[] password = "somearbitrarycrazystringthatdoesnotmatter".toCharArray();
-      PBEParameterSpec cipherSpec = new PBEParameterSpec( salt.getBytes(), iterationCount );
+      PBEParameterSpec cipherSpec = new PBEParameterSpec(salt.getBytes(), iterationCount);
       PBEKeySpec keySpec = new PBEKeySpec(password);
       SecretKey cipherKey = factory.generateSecret(keySpec);
 
-      
-      for( int i = 0 ; i < length; i++ )
+      for (int i = 0; i < length; i++)
       {
-         KeyValueType kvt = (KeyValueType) keyValueList.get( i );
-         
+         KeyValueType kvt = (KeyValueType) keyValueList.get(i);
+
          String val = kvt.getValue();
-         if( val.startsWith( PicketLinkFederationConstants.PASS_MASK_PREFIX) )
+         if (val.startsWith(PicketLinkFederationConstants.PASS_MASK_PREFIX))
          {
-            val = val.substring( PicketLinkFederationConstants.PASS_MASK_PREFIX.length() );
+            val = val.substring(PicketLinkFederationConstants.PASS_MASK_PREFIX.length());
             String decodedValue;
             try
             {
-               decodedValue = PBEUtils.decode64( val, pbeAlgo , cipherKey, cipherSpec);
+               decodedValue = PBEUtils.decode64(val, pbeAlgo, cipherKey, cipherSpec);
             }
             catch (UnsupportedEncodingException e)
             {
-               throw new RuntimeException( e );
-            } 
-            
+               throw new RuntimeException(e);
+            }
+
             KeyValueType newKVT = new KeyValueType();
-            if( keyValueList.get( 0 ) instanceof AuthPropertyType )
+            if (keyValueList.get(0) instanceof AuthPropertyType)
                newKVT = new AuthPropertyType();
-            newKVT.setKey( kvt.getKey() );
-            newKVT.setValue( new String( decodedValue ) );
-            returningList.add( newKVT );
+            newKVT.setKey(kvt.getKey());
+            newKVT.setValue(new String(decodedValue));
+            returningList.add(newKVT);
          }
          else
          {
-            returningList.add( kvt );
+            returningList.add(kvt);
          }
       }
-      
-      return returningList; 
+
+      return returningList;
    }
+
+   public static SPType getSPConfiguration(EntityDescriptorType entityDescriptor, String bindingURI)
+   {
+      List<EDTChoiceType> edtChoices = entityDescriptor.getChoiceType();
+      for (EDTChoiceType edt : edtChoices)
+      {
+         List<EDTDescriptorChoiceType> edtDescriptors = edt.getDescriptors();
+         for (EDTDescriptorChoiceType edtDesc : edtDescriptors)
+         {
+            IDPSSODescriptorType idpSSO = edtDesc.getIdpDescriptor();
+            if (idpSSO != null)
+            {
+               return getSPConfiguration(idpSSO, bindingURI);
+            }
+         }
+      }
+      return null;
+   }
+
+   public static IDPSSODescriptorType getIDPDescriptor(EntityDescriptorType entityDescriptor)
+   {
+      List<EDTChoiceType> edtChoices = entityDescriptor.getChoiceType();
+      for (EDTChoiceType edt : edtChoices)
+      {
+         List<EDTDescriptorChoiceType> edtDescriptors = edt.getDescriptors();
+         for (EDTDescriptorChoiceType edtDesc : edtDescriptors)
+         {
+            IDPSSODescriptorType idpSSO = edtDesc.getIdpDescriptor();
+            if (idpSSO != null)
+            {
+               return idpSSO;
+            }
+         }
+      }
+      return null;
+   }
+
+   public static SPType getSPConfiguration(IDPSSODescriptorType idp, String bindingURI)
+   {
+      String identityURL = null;
+
+      SPType sp = new SPType();
+      List<EndpointType> endpoints = idp.getSingleSignOnService();
+      for (EndpointType endpoint : endpoints)
+      {
+         if (endpoint.getBinding().toString().equals(bindingURI))
+         {
+            identityURL = endpoint.getLocation().toString();
+            break;
+         }
+
+      }
+      //get identity url
+      sp.setIdentityURL(identityURL);
+      return sp;
+   }
 }
\ No newline at end of file

Modified: federation/trunk/picketlink-fed-core/src/main/java/org/picketlink/identity/federation/core/util/XMLSignatureUtil.java
===================================================================
--- federation/trunk/picketlink-fed-core/src/main/java/org/picketlink/identity/federation/core/util/XMLSignatureUtil.java	2011-02-28 21:22:22 UTC (rev 785)
+++ federation/trunk/picketlink-fed-core/src/main/java/org/picketlink/identity/federation/core/util/XMLSignatureUtil.java	2011-03-01 19:10:15 UTC (rev 786)
@@ -80,29 +80,29 @@
 public class XMLSignatureUtil
 {
    private static Logger log = Logger.getLogger(XMLSignatureUtil.class);
+
    private static boolean trace = log.isTraceEnabled();
 
-   private static String canonicalizationMethodType = CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS; 
-   
-   private static XMLSignatureFactory fac =  getXMLSignatureFactory(); 
-    
+   private static String canonicalizationMethodType = CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS;
+
+   private static XMLSignatureFactory fac = getXMLSignatureFactory();
+
    private static XMLSignatureFactory getXMLSignatureFactory()
    {
-      XMLSignatureFactory xsf =   null;
-      
+      XMLSignatureFactory xsf = null;
+
       try
       {
-         xsf = XMLSignatureFactory.getInstance("DOM"); 
-      } 
-      catch(Exception err)
+         xsf = XMLSignatureFactory.getInstance("DOM");
+      }
+      catch (Exception err)
       {
          //JDK5
-         xsf = XMLSignatureFactory.getInstance("DOM",
-               new org.jcp.xml.dsig.internal.dom.XMLDSigRI());
+         xsf = XMLSignatureFactory.getInstance("DOM", new org.jcp.xml.dsig.internal.dom.XMLDSigRI());
       }
       return xsf;
    }
-   
+
    //Set some system properties
    static
    {
@@ -110,22 +110,22 @@
       {
          public Object run()
          {
-            System.setProperty("org.apache.xml.security.ignoreLineBreaks", "true"); 
+            System.setProperty("org.apache.xml.security.ignoreLineBreaks", "true");
             return null;
          }
-      }); 
-   }; 
-   
+      });
+   };
+
    /**
     * Set the canonicalization method type
     * @param canonical
     */
-   public static void setCanonicalizationMethodType( String canonical )
+   public static void setCanonicalizationMethodType(String canonical)
    {
-      if( canonical != null )
+      if (canonical != null)
          canonicalizationMethodType = canonical;
    }
-   
+
    /**
     * Precheck whether the document that will be validated
     * has the right signedinfo
@@ -137,7 +137,7 @@
       NodeList nl = doc.getElementsByTagNameNS(JBossSAMLURIConstants.XMLDSIG_NSURI.get(), "SignedInfo");
       return nl != null ? nl.getLength() > 0 : false;
    }
-   
+
    /**
     * Sign a node in a document
     * @param doc Document
@@ -153,20 +153,14 @@
     * @throws GeneralSecurityException 
     * @throws ParserConfigurationException  
     */
-   public static Document sign(Document doc,
-          Node parentOfNodeToBeSigned,
-          PrivateKey signingKey,
-          X509Certificate certificate,
-          String digestMethod, 
-          String signatureMethod,
-          String referenceURI) 
-   throws ParserConfigurationException, GeneralSecurityException, MarshalException, XMLSignatureException 
+   public static Document sign(Document doc, Node parentOfNodeToBeSigned, PrivateKey signingKey,
+         X509Certificate certificate, String digestMethod, String signatureMethod, String referenceURI)
+         throws ParserConfigurationException, GeneralSecurityException, MarshalException, XMLSignatureException
    {
-      KeyPair keyPair = new KeyPair(certificate.getPublicKey(),signingKey);
-      return sign(doc,parentOfNodeToBeSigned, keyPair,
-            digestMethod, signatureMethod, referenceURI);
+      KeyPair keyPair = new KeyPair(certificate.getPublicKey(), signingKey);
+      return sign(doc, parentOfNodeToBeSigned, keyPair, digestMethod, signatureMethod, referenceURI);
    }
-   
+
    /**
     * Sign a node in a document
     * @param doc
@@ -181,41 +175,37 @@
     * @throws XMLSignatureException 
     * @throws MarshalException 
     * @throws GeneralSecurityException 
-    */  
-   public static Document sign(Document doc,
-         Node nodeToBeSigned,
-         KeyPair keyPair,
-         String digestMethod, 
-         String signatureMethod,
-         String referenceURI) throws ParserConfigurationException, GeneralSecurityException, MarshalException, XMLSignatureException
-   { 
-      if(nodeToBeSigned == null)
+    */
+   public static Document sign(Document doc, Node nodeToBeSigned, KeyPair keyPair, String digestMethod,
+         String signatureMethod, String referenceURI) throws ParserConfigurationException, GeneralSecurityException,
+         MarshalException, XMLSignatureException
+   {
+      if (nodeToBeSigned == null)
          throw new IllegalArgumentException("Node to be signed is null");
-      if(trace)
+      if (trace)
       {
-         log.trace("Document to be signed=" + DocumentUtil.asString(doc)); 
+         log.trace("Document to be signed=" + DocumentUtil.asString(doc));
       }
-      
+
       Node parentNode = nodeToBeSigned.getParentNode();
-      
+
       //Let us create a new Document
       Document newDoc = DocumentUtil.createDocument();
       //Import the node
       Node signingNode = newDoc.importNode(nodeToBeSigned, true);
       newDoc.appendChild(signingNode);
-      
+
       newDoc = sign(newDoc, keyPair, digestMethod, signatureMethod, referenceURI);
-      
+
       //Now let us import this signed doc into the original document we got in the method call
       Node signedNode = doc.importNode(newDoc.getFirstChild(), true);
-      
+
       parentNode.replaceChild(signedNode, nodeToBeSigned);
       //doc.getDocumentElement().replaceChild(signedNode, nodeToBeSigned);
-      
-      return doc; 
+
+      return doc;
    }
-   
-   
+
    /**
     * Sign the root element
     * @param doc 
@@ -229,54 +219,47 @@
     * @throws XMLSignatureException 
     * @throws MarshalException 
     */
-   public static Document sign(Document doc, 
-         KeyPair keyPair,
-         String digestMethod, 
-         String signatureMethod,
-         String referenceURI) throws GeneralSecurityException, MarshalException, XMLSignatureException 
-  {   
-      if(trace)
+   public static Document sign(Document doc, KeyPair keyPair, String digestMethod, String signatureMethod,
+         String referenceURI) throws GeneralSecurityException, MarshalException, XMLSignatureException
+   {
+      if (trace)
       {
-         log.trace("Document to be signed=" + DocumentUtil.asString(doc)); 
+         log.trace("Document to be signed=" + DocumentUtil.asString(doc));
       }
       PrivateKey signingKey = keyPair.getPrivate();
       PublicKey publicKey = keyPair.getPublic();
-      
-     DOMSignContext dsc = new DOMSignContext(signingKey, doc.getDocumentElement());  
-     dsc.setDefaultNamespacePrefix("dsig"); 
-         
-     DigestMethod digestMethodObj = fac.newDigestMethod(digestMethod, null);
-     Transform transform1 = fac.newTransform(Transform.ENVELOPED,
-           (TransformParameterSpec) null);
-     Transform transform2 =  fac.newTransform("http://www.w3.org/2001/10/xml-exc-c14n#",
-           (TransformParameterSpec) null);
 
-     List<Transform>  transformList = new ArrayList<Transform>() ;
-     transformList.add(transform1); 
-     transformList.add(transform2);  
+      DOMSignContext dsc = new DOMSignContext(signingKey, doc.getDocumentElement());
+      dsc.setDefaultNamespacePrefix("dsig");
 
-     Reference ref = fac.newReference
-     ( referenceURI,  digestMethodObj,transformList,null, null); 
-     
-     CanonicalizationMethod canonicalizationMethod
-         = fac.newCanonicalizationMethod
-         (canonicalizationMethodType, (C14NMethodParameterSpec) null);
-     
-     List<Reference> referenceList = Collections.singletonList(ref); 
-     SignatureMethod signatureMethodObj = fac.newSignatureMethod(signatureMethod, null);
-     SignedInfo si =  fac.newSignedInfo (canonicalizationMethod, signatureMethodObj ,
-                             referenceList);  
-     
-     KeyInfoFactory kif = fac.getKeyInfoFactory(); 
-     KeyValue kv = kif.newKeyValue(publicKey);
-     KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv)); 
+      DigestMethod digestMethodObj = fac.newDigestMethod(digestMethod, null);
+      Transform transform1 = fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null);
+      Transform transform2 = fac.newTransform("http://www.w3.org/2001/10/xml-exc-c14n#", (TransformParameterSpec) null);
 
-     XMLSignature signature = fac.newXMLSignature(si, ki); 
+      List<Transform> transformList = new ArrayList<Transform>();
+      transformList.add(transform1);
+      transformList.add(transform2);
 
-     signature.sign(dsc); 
-     
-     return doc; 
-  }
+      Reference ref = fac.newReference(referenceURI, digestMethodObj, transformList, null, null);
+
+      CanonicalizationMethod canonicalizationMethod = fac.newCanonicalizationMethod(canonicalizationMethodType,
+            (C14NMethodParameterSpec) null);
+
+      List<Reference> referenceList = Collections.singletonList(ref);
+      SignatureMethod signatureMethodObj = fac.newSignatureMethod(signatureMethod, null);
+      SignedInfo si = fac.newSignedInfo(canonicalizationMethod, signatureMethodObj, referenceList);
+
+      KeyInfoFactory kif = fac.getKeyInfoFactory();
+      KeyValue kv = kif.newKeyValue(publicKey);
+      KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv));
+
+      XMLSignature signature = fac.newXMLSignature(si, ki);
+
+      signature.sign(dsc);
+
+      return doc;
+   }
+
    /**
     * Validate a signed document with the given public key
     * @param signedDoc
@@ -286,37 +269,37 @@
     * @throws XMLSignatureException 
     */
    @SuppressWarnings("unchecked")
-   public static boolean validate(Document signedDoc, Key publicKey) throws MarshalException, XMLSignatureException 
+   public static boolean validate(Document signedDoc, Key publicKey) throws MarshalException, XMLSignatureException
    {
-      if(signedDoc == null)
+      if (signedDoc == null)
          throw new IllegalArgumentException("Signed Document is null");
       NodeList nl = signedDoc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
-      if (nl == null || nl.getLength() == 0) 
+      if (nl == null || nl.getLength() == 0)
       {
-        throw new IllegalArgumentException("Cannot find Signature element");
-      } 
-      if(publicKey == null)
+         throw new IllegalArgumentException("Cannot find Signature element");
+      }
+      if (publicKey == null)
          throw new IllegalArgumentException("Public Key is null");
-      
-      DOMValidateContext valContext = new DOMValidateContext(publicKey, nl.item(0)); 
-      XMLSignature signature =  fac.unmarshalXMLSignature(valContext); 
-      boolean coreValidity = signature.validate(valContext); 
 
-      if(trace && !coreValidity)
+      DOMValidateContext valContext = new DOMValidateContext(publicKey, nl.item(0));
+      XMLSignature signature = fac.unmarshalXMLSignature(valContext);
+      boolean coreValidity = signature.validate(valContext);
+
+      if (trace && !coreValidity)
       {
          boolean sv = signature.getSignatureValue().validate(valContext);
-         log.trace("Signature validation status: " + sv); 
-         
+         log.trace("Signature validation status: " + sv);
+
          List<Reference> references = signature.getSignedInfo().getReferences();
-         for(Reference ref:references)
+         for (Reference ref : references)
          {
-            log.trace("[Ref id=" + ref.getId() +":uri=" + ref.getURI() + 
-                  "]validity status:" + ref.validate(valContext));
-         }  
+            log.trace("[Ref id=" + ref.getId() + ":uri=" + ref.getURI() + "]validity status:"
+                  + ref.validate(valContext));
+         }
       }
       return coreValidity;
    }
- 
+
    /**
     * Marshall a SignatureType to output stream
     * @param signature
@@ -324,57 +307,57 @@
     * @throws SAXException 
     * @throws JAXBException 
     */
-   public static void marshall(SignatureType signature, OutputStream os) throws JAXBException, SAXException 
+   public static void marshall(SignatureType signature, OutputStream os) throws JAXBException, SAXException
    {
-      throw new RuntimeException( "NYI" );
+      throw new RuntimeException("NYI");
       /*JAXBElement<SignatureType> jsig = objectFactory.createSignature(signature);
       Marshaller marshaller = JAXBUtil.getValidatingMarshaller(pkgName, schemaLocation);
       marshaller.marshal(jsig, os);*/
    }
- 
+
    /**
     * Marshall the signed document to an output stream
     * @param signedDocument
     * @param os
     * @throws TransformerException 
     */
-   public static void marshall(Document signedDocument, OutputStream os) 
-   throws TransformerException 
+   public static void marshall(Document signedDocument, OutputStream os) throws TransformerException
    {
       TransformerFactory tf = TransformerFactory.newInstance();
       Transformer trans = tf.newTransformer();
-      trans.transform(DocumentUtil.getXMLSource(signedDocument), new StreamResult(os)); 
+      trans.transform(DocumentUtil.getXMLSource(signedDocument), new StreamResult(os));
    }
-   
+
    /**
     * Given the X509Certificate in the keyinfo element, get a {@link X509Certificate}
     * @param certificateString
     * @return
     * @throws ProcessingException
     */
-   public static X509Certificate getX509CertificateFromKeyInfoString( String certificateString ) throws ProcessingException
+   public static X509Certificate getX509CertificateFromKeyInfoString(String certificateString)
+         throws ProcessingException
    {
       X509Certificate cert = null;
       StringBuilder builder = new StringBuilder();
-      builder.append( "-----BEGIN CERTIFICATE-----\n" ).append( certificateString ).append( "\n-----END CERTIFICATE-----" );
+      builder.append("-----BEGIN CERTIFICATE-----\n").append(certificateString).append("\n-----END CERTIFICATE-----");
 
       String derFormattedString = builder.toString();
 
       try
       {
          CertificateFactory cf = CertificateFactory.getInstance("X.509");
-         ByteArrayInputStream bais = new ByteArrayInputStream( derFormattedString.getBytes());
+         ByteArrayInputStream bais = new ByteArrayInputStream(derFormattedString.getBytes());
 
-         while ( bais.available() > 0) 
+         while (bais.available() > 0)
          {
             cert = (X509Certificate) cf.generateCertificate(bais);
-         } 
-      } 
+         }
+      }
       catch (java.security.cert.CertificateException e)
-      { 
-         throw new ProcessingException( e );
+      {
+         throw new ProcessingException(e);
       }
       return cert;
    }
-       
+
 }
\ No newline at end of file

Modified: federation/trunk/picketlink-fed-core/src/main/resources/schema/config/picketlink-fed.xsd
===================================================================
--- federation/trunk/picketlink-fed-core/src/main/resources/schema/config/picketlink-fed.xsd	2011-02-28 21:22:22 UTC (rev 785)
+++ federation/trunk/picketlink-fed-core/src/main/resources/schema/config/picketlink-fed.xsd	2011-03-01 19:10:15 UTC (rev 786)
@@ -1,7 +1,7 @@
 <?xml version="1.0" encoding="UTF-8"?>
-<schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="urn:picketlink:identity-federation:config:1.0"
-	xmlns:tns="urn:picketlink:identity-federation:config:1.0"
-	elementFormDefault="qualified" version="1.0">
+<schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="urn:picketlink:identity-federation:config:2.0"
+	xmlns:tns="urn:picketlink:identity-federation:config:2.0"
+	elementFormDefault="qualified" version="2.0">
 	<complexType name="IDPType">
 		<annotation>
 			<documentation>
@@ -101,8 +101,7 @@
     		<documentation>Base Type for IDP and SP</documentation>
     	</annotation>
     	<sequence>
-    		<element name="IdentityURL" type="string" maxOccurs="1"
-    			minOccurs="1">
+    		<element name="IdentityURL" type="string" maxOccurs="1" minOccurs="0">
     		</element>
     		<element name="Trust" type="tns:TrustType" maxOccurs="1"
     			minOccurs="0">
@@ -133,6 +132,7 @@
     		<extension base="tns:ProviderType">
     			<sequence>
     				<element name="ServiceURL" type="string"></element>
+    				<element name="IDPMetadataFile" type="string" minOccurs="0" maxOccurs="1"></element>
     			</sequence>
     		</extension>
     	</complexContent>

Added: federation/trunk/picketlink-fed-core/src/test/java/org/picketlink/test/identity/federation/core/config/MetadataToSPTypeUnitTestCase.java
===================================================================
--- federation/trunk/picketlink-fed-core/src/test/java/org/picketlink/test/identity/federation/core/config/MetadataToSPTypeUnitTestCase.java	                        (rev 0)
+++ federation/trunk/picketlink-fed-core/src/test/java/org/picketlink/test/identity/federation/core/config/MetadataToSPTypeUnitTestCase.java	2011-03-01 19:10:15 UTC (rev 786)
@@ -0,0 +1,60 @@
+/*
+ * 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.picketlink.test.identity.federation.core.config;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+import java.io.InputStream;
+
+import org.junit.Test;
+import org.picketlink.identity.federation.core.config.SPType;
+import org.picketlink.identity.federation.core.parsers.saml.SAMLParser;
+import org.picketlink.identity.federation.core.saml.v2.constants.JBossSAMLURIConstants;
+import org.picketlink.identity.federation.core.util.CoreConfigUtil;
+import org.picketlink.identity.federation.newmodel.saml.v2.metadata.EntitiesDescriptorType;
+import org.picketlink.identity.federation.newmodel.saml.v2.metadata.EntityDescriptorType;
+
+/**
+ * Given an IDP metadata, construct {@link SPType}
+ * @author Anil.Saldhana at redhat.com
+ * @since Feb 28, 2011
+ */
+public class MetadataToSPTypeUnitTestCase
+{
+   private final String idpMetadata = "saml2/metadata/testshib.org.idp-metadata.xml";
+
+   @Test
+   public void testMetadataToSP() throws Exception
+   {
+      InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(idpMetadata);
+      assertNotNull(is);
+      SAMLParser parser = new SAMLParser();
+      EntitiesDescriptorType entities = (EntitiesDescriptorType) parser.parse(is);
+      assertNotNull(entities);
+
+      SPType sp = CoreConfigUtil.getSPConfiguration((EntityDescriptorType) entities.getEntityDescriptor().get(0),
+            JBossSAMLURIConstants.SAML_HTTP_POST_BINDING.get());
+      assertNotNull(sp);
+      assertEquals("https://idp.testshib.org/idp/profile/SAML2/POST/SSO", sp.getIdentityURL());
+   }
+}
\ No newline at end of file

Modified: federation/trunk/picketlink-web/src/main/java/org/picketlink/identity/federation/web/constants/GeneralConstants.java
===================================================================
--- federation/trunk/picketlink-web/src/main/java/org/picketlink/identity/federation/web/constants/GeneralConstants.java	2011-02-28 21:22:22 UTC (rev 785)
+++ federation/trunk/picketlink-web/src/main/java/org/picketlink/identity/federation/web/constants/GeneralConstants.java	2011-03-01 19:10:15 UTC (rev 786)
@@ -29,46 +29,64 @@
 public interface GeneralConstants
 {
    String ASSERTIONS_VALIDITY = "ASSERTIONS_VALIDITY";
+
    String ASSERTION_ID = "ASSERTION_ID";
+
    String ASSERTION = "ASSERTION";
-   
+
    String ATTRIBUTES = "ATTRIBUTES";
+
    String ATTRIBUTE_KEYS = "ATTRIBUTE_KEYS";
-   String ATTIBUTE_MANAGER = "ATTRIBUTE_MANAGER"; 
-   
+
+   String ATTIBUTE_MANAGER = "ATTRIBUTE_MANAGER";
+
    String CANONICALIZATION_METHOD = "CANONICALIZATION_METHOD";
+
    String CONFIGURATION = "CONFIGURATION";
+
    String CONFIG_FILE_LOCATION = "/WEB-INF/picketlink-idfed.xml";
-   
+
    String GLOBAL_LOGOUT = "GLO";
-   
+
    String HANDLER_CONFIG_FILE_LOCATION = "/WEB-INF/picketlink-handlers.xml";
-   
+
    String IDENTITY_SERVER = "IDENTITY_SERVER";
+
    String IDENTITY_PARTICIPANT_STACK = "IDENTITY_PARTICIPANT_STACK";
+
    String IGNORE_SIGNATURES = "IGNORE_SIGNATURES";
-   
-   String KEYPAIR = "KEYPAIR"; 
-  
+
+   String KEYPAIR = "KEYPAIR";
+
    String LOGOUT_PAGE = "LOGOUT_PAGE";
+
    String LOGOUT_PAGE_NAME = "/logout.jsp";
-   
+
    String PRINCIPAL_ID = "jboss_identity.principal";
+
    String RELAY_STATE = "RelayState";
+
    String ROLES = "ROLES";
+
    String ROLES_ID = "jboss_identity.roles";
-   
+
    String ROLE_GENERATOR = "ROLE_GENERATOR";
+
    String ROLE_VALIDATOR = "ROLE_VALIDATOR";
+
    String ROLE_VALIDATOR_IGNORE = "ROLE_VALIDATOR_IGNORE";
-   
+
    String SAML_REQUEST_KEY = "SAMLRequest";
+
    String SAML_RESPONSE_KEY = "SAMLResponse";
-   
+
    String DECRYPTING_KEY = "DECRYPTING_KEY";
+
    String SENDER_PUBLIC_KEY = "SENDER_PUBLIC_KEY";
+
    String SIGN_OUTGOING_MESSAGES = "SIGN_OUTGOING_MESSAGES";
-   
+
    String USERNAME_FIELD = "JBID_USERNAME";
+
    String PASS_FIELD = "JBID_PASSWORD";
 }
\ No newline at end of file

Modified: federation/trunk/picketlink-web/src/main/java/org/picketlink/identity/federation/web/util/ConfigurationUtil.java
===================================================================
--- federation/trunk/picketlink-web/src/main/java/org/picketlink/identity/federation/web/util/ConfigurationUtil.java	2011-02-28 21:22:22 UTC (rev 785)
+++ federation/trunk/picketlink-web/src/main/java/org/picketlink/identity/federation/web/util/ConfigurationUtil.java	2011-03-01 19:10:15 UTC (rev 786)
@@ -42,45 +42,30 @@
     * @param is
     * @return 
     * @throws ParsingException 
-    */ 
-   public static IDPType getIDPConfiguration(InputStream is) throws ParsingException  
+    */
+   public static IDPType getIDPConfiguration(InputStream is) throws ParsingException
    {
-      if(is == null)
+      if (is == null)
          throw new IllegalArgumentException("inputstream is null");
-      /*String schema = PicketLinkFederationConstants.SCHEMA_IDFED;
-      
-      Unmarshaller un = getUnmarshaller(schema);
-      
-      JAXBElement<IDPType> jaxbSp =  (JAXBElement<IDPType>) un.unmarshal(is);
-      return jaxbSp.getValue(); */
-      
+
       SAMLConfigParser parser = new SAMLConfigParser();
       return (IDPType) parser.parse(is);
    }
 
-   
    /**
     * Get the SP Configuration from the
     * passed inputstream
     * @param is
     * @return 
     * @throws ParsingException 
-    */ 
-   public static SPType getSPConfiguration(InputStream is) throws ParsingException  
+    */
+   public static SPType getSPConfiguration(InputStream is) throws ParsingException
    {
-      if(is == null)
+      if (is == null)
          throw new IllegalArgumentException("inputstream is null");
-      /*
-      String schema = PicketLinkFederationConstants.SCHEMA_IDFED;
-      
-      Unmarshaller un = getUnmarshaller(schema);
-      
-      JAXBElement<SPType> jaxbSp =  (JAXBElement<SPType>) un.unmarshal(is);
-      return jaxbSp.getValue(); 
-      */
       return (SPType) (new SAMLConfigParser()).parse(is);
    }
-   
+
    /**
     * Get the Handlers from the configuration
     * @param is
@@ -89,14 +74,8 @@
     */
    public static Handlers getHandlers(InputStream is) throws ParsingException
    {
-      if(is == null)
-         throw new IllegalArgumentException("inputstream is null");/*
-      String[] schemas = new String[] { PicketLinkFederationConstants.SCHEMA_IDFED,
-    		  PicketLinkFederationConstants.SCHEMA_IDFED_HANDLER};
-
-      Unmarshaller un = getUnmarshaller(schemas);
-      JAXBElement<Handlers> handlers = (JAXBElement<Handlers>) un.unmarshal(is);
-      return handlers.getValue(); */
+      if (is == null)
+         throw new IllegalArgumentException("inputstream is null");
       return (Handlers) (new SAMLConfigParser()).parse(is);
    }
 }
\ No newline at end of file



More information about the jboss-cvs-commits mailing list