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: FSNameRegistrationRequest.java,v 1.4 2008/06/25 05:46:44 qcheng Exp $
026 *
027 * Portions Copyrighted 2014-2016 ForgeRock AS.
028 */
029
030package com.sun.identity.federation.message;
031
032import static org.forgerock.http.util.Uris.urlEncodeQueryParameterNameOrValue;
033import static org.forgerock.openam.utils.Time.*;
034
035import com.sun.identity.federation.common.FSUtils;
036import com.sun.identity.federation.common.IFSConstants;
037import com.sun.identity.federation.message.common.FSMsgException;
038import com.sun.identity.federation.message.common.IDPProvidedNameIdentifier;
039import com.sun.identity.federation.message.common.OldProvidedNameIdentifier;
040import com.sun.identity.federation.message.common.SPProvidedNameIdentifier;
041import com.sun.identity.saml.common.SAMLConstants;
042import com.sun.identity.saml.common.SAMLUtils;
043import com.sun.identity.saml.common.SAMLException;
044import com.sun.identity.saml.common.SAMLResponderException;
045import com.sun.identity.saml.protocol.AbstractRequest;
046import com.sun.identity.saml.xmlsig.XMLSignatureManager;
047import com.sun.identity.shared.DateUtils;
048import com.sun.identity.shared.encode.Base64;
049import com.sun.identity.shared.xml.XMLUtils;
050import java.util.ArrayList;
051import java.util.Collections;
052import java.util.Date;
053import java.util.Iterator;
054import java.util.List;
055import java.text.ParseException;
056import javax.servlet.http.HttpServletRequest;
057import org.w3c.dom.Element;
058import org.w3c.dom.Node;
059import org.w3c.dom.NodeList;
060import org.w3c.dom.Document;
061
062
063/**
064 * This class contains methods to create <code>NameRegistrationRequest</code>
065 * object.
066 *
067 * @supported.all.api
068 * @deprecated since 12.0.0
069 */
070@Deprecated
071
072public class FSNameRegistrationRequest extends AbstractRequest {
073    private String providerId;
074    private SPProvidedNameIdentifier spProvidedNameIdentifier;
075    private IDPProvidedNameIdentifier idpProvidedNameIdentifier;
076    private OldProvidedNameIdentifier oldProvidedNameIdentifier;
077    private String relayState = "";
078    protected String xmlString;
079    protected String signatureString;
080    protected String id;
081    protected int minorVersion = 0;
082
083    /** 
084     * Default Constructor.
085     */
086    
087    public FSNameRegistrationRequest() { 
088        setIssueInstant(newDate());
089    }
090        
091    /**
092     * Returns the value of <code>id</code> attribute.
093     *
094     * @return the value of <code>id</code> attribute.
095     * @see #setID(String)
096     */
097    public String getID(){
098        return id;
099    }
100    
101    /**
102     * Sets the value of <code>id</code> attribute.
103     *
104     * @param id the value of <code>id</code> attribute.
105     * @see #getID()
106     */
107    public void setID(String id){
108        this.id = id;
109    }
110    /**
111     * Returns the value of <code>RelayState</code> attribute.
112     *
113     * @return the value of <code>RelayState</code> attribute.
114     * @see #setRelayState(String)
115     */
116    
117    public String getRelayState(){
118        return relayState;
119    }
120    
121    /**
122     * Set the value of <code>RelayState</code> attribute.
123     *
124     * @param relayState the value of <code>RelayState</code> attribute.
125     * @see #getRelayState()
126     */
127    public void setRelayState(String relayState) {
128        this.relayState = relayState;
129    }
130
131   
132    /**
133     * Returns the signed <code>XML</code> string.
134     *
135     * @return the signed <code>XML</code> string.
136     */
137    public String getSignatureString(){
138        return signatureString;
139    }
140
141
142    /**
143     * Constructor creates the <code>FSNameRegistrationRequest</code>
144     * object.
145     *
146     * @param requestId the value of <code>RequestID</code> attribute.
147     * @param respondWiths the value of <code>RespondWiths</code> attribute.
148     * @param providerId the value of <code>ProviderID</code> attribute.
149     * @param spProvidedNameIdentifier the Service Provider 
150     *        <code>NameIdentifier</code>.
151     * @param idpProvidedNameIdentifier the Identity Provider 
152     *        <code>NameIdentifier</code>.
153     * @param oldProvidedNameIdentifier the Original Provider
154     *        <code>NameIdentifier</code>.
155     * @param relayState the value of <code>RelayState</code> attribute.
156     * @throws FSMsgException if there is an error creating this object.
157     */
158    public FSNameRegistrationRequest(
159        String requestId,
160        List respondWiths,
161        String providerId, 
162        SPProvidedNameIdentifier spProvidedNameIdentifier,
163        IDPProvidedNameIdentifier idpProvidedNameIdentifier,
164        OldProvidedNameIdentifier oldProvidedNameIdentifier,
165        String relayState) throws FSMsgException {
166     
167        int length = 0;
168        setIssueInstant(newDate());
169        if ((respondWiths != null) &&
170            (respondWiths != Collections.EMPTY_LIST)) {
171            length = respondWiths.size();
172            for (int i = 0; i < length; i++) {
173                Object temp = respondWiths.get(i);
174                if (!(temp instanceof String)) {
175                    if (FSUtils.debug.messageEnabled()) {
176                        FSUtils.debug.message("NameRegistrationRequest: "
177                            + "wrong input for RespondWith");
178                    }
179                    throw new FSMsgException("wrongInput", null);
180                }
181            }
182            this.respondWiths = respondWiths;
183        }
184     
185        if ((requestId != null) && (requestId.length() != 0)) {
186            requestID = requestId;
187        } else {
188            // random generate one
189            requestID = SAMLUtils.generateID();
190            if (requestID == null) {
191                FSUtils.debug.error("FSNameRegistrationRequest: "
192                    + "couldn't generate RequestID.");
193                throw new FSMsgException("errorGenerateID", null);
194            }
195        }
196        this.providerId=providerId;
197        this.spProvidedNameIdentifier=spProvidedNameIdentifier;
198        this.idpProvidedNameIdentifier=idpProvidedNameIdentifier;
199        this.oldProvidedNameIdentifier=oldProvidedNameIdentifier;
200        this.relayState = relayState;
201    }
202    
203    /**
204     * Constructor creates <code>FSNameRegistrationRequest</code>> object
205     * from a Document Element.
206     *
207     * @param root the Document Element.
208     * @throws FSMsgException if there is an error creating
209     *         this object.
210     */
211    public FSNameRegistrationRequest(Element root) throws FSMsgException {        
212        String tag = null;
213        if (root == null) {
214            FSUtils.debug.message(
215                "FSNameRegistrationRequest(Element): null input.");
216            throw new FSMsgException("nullInput",null);
217        }
218        if (((tag = root.getLocalName()) == null) ||
219        (!tag.equals("RegisterNameIdentifierRequest"))) {
220            FSUtils.debug.message(
221                "FSNameRegistrationRequest(Element): wrong input");
222            throw new FSMsgException("wrongInput",null);
223        }
224        
225        // Attribute IssueInstant
226        String instantString = root.getAttribute(IFSConstants.ISSUE_INSTANT);
227        if ((instantString == null) || (instantString.length() == 0)) {
228             FSUtils.debug.error("FSNameRegistrationRequest(Element):" +
229             "missing IssueInstant");
230             String[] args = { IFSConstants.ISSUE_INSTANT };
231             throw new FSMsgException("missingAttribute",args);
232        } else {
233             try {
234                 issueInstant = DateUtils.stringToDate(instantString);
235             } catch (ParseException e) {
236                 FSUtils.debug.error(
237                    "FSNameRegistrationRequest(Element): " +
238                    "could not parse IssueInstant" , e);
239                 throw new FSMsgException("wrongInput",null);
240             }
241        }
242        
243        int length = 0;
244        id = root.getAttribute("id");
245        requestID = root.getAttribute("RequestID");
246        parseMajorVersion(root.getAttribute("MajorVersion"));
247        parseMinorVersion(root.getAttribute("MinorVersion"));
248        NodeList contentnl = root.getChildNodes();
249        Node child;
250        String nodeName;
251        length = contentnl.getLength();
252        for (int i = 0; i < length; i++) {
253            child = contentnl.item(i);
254            if ((nodeName = child.getLocalName()) != null) {
255                if (nodeName.equals("RespondWith")) {
256                    if (respondWiths == Collections.EMPTY_LIST) {
257                        respondWiths = new ArrayList();
258                    }
259                    respondWiths.add(
260                    XMLUtils.getElementValue((Element) child));
261                } else if (nodeName.equals(IFSConstants.SIGNATURE)) {
262                } else if (nodeName.equals("ProviderID")) {
263                    if (providerId != null) {
264                        if (FSUtils.debug.messageEnabled()) {
265                            FSUtils.debug.message(
266                                "FSNameRegistrationRequest(Element): "
267                                + "should contain only one ProviderID.");
268                        }
269                        throw new FSMsgException("wrongInput",null);
270                    }
271                    providerId = XMLUtils.getElementValue((Element) child);
272                }  else if (nodeName.equals("SPProvidedNameIdentifier")) {
273                    spProvidedNameIdentifier = 
274                        new SPProvidedNameIdentifier((Element) child);
275                } else if (nodeName.equals("IDPProvidedNameIdentifier")) {
276                    idpProvidedNameIdentifier = 
277                        new IDPProvidedNameIdentifier((Element) child);
278                } else if (nodeName.equals("OldProvidedNameIdentifier")) {
279                    oldProvidedNameIdentifier = 
280                        new OldProvidedNameIdentifier((Element) child);
281                }else if (nodeName.equals("RelayState")) {
282                    relayState = XMLUtils.getElementValue((Element) child);
283                }else {
284                    if (FSUtils.debug.messageEnabled()) {
285                        FSUtils.debug.message(
286                            "FSNameRegistrationRequest(Element): "
287                            + "invalid node" + nodeName);
288                    }
289                    throw new FSMsgException("wrongInput",null);
290                }
291            }
292        }
293        List signs = XMLUtils.getElementsByTagNameNS1(root,
294                                        SAMLConstants.XMLSIG_NAMESPACE_URI,
295                                        SAMLConstants.XMLSIG_ELEMENT_NAME);
296        int signsSize = signs.size();
297        if (signsSize == 1) {
298            Element elem = (Element)signs.get(0);
299            setSignature(elem);
300            xmlString = XMLUtils.print(root);
301            signed = true;
302        } else if (signsSize != 0) {
303            FSUtils.debug.error("FSNameRegistrationRequest(Element): " +
304            "included more than one Signature element.");
305            throw new FSMsgException( "moreElement",null);
306        }        
307        //end check for signature
308    }
309    
310    /**
311     * Returns the <code>MinorVersion</code>.
312     *
313     * @return the <code>MinorVersion</code>.
314     * @see #setMinorVersion(int)
315     */
316    public int getMinorVersion() {
317       return minorVersion;
318    }
319    
320    /**
321     * Sets the <code>MinorVersion</code>.
322     *
323     * @param version the <code>MinorVersion</code>.
324     * @see #getMinorVersion()
325     */
326    public void setMinorVersion(int version) {
327       minorVersion = version;
328    }
329
330    public static FSNameRegistrationRequest parseXML(String xml)
331        throws FSMsgException {
332        Document doc = XMLUtils.toDOMDocument(xml, FSUtils.debug);
333        if (doc == null) {
334            FSUtils.debug.error("FSNameRegistrationRequest.parseXML:Error " +
335            "while parsing input xml string");
336            throw new FSMsgException("parseError",null);
337        }
338        Element root = doc.getDocumentElement();
339        return new FSNameRegistrationRequest(root);
340    }
341
342    /**
343     * Returns a String representation of the Logout Response.
344     *
345     * @return a string containing the valid XML for this element
346     * @throws FSMsgException if there is an error converting
347     *         this object ot a string.
348     */
349    public String toXMLString() throws FSMsgException {
350        return toXMLString(true, true);
351    }
352
353    /**
354     * Returns a String representation of the Logout Response.
355     *
356     * @param includeNS : Determines whether or not the namespace qualifier
357     *        is prepended to the Element when converted
358     * @param declareNS : Determines whether or not the namespace is declared
359     *        within the Element.
360     * @return a string containing the valid XML for this element
361     * @throws FSMsgException if there is an error converting
362     *         this object ot a string.
363     */
364    public String toXMLString(boolean includeNS, boolean declareNS)
365        throws FSMsgException {
366        return toXMLString(includeNS, declareNS, false);
367    }
368    
369    /**
370     * Returns a String representation of the Logout Response.
371     *
372     * @param includeNS Determines whether or not the namespace qualifier
373     *        is prepended to the Element when converted
374     * @param declareNS Determines whether or not the namespace is declared
375     *        within the Element.
376     * @param includeHeader Determines whether the output include the xml
377     *        declaration header.
378     * @return a string containing the valid XML for this element
379     * @throws FSMsgException if there is an error converting
380     *        this object ot a string.
381     */
382    public String toXMLString(boolean includeNS,boolean declareNS,
383        boolean includeHeader) throws FSMsgException {
384        if((providerId == null) || (providerId.length() == 0)){
385            FSUtils.debug.error("FSNameRegistrationRequest.toXMLString: "
386                + "providerId is null in the request with requestId:" 
387                + requestID);
388            String[] args = { requestID };
389            throw new FSMsgException("nullProviderIdWRequestId",args);
390        }
391        if ((requestID == null) || (requestID.length() == 0)){
392            requestID = SAMLUtils.generateID();
393            if (requestID == null) {
394                FSUtils.debug.error("FSNameRegistrationRequest.toXMLString: "
395                    + "couldn't generate RequestID.");
396                throw new FSMsgException("errorGenerateID",null);
397            }
398        }
399        
400        StringBuffer xml = new StringBuffer(1000);
401        if (includeHeader) {
402            xml.append("<?xml version=\"1.0\" encoding=\"").
403            append(IFSConstants.DEFAULT_ENCODING).append("\" ?>\n");
404        }
405        String prefix = "";
406        String uri = "";
407        String uriSAML = "";
408        if (includeNS) {
409            prefix = IFSConstants.LIB_PREFIX;
410        }
411        if (declareNS) {
412            if (minorVersion == IFSConstants.FF_12_PROTOCOL_MINOR_VERSION) {
413                uri = IFSConstants.LIB_12_NAMESPACE_STRING;
414            } else {
415                uri = IFSConstants.LIB_NAMESPACE_STRING;
416            }
417            uriSAML = IFSConstants.assertionDeclareStr;
418        }
419
420        String instantString = DateUtils.toUTCDateFormat(issueInstant);
421
422        if(requestID != null){
423           xml.append("<").append(prefix).
424           append("RegisterNameIdentifierRequest").
425           append(uri).append(uriSAML);
426           if (minorVersion == IFSConstants.FF_11_PROTOCOL_MINOR_VERSION && 
427              id != null && !(id.length() == 0)){
428              xml.append(" id=\"").append(id).append("\" ");
429           }
430           xml.append(" RequestID=\"").append(requestID).append("\" ").
431               append(" MajorVersion=\"").append(majorVersion).append("\" ").
432               append(" MinorVersion=\"").append(minorVersion).append("\" ").
433               append(" IssueInstant=\"").append(instantString).append("\"").
434               append(">");
435           if((respondWiths != null) && 
436               (respondWiths != Collections.EMPTY_LIST)) {
437                Iterator i = respondWiths.iterator();
438                while (i.hasNext()) {
439                    xml.append("<").append(prefix).append("RespondWith>").
440                    append((String) i.next()).append("</").append(prefix).
441                    append("RespondWith>");
442                }
443            }
444            if (signed) {
445                if (signatureString != null) {
446                    xml.append(signatureString);
447                } else if (signature != null) {
448                    signatureString = XMLUtils.print(signature);
449                    xml.append(signatureString);
450                }
451            }
452            
453            xml.append("<").append(prefix).append("ProviderID").append(">").
454            append(providerId).
455            append("</").append(prefix).append("ProviderID").append(">");
456            if(idpProvidedNameIdentifier != null && 
457               idpProvidedNameIdentifier.getName().length() != 0) {
458               xml.append(idpProvidedNameIdentifier.toXMLString());            
459            }
460            if(spProvidedNameIdentifier != null && 
461               spProvidedNameIdentifier.getName().length() != 0) {
462               xml.append(spProvidedNameIdentifier.toXMLString());
463            }
464            if(oldProvidedNameIdentifier != null && 
465               oldProvidedNameIdentifier.getName().length() != 0) {
466                xml.append(oldProvidedNameIdentifier.toXMLString());
467            }
468            if(relayState != null) {
469               xml.append("<").append(prefix).append("RelayState").append(">").
470                   append(relayState).append("</").append(prefix).
471                   append("RelayState").append(">");
472            }
473            xml.append("</").append(prefix).
474                append("RegisterNameIdentifierRequest>");
475        } else {
476            FSUtils.debug.error("FSNameRegistrationRequest.toString: " +
477            "requestID is null ");
478            throw new FSMsgException("nullRequestID",null);
479        }
480        
481        return xml.toString();
482    }
483
484    /**
485     * Returns the Identity Provider's <code>NameIdentifier</code>.
486     *
487     * @return the Identity Provider's <code>NameIdentifier</code>.
488     */
489    public IDPProvidedNameIdentifier getIDPProvidedNameIdentifier() {
490        return idpProvidedNameIdentifier;
491    }
492    
493    /**
494     * Returns the original <code>NameIdentifier</code>.
495     *
496     * @return the original <code>NameIdentifier</code>.
497     */
498    public OldProvidedNameIdentifier getOldProvidedNameIdentifier() {
499        return oldProvidedNameIdentifier;
500    }
501    
502    /**
503     * Returns the value of <code>ProviderID</code> attribute.
504     *
505     * @return the value of <code>ProviderID</code> attribute.
506     * @see #setProviderId(String).
507     */
508    public String getProviderId() {
509        return this.providerId;
510    }
511
512    /**
513     * Sets the Identity Provider's <code>NameIdentifier</code>.
514     *
515     * @param nameIdentifier the Identity Provider's
516     *        <code>NameIdentifier</code>.
517     * @see #getIDPProvidedNameIdentifier
518     */
519    public void setIDPProvidedNameIdentifier(
520        IDPProvidedNameIdentifier nameIdentifier) {
521        idpProvidedNameIdentifier=nameIdentifier;
522    }
523    
524    /**
525     * Sets the original <code>NameIdentifier</code>.
526     *
527     * @param nameIdentifier the original provider's
528     *        <code>NameIdentifier</code>.
529     * @see #getOldProvidedNameIdentifier
530     */
531    
532    public void setOldProvidedNameIdentifier(
533        OldProvidedNameIdentifier nameIdentifier) {
534        oldProvidedNameIdentifier=nameIdentifier;
535    }
536    /**
537     * Sets the Service Provider's <code>NameIdentifier</code>.
538     *
539     * @param nameIdentifier the Identity Provider's
540     *        <code>NameIdentifier</code>.
541     * @see #getSPProvidedNameIdentifier
542     */
543    public void setSPProvidedNameIdentifier(
544            SPProvidedNameIdentifier nameIdentifier) {
545        spProvidedNameIdentifier=nameIdentifier;
546    }
547
548    /**
549     * Sets the value of <code>ProviderID</code> attribute.
550     *
551     * @param providerId the value of <code>ProviderID</code> attribute.
552     */
553    public void setProviderId(String providerId) {
554        this.providerId = providerId;
555    }
556
557    /**
558     * Returns the <code>NameIdentifier</code> provided by
559     * the Service Provider.
560     *
561     * @return the <code>NameIdentifier</code> provided by
562     *         the Service Provider.
563     * @see #setSPProvidedNameIdentifier(SPProvidedNameIdentifier)
564     */
565    public SPProvidedNameIdentifier getSPProvidedNameIdentifier() {
566        return spProvidedNameIdentifier;
567    }
568
569    /**
570     * Returns a Base64 Encoded String.
571     *
572     * @return a Base64 Encoded String.
573     * @throws FSMsgException if there is an error encoding the string.
574     */
575    public String toBASE64EncodedString() throws FSMsgException {
576        if ((providerId == null) || (providerId.length() == 0)) {
577            FSUtils.debug.error(
578                "FSNameRegistrationRequest.toBASE64EncodedString: "
579                + "providerId is null in the request with requestId:" 
580                + requestID);
581            String[] args = { requestID };
582            throw new FSMsgException("nullProviderIdWRequestId",args);
583        }
584        if ((requestID == null) || (requestID.length() == 0)){
585            requestID = SAMLUtils.generateID();
586            if (requestID == null) {
587                FSUtils.debug.error(
588                    "FSNameRegistrationRequest.toBASE64EncodedString: "
589                    + "couldn't generate RequestID.");
590                throw new FSMsgException("errorGenerateID",null);
591            }
592        }
593        return Base64.encode(this.toXMLString().getBytes());        
594    }
595    
596    /**
597     * Sets the <code>MajorVersion</code> by parsing the version string.
598     *
599     * @param majorVer a String representing the <code>MajorVersion</code> to
600     *        be set.
601     * @throws FSMsgException on error.
602     */
603    private void parseMajorVersion(String majorVer) throws FSMsgException {
604        try {
605            majorVersion = Integer.parseInt(majorVer);
606        } catch (NumberFormatException e) {
607            if (FSUtils.debug.messageEnabled()) {
608                FSUtils.debug.message("FSNameRegistrationRequest(Element): "
609                    + "invalid MajorVersion", e);
610            }
611            throw new FSMsgException("wrongInput",null);
612        }
613        
614        if (majorVersion != SAMLConstants.PROTOCOL_MAJOR_VERSION) {
615            if (majorVersion > SAMLConstants.PROTOCOL_MAJOR_VERSION) {
616                if (FSUtils.debug.messageEnabled()) {
617                    FSUtils.debug.message("FSNameRegistrationRequest(Element): "
618                        + "MajorVersion of the RegisterNameIdentifierRequest"
619                        + "is too high.");
620                }
621                throw new FSMsgException("requestVersionTooHigh",null);
622            } else {
623                if (FSUtils.debug.messageEnabled()) {
624                    FSUtils.debug.message("FSNameRegistrationRequest(Element): "
625                        + "MajorVersion of the RegisterNameIdentifierRequest"
626                        + "is too low.");
627                }
628                throw new FSMsgException("requestVersionTooLow",null);
629            }
630        }
631    }
632    
633    /**
634     * Sets the <code>MinorVersion</code> by parsing the version string.
635     *
636     * @param minorVer a String representing the <code>MinorVersion</code> to
637     *        be set.
638     * @throws SAMLException when the version mismatchs.
639     */
640    private void parseMinorVersion(String minorVer) throws FSMsgException {
641        try {
642            minorVersion = Integer.parseInt(minorVer);
643        } catch (NumberFormatException e) {
644            if (FSUtils.debug.messageEnabled()) {
645                FSUtils.debug.message(
646                "FSNameRegis(Element): "
647                + "invalid MinorVersion", e);
648            }
649            throw new FSMsgException("wrongInput",null);
650        }
651
652        if (minorVersion > IFSConstants.FF_12_PROTOCOL_MINOR_VERSION) {
653            FSUtils.debug.error("FSNameRegisNot(Element):MinorVersion of"
654            + " the Response is too high.");
655            throw new FSMsgException("responseVersionTooHigh",null);
656        } else if (minorVersion < IFSConstants.FF_11_PROTOCOL_MINOR_VERSION) {
657            FSUtils.debug.error("FSNameRegis(Element):MinorVersion of"
658            + " the Response is too low.");
659            throw new FSMsgException("responseVersionTooLow",null);
660        }
661    }
662
663
664    public void signXML() {
665
666    }
667    /**
668     * Signs the <code>FSNameRegistrationRequest</code> object.
669     *
670     * @param certAlias the Certificate Alias.
671     * @throws SAMLException if this object cannot be signed.
672     */
673    public void signXML(String certAlias) throws SAMLException {
674        FSUtils.debug.message("FSNameRegistrationRequest.signXML: Called");
675        if (signed) {
676            if (FSUtils.debug.messageEnabled()) {
677                FSUtils.debug.message("FSNameRegistrationRequest.signXML: "
678                    + "the assertion is already signed.");
679            }
680            throw new SAMLResponderException(FSUtils.BUNDLE_NAME,
681                                             "alreadySigned",null);
682        }
683        if (certAlias == null || certAlias.length() == 0) {
684            throw new SAMLResponderException(FSUtils.BUNDLE_NAME,
685                "cannotFindCertAlias",null);
686        }
687        try{
688            XMLSignatureManager manager = XMLSignatureManager.getInstance();
689            if (minorVersion == IFSConstants.FF_11_PROTOCOL_MINOR_VERSION) {
690                     signatureString = manager.signXML(
691                                         this.toXMLString(true, true), 
692                                         certAlias,null,IFSConstants.ID, 
693                                         this.id, false);
694            } else if (minorVersion == 
695                                   IFSConstants.FF_12_PROTOCOL_MINOR_VERSION) {
696                    signatureString = manager.signXML(
697                                         this.toXMLString(true, true), 
698                                         certAlias,null,IFSConstants.REQUEST_ID, 
699                                         this.getRequestID(), false);
700            } else { 
701                    if (FSUtils.debug.messageEnabled()) { 
702                        FSUtils.debug.message("invalid minor version.");                 
703                    }
704            }
705                 
706            signature = 
707                XMLUtils.toDOMDocument(signatureString, FSUtils.debug)
708                        .getDocumentElement();
709            signed = true;
710            xmlString = this.toXMLString(true, true);      
711        } catch(Exception e){
712            throw new SAMLResponderException(
713                                  FSUtils.BUNDLE_NAME,"signFailed",null);
714        }
715    }
716
717    /**
718     * Sets the Signature.
719     *
720     * @param elem the Document Element.
721     * @return true if success otherwise false.
722     */
723    public boolean setSignature(Element elem) {
724        signatureString = XMLUtils.print(elem); 
725        return super.setSignature(elem); 
726    } 
727        
728    /**
729     * Returns an URL Encoded String.
730     *
731     * @return a url encoded query string.
732     * @throws FSMsgException if there is an error.
733     */
734    public String toURLEncodedQueryString() throws FSMsgException {
735        if((providerId == null) || (providerId.length() == 0)) {
736            FSUtils.debug.error("FSNameRegistrationRequest." +
737            "toURLEncodedQueryString: providerId is null in the request " +
738            "with requestId: " + requestID);
739            throw new FSMsgException("nullProviderID",null);
740         }
741         if((requestID == null) || (requestID.length() == 0)){
742             requestID = SAMLUtils.generateID();
743             if(requestID == null) {
744                 FSUtils.debug.error("FSNameRegistrationRequest." +
745                       "toURLEncodedQueryString: couldn't generate RequestID.");
746                 throw new FSMsgException("errorGenerateID",null);
747             }
748         }
749         StringBuffer urlEncodedAuthnReq = new StringBuffer(300);
750         urlEncodedAuthnReq.append("RequestID=").
751                 append(urlEncodeQueryParameterNameOrValue(requestID)).
752                 append(IFSConstants.AMPERSAND);
753         urlEncodedAuthnReq.append("MajorVersion=").
754                 append(majorVersion).
755                 append(IFSConstants.AMPERSAND);
756         urlEncodedAuthnReq.append("MinorVersion=").
757                 append(minorVersion).
758                 append(IFSConstants.AMPERSAND);
759         urlEncodedAuthnReq.append("RelayState=").
760                 append(urlEncodeQueryParameterNameOrValue(relayState)).
761                 append(IFSConstants.AMPERSAND);
762         
763         if (issueInstant != null){
764             urlEncodedAuthnReq.append("IssueInstant=")
765                               .append(urlEncodeQueryParameterNameOrValue(
766                                      DateUtils.toUTCDateFormat(issueInstant)))
767                               .append(IFSConstants.AMPERSAND);
768         } else {
769             FSUtils.debug.error("FSNameRegistrationRequest."
770                     + "toURLEncodedQueryString: issueInstant missing");
771             String[] args = { IFSConstants.ISSUE_INSTANT };
772             throw new FSMsgException("missingAttribute",args);
773         }
774         if (providerId != null && providerId.length() > 0) {
775             urlEncodedAuthnReq.append("ProviderID=").
776                     append(urlEncodeQueryParameterNameOrValue(providerId)).
777                     append(IFSConstants.AMPERSAND);
778         }
779    
780         if(spProvidedNameIdentifier != null) {
781             if (spProvidedNameIdentifier.getName() != null &&
782                     spProvidedNameIdentifier.getName().length() != 0) {
783                 urlEncodedAuthnReq.append("SPProvidedNameIdentifier=").
784                         append(urlEncodeQueryParameterNameOrValue(
785                         spProvidedNameIdentifier.getName())).
786                         append(IFSConstants.AMPERSAND);
787             }
788
789             if(spProvidedNameIdentifier.getNameQualifier() != null &&
790                    spProvidedNameIdentifier.getNameQualifier().length() != 0) {
791                 urlEncodedAuthnReq.append("SPNameQualifier=").
792                         append(urlEncodeQueryParameterNameOrValue(
793                         spProvidedNameIdentifier.getNameQualifier())).
794                         append(IFSConstants.AMPERSAND);
795             }
796              if (spProvidedNameIdentifier.getFormat() != null && 
797                 spProvidedNameIdentifier.getFormat().length() != 0) {
798                 urlEncodedAuthnReq.append("SPNameFormat=").
799                                    append(urlEncodeQueryParameterNameOrValue(
800                                         spProvidedNameIdentifier.getFormat())).
801                                    append(IFSConstants.AMPERSAND); 
802              }
803         } 
804
805         if (oldProvidedNameIdentifier != null) {
806            if (oldProvidedNameIdentifier.getName() != null && 
807               oldProvidedNameIdentifier.getName().length() != 0) {
808               urlEncodedAuthnReq.append("OldProvidedNameIdentifier=").
809                                  append(urlEncodeQueryParameterNameOrValue(
810                                      oldProvidedNameIdentifier.getName())).
811                                  append(IFSConstants.AMPERSAND);
812            }
813            if (oldProvidedNameIdentifier.getNameQualifier() != null && 
814                oldProvidedNameIdentifier.getNameQualifier().length() != 0) { 
815                urlEncodedAuthnReq.append("OldNameQualifier=").
816                                   append(urlEncodeQueryParameterNameOrValue(
817                                 oldProvidedNameIdentifier.getNameQualifier())).
818                                   append(IFSConstants.AMPERSAND);  
819            }
820            if (oldProvidedNameIdentifier.getFormat() != null&& 
821                         oldProvidedNameIdentifier.getFormat().length() != 0) {
822                urlEncodedAuthnReq.append("OldNameFormat=").
823                                   append(urlEncodeQueryParameterNameOrValue(
824                                        oldProvidedNameIdentifier.getFormat())).
825                                   append(IFSConstants.AMPERSAND); 
826            }
827         } 
828
829         if (idpProvidedNameIdentifier != null) {
830            if (idpProvidedNameIdentifier.getName() != null && 
831                idpProvidedNameIdentifier.getName().length() != 0){
832                urlEncodedAuthnReq.append("IDPProvidedNameIdentifier=").
833                                   append(urlEncodeQueryParameterNameOrValue(
834                                         idpProvidedNameIdentifier.getName())).
835                                   append(IFSConstants.AMPERSAND);
836            }
837            if (idpProvidedNameIdentifier.getNameQualifier() != null && 
838                idpProvidedNameIdentifier.getNameQualifier().length() != 0) {
839                urlEncodedAuthnReq.append("IDPNameQualifier=").
840                                   append(urlEncodeQueryParameterNameOrValue(
841                                idpProvidedNameIdentifier.getNameQualifier())).
842                                   append(IFSConstants.AMPERSAND);  
843            }
844            if(idpProvidedNameIdentifier.getFormat() != null&& 
845                idpProvidedNameIdentifier.getFormat().length() != 0) {
846                urlEncodedAuthnReq.append("IDPNameFormat=").
847                                   append(urlEncodeQueryParameterNameOrValue(
848                                        idpProvidedNameIdentifier.getFormat())).
849                                   append(IFSConstants.AMPERSAND); 
850            }
851         } 
852         return urlEncodedAuthnReq.toString();   
853   }
854   
855    /**
856     * Returns <code>FSNameRegistrationRequest</code> object. The
857     * object is creating by parsing the <code>HttpServletRequest</code>
858     * object.
859     *
860     * @param request the <code>HttpServletRequest</code> object.
861     * @throws FSMsgException if there is an error
862     *         creating this object.
863     * @throws SAMLException if there is an error.
864     */
865    public static FSNameRegistrationRequest parseURLEncodedRequest(
866            HttpServletRequest request) throws FSMsgException, SAMLException {
867        FSNameRegistrationRequest retNameRegistrationRequest =
868                new FSNameRegistrationRequest();
869        try {
870            FSUtils.debug.message("checking minor version");
871            retNameRegistrationRequest.majorVersion =
872                    Integer.parseInt(request.getParameter("MajorVersion"));
873            retNameRegistrationRequest.minorVersion =
874                    Integer.parseInt(request.getParameter("MinorVersion"));
875        } catch(NumberFormatException ex){
876            FSUtils.debug.error("FSNameRegistrationRequest.parseURLEncoded" +
877                    "Request: Invalid versions", ex);
878            throw new FSMsgException("invalidNumber",null);
879        }
880        FSUtils.debug.message("checking RequestID");
881        if(request.getParameter("RequestID")!= null) {
882            retNameRegistrationRequest.requestID =
883                    request.getParameter("RequestID");
884        } else {
885            FSUtils.debug.error("FSNameRegistrationRequest.parseURLEncoded" +
886                    "Request: RequestID not found");
887            String[] args = { IFSConstants.REQUEST_ID };
888            throw new FSMsgException("missingAttribute",args);
889        }
890        FSUtils.debug.message("checking instantString");
891        String instantString = request.getParameter("IssueInstant");
892        FSUtils.debug.message("instantString : " + instantString);
893        if(instantString == null ||
894                instantString.length() == 0) {
895            FSUtils.debug.error("FSNameRegistrationRequest.parseURLEncoded" +
896                    "Request: IssueInstant not found");
897            String[] args = { IFSConstants.ISSUE_INSTANT };
898            throw new FSMsgException("missingAttribute",args);
899        }
900        try{
901            FSUtils.debug.message(
902                    "calling : DateUtils.stringToDate.issueInstant");
903            retNameRegistrationRequest.issueInstant =
904                    DateUtils.stringToDate(instantString);
905        } catch (ParseException e){
906            FSUtils.debug.error("FSNameRegistrationRequest.parseURLEncoded" +
907                    "Request: Can not parse IssueInstant", e);
908            throw new FSMsgException("parseError",null);
909        }
910        
911        if(request.getParameter("ProviderID")!= null){
912            retNameRegistrationRequest.providerId =
913                    request.getParameter("ProviderID");
914        } else {
915            FSUtils.debug.error("FSNameRegistrationRequest.parseURLEncoded" +
916                    "Request: Can not find ProviderID");
917            throw new FSMsgException("missingElement",null);
918        }
919        FSUtils.debug.message("start identifier processing");
920        String spNameFormat = "";
921        String spNameQualifier = "";
922        String spName = "";
923        
924        if(request.getParameter("SPNameFormat") != null) {
925            spNameFormat = request.getParameter("SPNameFormat");
926        }
927        
928        if(request.getParameter("SPNameQualifier") != null) {
929            spNameQualifier = request.getParameter("SPNameQualifier");
930        }
931        
932        if(request.getParameter("SPProvidedNameIdentifier") != null) {
933            spName = request.getParameter("SPProvidedNameIdentifier");
934        }
935        if(spName != null &&  !(spName.length() < 1)) {
936            retNameRegistrationRequest.setSPProvidedNameIdentifier(
937                new SPProvidedNameIdentifier(spName, spNameQualifier, 
938                                             spNameFormat));
939        }
940        
941        String idpNameFormat = null;
942        String idpNameQualifier = null;
943        String idpName = null;
944        
945        if (request.getParameter("IDPNameFormat") != null) {
946            idpNameFormat = request.getParameter("IDPNameFormat");
947        }
948        
949        if (request.getParameter("IDPNameQualifier") != null) {
950            idpNameQualifier = request.getParameter("IDPNameQualifier");
951        }
952        
953        if (request.getParameter("IDPProvidedNameIdentifier") != null) {
954            idpName = request.getParameter("IDPProvidedNameIdentifier");
955        }
956        if (idpName != null && !(idpName.length() < 1)) {
957            retNameRegistrationRequest.idpProvidedNameIdentifier =
958                    new IDPProvidedNameIdentifier(idpName, idpNameQualifier,
959                    idpNameFormat);
960        }
961        
962        String oldNameFormat = null;
963        String oldNameQualifier = null;
964        String oldName = null;
965        
966        if (request.getParameter("OldNameFormat") != null) {
967            oldNameFormat = request.getParameter("OldNameFormat");
968        }
969        
970        if (request.getParameter("OldNameQualifier") != null) {
971            oldNameQualifier = request.getParameter("OldNameQualifier");
972        }
973        
974        if (request.getParameter("OldProvidedNameIdentifier") != null) {
975            oldName = request.getParameter("OldProvidedNameIdentifier");
976        }
977        
978        if (oldName != null && !(oldName.length() < 1)) {
979            retNameRegistrationRequest.oldProvidedNameIdentifier =
980                    new OldProvidedNameIdentifier(oldName, oldNameQualifier,
981                    oldNameFormat);
982        }
983        
984        if(request.getParameter("RelayState") != null) {
985            retNameRegistrationRequest.relayState =
986                    request.getParameter("RelayState");
987        }
988        return retNameRegistrationRequest;
989    }
990}