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