[jboss-cvs] Picketlink SVN: r1528 - in social/trunk: openid/src/main/java/org/picketlink/social/openid and 13 other directories.

jboss-cvs-commits at lists.jboss.org jboss-cvs-commits at lists.jboss.org
Mon Mar 19 16:39:35 EDT 2012


Author: anil.saldhana at jboss.com
Date: 2012-03-19 16:39:31 -0400 (Mon, 19 Mar 2012)
New Revision: 1528

Modified:
   social/trunk/facebook/src/main/java/org/picketlink/social/facebook/FacebookAuthenticator.java
   social/trunk/facebook/src/main/java/org/picketlink/social/facebook/FacebookConstants.java
   social/trunk/facebook/src/main/java/org/picketlink/social/facebook/FacebookLoginModule.java
   social/trunk/facebook/src/main/java/org/picketlink/social/facebook/FacebookPrincipal.java
   social/trunk/facebook/src/main/java/org/picketlink/social/facebook/FacebookProcessor.java
   social/trunk/facebook/src/main/java/org/picketlink/social/facebook/FacebookUtil.java
   social/trunk/facebook/src/main/java/org/picketlink/social/facebook/OAuthConstants.java
   social/trunk/facebook/src/main/java/org/picketlink/social/facebook/SecurityActions.java
   social/trunk/openid/src/main/java/org/picketlink/social/openid/OpenIdPrincipal.java
   social/trunk/openid/src/main/java/org/picketlink/social/openid/api/OpenIDAttributeMap.java
   social/trunk/openid/src/main/java/org/picketlink/social/openid/api/OpenIDConstants.java
   social/trunk/openid/src/main/java/org/picketlink/social/openid/api/OpenIDLifecycle.java
   social/trunk/openid/src/main/java/org/picketlink/social/openid/api/OpenIDLifecycleEvent.java
   social/trunk/openid/src/main/java/org/picketlink/social/openid/api/OpenIDManager.java
   social/trunk/openid/src/main/java/org/picketlink/social/openid/api/OpenIDProtocolAdapter.java
   social/trunk/openid/src/main/java/org/picketlink/social/openid/api/OpenIDRequest.java
   social/trunk/openid/src/main/java/org/picketlink/social/openid/api/exceptions/OpenIDAssociationException.java
   social/trunk/openid/src/main/java/org/picketlink/social/openid/api/exceptions/OpenIDConsumerException.java
   social/trunk/openid/src/main/java/org/picketlink/social/openid/api/exceptions/OpenIDDiscoveryException.java
   social/trunk/openid/src/main/java/org/picketlink/social/openid/api/exceptions/OpenIDGeneralException.java
   social/trunk/openid/src/main/java/org/picketlink/social/openid/api/exceptions/OpenIDLifeCycleException.java
   social/trunk/openid/src/main/java/org/picketlink/social/openid/api/exceptions/OpenIDMessageException.java
   social/trunk/openid/src/main/java/org/picketlink/social/openid/api/exceptions/OpenIDProtocolException.java
   social/trunk/openid/src/main/java/org/picketlink/social/openid/auth/OpenIDConsumerAuthenticator.java
   social/trunk/openid/src/main/java/org/picketlink/social/openid/auth/OpenIDLoginModule.java
   social/trunk/openid/src/main/java/org/picketlink/social/openid/auth/OpenIDProcessor.java
   social/trunk/openid/src/main/java/org/picketlink/social/openid/auth/SecurityActions.java
   social/trunk/openid/src/main/java/org/picketlink/social/openid/constants/OpenIDAliasMapper.java
   social/trunk/openid/src/main/java/org/picketlink/social/openid/providers/OpenIDTokenProvider.java
   social/trunk/openid/src/main/java/org/picketlink/social/openid/providers/OpenIDVersion2TokenProvider.java
   social/trunk/openid/src/main/java/org/picketlink/social/openid/providers/helpers/OpenIDParameterList.java
   social/trunk/openid/src/main/java/org/picketlink/social/openid/providers/helpers/OpenIDProtocolContext.java
   social/trunk/openid/src/main/java/org/picketlink/social/openid/providers/helpers/OpenIDProviderManager.java
   social/trunk/openid/src/main/java/org/picketlink/social/openid/providers/helpers/OpenIDTokenRegistryStore.java
   social/trunk/openid/src/main/java/org/picketlink/social/openid/servlets/OpenIDConsumerServlet.java
   social/trunk/openid/src/main/java/org/picketlink/social/openid/servlets/OpenIDProviderServlet.java
   social/trunk/openid/src/main/java/org/picketlink/social/openid/servlets/OpenIDYadisServlet.java
   social/trunk/openid/src/main/java/org/picketlink/social/openid/servlets/SecurityActions.java
   social/trunk/openid/src/main/java/org/picketlink/social/openid/web/HTTPOpenIDContext.java
   social/trunk/openid/src/main/java/org/picketlink/social/openid/web/HTTPOpenIDProvider.java
   social/trunk/openid/src/main/java/org/picketlink/social/openid/web/HTTPProtocolAdaptor.java
   social/trunk/openid/src/test/java/org/picketlink/test/social/openid/EmbeddedWebServerBase.java
   social/trunk/openid/src/test/java/org/picketlink/test/social/openid/InMemoryProtocolAdapter.java
   social/trunk/openid/src/test/java/org/picketlink/test/social/openid/integration/LocalProviderOpenIDUnitTestCase.java
   social/trunk/openid/src/test/java/org/picketlink/test/social/openid/integration/YadisMetadataUnitTestCase.java
   social/trunk/openid/src/test/java/org/picketlink/test/social/openid/workflow/OpenIDWorkflowTestConsumerServlet.java
   social/trunk/openid/src/test/java/org/picketlink/test/social/openid/workflow/OpenIDWorkflowUnitTestCase.java
   social/trunk/openid/src/test/java/org/picketlink/test/social/openid/workflow/PrincipalInducingTestServletFilter.java
   social/trunk/social/src/main/java/org/picketlink/social/auth/ExternalAuthLoginModule.java
   social/trunk/social/src/main/java/org/picketlink/social/auth/ExternalAuthenticator.java
   social/trunk/social/src/main/java/org/picketlink/social/auth/SecurityActions.java
   social/trunk/social/src/main/java/org/picketlink/social/reg/RegistrationValve.java
   social/trunk/social/src/main/java/org/picketlink/social/reg/UserRegistration.java
Log:
format change. No functionality change

Modified: social/trunk/facebook/src/main/java/org/picketlink/social/facebook/FacebookAuthenticator.java
===================================================================
--- social/trunk/facebook/src/main/java/org/picketlink/social/facebook/FacebookAuthenticator.java	2012-03-19 20:36:39 UTC (rev 1527)
+++ social/trunk/facebook/src/main/java/org/picketlink/social/facebook/FacebookAuthenticator.java	2012-03-19 20:39:31 UTC (rev 1528)
@@ -2,7 +2,7 @@
  * JBoss, Home of Professional Open Source.
  * Copyright 2011, 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. 
+ * 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
@@ -44,266 +44,236 @@
 
 /**
  * Component for sending login requests to Facebook.
- * 
+ *
  * @author Anil Saldhana
  * @author Marcel Kolsteren
  * @since May 8, 2011
  */
