001/**
002 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
003 *
004 * Copyright (c) 2006 Sun Microsystems Inc. All Rights Reserved
005 *
006 * The contents of this file are subject to the terms
007 * of the Common Development and Distribution License
008 * (the License). You may not use this file except in
009 * compliance with the License.
010 *
011 * You can obtain a copy of the License at
012 * https://opensso.dev.java.net/public/CDDLv1.0.html or
013 * opensso/legal/CDDLv1.0.txt
014 * See the License for the specific language governing
015 * permission and limitations under the License.
016 *
017 * When distributing Covered Code, include this CDDL
018 * Header Notice in each file and include the License file
019 * at opensso/legal/CDDLv1.0.txt.
020 * If applicable, add the following below the CDDL Header,
021 * with the fields enclosed by brackets [] replaced by
022 * your own identifying information:
023 * "Portions Copyrighted [year] [name of copyright owner]"
024 *
025 * $Id: LibertyManager.java,v 1.7 2008/06/25 05:48:17 qcheng Exp $
026 *
027 */
028
029
030package com.sun.liberty;
031
032import java.security.cert.X509Certificate;
033import java.util.Iterator;
034import java.util.Set;
035import java.util.Map;
036import java.util.ArrayList;
037import java.util.List;
038import java.util.HashMap;
039import java.util.HashSet;
040import java.util.Random;
041import java.util.Enumeration;
042import javax.servlet.http.HttpServletRequest;
043import javax.servlet.http.HttpSession;
044
045import javax.xml.soap.SOAPMessage;
046
047import com.sun.identity.shared.debug.Debug;
048import com.sun.identity.shared.encode.URLEncDec;
049
050import com.sun.identity.cot.CircleOfTrustManager;
051import com.sun.identity.cot.CircleOfTrustDescriptor;
052import com.sun.identity.cot.COTException;
053import com.sun.identity.cot.COTConstants;
054
055import com.sun.identity.federation.accountmgmt.FSAccountFedInfo;
056import com.sun.identity.federation.accountmgmt.FSAccountManager;
057import com.sun.identity.federation.accountmgmt.FSAccountMgmtException;
058import com.sun.identity.federation.common.IFSConstants;
059import com.sun.identity.federation.common.FSUtils;
060import com.sun.identity.federation.jaxb.entityconfig.BaseConfigType;
061import com.sun.identity.federation.message.common.FSMsgException;
062import com.sun.identity.federation.message.FSNameIdentifierMappingRequest;
063import com.sun.identity.federation.message.FSNameIdentifierMappingResponse;
064import com.sun.identity.federation.message.FSAuthnRequest;
065import com.sun.identity.federation.meta.IDFFMetaException;
066import com.sun.identity.federation.meta.IDFFMetaManager;
067import com.sun.identity.federation.meta.IDFFMetaUtils;
068import com.sun.identity.federation.services.FSLoginHelper;
069import com.sun.identity.federation.services.FSLoginHelperException;
070import com.sun.identity.federation.services.util.FSServiceUtils;
071import com.sun.identity.federation.services.FSSessionManager;
072import com.sun.identity.federation.services.FSSession;
073import com.sun.identity.federation.services.FSSOAPService;
074import com.sun.identity.federation.services.FSSessionPartner;
075import com.sun.identity.federation.services.namemapping.FSNameMappingHandler;
076import com.sun.identity.liberty.ws.meta.jaxb.IDPDescriptorType;
077import com.sun.identity.liberty.ws.meta.jaxb.SPDescriptorType;
078import com.sun.identity.plugin.session.SessionException;
079import com.sun.identity.plugin.session.SessionManager;
080import com.sun.identity.plugin.session.SessionProvider;
081import com.sun.identity.saml.assertion.NameIdentifier;
082import com.sun.identity.saml.common.SAMLException;
083import org.w3c.dom.*;
084
085
086/**
087 * <code>LibertyManager</code> forms the basis of the Public APIs. It has all
088 * the methods which the JSPs etc.  need to use for
089 * federation/termination/logout etc. 
090 * @supported.all.api
091 */
092public class LibertyManager {
093    
094    static Debug debug = null;
095    private static IDFFMetaManager metaManager = null;
096    
097    static {
098        debug = Debug.getInstance("libIDFF");
099        metaManager = FSUtils.getIDFFMetaManager();
100    }
101    
102    /**
103     * Returns a list of all trusted Identity Providers under root realm.
104     *
105     * @return an iterator to a list of strings, each containing the
106     *         entity ID of Identity Providers.
107     * @deprecated This method has been deprecated. Please use 
108     *  <code>getAllIDPList(String realm)</code> instead.
109     * @see #getAllIDPList(String)
110     */
111    public static Iterator getIDPList() {
112        return getAllIDPList(IFSConstants.ROOT_REALM);
113    }
114
115    /**
116     * Returns a list of all trusted Identity Providers under the realm.
117     *
118     * @param realm The realm under which the entity resides.
119     * @return an iterator to a list of strings, each containing the
120     *         entity ID of Identity Providers.
121     */
122    public static Iterator getAllIDPList(String realm) {
123        // returns list of idps... for default org.
124        // since all the providers have their description under default org..
125        // hence returning the List of all the active idps.
126        Set idpList = new HashSet();
127        try {
128            if (metaManager != null) {
129                // TODO: check if the idp is active if we decide to support it
130                idpList.addAll(
131                    metaManager.getAllHostedIdentityProviderIDs(realm));
132                idpList.addAll(
133                    metaManager.getAllRemoteIdentityProviderIDs(realm));
134            }
135        } catch (IDFFMetaException ame) {
136            debug.error("LibertyManager: getAllIDPList: Error while getting " +
137                " Active ProviderIds  ", ame);
138        }
139        return idpList.iterator();
140    }// end of method.
141    
142    /**
143     * Returns a list of all trusted Identity Providers under root realm
144     * for a given hosted provider's entity ID.
145     *
146     * @param hostedEntityID hosted provider's entity ID.
147     * @return an iterator to a list of strings, each containing the provider
148     *         ID of an trusted Identity Provider for this hosted provider.
149     * @deprecated This method is deprecated. Please use
150     *  <code>getIDPList(String,String)</code>
151     * @see #getIDPList(String,String)
152     */
153    public static Iterator getIDPList(String hostedEntityID) {
154        return getList(IFSConstants.ROOT_REALM, hostedEntityID, 
155            IFSConstants.SP, IFSConstants.IDP);
156    }
157
158    /**
159     * Returns a list of all trusted Identity Providers under the realm 
160     * for a given hosted provider's entity ID.
161     *
162     * @param realm The realm under which the entity resides.
163     * @param hostedEntityID hosted provider's entity ID.
164     * @return an iterator to a list of strings, each containing the provider
165     *         ID of an trusted Identity Provider for this hosted provider.
166     */
167    public static Iterator getIDPList(String realm, String hostedEntityID) {
168        return getList(
169            realm, hostedEntityID, IFSConstants.SP, IFSConstants.IDP);
170    }
171    
172    /**
173     * Returns a list of all trusted Service Providers under root realm.
174     *
175     * @return an iterator to a list of strings, each containing the
176     *  entity ID of a Service Provider.
177     * @deprecated This method is deprecated. Please use 
178     *  <code>getAllSPList(String realm)</code>.
179     * @see #getAllSPList(String)
180     */
181    public static Iterator getSPList() {
182        return getSPList(IFSConstants.ROOT_REALM);
183    }
184
185    /**
186     * Returns a list of all trusted Service Providers under the realm.
187     *
188     * @param realm The realm under which the entity resides.
189     * @return an iterator to a list of strings, each containing the
190     *  entity ID of a Service Provider.
191     */
192    public static Iterator getAllSPList(String realm) {
193        // returns list of sps... for default org.
194        // since all the providers have their description under default org..
195        // hence returning the List of all the active sps.
196        Set spList = new HashSet();
197        try {
198            if (metaManager != null) {
199                // TODO: check if the sp is active if we decide to support it
200                spList.addAll(
201                    metaManager.getAllHostedServiceProviderEntities(realm));
202                spList.addAll(
203                    metaManager.getAllRemoteServiceProviderEntities(realm));
204            }
205        } catch (IDFFMetaException ame) {
206            debug.error("LibertyManager: getAllSPList: Error while getting " +
207                " Active ProviderIds  ", ame);
208        }
209        return spList.iterator();
210    }
211    
212    /**
213     * Returns a list of all trusted Service Providers under root realm for this
214     * Hosted Provider.
215     *
216     * @param hostedEntityID hosted provider's entity ID.
217     * @return an iterator to a list of strings, each containing the
218     *  entity ID of an Service Provider for the given Hosted Provider.
219     * @deprecated This method is deprecated. Please use
220     *  <code>getSPList(String,String)</code>
221     * @see #getSPList(String,String)
222     */
223    public static Iterator getSPList(String hostedEntityID) {
224        return getList(IFSConstants.ROOT_REALM, hostedEntityID, 
225            IFSConstants.IDP, IFSConstants.SP);
226    }
227
228    /**
229     * Returns a list of all trusted Service Providers for this
230     * Hosted Provider.
231     *
232     * @param realm The realm under which the entity resides.
233     * @param hostedEntityID hosted provider's entity ID.
234     * @return an iterator to a list of strings, each containing the
235     *  entity ID of an Service Provider for the given Hosted Provider.
236     */
237    public static Iterator getSPList(String realm, String hostedEntityID) {
238        return getList(
239            realm, hostedEntityID, IFSConstants.IDP, IFSConstants.SP);
240    }
241    
242    /**
243     * Returns the federation status of a user with an Identity Provider.
244     * This method assumes that the user is already federated with the 
245     * provider.
246     * @param user The user name obtained by calling <code>getUser()</code> on a
247     * Liberty-authenticated <code>HttpServletRequest</code> from the user
248     * @param remoteEntityId Entity ID of the Remote Identity Provider.
249     * @param hostedEntityId Hosted Provider's entity ID.
250     * @param hostedProviderRole Hosted Provider's Role.
251     * @return The federation status of a user with an Identity Provider.
252     * @deprecated This method is deprecated.
253     * @see #getIDPFederationStatus(String,String,String,String)
254     */
255    public static boolean getIDPFederationStatus(
256        String user,
257        String remoteEntityId,
258        String hostedEntityId,
259        String hostedProviderRole)
260    {
261        return getIDPFederationStatus(
262            user, IFSConstants.ROOT_REALM, remoteEntityId, 
263            hostedEntityId, hostedProviderRole);
264    }
265
266    /**
267     * Returns the federation status of a user with an Identity Provider.
268     * This method assumes that the user is already federated with the 
269     * provider.
270     * @param user The user name obtained by calling <code>getUser()</code> on a
271     * Liberty-authenticated <code>HttpServletRequest</code> from the user
272     * @param realm The realm under which the entity resides.
273     * @param remoteEntityId Entity ID of the Remote Identity Provider.
274     * @param hostedEntityId Hosted Provider's entity ID.
275     * @param hostedProviderRole Hosted Provider's Role.
276     * @return The federation status of a user with an Identity Provider.
277     */
278    public static boolean getIDPFederationStatus(
279        String user,
280        String realm,
281        String remoteEntityId,
282        String hostedEntityId,
283        String hostedProviderRole)
284    {
285        boolean result = false;
286        if (user == null ||
287            remoteEntityId == null ||
288            hostedEntityId == null ||
289            hostedProviderRole == null)
290        {
291           debug.error("LibertyManager.getIDPFederationStatus:: null input " +
292               " parameters.");
293           return result;
294        }
295        try {
296            result = FSAccountManager.getInstance(
297                getMetaAlias(realm, hostedEntityId, hostedProviderRole)).
298                    isFederationActive(user, remoteEntityId);
299        } catch (FSAccountMgmtException ame) {
300            debug.error("LibertyManager: getIDPFederationStatus: " +
301                "Couldnot get Federation Status ", ame);
302        }
303        return result;
304    }
305    
306    /**
307     * Returns the federations status of a user with an Service Provider.
308     * This method assumes that the user is already federated with the 
309     * provider.
310     *
311     * @param user The user name obtained by calling
312     *  <code>getRemoteUser()</code> on a Liberty-authenticated
313     *  <code>HttpServletRequest</code> from the user.
314     * @param remoteProviderId The entity ID of the Remote Service Provider.
315     * @param hostedProviderId Hosted provider's entity ID.
316     * @param hostedProviderRole Hosted Provider Role.
317     * @return The federation status of a user with an Service Provider.
318     * @deprecated This method is deprecated.
319     * @see #getSPFederationStatus(String,String,String,String,String)
320     */
321    public static boolean getSPFederationStatus(
322        String user,
323        String remoteProviderId,
324        String hostedProviderId,
325        String hostedProviderRole)
326    {
327        return getSPFederationStatus(
328            user, IFSConstants.ROOT_REALM, remoteProviderId,
329            hostedProviderId, hostedProviderRole);
330    }
331
332    /**
333     * Returns the federations status of a user with an Service Provider.
334     * This method assumes that the user is already federated with the 
335     * provider.
336     *
337     * @param user The user name obtained by calling
338     *  <code>getRemoteUser()</code> on a Liberty-authenticated
339     *  <code>HttpServletRequest</code> from the user.
340     * @param realm The relam under which the entity resides.
341     * @param remoteProviderId The entity ID of the Remote Service Provider.
342     * @param hostedProviderId Hosted provider's entity ID.
343     * @param hostedProviderRole Hosted Provider Role.
344     * @return The federation status of a user with an Service Provider.
345     */
346    public static boolean getSPFederationStatus(
347        String user,
348        String realm,
349        String remoteProviderId,
350        String hostedProviderId,
351        String hostedProviderRole)
352    {
353        boolean result = false;
354        if (user == null ||
355            remoteProviderId == null ||
356            hostedProviderId == null ||
357            hostedProviderRole == null)
358        {
359           FSUtils.debug.error("LibertyManager.getSPFederationStatus:: " +
360               " null input parameters.");
361           return result;
362        }
363        try {
364            result = FSAccountManager.getInstance(
365                getMetaAlias(realm, hostedProviderId, hostedProviderRole)).
366                    isFederationActive(user, remoteProviderId);
367        } catch (FSAccountMgmtException ame) {
368            debug.error("LibertyManager: getIDPFederationStatus: " +
369                "Couldnot get Federation Status ", ame);
370        }
371        return result;
372    }
373    
374    /**
375     * Returns a nonce for use in forms to be posted to well known servlets.
376     * Avoids cross site scripting type attacks.
377     *
378     * @param user The user obtained by calling
379     *  <code>getRemoteUser()</code> on a Liberty-authenticated
380     *  <code>HttpServletRequest</code>from the user.
381     * @return A string to be put in a hidden form field called "nonce".
382     * @deprecated This method has been deprecated. Please use other
383     *  means to generate nounce.
384     */
385    public static String getNonce(String user) {
386        Random random = new Random();
387        long l = random.nextLong();
388        String nonce = String.valueOf(l);
389        return nonce;
390    }
391    
392    /**
393     * Checks that the given nonce is the same as the last one returned via
394     * <code>getNonce()</code>, and invalidates it.
395     *
396     * @param nonce String containing nonce.
397     * @param user User name passed to <code>getNonce</code> to obtain nonce.
398     * @deprecated This method has been deprecated. Please use other
399     *        means to verify nounce.
400     * @return true is <code>nonce</code> is the same as the last one
401     *         returned by <code>getNonce</code> method.
402     */
403    public static boolean checkNonce(String nonce, String user) {
404        return true;
405    }
406    
407    /**
408     * Returns the ID of the provider discovered via the introduction protocol.
409     * If <code>null</code>, no provider was discovered. Can be passed to
410     * <code>LoginServlet</code> if <code>null</code>.
411     *
412     * @param request HTTP servlet request.
413     * @return the provider ID
414     */
415    public static String getIntroducedProvider(HttpServletRequest request) {
416        String provider = request.getParameter(IFSConstants.PROVIDER_ID_KEY);
417        return provider;
418    }
419    
420    /**
421     * The steps for getting the <code>IDPList</code> and <code>SPList</code>
422     * are the same (except for a role check). So having this private method
423     * which takes in role and does the required function.
424     */
425    private static Iterator getList(
426        String realm,
427        String entityID, 
428        String providerRole,
429        String remoteProviderRole)
430    {
431        Set trustedProviders = null;
432        BaseConfigType providerConfig = IDFFMetaUtils.getExtendedConfig(
433            realm, entityID, providerRole, metaManager);
434        if (providerConfig != null) {
435            trustedProviders = metaManager.getAllTrustedProviders(
436                providerConfig.getMetaAlias());
437        }
438        if (trustedProviders == null) {
439            trustedProviders = new HashSet();
440        }
441        return trustedProviders.iterator();
442    }
443    
444    // From here starts the methods which are outside the publicAPI but are 
445    // used by the jsp(Logout/Termination/Federation/CommonLogin...)
446
447    /**
448     * Returns the <code>metaAliasKey</code> from <code>IFSConstants</code>.
449     *
450     * @return the <code>metaAliasKey</code> from <code>IFSConstants</code>.
451     */
452    public static String getMetaAliasKey() {
453        return IFSConstants.META_ALIAS;
454    }
455    
456    /** 
457     * Returns the termination <code>providerIDKey</code> from
458     * <code>IFSConstants</code>.
459     *
460     * @return the termination <code>providerIDKey</code> from
461     *  <code>IFSConstants</code>.
462     */
463    public static String getTerminationProviderIDKey() {
464        return IFSConstants.TERMINATION_PROVIDER_ID;
465    }
466    
467    /** 
468     * Returns the <code>requestIDKey</code> from <code>IFSConstants</code>.
469     *
470     * @return the <code>requestIDKey</code> from <code>IFSConstants</code>.
471     */
472    public static String getRequestIDKey() {
473        return IFSConstants.AUTH_REQUEST_ID;
474    }
475    
476    /**
477     * Returns the <code>providerIDKey</code> from <code>IFSConstants</code>.
478     *
479     * @return the <code>providerIDKey</code> from <code>IFSConstants</code>.
480     */
481    public static String getProviderIDKey() {
482        return IFSConstants.PROVIDER_ID_KEY;
483    }
484    
485    /** 
486     * Returns the <code>LRURLKey</code> from <code>IFSConstants</code>.
487     *
488     * @return the <code>LRURLKey</code> from <code>IFSConstants</code>.
489     */
490    public static String getLRURLKey() {
491        return IFSConstants.LRURL;
492    }
493    
494    /**
495     * Returns the <code>COT</code> key from <code>IFSConstants</code>.
496     *
497     * @return the <code>COT</code> key from <code>IFSConstants</code>.
498     */
499    public static String getCOTKey() {
500        return IFSConstants.COTKEY;
501    }
502    
503    /**
504     * Returns the <code>selectedProviderKey</code> from
505     * <code>IFSConstants</code>.
506     *
507     * @return the <code>selectedProviderKey</code> from
508     *  <code>IFSConstants</code>.
509     */
510    public static String getSelectedProviderKey() {
511        return IFSConstants.SELECTEDPROVIDER;
512    }
513    
514    /**
515     * Returns Federation Error Key.
516     *
517     * @return Federation Error Key
518     */
519    public static String getFedErrorKey() {
520        return IFSConstants.FEDERROR;
521    }
522    
523    /**
524     * Returns <code>FederationRemark</code> Key.
525     *
526     * @return <code>FederationRemark</code> Key
527     */
528    public static String getFedRemarkKey() {
529        return IFSConstants.FEDREMARK;
530    }
531    
532    /** 
533     * Returns the user from <code>HttpServletRequest</code>.
534     *
535     * @param request HTTP servlet request.
536     * @return the user from <code>HttpServletRequest</code>.
537     */
538    public static String getUser(HttpServletRequest request) {
539        Object ssoToken = null;
540        try {
541            SessionProvider sessionProvider = SessionManager.getProvider();
542            ssoToken = sessionProvider.getSession(request);
543            if (ssoToken != null && sessionProvider.isValid(ssoToken)) {
544                debug.message("LibertyManager: getUser: token is valid" );
545                return sessionProvider.getPrincipalName(ssoToken);
546            }
547            return null;
548        } catch (SessionException ssoe) {
549            debug.error("LibertyManager: getUser: SessionException: ", ssoe);
550            return null;
551        }
552    }
553    
554    /**
555     * Returns Provider's <code>HomePageURL</code>.
556     *
557     * @param providerID Provider's entity ID.
558     * @param providerRole Provider Role.
559     * @return Provider's <code>HomePageURL</code>.
560     * @deprecated This method is deprecated.
561     * @see #getHomeURL(String,String,String)
562     */
563    public static String getHomeURL(String providerID, String providerRole) {
564        return getHomeURL(IFSConstants.ROOT_REALM, providerID, providerRole);
565    }
566
567    /**
568     * Returns Provider's <code>HomePageURL</code>.
569     *
570     * @param realm The realm under which the entity resides.
571     * @param providerID Provider's entity ID.
572     * @param providerRole Provider Role.
573     * @return Provider's <code>HomePageURL</code>.
574     */
575    public static String getHomeURL(
576        String realm, String providerID, String providerRole) 
577    {
578        String homeURL = null;
579        BaseConfigType config = IDFFMetaUtils.getExtendedConfig(
580            realm, providerID, providerRole, metaManager);
581        if (config != null) {
582            homeURL = IDFFMetaUtils.getFirstAttributeValue(
583                IDFFMetaUtils.getAttributes(config),
584                    IFSConstants.PROVIDER_HOME_PAGE_URL);
585        }
586        return homeURL;
587    }
588    
589    /** 
590     * Returns <code>PreLoginServlet</code> URL and appends
591     * <code>metaAlias</code> to it.
592     *
593     * @param providerID Provider's entity ID.
594     * @param providerRole Provider Role.
595     * @param request HTTP servlet request.
596     * @return <code>PreLoginServlet</code> URL and appends
597     * <code>metaAlias</code> to it.
598     * @deprecated This method is deprecated.
599     * @see #getPreLoginServletURL(String,String,String,HttpServletRequest)
600     */
601    public static String getPreLoginServletURL(
602        String providerID, 
603        String providerRole,
604        HttpServletRequest request)
605    {
606        return getPreLoginServletURL(
607            IFSConstants.ROOT_REALM, providerID, providerRole, request);
608    }
609
610    /** 
611     * Returns <code>PreLoginServlet</code> URL and appends
612     * <code>metaAlias</code> to it.
613     *
614     * @param realm The realm under which the entity resides.
615     * @param providerID Provider's entity ID.
616     * @param providerRole Provider Role.
617     * @param request HTTP servlet request.
618     * @return <code>PreLoginServlet</code> URL and appends
619     * <code>metaAlias</code> to it.
620     */
621    public static String getPreLoginServletURL(
622        String realm,
623        String providerID, 
624        String providerRole,
625        HttpServletRequest request)
626    {
627        String metaAlias = getMetaAlias(realm, providerID, providerRole);
628        String baseURL = FSServiceUtils.getServicesBaseURL(request);
629        return baseURL + IFSConstants.PRE_LOGIN_PAGE + "?" +
630            IFSConstants.META_ALIAS + "=" + metaAlias;
631    }
632        
633    /** 
634     * Returns the <code>LoginURL</code> from <code>IFSConstants</code>.
635     *
636     * @param request HTTP servlet request.
637     * @return the <code>LoginURL</code> from <code>IFSConstants</code>
638     */
639    public static String getLoginURL(HttpServletRequest request) {
640        String returnURL = FSServiceUtils.getServicesBaseURL(request) +
641            IFSConstants.LOGIN_PAGE + 
642            "?" + IFSConstants.ARGKEY + "=" + IFSConstants.NEWSESSION;
643        if (debug.messageEnabled()) {
644            debug.message("LibertyManager: getLoginURL: " + 
645                " returnURL = " + returnURL);
646        }
647        return returnURL;
648    }
649    
650    /**
651     * Returns the <code>interSiteURL</code> from <code>IFSConstants</code>.
652     *
653     * @param request HTTP servlet request.
654     * @return the <code>interSiteURL</code> from <code>IFSConstants</code>.
655     */
656    public static String getInterSiteURL(HttpServletRequest request) {
657        String returnURL = FSServiceUtils.getServicesBaseURL(request) +
658            "/" + IFSConstants.INTERSITE_URL;
659        if (debug.messageEnabled()) {
660            debug.message("LibertyManager::getInterSiteURL:: "
661                + "returnURL = " + returnURL);
662        }
663        return returnURL;
664    }
665    
666    
667    /** 
668     * Returns <code>entityID</code> from the provider Alias
669     * using <code>meta manager</code> calls.
670     *
671     * @param metaAlias The <code>metaAlias</code> of the provider
672     * @return <code>entityID</code> corresponding to the 
673     *  <code>metaAlias</code>.
674     */
675    public static String getEntityID(String metaAlias) {
676        try {
677            if (metaManager == null) {
678                debug.error("LibertyManager: getEntityID: meta manager isnull");
679                return null;
680            }
681            return metaManager.getEntityIDByMetaAlias(metaAlias);
682        } catch (IDFFMetaException ame) {
683            debug.error("LibertyManager: getEntityID: Error getting ID", ame);
684            return null;
685        }
686    } 
687    
688    /**
689     * Returns the list of all Trusted Identity Providers of this user not
690     * already federated with.  This is a subset of the Set returned by
691     * <code>getIDPList()</code>. This method is used to show the drop-down
692     * menu consisting of all the Identity Providers that the user is not
693     * already federated with.
694     *
695     * @param providerID provider's entity ID.
696     * @param providerRole provider Role.
697     * @param userName name of user.
698     * @return Set containing all the Identity Provider IDs which the user is
699     *  not already federated with.
700     * @deprecated This method is deprecated. Please use 
701     *  <code>getProvidersToFederate(String, String, String,String)</code>
702     * @see #getProvidersToFederate(String,String,String,String)
703     */
704    public static Set getProvidersToFederate(
705        String providerID, 
706        String providerRole,
707        String userName) 
708    {
709        return getProvidersToFederate(
710            IFSConstants.ROOT_REALM, providerID, providerRole, userName);
711    }
712
713    /**
714     * Returns the list of all Trusted Identity Providers of this user not
715     * already federated with.  This is a subset of the Set returned by
716     * <code>getIDPList()</code>. This method is used to show the drop-down
717     * menu consisting of all the Identity Providers that the user is not
718     * already federated with.
719     *
720     * @param realm the realm that the provider resides
721     * @param providerID provider's entity ID.
722     * @param providerRole provider Role.
723     * @param userName name of user.
724     * @return Set containing all the Identity Provider IDs which the user is
725     *  not already federated with.
726     */
727    public static Set getProvidersToFederate(
728        String realm,
729        String providerID, 
730        String providerRole,
731        String userName) 
732    {
733        Set unFederatedIDPs = new HashSet();
734        if (providerID == null ||
735            providerRole == null ||
736            userName == null)
737        {
738            debug.error("LibertyManager.getProvidersToFederate:: null" +
739                " parameter values");
740            return unFederatedIDPs;
741        }
742
743        if (!providerRole.equals(IFSConstants.SP) &&
744            !providerRole.equals(IFSConstants.IDP)) 
745        {
746            debug.error("LibertyManager.getProvidersToFederate:: Invalid" +
747                " ProviderRole.");
748            return unFederatedIDPs;
749        }
750        Iterator idpList = getIDPList(realm, providerID);
751        Set alreadyFederatedProviders = null;
752        try {
753            alreadyFederatedProviders = FSAccountManager.getInstance(
754                getMetaAlias(realm, providerID, providerRole)).
755                    readAllFederatedProviderID(providerID, userName); 
756            String idp = null;
757            while (idpList.hasNext()) {
758                idp = (String) idpList.next();
759                if (!alreadyFederatedProviders.contains(idp)) {
760                    unFederatedIDPs.add(idp);
761                }
762            }
763        } catch (FSAccountMgmtException ame) {
764            debug.error("LibertyManager: getUnFederatedIDPList: Error while " +
765                " getting allFederatedProviderID from Account Mgmt", ame);
766        }
767        
768        return unFederatedIDPs;
769    }
770    
771    /** 
772     * Returns the set of federated providers for an user
773     * using Account Management API.
774     *
775     * @param userName for which the federated providers are to be returned.
776     * @param hostProviderId Hosted provider's entity ID.
777     * @param hostProviderRole Hosted Provider Role.
778     * @return federated providers a Set containing the provider IDs of
779     *  federated providers for the given <code>userName</code>.
780     * @deprecated This method is deprecated.
781     * @see #getFederatedProviders(String, String, String, String)
782     */
783    public static Set getFederatedProviders(
784        String userName,
785        String hostProviderId,
786        String hostProviderRole)
787    {
788        return getFederatedProviders(
789            userName, IFSConstants.ROOT_REALM,hostProviderId, hostProviderRole);
790    }
791
792    /** 
793     * Returns the set of federated providers for an user
794     * using Account Management API.
795     *
796     * @param userName for which the federated providers are to be returned.
797     * @param realm The realm under which the entity resides.
798     * @param hostProviderId Hosted provider's entity ID.
799     * @param hostProviderRole Hosted Provider Role.
800     * @return federated providers a Set containing the provider IDs of
801     *  federated providers for the given <code>userName</code>.
802     */
803    public static Set getFederatedProviders(
804        String userName,
805        String realm,
806        String hostProviderId,
807        String hostProviderRole)
808    {
809        Set federatedProviders = new HashSet();
810        try {
811            federatedProviders = FSAccountManager.getInstance(
812                getMetaAlias(realm, hostProviderId, hostProviderRole)).
813                    readAllFederatedProviderID(userName); 
814        } catch (FSAccountMgmtException ame) {
815            debug.error("LibertyManager: getFederatedProviders: Error while " +
816                " getting federatedProviderIDs from Account Mgmt", ame);
817        }
818        return federatedProviders;
819    }
820    
821    /**
822     * Returns the List of COTs for the given Provider under root realm.
823     *
824     * @param providerId The ID of the provider whose <code>COTList</code>
825     *  is to be found
826     * @param providerRole The Role of the provider whose <code>COTList</code>
827     *  is to be found
828     * @return The set containing the authentication domains for the given
829     *  provider.
830     * @deprecated This method is deprecated.
831     * @see #getListOfCOTs(String,String,String)
832     */
833    public static Set getListOfCOTs(String providerId, String providerRole) {
834        return getListOfCOTs(IFSConstants.ROOT_REALM, providerId, providerRole);
835    }
836
837    /**
838     * Returns the List of COTs for the given Provider under a realm.
839     *
840     * @param realm The realm under which the entity resides.
841     * @param providerId The ID of the provider whose <code>COTList</code>
842     *  is to be found
843     * @param providerRole The Role of the provider whose <code>COTList</code>
844     *  is to be found
845     * @return The set containing the authentication domains for the given
846     *  provider.
847     */
848    public static Set getListOfCOTs(
849        String realm, String providerId, String providerRole) 
850    {
851        Set returnSet = new HashSet();
852        BaseConfigType hostConfig = IDFFMetaUtils.getExtendedConfig(
853            realm, providerId, providerRole, metaManager);
854        if (hostConfig != null) {
855            List cotSet = IDFFMetaUtils.getAttributeValueFromConfig(
856                hostConfig, IFSConstants.COT_LIST);
857            if (cotSet != null && !cotSet.isEmpty()) {
858                Iterator iter = cotSet.iterator();
859                while (iter.hasNext()) {
860                    String cotID = (String) iter.next();
861                    try {
862                        CircleOfTrustManager cotManager = 
863                            new CircleOfTrustManager();
864                        CircleOfTrustDescriptor cotDesc =
865                            cotManager.getCircleOfTrust(realm, cotID);
866                        String tldURL = cotDesc.getIDFFWriterServiceURL();
867                        String cotStatus = cotDesc.getCircleOfTrustStatus();
868                        if (tldURL != null && tldURL.length() > 0 &&
869                            cotStatus.equalsIgnoreCase(IFSConstants.ACTIVE)) 
870                        {
871                            returnSet.add((String)cotID);
872                        }
873                    } catch (COTException fsExp) {
874                        debug.error("LibertyManager: getListOfCots " +
875                            "COTException caught ", fsExp);
876                    }
877                }
878            }
879            if (returnSet != null && returnSet.size() > 0) {
880                if (debug.messageEnabled()) {
881                    debug.message("LibertyManager: getListOfCots returning " +
882                        " cot set with " + returnSet);
883                }
884            } else {
885                if (debug.messageEnabled()) {
886                    debug.message("LibertyManager::getListOfCots returning" +
887                        " null. Looks like COT is not set");
888                }
889            }
890        }
891        return returnSet;
892    }
893
894    /** 
895     * Returns <code>metaAlias</code> from provider ID under root realm.
896     *
897     * @param providerID Provider's entity ID.
898     * @param providerRole Provider Role.
899     * @return <code>metaAlias</code> from provider ID
900     * @deprecated This method is deprecated by 
901     *  <code>getMetaAlias(String,String,String)</code>.
902     * @see #getMetaAlias(String,String,String)
903     */
904    public static String getMetaAlias(String providerID, String providerRole) {
905        return getMetaAlias(null, providerID, providerRole);
906    }
907
908    /** 
909     * Returns <code>metaAlias</code> from provider ID under a realm.
910     *
911     * @param realm The realm under which the entity resides.
912     * @param providerID Provider's entity ID.
913     * @param providerRole Provider Role.
914     * @return <code>metaAlias</code> from provider ID
915     */
916    public static String getMetaAlias(
917        String realm, String providerID, String providerRole) 
918    {
919        BaseConfigType providerConfig = IDFFMetaUtils.getExtendedConfig(
920            realm, providerID, providerRole, metaManager);
921
922        String metaAlias = "";
923        if (providerConfig != null) {
924            metaAlias = providerConfig.getMetaAlias();
925        }
926        if (debug.messageEnabled()) {
927            debug.message("LibertyManager: getMetaAlias: providerID is " +
928                providerID + " and corresponding metaAlias is " + metaAlias);
929        }
930        return metaAlias;
931     }
932
933    /** 
934     * Returns the <code>FederationDonePageURL</code> from the provider ID
935     * under root realm.
936     *
937     * @param providerID Provider's entity ID.
938     * @param providerRole Provider Role.
939     * @param request HTTP servlet request.
940     * @return the <code>FederationDonePageURL</code> from the provider ID.
941     * @deprecated This method is deprecated.
942     * @see #getFederationDonePageURL(String,String,String,HttpServletRequest)
943     */
944    public static String getFederationDonePageURL(
945        String providerID, String providerRole, HttpServletRequest request) 
946    {
947        return getFederationDonePageURL(
948            IFSConstants.ROOT_REALM, providerID, providerRole, request);
949    }
950
951    /** 
952     * Returns the <code>FederationDonePageURL</code> from the provider ID
953     * under a realm.
954     *
955     * @param realm The realm under which the entity resides.
956     * @param providerID Provider's entity ID.
957     * @param providerRole Provider Role.
958     * @param request HTTP servlet request.
959     * @return the <code>FederationDonePageURL</code> from the provider ID.
960     * @deprecated This method is deprecated.
961     * @see #getFederationDonePageURL(String,String,String,HttpServletRequest)
962     */
963    public static String getFederationDonePageURL(
964        String realm, String providerID, 
965        String providerRole, HttpServletRequest request) 
966    {
967        BaseConfigType providerConfig = IDFFMetaUtils.getExtendedConfig(
968            realm, providerID, providerRole, metaManager);
969        String metaAlias = null;
970        if (providerConfig != null) {
971            metaAlias = providerConfig.getMetaAlias();
972        }
973        return FSServiceUtils.getFederationDonePageURL(
974            request, providerConfig, metaAlias);
975    }
976    
977    
978    /** 
979     * Returns the <code>TerminationDonePageURL</code> from the provider ID
980     * under root realm.
981     *
982     * @param providerID Provider's entity ID.
983     * @param providerRole Provider Role.
984     * @param request HTTP servlet request.
985     * @return the <code>TerminationDonePageURL</code> from the provider ID.
986     * @deprecated This method is deprecated
987     * @see #getTerminationDonePageURL(String,String,String,HttpServletRequest)
988     */
989    public static String getTerminationDonePageURL(
990        String providerID, String providerRole, HttpServletRequest request) 
991    {
992        return getTerminationDonePageURL(
993            IFSConstants.ROOT_REALM, providerID, providerRole, request);
994    }
995
996    /** 
997     * Returns the <code>TerminationDonePageURL</code> from the provider ID
998     * under a realm.
999     *
1000     * @param realm The realm under which the entity resides.
1001     * @param providerID Provider's entity ID.
1002     * @param providerRole Provider Role.
1003     * @param request HTTP servlet request.
1004     * @return the <code>TerminationDonePageURL</code> from the provider ID.
1005     */
1006    public static String getTerminationDonePageURL(
1007        String realm, String providerID, 
1008        String providerRole, HttpServletRequest request) 
1009    {
1010        BaseConfigType providerConfig = IDFFMetaUtils.getExtendedConfig(
1011            realm, providerID, providerRole, metaManager);
1012        String metaAlias = null;
1013        if (providerConfig != null) {
1014            metaAlias = providerConfig.getMetaAlias();
1015        }
1016        return FSServiceUtils.getTerminationDonePageURL(
1017            request, providerConfig, metaAlias);
1018       
1019    }
1020    
1021    /**
1022     * Returns Termination URL.
1023     *
1024     * @param providerID Provider's entity ID.
1025     * @param providerRole Provider Role.
1026     * @param request HTTP servlet request.
1027     * @return Termination URL.
1028     * @deprecated This method is deprecated
1029     * @see #getTerminationURL(String,String,String,HttpServletRequest)
1030     */
1031    public  static String getTerminationURL(
1032        String providerID,
1033        String providerRole,
1034        HttpServletRequest request)
1035    {
1036        return getTerminationURL(IFSConstants.ROOT_REALM, providerID, 
1037            providerRole, request);
1038    }
1039
1040    /**
1041     * Returns Termination URL.
1042     *
1043     * @param realm The realm under which the entity resides.
1044     * @param providerID Provider's entity ID.
1045     * @param providerRole Provider Role.
1046     * @param request HTTP servlet request.
1047     * @return Termination URL.
1048     */
1049    public  static String getTerminationURL(
1050        String realm,
1051        String providerID,
1052        String providerRole,
1053        HttpServletRequest request)
1054    {
1055        String metaAlias = getMetaAlias(realm, providerID, providerRole);
1056        String baseURL = FSServiceUtils.getServicesBaseURL(request);
1057        return baseURL + IFSConstants.TERMINATE_SERVLET + "?"
1058            + IFSConstants.META_ALIAS + "=" + metaAlias;
1059    }
1060    
1061    /**
1062     * Returns <code>NameRegistrationURL</code>.
1063     *
1064     * @param providerID Provider's entity ID.
1065     * @param providerRole Provider Role.
1066     * @param request HTTP servlet request.
1067     * @return <code>NameRegistrationURL</code>.
1068     * @deprecated This method is deprecated.
1069     * @see #getNameRegistrationURL(String,String,String,HttpServletRequest)
1070     */
1071    public static String getNameRegistrationURL(
1072        String providerID,
1073        String providerRole,
1074        HttpServletRequest request)
1075    {
1076        return getNameRegistrationURL(
1077            IFSConstants.ROOT_REALM, providerID, providerRole, request);
1078    }
1079
1080    /**
1081     * Returns <code>NameRegistrationURL</code>.
1082     *
1083     * @param realm The realm under which the entity resides.
1084     * @param providerID Provider's entity ID.
1085     * @param providerRole Provider Role.
1086     * @param request HTTP servlet request.
1087     * @return <code>NameRegistrationURL</code>.
1088     */
1089    public static String getNameRegistrationURL(
1090        String realm,
1091        String providerID,
1092        String providerRole,
1093        HttpServletRequest request)
1094    {
1095        String metaAlias = getMetaAlias(realm, providerID, providerRole);
1096        String baseURL = FSServiceUtils.getServicesBaseURL(request);
1097        return baseURL + IFSConstants.REGISTRATION_SERVLET + "?"
1098            + IFSConstants.META_ALIAS + "=" + metaAlias;
1099        
1100    }
1101
1102    /**
1103     * Returns the provider's error page.
1104     *
1105     * @param providerId Provider's entity ID.
1106     * @param providerRole Provider Role.
1107     * @param request HTTP servlet request.
1108     * @return the provider's error page.
1109     * @deprecated This method is deprecated. Please use
1110     *  <code>getErrorPageURL(String,String,String,HttpServletRequest)</code>
1111     * @see #getErrorPageURL(String,String,String,HttpServletRequest)
1112     */
1113    public static String getErrorPageURL(
1114        String providerId, 
1115        String providerRole,
1116        HttpServletRequest request) 
1117    {
1118        return getErrorPageURL(IFSConstants.ROOT_REALM, providerId, 
1119            providerRole, request);
1120    }
1121
1122    /**
1123     * Returns the provider's error page.
1124     *
1125     * @param realm The realm under which the entity resides.
1126     * @param providerId Provider's entity ID.
1127     * @param providerRole Provider Role.
1128     * @param request HTTP servlet request.
1129     * @return the provider's error page.
1130     */
1131    public static String getErrorPageURL(
1132        String realm,
1133        String providerId, 
1134        String providerRole,
1135        HttpServletRequest request) 
1136    {
1137        BaseConfigType providerConfig = IDFFMetaUtils.getExtendedConfig(
1138            realm, providerId, providerRole, metaManager);
1139        String metaAlias = null;
1140        if (providerConfig != null) {
1141            metaAlias = providerConfig.getMetaAlias();
1142        }
1143        return FSServiceUtils.getErrorPageURL(
1144            request, providerConfig, metaAlias);
1145    }
1146    
1147    /**
1148     * Returns the <code>FederationHandler</code>.
1149     *
1150     * @param request HTTP servlet request
1151     * @return the <code>FederationHandler</code>.
1152     */
1153    public static String getFederationHandlerURL(HttpServletRequest request) {
1154        String returnURL = FSServiceUtils.getServicesBaseURL(request)
1155            + "/" + IFSConstants.FEDERATION_HANDLER;
1156        if (debug.messageEnabled()) {
1157            debug.message(
1158                "LibertyManager: getFederationHandler: returnURL = " + 
1159                returnURL);
1160        }
1161        return returnURL;
1162    }
1163    
1164    /**
1165     * Returns the <code>ConsentHandler</code>.
1166     *
1167     * @param request HTTP servlet request.
1168     * @return the <code>ConsentHandler</code>.
1169     */
1170    public static String getConsentHandlerURL(HttpServletRequest request) {
1171        String returnURL =FSServiceUtils.getServicesBaseURL(request)
1172            + "/" + IFSConstants.CONSENT_HANDLER;
1173        if (debug.messageEnabled()) {
1174            debug.message(
1175                "LibertyManager: getConsentHandler: returnURL = " + returnURL);
1176        }
1177        return returnURL;
1178    }
1179    
1180    /** 
1181     * Returns true if logout succeeded.
1182     *
1183     * @param request HTTP servlet request.
1184     * @return true if logout succeeded.
1185     */
1186    public static boolean isLogoutSuccess(HttpServletRequest request) {
1187        String status = request.getParameter(IFSConstants.LOGOUT_STATUS);
1188        if (status == null || 
1189            status.equalsIgnoreCase(IFSConstants.LOGOUT_SUCCESS)) 
1190        {
1191            return true;
1192        } else {
1193            return false;
1194        }
1195    }
1196    
1197    /** 
1198     * Returns true if Termination succeeds.
1199     *
1200     * @param request HTTP servlet request.
1201     * @return true if Termination succeeds.
1202     */
1203    public static boolean isTerminationSuccess(HttpServletRequest request) {
1204        String status = request.getParameter(IFSConstants.TERMINATION_STATUS);
1205        if (status == null ||
1206            status.equalsIgnoreCase(IFSConstants.TERMINATION_SUCCESS))
1207        {
1208            return true;
1209        } else {
1210            return false;
1211        }
1212    }
1213    
1214    /** 
1215     * Returns true if Federation is cancelled.
1216     *
1217     * @param request HTTP servlet request.
1218     * @return true if Federation is cancelled.
1219     */
1220    public static boolean isFederationCancelled(HttpServletRequest request) {
1221        String status = request.getParameter(IFSConstants.TERMINATION_STATUS);
1222        if (status != null &&
1223            status.equalsIgnoreCase(IFSConstants.CANCEL))
1224        {
1225            return true;
1226        } else {
1227            return false;
1228        }
1229    }
1230
1231    /** 
1232     * Returns true if termination is cancelled.
1233     *
1234     * @param request HTTP servlet request.
1235     * @return true if termination is cancelled.
1236     */
1237    public static boolean isTerminationCancelled(HttpServletRequest request) {
1238        String status = request.getParameter(IFSConstants.TERMINATION_STATUS);
1239        if (status != null &&
1240            status.equalsIgnoreCase(IFSConstants.CANCEL))
1241        {
1242            return true;
1243        } else {
1244            return false;
1245        }
1246    }
1247    
1248    /**
1249     * Returns the realm by parsing the metaAlias. MetaAlias format is
1250     * <pre>
1251     * &lt;realm>/&lt;any string without '/'> for non-root realm or
1252     * /&lt;any string without '/'> for root realm.
1253     * </pre>
1254     * @param metaAlias The metaAlias.
1255     * @return the realm associated with the metaAlias.
1256     */
1257    public static String getRealmByMetaAlias(String metaAlias) {
1258        return IDFFMetaUtils.getRealmByMetaAlias(metaAlias);
1259    }
1260
1261    /** 
1262     * Creates New Request ID from the <code>HttpRequestServlet</code>.
1263     *
1264     * @param request HTTP servlet request.
1265     * @return New Request ID from the <code>HttpRequestServlet</code>.
1266     */
1267    public static String getNewRequest(HttpServletRequest request) {
1268        String targetURL = request.getParameter(IFSConstants.LRURL);
1269        String metaAlias = request.getParameter(IFSConstants.META_ALIAS);
1270        String entityID = getEntityID(metaAlias);
1271        String realm = IDFFMetaUtils.getRealmByMetaAlias(metaAlias);
1272        Map headerMap = getHeaderMap(request);
1273        String homePage = null;
1274        if (targetURL == null || targetURL.length() <= 0 ) {
1275            try {
1276                if (metaManager != null) {
1277                    BaseConfigType providerConfig = 
1278                        metaManager.getSPDescriptorConfig(realm, entityID);
1279                    homePage = IDFFMetaUtils.getFirstAttributeValue(
1280                        IDFFMetaUtils.getAttributes(providerConfig),
1281                        IFSConstants.PROVIDER_HOME_PAGE_URL);
1282                }
1283            } catch (IDFFMetaException ame) {
1284                debug.error("LibertyManager: getNewRequest: Error" +
1285                    " while getting the HostedProvider from meta mgmt",
1286                    ame);
1287            }
1288            
1289            if (debug.messageEnabled()) {
1290                debug.message("LibertyManager: getNewRequestID." +
1291                    " no goto in queryString.Assinging targetURL = " +
1292                    homePage);
1293            }
1294            targetURL = homePage;
1295        }
1296        
1297        try {
1298            FSLoginHelper loginHelper = new FSLoginHelper(request);
1299            // get the authlevel key
1300            HttpSession httpSession = request.getSession();
1301            String authLevel = (String) httpSession.getAttribute(
1302                IFSConstants.AUTH_LEVEL_KEY);
1303            Map retMap = loginHelper.createAuthnRequest(
1304                headerMap, targetURL, authLevel, metaAlias, null, true);
1305            if (retMap != null) {
1306                String reqID = (String)retMap.get(IFSConstants.AUTH_REQUEST_ID);
1307                if (debug.messageEnabled()) {
1308                    debug.message("LibertyManager: getNewRequestID: " +
1309                        "new request created with id " + reqID);
1310                } 
1311                return reqID;
1312            } else {
1313                debug.error("LibertyManager: getNewRequestID " +
1314                    " Could not create new request ");
1315                return null;
1316            }
1317        } catch (FSLoginHelperException exp) {
1318            debug.error("LibertyManager::getNewRequestID" +
1319                "In login helper exception ", exp);
1320            return null;
1321        }
1322    }
1323    
1324    /**
1325     * Sets the authentication request to be sent to identity provider under
1326     * root realm.
1327     * 
1328     * @param request <code>FSAuthnRequest</code> associated with a user
1329     *  session.
1330     * @param entityID Hosted Provider's entity ID
1331     * @return <code>true</code> if the operation is successful; 
1332     *  <code>false</code> otherwise.
1333     * @deprecated This method is deprecated.
1334     * @see #setAuthnRequest(FSAuthnRequest,String,String)
1335     */
1336    public static boolean setAuthnRequest(
1337        FSAuthnRequest request, String entityID) 
1338    {
1339        return setAuthnRequest(request, IFSConstants.ROOT_REALM, entityID);
1340    }
1341
1342    /**
1343     * Sets the authentication request to be sent to identity provider.
1344     * 
1345     * @param request <code>FSAuthnRequest</code> associated with a user
1346     *  session.
1347     * @param realm the realm in which the entity resides
1348     * @param entityID Hosted Provider's entity ID
1349     * @return <code>true</code> if the operation is successful; 
1350     *  <code>false</code> otherwise.
1351     */
1352    public static boolean setAuthnRequest(
1353        FSAuthnRequest request, String realm, String entityID) 
1354    {
1355  
1356        if (request == null || entityID == null) {
1357            debug.message("LibertyManager.setAuthnRequest: null Input params");
1358            return false; 
1359        }
1360        try {
1361            FSSessionManager sessionManager = FSSessionManager.getInstance(
1362                getMetaAlias(realm, entityID, IFSConstants.SP));
1363            String requestID = request.getRequestID();
1364            if (requestID != null) {
1365                sessionManager.setAuthnRequest(requestID, request);
1366                return true;
1367            }
1368        } catch(Exception ex) {
1369            FSUtils.debug.error("LibertyManager.setAuthnRequest"+
1370                " Exception while setting authn request.", ex);
1371        }
1372        return false;
1373    }
1374
1375    /**
1376     * Returns the HeaderMap.
1377     */
1378    private static Map getHeaderMap(HttpServletRequest request) {
1379        Map headerMap = new HashMap();
1380        Enumeration headerNames = request.getHeaderNames();
1381        while (headerNames.hasMoreElements()) {
1382            String hn = headerNames.nextElement().toString();
1383            String hv = request.getHeader(hn);
1384            headerMap.put(hn, hv);
1385        }
1386        return headerMap;
1387    }
1388    
1389    public static String cleanQueryString(HttpServletRequest request) {
1390        Enumeration paramEnum = request.getParameterNames();
1391        String returnString = new String();
1392        while (paramEnum.hasMoreElements()) {
1393            String paramKey = (String)paramEnum.nextElement();
1394            if (paramKey.equalsIgnoreCase(IFSConstants.META_ALIAS) ||
1395                paramKey.equalsIgnoreCase(IFSConstants.AUTH_REQUEST_ID) ||
1396                paramKey.equalsIgnoreCase(IFSConstants.LRURL)) 
1397            {
1398                if (debug.messageEnabled()) {
1399                    debug.message("Libertymanager::cleanQueryString " +
1400                        " found metaAlias or LRURL or AUTH_REQUEST_ID.");
1401                }
1402            } else if (!paramKey.equals(IFSConstants.ARTIFACT_NAME_DEFAULT)) {
1403                String paramValue = request.getParameter(paramKey);
1404                if (returnString == null || returnString.length() < 1) {
1405                    returnString =  paramKey + "="
1406                        + URLEncDec.encode(paramValue);
1407                } else {
1408                    returnString = returnString + "&amp;"
1409                        +  paramKey + "="
1410                        + URLEncDec.encode(paramValue);
1411                }
1412            }
1413        }
1414        // check and append the authlevel key
1415        HttpSession httpSession = request.getSession();
1416        String authLevel = (String) httpSession.getAttribute(
1417                          IFSConstants.AUTH_LEVEL_KEY);
1418        if (authLevel != null) {
1419            if (returnString == null || returnString.length() < 1) {
1420                returnString = IFSConstants.AUTH_LEVEL_KEY + "=" + authLevel;
1421            } else {
1422                returnString = returnString + "&amp;" +
1423                    IFSConstants.AUTH_LEVEL_KEY + "=" + authLevel;
1424            }
1425        }
1426        if (debug.messageEnabled()) {
1427            debug.message("Libertymanager::cleanQueryString " +
1428                " returning with " + returnString);
1429        }
1430        return returnString;
1431    }
1432   
1433    /**
1434     * Returns succinct ID of a provider.
1435     *
1436     * @param entityID provider's entity ID.
1437     * @return succinct ID of a provider.
1438     * @deprecated This method has been deprecated. Use
1439     *   {@link #getSuccinctID(String, String)}
1440     */
1441    public static String getSuccinctID(String entityID) {
1442        return FSUtils.generateSourceID(entityID);
1443    }
1444   
1445    /**
1446     * Returns succinct ID of a provider.
1447     *
1448     * @param providerID provider's entity ID.
1449     * @param providerRole provider Role.
1450     * @return succinct ID of a provider.
1451     */
1452    public static String getSuccinctID(String providerID, String providerRole) {
1453        return FSUtils.generateSourceID(providerID);
1454    }
1455
1456    /**
1457     * Returns registered providers of an user.
1458     *
1459     * @param userName user ID.
1460     * @param hostProviderId Hosted provider's entity ID.
1461     * @param providerRole Hosted Provider Role.
1462     * @return registered providers.
1463     * @deprecated This method is deprecated. Please use
1464     *  <code>getRegisteredProviders(String,String,String,String)</code>
1465     * @see #getRegisteredProviders(String,String,String,String)
1466     */
1467    public static Set getRegisteredProviders(
1468        String userName,
1469        String hostProviderId,
1470        String providerRole)
1471    {
1472        return getRegisteredProviders(
1473            userName, IFSConstants.ROOT_REALM, hostProviderId, providerRole);
1474    }
1475
1476    /**
1477     * Returns registered providers of an user.
1478     *
1479     * @param userName user ID.
1480     * @param realm The realm under which the entity resides.
1481     * @param hostProviderId Hosted provider's entity ID.
1482     * @param providerRole Hosted Provider Role.
1483     * @return registered providers.
1484     */
1485    public static Set getRegisteredProviders(
1486        String userName,
1487        String realm,
1488        String hostProviderId,
1489        String providerRole)
1490    {
1491        Set registeredProviders = new HashSet();
1492        try {
1493            registeredProviders = FSAccountManager.getInstance(
1494                getMetaAlias(realm, hostProviderId, providerRole)).
1495                    readAllFederatedProviderID(userName); 
1496        } catch (FSAccountMgmtException ame) {
1497            debug.error("LibertyManager: getRegisteredProviders: Error while " +
1498                " getting federatedProviderIDs from Account Mgmt", ame);
1499        }
1500        return registeredProviders;
1501    }
1502
1503    /**
1504     * Returns name registration provider ID key.
1505     *
1506     * @return name registration provider ID key.
1507     */
1508    public static String getNameRegistrationProviderIDKey() {
1509        return IFSConstants.REGISTRATION_PROVIDER_ID;
1510    }
1511    
1512    /** 
1513     * Returns true if name registration is cancelled.
1514     *
1515     * @param request HTTP servlet request.
1516     * @return true if name registration is cancelled.
1517     */
1518    public static boolean isNameRegistrationCancelled(
1519        HttpServletRequest request) 
1520    {
1521        String status = request.getParameter(IFSConstants.REGISTRATION_STATUS);
1522        if (status != null && status.equalsIgnoreCase(IFSConstants.CANCEL)) {
1523            return true;
1524        } else {
1525            return false;
1526        }
1527    }
1528    
1529    /** 
1530     * Returns true if name registration succeeds.
1531     *
1532     * @param request HTTP servlet request.
1533     * @return true if name registration succeeds.
1534     */
1535    public static boolean isNameRegistrationSuccess(HttpServletRequest request)
1536    {
1537        String status = request.getParameter(IFSConstants.REGISTRATION_STATUS);
1538        if (status != null &&
1539            status.equalsIgnoreCase(IFSConstants.REGISTRATION_SUCCESS))
1540        {
1541            return true;
1542        } else {
1543            return false;
1544        }
1545    }
1546    
1547    /** 
1548     * Returns the Name <code>RegistrationDonePageURL</code> from the
1549     * <code>providerID</code> under root realm.
1550     *
1551     * @param providerID provider's entity ID.
1552     * @param providerRole provider Role.
1553     * @param request HTTP servlet request.
1554     * @return the Name <code>RegistrationDonePageURL</code> from the
1555     *  <code>providerID</code>.
1556     * @deprecated This method is deprecated. Please use
1557     *  <code>getNameRegistrationDonePageURL(
1558     *  String,String,String,HttpServletRequest)</code>
1559     * @see #getNameRegistrationDonePageURL(String,String,String,HttpServletRequest)
1560     */
1561    public static String getNameRegistrationDonePageURL(
1562        String providerID, String providerRole, HttpServletRequest request) 
1563    {      
1564        return getNameRegistrationDonePageURL(
1565            IFSConstants.ROOT_REALM, providerID, providerRole, request);
1566    }
1567
1568    /** 
1569     * Returns the Name <code>RegistrationDonePageURL</code> from the
1570     * <code>providerID</code> under a realm.
1571     *
1572     * @param realm The realm under which the entity resides.
1573     * @param providerID provider's entity ID.
1574     * @param providerRole provider Role.
1575     * @param request HTTP servlet request.
1576     * @return the Name <code>RegistrationDonePageURL</code> from the
1577     *  <code>providerID</code>.
1578     */
1579    public static String getNameRegistrationDonePageURL(
1580        String realm, 
1581        String providerID, 
1582        String providerRole, 
1583        HttpServletRequest request) 
1584    {      
1585        BaseConfigType extendedConfig = IDFFMetaUtils.getExtendedConfig(
1586            realm, providerID, providerRole, metaManager);
1587        String metaAlias = null;
1588        if (extendedConfig != null) {
1589            metaAlias = extendedConfig.getMetaAlias();
1590        }
1591        return FSServiceUtils.getRegistrationDonePageURL(
1592            request, extendedConfig, metaAlias);
1593    }
1594    
1595    /** 
1596     * Returns Authentication Request Envelope from a HTTP servlet request.
1597     * @param request a HTTP servlet request
1598     * @return Authentication Request Envelope in String
1599     */
1600    public static String getAuthnRequestEnvelope(HttpServletRequest request)
1601    {
1602        FSLoginHelper loginHelper = new FSLoginHelper(request);
1603        return loginHelper.createAuthnRequestEnvelope(request); 
1604    }
1605
1606    /** 
1607     * Determines if a HTTP servlet request is Liberty-enabled client and 
1608     * proxy profile.
1609     * @param request a HTTP servlet request
1610     * @return <code>true</code> if it is Liberty-enabled client and 
1611     *  proxy profile
1612     */
1613    public static boolean isLECPProfile(HttpServletRequest request) {
1614        return FSServiceUtils.isLECPProfile(request);
1615    }
1616
1617    /** 
1618     * Returns Liberty-enabled client and proxy profile HTTP header name.
1619     * @return header name
1620     */
1621    public static String getLECPHeaderName(){
1622        return IFSConstants.LECP_HEADER_NAME;
1623    }
1624
1625    /** 
1626     * Returns Liberty-enabled client and proxy profile HTTP content type.
1627     * @return content type
1628     */
1629    public static String getLECPContentType(){
1630        return IFSConstants.LECP_CONTENT_TYPE_HEADER;
1631    }
1632
1633    /**
1634     * Returns the Discovery Service Resource Offerings nodes in an attribute
1635     * statement. After a single sign-on with an Identity Provider, a service
1636     * provider may get Discovery Service Resource Offerings through a SAML
1637     * assertion. This APIs helps in retrieving the resource offerings
1638     * if the user has been authenticated through the liberty SSO. It will
1639     * need to have a valid single sign on token (generated through the
1640     * liberty SSO).
1641     *
1642     * @param request <code>HttpServletRequest</code> associated with a user
1643     *        session.
1644     * @param providerID Hosted Provider's entity ID
1645     * @return <code>NodeList</code> Discovery Resource Offering Nodes,
1646     *  <code>null</code> if there is any failure  or if there is not one
1647     * @deprecated This method has been deprecated. Use
1648     *   {@link #getDiscoveryBootStrapResourceOfferings(
1649     *     HttpServletRequest request, String providerID, String providerRole)}
1650     */
1651    public static NodeList getDiscoveryBootStrapResourceOfferings(
1652       HttpServletRequest request, String providerID) 
1653    {
1654       if (request == null || providerID == null) {
1655          if (debug.messageEnabled()) {
1656             debug.message("LibertyManager.getDiscoveryResource" +
1657                 "Offering: null Input params");
1658          }
1659          return null;
1660       }
1661       try {
1662           Object token  = SessionManager.getProvider().getSession(request);
1663           FSSessionManager sessionManager = FSSessionManager.getInstance(
1664               getMetaAlias(
1665                   IFSConstants.ROOT_REALM, providerID, IFSConstants.SP));
1666           FSSession session = sessionManager.getSession(token);
1667           if (session == null) {
1668               if (FSUtils.debug.messageEnabled()) {
1669                   FSUtils.debug.message("LibertyManager.getDiscoveryResource" +
1670                       "Offerings: Theres no liberty session for this token"); 
1671               }
1672               return null;
1673           }
1674           return session.getBootStrapResourceOfferings();
1675       } catch(Exception ex) {
1676           FSUtils.debug.error("LibertyManager.getDiscoveryResourceOfferings"+
1677               " Exception while retrieving discovery boot strap info.", ex);
1678           return null;
1679       }
1680       
1681    }
1682    
1683    /**
1684     * Returns the Discovery Service Resource Offerings nodes in an attribute
1685     * statement. After a single sign-on with an Identity Provider, a service
1686     * provider may get Discovery Service Resource Offerings through a SAML
1687     * assertion. This APIs helps in retrieving the resource offerings
1688     * if the user has been authenticated through the liberty SSO. It will
1689     * need to have a valid single sign on token (generated through the
1690     * liberty SSO). The service provider should be under root realm.
1691     *
1692     * @param request <code>HttpServletRequest</code> associated with a user
1693     *  session.
1694     * @param providerID Hosted Provider's entity ID
1695     * @param providerRole Hosted Provider Role
1696     * @return <code>NodeList</code> Discovery Resource Offering Nodes,
1697     *  <code>null</code> if there is any failure  or if there is not one
1698     */
1699    public static NodeList getDiscoveryBootStrapResourceOfferings(
1700       HttpServletRequest request, String providerID, String providerRole) 
1701    {
1702       if (request == null || providerID == null) {
1703          if (debug.messageEnabled()) {
1704              debug.message("LibertyManager.getDiscoveryResource" +
1705                  "Offering: null Input params");
1706          }
1707          return null;
1708       }
1709       try {
1710           Object token  = SessionManager.getProvider().getSession(request);
1711           FSSessionManager sessionManager = FSSessionManager.getInstance(
1712               getMetaAlias(
1713                   IFSConstants.ROOT_REALM, providerID, IFSConstants.SP));
1714           FSSession session = sessionManager.getSession(token);
1715           if (session == null) {
1716               if (debug.messageEnabled()) {
1717                   debug.message("LibertyManager.getDiscoveryResource" +
1718                       "Offerings: Theres no liberty session for this token"); 
1719               }
1720               return null;
1721           }
1722           return session.getBootStrapResourceOfferings();
1723       } catch(Exception ex) {
1724           FSUtils.debug.error("LibertyManager.getDiscoveryResourceOfferings"+
1725               " Exception while retrieving discovery boot strap info.", ex);
1726           return null;
1727       }
1728    }
1729
1730    /**
1731     * Returns the Discovery Service Credentials in the Advice element.
1732     * After a single sign-on with an Identity Provider, a service
1733     * provider may get Discovery Service Resource Offerings and Credentials
1734     * through a SAML assertion. This APIs helps in retrieving the Credentials
1735     * if the user has been authenticated through the liberty SSO. It will
1736     * need to have a valid single sign on token (generated through the
1737     * liberty SSO). The service provider should be under root realm.
1738     *
1739     * @param request <code>HttpServletRequest</code> associated with a user
1740     *  session.
1741     * @param providerID Hosted Provider's entity ID
1742     * @return <code>List</code> of <code>SecurityAssertions</code>,
1743     *         null if there is any failure  or if there is not one
1744     * @deprecated This method has been deprecated. Use
1745     *   {@link #getDiscoveryBootStrapCredentials(
1746     *     HttpServletRequest request, String providerID, String providerRole)}
1747     */
1748    public static List getDiscoveryBootStrapCredentials(
1749       HttpServletRequest request, String providerID) 
1750    {
1751  
1752       if (request == null || providerID == null) {
1753           if (debug.messageEnabled()) {
1754               debug.message("LibertyManager.getDiscoveryCredentials:" +
1755                   " null Input params");
1756           }
1757           return null;
1758       }
1759       try {
1760           Object token  = SessionManager.getProvider().getSession(request);
1761           FSSessionManager sessionManager = FSSessionManager.getInstance(
1762               getMetaAlias(
1763                   IFSConstants.ROOT_REALM, providerID, IFSConstants.SP));
1764           FSSession session = sessionManager.getSession(token);
1765           if (session == null) {
1766               if (debug.messageEnabled()) {
1767                   debug.message("LibertyManager.getDiscoveryCredentials" 
1768                       + ": Theres no liberty session for this token"); 
1769               }
1770               return null;
1771           }
1772           return session.getBootStrapCredential();
1773       } catch(Exception ex) {
1774           FSUtils.debug.error("LibertyManager.getDiscoveryCredentials"+
1775               " Exception while retrieving discovery boot strap info.", ex);
1776           return null;
1777       }
1778       
1779    }
1780
1781    /**
1782     * Returns the Discovery Service Credentials in the Advice element.
1783     * After a single sign-on with an Identity Provider, a service
1784     * provider may get Discovery Service Resource Offerings and Credentials
1785     * through a SAML assertion. This APIs helps in retrieving the Credentials
1786     * if the user has been authenticated through the liberty SSO. It will
1787     * need to have a valid single sign on token (generated through the
1788     * liberty SSO). The service provider should be under root realm.
1789     *
1790     * @param request <code>HttpServletRequest</code> associated with a user
1791     *  session.
1792     * @param providerID Hosted Provider's entity ID
1793     * @param providerRole Hosted Provider Role
1794     * @return <code>List</code> of <code>SecurityAssertions</code>,
1795     *  <code>null</code> if there is any failure  or if there is not one
1796     */
1797    public static List getDiscoveryBootStrapCredentials(
1798       HttpServletRequest request, String providerID, String providerRole) 
1799    {
1800       if (request == null || providerID == null) {
1801           if (debug.messageEnabled()) {
1802               debug.message("LibertyManager.getDiscoveryCredentials:" +
1803                   " null Input params");
1804           }
1805           return null;
1806       }
1807       try {
1808           Object token  = SessionManager.getProvider().getSession(request);
1809           FSSessionManager sessionManager = FSSessionManager.getInstance(
1810               getMetaAlias(
1811                   IFSConstants.ROOT_REALM, providerID, IFSConstants.SP));
1812           FSSession session = sessionManager.getSession(token);
1813           if (session == null) {
1814               if (debug.messageEnabled()) {
1815                   debug.message("LibertyManager.getDiscoveryCredentials" 
1816                       + ": Theres no liberty session for this token"); 
1817               }
1818               return null;
1819           }
1820           return session.getBootStrapCredential();
1821       } catch(Exception ex) {
1822           FSUtils.debug.error("LibertyManager.getDiscoveryCredentials"+
1823               " Exception while retrieving discovery boot strap info.", ex);
1824           return null;
1825       }
1826       
1827    }
1828
1829
1830    /**
1831     * Returns the authentication context used in liberty single sign-on.
1832     * After single sign-on with an Identity Provider, a service
1833     * provider may obtain the authentication context used by the identity
1834     * provider that authenticates the user. It will need to have a valid
1835     * single sign on token (generated through the liberty SSO). The providers
1836     * are under root realm.
1837     *
1838     * @param request <code>HttpServletRequest</code> associated with a user
1839     *  session.
1840     * @param entityID Hosted Provider's entity ID 
1841     * @return authentication context string;
1842     *         <code>null</code> if there is any failure, or no liberty
1843     *         session is found.
1844     * @deprecated This method is deprecated.
1845     * @see #getAuthnContext(HttpServletRequest,String,String)
1846     */
1847    public static String getAuthnContext(
1848        HttpServletRequest request, String entityID) 
1849    {
1850        return getAuthnContext(request, IFSConstants.ROOT_REALM, entityID);
1851    }
1852
1853    /**
1854     * Returns the authentication context used in liberty single sign-on.
1855     * After single sign-on with an Identity Provider, a service
1856     * provider may obtain the authentication context used by the identity
1857     * provider that authenticates the user. It will need to have a valid
1858     * single sign on token (generated through the liberty SSO).
1859     *
1860     * @param request <code>HttpServletRequest</code> associated with a user
1861     *  session.
1862     * @param realm the realm in which the provider resides
1863     * @param entityID Hosted Provider's entity ID
1864     * @return authentication context string;
1865     *         <code>null</code> if there is any failure, or no liberty
1866     *         session is found.
1867     */
1868    public static String getAuthnContext(
1869       HttpServletRequest request, String realm, String entityID) 
1870    {
1871  
1872       if (request == null || entityID == null) {
1873           debug.message("LibertyManager.getAuthnContext: null Input params");
1874           return null;
1875       }
1876       try {
1877           Object token  = SessionManager.getProvider().getSession(request);
1878           FSSessionManager sessionManager = FSSessionManager.getInstance(
1879               getMetaAlias(realm, entityID, IFSConstants.SP));
1880           FSSession session = sessionManager.getSession(token);
1881           if (session == null) {
1882               if (debug.messageEnabled()) {
1883                   debug.message("LibertyManager.getAuthnContext" 
1884                       + ": There is no liberty session for this token"); 
1885               }
1886               return null;
1887           }
1888           return session.getAuthnContext();
1889       } catch(Exception ex) {
1890           FSUtils.debug.error("LibertyManager.getAuthnContext"+
1891               " Exception while retrieving authncontext.", ex);
1892           return null;
1893       }
1894    }
1895
1896    /**
1897     * Returns the federation information associated with current liberty 
1898     * session.
1899     * It will need to have a valid single sign on token (generated through 
1900     * the liberty SSO). It is for a service provider in a root realm.
1901     *
1902     * @param request <code>HttpServletRequest</code> associated with a user
1903     *  session.
1904     * @param entityID Hosted Provider's entity ID
1905     * @return <code>FSAccountFedInfo</code> associated with this session.
1906     *         <code>null</code> if there is any failure, or no liberty session
1907     *         is found.
1908     * @deprecated This method is deprecated.
1909     * @see #getAccountFedInfo(HttpServletRequest,String,String,String)
1910     */
1911    public static FSAccountFedInfo getAccountFedInfo(
1912        HttpServletRequest request, String entityID) 
1913    {
1914        return getAccountFedInfo(
1915            request, IFSConstants.ROOT_REALM, entityID, IFSConstants.SP);
1916    }
1917
1918    /**
1919     * Returns the federation information associated with current liberty 
1920     * session. 
1921     * It will need to have a valid single sign on token (generated through 
1922     * the liberty SSO).
1923     *
1924     * @param request <code>HttpServletRequest</code> associated with a user
1925     *  session.
1926     * @param realm the realm in which the provider resides
1927     * @param entityID Hosted Provider's entity ID
1928     * @param providerRole the role of the provider
1929     * @return <code>FSAccountFedInfo</code> associated with this session.
1930     *         <code>null</code> if there is any failure, or no liberty session
1931     *         is found.
1932     */
1933    public static FSAccountFedInfo getAccountFedInfo(
1934       HttpServletRequest request, String realm, String entityID, 
1935       String providerRole) 
1936    {
1937  
1938       if (request == null || entityID == null) {
1939           debug.message("LibertyManager.getAccountFedInfo: null Input params");
1940           return null;
1941       }
1942       try {
1943           Object token  = SessionManager.getProvider().getSession(request);
1944           FSSessionManager sessionManager = FSSessionManager.getInstance(
1945               getMetaAlias(realm, entityID, providerRole));
1946           FSSession session = sessionManager.getSession(token);
1947           if (session == null) {
1948               if (debug.messageEnabled()) {
1949                   debug.message("LibertyManager.getAccountFedInfo" 
1950                       + ": Theres no liberty session for this token"); 
1951               }
1952               return null;
1953           }
1954           return session.getAccountFedInfo();
1955       } catch(Exception ex) {
1956           FSUtils.debug.error("LibertyManager.getAccountFedInfo"+
1957               " Exception while retrieving federation info.", ex);
1958           return null;
1959       }
1960    }
1961
1962    /**
1963     * Returns <code>providerRole</code> from the <code>ProviderAlias</code>
1964     * using <code>meta Mgmt</code> calls.
1965     *
1966     * @param metaAlias The <code>metaAlias</code> of the provider
1967     * @return <code>providerRole</code> corresponding to the
1968     *  <code>metaAlias</code>.
1969     */
1970    public static String getProviderRole(String metaAlias) {
1971        try {
1972            if (metaManager == null) {
1973                return null;
1974            }
1975            return metaManager.getProviderRoleByMetaAlias(metaAlias);
1976        } catch (IDFFMetaException ame) {
1977            debug.error("LibertyManager: getProviderRole: Error getting " +
1978                "Provider Role", ame);
1979            return null;
1980        }
1981    }
1982
1983    /**
1984     * Returns <code>NameIdentifier</code> between the IDP and
1985     * the other SP for the same principal. This method should
1986     * be used by the code on the hosted SP, where the user
1987     * has logged in, and has an account linking with the IDP.
1988     * Futhermore, the same principal has an account linking
1989     * between his/her other (remote) SP account and the IDP
1990     * account.
1991     *
1992     * @param hostedSPMetaAlias The <code>metaAlias</code> of
1993     * the local service provider.
1994     * @param ssoToken The session token of the logged-
1995     * in user on the local service provider.
1996     * @param remoteSPEntityID The entity ID of the remote
1997     * service provider. In other words, it is the targeted
1998     * name space for the returned name identifier.
1999     * @return <code>NameIdentifier</code> of the same principal
2000     * but original established between the remote SP and
2001     * the IDP
2002     */
2003    public static NameIdentifier getMappedNameIdentifier(
2004        String hostedSPMetaAlias,
2005        Object ssoToken,
2006        String remoteSPEntityID) 
2007    {
2008
2009        String classMethod = "LibertyManager.getMappedNameIdentifier: ";
2010        
2011        String hostedEntityID = getEntityID(hostedSPMetaAlias);
2012        String realm = IDFFMetaUtils.getRealmByMetaAlias(hostedSPMetaAlias);
2013        
2014        if (debug.messageEnabled()) {
2015            debug.message(
2016                "NameMappingRequester: hostedEntityID="+
2017                hostedEntityID
2018            );
2019        }
2020
2021        SPDescriptorType hostedDescriptor = null;
2022        BaseConfigType hostedConfig = null;
2023        try {
2024            hostedDescriptor = metaManager.getSPDescriptor(
2025                realm, hostedEntityID);
2026            hostedConfig = metaManager.getSPDescriptorConfig(
2027                realm, hostedEntityID);
2028        } catch (IDFFMetaException ie) {
2029            debug.error(classMethod + "couldn't obtain hosted meta:", ie);
2030            return null;
2031        }
2032
2033        String userID = null;
2034        try {
2035            userID = SessionManager.getProvider().getPrincipalName(ssoToken);
2036        } catch (SessionException ssoe) {
2037            debug.error(
2038                "SessionException caught when trying to "+
2039                "get user DN from session token:", ssoe
2040            );
2041            return null;
2042        }
2043        if (debug.messageEnabled()) {
2044            debug.message(classMethod + "userID="+ userID);
2045        }
2046        FSNameMappingHandler handler = new FSNameMappingHandler(
2047            hostedEntityID, hostedDescriptor, hostedConfig, hostedSPMetaAlias);
2048        
2049        NameIdentifier ni = null;
2050        
2051        if (debug.messageEnabled()) {
2052            debug.message(
2053                classMethod +
2054                "targetNamespace (remoteSPEntityID)=" +
2055                remoteSPEntityID);
2056        }
2057        FSSessionManager sMgr =
2058            FSSessionManager.getInstance(hostedSPMetaAlias);
2059        FSSession sess = null;
2060        if (sMgr != null) {
2061            sess = sMgr.getSession(ssoToken);
2062        }
2063        FSSessionPartner partner = null;
2064        if (sess != null) {
2065            partner = sess.getCurrentSessionPartner();
2066        } else {
2067            debug.error(classMethod +"session is null");
2068            return null;
2069        }
2070        String remoteIDPEntityID = null;
2071        if (partner != null) {
2072            remoteIDPEntityID = partner.getPartner();
2073        }
2074        if (debug.messageEnabled()) {
2075            debug.message(
2076                classMethod + "Remote IDP EntityID = " +
2077                remoteIDPEntityID);
2078        }
2079        try {
2080            ni = handler.getNameIdentifier(
2081                userID,
2082                remoteIDPEntityID,
2083                true);
2084        } catch (Exception e) {
2085            debug.error(
2086                classMethod+
2087                "Exception caught when trying to get Name "+
2088                "Identifier between local SP and remote IDP: ",
2089                e);
2090            return null;
2091        }
2092        if (debug.messageEnabled()) {
2093            debug.message(
2094                classMethod +
2095                "Name Identifier between local SP and " +
2096                " remote IDP: " + ni.toString());
2097        }
2098        
2099        FSNameIdentifierMappingRequest mappingRequest = null;
2100        try {
2101            mappingRequest = new
2102                FSNameIdentifierMappingRequest(
2103                    hostedEntityID,
2104                    ni,
2105                    remoteSPEntityID);
2106        } catch (com.sun.identity.federation.message.common.FSMsgException fe) {
2107            debug.error(classMethod, fe);
2108            return null;
2109        }
2110        if (FSServiceUtils.isSigningOn()) {
2111            try {
2112                mappingRequest.signXML(
2113                    IDFFMetaUtils.getFirstAttributeValueFromConfig(
2114                        hostedConfig, IFSConstants.SIGNING_CERT_ALIAS));
2115            } catch (SAMLException se) {
2116                debug.error(classMethod, se);
2117                return null;
2118            }
2119        } 
2120        IDPDescriptorType remoteProviderDesc = null;
2121        try {
2122            remoteProviderDesc = metaManager.getIDPDescriptor(
2123                realm, remoteIDPEntityID);
2124        } catch (IDFFMetaException fme1) {
2125            debug.error(classMethod, fme1);
2126            return null;
2127        }            
2128        String remoteSOAPEndPoint = remoteProviderDesc.getSoapEndpoint();
2129        
2130        if (debug.messageEnabled()) {
2131            debug.message(
2132                classMethod +
2133                "IDP's soap end point=" +
2134                remoteSOAPEndPoint);
2135        }
2136        FSSOAPService soapService = FSSOAPService.getInstance();
2137        
2138        SOAPMessage returnMsg = null;
2139        try {
2140            SOAPMessage msg = 
2141                soapService.bind(mappingRequest.toXMLString(true, true));
2142            returnMsg =
2143                soapService.sendMessage(msg, remoteSOAPEndPoint);
2144        } catch (FSMsgException mex) {
2145            debug.error(classMethod, mex);
2146            return null; 
2147        } catch (java.io.IOException ioe) {
2148            debug.error(classMethod, ioe);
2149            return null;
2150        } catch (javax.xml.soap.SOAPException soape) {
2151            debug.error(classMethod, soape);
2152            return null;
2153        }            
2154        Element elt = soapService.parseSOAPMessage(returnMsg);
2155        FSNameIdentifierMappingResponse mappingResponse = null;
2156        try {
2157            mappingResponse =
2158                new FSNameIdentifierMappingResponse(elt);
2159        } catch (FSMsgException fme2) {
2160            debug.error(classMethod, fme2);
2161            return null;
2162        }                        
2163        if (debug.messageEnabled()) {
2164            String resStr = null;
2165            try {
2166                resStr = mappingResponse.toXMLString();
2167            } catch (FSMsgException fme3)
2168            {
2169                debug.error(classMethod, fme3);
2170                return null;
2171            }                        
2172            debug.message(
2173                classMethod +
2174                "NameIdentifierMappingResponse: " +
2175                resStr);
2176        }
2177        if (FSServiceUtils.isSigningOn()) {
2178            if (FSNameMappingHandler.
2179                verifyNameIdMappingResponseSignature(elt, returnMsg, realm)) {
2180                
2181                if (debug.messageEnabled()) {
2182                    debug.message(
2183                        classMethod +
2184                        "Success in verifying Name Identifier Mapping"+
2185                        " Response Signature");
2186                    }
2187            } else {
2188                debug.error(
2189                    classMethod +
2190                    "Failed verifying Name Identifier Mapping "+
2191                    "Response");
2192                return null;        
2193                }
2194        }
2195        return mappingResponse.getNameIdentifier();
2196    }
2197}