-public class FacebookAuthenticator extends FormAuthenticator 
-{ 
-   protected static Logger log = Logger.getLogger(FacebookAuthenticator.class);
-   protected boolean trace = log.isTraceEnabled();
-   
-   protected String returnURL;
-   protected String clientID;
-   protected String clientSecret;
-   protected String scope = "email";
-   
-   protected List<String> roles = new ArrayList<String>();
-   
-   //Whether the authenticator has to to save and restore request
-   protected boolean saveRestoreRequest = true;
-   
-   private enum STATES { AUTH, AUTHZ, FINISH};
-   
-   protected FacebookProcessor processor;
-   
-   //Incompatibilities in register() method across JBossWeb versions
-   private Method theSuperRegisterMethod = null;
-     
-   public void setReturnURL(String returnURL)
-   {
-      this.returnURL = getSystemPropertyAsString(returnURL);
-   }
+public class FacebookAuthenticator extends FormAuthenticator {
+    protected static Logger log = Logger.getLogger(FacebookAuthenticator.class);
+    protected boolean trace = log.isTraceEnabled();
 
-   public void setClientID(String clientID)
-   {
-      this.clientID = clientID;
-   }
+    protected String returnURL;
+    protected String clientID;
+    protected String clientSecret;
+    protected String scope = "email";
 
-   public void setScope(String scope)
-   {
-      this.scope = scope;
-   }
+    protected List<String> roles = new ArrayList<String>();
 
-   public void setClientSecret(String clientSecret)
-   {
-      this.clientSecret = clientSecret;
-   }
+    // Whether the authenticator has to to save and restore request
+    protected boolean saveRestoreRequest = true;
 
-   /**
-    * A comma separated string that represents the roles the web app
-    * needs to pass authorization
-    * @param roleStr
-    */
-   public void setRoleString(String roleStr)
-   {
-      if(roleStr == null)
-         throw new RuntimeException("Role String is null in configuration");
-      StringTokenizer st = new StringTokenizer(roleStr, ",");
-      while(st.hasMoreElements())
-      {
-         roles.add(st.nextToken());
-      }
-   }
-   
-   public void setSaveRestoreRequest(boolean saveRestoreRequest)
-   {
-      this.saveRestoreRequest = saveRestoreRequest;
-   }
+    private enum STATES {
+        AUTH, AUTHZ, FINISH
+    };
 
-   public void start() throws LifecycleException
-   {
-      //Validate the input values
-      if(clientID == null)
-         throw new LifecycleException("clientID is not provided");
-      if(clientSecret == null)
-         throw new LifecycleException("clientSecret is not provided");
-      if(returnURL == null)
-         throw new LifecycleException("returnURL is not provided");
-      super.start();
-   }
+    protected FacebookProcessor processor;
 
-   public boolean authenticate(HttpServletRequest request, HttpServletResponse response, LoginConfig loginConfig) throws IOException
-   {
-      if(request instanceof Request == false)
-         throw new IOException("Not of type Catalina request");
-      if(response instanceof Response == false)
-         throw new IOException("Not of type Catalina response");
-      return authenticate((Request)request, (Response)response, loginConfig);
-   }
-   
-   /**
-    * Authenticate the request
-    * @param request
-    * @param response
-    * @param config
-    * @return
-    * @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
-   {
-      if (response instanceof Response)
-      {
-         Response catalinaResponse = (Response) response;
-         return authenticate(request, catalinaResponse, config);
-      }
-      throw new RuntimeException("Wrong type of response:"+response);
-   }
-    
-   public boolean authenticate(Request request, Response response, LoginConfig loginConfig) throws IOException
-   {  
-      if(trace) log.trace("authenticate");
-      
-      if(processor == null)
-         processor = new FacebookProcessor(clientID, clientSecret, scope, returnURL, roles);
-      
-      HttpSession session = request.getSession();
-      String state = (String) session.getAttribute("STATE");
-      
-      if(trace) log.trace("state="+ state);
-      
-      if( STATES.FINISH.name().equals(state))
-         return true;
-      
-      if( state == null || state.isEmpty())
-      { 
-         if (saveRestoreRequest)
-         {
-            this.saveRequest(request, request.getSessionInternal());
-         }
-         return processor.initialInteraction(request, response);
-      }
-      //We have sent an auth request
-      if( state.equals(STATES.AUTH.name()))
-      {
-         return processor.handleAuthStage(request, response);
-      }
-      
-      //Principal facebookPrincipal = null;
-      if( state.equals(STATES.AUTHZ.name()))
-      {  
-         Principal principal = processor.getPrincipal(request, response, context.getRealm());
+    // Incompatibilities in register() method across JBossWeb versions
+    private Method theSuperRegisterMethod = null;
 
-         if(principal == null)
-         { 
-        	 log.error("Principal was null. Maybe login modules need to be configured properly.");
-        	 response.sendError(HttpServletResponse.SC_FORBIDDEN);
-        	 return false;
-         }
-            
-         String userName = principal.getName();
-         
-         request.getSessionInternal().setNote(Constants.SESS_USERNAME_NOTE, userName);
-         request.getSessionInternal().setNote(Constants.SESS_PASSWORD_NOTE, "");
-         request.setUserPrincipal(principal);
+    public void setReturnURL(String returnURL) {
+        this.returnURL = getSystemPropertyAsString(returnURL);
+    }
 
-         if (saveRestoreRequest)
-         {
-            this.restoreRequest(request, request.getSessionInternal());
-         }
+    public void setClientID(String clientID) {
+        this.clientID = clientID;
+    }
 
-         registerWithAuthenticatorBase(request,response,principal,userName);
-         
-         request.getSession().setAttribute("STATE", STATES.FINISH.name());
+    public void setScope(String scope) {
+        this.scope = scope;
+    }
 
-         return true;
-      }
-      return false;
-   }
-   
+    public void setClientSecret(String clientSecret) {
+        this.clientSecret = clientSecret;
+    }
 
-   
-   protected void registerWithAuthenticatorBase(Request request, Response response, Principal principal, String userName)
-   {
-      try
-      {
-         register(request, response, principal, Constants.FORM_METHOD, userName, "");
-      }
-      catch(NoSuchMethodError nse)
-      { 
-         if(theSuperRegisterMethod == null)
-         {
-            Class<?>[] args = new Class[]
-            {Request.class, HttpServletResponse.class, Principal.class, String.class, String.class, String.class};
-            Class<?> superClass = getClass().getSuperclass();
-            theSuperRegisterMethod = SecurityActions.getMethod(superClass, "register", args);
-            
-         }
-         if(theSuperRegisterMethod != null)
-         {
-            Object[] objectArgs = new Object[] {request, response.getResponse(),
-                  principal, Constants.FORM_METHOD,
-                  userName, FacebookProcessor.EMPTY_PASSWORD };
-            try
-            {
-               theSuperRegisterMethod.invoke(this, objectArgs);
+    /**
+     * A comma separated string that represents the roles the web app needs to pass authorization
+     *
+     * @param roleStr
+     */
+    public void setRoleString(String roleStr) {
+        if (roleStr == null)
+            throw new RuntimeException("Role String is null in configuration");
+        StringTokenizer st = new StringTokenizer(roleStr, ",");
+        while (st.hasMoreElements()) {
+            roles.add(st.nextToken());
+        }
+    }
+
+    public void setSaveRestoreRequest(boolean saveRestoreRequest) {
+        this.saveRestoreRequest = saveRestoreRequest;
+    }
+
+    public void start() throws LifecycleException {
+        // Validate the input values
+        if (clientID == null)
+            throw new LifecycleException("clientID is not provided");
+        if (clientSecret == null)
+            throw new LifecycleException("clientSecret is not provided");
+        if (returnURL == null)
+            throw new LifecycleException("returnURL is not provided");
+        super.start();
+    }
+
+    public boolean authenticate(HttpServletRequest request, HttpServletResponse response, LoginConfig loginConfig)
+            throws IOException {
+        if (request instanceof Request == false)
+            throw new IOException("Not of type Catalina request");
+        if (response instanceof Response == false)
+            throw new IOException("Not of type Catalina response");
+        return authenticate((Request) request, (Response) response, loginConfig);
+    }
+
+    /**
+     * Authenticate the request
+     *
+     * @param request
+     * @param response
+     * @param config
+     * @return
+     * @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 {
+        if (response instanceof Response) {
+            Response catalinaResponse = (Response) response;
+            return authenticate(request, catalinaResponse, config);
+        }
+        throw new RuntimeException("Wrong type of response:" + response);
+    }
+
+    public boolean authenticate(Request request, Response response, LoginConfig loginConfig) throws IOException {
+        if (trace)
+            log.trace("authenticate");
+
+        if (processor == null)
+            processor = new FacebookProcessor(clientID, clientSecret, scope, returnURL, roles);
+
+        HttpSession session = request.getSession();
+        String state = (String) session.getAttribute("STATE");
+
+        if (trace)
+            log.trace("state=" + state);
+
+        if (STATES.FINISH.name().equals(state))
+            return true;
+
+        if (state == null || state.isEmpty()) {
+            if (saveRestoreRequest) {
+                this.saveRequest(request, request.getSessionInternal());
             }
-            catch (Exception e)
-            {
-               log.error("Unable to register:", e);
+            return processor.initialInteraction(request, response);
+        }
+        // We have sent an auth request
+        if (state.equals(STATES.AUTH.name())) {
+            return processor.handleAuthStage(request, response);
+        }
+
+        // Principal facebookPrincipal = null;
+        if (state.equals(STATES.AUTHZ.name())) {
+            Principal principal = processor.getPrincipal(request, response, context.getRealm());
+
+            if (principal == null) {
+                log.error("Principal was null. Maybe login modules need to be configured properly.");
+                response.sendError(HttpServletResponse.SC_FORBIDDEN);
+                return false;
             }
-         }
-      }
-   }
-   
-   /**
-    * <p>
-    * Get the system property value if the string is of the format ${sysproperty}
-    * </p>
-    * <p>
-    * You can insert default value when the system property is not set, by
-    * separating it at the beginning with ::
-    * </p>
-    * <p>
-    * <b>Examples:</b>
-    * </p>
-    * 
-    * <p>
-    * ${idp} should resolve to a value if the system property "idp" is set.
-    * </p>
-    * <p>
-    * ${idp::http://localhost:8080} will resolve to http://localhost:8080 if the system property "idp" is not set.
-    * </p>
-    * @param str
-    * @return
-    */
-   protected String getSystemPropertyAsString(String str)
-   {
-      if (str == null)
-         throw new IllegalArgumentException("str is null");
-      if (str.contains("${"))
-      {
-         Pattern pattern = Pattern.compile("\\$\\{([^}]+)}");
-         Matcher matcher = pattern.matcher(str);
 
-         StringBuffer buffer = new StringBuffer();
-         String sysPropertyValue = null;
+            String userName = principal.getName();
 
-         while (matcher.find())
-         {
-            String subString = matcher.group(1);
-            String defaultValue = "";
+            request.getSessionInternal().setNote(Constants.SESS_USERNAME_NOTE, userName);
+            request.getSessionInternal().setNote(Constants.SESS_PASSWORD_NOTE, "");
+            request.setUserPrincipal(principal);
 
-            //Look for default value
-            if (subString.contains("::"))
-            {
-               int index = subString.indexOf("::");
-               defaultValue = subString.substring(index + 2);
-               subString = subString.substring(0, index);
+            if (saveRestoreRequest) {
+                this.restoreRequest(request, request.getSessionInternal());
             }
-            sysPropertyValue = SecurityActions.getSystemProperty(subString, defaultValue);
-            if (sysPropertyValue.isEmpty())
-            {
-               throw new IllegalArgumentException(matcher.group(1) + " is missing in system properties");
+
+            registerWithAuthenticatorBase(request, response, principal, userName);
+
+            request.getSession().setAttribute("STATE", STATES.FINISH.name());
+
+            return true;
+        }
+        return false;
+    }
+
+    protected void registerWithAuthenticatorBase(Request request, Response response, Principal principal, String userName) {
+        try {
+            register(request, response, principal, Constants.FORM_METHOD, userName, "");
+        } catch (NoSuchMethodError nse) {
+            if (theSuperRegisterMethod == null) {
+                Class<?>[] args = new Class[] { Request.class, HttpServletResponse.class, Principal.class, String.class,
+                        String.class, String.class };
+                Class<?> superClass = getClass().getSuperclass();
+                theSuperRegisterMethod = SecurityActions.getMethod(superClass, "register", args);
+
             }
-            matcher.appendReplacement(buffer, sysPropertyValue);
-         }
+            if (theSuperRegisterMethod != null) {
+                Object[] objectArgs = new Object[] { request, response.getResponse(), principal, Constants.FORM_METHOD,
+                        userName, FacebookProcessor.EMPTY_PASSWORD };
+                try {
+                    theSuperRegisterMethod.invoke(this, objectArgs);
+                } catch (Exception e) {
+                    log.error("Unable to register:", e);
+                }
+            }
+        }
+    }
 
-         matcher.appendTail(buffer);
-         str = buffer.toString();
-      }
-      return str;
-   }
+    /**
+     * <p>
+     * Get the system property value if the string is of the format ${sysproperty}
+     * </p>
+     * <p>
+     * You can insert default value when the system property is not set, by separating it at the beginning with ::
+     * </p>
+     * <p>
+     * <b>Examples:</b>
+     * </p>
+     *
+     * <p>
+     * ${idp} should resolve to a value if the system property "idp" is set.
+     * </p>
+     * <p>
+     * ${idp::http://localhost:8080} will resolve to http://localhost:8080 if the system property "idp" is not set.
+     * </p>
+     *
+     * @param str
+     * @return
+     */
+    protected String getSystemPropertyAsString(String str) {
+        if (str == null)
+            throw new IllegalArgumentException("str is null");
+        if (str.contains("${")) {
+            Pattern pattern = Pattern.compile("\\$\\{([^}]+)}");
+            Matcher matcher = pattern.matcher(str);
+
+            StringBuffer buffer = new StringBuffer();
+            String sysPropertyValue = null;
+
+            while (matcher.find()) {
+                String subString = matcher.group(1);
+                String defaultValue = "";
+
+                // Look for default value
+                if (subString.contains("::")) {
+                    int index = subString.indexOf("::");
+                    defaultValue = subString.substring(index + 2);
+                    subString = subString.substring(0, index);
+                }
+                sysPropertyValue = SecurityActions.getSystemProperty(subString, defaultValue);
+                if (sysPropertyValue.isEmpty()) {
+                    throw new IllegalArgumentException(matcher.group(1) + " is missing in system properties");
+                }
+                matcher.appendReplacement(buffer, sysPropertyValue);
+            }
+
+            matcher.appendTail(buffer);
+            str = buffer.toString();
+        }
+        return str;
+    }
 }
\ No newline at end of file

Modified: social/trunk/facebook/src/main/java/org/picketlink/social/facebook/FacebookConstants.java
===================================================================
--- social/trunk/facebook/src/main/java/org/picketlink/social/facebook/FacebookConstants.java	2012-03-19 20:36:39 UTC (rev 1527)
+++ social/trunk/facebook/src/main/java/org/picketlink/social/facebook/FacebookConstants.java	2012-03-19 20:39:31 UTC (rev 1528)
@@ -1,47 +1,47 @@
 /*
-* 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.
-*/
+ * 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.social.facebook;
 
 /**
  * Constants for facebook
-* @author Marcel Kolsteren
-* @author anil saldhana
-* @since Sep 26, 2010
-*/
-public class FacebookConstants
-{
-   public static final String AUTHENTICATION_ENDPOINT_URL = "https://graph.facebook.com/oauth/authorize";
+ *
+ * @author Marcel Kolsteren
+ * @author anil saldhana
+ * @since Sep 26, 2010
+ */
+public class FacebookConstants {
+    public static final String AUTHENTICATION_ENDPOINT_URL = "https://graph.facebook.com/oauth/authorize";
 
-   public static final String ACCESS_TOKEN_ENDPOINT_URL = "https://graph.facebook.com/oauth/access_token";
+    public static final String ACCESS_TOKEN_ENDPOINT_URL = "https://graph.facebook.com/oauth/access_token";
 
-   public static final String PROFILE_ENDPOINT_URL = "https://graph.facebook.com/me";
-   
-   public static final String RETURN_URL_PARAMETER = "returnUrl";
-   
-   public static final String SERVICE_URL = "https://www.facebook.com/dialog/oauth";
-   
-   public static final String TYPE = "type";
-   
-   public static final String WEB_SERVER = "web_server";
-   
-   public static final String EXPIRES = "expires";
+    public static final String PROFILE_ENDPOINT_URL = "https://graph.facebook.com/me";
+
+    public static final String RETURN_URL_PARAMETER = "returnUrl";
+
+    public static final String SERVICE_URL = "https://www.facebook.com/dialog/oauth";
+
+    public static final String TYPE = "type";
+
+    public static final String WEB_SERVER = "web_server";
+
+    public static final String EXPIRES = "expires";
 }

Modified: social/trunk/facebook/src/main/java/org/picketlink/social/facebook/FacebookLoginModule.java
===================================================================
--- social/trunk/facebook/src/main/java/org/picketlink/social/facebook/FacebookLoginModule.java	2012-03-19 20:36:39 UTC (rev 1527)
+++ social/trunk/facebook/src/main/java/org/picketlink/social/facebook/FacebookLoginModule.java	2012-03-19 20:39:31 UTC (rev 1528)
@@ -2,7 +2,7 @@
  * JBoss, Home of Professional Open Source.
  * Copyright 2011, 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. 
+ * 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
@@ -34,37 +34,32 @@
 
 /**
  * A {@link LoginModule} for JBoss environment to support facebook authentication
+ *
  * @author Anil Saldhana
  * @since May 19, 2011
  */
-public class FacebookLoginModule extends UsernamePasswordLoginModule
-{ 
-   @Override
-   protected Principal getIdentity()
-   {
-      return FacebookProcessor.cachedPrincipal.get();
-   }
+public class FacebookLoginModule extends UsernamePasswordLoginModule {
+    @Override
+    protected Principal getIdentity() {
+        return FacebookProcessor.cachedPrincipal.get();
+    }
 
-   @Override
-   protected String getUsersPassword() throws LoginException
-   {
-      return FacebookProcessor.EMPTY_PASSWORD;
-   }
+    @Override
+    protected String getUsersPassword() throws LoginException {
+        return FacebookProcessor.EMPTY_PASSWORD;
+    }
 
-   @Override
-   protected Group[] getRoleSets() throws LoginException
-   {   
-      Group group = new SimpleGroup("Roles"); 
+    @Override
+    protected Group[] getRoleSets() throws LoginException {
+        Group group = new SimpleGroup("Roles");
 
-      List<String> roles = FacebookProcessor.cachedRoles.get();
+        List<String> roles = FacebookProcessor.cachedRoles.get();
 
-      if(roles != null)
-      {
-         for(String role: roles)
-         {
-            group.addMember(new SimplePrincipal(role));
-         }
-      }
-      return new Group[] {group};
-   }
+        if (roles != null) {
+            for (String role : roles) {
+                group.addMember(new SimplePrincipal(role));
+            }
+        }
+        return new Group[] { group };
+    }
 }
\ No newline at end of file

Modified: social/trunk/facebook/src/main/java/org/picketlink/social/facebook/FacebookPrincipal.java
===================================================================
--- social/trunk/facebook/src/main/java/org/picketlink/social/facebook/FacebookPrincipal.java	2012-03-19 20:36:39 UTC (rev 1527)
+++ social/trunk/facebook/src/main/java/org/picketlink/social/facebook/FacebookPrincipal.java	2012-03-19 20:39:31 UTC (rev 1528)
@@ -1,24 +1,24 @@
 /*
-* 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.
-*/
+ * 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.social.facebook;
 
 import java.io.Serializable;
@@ -26,125 +26,106 @@
 
 /**
  * An instance of {@link Principal} representing a facebook user
-* @author Marcel Kolsteren
-* @since Sep 26, 2010
-*/
-public class FacebookPrincipal implements Principal, Serializable
-{ 
-   private static final long serialVersionUID = 8086364702249670998L;
+ *
+ * @author Marcel Kolsteren
+ * @since Sep 26, 2010
+ */
+public class FacebookPrincipal implements Principal, Serializable {
+    private static final long serialVersionUID = 8086364702249670998L;
 
-   private String accessToken;
+    private String accessToken;
 
-   private String id;
+    private String id;
 
-   private String name;
+    private String name;
 
-   private String firstName;
+    private String firstName;
 
-   private String lastName;
+    private String lastName;
 
-   private String gender;
+    private String gender;
 
-   private String timezone;
+    private String timezone;
 
-   private String locale;
+    private String locale;
 
-   private String email;
+    private String email;
 
-   public String getAccessToken()
-   {
-      return accessToken;
-   }
+    public String getAccessToken() {
+        return accessToken;
+    }
 
-   public void setAccessToken(String accessToken)
-   {
-      this.accessToken = accessToken;
-   }
+    public void setAccessToken(String accessToken) {
+        this.accessToken = accessToken;
+    }
 
-   public String getId()
-   {
-      return id;
-   }
+    public String getId() {
+        return id;
+    }
 
-   public void setId(String id)
-   {
-      this.id = id;
-   }
+    public void setId(String id) {
+        this.id = id;
+    }
 
-   public String getFirstName()
-   {
-      return firstName;
-   }
+    public String getFirstName() {
+        return firstName;
+    }
 
-   public void setFirstName(String firstName)
-   {
-      this.firstName = firstName;
-   }
+    public void setFirstName(String firstName) {
+        this.firstName = firstName;
+    }
 
-   public String getLastName()
-   {
-      return lastName;
-   }
+    public String getLastName() {
+        return lastName;
+    }
 
-   public void setLastName(String lastName)
-   {
-      this.lastName = lastName;
-   }
+    public void setLastName(String lastName) {
+        this.lastName = lastName;
+    }
 
-   public String getGender()
-   {
-      return gender;
-   }
+    public String getGender() {
+        return gender;
+    }
 
-   public void setGender(String gender)
-   {
-      this.gender = gender;
-   }
+    public void setGender(String gender) {
+        this.gender = gender;
+    }
 
-   public String getTimezone()
-   {
-      return timezone;
-   }
+    public String getTimezone() {
+        return timezone;
+    }
 
-   public void setTimezone(String timezone)
-   {
-      this.timezone = timezone;
-   }
+    public void setTimezone(String timezone) {
+        this.timezone = timezone;
+    }
 
-   public String getLocale()
-   {
-      return locale;
-   }
+    public String getLocale() {
+        return locale;
+    }
 
-   public void setLocale(String locale)
-   {
-      this.locale = locale;
-   }
+    public void setLocale(String locale) {
+        this.locale = locale;
+    }
 
-   public void setName(String name)
-   {
-      this.name = name;
-   }
+    public void setName(String name) {
+        this.name = name;
+    }
 
-   public String getName()
-   {
-      return name;
-   }
+    public String getName() {
+        return name;
+    }
 
-   public String getEmail()
-   {
-      return email;
-   }
+    public String getEmail() {
+        return email;
+    }
 
-   public void setEmail(String email)
-   {
-      this.email = email;
-   }
+    public void setEmail(String email) {
+        this.email = email;
+    }
 
-   @Override
-   public String toString()
-   {
-      return "FacebookPrincipal [id=" + id + ", name=" + name + ", firstName=" + firstName + ", lastName=" + lastName
-            + ", gender=" + gender + ", timezone=" + timezone + ", locale=" + locale + ", email=" + email + "]";
-   }
+    @Override
+    public String toString() {
+        return "FacebookPrincipal [id=" + id + ", name=" + name + ", firstName=" + firstName + ", lastName=" + lastName
+                + ", gender=" + gender + ", timezone=" + timezone + ", locale=" + locale + ", email=" + email + "]";
+    }
 }
\ No newline at end of file

Modified: social/trunk/facebook/src/main/java/org/picketlink/social/facebook/FacebookProcessor.java
===================================================================
--- social/trunk/facebook/src/main/java/org/picketlink/social/facebook/FacebookProcessor.java	2012-03-19 20:36:39 UTC (rev 1527)
+++ social/trunk/facebook/src/main/java/org/picketlink/social/facebook/FacebookProcessor.java	2012-03-19 20:39:31 UTC (rev 1528)
@@ -2,7 +2,7 @@
  * JBoss, Home of Professional Open Source.
  * Copyright 2011, 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. 
+ * 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
@@ -50,286 +50,244 @@
 
 /**
  * Processor to perform Facebook interaction
+ *
  * @author Anil Saldhana
  * @since Sep 22, 2011
  */
-public class FacebookProcessor
-{ 
-   protected static Logger log = Logger.getLogger(FacebookProcessor.class);
-   protected boolean trace = log.isTraceEnabled();
+public class FacebookProcessor {
+    protected static Logger log = Logger.getLogger(FacebookProcessor.class);
+    protected boolean trace = log.isTraceEnabled();
 
-   protected  FacebookUtil util = new FacebookUtil(FacebookConstants.SERVICE_URL);
-   
-   public static ThreadLocal<Principal> cachedPrincipal = new ThreadLocal<Principal>();
-   
-   public static ThreadLocal<List<String>> cachedRoles = new ThreadLocal<List<String>>();
-   public static String EMPTY_PASSWORD = "EMPTY";
-   
-   protected List<String> roles = new ArrayList<String>();
-   
-   public enum STATES { AUTH, AUTHZ, FINISH};
-   
-   protected String clientID;
-   protected String clientSecret;
-   protected String scope;
-   private String returnURL;
-   
-   public FacebookProcessor(String clientID, String clientSecret, String scope, String returnURL, List<String> requiredRoles)
-   {
-      super();
-      this.clientID = clientID;
-      this.clientSecret = clientSecret;
-      this.scope = scope;
-      this.returnURL = returnURL;
-      this.roles.addAll(requiredRoles);
-   }
-   
-   public void setRoleString(String roleStr)
-   {
-      if(roleStr == null)
-         throw new RuntimeException("Role String is null in configuration");
-      StringTokenizer st = new StringTokenizer(roleStr, ",");
-      while(st.hasMoreElements())
-      {
-         roles.add(st.nextToken());
-      }
-   }
-   
-   public boolean initialInteraction(Request request, Response response) throws IOException
-   {  
-      HttpSession session = request.getSession();
-      Map<String, String> params = new HashMap<String, String>();
-      params.put(OAuthConstants.REDIRECT_URI_PARAMETER, returnURL);
-      params.put(OAuthConstants.CLIENT_ID_PARAMETER, clientID);
-      
-      if (scope != null)
-      {
-         params.put(OAuthConstants.SCOPE_PARAMETER, scope);
-      }
-      
-      String location = new StringBuilder(FacebookConstants.SERVICE_URL).append("?").append(
-            util.createQueryString(params)).toString();
-      try
-      { 
-         session.setAttribute("STATE", STATES.AUTH.name());
-         if(trace) log.trace("Redirect:"+location);
-         response.sendRedirect(location);
-         return false;
-      }
-      catch (IOException e)
-      {
-         throw new RuntimeException(e);
-      }
-   }
-   
-   public boolean handleAuthStage(HttpServletRequest request, HttpServletResponse response)
-   {
-      request.getSession().setAttribute("STATE",STATES.AUTHZ.name());
-      sendAuthorizeRequest(this.returnURL, response);
-      return false;
-   }
-   
-   protected void sendAuthorizeRequest(String returnUrl, HttpServletResponse response)
-   {  
-      String returnUri = returnUrl;
-      
-      Map<String, String> params = new HashMap<String, String>();
-      params.put(OAuthConstants.REDIRECT_URI_PARAMETER, returnUri);
-      params.put(OAuthConstants.CLIENT_ID_PARAMETER, clientID);
-      if (scope != null)
-      {
-         params.put(OAuthConstants.SCOPE_PARAMETER, scope);
-      }
-      String location = new StringBuilder(FacebookConstants.AUTHENTICATION_ENDPOINT_URL).append("?").append(
-            util.createQueryString(params)).toString();
-      try
-      {
-         response.sendRedirect(location);
-      }
-      catch (IOException e)
-      {
-         throw new RuntimeException(e);
-      }
-   }
-   
-   public Principal getPrincipal(Request request, Response response, Realm realm)
-   {
-      Principal principal = null;
-      Principal facebookPrincipal = handleAuthenticationResponse(request, response);
-      if(facebookPrincipal == null)
-    	  return null;
+    protected FacebookUtil util = new FacebookUtil(FacebookConstants.SERVICE_URL);
 
-      request.getSession().setAttribute("PRINCIPAL", facebookPrincipal);
-      cachedPrincipal.set(facebookPrincipal);
-      
-      if(isJBossEnv())
-      {
-         cachedRoles.set(roles);
-         principal = realm.authenticate(facebookPrincipal.getName(), EMPTY_PASSWORD); 
-      }
-      else
-      { 
-         //Create a Tomcat Generic Principal
-         principal = new GenericPrincipal(realm, facebookPrincipal.getName(), null, roles, facebookPrincipal);
-      }
-      return principal;
-   }
-   
-   protected Principal handleAuthenticationResponse(HttpServletRequest request, HttpServletResponse response)
-   {
-      String error = request.getParameter(OAuthConstants.ERROR_PARAMETER);
-      if (error != null)
-      {
-         throw new RuntimeException("error:" + error);
-      }
-      else
-      {
-         String returnUrl = returnURL;
-         String authorizationCode = request.getParameter(OAuthConstants.CODE_PARAMETER);
-         if (authorizationCode == null)
-         {
-            log.error("Authorization code parameter not found");
+    public static ThreadLocal<Principal> cachedPrincipal = new ThreadLocal<Principal>();
+
+    public static ThreadLocal<List<String>> cachedRoles = new ThreadLocal<List<String>>();
+    public static String EMPTY_PASSWORD = "EMPTY";
+
+    protected List<String> roles = new ArrayList<String>();
+
+    public enum STATES {
+        AUTH, AUTHZ, FINISH
+    };
+
+    protected String clientID;
+    protected String clientSecret;
+    protected String scope;
+    private String returnURL;
+
+    public FacebookProcessor(String clientID, String clientSecret, String scope, String returnURL, List<String> requiredRoles) {
+        super();
+        this.clientID = clientID;
+        this.clientSecret = clientSecret;
+        this.scope = scope;
+        this.returnURL = returnURL;
+        this.roles.addAll(requiredRoles);
+    }
+
+    public void setRoleString(String roleStr) {
+        if (roleStr == null)
+            throw new RuntimeException("Role String is null in configuration");
+        StringTokenizer st = new StringTokenizer(roleStr, ",");
+        while (st.hasMoreElements()) {
+            roles.add(st.nextToken());
+        }
+    }
+
+    public boolean initialInteraction(Request request, Response response) throws IOException {
+        HttpSession session = request.getSession();
+        Map<String, String> params = new HashMap<String, String>();
+        params.put(OAuthConstants.REDIRECT_URI_PARAMETER, returnURL);
+        params.put(OAuthConstants.CLIENT_ID_PARAMETER, clientID);
+
+        if (scope != null) {
+            params.put(OAuthConstants.SCOPE_PARAMETER, scope);
+        }
+
+        String location = new StringBuilder(FacebookConstants.SERVICE_URL).append("?").append(util.createQueryString(params))
+                .toString();
+        try {
+            session.setAttribute("STATE", STATES.AUTH.name());
+            if (trace)
+                log.trace("Redirect:" + location);
+            response.sendRedirect(location);
+            return false;
+        } catch (IOException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    public boolean handleAuthStage(HttpServletRequest request, HttpServletResponse response) {
+        request.getSession().setAttribute("STATE", STATES.AUTHZ.name());
+        sendAuthorizeRequest(this.returnURL, response);
+        return false;
+    }
+
+    protected void sendAuthorizeRequest(String returnUrl, HttpServletResponse response) {
+        String returnUri = returnUrl;
+
+        Map<String, String> params = new HashMap<String, String>();
+        params.put(OAuthConstants.REDIRECT_URI_PARAMETER, returnUri);
+        params.put(OAuthConstants.CLIENT_ID_PARAMETER, clientID);
+        if (scope != null) {
+            params.put(OAuthConstants.SCOPE_PARAMETER, scope);
+        }
+        String location = new StringBuilder(FacebookConstants.AUTHENTICATION_ENDPOINT_URL).append("?")
+                .append(util.createQueryString(params)).toString();
+        try {
+            response.sendRedirect(location);
+        } catch (IOException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    public Principal getPrincipal(Request request, Response response, Realm realm) {
+        Principal principal = null;
+        Principal facebookPrincipal = handleAuthenticationResponse(request, response);
+        if (facebookPrincipal == null)
             return null;
-         }
 
-         URLConnection connection = sendAccessTokenRequest(returnUrl, authorizationCode, response);
+        request.getSession().setAttribute("PRINCIPAL", facebookPrincipal);
+        cachedPrincipal.set(facebookPrincipal);
 
-         Map<String, String> params = formUrlDecode(readUrlContent(connection));
-         String accessToken = params.get(OAuthConstants.ACCESS_TOKEN_PARAMETER);
-         String expires = params.get(FacebookConstants.EXPIRES);
-         
-         if(trace) log.trace("Access Token=" + accessToken + " :: Expires=" + expires);
-         
-         if (accessToken == null)
-         {
-            throw new RuntimeException("No access token found");
-         } 
-         
-         return readInIdentity(request, response, accessToken, returnUrl);
-      } 
-   }
-   
-   protected URLConnection sendAccessTokenRequest(String returnUrl, String authorizationCode, HttpServletResponse response)
-   { 
-      String returnUri = returnURL;
+        if (isJBossEnv()) {
+            cachedRoles.set(roles);
+            principal = realm.authenticate(facebookPrincipal.getName(), EMPTY_PASSWORD);
+        } else {
+            // Create a Tomcat Generic Principal
+            principal = new GenericPrincipal(realm, facebookPrincipal.getName(), null, roles, facebookPrincipal);
+        }
+        return principal;
+    }
 
-      Map<String, String> params = new HashMap<String, String>();
-      params.put(OAuthConstants.REDIRECT_URI_PARAMETER, returnUri);
-      params.put(OAuthConstants.CLIENT_ID_PARAMETER, clientID);
-      params.put(OAuthConstants.CLIENT_SECRET_PARAMETER, clientSecret);
-      params.put(OAuthConstants.CODE_PARAMETER, authorizationCode);
-      
-      String location = new StringBuilder(FacebookConstants.ACCESS_TOKEN_ENDPOINT_URL).append("?").append(
-            util.createQueryString(params)).toString();
+    protected Principal handleAuthenticationResponse(HttpServletRequest request, HttpServletResponse response) {
+        String error = request.getParameter(OAuthConstants.ERROR_PARAMETER);
+        if (error != null) {
+            throw new RuntimeException("error:" + error);
+        } else {
+            String returnUrl = returnURL;
+            String authorizationCode = request.getParameter(OAuthConstants.CODE_PARAMETER);
+            if (authorizationCode == null) {
+                log.error("Authorization code parameter not found");
+                return null;
+            }
 
-      try
-      {
-         if(trace) log.trace("AccessToken Request="+location);
-         URL url = new URL(location);
-         URLConnection connection = url.openConnection();
-         return connection;
-      }
-      catch (IOException e)
-      {
-         throw new RuntimeException(e);
-      }
-   }
-   
-   private boolean isJBossEnv()
-   {
-      Class<?> clazz = SecurityActions.loadClass(getClass(), "org.jboss.as.web.WebServer");
-      if(clazz == null)
-    	  clazz = SecurityActions.loadClass(getClass(), "org.jboss.system.Service");
-      if( clazz != null )
-         return true;
-      return false;
-   }
-   
-   private Principal readInIdentity(HttpServletRequest request, HttpServletResponse response, String accessToken, String returnUrl)
-   {
-      FacebookPrincipal facebookPrincipal = null;
-      try
-      {
-         String urlString = new StringBuilder(FacebookConstants.PROFILE_ENDPOINT_URL).append("?access_token=").append(
-               URLEncoder.encode(accessToken, "UTF-8")).toString();
-         if(trace) log.trace("Profile read:"+urlString);
-         
-         URL profileUrl = new URL(urlString);
-         String profileContent = readUrlContent(profileUrl.openConnection());
-         JSONObject jsonObject = new JSONObject(profileContent);
+            URLConnection connection = sendAccessTokenRequest(returnUrl, authorizationCode, response);
 
-         facebookPrincipal = new FacebookPrincipal();
-         facebookPrincipal.setAccessToken(accessToken);
-         facebookPrincipal.setId(jsonObject.getString("id"));
-         facebookPrincipal.setName(jsonObject.getString("name"));
-         facebookPrincipal.setFirstName(jsonObject.getString("first_name"));
-         facebookPrincipal.setLastName(jsonObject.getString("last_name"));
-         facebookPrincipal.setGender(jsonObject.getString("gender"));
-         facebookPrincipal.setTimezone(jsonObject.getString("timezone"));
-         facebookPrincipal.setLocale(jsonObject.getString("locale"));
-         if (jsonObject.getString("email") != null)
-         {
-            facebookPrincipal.setEmail(jsonObject.getString("email"));
-         }
-      }
-      catch (JSONException e)
-      {
-         throw new RuntimeException(e);
-      }
-      catch (IOException e)
-      {
-         throw new RuntimeException(e);
-      }
-      
-      return facebookPrincipal;
-   }
-   
-   private String readUrlContent(URLConnection connection)
-   {
-      StringBuilder result = new StringBuilder();
-      try
-      {
-         Reader reader = new InputStreamReader(connection.getInputStream());
-         char[] buffer = new char[50];
-         int nrOfChars;
-         while ((nrOfChars = reader.read(buffer)) != -1)
-         {
-            result.append(buffer, 0, nrOfChars);
-         }
-      }
-      catch (IOException e)
-      {
-         throw new RuntimeException(e);
-      }
-      return result.toString();
-   }
-   
-   private Map<String, String> formUrlDecode(String encodedData)
-   {
-      Map<String, String> params = new HashMap<String, String>();
-      String[] elements = encodedData.split("&");
-      for (String element : elements)
-      {
-         String[] pair = element.split("=");
-         if (pair.length == 2)
-         {
-            String paramName = pair[0];
-            String paramValue;
-            try
-            {
-               paramValue = URLDecoder.decode(pair[1], "UTF-8");
+            Map<String, String> params = formUrlDecode(readUrlContent(connection));
+            String accessToken = params.get(OAuthConstants.ACCESS_TOKEN_PARAMETER);
+            String expires = params.get(FacebookConstants.EXPIRES);
+
+            if (trace)
+                log.trace("Access Token=" + accessToken + " :: Expires=" + expires);
+
+            if (accessToken == null) {
+                throw new RuntimeException("No access token found");
             }
-            catch (UnsupportedEncodingException e)
-            {
-               throw new RuntimeException(e);
+
+            return readInIdentity(request, response, accessToken, returnUrl);
+        }
+    }
+
+    protected URLConnection sendAccessTokenRequest(String returnUrl, String authorizationCode, HttpServletResponse response) {
+        String returnUri = returnURL;
+
+        Map<String, String> params = new HashMap<String, String>();
+        params.put(OAuthConstants.REDIRECT_URI_PARAMETER, returnUri);
+        params.put(OAuthConstants.CLIENT_ID_PARAMETER, clientID);
+        params.put(OAuthConstants.CLIENT_SECRET_PARAMETER, clientSecret);
+        params.put(OAuthConstants.CODE_PARAMETER, authorizationCode);
+
+        String location = new StringBuilder(FacebookConstants.ACCESS_TOKEN_ENDPOINT_URL).append("?")
+                .append(util.createQueryString(params)).toString();
+
+        try {
+            if (trace)
+                log.trace("AccessToken Request=" + location);
+            URL url = new URL(location);
+            URLConnection connection = url.openConnection();
+            return connection;
+        } catch (IOException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    private boolean isJBossEnv() {
+        Class<?> clazz = SecurityActions.loadClass(getClass(), "org.jboss.as.web.WebServer");
+        if (clazz == null)
+            clazz = SecurityActions.loadClass(getClass(), "org.jboss.system.Service");
+        if (clazz != null)
+            return true;
+        return false;
+    }
+
+    private Principal readInIdentity(HttpServletRequest request, HttpServletResponse response, String accessToken,
+            String returnUrl) {
+        FacebookPrincipal facebookPrincipal = null;
+        try {
+            String urlString = new StringBuilder(FacebookConstants.PROFILE_ENDPOINT_URL).append("?access_token=")
+                    .append(URLEncoder.encode(accessToken, "UTF-8")).toString();
+            if (trace)
+                log.trace("Profile read:" + urlString);
+
+            URL profileUrl = new URL(urlString);
+            String profileContent = readUrlContent(profileUrl.openConnection());
+            JSONObject jsonObject = new JSONObject(profileContent);
+
+            facebookPrincipal = new FacebookPrincipal();
+            facebookPrincipal.setAccessToken(accessToken);
+            facebookPrincipal.setId(jsonObject.getString("id"));
+            facebookPrincipal.setName(jsonObject.getString("name"));
+            facebookPrincipal.setFirstName(jsonObject.getString("first_name"));
+            facebookPrincipal.setLastName(jsonObject.getString("last_name"));
+            facebookPrincipal.setGender(jsonObject.getString("gender"));
+            facebookPrincipal.setTimezone(jsonObject.getString("timezone"));
+            facebookPrincipal.setLocale(jsonObject.getString("locale"));
+            if (jsonObject.getString("email") != null) {
+                facebookPrincipal.setEmail(jsonObject.getString("email"));
             }
-            params.put(paramName, paramValue);
-         }
-         else
-         {
-            throw new RuntimeException("Unexpected name-value pair in response: " + element);
-         }
-      }
-      return params;
-   }
+        } catch (JSONException e) {
+            throw new RuntimeException(e);
+        } catch (IOException e) {
+            throw new RuntimeException(e);
+        }
+
+        return facebookPrincipal;
+    }
+
+    private String readUrlContent(URLConnection connection) {
+        StringBuilder result = new StringBuilder();
+        try {
+            Reader reader = new InputStreamReader(connection.getInputStream());
+            char[] buffer = new char[50];
+            int nrOfChars;
+            while ((nrOfChars = reader.read(buffer)) != -1) {
+                result.append(buffer, 0, nrOfChars);
+            }
+        } catch (IOException e) {
+            throw new RuntimeException(e);
+        }
+        return result.toString();
+    }
+
+    private Map<String, String> formUrlDecode(String encodedData) {
+        Map<String, String> params = new HashMap<String, String>();
+        String[] elements = encodedData.split("&");
+        for (String element : elements) {
+            String[] pair = element.split("=");
+            if (pair.length == 2) {
+                String paramName = pair[0];
+                String paramValue;
+                try {
+                    paramValue = URLDecoder.decode(pair[1], "UTF-8");
+                } catch (UnsupportedEncodingException e) {
+                    throw new RuntimeException(e);
+                }
+                params.put(paramName, paramValue);
+            } else {
+                throw new RuntimeException("Unexpected name-value pair in response: " + element);
+            }
+        }
+        return params;
+    }
 }
\ No newline at end of file

Modified: social/trunk/facebook/src/main/java/org/picketlink/social/facebook/FacebookUtil.java
===================================================================
--- social/trunk/facebook/src/main/java/org/picketlink/social/facebook/FacebookUtil.java	2012-03-19 20:36:39 UTC (rev 1527)
+++ social/trunk/facebook/src/main/java/org/picketlink/social/facebook/FacebookUtil.java	2012-03-19 20:39:31 UTC (rev 1528)
@@ -2,7 +2,7 @@
  * JBoss, Home of Professional Open Source.
  * Copyright 2011, 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. 
+ * 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
@@ -27,53 +27,45 @@
 
 /**
  * Utility for facebook
+ *
  * @author Anil Saldhana
  * @since May 8, 2011
  */
-public class FacebookUtil
-{
-   protected String serviceURL = null;
-   
-   public FacebookUtil(String url)
-   {
-      this.serviceURL = url;
-   }
-   
-   /**
-    * Given a {@link Map} of params, construct a query string
-    * @param params
-    * @return
-    */
-   public String createQueryString(Map<String, String> params)
-   {
-      StringBuilder queryString = new StringBuilder();
-      boolean first = true;
-      for (Map.Entry<String, String> entry : params.entrySet())
-      {
-         String paramName = entry.getKey();
-         String paramValue = entry.getValue();
-         if (first)
-         {
-            first = false;
-         }
-         else
-         {
-            queryString.append("&");
-         }
-         queryString.append(paramName).append("=");
-         String encodedParamValue;
-         try
-         {
-            if(paramValue == null)
-               throw new RuntimeException("paramValue is null");
-            encodedParamValue = URLEncoder.encode(paramValue, "UTF-8");
-         }
-         catch (UnsupportedEncodingException e)
-         {
-            throw new RuntimeException(e);
-         }
-         queryString.append(encodedParamValue);
-      }
-      return queryString.toString();
-   }
+public class FacebookUtil {
+    protected String serviceURL = null;
+
+    public FacebookUtil(String url) {
+        this.serviceURL = url;
+    }
+
+    /**
+     * Given a {@link Map} of params, construct a query string
+     *
+     * @param params
+     * @return
+     */
+    public String createQueryString(Map<String, String> params) {
+        StringBuilder queryString = new StringBuilder();
+        boolean first = true;
+        for (Map.Entry<String, String> entry : params.entrySet()) {
+            String paramName = entry.getKey();
+            String paramValue = entry.getValue();
+            if (first) {
+                first = false;
+            } else {
+                queryString.append("&");
+            }
+            queryString.append(paramName).append("=");
+            String encodedParamValue;
+            try {
+                if (paramValue == null)
+                    throw new RuntimeException("paramValue is null");
+                encodedParamValue = URLEncoder.encode(paramValue, "UTF-8");
+            } catch (UnsupportedEncodingException e) {
+                throw new RuntimeException(e);
+            }
+            queryString.append(encodedParamValue);
+        }
+        return queryString.toString();
+    }
 }
\ No newline at end of file

Modified: social/trunk/facebook/src/main/java/org/picketlink/social/facebook/OAuthConstants.java
===================================================================
--- social/trunk/facebook/src/main/java/org/picketlink/social/facebook/OAuthConstants.java	2012-03-19 20:36:39 UTC (rev 1527)
+++ social/trunk/facebook/src/main/java/org/picketlink/social/facebook/OAuthConstants.java	2012-03-19 20:39:31 UTC (rev 1528)
@@ -1,44 +1,44 @@
 /*
-* 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.
-*/
+ * 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.social.facebook;
 
 /**
  * Constants defined by the OAuth spec
+ *
  * @author Marcel Kolsteren
  * @since Sep 26, 2010
  */
-public class OAuthConstants
-{
-   public static final String CODE_PARAMETER = "code";
+public class OAuthConstants {
+    public static final String CODE_PARAMETER = "code";
 
-   public static final String CLIENT_ID_PARAMETER = "client_id";
+    public static final String CLIENT_ID_PARAMETER = "client_id";
 
-   public static final String CLIENT_SECRET_PARAMETER = "client_secret";
+    public static final String CLIENT_SECRET_PARAMETER = "client_secret";
 
-   public static final String SCOPE_PARAMETER = "scope";
+    public static final String SCOPE_PARAMETER = "scope";
 
-   public static final String REDIRECT_URI_PARAMETER = "redirect_uri";
+    public static final String REDIRECT_URI_PARAMETER = "redirect_uri";
 
-   public static final String ACCESS_TOKEN_PARAMETER = "access_token";
+    public static final String ACCESS_TOKEN_PARAMETER = "access_token";
 
-   public static final String ERROR_PARAMETER = "error";
+    public static final String ERROR_PARAMETER = "error";
 }

Modified: social/trunk/facebook/src/main/java/org/picketlink/social/facebook/SecurityActions.java
===================================================================
--- social/trunk/facebook/src/main/java/org/picketlink/social/facebook/SecurityActions.java	2012-03-19 20:36:39 UTC (rev 1527)
+++ social/trunk/facebook/src/main/java/org/picketlink/social/facebook/SecurityActions.java	2012-03-19 20:39:31 UTC (rev 1528)
@@ -2,7 +2,7 @@
  * JBoss, Home of Professional Open Source.
  * Copyright 2011, 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. 
+ * 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
@@ -31,135 +31,107 @@
 
 /**
  * Privileged Blocks
+ *
  * @author Anil Saldhana
  * @since May 19, 2011
  */
-class SecurityActions
-{
-   static SecurityContext createSecurityContext( final String name)
-   {
-      return AccessController.doPrivileged(new PrivilegedAction<SecurityContext>()
-      {
-         public SecurityContext run()
-         { 
-            try
-            {
-               return SecurityContextFactory.createSecurityContext(name);
+class SecurityActions {
+    static SecurityContext createSecurityContext(final String name) {
+        return AccessController.doPrivileged(new PrivilegedAction<SecurityContext>() {
+            public SecurityContext run() {
+                try {
+                    return SecurityContextFactory.createSecurityContext(name);
+                } catch (Exception e) {
+                    throw new RuntimeException(e);
+                }
             }
-            catch (Exception e)
-            {
-               throw new RuntimeException(e);
+        });
+    }
+
+    static void setSecurityContext(final SecurityContext sc) {
+        AccessController.doPrivileged(new PrivilegedAction<Void>() {
+
+            public Void run() {
+                SecurityContextAssociation.setSecurityContext(sc);
+                return null;
             }
-         }
-      });
-   }
-   
-   static void setSecurityContext( final SecurityContext sc)
-   {
-      AccessController.doPrivileged(new PrivilegedAction<Void>()
-      {
+        });
+    }
 
-         public Void run()
-         { 
-            SecurityContextAssociation.setSecurityContext(sc);
-            return null;
-         }
-      });
-   }
-   
-   static SecurityContext getSecurityContext()
-   {
-      return AccessController.doPrivileged(new PrivilegedAction<SecurityContext>()
-      {
+    static SecurityContext getSecurityContext() {
+        return AccessController.doPrivileged(new PrivilegedAction<SecurityContext>() {
 
-         public SecurityContext run()
-         { 
-            return SecurityContextAssociation.getSecurityContext();
-         }
-      });
-   }
-   
-   static ClassLoader getContextClassLoader()
-   {
-      return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>()
-      {
+            public SecurityContext run() {
+                return SecurityContextAssociation.getSecurityContext();
+            }
+        });
+    }
 
-         public ClassLoader run()
-         { 
-            return Thread.currentThread().getContextClassLoader();
-         }
-      });
-   }
-   
-   /**
-    * Get the system property
-    * @param key
-    * @param defaultValue
-    * @return
-    */
-   static String getSystemProperty(final String key, final String defaultValue)
-   {
-      return AccessController.doPrivileged(new PrivilegedAction<String>()
-      {
-         public String run()
-         {
-            return System.getProperty(key, defaultValue);
-         }
-      });
-   }
-   
-   /**
-    * Use reflection to get the {@link Method} on a {@link Class} with the
-    * given parameter types
-    * @param clazz
-    * @param methodName
-    * @param parameterTypes
-    * @return
-    */
-   static Method getMethod(final Class<?> clazz, final String methodName, final Class<?>[] parameterTypes)
-   {
-      return AccessController.doPrivileged(new PrivilegedAction<Method>()
-      {
-         public Method run()
-         {
-            try
-            {
-               return clazz.getDeclaredMethod(methodName, parameterTypes);
+    static ClassLoader getContextClassLoader() {
+        return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
+
+            public ClassLoader run() {
+                return Thread.currentThread().getContextClassLoader();
             }
-            catch (Exception e)
-            {
-               return null;
+        });
+    }
+
+    /**
+     * Get the system property
+     *
+     * @param key
+     * @param defaultValue
+     * @return
+     */
+    static String getSystemProperty(final String key, final String defaultValue) {
+        return AccessController.doPrivileged(new PrivilegedAction<String>() {
+            public String run() {
+                return System.getProperty(key, defaultValue);
             }
-         }
-      });
-   }
-   
-   /**
-    * Using the caller class, try to load a class using its classloader. If unsuccessful, use the TCCL
-    * @param theAskingClass
-    * @param fqn
-    * @return
-    */
-   static Class<?> loadClass(final Class<?> theAskingClass, final String fqn)
-   {
-	   return AccessController.doPrivileged(new PrivilegedAction<Class<?>>()
-	   {
-	         public Class<?> run()
-	         {
-	            try
-	            {
-	            	ClassLoader tcl = theAskingClass.getClassLoader();
-	            	return tcl.loadClass(fqn);
-	            }
-	            catch (Exception e)
-	            {
-	               try {
-					return Thread.currentThread().getContextClassLoader().loadClass(fqn);
-				} catch (ClassNotFoundException e1) {
-					return null;
-				}
-	            }
-	         }
-	   }); 
-   }
+        });
+    }
+
+    /**
+     * Use reflection to get the {@link Method} on a {@link Class} with the given parameter types
+     *
+     * @param clazz
+     * @param methodName
+     * @param parameterTypes
+     * @return
+     */
+    static Method getMethod(final Class<?> clazz, final String methodName, final Class<?>[] parameterTypes) {
+        return AccessController.doPrivileged(new PrivilegedAction<Method>() {
+            public Method run() {
+                try {
+                    return clazz.getDeclaredMethod(methodName, parameterTypes);
+                } catch (Exception e) {
+                    return null;
+                }
+            }
+        });
+    }
+
+    /**
+     * Using the caller class, try to load a class using its classloader. If unsuccessful, use the TCCL
+     *
+     * @param theAskingClass
+     * @param fqn
+     * @return
+     */
+    static Class<?> loadClass(final Class<?> theAskingClass, final String fqn) {
+        return AccessController.doPrivileged(new PrivilegedAction<Class<?>>() {
+            public Class<?> run() {
+                try {
+                    ClassLoader tcl = theAskingClass.getClassLoader();
+                    return tcl.loadClass(fqn);
+                } catch (Exception e) {
+                    try {
+                        return Thread.currentThread().getContextClassLoader().loadClass(fqn);
+                    } catch (ClassNotFoundException e1) {
+                        return null;
+                    }
+                }
+            }
+        });
+    }
 }
\ No newline at end of file

Modified: social/trunk/openid/src/main/java/org/picketlink/social/openid/OpenIdPrincipal.java
===================================================================
--- social/trunk/openid/src/main/java/org/picketlink/social/openid/OpenIdPrincipal.java	2012-03-19 20:36:39 UTC (rev 1527)
+++ social/trunk/openid/src/main/java/org/picketlink/social/openid/OpenIdPrincipal.java	2012-03-19 20:39:31 UTC (rev 1528)
@@ -1,24 +1,24 @@
 /*
-* 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.
-*/
+ * 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.social.openid;
 
 import java.io.Serializable;
@@ -29,52 +29,46 @@
 
 /**
  * A {@link Principal} representing an OpenID Authenticated principal
-* @author Marcel Kolsteren
-* @author Anil Saldhana
-* @since Jan 30, 2010
-*/
-public class OpenIdPrincipal implements Principal, Serializable
-{ 
-   private static final long serialVersionUID = 4404673070085740561L;
+ *
+ * @author Marcel Kolsteren
+ * @author Anil Saldhana
+ * @since Jan 30, 2010
+ */
+public class OpenIdPrincipal implements Principal, Serializable {
+    private static final long serialVersionUID = 4404673070085740561L;
 
-   private String identifier;
+    private String identifier;
 
-   private URL openIdProvider;
+    private URL openIdProvider;
 
-   private Map<String, List<String>> attributes;
+    private Map<String, List<String>> attributes;
 
-   public OpenIdPrincipal(String identifier, URL openIdProvider, Map<String, List<String>> attributes)
-   {
-      super();
-      this.identifier = identifier;
-      this.openIdProvider = openIdProvider;
-      this.attributes = attributes;
-   }
+    public OpenIdPrincipal(String identifier, URL openIdProvider, Map<String, List<String>> attributes) {
+        super();
+        this.identifier = identifier;
+        this.openIdProvider = openIdProvider;
+        this.attributes = attributes;
+    }
 
-   public String getName()
-   {
-      return identifier;
-   }
+    public String getName() {
+        return identifier;
+    }
 
-   public String getIdentifier()
-   {
-      return identifier;
-   }
+    public String getIdentifier() {
+        return identifier;
+    }
 
-   public URL getOpenIdProvider()
-   {
-      return openIdProvider;
-   }
+    public URL getOpenIdProvider() {
+        return openIdProvider;
+    }
 
-   public Map<String, List<String>> getAttributes()
-   {
-      return attributes;
-   }
+    public Map<String, List<String>> getAttributes() {
+        return attributes;
+    }
 
-   @Override
-   public String toString()
-   {
-      return "OpenIdPrincipal [identifier=" + identifier + ", openIdProvider=" + openIdProvider + ", attributes="
-            + attributes + "]";
-   }
+    @Override
+    public String toString() {
+        return "OpenIdPrincipal [identifier=" + identifier + ", openIdProvider=" + openIdProvider + ", attributes="
+                + attributes + "]";
+    }
 }
\ No newline at end of file

Modified: social/trunk/openid/src/main/java/org/picketlink/social/openid/api/OpenIDAttributeMap.java
===================================================================
--- social/trunk/openid/src/main/java/org/picketlink/social/openid/api/OpenIDAttributeMap.java	2012-03-19 20:36:39 UTC (rev 1527)
+++ social/trunk/openid/src/main/java/org/picketlink/social/openid/api/OpenIDAttributeMap.java	2012-03-19 20:39:31 UTC (rev 1528)
@@ -2,7 +2,7 @@
  * 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. 
+ * 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
@@ -25,10 +25,10 @@
 
 /**
  * Attribute Map to be retrieved from the OpenID Provider
+ *
  * @author Anil.Saldhana at redhat.com
  * @since Jul 6, 2009
  */
-public class OpenIDAttributeMap extends HashMap<String, String>
-{
-   private static final long serialVersionUID = 1L;
+public class OpenIDAttributeMap extends HashMap<String, String> {
+    private static final long serialVersionUID = 1L;
 }
\ No newline at end of file

Modified: social/trunk/openid/src/main/java/org/picketlink/social/openid/api/OpenIDConstants.java
===================================================================
--- social/trunk/openid/src/main/java/org/picketlink/social/openid/api/OpenIDConstants.java	2012-03-19 20:36:39 UTC (rev 1527)
+++ social/trunk/openid/src/main/java/org/picketlink/social/openid/api/OpenIDConstants.java	2012-03-19 20:39:31 UTC (rev 1528)
@@ -2,7 +2,7 @@
  * 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. 
+ * 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
@@ -23,29 +23,23 @@
 
 /**
  * OpenID URL based Constants
+ *
  * @author Anil.Saldhana at redhat.com
  * @since Jul 7, 2009
  */
-public enum OpenIDConstants 
-{
-   EMAIL("http://schema.openid.net/contact/email"),
-   FULLNAME("http://schema.openid.net/contact/fullname"),
-   DOB("http://schema.openid.net/contact/dob"),
-   GENDER("http://schema.openid.net/contact/gender"),
-   POSTCODE("http://schema.openid.net/contact/postcode"),
-   COUNTRY("http://schema.openid.net/contact/country"),
-   LANGUAGE("http://schema.openid.net/contact/language"),
-   TIMEZONE("http://schema.openid.net/contact/timezone");
-   
-   private String constantURL;
-   
-   private OpenIDConstants(String url)
-   { 
-      this.constantURL = url;
-   }
+public enum OpenIDConstants {
+    EMAIL("http://schema.openid.net/contact/email"), FULLNAME("http://schema.openid.net/contact/fullname"), DOB(
+            "http://schema.openid.net/contact/dob"), GENDER("http://schema.openid.net/contact/gender"), POSTCODE(
+            "http://schema.openid.net/contact/postcode"), COUNTRY("http://schema.openid.net/contact/country"), LANGUAGE(
+            "http://schema.openid.net/contact/language"), TIMEZONE("http://schema.openid.net/contact/timezone");
 
-   public String url()
-   {
-      return this.constantURL;
-   }
+    private String constantURL;
+
+    private OpenIDConstants(String url) {
+        this.constantURL = url;
+    }
+
+    public String url() {
+        return this.constantURL;
+    }
 }

Modified: social/trunk/openid/src/main/java/org/picketlink/social/openid/api/OpenIDLifecycle.java
===================================================================
--- social/trunk/openid/src/main/java/org/picketlink/social/openid/api/OpenIDLifecycle.java	2012-03-19 20:36:39 UTC (rev 1527)
+++ social/trunk/openid/src/main/java/org/picketlink/social/openid/api/OpenIDLifecycle.java	2012-03-19 20:39:31 UTC (rev 1528)
@@ -2,7 +2,7 @@
  * 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. 
+ * 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
@@ -23,34 +23,33 @@
 
 import org.picketlink.social.openid.api.exceptions.OpenIDLifeCycleException;
 
-
 /**
- * Denotes the lifecycle methods the OpenIDManager
- * calls back - Consumer Side
+ * Denotes the lifecycle methods the OpenIDManager calls back - Consumer Side
+ *
  * @author Anil.Saldhana at redhat.com
  * @since Jul 10, 2009
  */
-public interface OpenIDLifecycle
-{ 
-   /**
-    * Handle an openid lifecycle event from
-    * the openid manager
-    * @param event
-    */
-   void handle(OpenIDLifecycleEvent event) throws OpenIDLifeCycleException; 
-   
-   /**
-    * Handle an array of lifecycle events from the OpenID Manager
-    * @param eventArr
-    * @throws OpenIDLifeCycleException
-    */
-   void handle(OpenIDLifecycleEvent[] eventArr) throws OpenIDLifeCycleException;
-   
-   /**
-    * Provide the value for an attribute to
-    * the openid manager
-    * @param name
-    * @return
-    */
-   Object getAttributeValue(String name);
+public interface OpenIDLifecycle {
+    /**
+     * Handle an openid lifecycle event from the openid manager
+     *
+     * @param event
+     */
+    void handle(OpenIDLifecycleEvent event) throws OpenIDLifeCycleException;
+
+    /**
+     * Handle an array of lifecycle events from the OpenID Manager
+     *
+     * @param eventArr
+     * @throws OpenIDLifeCycleException
+     */
+    void handle(OpenIDLifecycleEvent[] eventArr) throws OpenIDLifeCycleException;
+
+    /**
+     * Provide the value for an attribute to the openid manager
+     *
+     * @param name
+     * @return
+     */
+    Object getAttributeValue(String name);
 }
\ No newline at end of file

Modified: social/trunk/openid/src/main/java/org/picketlink/social/openid/api/OpenIDLifecycleEvent.java
===================================================================
--- social/trunk/openid/src/main/java/org/picketlink/social/openid/api/OpenIDLifecycleEvent.java	2012-03-19 20:36:39 UTC (rev 1527)
+++ social/trunk/openid/src/main/java/org/picketlink/social/openid/api/OpenIDLifecycleEvent.java	2012-03-19 20:39:31 UTC (rev 1528)
@@ -2,7 +2,7 @@
  * 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. 
+ * 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
@@ -23,80 +23,73 @@
 
 /**
  * Events in the lifecycle
+ *
  * @author Anil.Saldhana at redhat.com
  * @since Jul 10, 2009
  */
-public class OpenIDLifecycleEvent
-{
-   public enum TYPE
-   {
-      SUCCESS("lifecycle"),
-      SESSION("session");
-      private String type;
+public class OpenIDLifecycleEvent {
+    public enum TYPE {
+        SUCCESS("lifecycle"), SESSION("session");
+        private String type;
 
-      TYPE(String type)
-      {
-        this.type = type;  
-      }
-      
-      public String type()
-      {
-         return type;
-      }
-   }
-   
-   public enum OP
-   {
-      ADD,REMOVE;
-   }
-   
-   private TYPE eventType;
-   private OP operation;
-   private String attributeName;
-   private Object attributeValue;
-   
-   public OpenIDLifecycleEvent(TYPE type, OP operation, String attr, Object val)
-   {
-      this.eventType = type;
-      this.operation = operation;
-      this.attributeName = attr;
-      this.attributeValue = val;
-   }
-   
-   /**
-    * Get the type of the event (session, lifecycle etc)
-    * @return
-    */
-   public TYPE getEventType()
-   {
-      return eventType;
-   }
-   
-   /**
-    * Get the operation we are dealing with (add,remove)
-    * @return
-    */
-   public OP getOperation()
-   {
-      return this.operation;
-   }
+        TYPE(String type) {
+            this.type = type;
+        }
 
-   /**
-    * Return the attribute name that needs
-    * to be dealt at the session level
-    * @return
-    */
-   public String getAttributeName()
-   {
-      return attributeName;
-   }
+        public String type() {
+            return type;
+        }
+    }
 
-   /**
-    * Get the attribute value
-    * @return
-    */
-   public Object getAttributeValue()
-   {
-      return attributeValue;
-   }
+    public enum OP {
+        ADD, REMOVE;
+    }
+
+    private TYPE eventType;
+    private OP operation;
+    private String attributeName;
+    private Object attributeValue;
+
+    public OpenIDLifecycleEvent(TYPE type, OP operation, String attr, Object val) {
+        this.eventType = type;
+        this.operation = operation;
+        this.attributeName = attr;
+        this.attributeValue = val;
+    }
+
+    /**
+     * Get the type of the event (session, lifecycle etc)
+     *
+     * @return
+     */
+    public TYPE getEventType() {
+        return eventType;
+    }
+
+    /**
+     * Get the operation we are dealing with (add,remove)
+     *
+     * @return
+     */
+    public OP getOperation() {
+        return this.operation;
+    }
+
+    /**
+     * Return the attribute name that needs to be dealt at the session level
+     *
+     * @return
+     */
+    public String getAttributeName() {
+        return attributeName;
+    }
+
+    /**
+     * Get the attribute value
+     *
+     * @return
+     */
+    public Object getAttributeValue() {
+        return attributeValue;
+    }
 }
\ No newline at end of file

Modified: social/trunk/openid/src/main/java/org/picketlink/social/openid/api/OpenIDManager.java
===================================================================
--- social/trunk/openid/src/main/java/org/picketlink/social/openid/api/OpenIDManager.java	2012-03-19 20:36:39 UTC (rev 1527)
+++ social/trunk/openid/src/main/java/org/picketlink/social/openid/api/OpenIDManager.java	2012-03-19 20:39:31 UTC (rev 1528)
@@ -2,7 +2,7 @@
  * 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. 
+ * 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
@@ -51,375 +51,311 @@
 
 /**
  * OpenID Manager for consumers
+ *
  * @author Anil.Saldhana at redhat.com
  * @since Jul 6, 2009
  */
-public class OpenIDManager
-{
-   public enum CONST
-   {
-      OPENID("openid"),
-      OPENID_CLAIMED("openid-claimed"),
-      OPENID_DISC("openid-discovered");
-      
-      private String val;
-      CONST(String val)
-      {
-         this.val = val;
-      }
-      public String get()
-      {
-         return this.val;
-      } 
-   }
-   
-   private OpenIDRequest request = null;
+public class OpenIDManager {
+    public enum CONST {
+        OPENID("openid"), OPENID_CLAIMED("openid-claimed"), OPENID_DISC("openid-discovered");
 
-   private ConsumerManager consumerManager = null;
-   
-   private String userString = null;
+        private String val;
 
-   public OpenIDManager(OpenIDRequest theReq)
-   {
-      this.request = theReq;
-      consumerManager = new ConsumerManager(); 
-      consumerManager.setAssociations(new InMemoryConsumerAssociationStore());
-      consumerManager.setNonceVerifier(new InMemoryNonceVerifier(5000));
-      userString = request.getURL(); 
-   }
-   
-   /**
-    * Set the user string
-    * @param userString
-    */
-   public void setUserString(String userString)
-   {
-      this.userString = userString;
-   }
+        CONST(String val) {
+            this.val = val;
+        }
 
-   /**
-    * Get the OpenID Request
-    * @return
-    */
-   public OpenIDRequest getOpenIDRequest()
-   {
-      return this.request;
-   }
-   
-   @SuppressWarnings("unchecked")
-   public OpenIDProviderList discoverProviders() throws OpenIDDiscoveryException, OpenIDConsumerException
-   {
-      // perform discovery on the user-supplied identifier
-      List<DiscoveryInformation> discoveries;
-      try
-      {
-         discoveries = consumerManager.discover(userString);
-      }
-      catch (DiscoveryException e1)
-      {
-         throw new OpenIDDiscoveryException(e1);
-      }
+        public String get() {
+            return this.val;
+        }
+    }
 
-      return new OpenIDProviderList(discoveries); 
-   }
-   
-   /**
-    * Associate with a list of open id providers
-    * @param adapter Protocol adapter (such as http)
-    * @param listOfProviders (a list of providers from discovery)
-    * @return
-    * @throws OpenIDConsumerException
-    * @throws OpenIDLifeCycleException
-    */
-   public OpenIDProviderInformation associate(OpenIDProtocolAdapter adapter,
-         OpenIDProviderList listOfProviders)
-   throws OpenIDConsumerException, OpenIDLifeCycleException
-   {
-      OpenIDLifecycle lifeCycle = null;
-      
-      if(adapter instanceof OpenIDLifecycle)
-      {
-         lifeCycle = (OpenIDLifecycle) adapter; 
-      }
-      List<DiscoveryInformation> discoveries = listOfProviders.get();
-      
-      if(discoveries.size() == 0)
-         throw new OpenIDConsumerException("No open id endpoints discovered");
-      
-      // attempt to associate with the OpenID provider
-      // and retrieve one service endpoint for authentication
-      DiscoveryInformation discovered = consumerManager.associate(discoveries);
-      
-      // store the discovery information in the user's session for later use
-      // leave out for stateless operation / if there is no session
-      if(lifeCycle != null)
-      {
-         OpenIDLifecycleEvent ev =new OpenIDLifecycleEvent(TYPE.SESSION, 
-               OP.ADD, CONST.OPENID_DISC.get(), discovered); 
-         lifeCycle.handle(ev);
-      }
-      return new OpenIDProviderInformation(discovered);
-   }
+    private OpenIDRequest request = null;
 
-   /**
-    * Authenticate an user with the provider
-    * @param adapter protocol adapter
-    * @param providerInfo Information about a provider derived from discovery process
-    * @return
-    * @throws OpenIDDiscoveryException
-    * @throws OpenIDConsumerException
-    * @throws OpenIDMessageException
-    * @throws OpenIDProtocolException
-    */
-   @SuppressWarnings("unchecked")
-   public boolean authenticate(OpenIDProtocolAdapter adapter, OpenIDProviderInformation providerInfo) 
-   throws OpenIDDiscoveryException, 
-   OpenIDConsumerException, OpenIDMessageException, OpenIDProtocolException
-   {   
-      DiscoveryInformation discovered = providerInfo.get(); 
+    private ConsumerManager consumerManager = null;
 
-      // obtain a AuthRequest message to be sent to the OpenID provider
-      try
-      {
-         AuthRequest authReq = consumerManager.authenticate(discovered, 
-               adapter.getReturnURL());
+    private String userString = null;
 
-         // Attribute Exchange example: fetching the 'email' attribute
-         FetchRequest fetch = FetchRequest.createFetchRequest();
-         SRegRequest sregReq = SRegRequest.createFetchRequest();
+    public OpenIDManager(OpenIDRequest theReq) {
+        this.request = theReq;
+        consumerManager = new ConsumerManager();
+        consumerManager.setAssociations(new InMemoryConsumerAssociationStore());
+        consumerManager.setNonceVerifier(new InMemoryNonceVerifier(5000));
+        userString = request.getURL();
+    }
 
-         OpenIDAttributeMap amap = adapter.getAttributeMap();
-         
-         if ("1".equals(amap.get("nickname"))) 
-         {
-            // fetch.addAttribute("nickname",
-            // "http://schema.openid.net/contact/nickname", false);
-            sregReq.addAttribute("nickname", false);
-         }
-         
-         if ("1".equals(amap.get("email"))) 
-         {
-            fetch.addAttribute("email",OpenIDConstants.EMAIL.url(), false);
-            sregReq.addAttribute("email", false);
-         }
-         
-         if ("1".equals(amap.get("fullname"))) 
-         {
-            fetch.addAttribute("fullname",OpenIDConstants.FULLNAME.url(), false);
-            sregReq.addAttribute("fullname", false);
-         }
-         if ("1".equals(amap.get("dob"))) 
-         {
-            fetch.addAttribute("dob",OpenIDConstants.DOB.url(), true);
-            sregReq.addAttribute("dob", false);
-         }
-         
-         if ("1".equals(amap.get("gender"))) 
-         {
-            fetch.addAttribute("gender",OpenIDConstants.GENDER.url(), false);
-            sregReq.addAttribute("gender", false);
-         }
-         
-         if ("1".equals(amap.get("postcode"))) 
-         {
-            fetch.addAttribute("postcode",OpenIDConstants.POSTCODE.url(), false);
-            sregReq.addAttribute("postcode", false);
-         }
-         
-         if ("1".equals(amap.get("country"))) 
-         {
-            fetch.addAttribute("country",OpenIDConstants.COUNTRY.url(), false);
-            sregReq.addAttribute("country", false);
-         }
-         
-         if ("1".equals(amap.get("language"))) 
-         {
-            fetch.addAttribute("language", OpenIDConstants.LANGUAGE.url(),false);
-            sregReq.addAttribute("language", false);
-         }
-         
-         if ("1".equals(amap.get("timezone"))) 
-         {
-            fetch.addAttribute("timezone", OpenIDConstants.TIMEZONE.url(), false);
-            sregReq.addAttribute("timezone", false);
-         } 
-         
-         
-         // attach the extension to the authentication request
-         if (!sregReq.getAttributes().isEmpty()) 
-         {
-             authReq.addExtension(sregReq);
-         }
+    /**
+     * Set the user string
+     *
+     * @param userString
+     */
+    public void setUserString(String userString) {
+        this.userString = userString;
+    }
 
-         if (!discovered.isVersion2()) 
-         { 
-            // Option 1: GET HTTP-redirect to the OpenID Provider endpoint
-            // The only method supported in OpenID 1.x
-            // redirect-URL usually limited ~2048 bytes
-            adapter.sendToProvider(1, authReq.getDestinationUrl(true), null);
-            return true;
-         } 
-         else 
-         {
-             // Option 2: HTML FORM Redirection (Allows payloads >2048 bytes)
-            adapter.sendToProvider(2, authReq.getDestinationUrl(false), 
-                  authReq.getParameterMap()); 
-         }
-      }
-      catch (MessageException e)
-      {
-         throw new OpenIDMessageException(e);
-      }
-      catch (ConsumerException e)
-      {
-         throw new OpenIDConsumerException(e);
-      }  
-      return false;
-   }
-   
-   /**
-    * Verify a previously authenticated user with the provider
-    * @param adapter protocol adapter
-    * @param parameterMap request parameters
-    * @param receivedURL url where the response will be received
-    * @return
-    * @throws OpenIDMessageException
-    * @throws OpenIDDiscoveryException
-    * @throws OpenIDAssociationException
-    * @throws OpenIDLifeCycleException
-    */
-   public boolean verify(OpenIDProtocolAdapter adapter, Map<String,String> parameterMap,
-         String receivedURL) throws OpenIDMessageException, 
-         OpenIDDiscoveryException, OpenIDAssociationException, OpenIDLifeCycleException
-   {
-      OpenIDLifecycle lifeCycle = null;
-      
-      if(adapter instanceof OpenIDLifecycle)
-      {
-         lifeCycle = (OpenIDLifecycle) adapter; 
-      }
-      ParameterList responselist = new ParameterList(parameterMap);
-      
-      if(lifeCycle == null)
-         throw new IllegalStateException("Lifecycle not found");
-      
-      DiscoveryInformation discovered = 
-         (DiscoveryInformation) lifeCycle.getAttributeValue(CONST.OPENID_DISC.get());
-      
-      // verify the response; ConsumerManager needs to be the same
-      // (static) instance used to place the authentication request
-      try
-      {
-         VerificationResult verification = this.consumerManager.verify(
-                 receivedURL,
-                 responselist, discovered);
-         
-         // examine the verification result and extract the verified identifier
-         Identifier verified = verification.getVerifiedId();
-         if (verified != null)
-         {
-             AuthSuccess authSuccess =
-                     (AuthSuccess) verification.getAuthResponse();
-             
-             //Create an lifecycle event array
-             OpenIDLifecycleEvent[] eventArr = new OpenIDLifecycleEvent[] 
-             { 
-                  /**Store the id**/ 
-                  new OpenIDLifecycleEvent(TYPE.SESSION, 
-                       OP.ADD, CONST.OPENID.get(), authSuccess.getIdentity()),
-                       
-                  /** Store the claimed **/     
-                  new OpenIDLifecycleEvent(TYPE.SESSION, 
-                       OP.ADD, CONST.OPENID_CLAIMED.get(), authSuccess.getClaimed()),
-                       
-                  /** Indicate success **/     
-                  new OpenIDLifecycleEvent(TYPE.SUCCESS,
-                       null, null, null)
-             };
-             lifeCycle.handle(eventArr);
-             return true;
-         } 
-      }
-      catch (MessageException e)
-      {
-         throw new OpenIDMessageException(e);
-      }
-      catch (DiscoveryException e)
-      {
-         throw new OpenIDDiscoveryException(e);
-      }
-      catch (AssociationException e)
-      {
-         throw new OpenIDAssociationException(e);
-      } 
-      
-      return false; 
-   }
-   
-   /**
-    * Log an user out from an openid provider
-    * @param adapter protocol adapter
-    * @throws OpenIDLifeCycleException
-    */
-   public void logout(OpenIDProtocolAdapter adapter) throws OpenIDLifeCycleException
-   {
-      OpenIDLifecycle lifeCycle = null;
-      
-      if(adapter instanceof OpenIDLifecycle)
-      {
-         lifeCycle = (OpenIDLifecycle) adapter; 
-      }
-      if(lifeCycle != null)
-      {
-         lifeCycle.handle(new OpenIDLifecycleEvent(TYPE.SESSION, OP.REMOVE, CONST.OPENID.get(), null));
-         lifeCycle.handle(new OpenIDLifecycleEvent(TYPE.SESSION, OP.REMOVE, CONST.OPENID_CLAIMED.get(), null)); 
-      }
-   }
-   
-   /**
-    * Information about a provider from the
-    * discovery process 
-    */
-   public static class OpenIDProviderInformation
-   {
-      private DiscoveryInformation discovered;
+    /**
+     * Get the OpenID Request
+     *
+     * @return
+     */
+    public OpenIDRequest getOpenIDRequest() {
+        return this.request;
+    }
 
-      OpenIDProviderInformation(DiscoveryInformation di)
-      {
-         this.discovered = di;
-      }
-      
-      DiscoveryInformation get()
-      {
-         return this.discovered;
-      } 
-   }
-   
-   /**
-    * List of OpenID providers
-    */
-   public static class OpenIDProviderList
-   {
-      private List<DiscoveryInformation> providers = null;
-      
-      OpenIDProviderList(List<DiscoveryInformation> providers)
-      {
-         this.providers = providers;
-      }
-      
-      void addProvider( DiscoveryInformation provider )
-      {
-         this.providers.add( provider );
-      }
-      
-      List<DiscoveryInformation> get()
-      {
-         return Collections.unmodifiableList(providers);
-      }
-      
-      public int size()
-      {
-         return this.providers != null ? providers.size() : 0;
-      }
-   }
+    @SuppressWarnings("unchecked")
+    public OpenIDProviderList discoverProviders() throws OpenIDDiscoveryException, OpenIDConsumerException {
+        // perform discovery on the user-supplied identifier
+        List<DiscoveryInformation> discoveries;
+        try {
+            discoveries = consumerManager.discover(userString);
+        } catch (DiscoveryException e1) {
+            throw new OpenIDDiscoveryException(e1);
+        }
+
+        return new OpenIDProviderList(discoveries);
+    }
+
+    /**
+     * Associate with a list of open id providers
+     *
+     * @param adapter Protocol adapter (such as http)
+     * @param listOfProviders (a list of providers from discovery)
+     * @return
+     * @throws OpenIDConsumerException
+     * @throws OpenIDLifeCycleException
+     */
+    public OpenIDProviderInformation associate(OpenIDProtocolAdapter adapter, OpenIDProviderList listOfProviders)
+            throws OpenIDConsumerException, OpenIDLifeCycleException {
+        OpenIDLifecycle lifeCycle = null;
+
+        if (adapter instanceof OpenIDLifecycle) {
+            lifeCycle = (OpenIDLifecycle) adapter;
+        }
+        List<DiscoveryInformation> discoveries = listOfProviders.get();
+
+        if (discoveries.size() == 0)
+            throw new OpenIDConsumerException("No open id endpoints discovered");
+
+        // attempt to associate with the OpenID provider
+        // and retrieve one service endpoint for authentication
+        DiscoveryInformation discovered = consumerManager.associate(discoveries);
+
+        // store the discovery information in the user's session for later use
+        // leave out for stateless operation / if there is no session
+        if (lifeCycle != null) {
+            OpenIDLifecycleEvent ev = new OpenIDLifecycleEvent(TYPE.SESSION, OP.ADD, CONST.OPENID_DISC.get(), discovered);
+            lifeCycle.handle(ev);
+        }
+        return new OpenIDProviderInformation(discovered);
+    }
+
+    /**
+     * Authenticate an user with the provider
+     *
+     * @param adapter protocol adapter
+     * @param providerInfo Information about a provider derived from discovery process
+     * @return
+     * @throws OpenIDDiscoveryException
+     * @throws OpenIDConsumerException
+     * @throws OpenIDMessageException
+     * @throws OpenIDProtocolException
+     */
+    @SuppressWarnings("unchecked")
+    public boolean authenticate(OpenIDProtocolAdapter adapter, OpenIDProviderInformation providerInfo)
+            throws OpenIDDiscoveryException, OpenIDConsumerException, OpenIDMessageException, OpenIDProtocolException {
+        DiscoveryInformation discovered = providerInfo.get();
+
+        // obtain a AuthRequest message to be sent to the OpenID provider
+        try {
+            AuthRequest authReq = consumerManager.authenticate(discovered, adapter.getReturnURL());
+
+            // Attribute Exchange example: fetching the 'email' attribute
+            FetchRequest fetch = FetchRequest.createFetchRequest();
+            SRegRequest sregReq = SRegRequest.createFetchRequest();
+
+            OpenIDAttributeMap amap = adapter.getAttributeMap();
+
+            if ("1".equals(amap.get("nickname"))) {
+                // fetch.addAttribute("nickname",
+                // "http://schema.openid.net/contact/nickname", false);
+                sregReq.addAttribute("nickname", false);
+            }
+
+            if ("1".equals(amap.get("email"))) {
+                fetch.addAttribute("email", OpenIDConstants.EMAIL.url(), false);
+                sregReq.addAttribute("email", false);
+            }
+
+            if ("1".equals(amap.get("fullname"))) {
+                fetch.addAttribute("fullname", OpenIDConstants.FULLNAME.url(), false);
+                sregReq.addAttribute("fullname", false);
+            }
+            if ("1".equals(amap.get("dob"))) {
+                fetch.addAttribute("dob", OpenIDConstants.DOB.url(), true);
+                sregReq.addAttribute("dob", false);
+            }
+
+            if ("1".equals(amap.get("gender"))) {
+                fetch.addAttribute("gender", OpenIDConstants.GENDER.url(), false);
+                sregReq.addAttribute("gender", false);
+            }
+
+            if ("1".equals(amap.get("postcode"))) {
+                fetch.addAttribute("postcode", OpenIDConstants.POSTCODE.url(), false);
+                sregReq.addAttribute("postcode", false);
+            }
+
+            if ("1".equals(amap.get("country"))) {
+                fetch.addAttribute("country", OpenIDConstants.COUNTRY.url(), false);
+                sregReq.addAttribute("country", false);
+            }
+
+            if ("1".equals(amap.get("language"))) {
+                fetch.addAttribute("language", OpenIDConstants.LANGUAGE.url(), false);
+                sregReq.addAttribute("language", false);
+            }
+
+            if ("1".equals(amap.get("timezone"))) {
+                fetch.addAttribute("timezone", OpenIDConstants.TIMEZONE.url(), false);
+                sregReq.addAttribute("timezone", false);
+            }
+
+            // attach the extension to the authentication request
+            if (!sregReq.getAttributes().isEmpty()) {
+                authReq.addExtension(sregReq);
+            }
+
+            if (!discovered.isVersion2()) {
+                // Option 1: GET HTTP-redirect to the OpenID Provider endpoint
+                // The only method supported in OpenID 1.x
+                // redirect-URL usually limited ~2048 bytes
+                adapter.sendToProvider(1, authReq.getDestinationUrl(true), null);
+                return true;
+            } else {
+                // Option 2: HTML FORM Redirection (Allows payloads >2048 bytes)
+                adapter.sendToProvider(2, authReq.getDestinationUrl(false), authReq.getParameterMap());
+            }
+        } catch (MessageException e) {
+            throw new OpenIDMessageException(e);
+        } catch (ConsumerException e) {
+            throw new OpenIDConsumerException(e);
+        }
+        return false;
+    }
+
+    /**
+     * Verify a previously authenticated user with the provider
+     *
+     * @param adapter protocol adapter
+     * @param parameterMap request parameters
+     * @param receivedURL url where the response will be received
+     * @return
+     * @throws OpenIDMessageException
+     * @throws OpenIDDiscoveryException
+     * @throws OpenIDAssociationException
+     * @throws OpenIDLifeCycleException
+     */
+    public boolean verify(OpenIDProtocolAdapter adapter, Map<String, String> parameterMap, String receivedURL)
+            throws OpenIDMessageException, OpenIDDiscoveryException, OpenIDAssociationException, OpenIDLifeCycleException {
+        OpenIDLifecycle lifeCycle = null;
+
+        if (adapter instanceof OpenIDLifecycle) {
+            lifeCycle = (OpenIDLifecycle) adapter;
+        }
+        ParameterList responselist = new ParameterList(parameterMap);
+
+        if (lifeCycle == null)
+            throw new IllegalStateException("Lifecycle not found");
+
+        DiscoveryInformation discovered = (DiscoveryInformation) lifeCycle.getAttributeValue(CONST.OPENID_DISC.get());
+
+        // verify the response; ConsumerManager needs to be the same
+        // (static) instance used to place the authentication request
+        try {
+            VerificationResult verification = this.consumerManager.verify(receivedURL, responselist, discovered);
+
+            // examine the verification result and extract the verified identifier
+            Identifier verified = verification.getVerifiedId();
+            if (verified != null) {
+                AuthSuccess authSuccess = (AuthSuccess) verification.getAuthResponse();
+
+                // Create an lifecycle event array
+                OpenIDLifecycleEvent[] eventArr = new OpenIDLifecycleEvent[] {
+                /** Store the id **/
+                new OpenIDLifecycleEvent(TYPE.SESSION, OP.ADD, CONST.OPENID.get(), authSuccess.getIdentity()),
+
+                /** Store the claimed **/
+                new OpenIDLifecycleEvent(TYPE.SESSION, OP.ADD, CONST.OPENID_CLAIMED.get(), authSuccess.getClaimed()),
+
+                /** Indicate success **/
+                new OpenIDLifecycleEvent(TYPE.SUCCESS, null, null, null) };
+                lifeCycle.handle(eventArr);
+                return true;
+            }
+        } catch (MessageException e) {
+            throw new OpenIDMessageException(e);
+        } catch (DiscoveryException e) {
+            throw new OpenIDDiscoveryException(e);
+        } catch (AssociationException e) {
+            throw new OpenIDAssociationException(e);
+        }
+
+        return false;
+    }
+
+    /**
+     * Log an user out from an openid provider
+     *
+     * @param adapter protocol adapter
+     * @throws OpenIDLifeCycleException
+     */
+    public void logout(OpenIDProtocolAdapter adapter) throws OpenIDLifeCycleException {
+        OpenIDLifecycle lifeCycle = null;
+
+        if (adapter instanceof OpenIDLifecycle) {
+            lifeCycle = (OpenIDLifecycle) adapter;
+        }
+        if (lifeCycle != null) {
+            lifeCycle.handle(new OpenIDLifecycleEvent(TYPE.SESSION, OP.REMOVE, CONST.OPENID.get(), null));
+            lifeCycle.handle(new OpenIDLifecycleEvent(TYPE.SESSION, OP.REMOVE, CONST.OPENID_CLAIMED.get(), null));
+        }
+    }
+
+    /**
+     * Information about a provider from the discovery process
+     */
+    public static class OpenIDProviderInformation {
+        private DiscoveryInformation discovered;
+
+        OpenIDProviderInformation(DiscoveryInformation di) {
+            this.discovered = di;
+        }
+
+        DiscoveryInformation get() {
+            return this.discovered;
+        }
+    }
+
+    /**
+     * List of OpenID providers
+     */
+    public static class OpenIDProviderList {
+        private List<DiscoveryInformation> providers = null;
+
+        OpenIDProviderList(List<DiscoveryInformation> providers) {
+            this.providers = providers;
+        }
+
+        void addProvider(DiscoveryInformation provider) {
+            this.providers.add(provider);
+        }
+
+        List<DiscoveryInformation> get() {
+            return Collections.unmodifiableList(providers);
+        }
+
+        public int size() {
+            return this.providers != null ? providers.size() : 0;
+        }
+    }
 }

Modified: social/trunk/openid/src/main/java/org/picketlink/social/openid/api/OpenIDProtocolAdapter.java
===================================================================
--- social/trunk/openid/src/main/java/org/picketlink/social/openid/api/OpenIDProtocolAdapter.java	2012-03-19 20:36:39 UTC (rev 1527)
+++ social/trunk/openid/src/main/java/org/picketlink/social/openid/api/OpenIDProtocolAdapter.java	2012-03-19 20:39:31 UTC (rev 1528)
@@ -2,7 +2,7 @@
  * 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. 
+ * 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
@@ -24,37 +24,34 @@
 import java.util.Map;
 
 import org.picketlink.social.openid.api.exceptions.OpenIDProtocolException;
- 
 
 /**
- * Callback adapter sent to the OpenIDManager
- * that implements the protocol behavior
- * such as HTTP
+ * Callback adapter sent to the OpenIDManager that implements the protocol behavior such as HTTP
+ *
  * @author Anil.Saldhana at redhat.com
  * @since Jul 6, 2009
  */
-public interface OpenIDProtocolAdapter
-{
-   /**
-    * Map of attributes to be retrieved from the provider
-    * @return
-    */
-   OpenIDAttributeMap getAttributeMap();
-   
-   /**
-    * Provide the return url for the OpenIDManager where the
-    * Relying Party can handle responses from the OpenID Provider
-    * @return
-    */
-   String getReturnURL(); 
+public interface OpenIDProtocolAdapter {
+    /**
+     * Map of attributes to be retrieved from the provider
+     *
+     * @return
+     */
+    OpenIDAttributeMap getAttributeMap();
 
-   /**
-    * Send the request to the OpenID Provider
-    * @param version OpenID version 1 is via HTTP Redirect
-    * and by HTTP Post for version 2
-    * @param destinationURL Final Destination URL
-    * @param paramMap Map of parameters
-    */
-   void sendToProvider(int version, String destinationURL,
-         Map<String,String> paramMap) throws OpenIDProtocolException; 
+    /**
+     * Provide the return url for the OpenIDManager where the Relying Party can handle responses from the OpenID Provider
+     *
+     * @return
+     */
+    String getReturnURL();
+
+    /**
+     * Send the request to the OpenID Provider
+     *
+     * @param version OpenID version 1 is via HTTP Redirect and by HTTP Post for version 2
+     * @param destinationURL Final Destination URL
+     * @param paramMap Map of parameters
+     */
+    void sendToProvider(int version, String destinationURL, Map<String, String> paramMap) throws OpenIDProtocolException;
 }
\ No newline at end of file

Modified: social/trunk/openid/src/main/java/org/picketlink/social/openid/api/OpenIDRequest.java
===================================================================
--- social/trunk/openid/src/main/java/org/picketlink/social/openid/api/OpenIDRequest.java	2012-03-19 20:36:39 UTC (rev 1527)
+++ social/trunk/openid/src/main/java/org/picketlink/social/openid/api/OpenIDRequest.java	2012-03-19 20:39:31 UTC (rev 1528)
@@ -2,7 +2,7 @@
  * 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. 
+ * 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
@@ -23,47 +23,44 @@
 
 /**
  * Represents an OpenID request
+ *
  * @author Anil.Saldhana at redhat.com
  * @since Jul 6, 2009
  */
-public class OpenIDRequest
-{
-   private String url;
+public class OpenIDRequest {
+    private String url;
 
-   public OpenIDRequest()
-   {   
-   }
-   
-   public OpenIDRequest(String url)
-   {
-      this.url = url;
-   }
+    public OpenIDRequest() {
+    }
 
-   /**
-    * Get the username (openid url)
-    * @return
-    */
-   public String getURL()
-   {
-      return this.url;
-   }
-   
-   /**
-    * Set the username in the form of url
-    * @param url
-    * @return
-    */
-   public OpenIDRequest setURL(String url)
-   {
-      this.url = url;
-      return this;
-   }
-   
-   @Override
-   public String toString()
-   {
-      StringBuilder builder = new StringBuilder();
-      builder.append("[OpenIDRequest:").append(this.url).append("]");
-      return builder.toString();
-   }
+    public OpenIDRequest(String url) {
+        this.url = url;
+    }
+
+    /**
+     * Get the username (openid url)
+     *
+     * @return
+     */
+    public String getURL() {
+        return this.url;
+    }
+
+    /**
+     * Set the username in the form of url
+     *
+     * @param url
+     * @return
+     */
+    public OpenIDRequest setURL(String url) {
+        this.url = url;
+        return this;
+    }
+
+    @Override
+    public String toString() {
+        StringBuilder builder = new StringBuilder();
+        builder.append("[OpenIDRequest:").append(this.url).append("]");
+        return builder.toString();
+    }
 }
\ No newline at end of file

Modified: social/trunk/openid/src/main/java/org/picketlink/social/openid/api/exceptions/OpenIDAssociationException.java
===================================================================
--- social/trunk/openid/src/main/java/org/picketlink/social/openid/api/exceptions/OpenIDAssociationException.java	2012-03-19 20:36:39 UTC (rev 1527)
+++ social/trunk/openid/src/main/java/org/picketlink/social/openid/api/exceptions/OpenIDAssociationException.java	2012-03-19 20:39:31 UTC (rev 1528)
@@ -2,7 +2,7 @@
  * 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. 
+ * 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
@@ -23,30 +23,26 @@
 
 /**
  * Exception indicating openid association problems
+ *
  * @author Anil.Saldhana at redhat.com
  * @since Jul 10, 2009
  */
-public class OpenIDAssociationException extends OpenIDGeneralException
-{
-   private static final long serialVersionUID = 1L;
+public class OpenIDAssociationException extends OpenIDGeneralException {
+    private static final long serialVersionUID = 1L;
 
-   public OpenIDAssociationException()
-   {
-      super(); 
-   }
+    public OpenIDAssociationException() {
+        super();
+    }
 
-   public OpenIDAssociationException(String message, Throwable cause)
-   {
-      super(message, cause); 
-   }
+    public OpenIDAssociationException(String message, Throwable cause) {
+        super(message, cause);
+    }
 
-   public OpenIDAssociationException(String msg)
-   {
-      super(msg); 
-   }
+    public OpenIDAssociationException(String msg) {
+        super(msg);
+    }
 
-   public OpenIDAssociationException(Throwable cause)
-   {
-      super(cause); 
-   } 
+    public OpenIDAssociationException(Throwable cause) {
+        super(cause);
+    }
 }
\ No newline at end of file

Modified: social/trunk/openid/src/main/java/org/picketlink/social/openid/api/exceptions/OpenIDConsumerException.java
===================================================================
--- social/trunk/openid/src/main/java/org/picketlink/social/openid/api/exceptions/OpenIDConsumerException.java	2012-03-19 20:36:39 UTC (rev 1527)
+++ social/trunk/openid/src/main/java/org/picketlink/social/openid/api/exceptions/OpenIDConsumerException.java	2012-03-19 20:39:31 UTC (rev 1528)
@@ -2,7 +2,7 @@
  * 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. 
+ * 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
@@ -21,33 +21,28 @@
  */
 package org.picketlink.social.openid.api.exceptions;
 
-
 /**
  * OpenID Exception at the consumer
+ *
  * @author Anil.Saldhana at redhat.com
  * @since Jul 6, 2009
  */
-public class OpenIDConsumerException extends OpenIDGeneralException
-{
-   private static final long serialVersionUID = 1L;
+public class OpenIDConsumerException extends OpenIDGeneralException {
+    private static final long serialVersionUID = 1L;
 
-   public OpenIDConsumerException()
-   {
-      super(); 
-   }
+    public OpenIDConsumerException() {
+        super();
+    }
 
-   public OpenIDConsumerException(String message, Throwable cause)
-   {
-      super(message, cause); 
-   }
+    public OpenIDConsumerException(String message, Throwable cause) {
+        super(message, cause);
+    }
 
-   public OpenIDConsumerException(String msg)
-   {
-      super(msg); 
-   }
+    public OpenIDConsumerException(String msg) {
+        super(msg);
+    }
 
-   public OpenIDConsumerException(Throwable cause)
-   {
-      super(cause); 
-   } 
+    public OpenIDConsumerException(Throwable cause) {
+        super(cause);
+    }
 }
\ No newline at end of file

Modified: social/trunk/openid/src/main/java/org/picketlink/social/openid/api/exceptions/OpenIDDiscoveryException.java
===================================================================
--- social/trunk/openid/src/main/java/org/picketlink/social/openid/api/exceptions/OpenIDDiscoveryException.java	2012-03-19 20:36:39 UTC (rev 1527)
+++ social/trunk/openid/src/main/java/org/picketlink/social/openid/api/exceptions/OpenIDDiscoveryException.java	2012-03-19 20:39:31 UTC (rev 1528)
@@ -2,7 +2,7 @@
  * 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. 
+ * 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
@@ -21,33 +21,28 @@
  */
 package org.picketlink.social.openid.api.exceptions;
 
-
 /**
  * Discovery of OpenID Provider Exception
+ *
  * @author Anil.Saldhana at redhat.com
  * @since Jul 6, 2009
  */
-public class OpenIDDiscoveryException extends OpenIDGeneralException
-{
-   private static final long serialVersionUID = 1L;
+public class OpenIDDiscoveryException extends OpenIDGeneralException {
+    private static final long serialVersionUID = 1L;
 
-   public OpenIDDiscoveryException()
-   {
-      super(); 
-   }
+    public OpenIDDiscoveryException() {
+        super();
+    }
 
-   public OpenIDDiscoveryException(String message, Throwable cause)
-   {
-      super(message, cause); 
-   }
+    public OpenIDDiscoveryException(String message, Throwable cause) {
+        super(message, cause);
+    }
 
-   public OpenIDDiscoveryException(String msg)
-   {
-      super(msg); 
-   }
+    public OpenIDDiscoveryException(String msg) {
+        super(msg);
+    }
 
-   public OpenIDDiscoveryException(Throwable cause)
-   {
-      super(cause); 
-   } 
+    public OpenIDDiscoveryException(Throwable cause) {
+        super(cause);
+    }
 }
\ No newline at end of file

Modified: social/trunk/openid/src/main/java/org/picketlink/social/openid/api/exceptions/OpenIDGeneralException.java
===================================================================
--- social/trunk/openid/src/main/java/org/picketlink/social/openid/api/exceptions/OpenIDGeneralException.java	2012-03-19 20:36:39 UTC (rev 1527)
+++ social/trunk/openid/src/main/java/org/picketlink/social/openid/api/exceptions/OpenIDGeneralException.java	2012-03-19 20:39:31 UTC (rev 1528)
@@ -2,7 +2,7 @@
  * 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. 
+ * 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
@@ -25,30 +25,26 @@
 
 /**
  * Base class for all OpenID exceptions
+ *
  * @author Anil.Saldhana at redhat.com
  * @since Jul 10, 2009
  */
-public class OpenIDGeneralException extends GeneralSecurityException
-{
-   private static final long serialVersionUID = 1L;
+public class OpenIDGeneralException extends GeneralSecurityException {
+    private static final long serialVersionUID = 1L;
 
-   public OpenIDGeneralException()
-   {
-      super(); 
-   }
+    public OpenIDGeneralException() {
+        super();
+    }
 
-   public OpenIDGeneralException(String message, Throwable cause)
-   {
-      super(message, cause); 
-   }
+    public OpenIDGeneralException(String message, Throwable cause) {
+        super(message, cause);
+    }
 
-   public OpenIDGeneralException(String msg)
-   {
-      super(msg); 
-   }
+    public OpenIDGeneralException(String msg) {
+        super(msg);
+    }
 
-   public OpenIDGeneralException(Throwable cause)
-   {
-      super(cause); 
-   } 
+    public OpenIDGeneralException(Throwable cause) {
+        super(cause);
+    }
 }
\ No newline at end of file

Modified: social/trunk/openid/src/main/java/org/picketlink/social/openid/api/exceptions/OpenIDLifeCycleException.java
===================================================================
--- social/trunk/openid/src/main/java/org/picketlink/social/openid/api/exceptions/OpenIDLifeCycleException.java	2012-03-19 20:36:39 UTC (rev 1527)
+++ social/trunk/openid/src/main/java/org/picketlink/social/openid/api/exceptions/OpenIDLifeCycleException.java	2012-03-19 20:39:31 UTC (rev 1528)
@@ -2,7 +2,7 @@
  * 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. 
+ * 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
@@ -23,30 +23,26 @@
 
 /**
  * Exception indicating issues during lifecycle handling
+ *
  * @author Anil.Saldhana at redhat.com
  * @since Jul 10, 2009
  */
-public class OpenIDLifeCycleException extends OpenIDGeneralException
-{
-   private static final long serialVersionUID = 1L;
+public class OpenIDLifeCycleException extends OpenIDGeneralException {
+    private static final long serialVersionUID = 1L;
 
-   public OpenIDLifeCycleException()
-   {
-      super(); 
-   }
+    public OpenIDLifeCycleException() {
+        super();
+    }
 
-   public OpenIDLifeCycleException(String message, Throwable cause)
-   {
-      super(message, cause); 
-   }
+    public OpenIDLifeCycleException(String message, Throwable cause) {
+        super(message, cause);
+    }
 
-   public OpenIDLifeCycleException(String msg)
-   {
-      super(msg); 
-   }
+    public OpenIDLifeCycleException(String msg) {
+        super(msg);
+    }
 
-   public OpenIDLifeCycleException(Throwable cause)
-   {
-      super(cause); 
-   } 
+    public OpenIDLifeCycleException(Throwable cause) {
+        super(cause);
+    }
 }
\ No newline at end of file

Modified: social/trunk/openid/src/main/java/org/picketlink/social/openid/api/exceptions/OpenIDMessageException.java
===================================================================
--- social/trunk/openid/src/main/java/org/picketlink/social/openid/api/exceptions/OpenIDMessageException.java	2012-03-19 20:36:39 UTC (rev 1527)
+++ social/trunk/openid/src/main/java/org/picketlink/social/openid/api/exceptions/OpenIDMessageException.java	2012-03-19 20:39:31 UTC (rev 1528)
@@ -2,7 +2,7 @@
  * 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. 
+ * 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
@@ -21,33 +21,28 @@
  */
 package org.picketlink.social.openid.api.exceptions;
 
-
 /**
  * OpenID exception for message transit
+ *
  * @author Anil.Saldhana at redhat.com
  * @since Jul 6, 2009
  */
-public class OpenIDMessageException extends OpenIDGeneralException
-{
-   private static final long serialVersionUID = 1L;
+public class OpenIDMessageException extends OpenIDGeneralException {
+    private static final long serialVersionUID = 1L;
 
-   public OpenIDMessageException()
-   {
-      super(); 
-   }
+    public OpenIDMessageException() {
+        super();
+    }
 
-   public OpenIDMessageException(String message, Throwable cause)
-   {
-      super(message, cause); 
-   }
+    public OpenIDMessageException(String message, Throwable cause) {
+        super(message, cause);
+    }
 
-   public OpenIDMessageException(String msg)
-   {
-      super(msg); 
-   }
+    public OpenIDMessageException(String msg) {
+        super(msg);
+    }
 
-   public OpenIDMessageException(Throwable cause)
-   {
-      super(cause); 
-   } 
+    public OpenIDMessageException(Throwable cause) {
+        super(cause);
+    }
 }
\ No newline at end of file

Modified: social/trunk/openid/src/main/java/org/picketlink/social/openid/api/exceptions/OpenIDProtocolException.java
===================================================================
--- social/trunk/openid/src/main/java/org/picketlink/social/openid/api/exceptions/OpenIDProtocolException.java	2012-03-19 20:36:39 UTC (rev 1527)
+++ social/trunk/openid/src/main/java/org/picketlink/social/openid/api/exceptions/OpenIDProtocolException.java	2012-03-19 20:39:31 UTC (rev 1528)
@@ -2,7 +2,7 @@
  * 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. 
+ * 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
@@ -21,33 +21,28 @@
  */
 package org.picketlink.social.openid.api.exceptions;
 
-
 /**
  * Exception indicating a protocol exception
+ *
  * @author Anil.Saldhana at redhat.com
  * @since Jul 6, 2009
  */
-public class OpenIDProtocolException extends OpenIDGeneralException
-{
-   private static final long serialVersionUID = 1L;
+public class OpenIDProtocolException extends OpenIDGeneralException {
+    private static final long serialVersionUID = 1L;
 
-   public OpenIDProtocolException()
-   {
-      super(); 
-   }
+    public OpenIDProtocolException() {
+        super();
+    }
 
-   public OpenIDProtocolException(String message, Throwable cause)
-   {
-      super(message, cause); 
-   }
+    public OpenIDProtocolException(String message, Throwable cause) {
+        super(message, cause);
+    }
 
-   public OpenIDProtocolException(String msg)
-   {
-      super(msg); 
-   }
+    public OpenIDProtocolException(String msg) {
+        super(msg);
+    }
 
-   public OpenIDProtocolException(Throwable cause)
-   {
-      super(cause); 
-   }
+    public OpenIDProtocolException(Throwable cause) {
+        super(cause);
+    }
 }

Modified: social/trunk/openid/src/main/java/org/picketlink/social/openid/auth/OpenIDConsumerAuthenticator.java
===================================================================
--- social/trunk/openid/src/main/java/org/picketlink/social/openid/auth/OpenIDConsumerAuthenticator.java	2012-03-19 20:36:39 UTC (rev 1527)
+++ social/trunk/openid/src/main/java/org/picketlink/social/openid/auth/OpenIDConsumerAuthenticator.java	2012-03-19 20:39:31 UTC (rev 1528)
@@ -2,7 +2,7 @@
  * JBoss, Home of Professional Open Source.
  * Copyright 2011, 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. 
+ * 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
@@ -42,200 +42,176 @@
 
 /**
  * Tomcat Authenticator that provides OpenID based authentication
+ *
  * @author Anil Saldhana
  * @since Sep 17, 2011
  */
-public class OpenIDConsumerAuthenticator extends FormAuthenticator
-{
-   protected static Logger log = Logger.getLogger(OpenIDConsumerAuthenticator.class);
-   protected boolean trace = log.isTraceEnabled(); 
+public class OpenIDConsumerAuthenticator extends FormAuthenticator {
+    protected static Logger log = Logger.getLogger(OpenIDConsumerAuthenticator.class);
+    protected boolean trace = log.isTraceEnabled();
 
-   private enum STATES { AUTH, AUTHZ, FINISH};
+    private enum STATES {
+        AUTH, AUTHZ, FINISH
+    };
 
-   public static ThreadLocal<Principal> cachedPrincipal = new ThreadLocal<Principal>();
+    public static ThreadLocal<Principal> cachedPrincipal = new ThreadLocal<Principal>();
 
-   public static ThreadLocal<List<String>> cachedRoles = new ThreadLocal<List<String>>();
-   public static String EMPTY_PASSWORD = "EMPTY";
+    public static ThreadLocal<List<String>> cachedRoles = new ThreadLocal<List<String>>();
+    public static String EMPTY_PASSWORD = "EMPTY";
 
-   private String returnURL = null;
+    private String returnURL = null;
 
-   private String requiredAttributes = "name,email,ax_firstName,ax_lastName,ax_fullName,ax_email";
+    private String requiredAttributes = "name,email,ax_firstName,ax_lastName,ax_fullName,ax_email";
 
-   private String optionalAttributes = null;
+    private String optionalAttributes = null;
 
-   protected List<String> roles = new ArrayList<String>();
+    protected List<String> roles = new ArrayList<String>();
 
-   //Whether the authenticator has to to save and restore request
-   protected boolean saveRestoreRequest = true;
+    // Whether the authenticator has to to save and restore request
+    protected boolean saveRestoreRequest = true;
 
-   protected OpenIDProcessor processor = null;
-   
-   //Incompatibilities in register() method across JBossWeb versions
-   private Method theSuperRegisterMethod = null;
+    protected OpenIDProcessor processor = null;
 
-   public void setReturnURL(String returnURL)
-   {
-      this.returnURL = StringUtil.getSystemPropertyAsString(returnURL);
-   }
+    // Incompatibilities in register() method across JBossWeb versions
+    private Method theSuperRegisterMethod = null;
 
-   public void setRequiredAttributes(String requiredAttributes)
-   {
-      this.requiredAttributes = requiredAttributes;
-   }
+    public void setReturnURL(String returnURL) {
+        this.returnURL = StringUtil.getSystemPropertyAsString(returnURL);
+    }
 
-   public void setOptionalAttributes(String optionalAttributes)
-   {
-      this.optionalAttributes = optionalAttributes;
-   }
+    public void setRequiredAttributes(String requiredAttributes) {
+        this.requiredAttributes = requiredAttributes;
+    }
 
-   public void setSaveRestoreRequest(boolean saveRestoreRequest)
-   {
-      this.saveRestoreRequest = saveRestoreRequest;
-   } 
+    public void setOptionalAttributes(String optionalAttributes) {
+        this.optionalAttributes = optionalAttributes;
+    }
 
-   /**
-    * A comma separated string that represents the roles the web app
-    * needs to pass authorization
-    * @param roleStr
-    */
-   public void setRoleString(String roleStr)
-   {
-      if(roleStr == null)
-         throw new RuntimeException("Role String is null in configuration");
-      List<String> tokens = StringUtil.tokenize(roleStr);
-      for(String token: tokens)
-      {
-         roles.add(token);
-      }
-   }
-   
-   public boolean authenticate(HttpServletRequest request, HttpServletResponse response, LoginConfig loginConfig) throws IOException
-   {
-      if(request instanceof Request == false)
-         throw new IOException("Not of type Catalina request");
-      if(response instanceof Response == false)
-         throw new IOException("Not of type Catalina response");
-      return authenticate((Request)request, (Response)response, loginConfig);
-   }
-   
-   /**
-    * Authenticate the request
-    * @param request
-    * @param response
-    * @param config
-    * @return
-    * @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
-   {
-      if (response instanceof Response)
-      {
-         Response catalinaResponse = (Response) response;
-         return authenticate(request, catalinaResponse, config);
-      }
-      throw new RuntimeException("Wrong type of response:"+response);
-   }
-   
-   public boolean authenticate(Request request, Response response, LoginConfig loginConfig) throws IOException
-   {  
-      if(processor == null)
-         processor = new OpenIDProcessor(returnURL, requiredAttributes, optionalAttributes);
+    public void setSaveRestoreRequest(boolean saveRestoreRequest) {
+        this.saveRestoreRequest = saveRestoreRequest;
+    }
 
-      Principal userPrincipal = request.getUserPrincipal();
-      if(userPrincipal != null)
-      {
-         if(trace)
-            log.trace("Logged in as:"+userPrincipal);
-         return true;
-      }
+    /**
+     * A comma separated string that represents the roles the web app needs to pass authorization
+     *
+     * @param roleStr
+     */
+    public void setRoleString(String roleStr) {
+        if (roleStr == null)
+            throw new RuntimeException("Role String is null in configuration");
+        List<String> tokens = StringUtil.tokenize(roleStr);
+        for (String token : tokens) {
+            roles.add(token);
+        }
+    }
 
-      if(!processor.isInitialized())
-      {
-         try
-         {
-            processor.initialize(roles);
-         }
-         catch (Exception e)
-         { 
-            throw new RuntimeException(e);
-         }
-      }
+    public boolean authenticate(HttpServletRequest request, HttpServletResponse response, LoginConfig loginConfig)
+            throws IOException {
+        if (request instanceof Request == false)
+            throw new IOException("Not of type Catalina request");
+        if (response instanceof Response == false)
+            throw new IOException("Not of type Catalina response");
+        return authenticate((Request) request, (Response) response, loginConfig);
+    }
 
-      HttpSession httpSession = request.getSession();
-      String state = (String) httpSession.getAttribute("STATE");
-      if(trace) log.trace("state="+ state);
+    /**
+     * Authenticate the request
+     *
+     * @param request
+     * @param response
+     * @param config
+     * @return
+     * @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 {
+        if (response instanceof Response) {
+            Response catalinaResponse = (Response) response;
+            return authenticate(request, catalinaResponse, config);
+        }
+        throw new RuntimeException("Wrong type of response:" + response);
+    }
 
-      if( STATES.FINISH.name().equals(state))
-         return true;
+    public boolean authenticate(Request request, Response response, LoginConfig loginConfig) throws IOException {
+        if (processor == null)
+            processor = new OpenIDProcessor(returnURL, requiredAttributes, optionalAttributes);
 
-      if( state == null || state.isEmpty())
-      { 
-         return processor.prepareAndSendAuthRequest(request, response);
-      } 
-      //We have sent an auth request
-      if( state.equals(STATES.AUTH.name()))
-      {
-         Session session = request.getSessionInternal(true);
-         if (saveRestoreRequest)
-         {
-            this.saveRequest(request, session);
-         }
+        Principal userPrincipal = request.getUserPrincipal();
+        if (userPrincipal != null) {
+            if (trace)
+                log.trace("Logged in as:" + userPrincipal);
+            return true;
+        }
 
-         Principal principal = processor.processIncomingAuthResult(request, response, context.getRealm());
-         if(principal == null)
-            throw new RuntimeException("Principal was null. Maybe login modules need to be configured properly.");
-         String principalName = principal.getName();
-         request.getSessionInternal().setNote(Constants.SESS_USERNAME_NOTE, principalName);
-         request.getSessionInternal().setNote(Constants.SESS_PASSWORD_NOTE, "");
-         request.setUserPrincipal(principal);
+        if (!processor.isInitialized()) {
+            try {
+                processor.initialize(roles);
+            } catch (Exception e) {
+                throw new RuntimeException(e);
+            }
+        }
 
-         if (saveRestoreRequest)
-         {
-            this.restoreRequest(request, request.getSessionInternal());
-         }
+        HttpSession httpSession = request.getSession();
+        String state = (String) httpSession.getAttribute("STATE");
+        if (trace)
+            log.trace("state=" + state);
 
-         if(trace)
-            log.trace("Logged in as:" + principal);
-         
-         registerWithAuthenticatorBase(request,response,principal,principalName);
-         
-         request.getSession().setAttribute("STATE", STATES.FINISH.name());
-         return true;
-      }
-      return false;
-   }
-   
-   protected void registerWithAuthenticatorBase(Request request, Response response, Principal principal, String userName)
-   {
-      try
-      {
-         register(request, response, principal, Constants.FORM_METHOD, userName, "");
-      }
-      catch(NoSuchMethodError nse)
-      { 
-         if(theSuperRegisterMethod == null)
-         {
-            Class<?>[] args = new Class[]
-            {Request.class, HttpServletResponse.class, Principal.class, String.class, String.class, String.class};
-            Class<?> superClass = getClass().getSuperclass();
-            theSuperRegisterMethod = SecurityActions.getMethod(superClass, "register", args);
-            
-         }
-         if(theSuperRegisterMethod != null)
-         {
-            Object[] objectArgs = new Object[] {request, response.getResponse(),
-                  principal, Constants.FORM_METHOD,
-                  userName, OpenIDProcessor.EMPTY_PASSWORD };
-            try
-            {
-               theSuperRegisterMethod.invoke(this, objectArgs);
+        if (STATES.FINISH.name().equals(state))
+            return true;
+
+        if (state == null || state.isEmpty()) {
+            return processor.prepareAndSendAuthRequest(request, response);
+        }
+        // We have sent an auth request
+        if (state.equals(STATES.AUTH.name())) {
+            Session session = request.getSessionInternal(true);
+            if (saveRestoreRequest) {
+                this.saveRequest(request, session);
             }
-            catch (Exception e)
-            {
-               log.error("Unable to register:", e);
+
+            Principal principal = processor.processIncomingAuthResult(request, response, context.getRealm());
+            if (principal == null)
+                throw new RuntimeException("Principal was null. Maybe login modules need to be configured properly.");
+            String principalName = principal.getName();
+            request.getSessionInternal().setNote(Constants.SESS_USERNAME_NOTE, principalName);
+            request.getSessionInternal().setNote(Constants.SESS_PASSWORD_NOTE, "");
+            request.setUserPrincipal(principal);
+
+            if (saveRestoreRequest) {
+                this.restoreRequest(request, request.getSessionInternal());
             }
-         }
-      }
-   }
+
+            if (trace)
+                log.trace("Logged in as:" + principal);
+
+            registerWithAuthenticatorBase(request, response, principal, principalName);
+
+            request.getSession().setAttribute("STATE", STATES.FINISH.name());
+            return true;
+        }
+        return false;
+    }
+
+    protected void registerWithAuthenticatorBase(Request request, Response response, Principal principal, String userName) {
+        try {
+            register(request, response, principal, Constants.FORM_METHOD, userName, "");
+        } catch (NoSuchMethodError nse) {
+            if (theSuperRegisterMethod == null) {
+                Class<?>[] args = new Class[] { Request.class, HttpServletResponse.class, Principal.class, String.class,
+                        String.class, String.class };
+                Class<?> superClass = getClass().getSuperclass();
+                theSuperRegisterMethod = SecurityActions.getMethod(superClass, "register", args);
+
+            }
+            if (theSuperRegisterMethod != null) {
+                Object[] objectArgs = new Object[] { request, response.getResponse(), principal, Constants.FORM_METHOD,
+                        userName, OpenIDProcessor.EMPTY_PASSWORD };
+                try {
+                    theSuperRegisterMethod.invoke(this, objectArgs);
+                } catch (Exception e) {
+                    log.error("Unable to register:", e);
+                }
+            }
+        }
+    }
 }
\ No newline at end of file

Modified: social/trunk/openid/src/main/java/org/picketlink/social/openid/auth/OpenIDLoginModule.java
===================================================================
--- social/trunk/openid/src/main/java/org/picketlink/social/openid/auth/OpenIDLoginModule.java	2012-03-19 20:36:39 UTC (rev 1527)
+++ social/trunk/openid/src/main/java/org/picketlink/social/openid/auth/OpenIDLoginModule.java	2012-03-19 20:39:31 UTC (rev 1528)
@@ -2,7 +2,7 @@
  * JBoss, Home of Professional Open Source.
  * Copyright 2011, 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. 
+ * 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
@@ -34,37 +34,32 @@
 
 /**
  * A {@link LoginModule} for JBoss environment to support OpenID
+ *
  * @author Anil Saldhana
  * @since May 19, 2011
  */
-public class OpenIDLoginModule extends UsernamePasswordLoginModule
-{ 
-   @Override
-   protected Principal getIdentity()
-   {
-      return OpenIDProcessor.cachedPrincipal.get();
-   }
+public class OpenIDLoginModule extends UsernamePasswordLoginModule {
+    @Override
+    protected Principal getIdentity() {
+        return OpenIDProcessor.cachedPrincipal.get();
+    }
 
-   @Override
-   protected String getUsersPassword() throws LoginException
-   {
-      return OpenIDProcessor.EMPTY_PASSWORD;
-   }
+    @Override
+    protected String getUsersPassword() throws LoginException {
+        return OpenIDProcessor.EMPTY_PASSWORD;
+    }
 
-   @Override
-   protected Group[] getRoleSets() throws LoginException
-   {   
-      Group group = new SimpleGroup("Roles"); 
+    @Override
+    protected Group[] getRoleSets() throws LoginException {
+        Group group = new SimpleGroup("Roles");
 
-      List<String> roles = OpenIDProcessor.cachedRoles.get();
+        List<String> roles = OpenIDProcessor.cachedRoles.get();
 
-      if(roles != null)
-      {
-         for(String role: roles)
-         {
-            group.addMember(new SimplePrincipal(role));
-         }
-      }
-      return new Group[] {group};
-   }
+        if (roles != null) {
+            for (String role : roles) {
+                group.addMember(new SimplePrincipal(role));
+            }
+        }
+        return new Group[] { group };
+    }
 }
\ No newline at end of file

Modified: social/trunk/openid/src/main/java/org/picketlink/social/openid/auth/OpenIDProcessor.java
===================================================================
--- social/trunk/openid/src/main/java/org/picketlink/social/openid/auth/OpenIDProcessor.java	2012-03-19 20:36:39 UTC (rev 1527)
+++ social/trunk/openid/src/main/java/org/picketlink/social/openid/auth/OpenIDProcessor.java	2012-03-19 20:39:31 UTC (rev 1528)
@@ -2,7 +2,7 @@
  * JBoss, Home of Professional Open Source.
  * Copyright 2011, 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. 
+ * 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
@@ -55,272 +55,237 @@
 
 /**
  * Processor for the OpenID interaction
+ *
  * @author Anil Saldhana
  * @since Sep 22, 2011
  */
-public class OpenIDProcessor
-{
-   protected static Logger log = Logger.getLogger(OpenIDProcessor.class);
-   protected boolean trace = log.isTraceEnabled();
-   
-   public static final String AUTH_TYPE = "authType";
-   
-   private ConsumerManager openIdConsumerManager;
-   private FetchRequest fetchRequest;
-   
-   private String openIdServiceUrl = null;
-   
-   private String returnURL = null;
-   
-   private String requiredAttributes,optionalAttributes = null;
-   
-   private boolean initialized = false;
+public class OpenIDProcessor {
+    protected static Logger log = Logger.getLogger(OpenIDProcessor.class);
+    protected boolean trace = log.isTraceEnabled();
 
-   protected List<String> roles = new ArrayList<String>();
-   
-   public static ThreadLocal<Principal> cachedPrincipal = new ThreadLocal<Principal>();
-   
-   public static ThreadLocal<List<String>> cachedRoles = new ThreadLocal<List<String>>();
-   public static String EMPTY_PASSWORD = "EMPTY";
+    public static final String AUTH_TYPE = "authType";
 
-   private enum STATES { AUTH, AUTHZ, FINISH};
-   
-   private enum Providers
-   {
-      GOOGLE("https://www.google.com/accounts/o8/id"),
-      YAHOO("https://me.yahoo.com/"),
-      MYSPACE("myspace.com"),
-      MYOPENID("https://myopenid.com/");
-      
-      private String name;
+    private ConsumerManager openIdConsumerManager;
+    private FetchRequest fetchRequest;
 
-      Providers(String name)
-      {
-         this.name = name;
-      }
-      String get()
-      {
-         return name;
-      }
-   }
-   
-   public OpenIDProcessor(String theReturnURL, String requiredAttributes, String optionalAttributes)
-   {
-      this.returnURL = theReturnURL;
-      this.requiredAttributes = requiredAttributes;
-      this.optionalAttributes = optionalAttributes;
-   }
-   
-   /**
-    * Return whether the processor has initialized
-    * @return
-    */
-   public boolean isInitialized()
-   {
-      return initialized;
-   }
-   
-   /**
-    * Initialize the processor
-    * @param requiredRoles
-    * @throws MessageException
-    * @throws ConsumerException
-    */
-   public void initialize(List<String> requiredRoles) throws MessageException, ConsumerException
-   {
-      if(openIdConsumerManager == null)
-         openIdConsumerManager = new ConsumerManager();
-      
-      fetchRequest = FetchRequest.createFetchRequest();
-      //Work on the required attributes
-      if(StringUtil.isNotNull(requiredAttributes))
-      {
-         List<String> tokens = StringUtil.tokenize(requiredAttributes);
-         for(String token: tokens)
-         {
-            fetchRequest.addAttribute(token, OpenIDAliasMapper.get(token),true);
-         }
-      }
-      //Work on the optional attributes
-      if(StringUtil.isNotNull(optionalAttributes))
-      {
-         List<String> tokens = StringUtil.tokenize(optionalAttributes);
-         for(String token: tokens)
-         {
-            String type = OpenIDAliasMapper.get(token);
-            if(type == null)
-            {
-               log.error("Null Type returned for " + token);
+    private String openIdServiceUrl = null;
+
+    private String returnURL = null;
+
+    private String requiredAttributes, optionalAttributes = null;
+
+    private boolean initialized = false;
+
+    protected List<String> roles = new ArrayList<String>();
+
+    public static ThreadLocal<Principal> cachedPrincipal = new ThreadLocal<Principal>();
+
+    public static ThreadLocal<List<String>> cachedRoles = new ThreadLocal<List<String>>();
+    public static String EMPTY_PASSWORD = "EMPTY";
+
+    private enum STATES {
+        AUTH, AUTHZ, FINISH
+    };
+
+    private enum Providers {
+        GOOGLE("https://www.google.com/accounts/o8/id"), YAHOO("https://me.yahoo.com/"), MYSPACE("myspace.com"), MYOPENID(
+                "https://myopenid.com/");
+
+        private String name;
+
+        Providers(String name) {
+            this.name = name;
+        }
+
+        String get() {
+            return name;
+        }
+    }
+
+    public OpenIDProcessor(String theReturnURL, String requiredAttributes, String optionalAttributes) {
+        this.returnURL = theReturnURL;
+        this.requiredAttributes = requiredAttributes;
+        this.optionalAttributes = optionalAttributes;
+    }
+
+    /**
+     * Return whether the processor has initialized
+     *
+     * @return
+     */
+    public boolean isInitialized() {
+        return initialized;
+    }
+
+    /**
+     * Initialize the processor
+     *
+     * @param requiredRoles
+     * @throws MessageException
+     * @throws ConsumerException
+     */
+    public void initialize(List<String> requiredRoles) throws MessageException, ConsumerException {
+        if (openIdConsumerManager == null)
+            openIdConsumerManager = new ConsumerManager();
+
+        fetchRequest = FetchRequest.createFetchRequest();
+        // Work on the required attributes
+        if (StringUtil.isNotNull(requiredAttributes)) {
+            List<String> tokens = StringUtil.tokenize(requiredAttributes);
+            for (String token : tokens) {
+                fetchRequest.addAttribute(token, OpenIDAliasMapper.get(token), true);
             }
-            fetchRequest.addAttribute(token, type,false);
-         }
-      }
-      
-      roles.addAll(requiredRoles);
-      initialized = true;
-   }
-   
-   @SuppressWarnings("unchecked")
-   public boolean prepareAndSendAuthRequest(Request request, Response response) throws IOException
-   { 
-      //Figure out the service url
-      String authType = request.getParameter(AUTH_TYPE);
-      if(authType == null || authType.length() == 0)
-      {
-         authType = (String) request.getSession().getAttribute(AUTH_TYPE);
-      }
-      determineServiceUrl(authType);
-      
-      String openId = openIdServiceUrl;
-      Session session = request.getSessionInternal(true);
-      if(openId != null)
-      { 
-         session.setNote("openid", openId);
-         List<DiscoveryInformation> discoveries;
-         try
-         {
-            discoveries = openIdConsumerManager.discover(openId);
-         }
-         catch (DiscoveryException e)
-         { 
-            throw new RuntimeException(e);
-         }
+        }
+        // Work on the optional attributes
+        if (StringUtil.isNotNull(optionalAttributes)) {
+            List<String> tokens = StringUtil.tokenize(optionalAttributes);
+            for (String token : tokens) {
+                String type = OpenIDAliasMapper.get(token);
+                if (type == null) {
+                    log.error("Null Type returned for " + token);
+                }
+                fetchRequest.addAttribute(token, type, false);
+            }
+        }
 
-         DiscoveryInformation discovered = openIdConsumerManager.associate(discoveries);
-         session.setNote("discovery", discovered);
-         try
-         {
-            AuthRequest authReq = openIdConsumerManager.authenticate(discovered, returnURL);
+        roles.addAll(requiredRoles);
+        initialized = true;
+    }
 
-            //Add in required attributes
-            authReq.addExtension(fetchRequest);
-            
-            String url = authReq.getDestinationUrl(true);
-            response.sendRedirect(url);
-            
-            request.getSession().setAttribute("STATE", STATES.AUTH.name());
-            return false;
-         }
-         catch (Exception e)
-         { 
+    @SuppressWarnings("unchecked")
+    public boolean prepareAndSendAuthRequest(Request request, Response response) throws IOException {
+        // Figure out the service url
+        String authType = request.getParameter(AUTH_TYPE);
+        if (authType == null || authType.length() == 0) {
+            authType = (String) request.getSession().getAttribute(AUTH_TYPE);
+        }
+        determineServiceUrl(authType);
+
+        String openId = openIdServiceUrl;
+        Session session = request.getSessionInternal(true);
+        if (openId != null) {
+            session.setNote("openid", openId);
+            List<DiscoveryInformation> discoveries;
+            try {
+                discoveries = openIdConsumerManager.discover(openId);
+            } catch (DiscoveryException e) {
+                throw new RuntimeException(e);
+            }
+
+            DiscoveryInformation discovered = openIdConsumerManager.associate(discoveries);
+            session.setNote("discovery", discovered);
+            try {
+                AuthRequest authReq = openIdConsumerManager.authenticate(discovered, returnURL);
+
+                // Add in required attributes
+                authReq.addExtension(fetchRequest);
+
+                String url = authReq.getDestinationUrl(true);
+                response.sendRedirect(url);
+
+                request.getSession().setAttribute("STATE", STATES.AUTH.name());
+                return false;
+            } catch (Exception e) {
+                throw new RuntimeException(e);
+            }
+        }
+        return false;
+    }
+
+    @SuppressWarnings("unchecked")
+    public Principal processIncomingAuthResult(Request request, Response response, Realm realm) throws IOException {
+        Principal principal = null;
+        Session session = request.getSessionInternal(false);
+        if (session == null)
+            throw new RuntimeException("wrong lifecycle: session was null");
+
+        // extract the parameters from the authentication response
+        // (which comes in as a HTTP request from the OpenID provider)
+        ParameterList responseParamList = new ParameterList(request.getParameterMap());
+        // retrieve the previously stored discovery information
+        DiscoveryInformation discovered = (DiscoveryInformation) session.getNote("discovery");
+        if (discovered == null)
+            throw new RuntimeException("discovered information was null");
+        // extract the receiving URL from the HTTP request
+        StringBuffer receivingURL = request.getRequestURL();
+        String queryString = request.getQueryString();
+        if (queryString != null && queryString.length() > 0)
+            receivingURL.append("?").append(request.getQueryString());
+
+        // verify the response; ConsumerManager needs to be the same
+        // (static) instance used to place the authentication request
+        VerificationResult verification;
+        try {
+            verification = openIdConsumerManager.verify(receivingURL.toString(), responseParamList, discovered);
+        } catch (Exception e) {
             throw new RuntimeException(e);
-         }
-      } 
-      return false;
-   }
-   
-   @SuppressWarnings("unchecked")
-   public Principal processIncomingAuthResult(Request request, Response response, Realm realm) throws IOException
-   {
-      Principal principal = null;
-      Session session = request.getSessionInternal(false);
-      if(session == null)
-         throw new RuntimeException("wrong lifecycle: session was null");
-      
-      // extract the parameters from the authentication response
-      // (which comes in as a HTTP request from the OpenID provider)
-      ParameterList responseParamList = new ParameterList(request.getParameterMap());
-      // retrieve the previously stored discovery information
-      DiscoveryInformation discovered = (DiscoveryInformation) session.getNote("discovery");
-      if(discovered == null)
-         throw new RuntimeException("discovered information was null");
-      // extract the receiving URL from the HTTP request
-      StringBuffer receivingURL = request.getRequestURL();
-      String queryString = request.getQueryString();
-      if (queryString != null && queryString.length() > 0)
-         receivingURL.append("?").append(request.getQueryString());
+        }
 
-      // verify the response; ConsumerManager needs to be the same
-      // (static) instance used to place the authentication request
-      VerificationResult verification;
-      try
-      {
-         verification = openIdConsumerManager.verify(receivingURL.toString(), responseParamList, discovered);
-      }
-      catch (Exception e)
-      { 
-         throw new RuntimeException(e);
-      }
-      
-      // examine the verification result and extract the verified identifier
-      Identifier identifier = verification.getVerifiedId();
+        // examine the verification result and extract the verified identifier
+        Identifier identifier = verification.getVerifiedId();
 
-      if (identifier != null)
-      {
-         AuthSuccess authSuccess = (AuthSuccess) verification.getAuthResponse();
+        if (identifier != null) {
+            AuthSuccess authSuccess = (AuthSuccess) verification.getAuthResponse();
 
-         Map<String, List<String>> attributes = null;
-         if (authSuccess.hasExtension(AxMessage.OPENID_NS_AX))
-         {
-            FetchResponse fetchResp;
-            try
-            {
-               fetchResp = (FetchResponse) authSuccess.getExtension(AxMessage.OPENID_NS_AX);
+            Map<String, List<String>> attributes = null;
+            if (authSuccess.hasExtension(AxMessage.OPENID_NS_AX)) {
+                FetchResponse fetchResp;
+                try {
+                    fetchResp = (FetchResponse) authSuccess.getExtension(AxMessage.OPENID_NS_AX);
+                } catch (MessageException e) {
+                    throw new RuntimeException(e);
+                }
+
+                attributes = fetchResp.getAttributes();
             }
-            catch (MessageException e)
-            {
-               throw new RuntimeException(e);
+
+            OpenIdPrincipal openIDPrincipal = createPrincipal(identifier.getIdentifier(), discovered.getOPEndpoint(),
+                    attributes);
+            request.getSession().setAttribute("PRINCIPAL", openIDPrincipal);
+
+            String principalName = openIDPrincipal.getName();
+            cachedPrincipal.set(openIDPrincipal);
+
+            if (isJBossEnv()) {
+                cachedRoles.set(roles);
+                principal = realm.authenticate(principalName, EMPTY_PASSWORD);
+            } else {
+                // Create a Tomcat Generic Principal
+                principal = new GenericPrincipal(realm, principalName, null, roles, openIDPrincipal);
             }
 
-            attributes = fetchResp.getAttributes();
-         }
+            if (trace)
+                log.trace("Logged in as:" + principal);
+        } else {
+            response.sendError(HttpServletResponse.SC_FORBIDDEN);
+        }
+        return principal;
+    }
 
-         OpenIdPrincipal openIDPrincipal = createPrincipal(identifier.getIdentifier(), discovered.getOPEndpoint(),
-               attributes);
-         request.getSession().setAttribute("PRINCIPAL", openIDPrincipal);
-         
-         String principalName = openIDPrincipal.getName();
-         cachedPrincipal.set(openIDPrincipal);
-         
-         if(isJBossEnv())
-         {
-            cachedRoles.set(roles);
-            principal = realm.authenticate(principalName, EMPTY_PASSWORD); 
-         }
-         else
-         { 
-            //Create a Tomcat Generic Principal
-            principal = new GenericPrincipal(realm, principalName, null, roles, openIDPrincipal);
-         }
+    private OpenIdPrincipal createPrincipal(String identifier, URL openIdProvider, Map<String, List<String>> attributes) {
+        return new OpenIdPrincipal(identifier, openIdProvider, attributes);
+    }
 
-         if(trace)
-            log.trace("Logged in as:" + principal); 
-      }
-      else
-      {
-         response.sendError(HttpServletResponse.SC_FORBIDDEN);
-      }
-      return principal;
-   }
+    private boolean isJBossEnv() {
+        Class<?> clazz = SecurityActions.loadClass(getClass(), "org.jboss.as.web.WebServer");
+        if (clazz == null)
+            clazz = SecurityActions.loadClass(getClass(), "org.jboss.system.Service");
+        if (clazz != null)
+            return true;
+        return false;
+    }
 
-   private OpenIdPrincipal createPrincipal(String identifier, URL openIdProvider, Map<String, List<String>> attributes)
-   {
-      return new OpenIdPrincipal(identifier, openIdProvider, attributes);
-   }
-   
-   private boolean isJBossEnv()
-   {
-      Class<?> clazz = SecurityActions.loadClass(getClass(), "org.jboss.as.web.WebServer");
-      if(clazz == null)
-    	  clazz = SecurityActions.loadClass(getClass(), "org.jboss.system.Service");
-      if( clazz != null )
-         return true;
-      return false;
-   }
-   
-   private void determineServiceUrl(String service)
-   {
-      openIdServiceUrl = Providers.GOOGLE.get();
-      if(StringUtil.isNotNull(service))
-      {
-         if("google".equals(service))
-            openIdServiceUrl = Providers.GOOGLE.get();
-         else if("yahoo".equals(service))
-            openIdServiceUrl = Providers.YAHOO.get();
-         else if("myspace".equals(service))
-            openIdServiceUrl = Providers.MYSPACE.get();
-         else if("myopenid".equals(service))
-            openIdServiceUrl = Providers.MYOPENID.get();
-      }
-   }
+    private void determineServiceUrl(String service) {
+        openIdServiceUrl = Providers.GOOGLE.get();
+        if (StringUtil.isNotNull(service)) {
+            if ("google".equals(service))
+                openIdServiceUrl = Providers.GOOGLE.get();
+            else if ("yahoo".equals(service))
+                openIdServiceUrl = Providers.YAHOO.get();
+            else if ("myspace".equals(service))
+                openIdServiceUrl = Providers.MYSPACE.get();
+            else if ("myopenid".equals(service))
+                openIdServiceUrl = Providers.MYOPENID.get();
+        }
+    }
 }
\ No newline at end of file

Modified: social/trunk/openid/src/main/java/org/picketlink/social/openid/auth/SecurityActions.java
===================================================================
--- social/trunk/openid/src/main/java/org/picketlink/social/openid/auth/SecurityActions.java	2012-03-19 20:36:39 UTC (rev 1527)
+++ social/trunk/openid/src/main/java/org/picketlink/social/openid/auth/SecurityActions.java	2012-03-19 20:39:31 UTC (rev 1528)
@@ -2,7 +2,7 @@
  * JBoss, Home of Professional Open Source.
  * Copyright 2011, 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. 
+ * 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
@@ -31,120 +31,93 @@
 
 /**
  * Privileged Blocks
+ *
  * @author Anil Saldhana
  * @since May 19, 2011
  */
-class SecurityActions
-{
-   static SecurityContext createSecurityContext( final String name)
-   {
-      return AccessController.doPrivileged(new PrivilegedAction<SecurityContext>()
-      {
-         public SecurityContext run()
-         { 
-            try
-            {
-               return SecurityContextFactory.createSecurityContext(name);
+class SecurityActions {
+    static SecurityContext createSecurityContext(final String name) {
+        return AccessController.doPrivileged(new PrivilegedAction<SecurityContext>() {
+            public SecurityContext run() {
+                try {
+                    return SecurityContextFactory.createSecurityContext(name);
+                } catch (Exception e) {
+                    throw new RuntimeException(e);
+                }
             }
-            catch (Exception e)
-            {
-               throw new RuntimeException(e);
+        });
+    }
+
+    static void setSecurityContext(final SecurityContext sc) {
+        AccessController.doPrivileged(new PrivilegedAction<Void>() {
+
+            public Void run() {
+                SecurityContextAssociation.setSecurityContext(sc);
+                return null;
             }
-         }
-      });
-   }
-   
-   static void setSecurityContext( final SecurityContext sc)
-   {
-      AccessController.doPrivileged(new PrivilegedAction<Void>()
-      {
+        });
+    }
 
-         public Void run()
-         { 
-            SecurityContextAssociation.setSecurityContext(sc);
-            return null;
-         }
-      });
-   }
-   
-   static SecurityContext getSecurityContext()
-   {
-      return AccessController.doPrivileged(new PrivilegedAction<SecurityContext>()
-      {
+    static SecurityContext getSecurityContext() {
+        return AccessController.doPrivileged(new PrivilegedAction<SecurityContext>() {
 
-         public SecurityContext run()
-         { 
-            return SecurityContextAssociation.getSecurityContext();
-         }
-      });
-   }
-   
-   static ClassLoader getContextClassLoader()
-   {
-      return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>()
-      {
+            public SecurityContext run() {
+                return SecurityContextAssociation.getSecurityContext();
+            }
+        });
+    }
 
-         public ClassLoader run()
-         { 
-            return Thread.currentThread().getContextClassLoader();
-         }
-      });
-   }
-   
+    static ClassLoader getContextClassLoader() {
+        return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
 
-   /**
-    * Use reflection to get the {@link Method} on a {@link Class} with the
-    * given parameter types
-    * @param clazz
-    * @param methodName
-    * @param parameterTypes
-    * @return
-    */
-   static Method getMethod(final Class<?> clazz, final String methodName, final Class<?>[] parameterTypes)
-   {
-      return AccessController.doPrivileged(new PrivilegedAction<Method>()
-      {
-         public Method run()
-         {
-            try
-            {
-               return clazz.getDeclaredMethod(methodName, parameterTypes);
+            public ClassLoader run() {
+                return Thread.currentThread().getContextClassLoader();
             }
-            catch (Exception e)
-            {
-               return null;
+        });
+    }
+
+    /**
+     * Use reflection to get the {@link Method} on a {@link Class} with the given parameter types
+     *
+     * @param clazz
+     * @param methodName
+     * @param parameterTypes
+     * @return
+     */
+    static Method getMethod(final Class<?> clazz, final String methodName, final Class<?>[] parameterTypes) {
+        return AccessController.doPrivileged(new PrivilegedAction<Method>() {
+            public Method run() {
+                try {
+                    return clazz.getDeclaredMethod(methodName, parameterTypes);
+                } catch (Exception e) {
+                    return null;
+                }
             }
-         }
-      });
-   }
-   
-   /**
-    * Using the caller class, try to load a class using its classloader. If unsuccessful, use the TCCL
-    * @param theAskingClass
-    * @param fqn
-    * @return
-    */
-   static Class<?> loadClass(final Class<?> theAskingClass, final String fqn)
-   {
-	   return AccessController.doPrivileged(new PrivilegedAction<Class<?>>()
-	   {
-	         public Class<?> run()
-	         {
-	            try
-	            {
-	            	ClassLoader tcl = theAskingClass.getClassLoader();
-	            	return tcl.loadClass(fqn);
-	            }
-	            catch (Exception e)
-	            {
-	               try {
-					return Thread.currentThread().getContextClassLoader().loadClass(fqn);
-				} catch (ClassNotFoundException e1) {
-					return null;
-				}
-	            }
-	         }
-	   }); 
-   }
+        });
+    }
 
+    /**
+     * Using the caller class, try to load a class using its classloader. If unsuccessful, use the TCCL
+     *
+     * @param theAskingClass
+     * @param fqn
+     * @return
+     */
+    static Class<?> loadClass(final Class<?> theAskingClass, final String fqn) {
+        return AccessController.doPrivileged(new PrivilegedAction<Class<?>>() {
+            public Class<?> run() {
+                try {
+                    ClassLoader tcl = theAskingClass.getClassLoader();
+                    return tcl.loadClass(fqn);
+                } catch (Exception e) {
+                    try {
+                        return Thread.currentThread().getContextClassLoader().loadClass(fqn);
+                    } catch (ClassNotFoundException e1) {
+                        return null;
+                    }
+                }
+            }
+        });
+    }
+
 }
\ No newline at end of file

Modified: social/trunk/openid/src/main/java/org/picketlink/social/openid/constants/OpenIDAliasMapper.java
===================================================================
--- social/trunk/openid/src/main/java/org/picketlink/social/openid/constants/OpenIDAliasMapper.java	2012-03-19 20:36:39 UTC (rev 1527)
+++ social/trunk/openid/src/main/java/org/picketlink/social/openid/constants/OpenIDAliasMapper.java	2012-03-19 20:39:31 UTC (rev 1528)
@@ -2,7 +2,7 @@
  * JBoss, Home of Professional Open Source.
  * Copyright 2011, 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. 
+ * 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
@@ -25,36 +25,33 @@
 import java.util.Map;
 
 /**
- * Provides a mapping of OpenID Attribute alias
- * to type
+ * Provides a mapping of OpenID Attribute alias to type
+ *
  * @author Anil Saldhana
  * @since Sep 17, 2011
  */
-public class OpenIDAliasMapper
-{
-   private static Map<String,String> map = new HashMap<String,String>();
-   
-   static
-   {
-      map.put("name", "http://schema.openid.net/namePerson");
-      map.put("email", "http://schema.openid.net/contact/email");
-      map.put("birthDate", "http://schema.openid.net/birthDate");
-      map.put("gender", "http://schema.openid.net/person/gender");
-      map.put("postalCode", "http://schema.openid.net/contact/postalCode/home");
-      map.put("country", "http://schema.openid.net/contact/country/home");
-      map.put("language", "http://schema.openid.net/pref/language");
-      map.put("timezone", "http://schema.openid.net/pref/timezone");
-      
-      map.put("timezone", "http://schema.openid.net/pref/timezone");
-      
-      map.put( "ax_email", "http://axschema.org/contact/email");
-      map.put( "ax_firstName", "http://axschema.org/namePerson/first");
-      map.put( "ax_lastName", "http://axschema.org/namePerson/last");
-      map.put( "ax_fullName", "http://axschema.org/namePerson");
-   }
-   
-   public static String get(String key)
-   {
-      return map.get(key);
-   }
+public class OpenIDAliasMapper {
+    private static Map<String, String> map = new HashMap<String, String>();
+
+    static {
+        map.put("name", "http://schema.openid.net/namePerson");
+        map.put("email", "http://schema.openid.net/contact/email");
+        map.put("birthDate", "http://schema.openid.net/birthDate");
+        map.put("gender", "http://schema.openid.net/person/gender");
+        map.put("postalCode", "http://schema.openid.net/contact/postalCode/home");
+        map.put("country", "http://schema.openid.net/contact/country/home");
+        map.put("language", "http://schema.openid.net/pref/language");
+        map.put("timezone", "http://schema.openid.net/pref/timezone");
+
+        map.put("timezone", "http://schema.openid.net/pref/timezone");
+
+        map.put("ax_email", "http://axschema.org/contact/email");
+        map.put("ax_firstName", "http://axschema.org/namePerson/first");
+        map.put("ax_lastName", "http://axschema.org/namePerson/last");
+        map.put("ax_fullName", "http://axschema.org/namePerson");
+    }
+
+    public static String get(String key) {
+        return map.get(key);
+    }
 }
\ No newline at end of file

Modified: social/trunk/openid/src/main/java/org/picketlink/social/openid/providers/OpenIDTokenProvider.java
===================================================================
--- social/trunk/openid/src/main/java/org/picketlink/social/openid/providers/OpenIDTokenProvider.java	2012-03-19 20:36:39 UTC (rev 1527)
+++ social/trunk/openid/src/main/java/org/picketlink/social/openid/providers/OpenIDTokenProvider.java	2012-03-19 20:39:31 UTC (rev 1528)
@@ -2,7 +2,7 @@
  * 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. 
+ * 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
@@ -22,7 +22,7 @@
 package org.picketlink.social.openid.providers;
 
 import javax.xml.namespace.QName;
- 
+
 import org.jboss.security.xacml.sunxacml.ProcessingException;
 import org.picketlink.identity.federation.core.interfaces.ProtocolContext;
 import org.picketlink.identity.federation.core.interfaces.SecurityTokenProvider;
@@ -34,162 +34,143 @@
 import org.picketlink.social.openid.providers.helpers.OpenIDProtocolContext.MODE;
 import org.picketlink.social.openid.providers.helpers.OpenIDProviderManager;
 import org.picketlink.social.openid.providers.helpers.OpenIDTokenRegistryStore;
-import org.picketlink.social.openid.providers.helpers.OpenIDProviderManager.OpenIDMessage; 
+import org.picketlink.social.openid.providers.helpers.OpenIDProviderManager.OpenIDMessage;
 
 /**
  * @author Anil.Saldhana at redhat.com
  * @since Jan 20, 2011
  */
-public class OpenIDTokenProvider extends AbstractSecurityTokenProvider implements SecurityTokenProvider
-{ 
-   public final static String OPENID_1_0_NS = "urn:openid:1:0";
-   public final static String OPENID_1_1_NS = "urn:openid:1:1";
-   public final static String OPENID_2_0_NS = "urn:openid:2:0";
-   
-   protected static OpenIDProviderManager serverManager = null; //Will be initialized the first time of access
-   
-   /**
-    * @see org.picketlink.social.interfaces.SecurityTokenProvider#supports(java.lang.String)
-    */
-   public boolean supports(String namespace)
-   { 
-      return OPENID_1_0_NS.equals( namespace );
-   }
+public class OpenIDTokenProvider extends AbstractSecurityTokenProvider implements SecurityTokenProvider {
+    public final static String OPENID_1_0_NS = "urn:openid:1:0";
+    public final static String OPENID_1_1_NS = "urn:openid:1:1";
+    public final static String OPENID_2_0_NS = "urn:openid:2:0";
 
-   /**
-    * @see org.picketlink.social.interfaces.SecurityTokenProvider#tokenType()
-    */
-   public String tokenType()
-   { 
-      return OPENID_1_0_NS;
-   }
+    protected static OpenIDProviderManager serverManager = null; // Will be initialized the first time of access
 
-   /**
-    * @see org.picketlink.social.interfaces.SecurityTokenProvider#getSupportedQName()
-    */
-   public QName getSupportedQName()
-   { 
-      return new QName( OPENID_1_0_NS );
-   }
+    /**
+     * @see org.picketlink.social.interfaces.SecurityTokenProvider#supports(java.lang.String)
+     */
+    public boolean supports(String namespace) {
+        return OPENID_1_0_NS.equals(namespace);
+    }
 
-   /**
-    * @see org.picketlink.social.interfaces.SecurityTokenProvider#family()
-    */
-   public String family()
-   { 
-      return SecurityTokenProvider.FAMILY_TYPE.OPENID.name();
-   }
+    /**
+     * @see org.picketlink.social.interfaces.SecurityTokenProvider#tokenType()
+     */
+    public String tokenType() {
+        return OPENID_1_0_NS;
+    }
 
-   /**
-    * @see org.picketlink.social.interfaces.SecurityTokenProvider#issueToken(org.picketlink.social.interfaces.ProtocolContext)
-    */
-   public void issueToken(ProtocolContext context) throws ProcessingException
-   { 
-      if( context instanceof OpenIDProtocolContext == false )
-         return;
-      
-      check();
-      
-      OpenIDProtocolContext openIDProtoCtx = (OpenIDProtocolContext) context;
-      if( serverManager.getEndPoint() == null )
-      {
-         serverManager.setEndPoint( openIDProtoCtx.getEndpoint() );
-      }
-      
-      OpenIDParameterList requestp = openIDProtoCtx.getRequestParameterList();
-      OpenIDMessage responsem = null;
-      
-      if( openIDProtoCtx.getIssueError() )
-      {
-         String errorText = openIDProtoCtx.getErrorText() == null ? "Unknown request" : openIDProtoCtx.getErrorText();
-         
-         responsem = serverManager.getDirectError( errorText );
-      }
-      else
-      {
-         MODE mode = openIDProtoCtx.getMode();
-         switch (mode )
-         {
-            case ASSOCIATE :
-               responsem = serverManager.processAssociationRequest( requestp );
-               break;
-            
-            case CHECK_AUTHENTICATION:
-               validateToken(openIDProtoCtx);
-               return;
-            
-            case CHECK_ID_SETUP:
-            case CHECK_ID_IMMEDIATE:
-               AUTH_HOLDER authHolder = openIDProtoCtx.getAuthenticationHolder();
-               if( authHolder == null )
-                  throw new ProcessingException( "Authentication Holder is null" );
-               
-               responsem = serverManager.processAuthenticationRequest(requestp,
-                     authHolder.getUserSelectedId(),
-                     authHolder.getUserSelectedClaimedId(),
-                     authHolder.isAuthenticatedAndApproved() );
-               break;
-            default:
-               throw new ProcessingException("Unknown mode"); 
-         } 
-      }
-      openIDProtoCtx.setResponseMessage( responsem );
-   }
+    /**
+     * @see org.picketlink.social.interfaces.SecurityTokenProvider#getSupportedQName()
+     */
+    public QName getSupportedQName() {
+        return new QName(OPENID_1_0_NS);
+    }
 
-   /**
-    * @see org.picketlink.social.interfaces.SecurityTokenProvider#renewToken(org.picketlink.social.interfaces.ProtocolContext)
-    */
-   public void renewToken(ProtocolContext context) throws ProcessingException
-   { 
-      if( context instanceof OpenIDProtocolContext == false )
-         return;
-      
-      check();
-   }
+    /**
+     * @see org.picketlink.social.interfaces.SecurityTokenProvider#family()
+     */
+    public String family() {
+        return SecurityTokenProvider.FAMILY_TYPE.OPENID.name();
+    }
 
-   /*
-    * @see org.picketlink.social.interfaces.SecurityTokenProvider#cancelToken(org.picketlink.social.interfaces.ProtocolContext)
-    */
-   public void cancelToken(ProtocolContext context) throws ProcessingException
-   { 
-      if( context instanceof OpenIDProtocolContext == false )
-         return;
-      
-      check();
-   }
+    /**
+     * @see org.picketlink.social.interfaces.SecurityTokenProvider#issueToken(org.picketlink.social.interfaces.ProtocolContext)
+     */
+    public void issueToken(ProtocolContext context) throws ProcessingException {
+        if (context instanceof OpenIDProtocolContext == false)
+            return;
 
-   /**
-    * @see org.picketlink.social.interfaces.SecurityTokenProvider#validateToken(org.picketlink.social.interfaces.ProtocolContext)
-    */
-   public void validateToken(ProtocolContext context) throws ProcessingException
-   { 
-      if( context instanceof OpenIDProtocolContext == false )
-         return;
-      
-       check();
-      
-      OpenIDProtocolContext openIDProtoCtx = (OpenIDProtocolContext) context;
-      if( serverManager.getEndPoint() == null )
-      {
-         serverManager.setEndPoint( openIDProtoCtx.getEndpoint() );
-      }
-      
-      OpenIDParameterList requestp = openIDProtoCtx.getRequestParameterList();
-      OpenIDMessage responsem = serverManager.verify( requestp );
-      openIDProtoCtx.setResponseMessage( responsem );
-   }
-   
-   protected void check()
-   { 
-      SecurityManager sm = System.getSecurityManager();
-      if( sm != null )
-         sm.checkPermission( PicketLinkCoreSTS.rte );
-      
-      if( serverManager == null )
-      {
+        check();
 
-         serverManager = new OpenIDProviderManager();
-         serverManager.initialize( new OpenIDTokenRegistryStore(), new OpenIDTokenRegistryStore()); 
-      }
-   }
+        OpenIDProtocolContext openIDProtoCtx = (OpenIDProtocolContext) context;
+        if (serverManager.getEndPoint() == null) {
+            serverManager.setEndPoint(openIDProtoCtx.getEndpoint());
+        }
+
+        OpenIDParameterList requestp = openIDProtoCtx.getRequestParameterList();
+        OpenIDMessage responsem = null;
+
+        if (openIDProtoCtx.getIssueError()) {
+            String errorText = openIDProtoCtx.getErrorText() == null ? "Unknown request" : openIDProtoCtx.getErrorText();
+
+            responsem = serverManager.getDirectError(errorText);
+        } else {
+            MODE mode = openIDProtoCtx.getMode();
+            switch (mode) {
+                case ASSOCIATE:
+                    responsem = serverManager.processAssociationRequest(requestp);
+                    break;
+
+                case CHECK_AUTHENTICATION:
+                    validateToken(openIDProtoCtx);
+                    return;
+
+                case CHECK_ID_SETUP:
+                case CHECK_ID_IMMEDIATE:
+                    AUTH_HOLDER authHolder = openIDProtoCtx.getAuthenticationHolder();
+                    if (authHolder == null)
+                        throw new ProcessingException("Authentication Holder is null");
+
+                    responsem = serverManager.processAuthenticationRequest(requestp, authHolder.getUserSelectedId(),
+                            authHolder.getUserSelectedClaimedId(), authHolder.isAuthenticatedAndApproved());
+                    break;
+                default:
+                    throw new ProcessingException("Unknown mode");
+            }
+        }
+        openIDProtoCtx.setResponseMessage(responsem);
+    }
+
+    /**
+     * @see org.picketlink.social.interfaces.SecurityTokenProvider#renewToken(org.picketlink.social.interfaces.ProtocolContext)
+     */
+    public void renewToken(ProtocolContext context) throws ProcessingException {
+        if (context instanceof OpenIDProtocolContext == false)
+            return;
+
+        check();
+    }
+
+    /*
+     * @see org.picketlink.social.interfaces.SecurityTokenProvider#cancelToken(org.picketlink.social.interfaces.ProtocolContext)
+     */
+    public void cancelToken(ProtocolContext context) throws ProcessingException {
+        if (context instanceof OpenIDProtocolContext == false)
+            return;
+
+        check();
+    }
+
+    /**
+     * @see org.picketlink.social.interfaces.SecurityTokenProvider#validateToken(org.picketlink.social.interfaces.ProtocolContext)
+     */
+    public void validateToken(ProtocolContext context) throws ProcessingException {
+        if (context instanceof OpenIDProtocolContext == false)
+            return;
+
+        check();
+
+        OpenIDProtocolContext openIDProtoCtx = (OpenIDProtocolContext) context;
+        if (serverManager.getEndPoint() == null) {
+            serverManager.setEndPoint(openIDProtoCtx.getEndpoint());
+        }
+
+        OpenIDParameterList requestp = openIDProtoCtx.getRequestParameterList();
+        OpenIDMessage responsem = serverManager.verify(requestp);
+        openIDProtoCtx.setResponseMessage(responsem);
+    }
+
+    protected void check() {
+        SecurityManager sm = System.getSecurityManager();
+        if (sm != null)
+            sm.checkPermission(PicketLinkCoreSTS.rte);
+
+        if (serverManager == null) {
+
+            serverManager = new OpenIDProviderManager();
+            serverManager.initialize(new OpenIDTokenRegistryStore(), new OpenIDTokenRegistryStore());
+        }
+    }
 }
\ No newline at end of file

Modified: social/trunk/openid/src/main/java/org/picketlink/social/openid/providers/OpenIDVersion2TokenProvider.java
===================================================================
--- social/trunk/openid/src/main/java/org/picketlink/social/openid/providers/OpenIDVersion2TokenProvider.java	2012-03-19 20:36:39 UTC (rev 1527)
+++ social/trunk/openid/src/main/java/org/picketlink/social/openid/providers/OpenIDVersion2TokenProvider.java	2012-03-19 20:39:31 UTC (rev 1528)
@@ -2,7 +2,7 @@
  * 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. 
+ * 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
@@ -25,26 +25,23 @@
 
 /**
  * A {@code SecurityTokenProvider} implementation for Open ID v2
+ *
  * @author Anil.Saldhana at redhat.com
  * @since Jan 20, 2011
  */
-public class OpenIDVersion2TokenProvider extends OpenIDTokenProvider
-{ 
-   @Override
-   public boolean supports(String namespace)
-   {
-      return OPENID_2_0_NS.equals( namespace );
-   }
+public class OpenIDVersion2TokenProvider extends OpenIDTokenProvider {
+    @Override
+    public boolean supports(String namespace) {
+        return OPENID_2_0_NS.equals(namespace);
+    }
 
-   @Override
-   public String tokenType()
-   { 
-      return OPENID_2_0_NS;
-   }
+    @Override
+    public String tokenType() {
+        return OPENID_2_0_NS;
+    }
 
-   @Override
-   public QName getSupportedQName()
-   { 
-      return new QName( OPENID_2_0_NS );
-   }   
+    @Override
+    public QName getSupportedQName() {
+        return new QName(OPENID_2_0_NS);
+    }
 }
\ No newline at end of file

Modified: social/trunk/openid/src/main/java/org/picketlink/social/openid/providers/helpers/OpenIDParameterList.java
===================================================================
--- social/trunk/openid/src/main/java/org/picketlink/social/openid/providers/helpers/OpenIDParameterList.java	2012-03-19 20:36:39 UTC (rev 1527)
+++ social/trunk/openid/src/main/java/org/picketlink/social/openid/providers/helpers/OpenIDParameterList.java	2012-03-19 20:39:31 UTC (rev 1528)
@@ -2,7 +2,7 @@
  * 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. 
+ * 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
@@ -27,21 +27,19 @@
 
 /**
  * Parameter List passed in the messages
+ *
  * @author Anil.Saldhana at redhat.com
  * @since Jul 15, 2009
  */
-public class OpenIDParameterList extends ParameterList
-{
-   private static final long serialVersionUID = 1L;
+public class OpenIDParameterList extends ParameterList {
+    private static final long serialVersionUID = 1L;
 
-   public OpenIDParameterList()
-   {
-      super(); 
-   }
+    public OpenIDParameterList() {
+        super();
+    }
 
-   @SuppressWarnings({ "rawtypes"})
-   public OpenIDParameterList(Map parameterMap)
-   {
-      super(parameterMap); 
-   }
+    @SuppressWarnings({ "rawtypes" })
+    public OpenIDParameterList(Map parameterMap) {
+        super(parameterMap);
+    }
 }

Modified: social/trunk/openid/src/main/java/org/picketlink/social/openid/providers/helpers/OpenIDProtocolContext.java
===================================================================
--- social/trunk/openid/src/main/java/org/picketlink/social/openid/providers/helpers/OpenIDProtocolContext.java	2012-03-19 20:36:39 UTC (rev 1527)
+++ social/trunk/openid/src/main/java/org/picketlink/social/openid/providers/helpers/OpenIDProtocolContext.java	2012-03-19 20:39:31 UTC (rev 1528)
@@ -2,7 +2,7 @@
  * 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. 
+ * 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
@@ -30,244 +30,236 @@
 
 /**
  * {@code ProtocolContext} for the OpenID Layer
+ *
  * @author Anil.Saldhana at redhat.com
  * @since Jan 20, 2011
  */
-public class OpenIDProtocolContext implements ProtocolContext
-{ 
-   /**
-    * The response message generated by the STS
-    */
-   protected OpenIDMessage responseMessage;
-   
-   /**
-    * The list of request parameters for use by the STS
-    */
-   protected OpenIDParameterList requestParameterList;
-   
-   /**
-    * The Server Manager needs an endpoint
-    */
-   protected String endpoint;
-   
-   /**
-    * Should the STS issue an error?
-    */
-   protected Boolean issueError = Boolean.FALSE;
-   
-   /**
-    * What is the text the STS should use for the error?
-    */
-   protected String errorText = null;
+public class OpenIDProtocolContext implements ProtocolContext {
+    /**
+     * The response message generated by the STS
+     */
+    protected OpenIDMessage responseMessage;
 
-   /**
-    * The OpenID mode
-    */
-   protected MODE mode;
-  
-   /**
-    * STS uses the AUTH_HOLDER information for processing authentication requests
-    */
-   protected AUTH_HOLDER authenticationHolder;
-   
-   /**
-    * An Enum indicating the OpenID mode 
-    */
-   public enum MODE { ASSOCIATE, CHECK_ID_SETUP, CHECK_ID_IMMEDIATE, CHECK_AUTHENTICATION };
-   
-   /**
-    * Class to hold the information for authentication requests 
-    */
-   public static class AUTH_HOLDER
-   {
-      private String userSelectedId, userSelectedClaimedId;
-      private boolean authenticatedAndApproved;
-      
-      public AUTH_HOLDER(String userSelectedId, String userSelectedClaimedId, boolean authenticatedAndApproved)
-      {
-         this.userSelectedId = userSelectedId;
-         this.userSelectedClaimedId = userSelectedClaimedId;
-         this.authenticatedAndApproved = authenticatedAndApproved;
-      }
+    /**
+     * The list of request parameters for use by the STS
+     */
+    protected OpenIDParameterList requestParameterList;
 
-      @Override
-      public String toString()
-      {
-         return "AUTH_HOLDER [userSelectedId=" + userSelectedId + ", userSelectedClaimedId=" + userSelectedClaimedId
-               + ", authenticatedAndApproved=" + authenticatedAndApproved + "]";
-      }
+    /**
+     * The Server Manager needs an endpoint
+     */
+    protected String endpoint;
 
-      public String getUserSelectedId()
-      {
-         return userSelectedId;
-      }
+    /**
+     * Should the STS issue an error?
+     */
+    protected Boolean issueError = Boolean.FALSE;
 
-      public String getUserSelectedClaimedId()
-      {
-         return userSelectedClaimedId;
-      }
+    /**
+     * What is the text the STS should use for the error?
+     */
+    protected String errorText = null;
 
-      public boolean isAuthenticatedAndApproved()
-      {
-         return authenticatedAndApproved;
-      } 
-   }
-   
-   /**
-    * Get the holder of authentication information
-    * @return
-    */
-   public AUTH_HOLDER getAuthenticationHolder()
-   {
-      return authenticationHolder;
-   }
+    /**
+     * The OpenID mode
+     */
+    protected MODE mode;
 
-   /**
-    * Set an authentication holder
-    * @param authenticationHolder
-    */
-   public void setAuthenticationHolder(AUTH_HOLDER authenticationHolder)
-   {
-      this.authenticationHolder = authenticationHolder;
-   }
+    /**
+     * STS uses the AUTH_HOLDER information for processing authentication requests
+     */
+    protected AUTH_HOLDER authenticationHolder;
 
-   /**
-    * Get the Open ID mode
-    * @return
-    */
-   public MODE getMode()
-   {
-      return this.mode;
-   }
-   
-   /**
-    * Set the OpenID mode
-    * @param theMode
-    */
-   public void setMode( MODE theMode )
-   {
-      this.mode = theMode;
-   }
-   
-   /**
-    * Get the error text (Null by default)
-    * @return
-    */
-   public String getErrorText()
-   {
-      return errorText;
-   }
+    /**
+     * An Enum indicating the OpenID mode
+     */
+    public enum MODE {
+        ASSOCIATE, CHECK_ID_SETUP, CHECK_ID_IMMEDIATE, CHECK_AUTHENTICATION
+    };
 
-   /**
-    * Set the error text
-    * @param errorText
-    */
-   public void setErrorText(String errorText)
-   {
-      this.errorText = errorText;
-   }
+    /**
+     * Class to hold the information for authentication requests
+     */
+    public static class AUTH_HOLDER {
+        private String userSelectedId, userSelectedClaimedId;
+        private boolean authenticatedAndApproved;
 
-   /**
-    * Should the STS issue an error response token
-    * @return
-    */
-   public Boolean getIssueError()
-   {
-      return issueError;
-   }
+        public AUTH_HOLDER(String userSelectedId, String userSelectedClaimedId, boolean authenticatedAndApproved) {
+            this.userSelectedId = userSelectedId;
+            this.userSelectedClaimedId = userSelectedClaimedId;
+            this.authenticatedAndApproved = authenticatedAndApproved;
+        }
 
-   /**
-    * Set the error response token for the STS
-    * @param issueError
-    */
-   public void setIssueError(Boolean issueError)
-   {
-      this.issueError = issueError;
-   }
+        @Override
+        public String toString() {
+            return "AUTH_HOLDER [userSelectedId=" + userSelectedId + ", userSelectedClaimedId=" + userSelectedClaimedId
+                    + ", authenticatedAndApproved=" + authenticatedAndApproved + "]";
+        }
 
-   /**
-    * Get the endpoint address
-    * @return
-    */
-   public String getEndpoint()
-   {
-      return endpoint;
-   }
-   
-   /**
-    * Set the endpoint address
-    * @param endpoint
-    */
-   public void setEndpoint(String endpoint)
-   {
-      this.endpoint = endpoint;
-   }
+        public String getUserSelectedId() {
+            return userSelectedId;
+        }
 
-   /**
-    * Get the request parameter list
-    * @return an instanceof {@code OpenIDParameterList}
-    */
-   public OpenIDParameterList getRequestParameterList()
-   {
-      return requestParameterList;
-   }
+        public String getUserSelectedClaimedId() {
+            return userSelectedClaimedId;
+        }
 
-   /**
-    * Set the request parameter list
-    * @param requestParameterList an instanceof {@code OpenIDParameterList}
-    */
-   public void setRequestParameterList(OpenIDParameterList requestParameterList)
-   {
-      this.requestParameterList = requestParameterList;
-   }
+        public boolean isAuthenticatedAndApproved() {
+            return authenticatedAndApproved;
+        }
+    }
 
-   /**
-    * Get the {@code OpenIDMessage} response message that the STS has generated
-    * @return 
-    */
-   public OpenIDMessage getResponseMessage()
-   {
-      return responseMessage;
-   }
-   
-   /**
-    * Set the {@code OpenIDMessage} response message
-    * @param responseMessage
-    */
-   public void setResponseMessage(OpenIDMessage responseMessage)
-   {
-      this.responseMessage = responseMessage;
-   }
+    /**
+     * Get the holder of authentication information
+     *
+     * @return
+     */
+    public AUTH_HOLDER getAuthenticationHolder() {
+        return authenticationHolder;
+    }
 
-   /**
-    * @see org.picketlink.identity.federation.core.interfaces.ProtocolContext#serviceName()
-    */
-   public String serviceName()
-   {
-      return null;
-   }
+    /**
+     * Set an authentication holder
+     *
+     * @param authenticationHolder
+     */
+    public void setAuthenticationHolder(AUTH_HOLDER authenticationHolder) {
+        this.authenticationHolder = authenticationHolder;
+    }
 
-   /**
-    * @see org.picketlink.identity.federation.core.interfaces.ProtocolContext#tokenType()
-    */
-   public String tokenType()
-   {
-      return OpenIDTokenProvider.OPENID_1_0_NS;
-   }
+    /**
+     * Get the Open ID mode
+     *
+     * @return
+     */
+    public MODE getMode() {
+        return this.mode;
+    }
 
-   /**
-    * @see org.picketlink.identity.federation.core.interfaces.ProtocolContext#getQName()
-    */
-   public QName getQName()
-   {
-      return new QName( OpenIDTokenProvider.OPENID_1_0_NS );
-   }
+    /**
+     * Set the OpenID mode
+     *
+     * @param theMode
+     */
+    public void setMode(MODE theMode) {
+        this.mode = theMode;
+    }
 
-   /**
-    * @see org.picketlink.identity.federation.core.interfaces.ProtocolContext#family()
-    */
-   public String family()
-   { 
-      return SecurityTokenProvider.FAMILY_TYPE.OPENID.name();
-   } 
+    /**
+     * Get the error text (Null by default)
+     *
+     * @return
+     */
+    public String getErrorText() {
+        return errorText;
+    }
+
+    /**
+     * Set the error text
+     *
+     * @param errorText
+     */
+    public void setErrorText(String errorText) {
+        this.errorText = errorText;
+    }
+
+    /**
+     * Should the STS issue an error response token
+     *
+     * @return
+     */
+    public Boolean getIssueError() {
+        return issueError;
+    }
+
+    /**
+     * Set the error response token for the STS
+     *
+     * @param issueError
+     */
+    public void setIssueError(Boolean issueError) {
+        this.issueError = issueError;
+    }
+
+    /**
+     * Get the endpoint address
+     *
+     * @return
+     */
+    public String getEndpoint() {
+        return endpoint;
+    }
+
+    /**
+     * Set the endpoint address
+     *
+     * @param endpoint
+     */
+    public void setEndpoint(String endpoint) {
+        this.endpoint = endpoint;
+    }
+
+    /**
+     * Get the request parameter list
+     *
+     * @return an instanceof {@code OpenIDParameterList}
+     */
+    public OpenIDParameterList getRequestParameterList() {
+        return requestParameterList;
+    }
+
+    /**
+     * Set the request parameter list
+     *
+     * @param requestParameterList an instanceof {@code OpenIDParameterList}
+     */
+    public void setRequestParameterList(OpenIDParameterList requestParameterList) {
+        this.requestParameterList = requestParameterList;
+    }
+
+    /**
+     * Get the {@code OpenIDMessage} response message that the STS has generated
+     *
+     * @return
+     */
+    public OpenIDMessage getResponseMessage() {
+        return responseMessage;
+    }
+
+    /**
+     * Set the {@code OpenIDMessage} response message
+     *
+     * @param responseMessage
+     */
+    public void setResponseMessage(OpenIDMessage responseMessage) {
+        this.responseMessage = responseMessage;
+    }
+
+    /**
+     * @see org.picketlink.identity.federation.core.interfaces.ProtocolContext#serviceName()
+     */
+    public String serviceName() {
+        return null;
+    }
+
+    /**
+     * @see org.picketlink.identity.federation.core.interfaces.ProtocolContext#tokenType()
+     */
+    public String tokenType() {
+        return OpenIDTokenProvider.OPENID_1_0_NS;
+    }
+
+    /**
+     * @see org.picketlink.identity.federation.core.interfaces.ProtocolContext#getQName()
+     */
+    public QName getQName() {
+        return new QName(OpenIDTokenProvider.OPENID_1_0_NS);
+    }
+
+    /**
+     * @see org.picketlink.identity.federation.core.interfaces.ProtocolContext#family()
+     */
+    public String family() {
+        return SecurityTokenProvider.FAMILY_TYPE.OPENID.name();
+    }
 }
\ No newline at end of file

Modified: social/trunk/openid/src/main/java/org/picketlink/social/openid/providers/helpers/OpenIDProviderManager.java
===================================================================
--- social/trunk/openid/src/main/java/org/picketlink/social/openid/providers/helpers/OpenIDProviderManager.java	2012-03-19 20:36:39 UTC (rev 1527)
+++ social/trunk/openid/src/main/java/org/picketlink/social/openid/providers/helpers/OpenIDProviderManager.java	2012-03-19 20:39:31 UTC (rev 1528)
@@ -2,7 +2,7 @@
  * 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. 
+ * 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
@@ -31,138 +31,126 @@
 
 /**
  * Manages a OpenID Provider
+ *
  * @author Anil.Saldhana at redhat.com
  * @since Jul 15, 2009
  */
-public class OpenIDProviderManager
-{
-   /**
-    * Internal server manager for processing
-    */
-   private ServerManager serverManager = new ServerManager();
-   
-   /**
-    * Initialize internal data structures
-    */
-   public void initialize()
-   {
-      serverManager.setSharedAssociations(new InMemoryServerAssociationStore());
-      serverManager.setPrivateAssociations(new InMemoryServerAssociationStore());
-   }
-   
-   /**
-    * Initialize the Shared Association and Private Association stores
-    * @param sharedAssociationStore a set of 2 association stores {@code ServerAssociationStore}
-    * @throws {@code IllegalArgumentException} if the number of stores is not 2
-    */
-   public void initialize( ServerAssociationStore... sharedAssociationStore )
-   {
-      if( sharedAssociationStore == null || sharedAssociationStore.length == 0 )
-      {
-         initialize();
-         return;
-      }
-      
-      if( sharedAssociationStore.length != 2 )
-         throw new IllegalArgumentException( "Number of association stores not equal to 2" );
-      serverManager.setSharedAssociations( sharedAssociationStore[0] );
-      serverManager.setPrivateAssociations( sharedAssociationStore[1] );
-   }
-   
-   /**
-    * Get the end point where the provider is active
-    * @return string an url
-    */
-   public String getEndPoint()
-   {
-      return serverManager.getOPEndpointUrl();
-   }
-   
-   /**
-    * Set the end point where the provider is active
-    * @param url
-    */
-   public void setEndPoint(String url)
-   {
-      serverManager.setOPEndpointUrl(url);
-   }
-   
-   /**
-    * Process a request from the RP/Relying Party (or OpenID Consumer)
-    * for authenticating an user
-    * @param requestParams
-    * @param userSelId
-    * @param userSelClaimed
-    * @param authenticatedAndApproved
-    * @return
-    */
-   public OpenIDMessage processAuthenticationRequest(ParameterList requestParams,
-         String userSelId,
-         String userSelClaimed,
-         boolean authenticatedAndApproved)
-   {
-      Message authMessage = serverManager.authResponse(requestParams, 
-            userSelId, userSelClaimed, authenticatedAndApproved);
-      
-      return new OpenIDMessage(authMessage); 
-   }
-   
-   /**
-    * Process a request for association from the RP
-    * @param requestParams
-    * @return
-    */
-   public OpenIDMessage processAssociationRequest(ParameterList requestParams)
-   {
-      return new OpenIDMessage(serverManager.associationResponse(requestParams));
-   }
-   
-   /**
-    * Process a verification request from RP for an already
-    * authenticated user
-    * @param requestParams
-    * @return
-    */
-   public OpenIDMessage verify(ParameterList requestParams)
-   {
-      return new OpenIDMessage(serverManager.verify(requestParams));
-   }
-   
-   /**
-    * Create an error message that needs to be passed to the RP
-    * @param msg
-    * @return
-    */
-   public OpenIDMessage getDirectError(String msg)
-   {
-     return new OpenIDMessage(DirectError.createDirectError(msg));  
-   }
-   
-   /**
-    * Class to hold the open id message 
-    */
-   public static class OpenIDMessage
-   {
-      private Message message;
-      
-      OpenIDMessage(Message message)
-      {
-         this.message = message;
-      }
-      
-      public boolean isSuccessful()
-      {
-         return message instanceof AuthSuccess;
-      }
-      
-      public String getDestinationURL(boolean httpget)
-      {
-         return ((AuthSuccess) message).getDestinationUrl(httpget);
-      }
-      
-      public String getResponseText()
-      {
-         return message.keyValueFormEncoding();
-      }
-   }
+public class OpenIDProviderManager {
+    /**
+     * Internal server manager for processing
+     */
+    private ServerManager serverManager = new ServerManager();
+
+    /**
+     * Initialize internal data structures
+     */
+    public void initialize() {
+        serverManager.setSharedAssociations(new InMemoryServerAssociationStore());
+        serverManager.setPrivateAssociations(new InMemoryServerAssociationStore());
+    }
+
+    /**
+     * Initialize the Shared Association and Private Association stores
+     *
+     * @param sharedAssociationStore a set of 2 association stores {@code ServerAssociationStore}
+     * @throws {@code IllegalArgumentException} if the number of stores is not 2
+     */
+    public void initialize(ServerAssociationStore... sharedAssociationStore) {
+        if (sharedAssociationStore == null || sharedAssociationStore.length == 0) {
+            initialize();
+            return;
+        }
+
+        if (sharedAssociationStore.length != 2)
+            throw new IllegalArgumentException("Number of association stores not equal to 2");
+        serverManager.setSharedAssociations(sharedAssociationStore[0]);
+        serverManager.setPrivateAssociations(sharedAssociationStore[1]);
+    }
+
+    /**
+     * Get the end point where the provider is active
+     *
+     * @return string an url
+     */
+    public String getEndPoint() {
+        return serverManager.getOPEndpointUrl();
+    }
+
+    /**
+     * Set the end point where the provider is active
+     *
+     * @param url
+     */
+    public void setEndPoint(String url) {
+        serverManager.setOPEndpointUrl(url);
+    }
+
+    /**
+     * Process a request from the RP/Relying Party (or OpenID Consumer) for authenticating an user
+     *
+     * @param requestParams
+     * @param userSelId
+     * @param userSelClaimed
+     * @param authenticatedAndApproved
+     * @return
+     */
+    public OpenIDMessage processAuthenticationRequest(ParameterList requestParams, String userSelId, String userSelClaimed,
+            boolean authenticatedAndApproved) {
+        Message authMessage = serverManager.authResponse(requestParams, userSelId, userSelClaimed, authenticatedAndApproved);
+
+        return new OpenIDMessage(authMessage);
+    }
+
+    /**
+     * Process a request for association from the RP
+     *
+     * @param requestParams
+     * @return
+     */
+    public OpenIDMessage processAssociationRequest(ParameterList requestParams) {
+        return new OpenIDMessage(serverManager.associationResponse(requestParams));
+    }
+
+    /**
+     * Process a verification request from RP for an already authenticated user
+     *
+     * @param requestParams
+     * @return
+     */
+    public OpenIDMessage verify(ParameterList requestParams) {
+        return new OpenIDMessage(serverManager.verify(requestParams));
+    }
+
+    /**
+     * Create an error message that needs to be passed to the RP
+     *
+     * @param msg
+     * @return
+     */
+    public OpenIDMessage getDirectError(String msg) {
+        return new OpenIDMessage(DirectError.createDirectError(msg));
+    }
+
+    /**
+     * Class to hold the open id message
+     */
+    public static class OpenIDMessage {
+        private Message message;
+
+        OpenIDMessage(Message message) {
+            this.message = message;
+        }
+
+        public boolean isSuccessful() {
+            return message instanceof AuthSuccess;
+        }
+
+        public String getDestinationURL(boolean httpget) {
+            return ((AuthSuccess) message).getDestinationUrl(httpget);
+        }
+
+        public String getResponseText() {
+            return message.keyValueFormEncoding();
+        }
+    }
 }
\ No newline at end of file

Modified: social/trunk/openid/src/main/java/org/picketlink/social/openid/providers/helpers/OpenIDTokenRegistryStore.java
===================================================================
--- social/trunk/openid/src/main/java/org/picketlink/social/openid/providers/helpers/OpenIDTokenRegistryStore.java	2012-03-19 20:36:39 UTC (rev 1527)
+++ social/trunk/openid/src/main/java/org/picketlink/social/openid/providers/helpers/OpenIDTokenRegistryStore.java	2012-03-19 20:39:31 UTC (rev 1528)
@@ -2,7 +2,7 @@
  * 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. 
+ * 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
@@ -32,50 +32,41 @@
 
 /**
  * A {@code SecurityTokenRegistry} for OpenID that uses in memory registry
+ *
  * @author Anil.Saldhana at redhat.com
  * @since Jan 20, 2011
  */
-public class OpenIDTokenRegistryStore extends DefaultTokenRegistry implements ServerAssociationStore, SecurityTokenRegistry
-{
-   protected InMemoryServerAssociationStore store = new InMemoryServerAssociationStore();
-   
-   /**
-    * @see org.openid4java.server.ServerAssociationStore#generate(java.lang.String, int)
-    */
-   public Association generate(String type, int expiryIn) throws AssociationException
-   { 
-      Association association = store.generate(type, expiryIn);
-      try
-      {
-         addToken( association.getHandle(), association );
-      }
-      catch (IOException e)
-      {
-         throw new AssociationException( e );
-      }
-      return association;
-   }
+public class OpenIDTokenRegistryStore extends DefaultTokenRegistry implements ServerAssociationStore, SecurityTokenRegistry {
+    protected InMemoryServerAssociationStore store = new InMemoryServerAssociationStore();
 
-   /**
-    * @see org.openid4java.server.ServerAssociationStore#load(java.lang.String)
-    */
-   public Association load(String handle)
-   { 
-      return (Association) getToken( handle );
-   }
+    /**
+     * @see org.openid4java.server.ServerAssociationStore#generate(java.lang.String, int)
+     */
+    public Association generate(String type, int expiryIn) throws AssociationException {
+        Association association = store.generate(type, expiryIn);
+        try {
+            addToken(association.getHandle(), association);
+        } catch (IOException e) {
+            throw new AssociationException(e);
+        }
+        return association;
+    }
 
-   /**
-    * @see org.openid4java.server.ServerAssociationStore#remove(java.lang.String)
-    */
-   public void remove(String handle)
-   {  
-      try
-      {
-         removeToken( handle );
-      }
-      catch (IOException e)
-      { 
-         throw new RuntimeException( e );
-      }
-   }
+    /**
+     * @see org.openid4java.server.ServerAssociationStore#load(java.lang.String)
+     */
+    public Association load(String handle) {
+        return (Association) getToken(handle);
+    }
+
+    /**
+     * @see org.openid4java.server.ServerAssociationStore#remove(java.lang.String)
+     */
+    public void remove(String handle) {
+        try {
+            removeToken(handle);
+        } catch (IOException e) {
+            throw new RuntimeException(e);
+        }
+    }
 }
\ No newline at end of file

Modified: social/trunk/openid/src/main/java/org/picketlink/social/openid/servlets/OpenIDConsumerServlet.java
===================================================================
--- social/trunk/openid/src/main/java/org/picketlink/social/openid/servlets/OpenIDConsumerServlet.java	2012-03-19 20:36:39 UTC (rev 1527)
+++ social/trunk/openid/src/main/java/org/picketlink/social/openid/servlets/OpenIDConsumerServlet.java	2012-03-19 20:39:31 UTC (rev 1528)
@@ -2,7 +2,7 @@
  * 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. 
+ * 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
@@ -39,63 +39,53 @@
 import org.picketlink.social.openid.web.HTTPOpenIDContext;
 import org.picketlink.social.openid.web.HTTPProtocolAdaptor;
 
-
 /**
- * OpenID Consumer Servlet that gets a post
- * request from the main JSP page of the consumer
- * web application.
+ * OpenID Consumer Servlet that gets a post request from the main JSP page of the consumer web application.
+ *
  * @author Anil.Saldhana at redhat.com
  * @since Jul 10, 2009
  */
-public class OpenIDConsumerServlet extends HttpServlet
-{
-   private static final long serialVersionUID = 1L; 
- 
-   private transient ServletContext servletContext;
-   private String returnURL;
+public class OpenIDConsumerServlet extends HttpServlet {
+    private static final long serialVersionUID = 1L;
 
-   @Override
-   public void init(ServletConfig config) throws ServletException
-   {
-      super.init(config);
-      this.servletContext = config.getServletContext(); 
-      returnURL = this.servletContext.getInitParameter("returnURL"); 
-   }
-   
-   @Override
-   protected void doPost(HttpServletRequest req, HttpServletResponse resp) 
-   throws ServletException, IOException
-   {
-      if(returnURL == null)
-         returnURL = "http://" + req.getServerName() + ":" + req.getServerPort() +
-                 req.getContextPath() + "/consumer_return.jsp";
-      
-      String userEntry = req.getParameter("openid");
-      OpenIDRequest openIDReq = new OpenIDRequest(userEntry);
-      
-      HttpSession session = req.getSession();
-      OpenIDManager manager = (OpenIDManager) session.getAttribute("openid_manager");
-      if(manager == null)
-      {
-         manager = new OpenIDManager(openIDReq);
-         session.setAttribute("openid_manager", manager); 
-      }
-      manager.setUserString( userEntry );
-      
-      try
-      {
-         OpenIDProviderList listOfProviders = manager.discoverProviders();
-         HTTPOpenIDContext httpOpenIDCtx = new HTTPOpenIDContext(req,resp, this.servletContext);
-         httpOpenIDCtx.setReturnURL(returnURL);
-         
-         HTTPProtocolAdaptor adapter = new HTTPProtocolAdaptor(httpOpenIDCtx);
-         OpenIDProviderInformation providerInfo = manager.associate(adapter, listOfProviders);
-         manager.authenticate(adapter, providerInfo);
-      }
-      catch (OpenIDGeneralException e)
-      {
-         log("[OpenIDConsumerServlet]Exception in dealing with the provider:",e);
-         resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
-      } 
-   }
+    private transient ServletContext servletContext;
+    private String returnURL;
+
+    @Override
+    public void init(ServletConfig config) throws ServletException {
+        super.init(config);
+        this.servletContext = config.getServletContext();
+        returnURL = this.servletContext.getInitParameter("returnURL");
+    }
+
+    @Override
+    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
+        if (returnURL == null)
+            returnURL = "http://" + req.getServerName() + ":" + req.getServerPort() + req.getContextPath()
+                    + "/consumer_return.jsp";
+
+        String userEntry = req.getParameter("openid");
+        OpenIDRequest openIDReq = new OpenIDRequest(userEntry);
+
+        HttpSession session = req.getSession();
+        OpenIDManager manager = (OpenIDManager) session.getAttribute("openid_manager");
+        if (manager == null) {
+            manager = new OpenIDManager(openIDReq);
+            session.setAttribute("openid_manager", manager);
+        }
+        manager.setUserString(userEntry);
+
+        try {
+            OpenIDProviderList listOfProviders = manager.discoverProviders();
+            HTTPOpenIDContext httpOpenIDCtx = new HTTPOpenIDContext(req, resp, this.servletContext);
+            httpOpenIDCtx.setReturnURL(returnURL);
+
+            HTTPProtocolAdaptor adapter = new HTTPProtocolAdaptor(httpOpenIDCtx);
+            OpenIDProviderInformation providerInfo = manager.associate(adapter, listOfProviders);
+            manager.authenticate(adapter, providerInfo);
+        } catch (OpenIDGeneralException e) {
+            log("[OpenIDConsumerServlet]Exception in dealing with the provider:", e);
+            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+        }
+    }
 }
\ No newline at end of file

Modified: social/trunk/openid/src/main/java/org/picketlink/social/openid/servlets/OpenIDProviderServlet.java
===================================================================
--- social/trunk/openid/src/main/java/org/picketlink/social/openid/servlets/OpenIDProviderServlet.java	2012-03-19 20:36:39 UTC (rev 1527)
+++ social/trunk/openid/src/main/java/org/picketlink/social/openid/servlets/OpenIDProviderServlet.java	2012-03-19 20:39:31 UTC (rev 1528)
@@ -2,7 +2,7 @@
  * 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. 
+ * 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
@@ -42,216 +42,171 @@
 import org.picketlink.social.openid.providers.helpers.OpenIDProviderManager.OpenIDMessage;
 
 /**
- * Servlet that provides the Provider functionality
- * for OpenID
+ * Servlet that provides the Provider functionality for OpenID
+ *
  * @author Anil.Saldhana at redhat.com
  * @since Jul 15, 2009
  */
-public class OpenIDProviderServlet extends HttpServlet
-{
-   private static final long serialVersionUID = 1L;
-   private transient ServletContext servletContext = null;
-   private String securePageName = "securepage.jsp";
-   
-   private transient PicketLinkCoreSTS sts = PicketLinkCoreSTS.instance();
+public class OpenIDProviderServlet extends HttpServlet {
+    private static final long serialVersionUID = 1L;
+    private transient ServletContext servletContext = null;
+    private String securePageName = "securepage.jsp";
 
-   @Override
-   public void init(ServletConfig config) throws ServletException
-   {
-      super.init(config);
-      this.servletContext = config.getServletContext();
-      String secpageStr = this.servletContext.getInitParameter("securePage");
-      if(secpageStr != null && secpageStr.length() > 0)
-         securePageName = secpageStr;
-      
-      String configFile = null;
-      String configFileStr = this.servletContext.getInitParameter("configFile");
-      if(configFileStr != null && configFileStr.length() > 0)
-      {
-         try
-         {
-            configFile = servletContext.getResource(configFileStr).toExternalForm();
-         }
-         catch (MalformedURLException e)
-         {
-            throw new ServletException(e);
-         }
-      }
-      
-      log("configFile="+configFile);
+    private transient PicketLinkCoreSTS sts = PicketLinkCoreSTS.instance();
 
-      sts.installDefaultConfiguration( new String[] {configFile} ); 
-   }
+    @Override
+    public void init(ServletConfig config) throws ServletException {
+        super.init(config);
+        this.servletContext = config.getServletContext();
+        String secpageStr = this.servletContext.getInitParameter("securePage");
+        if (secpageStr != null && secpageStr.length() > 0)
+            securePageName = secpageStr;
 
-   @Override
-   protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
-   {
-      doPost(request, response);
-   }
+        String configFile = null;
+        String configFileStr = this.servletContext.getInitParameter("configFile");
+        if (configFileStr != null && configFileStr.length() > 0) {
+            try {
+                configFile = servletContext.getResource(configFileStr).toExternalForm();
+            } catch (MalformedURLException e) {
+                throw new ServletException(e);
+            }
+        }
 
-   @Override
-   protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
-   {
-      HttpSession session = request.getSession(); 
-      
-      OpenIDProtocolContext protoCtx = new OpenIDProtocolContext();
-      
-      protoCtx.setEndpoint(request.getScheme() + "://" + 
-            request.getServerName() + ":" + 
-            request.getServerPort() + 
-            request.getContextPath() +
-      "/provider/");  
+        log("configFile=" + configFile);
 
-      OpenIDParameterList requestp;
+        sts.installDefaultConfiguration(new String[] { configFile });
+    }
 
-      if ("complete".equals(request.getParameter("_action"))) // Completing the authz and authn process by redirecting here
-      {
-         requestp=(OpenIDParameterList) session.getAttribute("parameterlist"); // On a redirect from the OP authn & authz sequence
-      }
-      else
-      {
-         requestp = new OpenIDParameterList(request.getParameterMap());
-         Parameter openidIdentity = requestp.getParameter("openid.identity");
-         if( openidIdentity != null )
-         {
-            session.setAttribute("openid.identity", openidIdentity.getValue()); 
-         }
-         else
-         {
-            log( "The Parameter openid.identity is null " );
-         }
-      }
+    @Override
+    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
+        doPost(request, response);
+    }
 
-      protoCtx.setRequestParameterList( requestp );
-      
-      
-      String mode = requestp.hasParameter("openid.mode") ?
-            requestp.getParameterValue("openid.mode") : null;
+    @Override
+    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
+        HttpSession session = request.getSession();
 
-            OpenIDMessage responsem = null;
-            String responseText = null;
+        OpenIDProtocolContext protoCtx = new OpenIDProtocolContext();
 
-            log("mode=" + mode + "::ParameterMap:" + requestp);
+        protoCtx.setEndpoint(request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
+                + request.getContextPath() + "/provider/");
 
-            if ("associate".equals(mode))
-            {
-               protoCtx.setMode( MODE.ASSOCIATE );
-               try
-               {
-                  sts.issueToken( protoCtx );
-               }
-               catch (ProcessingException e)
-               {
-                  throw new ServletException( e );
-               }
-               
-               responsem = protoCtx.getResponseMessage();
-               
-               // --- process an association request --- 
-               responseText = responsem.getResponseText();
+        OpenIDParameterList requestp;
+
+        if ("complete".equals(request.getParameter("_action"))) // Completing the authz and authn process by redirecting here
+        {
+            requestp = (OpenIDParameterList) session.getAttribute("parameterlist"); // On a redirect from the OP authn & authz
+                                                                                    // sequence
+        } else {
+            requestp = new OpenIDParameterList(request.getParameterMap());
+            Parameter openidIdentity = requestp.getParameter("openid.identity");
+            if (openidIdentity != null) {
+                session.setAttribute("openid.identity", openidIdentity.getValue());
+            } else {
+                log("The Parameter openid.identity is null ");
             }
-            else if ("checkid_setup".equals(mode)
-                  || "checkid_immediate".equals(mode))
-            {
-               // interact with the user and obtain data needed to continue
-               //List userData = userInteraction(requestp);
-               String userSelectedId = null;
-               String userSelectedClaimedId = null;
-               Boolean authenticatedAndApproved = Boolean.FALSE;
+        }
 
-               if ((session.getAttribute("authenticatedAndApproved") == null) ||
-                     (((Boolean)session.getAttribute("authenticatedAndApproved")) == Boolean.FALSE) )
-               {
-                  session.setAttribute("parameterlist", requestp);
-                  response.setContentType("text/html" );
-                  response.sendRedirect( request.getContextPath() + "/" + this.securePageName);
-                  return;
-               }
-               else
-               {
-                  userSelectedId = (String) session.getAttribute("openid.claimed_id");
-                  userSelectedClaimedId = (String) session.getAttribute("openid.identity");
-                  authenticatedAndApproved = (Boolean) session.getAttribute("authenticatedAndApproved");
-                  // Remove the parameterlist so this provider can accept requests from elsewhere
-                  session.removeAttribute("parameterlist");
-                  session.setAttribute("authenticatedAndApproved", Boolean.FALSE); // Makes you authorize each and every time
+        protoCtx.setRequestParameterList(requestp);
 
+        String mode = requestp.hasParameter("openid.mode") ? requestp.getParameterValue("openid.mode") : null;
 
-                  //Fallback
-                  if( authenticatedAndApproved == Boolean.TRUE && userSelectedId == null )
-                  { 
-                     userSelectedId = userSelectedClaimedId;
-                  }
-                  if( "checkid_setup".equals(mode) ) 
-                     protoCtx.setMode( MODE.CHECK_ID_SETUP );
-                  else
-                     protoCtx.setMode( MODE.CHECK_ID_IMMEDIATE );
-                  
-                  protoCtx.setAuthenticationHolder( new AUTH_HOLDER(userSelectedId, 
-                                                           userSelectedClaimedId, authenticatedAndApproved));
-                  
-                  try
-                  {
-                     // --- process an authentication request ---
-                     sts.issueToken(protoCtx);
-                  }
-                  catch (ProcessingException e)
-                  { 
-                     throw new ServletException( e );
-                  }
-                  
-                  responsem = protoCtx.getResponseMessage();
+        OpenIDMessage responsem = null;
+        String responseText = null;
 
-                  // caller will need to decide which of the following to use:
-                  // - GET HTTP-redirect to the return_to URL
-                  // - HTML FORM Redirection
-                  //responseText = response.wwwFormEncoding();
-                  if (responsem.isSuccessful())
-                  {
-                     response.sendRedirect( responsem.getDestinationURL(true));
-                     return;
-                  }
-                  else
-                  {
-                     responseText="<pre>"+ responsem.getResponseText() +"</pre>";
-                  }
+        log("mode=" + mode + "::ParameterMap:" + requestp);
 
-               }
+        if ("associate".equals(mode)) {
+            protoCtx.setMode(MODE.ASSOCIATE);
+            try {
+                sts.issueToken(protoCtx);
+            } catch (ProcessingException e) {
+                throw new ServletException(e);
             }
-            else if ("check_authentication".equals(mode))
-            {
-               try
-               {
-                  // --- processing a verification request ---
-                  sts.validateToken( protoCtx );
-               }
-               catch (ProcessingException e)
-               { 
-                  throw new ServletException( e );
-               }
-               responsem = protoCtx.getResponseMessage();
-               
-               responseText = responsem.getResponseText();
+
+            responsem = protoCtx.getResponseMessage();
+
+            // --- process an association request ---
+            responseText = responsem.getResponseText();
+        } else if ("checkid_setup".equals(mode) || "checkid_immediate".equals(mode)) {
+            // interact with the user and obtain data needed to continue
+            // List userData = userInteraction(requestp);
+            String userSelectedId = null;
+            String userSelectedClaimedId = null;
+            Boolean authenticatedAndApproved = Boolean.FALSE;
+
+            if ((session.getAttribute("authenticatedAndApproved") == null)
+                    || (((Boolean) session.getAttribute("authenticatedAndApproved")) == Boolean.FALSE)) {
+                session.setAttribute("parameterlist", requestp);
+                response.setContentType("text/html");
+                response.sendRedirect(request.getContextPath() + "/" + this.securePageName);
+                return;
+            } else {
+                userSelectedId = (String) session.getAttribute("openid.claimed_id");
+                userSelectedClaimedId = (String) session.getAttribute("openid.identity");
+                authenticatedAndApproved = (Boolean) session.getAttribute("authenticatedAndApproved");
+                // Remove the parameterlist so this provider can accept requests from elsewhere
+                session.removeAttribute("parameterlist");
+                session.setAttribute("authenticatedAndApproved", Boolean.FALSE); // Makes you authorize each and every time
+
+                // Fallback
+                if (authenticatedAndApproved == Boolean.TRUE && userSelectedId == null) {
+                    userSelectedId = userSelectedClaimedId;
+                }
+                if ("checkid_setup".equals(mode))
+                    protoCtx.setMode(MODE.CHECK_ID_SETUP);
+                else
+                    protoCtx.setMode(MODE.CHECK_ID_IMMEDIATE);
+
+                protoCtx.setAuthenticationHolder(new AUTH_HOLDER(userSelectedId, userSelectedClaimedId,
+                        authenticatedAndApproved));
+
+                try {
+                    // --- process an authentication request ---
+                    sts.issueToken(protoCtx);
+                } catch (ProcessingException e) {
+                    throw new ServletException(e);
+                }
+
+                responsem = protoCtx.getResponseMessage();
+
+                // caller will need to decide which of the following to use:
+                // - GET HTTP-redirect to the return_to URL
+                // - HTML FORM Redirection
+                // responseText = response.wwwFormEncoding();
+                if (responsem.isSuccessful()) {
+                    response.sendRedirect(responsem.getDestinationURL(true));
+                    return;
+                } else {
+                    responseText = "<pre>" + responsem.getResponseText() + "</pre>";
+                }
+
             }
-            else
-            {
-               protoCtx.setIssueError( Boolean.TRUE );
-               protoCtx.setErrorText( "Unknown request" );
-               try
-               {
-                  // --- error response ---
-                  sts.issueToken(protoCtx);
-               }
-               catch (ProcessingException e)
-               { 
-                  throw new ServletException( e );
-               }
-               responsem = protoCtx.getResponseMessage();
-               
-               responseText = responsem.getResponseText();
+        } else if ("check_authentication".equals(mode)) {
+            try {
+                // --- processing a verification request ---
+                sts.validateToken(protoCtx);
+            } catch (ProcessingException e) {
+                throw new ServletException(e);
             }
+            responsem = protoCtx.getResponseMessage();
 
-            log( "response="+responseText );
-            response.getWriter().write(responseText);
-   }   
+            responseText = responsem.getResponseText();
+        } else {
+            protoCtx.setIssueError(Boolean.TRUE);
+            protoCtx.setErrorText("Unknown request");
+            try {
+                // --- error response ---
+                sts.issueToken(protoCtx);
+            } catch (ProcessingException e) {
+                throw new ServletException(e);
+            }
+            responsem = protoCtx.getResponseMessage();
+
+            responseText = responsem.getResponseText();
+        }
+
+        log("response=" + responseText);
+        response.getWriter().write(responseText);
+    }
 }
\ No newline at end of file

Modified: social/trunk/openid/src/main/java/org/picketlink/social/openid/servlets/OpenIDYadisServlet.java
===================================================================
--- social/trunk/openid/src/main/java/org/picketlink/social/openid/servlets/OpenIDYadisServlet.java	2012-03-19 20:36:39 UTC (rev 1527)
+++ social/trunk/openid/src/main/java/org/picketlink/social/openid/servlets/OpenIDYadisServlet.java	2012-03-19 20:39:31 UTC (rev 1528)
@@ -2,7 +2,7 @@
  * 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. 
+ * 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
@@ -34,89 +34,79 @@
 
 /**
  * Servlet used for Yadis Discovery in OpenID
+ *
  * @author Anil.Saldhana at redhat.com
  * @since Jul 7, 2009
  */
-public class OpenIDYadisServlet extends HttpServlet
-{
-   private static final long serialVersionUID = 1L; 
-   
-   private String yadisResourceFile = "/WEB-INF/openid-yadis.xml";
-   private String yadisURL = null;
-   
-   private boolean supportHTTP_HEAD = false; //By default, we support GET
-   
-   private transient InputStream yadisResourceInputStream = null;
-    
-   @Override
-   public void init(ServletConfig config) throws ServletException
-   {
-      super.init(config);
-      ServletContext context = config.getServletContext();
-      
-      String yadisResourceFileStr = config.getInitParameter("yadisResourceFile");
-      if(yadisResourceFileStr != null && yadisResourceFileStr.length() > 0)
-         yadisResourceFile = yadisResourceFileStr;
-      log("yadisResourceFile Location="+ yadisResourceFile);
-       
-      yadisURL = config.getInitParameter("yadisResourceURL");
-      
-      if(yadisURL == null || yadisURL.length() == 0)
-      {
-         yadisResourceInputStream = context.getResourceAsStream(yadisResourceFile);
-         if(yadisResourceInputStream == null)
-            throw new RuntimeException("yadisResourceFile is missing"); 
-      }
-    
-      String supportHead = config.getInitParameter("support_HTTP_HEAD");
-      if(supportHead != null && supportHead.length() > 0)
-         supportHTTP_HEAD = Boolean.parseBoolean(supportHead);
-   }
- 
+public class OpenIDYadisServlet extends HttpServlet {
+    private static final long serialVersionUID = 1L;
 
-   @Override
-   protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
-   {
-      if(this.supportHTTP_HEAD)
-      {
-         log("GET not supported as HTTP HEAD has been configured");
-         resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
-         return;
-      }
-      else
-      { 
-         if(yadisResourceInputStream == null)
-         {
-            log("ERROR::yadisResourceInputStream is null");
-            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
-            return; 
-         }
-         
-         byte[] barr = new byte[1024];
-         for (int i = 0; i < barr.length; i++) 
-         {
-            int b = yadisResourceInputStream.read( );
-            if (b  == -1) break;
-            barr[i] = (byte) b;
-          }
-         
-         resp.setContentType("application/xrds+xml");
-         resp.setStatus(HttpServletResponse.SC_OK);  
-         OutputStream os = resp.getOutputStream();
-         os.write(barr);
-         os.flush();
-         os.close(); 
-      } 
-   }
+    private String yadisResourceFile = "/WEB-INF/openid-yadis.xml";
+    private String yadisURL = null;
 
-   @Override
-   protected void doHead(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
-   {
-       if(this.supportHTTP_HEAD)
-       {
-          resp.addHeader("X-XRDS-Location", yadisURL); 
-       }
-       resp.setStatus(HttpServletResponse.SC_OK);  
-       return;
-   } 
+    private boolean supportHTTP_HEAD = false; // By default, we support GET
+
+    private transient InputStream yadisResourceInputStream = null;
+
+    @Override
+    public void init(ServletConfig config) throws ServletException {
+        super.init(config);
+        ServletContext context = config.getServletContext();
+
+        String yadisResourceFileStr = config.getInitParameter("yadisResourceFile");
+        if (yadisResourceFileStr != null && yadisResourceFileStr.length() > 0)
+            yadisResourceFile = yadisResourceFileStr;
+        log("yadisResourceFile Location=" + yadisResourceFile);
+
+        yadisURL = config.getInitParameter("yadisResourceURL");
+
+        if (yadisURL == null || yadisURL.length() == 0) {
+            yadisResourceInputStream = context.getResourceAsStream(yadisResourceFile);
+            if (yadisResourceInputStream == null)
+                throw new RuntimeException("yadisResourceFile is missing");
+        }
+
+        String supportHead = config.getInitParameter("support_HTTP_HEAD");
+        if (supportHead != null && supportHead.length() > 0)
+            supportHTTP_HEAD = Boolean.parseBoolean(supportHead);
+    }
+
+    @Override
+    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
+        if (this.supportHTTP_HEAD) {
+            log("GET not supported as HTTP HEAD has been configured");
+            resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
+            return;
+        } else {
+            if (yadisResourceInputStream == null) {
+                log("ERROR::yadisResourceInputStream is null");
+                resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+                return;
+            }
+
+            byte[] barr = new byte[1024];
+            for (int i = 0; i < barr.length; i++) {
+                int b = yadisResourceInputStream.read();
+                if (b == -1)
+                    break;
+                barr[i] = (byte) b;
+            }
+
+            resp.setContentType("application/xrds+xml");
+            resp.setStatus(HttpServletResponse.SC_OK);
+            OutputStream os = resp.getOutputStream();
+            os.write(barr);
+            os.flush();
+            os.close();
+        }
+    }
+
+    @Override
+    protected void doHead(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
+        if (this.supportHTTP_HEAD) {
+            resp.addHeader("X-XRDS-Location", yadisURL);
+        }
+        resp.setStatus(HttpServletResponse.SC_OK);
+        return;
+    }
 }
\ No newline at end of file

Modified: social/trunk/openid/src/main/java/org/picketlink/social/openid/servlets/SecurityActions.java
===================================================================
--- social/trunk/openid/src/main/java/org/picketlink/social/openid/servlets/SecurityActions.java	2012-03-19 20:36:39 UTC (rev 1527)
+++ social/trunk/openid/src/main/java/org/picketlink/social/openid/servlets/SecurityActions.java	2012-03-19 20:39:31 UTC (rev 1528)
@@ -2,7 +2,7 @@
  * 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. 
+ * 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
@@ -26,23 +26,21 @@
 
 /**
  * Privileged Blocks
+ *
  * @author Anil.Saldhana at redhat.com
  * @since Dec 9, 2008
  */
-class SecurityActions
-{
-   /**
-    * Get the Thread Context ClassLoader
-    * @return
-    */
-   static ClassLoader getContextClassLoader()
-   {
-      return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>()
-      {
-         public ClassLoader run()
-         {
-            return Thread.currentThread().getContextClassLoader();
-         }
-      });
-   }
+class SecurityActions {
+    /**
+     * Get the Thread Context ClassLoader
+     *
+     * @return
+     */
+    static ClassLoader getContextClassLoader() {
+        return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
+            public ClassLoader run() {
+                return Thread.currentThread().getContextClassLoader();
+            }
+        });
+    }
 }

Modified: social/trunk/openid/src/main/java/org/picketlink/social/openid/web/HTTPOpenIDContext.java
===================================================================
--- social/trunk/openid/src/main/java/org/picketlink/social/openid/web/HTTPOpenIDContext.java	2012-03-19 20:36:39 UTC (rev 1527)
+++ social/trunk/openid/src/main/java/org/picketlink/social/openid/web/HTTPOpenIDContext.java	2012-03-19 20:39:31 UTC (rev 1528)
@@ -2,7 +2,7 @@
  * 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. 
+ * 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
@@ -29,29 +29,25 @@
 
 /**
  * HTTP Context for OpenID
+ *
  * @author Anil.Saldhana at redhat.com
  * @since Jul 6, 2009
  */
-public class HTTPOpenIDContext extends HTTPContext
-{ 
-   private String returnURL; 
-    
-   public HTTPOpenIDContext(HttpServletRequest httpReq, HttpServletResponse httpResp,
-         ServletContext sctx)
-   {
-      super(httpReq, httpResp, sctx); 
-   } 
+public class HTTPOpenIDContext extends HTTPContext {
+    private String returnURL;
 
-   public String getReturnURL()
-   {
-      return returnURL;
-   } 
-   
-   //Setters
-   
-   public HTTPOpenIDContext setReturnURL(String url)
-   {
-      this.returnURL = url;
-      return this;
-   } 
+    public HTTPOpenIDContext(HttpServletRequest httpReq, HttpServletResponse httpResp, ServletContext sctx) {
+        super(httpReq, httpResp, sctx);
+    }
+
+    public String getReturnURL() {
+        return returnURL;
+    }
+
+    // Setters
+
+    public HTTPOpenIDContext setReturnURL(String url) {
+        this.returnURL = url;
+        return this;
+    }
 }
\ No newline at end of file

Modified: social/trunk/openid/src/main/java/org/picketlink/social/openid/web/HTTPOpenIDProvider.java
===================================================================
--- social/trunk/openid/src/main/java/org/picketlink/social/openid/web/HTTPOpenIDProvider.java	2012-03-19 20:36:39 UTC (rev 1527)
+++ social/trunk/openid/src/main/java/org/picketlink/social/openid/web/HTTPOpenIDProvider.java	2012-03-19 20:39:31 UTC (rev 1528)
@@ -2,7 +2,7 @@
  * 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. 
+ * 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
@@ -36,107 +36,84 @@
 
 /**
  * Common code at an OpenID Provider
+ *
  * @author Anil.Saldhana at redhat.com
  * @since Jul 7, 2009
  */
-public class HTTPOpenIDProvider
-{
-   public String process(HttpServletRequest request, HttpServletResponse response) 
-   throws IOException
-   {
-      HttpSession session = request.getSession();
-      
-      ServerManager manager=new ServerManager();
-      manager.setSharedAssociations(new InMemoryServerAssociationStore());
-      manager.setPrivateAssociations(new InMemoryServerAssociationStore());
-      manager.setOPEndpointUrl(request.getScheme() + "://" 
-            + request.getServerName() + ":" 
-            + request.getServerPort() + "/simple-openid/provider.jsp");
-      
-      ParameterList requestp;
+public class HTTPOpenIDProvider {
+    public String process(HttpServletRequest request, HttpServletResponse response) throws IOException {
+        HttpSession session = request.getSession();
 
-      if ("complete".equals(request.getParameter("_action"))) // Completing the authz and authn process by redirecting here
-      {
-          requestp=(ParameterList) session.getAttribute("parameterlist"); // On a redirect from the OP authn & authz sequence
-      }
-      else
-      {
-          requestp = new ParameterList(request.getParameterMap());
-      }
+        ServerManager manager = new ServerManager();
+        manager.setSharedAssociations(new InMemoryServerAssociationStore());
+        manager.setPrivateAssociations(new InMemoryServerAssociationStore());
+        manager.setOPEndpointUrl(request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
+                + "/simple-openid/provider.jsp");
 
-      String mode = requestp.hasParameter("openid.mode") ?
-                  requestp.getParameterValue("openid.mode") : null;
+        ParameterList requestp;
 
-          Message responsem;
-          String responseText;
+        if ("complete".equals(request.getParameter("_action"))) // Completing the authz and authn process by redirecting here
+        {
+            requestp = (ParameterList) session.getAttribute("parameterlist"); // On a redirect from the OP authn & authz
+                                                                              // sequence
+        } else {
+            requestp = new ParameterList(request.getParameterMap());
+        }
 
-          if ("associate".equals(mode))
-          {
-              // --- process an association request ---
-              responsem = manager.associationResponse(requestp);
-              responseText = responsem.keyValueFormEncoding();
-          }
-          else if ("checkid_setup".equals(mode)
-                  || "checkid_immediate".equals(mode))
-          {
-              // interact with the user and obtain data needed to continue
-              //List userData = userInteraction(requestp);
-              String userSelectedId = null;
-              String userSelectedClaimedId = null;
-              Boolean authenticatedAndApproved = Boolean.FALSE;
+        String mode = requestp.hasParameter("openid.mode") ? requestp.getParameterValue("openid.mode") : null;
 
-              if ((session.getAttribute("authenticatedAndApproved") == null) ||
-                      (((Boolean)session.getAttribute("authenticatedAndApproved")) == Boolean.FALSE) )
-              {
-                  session.setAttribute("parameterlist", requestp);
-                  response.sendRedirect("provider_authorization.jsp");
-              }
-              else
-              {
-                  userSelectedId = (String) session.getAttribute("openid.claimed_id");
-                  userSelectedClaimedId = (String) session.getAttribute("openid.identity");
-                  authenticatedAndApproved = (Boolean) session.getAttribute("authenticatedAndApproved");
-                  // Remove the parameterlist so this provider can accept requests from elsewhere
-                  session.removeAttribute("parameterlist");
-                  session.setAttribute("authenticatedAndApproved", Boolean.FALSE); // Makes you authorize each and every time
-              }
+        Message responsem;
+        String responseText;
 
-              // --- process an authentication request ---
-              responsem = manager.authResponse(requestp,
-                      userSelectedId,
-                      userSelectedClaimedId,
-                      authenticatedAndApproved.booleanValue());
+        if ("associate".equals(mode)) {
+            // --- process an association request ---
+            responsem = manager.associationResponse(requestp);
+            responseText = responsem.keyValueFormEncoding();
+        } else if ("checkid_setup".equals(mode) || "checkid_immediate".equals(mode)) {
+            // interact with the user and obtain data needed to continue
+            // List userData = userInteraction(requestp);
+            String userSelectedId = null;
+            String userSelectedClaimedId = null;
+            Boolean authenticatedAndApproved = Boolean.FALSE;
 
-              // caller will need to decide which of the following to use:
-              // - GET HTTP-redirect to the return_to URL
-              // - HTML FORM Redirection
-              //responseText = response.wwwFormEncoding();
-              if (responsem instanceof AuthSuccess)
-              {
-                  response.sendRedirect(((AuthSuccess) responsem).getDestinationUrl(true));
-                  return "";
-              }
-              else
-              {
-                  responseText="<pre>"+responsem.keyValueFormEncoding()+"</pre>";
-              }
-          }
-          else if ("check_authentication".equals(mode))
-          {
-              // --- processing a verification request ---
-              responsem = manager.verify(requestp);
-              responseText = responsem.keyValueFormEncoding();
-          }
-          else
-          {
-              // --- error response ---
-              responsem = DirectError.createDirectError("Unknown request");
-              responseText = responsem.keyValueFormEncoding();
-          }
-          
-          
-      
-      return responseText != null ? responseText.trim() : null;
-   }
+            if ((session.getAttribute("authenticatedAndApproved") == null)
+                    || (((Boolean) session.getAttribute("authenticatedAndApproved")) == Boolean.FALSE)) {
+                session.setAttribute("parameterlist", requestp);
+                response.sendRedirect("provider_authorization.jsp");
+            } else {
+                userSelectedId = (String) session.getAttribute("openid.claimed_id");
+                userSelectedClaimedId = (String) session.getAttribute("openid.identity");
+                authenticatedAndApproved = (Boolean) session.getAttribute("authenticatedAndApproved");
+                // Remove the parameterlist so this provider can accept requests from elsewhere
+                session.removeAttribute("parameterlist");
+                session.setAttribute("authenticatedAndApproved", Boolean.FALSE); // Makes you authorize each and every time
+            }
 
+            // --- process an authentication request ---
+            responsem = manager.authResponse(requestp, userSelectedId, userSelectedClaimedId,
+                    authenticatedAndApproved.booleanValue());
+
+            // caller will need to decide which of the following to use:
+            // - GET HTTP-redirect to the return_to URL
+            // - HTML FORM Redirection
+            // responseText = response.wwwFormEncoding();
+            if (responsem instanceof AuthSuccess) {
+                response.sendRedirect(((AuthSuccess) responsem).getDestinationUrl(true));
+                return "";
+            } else {
+                responseText = "<pre>" + responsem.keyValueFormEncoding() + "</pre>";
+            }
+        } else if ("check_authentication".equals(mode)) {
+            // --- processing a verification request ---
+            responsem = manager.verify(requestp);
+            responseText = responsem.keyValueFormEncoding();
+        } else {
+            // --- error response ---
+            responsem = DirectError.createDirectError("Unknown request");
+            responseText = responsem.keyValueFormEncoding();
+        }
+
+        return responseText != null ? responseText.trim() : null;
+    }
+
 }
\ No newline at end of file

Modified: social/trunk/openid/src/main/java/org/picketlink/social/openid/web/HTTPProtocolAdaptor.java
===================================================================
--- social/trunk/openid/src/main/java/org/picketlink/social/openid/web/HTTPProtocolAdaptor.java	2012-03-19 20:36:39 UTC (rev 1527)
+++ social/trunk/openid/src/main/java/org/picketlink/social/openid/web/HTTPProtocolAdaptor.java	2012-03-19 20:39:31 UTC (rev 1528)
@@ -2,7 +2,7 @@
  * 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. 
+ * 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
@@ -30,7 +30,7 @@
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 
-import org.apache.log4j.Logger; 
+import org.apache.log4j.Logger;
 import org.picketlink.social.openid.api.OpenIDAttributeMap;
 import org.picketlink.social.openid.api.OpenIDLifecycle;
 import org.picketlink.social.openid.api.OpenIDLifecycleEvent;
@@ -42,170 +42,135 @@
 
 /**
  * Protocol adapter for HTTP
+ *
  * @author Anil.Saldhana at redhat.com
  * @since Jul 6, 2009
  */
-public class HTTPProtocolAdaptor implements OpenIDProtocolAdapter, OpenIDLifecycle
-{
-   private static Logger log = Logger.getLogger(HTTPProtocolAdaptor.class);
-   private boolean trace = log.isTraceEnabled();
-   
-   private HttpServletRequest request;
-   private HttpServletResponse response; 
-   private ServletContext servletContext;
-   private String returnURL;
+public class HTTPProtocolAdaptor implements OpenIDProtocolAdapter, OpenIDLifecycle {
+    private static Logger log = Logger.getLogger(HTTPProtocolAdaptor.class);
+    private boolean trace = log.isTraceEnabled();
 
-   public HTTPProtocolAdaptor(HTTPOpenIDContext octx)
-   {
-      if(octx == null)
-         throw new IllegalArgumentException("http openid context is null");
-      
-      this.request = octx.getRequest();
-      this.response = octx.getResponse(); 
-      this.returnURL = octx.getReturnURL();
-      this.servletContext = octx.getServletContext();
-   }
+    private HttpServletRequest request;
+    private HttpServletResponse response;
+    private ServletContext servletContext;
+    private String returnURL;
 
-   public OpenIDAttributeMap getAttributeMap()
-   { 
-      OpenIDAttributeMap map = new OpenIDAttributeMap();
-      if ("1".equals(request.getParameter("nickname"))) 
-      {
-         map.put("nickname", "1");
-      }
-      if ("1".equals(request.getParameter("email"))) 
-      {
-         map.put("email", "1");
-      }
-      if ("1".equals(request.getParameter("fullname"))) 
-      {
-         map.put("fullname", "1");
-      }
-      if ("1".equals(request.getParameter("dob"))) 
-      {
-         map.put("dob", "1");
-      }
-      if ("1".equals(request.getParameter("gender"))) 
-      {
-         map.put("gender", "1");
-      }
-      if ("1".equals(request.getParameter("postcode"))) 
-      {
-         map.put("postcode", "1");
-      }
-      if ("1".equals(request.getParameter("country"))) 
-      {
-         map.put("country", "1");
-      }
-      if ("1".equals(request.getParameter("language"))) 
-      {
-         map.put("language", "1");
-      }
-      if ("1".equals(request.getParameter("timezone"))) 
-      {
-         map.put("timezone", "1");
-      }
+    public HTTPProtocolAdaptor(HTTPOpenIDContext octx) {
+        if (octx == null)
+            throw new IllegalArgumentException("http openid context is null");
 
-      return map;
-   }
+        this.request = octx.getRequest();
+        this.response = octx.getResponse();
+        this.returnURL = octx.getReturnURL();
+        this.servletContext = octx.getServletContext();
+    }
 
-   public String getReturnURL()
-   { 
-      return this.returnURL;
-   } 
-   
-   /**
-    * @throws OpenIDLifeCycleException 
-    * @see OpenIDLifecycle#handle(OpenIDLifecycleEvent)
-    */
-   public void handle(OpenIDLifecycleEvent event) throws OpenIDLifeCycleException 
-   {
-      if(event == null)
-         throw new IllegalArgumentException("event is null");
-      
-      if(event.getEventType() == TYPE.SESSION)
-      {
-         String attr = event.getAttributeName();
-         Object attrVal = event.getAttributeValue();
-         
-         if(event.getOperation() == OP.ADD)
-         {
-            request.getSession().setAttribute(attr, attrVal); 
-         }
-         else if(event.getOperation() == OP.REMOVE)
-         {
-            request.getSession().removeAttribute(attr); 
-         }
-      }
-      
-      if(event.getEventType() == TYPE.SUCCESS)
-         try
-         {
-            response.sendRedirect(".");
-         }
-         catch (IOException e)
-         {
-            throw new OpenIDLifeCycleException(e);
-         }
-   }
-   
-   /**
-    * @see OpenIDLifecycle#handle(OpenIDLifecycleEvent[])
-    */
-   public void handle(OpenIDLifecycleEvent[] eventArr) throws OpenIDLifeCycleException
-   {
-      for(OpenIDLifecycleEvent ev: eventArr)
-      {
-         this.handle(ev);
-      }
-   }
+    public OpenIDAttributeMap getAttributeMap() {
+        OpenIDAttributeMap map = new OpenIDAttributeMap();
+        if ("1".equals(request.getParameter("nickname"))) {
+            map.put("nickname", "1");
+        }
+        if ("1".equals(request.getParameter("email"))) {
+            map.put("email", "1");
+        }
+        if ("1".equals(request.getParameter("fullname"))) {
+            map.put("fullname", "1");
+        }
+        if ("1".equals(request.getParameter("dob"))) {
+            map.put("dob", "1");
+        }
+        if ("1".equals(request.getParameter("gender"))) {
+            map.put("gender", "1");
+        }
+        if ("1".equals(request.getParameter("postcode"))) {
+            map.put("postcode", "1");
+        }
+        if ("1".equals(request.getParameter("country"))) {
+            map.put("country", "1");
+        }
+        if ("1".equals(request.getParameter("language"))) {
+            map.put("language", "1");
+        }
+        if ("1".equals(request.getParameter("timezone"))) {
+            map.put("timezone", "1");
+        }
 
-   public void sendToProvider(int version, String destinationURL, 
-         Map<String, String> paramMap) throws OpenIDProtocolException
-   {
-      if(trace) 
-         log.trace("send to provider=" + version + "::destinationURL=" + destinationURL);
-      
-      if(version == 1)
-      {
-         try
-         {
-            response.sendRedirect(destinationURL);
-            return;
-         }
-         catch (IOException e)
-         {
-            throw new OpenIDProtocolException(e);
-         } 
-      }
+        return map;
+    }
 
-      //Version != 1 
-      
-      // Option 2: HTML FORM Redirection (Allows payloads >2048 bytes)
+    public String getReturnURL() {
+        return this.returnURL;
+    }
 
-      RequestDispatcher dispatcher =
-              this.servletContext.getRequestDispatcher("/formredirection.jsp");
-      request.setAttribute("parameterMap", paramMap);
-      request.setAttribute("destinationUrl", destinationURL);
-      try
-      {
-        dispatcher.forward(request, response); 
-      }
-      catch(IOException io)
-      {
-         throw new OpenIDProtocolException(io);
-      }
-      catch (ServletException e)
-      {
-         throw new OpenIDProtocolException(e);
-      }
-   }
+    /**
+     * @throws OpenIDLifeCycleException
+     * @see OpenIDLifecycle#handle(OpenIDLifecycleEvent)
+     */
+    public void handle(OpenIDLifecycleEvent event) throws OpenIDLifeCycleException {
+        if (event == null)
+            throw new IllegalArgumentException("event is null");
 
-   /**
-    * @see OpenIDLifecycle#getAttributeValue(String)
-    */
-   public Object getAttributeValue(String name)
-   {
-      return this.request.getSession().getAttribute(name);
-   }
+        if (event.getEventType() == TYPE.SESSION) {
+            String attr = event.getAttributeName();
+            Object attrVal = event.getAttributeValue();
+
+            if (event.getOperation() == OP.ADD) {
+                request.getSession().setAttribute(attr, attrVal);
+            } else if (event.getOperation() == OP.REMOVE) {
+                request.getSession().removeAttribute(attr);
+            }
+        }
+
+        if (event.getEventType() == TYPE.SUCCESS)
+            try {
+                response.sendRedirect(".");
+            } catch (IOException e) {
+                throw new OpenIDLifeCycleException(e);
+            }
+    }
+
+    /**
+     * @see OpenIDLifecycle#handle(OpenIDLifecycleEvent[])
+     */
+    public void handle(OpenIDLifecycleEvent[] eventArr) throws OpenIDLifeCycleException {
+        for (OpenIDLifecycleEvent ev : eventArr) {
+            this.handle(ev);
+        }
+    }
+
+    public void sendToProvider(int version, String destinationURL, Map<String, String> paramMap) throws OpenIDProtocolException {
+        if (trace)
+            log.trace("send to provider=" + version + "::destinationURL=" + destinationURL);
+
+        if (version == 1) {
+            try {
+                response.sendRedirect(destinationURL);
+                return;
+            } catch (IOException e) {
+                throw new OpenIDProtocolException(e);
+            }
+        }
+
+        // Version != 1
+
+        // Option 2: HTML FORM Redirection (Allows payloads >2048 bytes)
+
+        RequestDispatcher dispatcher = this.servletContext.getRequestDispatcher("/formredirection.jsp");
+        request.setAttribute("parameterMap", paramMap);
+        request.setAttribute("destinationUrl", destinationURL);
+        try {
+            dispatcher.forward(request, response);
+        } catch (IOException io) {
+            throw new OpenIDProtocolException(io);
+        } catch (ServletException e) {
+            throw new OpenIDProtocolException(e);
+        }
+    }
+
+    /**
+     * @see OpenIDLifecycle#getAttributeValue(String)
+     */
+    public Object getAttributeValue(String name) {
+        return this.request.getSession().getAttribute(name);
+    }
 }
\ No newline at end of file

Modified: social/trunk/openid/src/test/java/org/picketlink/test/social/openid/EmbeddedWebServerBase.java
===================================================================
--- social/trunk/openid/src/test/java/org/picketlink/test/social/openid/EmbeddedWebServerBase.java	2012-03-19 20:36:39 UTC (rev 1527)
+++ social/trunk/openid/src/test/java/org/picketlink/test/social/openid/EmbeddedWebServerBase.java	2012-03-19 20:39:31 UTC (rev 1528)
@@ -2,7 +2,7 @@
  * 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. 
+ * 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
@@ -29,53 +29,48 @@
 
 /**
  * Base class for embedded web server based tests
+ *
  * @author Anil.Saldhana at redhat.com
  * @since Jul 8, 2009
  */
-public abstract class EmbeddedWebServerBase extends TestCase
-{
-   protected Server server = null;
-   
-   public void setUp() throws Exception
-   {
-      super.setUp(); 
-      
-      //Start the Jetty embedded container
-      server = new Server();
-      
-      server.setConnectors(getConnectors());
-      
-      this.establishUserApps(); 
+public abstract class EmbeddedWebServerBase extends TestCase {
+    protected Server server = null;
 
-      server.start();        
-   } 
-   
-   public void tearDown() throws Exception
-   {
-      if(server != null)
-      {
-         server.stop();
-         server.destroy();
-         server = null;
-      } 
-      super.tearDown();
-   }
-   
-   /**
-    * Return the connectors that need to be configured
-    * on the server. Subclasses can create as many connectors
-    * as they want
-    * @return
-    */
-   protected Connector[] getConnectors()
-   {
-      Connector connector=new SocketConnector();
-      connector.setPort(11080);
-      return new Connector[]{connector}; 
-   }
-   
-   /**
-    * Establish the user applications - context, servlets etc
-    */
-   protected abstract void establishUserApps(); 
+    public void setUp() throws Exception {
+        super.setUp();
+
+        // Start the Jetty embedded container
+        server = new Server();
+
+        server.setConnectors(getConnectors());
+
+        this.establishUserApps();
+
+        server.start();
+    }
+
+    public void tearDown() throws Exception {
+        if (server != null) {
+            server.stop();
+            server.destroy();
+            server = null;
+        }
+        super.tearDown();
+    }
+
+    /**
+     * Return the connectors that need to be configured on the server. Subclasses can create as many connectors as they want
+     *
+     * @return
+     */
+    protected Connector[] getConnectors() {
+        Connector connector = new SocketConnector();
+        connector.setPort(11080);
+        return new Connector[] { connector };
+    }
+
+    /**
+     * Establish the user applications - context, servlets etc
+     */
+    protected abstract void establishUserApps();
 }
\ No newline at end of file

Modified: social/trunk/openid/src/test/java/org/picketlink/test/social/openid/InMemoryProtocolAdapter.java
===================================================================
--- social/trunk/openid/src/test/java/org/picketlink/test/social/openid/InMemoryProtocolAdapter.java	2012-03-19 20:36:39 UTC (rev 1527)
+++ social/trunk/openid/src/test/java/org/picketlink/test/social/openid/InMemoryProtocolAdapter.java	2012-03-19 20:39:31 UTC (rev 1528)
@@ -2,7 +2,7 @@
  * 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. 
+ * 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
@@ -39,66 +39,52 @@
 
 /**
  * Adapter that is in memory or the same VM
+ *
  * @author Anil.Saldhana at redhat.com
  * @since Jul 7, 2009
  */
-public class InMemoryProtocolAdapter implements OpenIDProtocolAdapter, OpenIDLifecycle
-{ 
-   public OpenIDAttributeMap getAttributeMap()
-   { 
-      return new OpenIDAttributeMap();
-   }
-   
-   public void handle(OpenIDLifecycleEvent event)
-   { 
-   }
+public class InMemoryProtocolAdapter implements OpenIDProtocolAdapter, OpenIDLifecycle {
+    public OpenIDAttributeMap getAttributeMap() {
+        return new OpenIDAttributeMap();
+    }
 
-   public Object getAttributeValue(String name)
-   {
-      return null;
-   }
+    public void handle(OpenIDLifecycleEvent event) {
+    }
 
-   public void handle(OpenIDLifecycleEvent[] eventArr) throws OpenIDLifeCycleException
-   { 
-   } 
-   
-   public String getReturnURL()
-   {
-      return "http://localhost:11080/consumer";
-   }
+    public Object getAttributeValue(String name) {
+        return null;
+    }
 
-   public void sendToProvider(int version, String destinationURL, Map<String, String> paramMap)
-         throws OpenIDProtocolException
-   {
-      System.out.println("Version="+ version);
-      System.out.println("destinationURL="+ destinationURL);
-      System.out.println("paramMap="+ paramMap);
-      
-      if(version == 1)
-      {   
-         WebConversation wc = new WebConversation();
-         wc.setAuthorization( "anil", "anil" );
-         WebRequest req = new GetMethodWebRequest( destinationURL );
-         try
-         {
-            WebResponse resp = wc.getResponse( req );
-            URL responseURL = resp.getURL(); 
-            if( responseURL.toString().contains( "securepage.jsp" ))
-            {
-               resp = wc.getResponse( responseURL.toString() );
-               WebForm form = resp.getForms()[0];
-               resp = form.submit();
+    public void handle(OpenIDLifecycleEvent[] eventArr) throws OpenIDLifeCycleException {
+    }
+
+    public String getReturnURL() {
+        return "http://localhost:11080/consumer";
+    }
+
+    public void sendToProvider(int version, String destinationURL, Map<String, String> paramMap) throws OpenIDProtocolException {
+        System.out.println("Version=" + version);
+        System.out.println("destinationURL=" + destinationURL);
+        System.out.println("paramMap=" + paramMap);
+
+        if (version == 1) {
+            WebConversation wc = new WebConversation();
+            wc.setAuthorization("anil", "anil");
+            WebRequest req = new GetMethodWebRequest(destinationURL);
+            try {
+                WebResponse resp = wc.getResponse(req);
+                URL responseURL = resp.getURL();
+                if (responseURL.toString().contains("securepage.jsp")) {
+                    resp = wc.getResponse(responseURL.toString());
+                    WebForm form = resp.getForms()[0];
+                    resp = form.submit();
+                }
+            } catch (Exception e) {
+                e.printStackTrace();
+                throw new OpenIDProtocolException();
             }
-         }
-         catch ( Exception e)
-         { 
-            e.printStackTrace();
-            throw new OpenIDProtocolException();
-         }  
-      }
-      else
-      {
-         throw new RuntimeException("Not implemented");
-      }
-   }
+        } else {
+            throw new RuntimeException("Not implemented");
+        }
+    }
 }
\ No newline at end of file

Modified: social/trunk/openid/src/test/java/org/picketlink/test/social/openid/integration/LocalProviderOpenIDUnitTestCase.java
===================================================================
--- social/trunk/openid/src/test/java/org/picketlink/test/social/openid/integration/LocalProviderOpenIDUnitTestCase.java	2012-03-19 20:36:39 UTC (rev 1527)
+++ social/trunk/openid/src/test/java/org/picketlink/test/social/openid/integration/LocalProviderOpenIDUnitTestCase.java	2012-03-19 20:39:31 UTC (rev 1528)
@@ -2,7 +2,7 @@
  * 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. 
+ * 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
@@ -28,7 +28,7 @@
 import javax.servlet.http.HttpServlet;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
- 
+
 import org.picketlink.social.openid.api.OpenIDManager;
 import org.picketlink.social.openid.api.OpenIDManager.OpenIDProviderInformation;
 import org.picketlink.social.openid.api.OpenIDManager.OpenIDProviderList;
@@ -46,153 +46,128 @@
 
 /**
  * Test the OpenID functionality within the VM
+ *
  * @author Anil.Saldhana at redhat.com
  * @since Jul 7, 2009
  */
-public class LocalProviderOpenIDUnitTestCase extends EmbeddedWebServerBase
-{  
-   protected void establishUserApps()
-   {
-      ClassLoader tcl = Thread.currentThread().getContextClassLoader();
-      InputStream is = tcl.getResourceAsStream("openid/localhost-yadis.xml");
+public class LocalProviderOpenIDUnitTestCase extends EmbeddedWebServerBase {
+    protected void establishUserApps() {
+        ClassLoader tcl = Thread.currentThread().getContextClassLoader();
+        InputStream is = tcl.getResourceAsStream("openid/localhost-yadis.xml");
 
-      assertNotNull("Yadis descriptor not null", is);
+        assertNotNull("Yadis descriptor not null", is);
 
-      Context context = new Context(server,"/",Context.SESSIONS); 
-      context.addServlet(new ServletHolder(new YadisServlet(is)), "/*");
+        Context context = new Context(server, "/", Context.SESSIONS);
+        context.addServlet(new ServletHolder(new YadisServlet(is)), "/*");
 
-      context.addServlet(new ServletHolder(new ProviderServlet()), "/provider/");
-   }
+        context.addServlet(new ServletHolder(new ProviderServlet()), "/provider/");
+    }
 
-   public void testOpenIDAuth() throws Exception
-   {
-      //String username = "http://jbosstest.myopenid.com";
-      String username = "http://localhost:11080";
-      InMemoryProtocolAdapter ad = new InMemoryProtocolAdapter();
-      OpenIDRequest openIDRequest = new OpenIDRequest(username);
-      OpenIDManager idm = new OpenIDManager(openIDRequest); 
-      OpenIDProviderList providers = idm.discoverProviders();
-      assertNotNull("List of providers is not null", providers);
+    public void testOpenIDAuth() throws Exception {
+        // String username = "http://jbosstest.myopenid.com";
+        String username = "http://localhost:11080";
+        InMemoryProtocolAdapter ad = new InMemoryProtocolAdapter();
+        OpenIDRequest openIDRequest = new OpenIDRequest(username);
+        OpenIDManager idm = new OpenIDManager(openIDRequest);
+        OpenIDProviderList providers = idm.discoverProviders();
+        assertNotNull("List of providers is not null", providers);
 
-      OpenIDProviderInformation providerInfo = idm.associate(ad,providers);
-      boolean auth = idm.authenticate(ad, providerInfo);
-      assertTrue( "OpenID Auth was successful", auth );
-   }
+        OpenIDProviderInformation providerInfo = idm.associate(ad, providers);
+        boolean auth = idm.authenticate(ad, providerInfo);
+        assertTrue("OpenID Auth was successful", auth);
+    }
 
-   //A provider servlet that always returns true
-   private static class ProviderServlet extends HttpServlet
-   {
-      private static final long serialVersionUID = 1L; 
-      
-      @Override
-      protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
-      {
-         doGet(req, resp);
-      }
+    // A provider servlet that always returns true
+    private static class ProviderServlet extends HttpServlet {
+        private static final long serialVersionUID = 1L;
 
-      @Override
-      protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
-      {
-         System.out.println("Inside ProviderServlet::doGet");
-         
-         ParameterList requestP = new ParameterList(req.getParameterMap());
-         
-         ServerManager manager = new ServerManager();
-         manager.setSharedAssociations(new InMemoryServerAssociationStore());
-         manager.setPrivateAssociations(new InMemoryServerAssociationStore());
-         manager.setOPEndpointUrl("http://localhost:11080/provider/");
-         
-         String userSelectedId = "http://test.localhost:11080";
-         String userSelectedClaimedId = userSelectedId;
-         boolean authenticatedAndApproved = true;
-         
-         String responseText = "";
-         
-         String mode = requestP.hasParameter("openid.mode") ?
-               requestP.getParameterValue("openid.mode") : null;
+        @Override
+        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
+            doGet(req, resp);
+        }
 
-         System.out.println("ProviderServlet::mode="+mode);
-         Message responsem ;
-         if ("associate".equals(mode))
-         {
-                  // --- process an association request ---
-                  responsem = manager.associationResponse(requestP);
-                  responseText = responsem.keyValueFormEncoding().trim();
-         }
-         else if ("checkid_setup".equals(mode)
-               || "checkid_immediate".equals(mode))
-         {
-            responsem = manager.authResponse(requestP,
-                  userSelectedId,
-                  userSelectedClaimedId,
-                  authenticatedAndApproved );
+        @Override
+        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
+            System.out.println("Inside ProviderServlet::doGet");
 
-            if (responsem instanceof AuthSuccess)
-            {
-                resp.sendRedirect(((AuthSuccess) responsem).getDestinationUrl(true));
-                return;
+            ParameterList requestP = new ParameterList(req.getParameterMap());
+
+            ServerManager manager = new ServerManager();
+            manager.setSharedAssociations(new InMemoryServerAssociationStore());
+            manager.setPrivateAssociations(new InMemoryServerAssociationStore());
+            manager.setOPEndpointUrl("http://localhost:11080/provider/");
+
+            String userSelectedId = "http://test.localhost:11080";
+            String userSelectedClaimedId = userSelectedId;
+            boolean authenticatedAndApproved = true;
+
+            String responseText = "";
+
+            String mode = requestP.hasParameter("openid.mode") ? requestP.getParameterValue("openid.mode") : null;
+
+            System.out.println("ProviderServlet::mode=" + mode);
+            Message responsem;
+            if ("associate".equals(mode)) {
+                // --- process an association request ---
+                responsem = manager.associationResponse(requestP);
+                responseText = responsem.keyValueFormEncoding().trim();
+            } else if ("checkid_setup".equals(mode) || "checkid_immediate".equals(mode)) {
+                responsem = manager.authResponse(requestP, userSelectedId, userSelectedClaimedId, authenticatedAndApproved);
+
+                if (responsem instanceof AuthSuccess) {
+                    resp.sendRedirect(((AuthSuccess) responsem).getDestinationUrl(true));
+                    return;
+                } else {
+                    responseText = "<pre>" + responsem.keyValueFormEncoding().trim() + "</pre>";
+                }
+            } else if ("check_authentication".equals(mode)) {
+                // --- processing a verification request ---
+                responsem = manager.verify(requestP);
+                responseText = responsem.keyValueFormEncoding().trim();
+            } else {
+                // --- error response ---
+                responsem = DirectError.createDirectError("Unknown request");
+                responseText = responsem.keyValueFormEncoding().trim();
             }
-            else
-            {
-                responseText="<pre>"+responsem.keyValueFormEncoding().trim()+"</pre>";
-            } 
-         }
-         else if ("check_authentication".equals(mode))
-         {
-             // --- processing a verification request ---
-             responsem = manager.verify(requestP);
-             responseText = responsem.keyValueFormEncoding().trim();
-         }
-         else
-         {
-             // --- error response ---
-             responsem = DirectError.createDirectError("Unknown request");
-             responseText = responsem.keyValueFormEncoding().trim();
-         }
 
-         resp.setStatus(HttpServletResponse.SC_OK); 
-         resp.getWriter().print(responseText);
-      }  
-   }
-   
-   //A Yadis servlet that just reads the XML from the Inputstream and passes it back
-   private class YadisServlet extends HttpServlet
-   {
-      private static final long serialVersionUID = 1L; 
+            resp.setStatus(HttpServletResponse.SC_OK);
+            resp.getWriter().print(responseText);
+        }
+    }
 
-      private InputStream yadisDescriptor;
-    
-      public YadisServlet(InputStream yadisDescriptor)
-      {
-         if(yadisDescriptor == null)
-            throw new RuntimeException("input stream null");
-         this.yadisDescriptor = yadisDescriptor; 
-      } 
+    // A Yadis servlet that just reads the XML from the Inputstream and passes it back
+    private class YadisServlet extends HttpServlet {
+        private static final long serialVersionUID = 1L;
 
-      protected void doGet(HttpServletRequest request, HttpServletResponse resp) 
-      throws ServletException, IOException
-      {
-         System.out.println("Inside Yadis Servlet");
-         if("HEAD".equals(request.getMethod()))
-         {
-            resp.setStatus(HttpServletResponse.SC_OK); 
-            return; 
-         } 
-        
-         //Asking for Yadis discovery
-         byte[] barr = new byte[1024];
-         for (int i = 0; i < barr.length; i++) 
-         {
-            int b = yadisDescriptor.read();
-            if (b  == -1) break;
-            barr[i] = (byte) b;
-          }
-         resp.setContentType("application/xrds+xml");
-         resp.setStatus(HttpServletResponse.SC_OK);  
-         
-         String ycontent = new String(barr);
-         ycontent = ycontent.replace("\n"," ").trim();  
-         resp.getWriter().print(ycontent); 
-      }
-   }
+        private InputStream yadisDescriptor;
+
+        public YadisServlet(InputStream yadisDescriptor) {
+            if (yadisDescriptor == null)
+                throw new RuntimeException("input stream null");
+            this.yadisDescriptor = yadisDescriptor;
+        }
+
+        protected void doGet(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException {
+            System.out.println("Inside Yadis Servlet");
+            if ("HEAD".equals(request.getMethod())) {
+                resp.setStatus(HttpServletResponse.SC_OK);
+                return;
+            }
+
+            // Asking for Yadis discovery
+            byte[] barr = new byte[1024];
+            for (int i = 0; i < barr.length; i++) {
+                int b = yadisDescriptor.read();
+                if (b == -1)
+                    break;
+                barr[i] = (byte) b;
+            }
+            resp.setContentType("application/xrds+xml");
+            resp.setStatus(HttpServletResponse.SC_OK);
+
+            String ycontent = new String(barr);
+            ycontent = ycontent.replace("\n", " ").trim();
+            resp.getWriter().print(ycontent);
+        }
+    }
 }
\ No newline at end of file

Modified: social/trunk/openid/src/test/java/org/picketlink/test/social/openid/integration/YadisMetadataUnitTestCase.java
===================================================================
--- social/trunk/openid/src/test/java/org/picketlink/test/social/openid/integration/YadisMetadataUnitTestCase.java	2012-03-19 20:36:39 UTC (rev 1527)
+++ social/trunk/openid/src/test/java/org/picketlink/test/social/openid/integration/YadisMetadataUnitTestCase.java	2012-03-19 20:39:31 UTC (rev 1528)
@@ -2,7 +2,7 @@
  * 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. 
+ * 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
@@ -27,7 +27,7 @@
 import javax.servlet.http.HttpServlet;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
- 
+
 import org.picketlink.social.openid.api.OpenIDManager;
 import org.picketlink.social.openid.api.OpenIDManager.OpenIDProviderList;
 import org.picketlink.social.openid.api.OpenIDRequest;
@@ -38,60 +38,50 @@
 
 /**
  * Unit test the OpenID Yadis Servlet
+ *
  * @author Anil.Saldhana at redhat.com
  * @since Jul 7, 2009
  */
-public class YadisMetadataUnitTestCase extends EmbeddedWebServerBase
-{    
-   protected void establishUserApps()
-   {
-      Context context = new Context(server,"/",Context.SESSIONS);
-      ServletHolder servletHolder = new ServletHolder(new OpenIDYadisServlet()); 
-      servletHolder.setInitParameter("support_HTTP_HEAD", "true");
-      servletHolder.setInitParameter("yadisResourceURL", "http://localhost:11080/yadis");
-      
-      context.addServlet(servletHolder, "/*");
-      
-      context.addServlet(new ServletHolder( new TestYadisResourceServlet()), "/yadis");
-   }
-   
-   public void testYadisDiscovery() throws Exception
-   {
-      //String username = "http://jbosstest.myopenid.com";
-      String username = "http://localhost:11080"; 
-      
-      OpenIDRequest openIDRequest = new OpenIDRequest(username);
-      OpenIDManager idm = new OpenIDManager(openIDRequest);
-      
-      OpenIDProviderList providers = idm.discoverProviders(); 
-      assertNotNull("Providers list is not null", providers);
-      assertEquals("1 provider", 1, providers.size());
-   }
-   
-   /**
-    * Servlet that just outputs an Yadis resource
-    */
-   private class TestYadisResourceServlet extends HttpServlet
-   {
-      private static final long serialVersionUID = 1L;
-    
-      String yadis = "<xrds:XRDS "+
-                        " xmlns:xrds=\'xri://$xrds\' " +
-                        " xmlns:openid=\'http://openid.net/xmlns/1.0\'" +
-                        " xmlns=\'xri://$xrd*($v*2.0)\'>" +
-                        "<XRD>" +
-                        " <Service priority=\'0\'>" +
-                        " <Type>http://openid.net/signon/1.0</Type>" +
-                        " <URI>http://localhost/provider.jsp</URI>" +
-                        " </Service>"+
-                        "</XRD>" +
-                     "</xrds:XRDS>";
-      @Override
-      protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
-      {
-         resp.setContentType("application/xrds+xml");
-         resp.setStatus(HttpServletResponse.SC_OK);
-         resp.getWriter().print(yadis); 
-      } 
-   }
+public class YadisMetadataUnitTestCase extends EmbeddedWebServerBase {
+    protected void establishUserApps() {
+        Context context = new Context(server, "/", Context.SESSIONS);
+        ServletHolder servletHolder = new ServletHolder(new OpenIDYadisServlet());
+        servletHolder.setInitParameter("support_HTTP_HEAD", "true");
+        servletHolder.setInitParameter("yadisResourceURL", "http://localhost:11080/yadis");
+
+        context.addServlet(servletHolder, "/*");
+
+        context.addServlet(new ServletHolder(new TestYadisResourceServlet()), "/yadis");
+    }
+
+    public void testYadisDiscovery() throws Exception {
+        // String username = "http://jbosstest.myopenid.com";
+        String username = "http://localhost:11080";
+
+        OpenIDRequest openIDRequest = new OpenIDRequest(username);
+        OpenIDManager idm = new OpenIDManager(openIDRequest);
+
+        OpenIDProviderList providers = idm.discoverProviders();
+        assertNotNull("Providers list is not null", providers);
+        assertEquals("1 provider", 1, providers.size());
+    }
+
+    /**
+     * Servlet that just outputs an Yadis resource
+     */
+    private class TestYadisResourceServlet extends HttpServlet {
+        private static final long serialVersionUID = 1L;
+
+        String yadis = "<xrds:XRDS " + " xmlns:xrds=\'xri://$xrds\' " + " xmlns:openid=\'http://openid.net/xmlns/1.0\'"
+                + " xmlns=\'xri://$xrd*($v*2.0)\'>" + "<XRD>" + " <Service priority=\'0\'>"
+                + " <Type>http://openid.net/signon/1.0</Type>" + " <URI>http://localhost/provider.jsp</URI>" + " </Service>"
+                + "</XRD>" + "</xrds:XRDS>";
+
+        @Override
+        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
+            resp.setContentType("application/xrds+xml");
+            resp.setStatus(HttpServletResponse.SC_OK);
+            resp.getWriter().print(yadis);
+        }
+    }
 }
\ No newline at end of file

Modified: social/trunk/openid/src/test/java/org/picketlink/test/social/openid/workflow/OpenIDWorkflowTestConsumerServlet.java
===================================================================
--- social/trunk/openid/src/test/java/org/picketlink/test/social/openid/workflow/OpenIDWorkflowTestConsumerServlet.java	2012-03-19 20:36:39 UTC (rev 1527)
+++ social/trunk/openid/src/test/java/org/picketlink/test/social/openid/workflow/OpenIDWorkflowTestConsumerServlet.java	2012-03-19 20:39:31 UTC (rev 1528)
@@ -2,7 +2,7 @@
  * 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. 
+ * 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
@@ -31,48 +31,42 @@
 import org.picketlink.social.openid.api.OpenIDManager;
 import org.picketlink.social.openid.web.HTTPOpenIDContext;
 import org.picketlink.social.openid.web.HTTPProtocolAdaptor;
- 
 
 /**
  * Test Consumer Servlet
+ *
  * @author Anil.Saldhana at redhat.com
  * @since Jan 19, 2011
  */
-public class OpenIDWorkflowTestConsumerServlet extends HttpServlet
-{ 
-   private static final long serialVersionUID = 1L;
-   
-   private OpenIDManager manager = null;
-   
-   public OpenIDWorkflowTestConsumerServlet( OpenIDManager mgr )
-   {
-      this.manager = mgr;
-   }
+public class OpenIDWorkflowTestConsumerServlet extends HttpServlet {
+    private static final long serialVersionUID = 1L;
 
-   @SuppressWarnings("unchecked")
-   @Override
-   protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
-   { 
-      log( "Provider response:" + request.getQueryString() );
-      log( "UserID Chosen=" + request.getParameter( "openid.identity" )); 
-      
-      // extract the receiving URL from the HTTP request
-      StringBuffer receivingURL = request.getRequestURL();
-      String queryString = request.getQueryString();
-      if (queryString != null && queryString.length() > 0)
-          receivingURL.append("?").append(request.getQueryString());
+    private OpenIDManager manager = null;
 
-      HTTPProtocolAdaptor adapter = new HTTPProtocolAdaptor(new HTTPOpenIDContext( request,response, getServletContext() ));
-      try
-      { 
-         boolean auth = manager.verify(adapter, request.getParameterMap(), receivingURL.toString() );
-         if( !auth )
-            throw new ServletException( "OpenID information from provider not successfully verified" );
-      }
-      catch ( Exception e)
-      { 
-         e.printStackTrace();
-         throw new IOException();
-      } 
-   } 
+    public OpenIDWorkflowTestConsumerServlet(OpenIDManager mgr) {
+        this.manager = mgr;
+    }
+
+    @SuppressWarnings("unchecked")
+    @Override
+    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
+        log("Provider response:" + request.getQueryString());
+        log("UserID Chosen=" + request.getParameter("openid.identity"));
+
+        // extract the receiving URL from the HTTP request
+        StringBuffer receivingURL = request.getRequestURL();
+        String queryString = request.getQueryString();
+        if (queryString != null && queryString.length() > 0)
+            receivingURL.append("?").append(request.getQueryString());
+
+        HTTPProtocolAdaptor adapter = new HTTPProtocolAdaptor(new HTTPOpenIDContext(request, response, getServletContext()));
+        try {
+            boolean auth = manager.verify(adapter, request.getParameterMap(), receivingURL.toString());
+            if (!auth)
+                throw new ServletException("OpenID information from provider not successfully verified");
+        } catch (Exception e) {
+            e.printStackTrace();
+            throw new IOException();
+        }
+    }
 }
\ No newline at end of file

Modified: social/trunk/openid/src/test/java/org/picketlink/test/social/openid/workflow/OpenIDWorkflowUnitTestCase.java
===================================================================
--- social/trunk/openid/src/test/java/org/picketlink/test/social/openid/workflow/OpenIDWorkflowUnitTestCase.java	2012-03-19 20:36:39 UTC (rev 1527)
+++ social/trunk/openid/src/test/java/org/picketlink/test/social/openid/workflow/OpenIDWorkflowUnitTestCase.java	2012-03-19 20:39:31 UTC (rev 1528)
@@ -2,7 +2,7 @@
  * 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. 
+ * 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
@@ -27,7 +27,7 @@
 
 import org.mortbay.jetty.servlet.Context;
 import org.mortbay.jetty.servlet.ServletHolder;
-import org.mortbay.jetty.webapp.WebAppContext; 
+import org.mortbay.jetty.webapp.WebAppContext;
 import org.picketlink.social.openid.api.OpenIDManager;
 import org.picketlink.social.openid.api.OpenIDManager.OpenIDProviderInformation;
 import org.picketlink.social.openid.api.OpenIDManager.OpenIDProviderList;
@@ -36,55 +36,52 @@
 import org.picketlink.test.social.openid.EmbeddedWebServerBase;
 import org.picketlink.test.social.openid.InMemoryProtocolAdapter;
 
-
 /**
  * Test the workflow of an OpenID Consumer with a provider
+ *
  * @author Anil.Saldhana at redhat.com
  * @since Jan 18, 2011
  */
-public class OpenIDWorkflowUnitTestCase extends EmbeddedWebServerBase
-{ 
-   private String username = "http://localhost:11080";
-   private OpenIDRequest openIDRequest = new OpenIDRequest( username ); 
-   private OpenIDManager manager = new OpenIDManager( openIDRequest ); 
-   
-   @SuppressWarnings({"unchecked", "rawtypes"})
-   protected void establishUserApps()
-   {
-      ClassLoader tcl = Thread.currentThread().getContextClassLoader();
-      
-      final String WEBAPPDIR = "openid/webapp"; 
+public class OpenIDWorkflowUnitTestCase extends EmbeddedWebServerBase {
+    private String username = "http://localhost:11080";
+    private OpenIDRequest openIDRequest = new OpenIDRequest(username);
+    private OpenIDManager manager = new OpenIDManager(openIDRequest);
 
-      final String CONTEXTPATH = "/";
+    @SuppressWarnings({ "unchecked", "rawtypes" })
+    protected void establishUserApps() {
+        ClassLoader tcl = Thread.currentThread().getContextClassLoader();
 
-      // for localhost:port/admin/index.html and whatever else is in the webapp directory
-      final URL warUrl = tcl.getResource(WEBAPPDIR);
-      final String warUrlString = warUrl.toExternalForm();
-      
-      Context context = new WebAppContext( warUrlString, CONTEXTPATH );
-      server.setHandler( context );
-      
-      Map initParams = new HashMap();
-      initParams.put("configFile", "/test-sts.xml");
-      context.setInitParams(initParams);
-      
-      Thread.currentThread().setContextClassLoader(context.getClassLoader());
- 
-      context.addServlet(new ServletHolder(new OpenIDProviderServlet()), "/provider/");
-      
-      context.addServlet( new ServletHolder( new OpenIDWorkflowTestConsumerServlet( manager)), "/consumer" );
-      
-      context.addFilter(PrincipalInducingTestServletFilter.class, "/securepage.jsp",  1 );
-   }
+        final String WEBAPPDIR = "openid/webapp";
 
-   public void testOpenIDAuth() throws Exception
-   {   
-      InMemoryProtocolAdapter ad = new InMemoryProtocolAdapter(); 
-      OpenIDProviderList providers = manager.discoverProviders();
-      assertNotNull("List of providers is not null", providers);
+        final String CONTEXTPATH = "/";
 
-      OpenIDProviderInformation providerInfo = manager.associate( ad,providers );
-      boolean isValid = manager.authenticate( ad, providerInfo );
-      assertTrue( "Authentication is valid" , isValid );
-   } 
+        // for localhost:port/admin/index.html and whatever else is in the webapp directory
+        final URL warUrl = tcl.getResource(WEBAPPDIR);
+        final String warUrlString = warUrl.toExternalForm();
+
+        Context context = new WebAppContext(warUrlString, CONTEXTPATH);
+        server.setHandler(context);
+
+        Map initParams = new HashMap();
+        initParams.put("configFile", "/test-sts.xml");
+        context.setInitParams(initParams);
+
+        Thread.currentThread().setContextClassLoader(context.getClassLoader());
+
+        context.addServlet(new ServletHolder(new OpenIDProviderServlet()), "/provider/");
+
+        context.addServlet(new ServletHolder(new OpenIDWorkflowTestConsumerServlet(manager)), "/consumer");
+
+        context.addFilter(PrincipalInducingTestServletFilter.class, "/securepage.jsp", 1);
+    }
+
+    public void testOpenIDAuth() throws Exception {
+        InMemoryProtocolAdapter ad = new InMemoryProtocolAdapter();
+        OpenIDProviderList providers = manager.discoverProviders();
+        assertNotNull("List of providers is not null", providers);
+
+        OpenIDProviderInformation providerInfo = manager.associate(ad, providers);
+        boolean isValid = manager.authenticate(ad, providerInfo);
+        assertTrue("Authentication is valid", isValid);
+    }
 }
\ No newline at end of file

Modified: social/trunk/openid/src/test/java/org/picketlink/test/social/openid/workflow/PrincipalInducingTestServletFilter.java
===================================================================
--- social/trunk/openid/src/test/java/org/picketlink/test/social/openid/workflow/PrincipalInducingTestServletFilter.java	2012-03-19 20:36:39 UTC (rev 1527)
+++ social/trunk/openid/src/test/java/org/picketlink/test/social/openid/workflow/PrincipalInducingTestServletFilter.java	2012-03-19 20:39:31 UTC (rev 1528)
@@ -2,7 +2,7 @@
  * 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. 
+ * 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
@@ -35,32 +35,28 @@
 
 /**
  * A servlet filter for testing that adds a principal with name "anil"
+ *
  * @author Anil.Saldhana at redhat.com
  * @since Jan 19, 2011
  */
-public class PrincipalInducingTestServletFilter implements Filter
-{  
-   public void init(FilterConfig filterConfig) throws ServletException
-   { 
-   }
+public class PrincipalInducingTestServletFilter implements Filter {
+    public void init(FilterConfig filterConfig) throws ServletException {
+    }
 
-   public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
-         ServletException
-   { 
-      Request jettyRequest = (Request) request;
-      if( jettyRequest.getUserPrincipal() == null )
-      {
-         jettyRequest.setUserPrincipal( new Principal() {
+    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
+            ServletException {
+        Request jettyRequest = (Request) request;
+        if (jettyRequest.getUserPrincipal() == null) {
+            jettyRequest.setUserPrincipal(new Principal() {
 
-            public String getName()
-            { 
-               return "http://localhost:11080/";
-            }} );
-      }
-      chain.doFilter(request, response); 
-   }
+                public String getName() {
+                    return "http://localhost:11080/";
+                }
+            });
+        }
+        chain.doFilter(request, response);
+    }
 
-   public void destroy()
-   {
-   } 
+    public void destroy() {
+    }
 }
\ No newline at end of file

Modified: social/trunk/social/src/main/java/org/picketlink/social/auth/ExternalAuthLoginModule.java
===================================================================
--- social/trunk/social/src/main/java/org/picketlink/social/auth/ExternalAuthLoginModule.java	2012-03-19 20:36:39 UTC (rev 1527)
+++ social/trunk/social/src/main/java/org/picketlink/social/auth/ExternalAuthLoginModule.java	2012-03-19 20:39:31 UTC (rev 1528)
@@ -2,7 +2,7 @@
  * JBoss, Home of Professional Open Source.
  * Copyright 2011, 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. 
+ * 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
@@ -36,54 +36,46 @@
 
 /**
  * A {@link LoginModule} for JBoss environment to support external 3rd party authentication
+ *
  * @author Anil Saldhana
  * @since Sep 22, 2011
  */
-public class ExternalAuthLoginModule extends UsernamePasswordLoginModule
-{
-   @Override
-   protected Principal getIdentity()
-   {
-      Principal principal = null;
-      //Try facebook
-      principal = FacebookProcessor.cachedPrincipal.get();
-      if(principal == null )
-         principal =  OpenIDProcessor.cachedPrincipal.get();
-      return principal;
-   }
+public class ExternalAuthLoginModule extends UsernamePasswordLoginModule {
+    @Override
+    protected Principal getIdentity() {
+        Principal principal = null;
+        // Try facebook
+        principal = FacebookProcessor.cachedPrincipal.get();
+        if (principal == null)
+            principal = OpenIDProcessor.cachedPrincipal.get();
+        return principal;
+    }
 
-   @Override
-   protected String getUsersPassword() throws LoginException
-   {
-      return OpenIDProcessor.EMPTY_PASSWORD;
-   }
+    @Override
+    protected String getUsersPassword() throws LoginException {
+        return OpenIDProcessor.EMPTY_PASSWORD;
+    }
 
-   @Override
-   protected Group[] getRoleSets() throws LoginException
-   {   
-      Group group = new SimpleGroup("Roles"); 
+    @Override
+    protected Group[] getRoleSets() throws LoginException {
+        Group group = new SimpleGroup("Roles");
 
-      List<String> roles = OpenIDProcessor.cachedRoles.get();
+        List<String> roles = OpenIDProcessor.cachedRoles.get();
 
-      if(roles != null)
-      {
-         for(String role: roles)
-         {
-            group.addMember(new SimplePrincipal(role));
-         }
-      }
-      roles = FacebookProcessor.cachedRoles.get();
-      if(roles != null)
-      {
-         for(String role: roles)
-         {
-            Principal rolePrincipal = new SimplePrincipal(role);
-            if(group.isMember(rolePrincipal) == false)
-            {
-               group.addMember(rolePrincipal); 
+        if (roles != null) {
+            for (String role : roles) {
+                group.addMember(new SimplePrincipal(role));
             }
-         }
-      }
-      return new Group[] {group};
-   }
+        }
+        roles = FacebookProcessor.cachedRoles.get();
+        if (roles != null) {
+            for (String role : roles) {
+                Principal rolePrincipal = new SimplePrincipal(role);
+                if (group.isMember(rolePrincipal) == false) {
+                    group.addMember(rolePrincipal);
+                }
+            }
+        }
+        return new Group[] { group };
+    }
 }
\ No newline at end of file

Modified: social/trunk/social/src/main/java/org/picketlink/social/auth/ExternalAuthenticator.java
===================================================================
--- social/trunk/social/src/main/java/org/picketlink/social/auth/ExternalAuthenticator.java	2012-03-19 20:36:39 UTC (rev 1527)
+++ social/trunk/social/src/main/java/org/picketlink/social/auth/ExternalAuthenticator.java	2012-03-19 20:39:31 UTC (rev 1528)
@@ -2,7 +2,7 @@
  * JBoss, Home of Professional Open Source.
  * Copyright 2011, 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. 
+ * 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
@@ -44,343 +44,302 @@
 import org.picketlink.social.openid.auth.OpenIDProcessor;
 
 /**
- * Authenticator that performs authentication with
- * external providers such as facebook, google, yahoo etc.
+ * Authenticator that performs authentication with external providers such as facebook, google, yahoo etc.
+ *
  * @author Anil Saldhana
  * @since Sep 22, 2011
  */
-public class ExternalAuthenticator extends FormAuthenticator
-{
-   protected static Logger log = Logger.getLogger(OpenIDConsumerAuthenticator.class);
-   protected boolean trace = log.isTraceEnabled();
-   
-   private enum AUTH_PROVIDERS
-   {
-      FACEBOOK, OPENID;
-   }
-   
-   public static final String AUTH_TYPE = "authType";
- 
-   protected FacebookProcessor facebookProcessor;
-   protected OpenIDProcessor openidProcessor;
-   
-   protected String returnURL;
-   protected String clientID;
-   protected String clientSecret;
-   protected String facebookScope = "email";
+public class ExternalAuthenticator extends FormAuthenticator {
+    protected static Logger log = Logger.getLogger(OpenIDConsumerAuthenticator.class);
+    protected boolean trace = log.isTraceEnabled();
 
-   private String requiredAttributes = "name,email,ax_firstName,ax_lastName,ax_fullName,ax_email";
+    private enum AUTH_PROVIDERS {
+        FACEBOOK, OPENID;
+    }
 
-   private String optionalAttributes = null;
-   
-   //Whether the authenticator has to to save and restore request
-   protected boolean saveRestoreRequest = true;
-   
-   private enum STATES { AUTH, AUTHZ, FINISH}; 
-   
-   //Incompatibilities in register() method across JBossWeb versions
-   private Method theSuperRegisterMethod = null;
+    public static final String AUTH_TYPE = "authType";
 
-   /**
-    * A comma separated string that represents the roles the web app
-    * needs to pass authorization
-    * @param roleStr
-    */
-   public void setRoleString(String roleStr)
-   {
-      if(roleStr == null)
-         throw new RuntimeException("Role String is null in configuration");
-      StringTokenizer st = new StringTokenizer(StringUtil.getSystemPropertyAsString(roleStr), ",");
-      while(st.hasMoreElements())
-      {
-         roles.add(st.nextToken());
-      }
-   }
-   
-   public void setSaveRestoreRequest(boolean saveRestoreRequest)
-   {
-      this.saveRestoreRequest = saveRestoreRequest;
-   }
-   
-   protected List<String> roles = new ArrayList<String>();
-   
-   /**
-    * Set the url where the 3rd party authentication service will redirect after authentication
-    * @param returnURL
-    */
-   public void setReturnURL(String returnURL)
-   {
-      this.returnURL = StringUtil.getSystemPropertyAsString(returnURL);
-   }
-   
-   /**
-    * Set the client id for facebook
-    * @param clientID
-    */
-   public void setClientID(String clientID)
-   {
-      this.clientID = StringUtil.getSystemPropertyAsString(clientID);
-   }
-   
-   /**
-    * Set the client secret for facebook
-    * @param clientSecret
-    */
-   public void setClientSecret(String clientSecret)
-   {
-      this.clientSecret = StringUtil.getSystemPropertyAsString(clientSecret);
-   }
-   
-   /**
-    * Set the scope for facebook (Default: email)
-    * @param facebookScope
-    */
-   public void setFacebookScope(String facebookScope)
-   {
-      this.facebookScope = StringUtil.getSystemPropertyAsString(facebookScope);
-   }
-   
-   public boolean authenticate(HttpServletRequest request, HttpServletResponse response, LoginConfig loginConfig) throws IOException
-   {
-      if(request instanceof Request == false)
-         throw new IOException("Not of type Catalina request");
-      if(response instanceof Response == false)
-         throw new IOException("Not of type Catalina response");
-      return authenticate((Request)request, (Response)response, loginConfig);
-   }
-   
-   /**
-    * Authenticate the request
-    * @param request
-    * @param response
-    * @param config
-    * @return
-    * @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
-   {
-      if (response instanceof Response)
-      {
-         Response catalinaResponse = (Response) response;
-         return authenticate(request, catalinaResponse, config);
-      }
-      throw new RuntimeException("Wrong type of response:"+response);
-   }
-    
-   public boolean authenticate(Request request, Response response, LoginConfig loginConfig) throws IOException
-   {  
-      if(trace) log.trace("authenticate");
+    protected FacebookProcessor facebookProcessor;
+    protected OpenIDProcessor openidProcessor;
 
-      if(facebookProcessor == null)
-         facebookProcessor = new FacebookProcessor(clientID, clientSecret, facebookScope, returnURL, roles);
+    protected String returnURL;
+    protected String clientID;
+    protected String clientSecret;
+    protected String facebookScope = "email";
 
-      if(openidProcessor == null)
-         openidProcessor = new OpenIDProcessor(returnURL, requiredAttributes, optionalAttributes);
-    
-      HttpSession session = request.getSession();
-      //Determine the type of service based on request param
-      String authType = request.getParameter(AUTH_TYPE);
-      if(authType != null && authType.length() > 0)
-      {
-         //Place it on the session
-         session.setAttribute(AUTH_TYPE, authType);
-      }
-      if(authType == null || authType.length() == 0)
-      {
-         authType = (String) session.getAttribute(AUTH_TYPE);
-      }
-      if(authType == null)
-      {
-         authType = AUTH_PROVIDERS.FACEBOOK.name();
-      }
-      if(authType != null && authType.equals(AUTH_PROVIDERS.FACEBOOK.name()))
-      {
-         return processFacebook(request, response);  
-      }
-      else
-      {
-         return processOpenID(request, response);
-      }
-   }
-   
-   protected boolean processFacebook(Request request, Response response) throws IOException
-   {
-      HttpSession session = request.getSession();
-      String state = (String) session.getAttribute("STATE");
-      
-      if(trace) log.trace("state="+ state);
-      
-      if( STATES.FINISH.name().equals(state))
-      {
-    	  Principal principal = request.getPrincipal();
-    	  if(principal == null)
-    	  {
-    		  principal = facebookProcessor.getPrincipal(request, response, context.getRealm());
-    	  }
-    	  if(principal == null)
-    	  {
-    		  response.sendError(HttpServletResponse.SC_FORBIDDEN);
-    		  return false;
-    	  }
-          return dealWithFacebookPrincipal(request, response, principal);
-      }
-      
-      if( state == null || state.isEmpty())
-      { 
-         if (saveRestoreRequest)
-         {
-            this.saveRequest(request, request.getSessionInternal());
-         }
-         return facebookProcessor.initialInteraction(request, response);
-      }
-      //We have sent an auth request
-      if( state.equals(STATES.AUTH.name()))
-      {
-         return facebookProcessor.handleAuthStage(request, response);
-      }
-      
-      //Principal facebookPrincipal = null;
-      if( state.equals(STATES.AUTHZ.name()))
-      {  
-         Principal principal = facebookProcessor.getPrincipal(request, response, context.getRealm());
-         
-         if(principal == null)
-         {
-             log.error("Principal was null. Maybe login modules need to be configured properly. Or user chose no data");
-   		     response.sendError(HttpServletResponse.SC_FORBIDDEN);
-             return false;
-         }
-         
-         return dealWithFacebookPrincipal(request, response, principal);
-      }
-      return false;
-   }
-   
-   protected boolean processOpenID(Request request, Response response) throws IOException
-   {
-      Principal userPrincipal = request.getUserPrincipal();
-      if(userPrincipal != null)
-      {
-         if(trace)
-            log.trace("Logged in as:"+userPrincipal);
-         return true;
-      }
+    private String requiredAttributes = "name,email,ax_firstName,ax_lastName,ax_fullName,ax_email";
 
-      if(!openidProcessor.isInitialized())
-      {
-         try
-         {
-            openidProcessor.initialize(roles);
-         }
-         catch (Exception e)
-         { 
-            throw new RuntimeException(e);
-         }
-      }
+    private String optionalAttributes = null;
 
-      HttpSession httpSession = request.getSession();
-      String state = (String) httpSession.getAttribute("STATE");
-      if(trace) log.trace("state="+ state);
- 
-      if( STATES.FINISH.name().equals(state))
-      {
-    	  //This is a replay. We need to resend a request back to the OpenID provider
-    	  httpSession.setAttribute("STATE", STATES.AUTH.name());
-    	  
-    	  return openidProcessor.prepareAndSendAuthRequest(request, response);
-      }
+    // Whether the authenticator has to to save and restore request
+    protected boolean saveRestoreRequest = true;
 
-      if( state == null || state.isEmpty())
-      { 
-         return openidProcessor.prepareAndSendAuthRequest(request, response);
-      } 
-      //We have sent an auth request
-      if( state.equals(STATES.AUTH.name()))
-      { 
-         Principal principal = openidProcessor.processIncomingAuthResult(request, response, context.getRealm());
+    private enum STATES {
+        AUTH, AUTHZ, FINISH
+    };
 
-         if(principal == null)
-         {
-             log.error("Principal was null. Maybe login modules need to be configured properly. Or user chose no data");
-        	 return false;
-         }
-         
-         return dealWithOpenIDPrincipal(request, response, principal);
-      }
-      return false;
-   }
-   
-   protected void registerWithAuthenticatorBase(Request request, Response response, Principal principal, String userName)
-   {
-      try
-      {
-         register(request, response, principal, Constants.FORM_METHOD, userName, "");
-      }
-      catch(NoSuchMethodError nse)
-      { 
-         if(theSuperRegisterMethod == null)
-         {
-            Class<?>[] args = new Class[]
-            {Request.class, HttpServletResponse.class, Principal.class, String.class, String.class, String.class};
-            Class<?> superClass = getClass().getSuperclass();
-            theSuperRegisterMethod = SecurityActions.getMethod(superClass, "register", args);
-            
-         }
-         if(theSuperRegisterMethod != null)
-         {
-            Object[] objectArgs = new Object[] {request, response.getResponse(),
-                  principal, Constants.FORM_METHOD,
-                  userName, FacebookProcessor.EMPTY_PASSWORD };
-            try
-            {
-               theSuperRegisterMethod.invoke(this, objectArgs);
+    // Incompatibilities in register() method across JBossWeb versions
+    private Method theSuperRegisterMethod = null;
+
+    /**
+     * A comma separated string that represents the roles the web app needs to pass authorization
+     *
+     * @param roleStr
+     */
+    public void setRoleString(String roleStr) {
+        if (roleStr == null)
+            throw new RuntimeException("Role String is null in configuration");
+        StringTokenizer st = new StringTokenizer(StringUtil.getSystemPropertyAsString(roleStr), ",");
+        while (st.hasMoreElements()) {
+            roles.add(st.nextToken());
+        }
+    }
+
+    public void setSaveRestoreRequest(boolean saveRestoreRequest) {
+        this.saveRestoreRequest = saveRestoreRequest;
+    }
+
+    protected List<String> roles = new ArrayList<String>();
+
+    /**
+     * Set the url where the 3rd party authentication service will redirect after authentication
+     *
+     * @param returnURL
+     */
+    public void setReturnURL(String returnURL) {
+        this.returnURL = StringUtil.getSystemPropertyAsString(returnURL);
+    }
+
+    /**
+     * Set the client id for facebook
+     *
+     * @param clientID
+     */
+    public void setClientID(String clientID) {
+        this.clientID = StringUtil.getSystemPropertyAsString(clientID);
+    }
+
+    /**
+     * Set the client secret for facebook
+     *
+     * @param clientSecret
+     */
+    public void setClientSecret(String clientSecret) {
+        this.clientSecret = StringUtil.getSystemPropertyAsString(clientSecret);
+    }
+
+    /**
+     * Set the scope for facebook (Default: email)
+     *
+     * @param facebookScope
+     */
+    public void setFacebookScope(String facebookScope) {
+        this.facebookScope = StringUtil.getSystemPropertyAsString(facebookScope);
+    }
+
+    public boolean authenticate(HttpServletRequest request, HttpServletResponse response, LoginConfig loginConfig)
+            throws IOException {
+        if (request instanceof Request == false)
+            throw new IOException("Not of type Catalina request");
+        if (response instanceof Response == false)
+            throw new IOException("Not of type Catalina response");
+        return authenticate((Request) request, (Response) response, loginConfig);
+    }
+
+    /**
+     * Authenticate the request
+     *
+     * @param request
+     * @param response
+     * @param config
+     * @return
+     * @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 {
+        if (response instanceof Response) {
+            Response catalinaResponse = (Response) response;
+            return authenticate(request, catalinaResponse, config);
+        }
+        throw new RuntimeException("Wrong type of response:" + response);
+    }
+
+    public boolean authenticate(Request request, Response response, LoginConfig loginConfig) throws IOException {
+        if (trace)
+            log.trace("authenticate");
+
+        if (facebookProcessor == null)
+            facebookProcessor = new FacebookProcessor(clientID, clientSecret, facebookScope, returnURL, roles);
+
+        if (openidProcessor == null)
+            openidProcessor = new OpenIDProcessor(returnURL, requiredAttributes, optionalAttributes);
+
+        HttpSession session = request.getSession();
+        // Determine the type of service based on request param
+        String authType = request.getParameter(AUTH_TYPE);
+        if (authType != null && authType.length() > 0) {
+            // Place it on the session
+            session.setAttribute(AUTH_TYPE, authType);
+        }
+        if (authType == null || authType.length() == 0) {
+            authType = (String) session.getAttribute(AUTH_TYPE);
+        }
+        if (authType == null) {
+            authType = AUTH_PROVIDERS.FACEBOOK.name();
+        }
+        if (authType != null && authType.equals(AUTH_PROVIDERS.FACEBOOK.name())) {
+            return processFacebook(request, response);
+        } else {
+            return processOpenID(request, response);
+        }
+    }
+
+    protected boolean processFacebook(Request request, Response response) throws IOException {
+        HttpSession session = request.getSession();
+        String state = (String) session.getAttribute("STATE");
+
+        if (trace)
+            log.trace("state=" + state);
+
+        if (STATES.FINISH.name().equals(state)) {
+            Principal principal = request.getPrincipal();
+            if (principal == null) {
+                principal = facebookProcessor.getPrincipal(request, response, context.getRealm());
             }
-            catch (Exception e)
-            {
-               log.error("Unable to register:", e);
+            if (principal == null) {
+                response.sendError(HttpServletResponse.SC_FORBIDDEN);
+                return false;
             }
-         }
-      }
-   }
-   
-   private boolean dealWithFacebookPrincipal(Request request, Response response, Principal principal) throws IOException
-   {
-	   String userName = principal.getName();
-       
-       request.getSessionInternal().setNote(Constants.SESS_USERNAME_NOTE, userName);
-       request.getSessionInternal().setNote(Constants.SESS_PASSWORD_NOTE, "");
-       request.setUserPrincipal(principal);
+            return dealWithFacebookPrincipal(request, response, principal);
+        }
 
-       if (saveRestoreRequest)
-       {
-          this.restoreRequest(request, request.getSessionInternal());
-       }
-       registerWithAuthenticatorBase(request,response,principal,userName);
-       
-       request.getSession().setAttribute("STATE", STATES.FINISH.name());
+        if (state == null || state.isEmpty()) {
+            if (saveRestoreRequest) {
+                this.saveRequest(request, request.getSessionInternal());
+            }
+            return facebookProcessor.initialInteraction(request, response);
+        }
+        // We have sent an auth request
+        if (state.equals(STATES.AUTH.name())) {
+            return facebookProcessor.handleAuthStage(request, response);
+        }
 
-       return true;
-   }
-   
-   private boolean dealWithOpenIDPrincipal(Request request, Response response, Principal principal) throws IOException
-   {
-	   HttpSession httpSession = request.getSession();
-	      
-	   String principalName = principal.getName();
-       request.getSessionInternal().setNote(Constants.SESS_USERNAME_NOTE, principalName);
-       request.getSessionInternal().setNote(Constants.SESS_PASSWORD_NOTE, "");
-       request.setUserPrincipal(principal);
+        // Principal facebookPrincipal = null;
+        if (state.equals(STATES.AUTHZ.name())) {
+            Principal principal = facebookProcessor.getPrincipal(request, response, context.getRealm());
 
-       if (saveRestoreRequest)
-       {
-          this.restoreRequest(request, request.getSessionInternal());
-       }
+            if (principal == null) {
+                log.error("Principal was null. Maybe login modules need to be configured properly. Or user chose no data");
+                response.sendError(HttpServletResponse.SC_FORBIDDEN);
+                return false;
+            }
 
-       if(trace)
-          log.trace("Logged in as:" + principal);
-       registerWithAuthenticatorBase(request,response,principal,principalName);
-       httpSession.setAttribute("STATE", STATES.FINISH.name());
-       return true;  
-   }
+            return dealWithFacebookPrincipal(request, response, principal);
+        }
+        return false;
+    }
+
+    protected boolean processOpenID(Request request, Response response) throws IOException {
+        Principal userPrincipal = request.getUserPrincipal();
+        if (userPrincipal != null) {
+            if (trace)
+                log.trace("Logged in as:" + userPrincipal);
+            return true;
+        }
+
+        if (!openidProcessor.isInitialized()) {
+            try {
+                openidProcessor.initialize(roles);
+            } catch (Exception e) {
+                throw new RuntimeException(e);
+            }
+        }
+
+        HttpSession httpSession = request.getSession();
+        String state = (String) httpSession.getAttribute("STATE");
+        if (trace)
+            log.trace("state=" + state);
+
+        if (STATES.FINISH.name().equals(state)) {
+            // This is a replay. We need to resend a request back to the OpenID provider
+            httpSession.setAttribute("STATE", STATES.AUTH.name());
+
+            return openidProcessor.prepareAndSendAuthRequest(request, response);
+        }
+
+        if (state == null || state.isEmpty()) {
+            return openidProcessor.prepareAndSendAuthRequest(request, response);
+        }
+        // We have sent an auth request
+        if (state.equals(STATES.AUTH.name())) {
+            Principal principal = openidProcessor.processIncomingAuthResult(request, response, context.getRealm());
+
+            if (principal == null) {
+                log.error("Principal was null. Maybe login modules need to be configured properly. Or user chose no data");
+                return false;
+            }
+
+            return dealWithOpenIDPrincipal(request, response, principal);
+        }
+        return false;
+    }
+
+    protected void registerWithAuthenticatorBase(Request request, Response response, Principal principal, String userName) {
+        try {
+            register(request, response, principal, Constants.FORM_METHOD, userName, "");
+        } catch (NoSuchMethodError nse) {
+            if (theSuperRegisterMethod == null) {
+                Class<?>[] args = new Class[] { Request.class, HttpServletResponse.class, Principal.class, String.class,
+                        String.class, String.class };
+                Class<?> superClass = getClass().getSuperclass();
+                theSuperRegisterMethod = SecurityActions.getMethod(superClass, "register", args);
+
+            }
+            if (theSuperRegisterMethod != null) {
+                Object[] objectArgs = new Object[] { request, response.getResponse(), principal, Constants.FORM_METHOD,
+                        userName, FacebookProcessor.EMPTY_PASSWORD };
+                try {
+                    theSuperRegisterMethod.invoke(this, objectArgs);
+                } catch (Exception e) {
+                    log.error("Unable to register:", e);
+                }
+            }
+        }
+    }
+
+    private boolean dealWithFacebookPrincipal(Request request, Response response, Principal principal) throws IOException {
+        String userName = principal.getName();
+
+        request.getSessionInternal().setNote(Constants.SESS_USERNAME_NOTE, userName);
+        request.getSessionInternal().setNote(Constants.SESS_PASSWORD_NOTE, "");
+        request.setUserPrincipal(principal);
+
+        if (saveRestoreRequest) {
+            this.restoreRequest(request, request.getSessionInternal());
+        }
+        registerWithAuthenticatorBase(request, response, principal, userName);
+
+        request.getSession().setAttribute("STATE", STATES.FINISH.name());
+
+        return true;
+    }
+
+    private boolean dealWithOpenIDPrincipal(Request request, Response response, Principal principal) throws IOException {
+        HttpSession httpSession = request.getSession();
+
+        String principalName = principal.getName();
+        request.getSessionInternal().setNote(Constants.SESS_USERNAME_NOTE, principalName);
+        request.getSessionInternal().setNote(Constants.SESS_PASSWORD_NOTE, "");
+        request.setUserPrincipal(principal);
+
+        if (saveRestoreRequest) {
+            this.restoreRequest(request, request.getSessionInternal());
+        }
+
+        if (trace)
+            log.trace("Logged in as:" + principal);
+        registerWithAuthenticatorBase(request, response, principal, principalName);
+        httpSession.setAttribute("STATE", STATES.FINISH.name());
+        return true;
+    }
 }
\ No newline at end of file

Modified: social/trunk/social/src/main/java/org/picketlink/social/auth/SecurityActions.java
===================================================================
--- social/trunk/social/src/main/java/org/picketlink/social/auth/SecurityActions.java	2012-03-19 20:36:39 UTC (rev 1527)
+++ social/trunk/social/src/main/java/org/picketlink/social/auth/SecurityActions.java	2012-03-19 20:39:31 UTC (rev 1528)
@@ -2,7 +2,7 @@
  * JBoss, Home of Professional Open Source.
  * Copyright 2011, 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. 
+ * 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
@@ -27,34 +27,28 @@
 
 /**
  * Privileged Blocks
+ *
  * @author Anil Saldhana
  * @since Sep 26, 2011
  */
-class SecurityActions
-{
-   /**
-    * Use reflection to get the {@link Method} on a {@link Class} with the
-    * given parameter types
-    * @param clazz
-    * @param methodName
-    * @param parameterTypes
-    * @return
-    */
-   static Method getMethod(final Class<?> clazz, final String methodName, final Class<?>[] parameterTypes)
-   {
-      return AccessController.doPrivileged(new PrivilegedAction<Method>()
-      {
-         public Method run()
-         {
-            try
-            {
-               return clazz.getDeclaredMethod(methodName, parameterTypes);
+class SecurityActions {
+    /**
+     * Use reflection to get the {@link Method} on a {@link Class} with the given parameter types
+     *
+     * @param clazz
+     * @param methodName
+     * @param parameterTypes
+     * @return
+     */
+    static Method getMethod(final Class<?> clazz, final String methodName, final Class<?>[] parameterTypes) {
+        return AccessController.doPrivileged(new PrivilegedAction<Method>() {
+            public Method run() {
+                try {
+                    return clazz.getDeclaredMethod(methodName, parameterTypes);
+                } catch (Exception e) {
+                    return null;
+                }
             }
-            catch (Exception e)
-            {
-               return null;
-            }
-         }
-      });
-   }
+        });
+    }
 }
\ No newline at end of file

Modified: social/trunk/social/src/main/java/org/picketlink/social/reg/RegistrationValve.java
===================================================================
--- social/trunk/social/src/main/java/org/picketlink/social/reg/RegistrationValve.java	2012-03-19 20:36:39 UTC (rev 1527)
+++ social/trunk/social/src/main/java/org/picketlink/social/reg/RegistrationValve.java	2012-03-19 20:39:31 UTC (rev 1528)
@@ -2,7 +2,7 @@
  * JBoss, Home of Professional Open Source.
  * Copyright 2011, 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. 
+ * 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
@@ -38,90 +38,77 @@
 import org.picketlink.social.openid.OpenIdPrincipal;
 
 /**
- * A Valve that can be added after the authenticator to look
- * into the authenticated principal and derive useful information
- * to register the user
- * 
+ * A Valve that can be added after the authenticator to look into the authenticated principal and derive useful information to
+ * register the user
+ *
  * @author Anil Saldhana
  * @since Sep 22, 2011
  */
-public class RegistrationValve extends ValveBase
-{
-   public void invoke(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
-   {
-      if(request instanceof Request == false)
-         throw new IOException("Not of type Catalina request");
-      if(response instanceof Response == false)
-         throw new IOException("Not of type Catalina response");
-      invoke((Request)request, (Response)response);
-   }
+public class RegistrationValve extends ValveBase {
+    public void invoke(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
+        if (request instanceof Request == false)
+            throw new IOException("Not of type Catalina request");
+        if (response instanceof Response == false)
+            throw new IOException("Not of type Catalina response");
+        invoke((Request) request, (Response) response);
+    }
 
-   public void invoke(Request request, Response response) throws IOException, ServletException
-   {
-      HttpSession session = request.getSession();
-      Principal principal = (Principal) session.getAttribute("PRINCIPAL");
-      if(principal != null)
-      {
-         UserRegistration user = null;
-         if(principal instanceof OpenIdPrincipal)
-         {
-            user = processOpenIDPrincipal((OpenIdPrincipal) principal);
-         }
-         else if(principal instanceof FacebookPrincipal)
-         { 
-            user = processFacebookPrincipal((FacebookPrincipal) principal);
-         }
-         else
-            throw new ServletException("Unknown principal type:" + principal);
-         if(user != null)
-         {
-            session.setAttribute("user", user);
-         }
-      }
-      getNext().invoke(request, response);
-   }
+    public void invoke(Request request, Response response) throws IOException, ServletException {
+        HttpSession session = request.getSession();
+        Principal principal = (Principal) session.getAttribute("PRINCIPAL");
+        if (principal != null) {
+            UserRegistration user = null;
+            if (principal instanceof OpenIdPrincipal) {
+                user = processOpenIDPrincipal((OpenIdPrincipal) principal);
+            } else if (principal instanceof FacebookPrincipal) {
+                user = processFacebookPrincipal((FacebookPrincipal) principal);
+            } else
+                throw new ServletException("Unknown principal type:" + principal);
+            if (user != null) {
+                session.setAttribute("user", user);
+            }
+        }
+        getNext().invoke(request, response);
+    }
 
-   private UserRegistration processOpenIDPrincipal(OpenIdPrincipal openIDPrincipal)
-   {
-      UserRegistration user = new UserRegistration();
-      Map<String,List<String>> attributes = openIDPrincipal.getAttributes();
-      user.setIdentifier(openIDPrincipal.getIdentifier());
+    private UserRegistration processOpenIDPrincipal(OpenIdPrincipal openIDPrincipal) {
+        UserRegistration user = new UserRegistration();
+        Map<String, List<String>> attributes = openIDPrincipal.getAttributes();
+        user.setIdentifier(openIDPrincipal.getIdentifier());
 
-      if(attributes != null)
-      {
-         List<String> values = attributes.get("ax_firstName");
-         if(values != null && values.size() > 0)
-            user.setFirstName(values.get(0));
+        if (attributes != null) {
+            List<String> values = attributes.get("ax_firstName");
+            if (values != null && values.size() > 0)
+                user.setFirstName(values.get(0));
 
-         //Try the last name
-         values = attributes.get("ax_lastName");
-         if(values != null && values.size() > 0)
-            user.setLastName(values.get(0));  
+            // Try the last name
+            values = attributes.get("ax_lastName");
+            if (values != null && values.size() > 0)
+                user.setLastName(values.get(0));
 
-         //Try the full name
-         values = attributes.get("ax_fullName");
-         if(values != null && values.size() > 0)
-            user.setFullName(values.get(0));  
+            // Try the full name
+            values = attributes.get("ax_fullName");
+            if (values != null && values.size() > 0)
+                user.setFullName(values.get(0));
 
-         values = attributes.get("fullname"); //Yahoo
-         if(values != null && values.size() > 0)
-            user.setFullName(values.get(0));
+            values = attributes.get("fullname"); // Yahoo
+            if (values != null && values.size() > 0)
+                user.setFullName(values.get(0));
 
-         //Email
-         values = attributes.get("ax_email");
-         if(values != null && values.size() > 0)
-            user.setEmail(values.get(0));
-      }
-      return user;
-   }
+            // Email
+            values = attributes.get("ax_email");
+            if (values != null && values.size() > 0)
+                user.setEmail(values.get(0));
+        }
+        return user;
+    }
 
-   private UserRegistration processFacebookPrincipal(FacebookPrincipal facebookPrincipal)
-   {
-      UserRegistration user = new UserRegistration();
-      user.setEmail(facebookPrincipal.getEmail());
-      user.setFirstName(facebookPrincipal.getFirstName());
-      user.setLastName(facebookPrincipal.getLastName());
-      user.setIdentifier(facebookPrincipal.getId());
-      return user;
-   }
+    private UserRegistration processFacebookPrincipal(FacebookPrincipal facebookPrincipal) {
+        UserRegistration user = new UserRegistration();
+        user.setEmail(facebookPrincipal.getEmail());
+        user.setFirstName(facebookPrincipal.getFirstName());
+        user.setLastName(facebookPrincipal.getLastName());
+        user.setIdentifier(facebookPrincipal.getId());
+        return user;
+    }
 }
\ No newline at end of file

Modified: social/trunk/social/src/main/java/org/picketlink/social/reg/UserRegistration.java
===================================================================
--- social/trunk/social/src/main/java/org/picketlink/social/reg/UserRegistration.java	2012-03-19 20:36:39 UTC (rev 1527)
+++ social/trunk/social/src/main/java/org/picketlink/social/reg/UserRegistration.java	2012-03-19 20:39:31 UTC (rev 1528)
@@ -2,7 +2,7 @@
  * JBoss, Home of Professional Open Source.
  * Copyright 2011, 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. 
+ * 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
@@ -23,68 +23,58 @@
 
 /**
  * Represents a user with details from 3rd party provider
+ *
  * @author Anil Saldhana
  * @since Sep 22, 2011
  */
-public class UserRegistration
-{
-   private String identifier;
-   
-   private String firstName;
-   
-   private String lastName;
-   
-   private String fullName;
-   
-   private String email;
+public class UserRegistration {
+    private String identifier;
 
-   public String getIdentifier()
-   {
-      return identifier;
-   }
+    private String firstName;
 
-   public void setIdentifier(String identifier)
-   {
-      this.identifier = identifier;
-   }
+    private String lastName;
 
-   public String getFirstName()
-   {
-      return firstName;
-   }
+    private String fullName;
 
-   public void setFirstName(String firstName)
-   {
-      this.firstName = firstName;
-   }
+    private String email;
 
-   public String getLastName()
-   {
-      return lastName;
-   }
+    public String getIdentifier() {
+        return identifier;
+    }
 
-   public void setLastName(String lastName)
-   {
-      this.lastName = lastName;
-   }
+    public void setIdentifier(String identifier) {
+        this.identifier = identifier;
+    }
 
-   public String getFullName()
-   {
-      return fullName;
-   }
+    public String getFirstName() {
+        return firstName;
+    }
 
-   public void setFullName(String fullName)
-   {
-      this.fullName = fullName;
-   }
+    public void setFirstName(String firstName) {
+        this.firstName = firstName;
+    }
 
-   public String getEmail()
-   {
-      return email;
-   }
+    public String getLastName() {
+        return lastName;
+    }
 
-   public void setEmail(String email)
-   {
-      this.email = email;
-   }
+    public void setLastName(String lastName) {
+        this.lastName = lastName;
+    }
+
+    public String getFullName() {
+        return fullName;
+    }
+
+    public void setFullName(String fullName) {
+        this.fullName = fullName;
+    }
+
+    public String getEmail() {
+        return email;
+    }
+
+    public void setEmail(String email) {
+        this.email = email;
+    }
 }
\ No newline at end of file



More information about the jboss-cvs-commits mailing list