Example usage for org.w3c.dom Element toString

List of usage examples for org.w3c.dom Element toString

Introduction

In this page you can find the example usage for org.w3c.dom Element toString.

Prototype

public String toString() 

Source Link

Document

Returns a string representation of the object.

Usage

From source file:es.bsc.servicess.ide.ProjectMetadata.java

/** Check if Orchestration Element class comes from external package
 * @return Sting with the FQDN of the orchestration class
 *///  ww w.ja v a 2s  .  c o m
public Map<String, OrchestrationElement> getOrchestrationElementFormExternalClass(IType orchClass) {

    String oeClass = orchClass.getFullyQualifiedName();
    NodeList orch_classes = projectElement.getElementsByTagName(ORCH_CLASS_TAG);
    if (orch_classes != null) {
        for (int i = 0; i < orch_classes.getLength(); i++) {
            Element oec = (Element) (orch_classes.item(i));
            if (oeClass.equals(oec.getAttribute(CLASS_ATTR))) {
                HashMap<String, OrchestrationElement> els = new HashMap<String, OrchestrationElement>();
                NodeList elements = oec.getElementsByTagName(ELEMENT_TAG);
                if (elements != null && elements.getLength() > 0) {

                    for (int j = 0; j < elements.getLength(); j++) {

                        Element oe = (Element) (elements.item(j));
                        try {
                            String label = oe.getAttribute(LABEL_ATTR);
                            String return_type = oe.getAttribute(RETURN_TYPE_ATTR);
                            int modifier = Integer.parseInt(oe.getAttribute(MODIFIER_ATTR));
                            OrchestrationElement orchElement = OrchestrationElement.extractElement(label,
                                    modifier, return_type, orchClass);
                            orchElement.setConstraints(getConstraintsFromElement(oe));
                            els.put(label, orchElement);
                        } catch (Exception e) {
                            log.error("Error loading element (" + oe.toString() + ").", e);
                        }

                    }
                    return els;
                } else {
                    log.warn("No elements for orchestration class " + oeClass);
                    return new HashMap<String, OrchestrationElement>();
                }
            }
        }
        log.warn("No orchestration classes called " + oeClass);
        return new HashMap<String, OrchestrationElement>();

    } else {
        log.warn("No orchestration classes found");
        return new HashMap<String, OrchestrationElement>();
    }
}

From source file:eu.optimis.sm.gui.server.ServiceManagerWebServiceImpl.java

public ArrayList<Service> availableServices(String sess_id, boolean test) {
    logger.info("availableServices: sess_id = " + sess_id);

    ArrayList<Service> services = new ArrayList<Service>();
    String res = checkSession(sess_id);
    if (res != null) {
        logger.info("Wrong session...");
        services.add(new Service());
        services.get(services.size() - 1).set("service_number", "-100");
        services.get(services.size() - 1).set("service_id", res);
        return services;
    }//from   www.  j  a  v  a2s.  co  m

    PropertyConfigurator.configure(ConfigManager.getFilePath(ConfigManager.LOG4J_CONFIG_FILE));
    configServiceManagerWeb = ConfigManager.getPropertiesConfiguration(ConfigManager.SMWEB_CONFIG_FILE);

    String port, host;
    String output3 = null;

    /*
    sla0 = "<agreement_endpoint><xml-fragment> <wsa:Address xmlns:wsa=\"http://www.w3.org/2005/08/addressing\">" +
    "http://optimis-ipvm2.ds.cs.umu.se:8080/optimis-sla/services/Agreement</wsa:Address>" +
    "<wsa:ReferenceParameters xmlns:wsa=\"http://www.w3.org/2005/08/addressing\">" +
    "<ResourceId xmlns=\"http://schemas.scai.fraunhofer.de/wsag4j\">WSAG4J_ResourceId-8</ResourceId>" +
    "</wsa:ReferenceParameters><Metadata xmlns=\"http://www.w3.org/2005/08/addressing\">" +
    "<ServerIdentity xmlns=\"http://schemas.scai.fraunhofer.de/2008/11/wsag4j/engine\">" +
    "OU=WSAG4J Development,O=wsag4j.sf.net,1.2.840.113549.1.9.1=#16147365727665724077736167346a2e73662e6e6574," +
    "C=DE,ST=NRW,CN=WSAG4J Server</ServerIdentity> </Metadata> </xml-fragment></agreement_endpoint>";
            
    NO_VM_SERVICE_XML = "<service xmlns=\"http://www.optimis.eu/service-manager\">"
    + "<service_id>" + serId + "</service_id>" + "<status>pending</status>"
    + "<infrastructure-provider>" + "<id>" + id0 + "</id>"
     + "<ip_address>" + ip0 + "</ip_address>" + "<sla_id>" + sla0 + "</sla_id>"
     + "<agreement_endpoint>" + agr0 + "</agreement_endpoint>"
    + "</infrastructure-provider>" + "</service>";
    */
    host = SM_URL; //host = "optimis-spvm2.ds.cs.umu.se";
    port = SM_PORT;

    ServiceManagerClient smClient = new ServiceManagerClient(host, port);

    String ser = "ser:";
    logger.info("------------------------------");
    logger.info("output #3 (host = " + host + ")");
    output3 = smClient.getServices();
    logger.info(output3);
    Document doc = XmlUtil.getDocument(output3);
    NodeList nList = doc.getElementsByTagName(ser + "service");
    List<ServiceProvider> listSP = null;
    List<ServiceProviderVM> listSPVM = null;
    logger.info("number of services = " + nList.getLength());
    ArrayList<Object> returnedArray = new ArrayList<Object>();

    if (nList.getLength() == 0) {
        logger.info("No services found!");
        services.add(new Service());
        services.get(services.size() - 1).set("service_number", "-100");
        services.get(services.size() - 1).set("service_id", "No services found!");
        returnedArray.add(0, services);
        return services;
    }

    for (Integer temp = 0; temp < nList.getLength(); temp++) {
        Node nNode = nList.item(temp);
        if (nNode.getNodeType() == Node.ELEMENT_NODE) {
            Element eElement = (Element) nNode;
            services.add(new Service());
            String servID;
            services.get(services.size() - 1).set("service_number", temp.toString());
            services.get(services.size() - 1).set("service_id", getTagValue(ser + "service_id", eElement));
            services.get(services.size() - 1).set("service_status", getTagValue(ser + "status", eElement));
            services.get(services.size() - 1).set("manifest_id", getTagValue(ser + "manifest_id", eElement));
            services.get(services.size() - 1).set("listServiceProvider", null);
            servID = getTagValue(ser + "service_id", eElement);

            NodeList nList2 = nNode.getChildNodes();
            listSP = new ArrayList<ServiceProvider>();
            for (int temp2 = 0; temp2 < nList2.getLength(); temp2++) {
                Node nNode2 = nList2.item(temp2);
                if (nNode2.getNodeType() == Node.ELEMENT_NODE) {
                    Element eElement2 = (Element) (nNode2);
                    if (getTagValue(ser + "id", eElement2) != null) {
                        listSP.add(new ServiceProvider());
                        String dm;
                        String getCPD = "<br><b>Data Manager client info</b>" + " (for "
                                + getTagValue(ser + "id", eElement2) + ")<br>";
                        DataManagerClient dmClient = new DataManagerClient();
                        try {
                            dm = dmClient.getCPD(getTagValue(ser + "id", eElement2));
                            //getCPD = getCPD + "  (dmClient.dmClient.getCPD(): success!)<br>";

                            //-----------------------------------------------------------------------------------------------------------
                            /**/
                            Document docDM = XmlUtil.getDocument(dm);
                            NodeList nListDM = docDM.getElementsByTagName("tns:IaaSProvider");
                            for (Integer t = 0; t < nListDM.getLength(); t++) {
                                Node nNodeDM = nListDM.item(t);
                                if (nNodeDM.getNodeType() == Node.ELEMENT_NODE) {
                                    getCPD = getCPD + "<b>"
                                            + nNodeDM.getNodeName().subSequence(
                                                    Math.min(nNodeDM.getNodeName().length(), 4),
                                                    nNodeDM.getNodeName().length())
                                            + "</b>:<br>";
                                    NodeList nListDM2 = nNodeDM.getChildNodes();
                                    for (int tt = 0; tt < nListDM2.getLength(); tt++) {
                                        Node nNodeDM2 = nListDM2.item(tt);
                                        if (nNodeDM2.getNodeType() == Node.ELEMENT_NODE) {
                                            NodeList nListDM3 = nNodeDM2.getChildNodes();
                                            if (nListDM3.getLength() <= 1) {
                                                if (nNodeDM2.getNodeName() != null)
                                                    getCPD = getCPD + "-"
                                                            + nNodeDM2.getNodeName().subSequence(Math
                                                                    .min(nNodeDM2.getNodeName().length(), 4),
                                                                    nNodeDM2.getNodeName().length())
                                                            + ": ";
                                                if (nNodeDM2.getTextContent() != null)
                                                    getCPD = getCPD + "" + nNodeDM2.getTextContent() + "<br>";
                                            }
                                            for (int ttt = 0; ttt < nListDM3.getLength(); ttt++) {
                                                Node nNodeDM3 = nListDM3.item(ttt);
                                                if (nNodeDM3.getNodeType() == Node.ELEMENT_NODE) {
                                                    NodeList nListDM4 = nNodeDM3.getChildNodes();
                                                    if (nListDM4.getLength() <= 1) {
                                                        if (nNodeDM3.getNodeName() != null)
                                                            getCPD = getCPD + "---"
                                                                    + nNodeDM3.getNodeName().subSequence(
                                                                            Math.min(nNodeDM3.getNodeName()
                                                                                    .length(), 4),
                                                                            nNodeDM3.getNodeName().length())
                                                                    + ": ";
                                                        if (nNodeDM3.getTextContent() != null)
                                                            getCPD = getCPD + "" + nNodeDM3.getTextContent()
                                                                    + "<br>";
                                                    }
                                                    for (int tttt = 0; tttt < nListDM4.getLength(); tttt++) {
                                                        Node nNodeDM4 = nListDM4.item(tttt);
                                                        if (nNodeDM4.getNodeType() == Node.ELEMENT_NODE) {
                                                            NodeList nListDM5 = nNodeDM4.getChildNodes();
                                                            if (nListDM5.getLength() <= 1) {
                                                                if (nNodeDM4.getNodeName() != null)
                                                                    getCPD = getCPD + "------" + nNodeDM4
                                                                            .getNodeName()
                                                                            .subSequence(Math.min(nNodeDM4
                                                                                    .getNodeName().length(), 4),
                                                                                    nNodeDM4.getNodeName()
                                                                                            .length())
                                                                            + ": ";
                                                                if (nNodeDM4.getTextContent() != null)
                                                                    getCPD = getCPD + ""
                                                                            + nNodeDM4.getTextContent()
                                                                            + "<br>";
                                                            }
                                                            for (int ttttt = 0; ttttt < nListDM5
                                                                    .getLength(); ttttt++) {
                                                                Node nNodeDM5 = nListDM5.item(ttttt);
                                                                if (nNodeDM5
                                                                        .getNodeType() == Node.ELEMENT_NODE) {
                                                                    if (nNodeDM5.getNodeName() != null)
                                                                        getCPD = getCPD + "------------"
                                                                                + nNodeDM5.getNodeName()
                                                                                        .subSequence(Math.min(
                                                                                                nNodeDM5.getNodeName()
                                                                                                        .length(),
                                                                                                4),
                                                                                                nNodeDM5.getNodeName()
                                                                                                        .length())
                                                                                + ": ";
                                                                    if (nNodeDM5.getTextContent() != null)
                                                                        getCPD = getCPD + ""
                                                                                + nNodeDM5.getTextContent()
                                                                                + "<br>";
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            /**/
                            //-----------------------------------------------------------------------------------------------------------
                        } catch (Exception e1) {
                            getCPD = getCPD + "  dmClient.dmClient.getCPD() error: " + e1.getMessage() + "...";
                            e1.printStackTrace();
                            logger.info(e1.getMessage());
                        }
                        String str5 = "<style> label {position: relative;} .box {position: absolute;"
                                + "left: 0; top: 100%; z-index: 100; -webkit-backface-visibility: hidden;"
                                + "-moz-border-radius:    0px; -webkit-border-radius: 0px;"
                                + "border-radius:         0px; -moz-background-clip:    padding;"
                                + "-webkit-background-clip: padding-box; background-clip:         padding-box;"
                                + "width: 20px; padding: 0px; margin: 0px 0; opacity: 0; }"
                                + ".box:after {content: \"\";   position: absolute; bottom: 100%;"
                                + "left: 0px; border-bottom: 0px solid #eee;"
                                + "border-left:   0px solid transparent; border-right:  14px solid transparent;"
                                + "width:  20px;    height: 0; } .popUpControl:checked ~ label > .box {"
                                + "opacity: 1; } .popUpControl { display: none;  }"
                                + ".link { color: blue; text-decoration: underline; width: 20px; }" + ".title"
                                + temp + temp2 + getTagValue(ser + "id", eElement2)
                                + "1 { display: block; margin: -10px 0px 0px -75px; color: black; width: 350px; "
                                + " font: 14px Sans-Serif; text-decoration: none; background-color:#FFFFFF; }"
                                + ".copy { color: black; text-decoration: none; background-color:#FFFFFF; width: 20px; }"
                                + "</style> <div id=\"page-wrap\"> <p>" + "<input type=\"checkbox\" id=\"linkie"
                                + temp + temp2 + getTagValue(ser + "id", eElement2)
                                + "\" class=\"popUpControl\">" + "<label for=\"linkie" + temp + temp2
                                + getTagValue(ser + "id", eElement2) + "\" class=\"link\">"
                                + "<span>DM client info</span> <span class=\"box\">" + "<span class=\"title"
                                + temp + temp2 + getTagValue(ser + "id", eElement2) + "1\">" + getCPD
                                + "</span>" + "</span> </label> </p> </div>";

                        getCPD = str5;
                        logger.info(getCPD);

                        listSP.get(listSP.size() - 1).set("provider_id", getTagValue(ser + "id", eElement2)
                                + "<br><u><a href=\"" + TREC_URL + "?side=sp&providerId="
                                + getTagValue(ser + "id", eElement2) + "&stage=operation" + "&identifier="
                                + servID + "&level=service" + "\" target=\"_blank\">Link: TREC GUI (for "
                                + getTagValue(ser + "id", eElement2) + " operation)</a>"
                                + "</u><br><u><a href=\"" + TREC_URL + "?side=sp&providerId="
                                + getTagValue(ser + "id", eElement2) + "&stage=deployment" + "&identifier="
                                + servID + "&level=service" + "\" target=\"_blank\">Link: TREC GUI (for "
                                + getTagValue(ser + "id", eElement2) + " deployment history)</a>" + "</u>");
                        listSP.get(listSP.size() - 1).set("provider_ip",
                                getTagValue(ser + "ip_address", eElement2));
                        listSP.get(listSP.size() - 1).set("provider_sla",
                                getTagValue(ser + "sla_id", eElement2));

                        String slaInfo = "<br><b>SLA Details</b>" + " (for "
                                + getTagValue(ser + "id", eElement2) + ")<br>";
                        SLAClient slaClient = new SLAClient();

                        try {
                            AgreementClient ac = slaClient
                                    .getSLA(getTagValue(ser + "agreement_endpoint", eElement2));

                            Document docSLA = XmlUtil.getDocument(ac.getTerms().xmlText());

                            NodeList nListSLA2 = docSLA.getElementsByTagName("opt:DataProtectionSection");
                            for (Integer t = 0; t < nListSLA2.getLength(); t++) {
                                Node nNodeSLA2 = nListSLA2.item(t);
                                if (nNodeSLA2.getNodeType() == Node.ELEMENT_NODE) {
                                    slaInfo = slaInfo + "----------Data Protection Section<br>";

                                    NodeList nListSLA22 = nNodeSLA2.getChildNodes();
                                    for (int tt = 0; tt < nListSLA22.getLength(); tt++) {
                                        Node nNode22 = nListSLA22.item(tt);
                                        if (nNode22.getNodeType() == Node.ELEMENT_NODE) {

                                            if (nNode22.getNodeName().equalsIgnoreCase("opt:SCC")) {
                                                slaInfo = slaInfo + "----------SCC terms<br>";
                                                NodeList nListSLA33 = nNode22.getChildNodes();
                                                for (int ttt = 0; ttt < nListSLA33.getLength(); ttt++) {
                                                    Node nNode33 = nListSLA33.item(ttt);
                                                    if (nNode33.getNodeType() == Node.ELEMENT_NODE) {
                                                        Element e33 = (Element) nNode33;
                                                        if (getTagValue("Title", e33) != null)
                                                            slaInfo = slaInfo + "----------"
                                                                    + getTagValue("Title", e33) + ": ";
                                                        if (getTagValue("Description", e33) != null)
                                                            slaInfo = slaInfo + getTagValue("Description", e33)
                                                                    + "<br>";

                                                        NodeList nListSLA44 = e33.getElementsByTagName("Item");
                                                        for (int tttt = 0; tttt < nListSLA44
                                                                .getLength(); tttt++) {
                                                            Node nNode44 = nListSLA44.item(tttt);
                                                            if (nNode44.getNodeType() == Node.ELEMENT_NODE) {
                                                                if (nNode44.getTextContent() != null)
                                                                    slaInfo = slaInfo + "---"
                                                                            + nNode44.getTextContent() + "<br>";
                                                            }
                                                        }
                                                    }
                                                }
                                            }

                                            if (nNode22.getNodeName().equalsIgnoreCase("opt:BCR")) {
                                                if (nNode22.getNodeName() != null)
                                                    slaInfo = slaInfo + "----------BCR terms<br>";
                                                NodeList nListSLA33 = nNode22.getChildNodes();
                                                for (int ttt = 0; ttt < nListSLA33.getLength(); ttt++) {
                                                    Node nNode33 = nListSLA33.item(ttt);
                                                    if (nNode33.getNodeType() == Node.ELEMENT_NODE) {
                                                        Element e33 = (Element) nNode33;
                                                        if (getTagValue("Title", e33) != null)
                                                            slaInfo = slaInfo + "----------"
                                                                    + getTagValue("Title", e33) + ": ";
                                                        if (getTagValue("Description", e33) != null)
                                                            slaInfo = slaInfo + getTagValue("Description", e33)
                                                                    + "<br>";
                                                        NodeList nListSLA44 = e33.getElementsByTagName("Item");
                                                        for (int tttt = 0; tttt < nListSLA44
                                                                .getLength(); tttt++) {
                                                            Node nNode44 = nListSLA44.item(tttt);
                                                            if (nNode44.getNodeType() == Node.ELEMENT_NODE) {
                                                                if (nNode44.getTextContent() != null)
                                                                    slaInfo = slaInfo + "---"
                                                                            + nNode44.getTextContent() + "<br>";
                                                            }
                                                        }
                                                    }
                                                }
                                            }

                                            if (nNode22.getNodeName().equalsIgnoreCase("opt:IPR")) {
                                                slaInfo = slaInfo + "----------IPR terms<br>";
                                                NodeList nListSLA33 = nNode22.getChildNodes();
                                                for (int ttt = 0; ttt < nListSLA33.getLength(); ttt++) {
                                                    Node nNode33 = nListSLA33.item(ttt);
                                                    if (nNode33.getNodeType() == Node.ELEMENT_NODE) {
                                                        Element e33 = (Element) nNode33;
                                                        if (getTagValue("opt:Title", e33) != null)
                                                            slaInfo = slaInfo + "----------"
                                                                    + getTagValue("opt:Title", e33) + ": ";
                                                        if (getTagValue("opt:Description", e33) != null)
                                                            slaInfo = slaInfo
                                                                    + getTagValue("opt:Description", e33)
                                                                    + "<br>";
                                                        NodeList nListSLA44 = e33
                                                                .getElementsByTagName("opt:Item");
                                                        for (int tttt = 0; tttt < nListSLA44
                                                                .getLength(); tttt++) {
                                                            Node nNode44 = nListSLA44.item(tttt);
                                                            if (nNode44.getNodeType() == Node.ELEMENT_NODE) {
                                                                if (nNode44.getTextContent() != null)
                                                                    slaInfo = slaInfo + "---"
                                                                            + nNode44.getTextContent() + "<br>";
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            //-----------------------------------------------------------------------------------------------------------
                        } catch (Exception e) {
                            slaInfo = slaInfo + "  slaClient.getSLA() error: " + e.getMessage() + "...";
                            e.printStackTrace();
                            logger.info(e.getMessage());
                        }
                        String str5a = "<style> label {position: relative;} .box {position: absolute;"
                                + "left: 0; top: 100%; z-index: 100; -webkit-backface-visibility: hidden;"
                                + "-moz-border-radius: 0px; -webkit-border-radius: 0px;"
                                + "border-radius: 0px; -moz-background-clip: padding;"
                                + "-webkit-background-clip: padding-box; background-clip: padding-box;"
                                + "width: 20px; padding: 0px; margin: 0px 0; opacity: 0; }"
                                + ".box:after {content: \"\";   position: absolute; bottom: 100%;"
                                + "left: 0px; border-bottom: 0px solid #eee;"
                                + "border-left:   0px solid transparent; border-right:  14px solid transparent;"
                                + "width:  20px; height: 0; } .popUpControl:checked ~ label > .box {"
                                + "opacity: 1; } .popUpControl { display: none;  }"
                                + ".link { color: blue; text-decoration: underline; width: 20px; }" + ".title"
                                + temp + temp2 + getTagValue(ser + "id", eElement2)
                                + " { display: block; margin: -10px 0px 0px -100px; color: black; width: 450px; "
                                + " font: 14px Sans-Serif; text-decoration: none; background-color:#FFFFFF; }"
                                + ".copy { color: black; text-decoration: none; background-color:#FFFFFF; width: 20px; }"
                                + "</style> <div id=\"page-wrap\"> <p>" + "<input type=\"checkbox\" id=\"linkie"
                                + temp + temp2 + getTagValue(ser + "id", eElement2)
                                + "2\" class=\"popUpControl\">" + "<label for=\"linkie" + temp + temp2
                                + getTagValue(ser + "id", eElement2) + "2\" class=\"link\">"
                                + "<span>SLA info</span> <span class=\"box\">" + "<span class=\"title" + temp
                                + temp2 + getTagValue(ser + "id", eElement2) + "\">" + slaInfo + "</span>"
                                + "</span> </label> </p> </div>";

                        slaInfo = str5a;

                        String agrEndp;
                        agrEndp = getTagValue(ser + "agreement_endpoint", eElement2);

                        agrEndp = "<style> label {position: relative;} .box {position: absolute;"
                                + "left: 0; top: 100%; z-index: 100; -webkit-backface-visibility: hidden;"
                                + "-moz-border-radius: 0px; -webkit-border-radius: 0px;"
                                + "border-radius: 0px; -moz-background-clip: padding;"
                                + "-webkit-background-clip: padding-box; background-clip: padding-box;"
                                + "width: 20px; padding: 0px; margin: 0px 0; opacity: 0; }"
                                + ".box:after {content: \"\";   position: absolute; bottom: 100%;"
                                + "left: 0px; border-bottom: 0px solid #eee;"
                                + "border-left:   0px solid transparent; border-right:  14px solid transparent;"
                                + "width:  20px; height: 0; } .popUpControl:checked ~ label > .box {"
                                + "opacity: 1; } .popUpControl { display: none;  }"
                                + ".link { color: blue; text-decoration: underline; width: 20px; }" + ".titlex"
                                + temp + temp2 + getTagValue(ser + "id", eElement2)
                                + " { display: block; margin: -10px 0px 0px -100px; color: black; width: 450px; "
                                + " font: 14px Sans-Serif; text-decoration: none; background-color:#FFFFFF; }"
                                + ".copy { color: black; text-decoration: none; background-color:#FFFFFF; width: 20px; }"
                                + "</style> <div id=\"page-wrap\"> <p>"
                                + "<input type=\"checkbox\" id=\"linkiex" + temp + temp2
                                + getTagValue(ser + "id", eElement2) + "2\" class=\"popUpControl\">"
                                + "<label for=\"linkiex" + temp + temp2 + getTagValue(ser + "id", eElement2)
                                + "2\" class=\"link\">" + "<span>Agreement Endpoint</span> <span class=\"box\">"
                                + "<span class=\"titlex" + temp + temp2 + getTagValue(ser + "id", eElement2)
                                + "\">" + agrEndp + "</span>" + "</span> </label> </p> </div>";

                        listSP.get(listSP.size() - 1).set("provider_agreement_endpoint", agrEndp);
                        listSP.get(listSP.size() - 1).set("provider_initial_trust_value",
                                getTagValue(ser + "initial_trust_value", eElement2));
                        listSP.get(listSP.size() - 1).set("provider_initial_risk_value",
                                getTagValue(ser + "initial_risk_value", eElement2));
                        listSP.get(listSP.size() - 1).set("provider_initial_eco_value",
                                getTagValue(ser + "initial_eco_value", eElement2));
                        listSP.get(listSP.size() - 1).set("provider_initial_cost_value",
                                getTagValue(ser + "initial_cost_value", eElement2));
                        listSP.get(listSP.size() - 1).set("data_manager_info", getCPD);
                        listSP.get(listSP.size() - 1).set("sla_details", slaInfo);
                    }
                    NodeList nList3a = nNode2.getChildNodes();
                    for (int temp3a = 0; temp3a < nList3a.getLength(); temp3a++) {
                        Node nNode3a = nList3a.item(temp3a);
                        if (nNode3a.getNodeType() == Node.ELEMENT_NODE) {
                            Element eElement3a = (Element) (nNode3a);
                            NodeList nList3 = eElement3a.getElementsByTagName(ser + "vm");
                            listSPVM = new ArrayList<ServiceProviderVM>();
                            for (int temp3 = 0; temp3 < nList3.getLength(); temp3++) {
                                Node nNode3 = nList3.item(temp3);
                                if (nNode3.getNodeType() == Node.ELEMENT_NODE) {
                                    Element eElement3 = (Element) (nNode3);
                                    if (getTagValue(ser + "id", eElement3) != null) {
                                        listSPVM.add(new ServiceProviderVM());
                                        listSPVM.get(listSPVM.size() - 1).set("vm_id",
                                                getTagValue(ser + "id", eElement3));
                                        listSPVM.get(listSPVM.size() - 1).set("vm_type",
                                                getTagValue(ser + "type", eElement3));
                                        listSPVM.get(listSPVM.size() - 1).set("vm_status",
                                                getTagValue(ser + "status", eElement3));
                                        listSPVM.get(listSPVM.size() - 1).set("vm_deployment_duration_in_ms",
                                                getTagValue(ser + "deployment_duration_in_ms", eElement3));
                                    } else
                                        logger.info("eElement3error====" + eElement3.toString());
                                }
                                if (listSPVM != null) {
                                    String vms = new String();
                                    for (int rr = 0; rr < listSPVM.size(); rr++)
                                        vms = vms + listSPVM.get(rr).toString();
                                    listSP.get(listSP.size() - 1).set("listServiceProviderVMStr", vms);
                                }
                            }
                        }
                    }
                }
            }
            String providers = new String();
            for (int tt = 0; tt < listSP.size(); tt++)
                providers = providers + listSP.get(tt).toString();
            services.get(services.size() - 1).set("listServiceProviderStr", providers);
        }
    }
    returnedArray.add(0, services);
    return services;
}

From source file:com.amalto.workbench.providers.datamodel.util.SchemaItemLabelCreator.java

protected String getLableForElement(Element element) {
    try {//  w w w  .j  a  v a  2 s. c  o  m
        if (element.getLocalName().equals("documentation")) {//$NON-NLS-1$
            return "Documentation: " + element.getChildNodes().item(0).getNodeValue();//$NON-NLS-1$
        } else if (element.getLocalName().equals("appinfo")) {//$NON-NLS-1$
            String source = element.getAttribute("source");//$NON-NLS-1$
            if (source != null) {
                if (source.startsWith("X_Label_")) {//$NON-NLS-1$
                    return Util.iso2lang.get(source.substring(8).toLowerCase()) + " Label: "//$NON-NLS-1$
                            + element.getChildNodes().item(0).getNodeValue();
                } else if (source.equals("X_ForeignKey")) {//$NON-NLS-1$
                    return "Foreign Key:  " + element.getChildNodes().item(0).getNodeValue();//$NON-NLS-1$
                } else if (source.equals("X_ForeignKeyInfo")) {//$NON-NLS-1$
                    return "Foreign Key Info:  " + element.getChildNodes().item(0).getNodeValue();//$NON-NLS-1$
                } else if (source.equals("X_SourceSystem")) {//$NON-NLS-1$
                    return "Source System:  " + element.getChildNodes().item(0).getNodeValue();//$NON-NLS-1$
                } else if (source.equals("X_TargetSystem")) {//$NON-NLS-1$
                    return "Target System(s):  " + element.getChildNodes().item(0).getNodeValue();//$NON-NLS-1$
                } else if (source.startsWith("X_Description_")) {//$NON-NLS-1$
                    return Util.iso2lang.get(source.substring(14).toLowerCase()) + " Description: "//$NON-NLS-1$
                            + element.getChildNodes().item(0).getNodeValue();
                } else if (source.equals("X_Write")) {//$NON-NLS-1$
                    return "Writable By : " + element.getChildNodes().item(0).getNodeValue();//$NON-NLS-1$
                } else if (source.equals("X_Lookup_Field")) {//$NON-NLS-1$
                    return "Look Field : " + element.getChildNodes().item(0).getNodeValue();//$NON-NLS-1$
                } else if (source.equals("X_Workflow")) {//$NON-NLS-1$
                    return "Workflow access : " + element.getChildNodes().item(0).getNodeValue();//$NON-NLS-1$
                } else if (source.equals("X_Hide")) {//$NON-NLS-1$
                    return "No Access to : " + element.getChildNodes().item(0).getNodeValue();//$NON-NLS-1$

                } else if (source.startsWith("X_Facet")) {//$NON-NLS-1$
                    return source.substring(2, 7) + "_Msg_" + source.substring(8) + ": "//$NON-NLS-1$//$NON-NLS-2$
                            + element.getChildNodes().item(0).getNodeValue();

                } else if (source.startsWith("X_Display_Format_")) {//$NON-NLS-1$
                    return source + ": " + element.getChildNodes().item(0).getNodeValue();//$NON-NLS-1$
                } else if (source.equals("X_Schematron")) {//$NON-NLS-1$

                    String pattern = (String) element.getFirstChild().getUserData("pattern_name");//$NON-NLS-1$
                    if (pattern == null) {
                        Element el = Util.parse(element.getChildNodes().item(0).getNodeValue())
                                .getDocumentElement();
                        if (el.getAttributes().getNamedItem("name") != null)//$NON-NLS-1$
                            pattern = el.getAttributes().getNamedItem("name").getTextContent();//$NON-NLS-1$
                    }
                    return "Validation Rule: " + (pattern == null ? "" : pattern);//$NON-NLS-1$//$NON-NLS-2$
                } else if (source.equals("X_Retrieve_FKinfos")) {//$NON-NLS-1$
                    return "Foreign Key resolution:  " + element.getChildNodes().item(0).getNodeValue();//$NON-NLS-1$
                } else if (source.equals("X_FKIntegrity")) {//$NON-NLS-1$
                    return "Foreign Key integrity:  " + element.getChildNodes().item(0).getNodeValue(); //$NON-NLS-1$
                } else if (source.equals("X_FKIntegrity_Override")) {//$NON-NLS-1$
                    return "Foreign Key integrity override:  " + element.getChildNodes().item(0).getNodeValue(); //$NON-NLS-1$
                }
                if (source.equals("X_ForeignKey_Filter")) {//$NON-NLS-1$
                    return "Foreign Key Filter:  " + element.getChildNodes().item(0).getNodeValue();//$NON-NLS-1$
                } else {
                    return source + ": " + Util.nodeToString(element);//$NON-NLS-1$
                }
            } else {
                return Util.nodeToString(element);
            }
        } else {
            return Util.nodeToString(element);
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }

    return "?? " + element.getClass().getName() + " : " + element.toString();//$NON-NLS-1$//$NON-NLS-2$
}

From source file:org.apache.ode.bpel.engine.PartnerLinkMyRoleImpl.java

@SuppressWarnings("unchecked")
private CorrelationKey computeCorrelationKey(OScope.CorrelationSet cset, OMessageVarType messagetype,
        Element msg, Map<String, Node> headerParts) {
    CorrelationKey key = null;//from w w w .  j a  va2  s. c om

    String[] values = new String[cset.properties.size()];

    int jIdx = 0;
    for (Iterator j = cset.properties.iterator(); j.hasNext(); ++jIdx) {
        OProcess.OProperty property = (OProcess.OProperty) j.next();
        OProcess.OPropertyAlias alias = property.getAlias(messagetype);

        if (alias == null) {
            // TODO: Throw a real exception! And catch this at compile
            // time.
            throw new IllegalArgumentException("No alias matching property '" + property.name
                    + "' with message type '" + messagetype + "'");
        }

        String value;
        try {
            value = _process.extractProperty(msg, headerParts, alias, msg.toString());
        } catch (FaultException fe) {
            String emsg = __msgs.msgPropertyAliasDerefFailedOnMessage(alias.getDescription(), fe.getMessage());
            __log.error(emsg, fe);
            throw new InvalidMessageException(emsg, fe);
        }
        values[jIdx] = value;
    }

    if (cset.hasJoinUseCases) {
        key = new OptionalCorrelationKey(cset.name, values);
    } else {
        key = new CorrelationKey(cset.name, values);
    }

    return key;
}

From source file:org.apache.rahas.impl.SAML2TokenIssuer.java

/**
 * This method is used to create the subject of an assertion
 * @param config//from w ww . j a v  a2 s. c  o m
 * @param doc
 * @param crypto
 * @param creationTime
 * @param expirationTime
 * @param data
 * @return Subject
 * @throws Exception
 */
private Subject createSubjectWithHolderOfKeySC(SAMLTokenIssuerConfig config, Document doc, Crypto crypto,
        DateTime creationTime, DateTime expirationTime, RahasData data) throws Exception {

    XMLObjectBuilderFactory builderFactory = Configuration.getBuilderFactory();
    SAMLObjectBuilder<Subject> subjectBuilder = (SAMLObjectBuilder<Subject>) builderFactory
            .getBuilder(Subject.DEFAULT_ELEMENT_NAME);
    Subject subject = subjectBuilder.buildObject();
    Element keyInfoElem = null;

    // If it is a Symmetric Key
    if (data.getKeyType().endsWith(RahasConstants.KEY_TYPE_SYMM_KEY)) {

        isSymmetricKeyBasedHoK = true;
        Element encryptedKeyElem;
        X509Certificate serviceCert = null;
        try {
            if (data.getPrincipal() != null) {
                //get subject's name from Rahas data
                String subjectNameID = data.getPrincipal().getName();
                //Create NameID and attach it to the subject
                NameID nameID = new NameIDBuilder().buildObject();
                nameID.setValue(subjectNameID);
                nameID.setFormat(NameIdentifier.EMAIL);
                subject.setNameID(nameID);
            }
            // Get ApliesTo to figure out which service to issue the token
            // for
            serviceCert = config.getServiceCert(crypto, data.getAppliesToAddress());

            // Create the encrypted key
            WSSecEncryptedKey encrKeyBuilder = new WSSecEncryptedKey();

            // Use thumbprint id
            encrKeyBuilder.setKeyIdentifierType(WSConstants.THUMBPRINT_IDENTIFIER);

            // SEt the encryption cert
            encrKeyBuilder.setUseThisCert(serviceCert);

            // set keysize
            int keysize = data.getKeysize();
            keysize = (keysize != -1) ? keysize : config.keySize;
            encrKeyBuilder.setKeySize(keysize);

            encrKeyBuilder
                    .setEphemeralKey(TokenIssuerUtil.getSharedSecret(data, config.keyComputation, keysize));

            // Set key encryption algo
            encrKeyBuilder.setKeyEncAlgo(EncryptionConstants.ALGO_ID_KEYTRANSPORT_RSA15);

            // Build
            encrKeyBuilder.prepare(doc, crypto);

            // Extract the base64 encoded secret value
            byte[] tempKey = new byte[keysize / 8];
            System.arraycopy(encrKeyBuilder.getEphemeralKey(), 0, tempKey, 0, keysize / 8);

            data.setEphmeralKey(tempKey);

            // Extract the Encryptedkey DOM element
            encryptedKeyElem = encrKeyBuilder.getEncryptedKeyElement();
        } catch (WSSecurityException e) {
            throw new TrustException("errorInBuildingTheEncryptedKeyForPrincipal",
                    new String[] { serviceCert.getSubjectDN().getName() }, e);
        }

        keyInfoElem = doc.createElementNS(WSConstants.SIG_NS, "ds:KeyInfo");
        ((OMElement) encryptedKeyElem).declareNamespace(WSConstants.SIG_NS, WSConstants.SIG_PREFIX);
        ((OMElement) encryptedKeyElem).declareNamespace(WSConstants.ENC_NS, WSConstants.ENC_PREFIX);

        keyInfoElem.appendChild(encryptedKeyElem);

    }

    // If it is a public Key
    else if (data.getKeyType().endsWith(RahasConstants.KEY_TYPE_PUBLIC_KEY)) {
        try {
            String subjectNameId = data.getPrincipal().getName();

            //Create NameID and attach it to the subject
            NameIDBuilder nb = new NameIDBuilder();
            NameID nameID = nb.buildObject();
            nameID.setValue(subjectNameId);
            nameID.setFormat(NameIdentifier.EMAIL);
            subject.setNameID(nameID);

            // Create the ds:KeyValue element with the ds:X509Data
            X509Certificate clientCert = data.getClientCert();

            if (clientCert == null) {
                X509Certificate[] certs = crypto.getCertificates(data.getPrincipal().getName());
                clientCert = certs[0];
            }

            byte[] clientCertBytes = clientCert.getEncoded();

            String base64Cert = Base64.encode(clientCertBytes);

            Text base64CertText = doc.createTextNode(base64Cert);

            //-----------------------------------------

            Element x509CertElem = doc.createElementNS(WSConstants.SIG_NS, "ds:X509Certificate");
            x509CertElem.appendChild(base64CertText);
            Element x509DataElem = doc.createElementNS(WSConstants.SIG_NS, "ds:X509Data");
            x509DataElem.appendChild(x509CertElem);

            if (x509DataElem != null) {
                keyInfoElem = doc.createElementNS(WSConstants.SIG_NS, "ds:KeyInfo");
                ((OMElement) x509DataElem).declareNamespace(WSConstants.SIG_NS, WSConstants.SIG_PREFIX);
                keyInfoElem.appendChild(x509DataElem);
            }

        } catch (Exception e) {
            throw new TrustException("samlAssertionCreationError", e);
        }
    }

    // Unmarshall the keyInfo DOM element into an XMLObject
    String keyInfoElementString = keyInfoElem.toString();
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    DocumentBuilder docBuilder = documentBuilderFactory.newDocumentBuilder();
    Document document = docBuilder.parse(new ByteArrayInputStream(keyInfoElementString.trim().getBytes()));
    Element element = document.getDocumentElement();

    // Get appropriate unmarshaller
    UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory();
    Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(element);

    // Unmarshall using the document root element, an keyInfo element in this case
    XMLObject keyInfoElement = null;
    try {
        keyInfoElement = unmarshaller.unmarshall(element);
    } catch (UnmarshallingException e) {
        throw new TrustException("Error unmarshalling KeyInfo Element", e);
    }

    //Build the Subject Confirmation
    SAMLObjectBuilder<SubjectConfirmation> subjectConfirmationBuilder = (SAMLObjectBuilder<SubjectConfirmation>) builderFactory
            .getBuilder(SubjectConfirmation.DEFAULT_ELEMENT_NAME);
    SubjectConfirmation subjectConfirmation = subjectConfirmationBuilder.buildObject();

    //Set the subject Confirmation method
    subjectConfirmation.setMethod("urn:oasis:names:tc:SAML:2.0:cm:holder-of-key");

    SAMLObjectBuilder<KeyInfoConfirmationDataType> keyInfoSubjectConfirmationDataBuilder = (SAMLObjectBuilder<KeyInfoConfirmationDataType>) builderFactory
            .getBuilder(KeyInfoConfirmationDataType.TYPE_NAME);

    //Build the subject confirmation data element
    KeyInfoConfirmationDataType scData = keyInfoSubjectConfirmationDataBuilder
            .buildObject(SubjectConfirmationData.DEFAULT_ELEMENT_NAME, KeyInfoConfirmationDataType.TYPE_NAME);

    //Set the keyInfo element
    scData.getKeyInfos().add(keyInfoElement);

    // Set the validity period
    scData.setNotBefore(creationTime);
    scData.setNotOnOrAfter(expirationTime);

    //Set the subject confirmation data
    subjectConfirmation.setSubjectConfirmationData(scData);

    //set the subject confirmation
    subject.getSubjectConfirmations().add(subjectConfirmation);

    log.debug("SAML2.0 subject is constructed successfully.");
    return subject;
}

From source file:org.apache.rahas.impl.util.SAML2Utils.java

/**
* Extract certificates or the key available in the SAMLAssertion
*
* @param elem//  w ww.ja  v  a2  s. com
* @return the SAML2 Key Info
* @throws org.apache.ws.security.WSSecurityException
*
*/
public static SAML2KeyInfo getSAML2KeyInfo(Element elem, Crypto crypto, CallbackHandler cb)
        throws WSSecurityException {
    Assertion assertion;

    //build the assertion by unmarhalling the DOM element.
    try {
        DefaultBootstrap.bootstrap();

        String keyInfoElementString = elem.toString();
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setNamespaceAware(true);
        DocumentBuilder docBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = docBuilder.parse(new ByteArrayInputStream(keyInfoElementString.trim().getBytes()));
        Element element = document.getDocumentElement();
        UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory();
        Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(element);
        assertion = (Assertion) unmarshaller.unmarshall(element);
    } catch (ConfigurationException e) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "Failure in bootstrapping", null, e);
    } catch (UnmarshallingException e) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "Failure in unmarshelling the assertion",
                null, e);
    } catch (IOException e) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "Failure in unmarshelling the assertion",
                null, e);
    } catch (SAXException e) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "Failure in unmarshelling the assertion",
                null, e);
    } catch (ParserConfigurationException e) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "Failure in unmarshelling the assertion",
                null, e);
    }
    return getSAML2KeyInfo(assertion, crypto, cb);

}

From source file:org.apache.ws.security.message.token.SecurityTokenReference.java

public KrbSession getKerberosSession() {
    KrbSession result = null;//  w  ww  . j ava 2s. co m
    Element elem = (Element) WSSecurityUtil.findElement(element, "KeyIdentifier",
            "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");

    String thumbPrint = elem.toString();
    thumbPrint = thumbPrint.substring(thumbPrint.indexOf(">") + 1);
    thumbPrint = thumbPrint.substring(0, thumbPrint.indexOf("<"));
    result = KrbSessionCache.getInstance().getSession(thumbPrint);
    return result;
}

From source file:org.apache.ws.security.processor.SAML2TokenProcessor.java

/**
 * This method is used to validate a SAML2.0 Token.
 * TODO At the moment it only validates by building an assertion similar to the SAMLTokenProcessor.
 * @param elem/*from ww w. j  a  v  a2 s.  c om*/
 * @return SAML2.0 Assertion
 * @throws WSSecurityException
 */
public Assertion buildAssertion(Element elem) throws WSSecurityException {
    Assertion samlAssertion;
    try {
        DefaultBootstrap.bootstrap();

        // Unmarshall and build the assertion from the DOM element.
        String keyInfoElementString = elem.toString();
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setNamespaceAware(true);
        DocumentBuilder docBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = docBuilder.parse(new ByteArrayInputStream(keyInfoElementString.trim().getBytes()));
        Element element = document.getDocumentElement();
        UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory();
        Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(element);
        samlAssertion = (Assertion) unmarshaller.unmarshall(element);
    } catch (ConfigurationException e) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "Failure in bootstrapping", null, e);
    } catch (UnmarshallingException e) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "Failure in unmarshelling the assertion",
                null, e);
    } catch (IOException e) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "Failure in unmarshelling the assertion",
                null, e);
    } catch (SAXException e) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "Failure in unmarshelling the assertion",
                null, e);
    } catch (ParserConfigurationException e) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "Failure in unmarshelling the assertion",
                null, e);
    }

    if (log.isDebugEnabled()) {
        log.debug("SAML2 Token was validated successfully.");
    }
    return samlAssertion;
}

From source file:org.apache.ws.security.transform.STRTransform.java

/**
 * Method enginePerformTransform//from   w w w .  java 2  s  . c  o m
 * 
 * @param input
 * @throws CanonicalizationException
 * @throws InvalidCanonicalizerException
 */
protected XMLSignatureInput enginePerformTransform(XMLSignatureInput input, Transform transformObject)
        throws IOException, CanonicalizationException, InvalidCanonicalizerException {
    doDebug = log.isDebugEnabled();

    if (doDebug) {
        log.debug("Beginning STRTransform..." + input.toString());
    }

    try {
        //
        // Get the main document, that is the complete SOAP request document
        //
        Document thisDoc = transformObject.getDocument();

        //
        // Here we get some information about the document that is being
        // processed, in particular the crypto implementation, and already
        // detected BST that may be used later during dereferencing.
        //
        wsDocInfo = WSDocInfoStore.lookup(thisDoc);
        if (wsDocInfo == null) {
            throw (new CanonicalizationException("no WSDocInfo found"));
        }
        //
        // According to the OASIS WS Specification "Web Services Security:
        // SOAP Message Security 1.0" Monday, 19 January 2004, chapter 8.3
        // describes that the input node set must be processed by the c14n
        // that is specified in the argument element of the STRTransform
        // element.
        // 
        // First step: Get the required c14n argument and get the specified
        // Canonicalizer
        //
        String canonAlgo = null;
        if (transformObject.length(WSConstants.WSSE_NS, "TransformationParameters") == 1) {
            Element tmpE = XMLUtils.selectNode(transformObject.getElement().getFirstChild(),
                    WSConstants.WSSE_NS, "TransformationParameters", 0);
            Element canonElem = (Element) WSSecurityUtil.getDirectChild(tmpE, "CanonicalizationMethod",
                    WSConstants.SIG_NS);
            canonAlgo = canonElem.getAttribute("Algorithm");
            if (doDebug) {
                log.debug("CanonAlgo: " + canonAlgo);
            }
        }
        Canonicalizer canon = Canonicalizer.getInstance(canonAlgo);

        ByteArrayOutputStream bos = null;
        byte[] buf = null;
        if (doDebug) {
            buf = input.getBytes();
            bos = new ByteArrayOutputStream(buf.length);
            bos.write(buf, 0, buf.length);
            log.debug("canon bos: " + bos.toString());
        }

        //
        // Get the input (node) to transform. Currently we support only an
        // Element as input format. If other formats are required we must
        // get it as bytes and probably reparse it into a DOM tree (How to
        // work with nodesets? how to select the right node from a nodeset?)
        //
        Element str = null;
        if (input.isElement()) {
            str = (Element) input.getSubNode();
        } else {
            throw new CanonicalizationException("Wrong input format - only element input supported");
        }

        if (doDebug) {
            log.debug("STR: " + str.toString());
        }
        //
        // The element to transform MUST be a SecurityTokenReference
        // element.
        //
        SecurityTokenReference secRef = new SecurityTokenReference(str);
        //
        // Third and forth step are performed by derefenceSTR()
        //
        Element dereferencedToken = STRTransformUtil.dereferenceSTR(thisDoc, secRef, wsDocInfo);
        //
        // C14n with specified algorithm. According to WSS Specification.
        //
        buf = canon.canonicalizeSubtree(dereferencedToken, "#default");
        if (doDebug) {
            bos = new ByteArrayOutputStream(buf.length);
            bos.write(buf, 0, buf.length);
            log.debug("after c14n: " + bos.toString());
        }

        //
        // Alert: Hacks ahead According to WSS spec an Apex node must
        // contain a default namespace. If none is availabe in the first
        // node of the c14n output (this is the apex element) then we do
        // some editing to insert an empty default namespace
        // 
        // TODO: Rework theses hacks after c14n was updated and can be
        // instructed to insert empty default namespace if required
        //
        // If the problem with c14n method is solved then just do:
        // return new XMLSignatureInput(buf);

        // start of HACK
        StringBuffer bf = new StringBuffer(new String(buf));
        String bf1 = bf.toString();

        //
        // Find start and end of first element <....>, this is the Apex node
        //
        int gt = bf1.indexOf(">");
        //
        // Lookup the default namespace
        //
        int idx = bf1.indexOf(XMLNS);
        //
        // If none found or if it is outside of this (Apex) element look for
        // first blank in, insert default namespace there (this is the
        // correct place according to c14n specification)
        //
        if (idx < 0 || idx > gt) {
            idx = bf1.indexOf(" ");
            bf.insert(idx + 1, "xmlns=\"\" ");
            bf1 = bf.toString();
        }
        if (doDebug) {
            log.debug("last result: ");
            log.debug(bf1);
        }
        return new XMLSignatureInput(bf1.getBytes());
    }
    // End of HACK
    catch (WSSecurityException ex) {
        log.debug(ex.getMessage(), ex);
        throw (new CanonicalizationException("c14n.Canonicalizer.Exception", ex));
    }
}

From source file:org.aselect.server.request.handler.xsaml20.sp.Xsaml20_AssertionConsumer.java

/**
 * Assertion consumer. <br>/*from ww  w . j  a  v a2  s .  co  m*/
 * 
 * @param servletRequest
 *            HttpServletRequest.
 * @param servletResponse
 *            HttpServletResponse.
 * @return the request state
 * @throws ASelectException
 *             on failure
 */
@SuppressWarnings("unchecked")
public RequestState process(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws ASelectException {
    String sMethod = "process";
    boolean checkAssertionSigning = false;
    Object samlResponseObject = null;
    String auth_proof = null;
    PrintWriter pwOut = null;

    try {
        pwOut = Utils.prepareForHtmlOutput(servletRequest, servletResponse);

        String sReceivedArtifact = servletRequest.getParameter("SAMLart");
        String sReceivedResponse = servletRequest.getParameter("SAMLResponse");
        String sRelayState = servletRequest.getParameter("RelayState");
        _systemLogger.log(Level.INFO, MODULE, sMethod,
                "Received artifact: " + sReceivedArtifact + " RelayState=" + sRelayState);
        if (!(sReceivedArtifact == null || "".equals(sReceivedArtifact))) {
            String sFederationUrl = _sFederationUrl; // default, remove later on, can be null
            if (sRelayState.startsWith("idp=")) {
                sFederationUrl = sRelayState.substring(4);
            } else { // Could be Base64 encoded
                sRelayState = new String(Base64Codec.decode(sRelayState));
                _systemLogger.log(Level.INFO, MODULE, sMethod, "RelayState=" + sRelayState);
                sFederationUrl = Utils.getParameterValueFromUrl(sRelayState, "idp");
            }
            if (!Utils.hasValue(sFederationUrl)) {
                _systemLogger.log(Level.WARNING, MODULE, sMethod,
                        "No idp value found in RelayState (or in <federation_url> config)");
                throw new ASelectException(Errors.ERROR_ASELECT_SERVER_INVALID_REQUEST);
            }

            _systemLogger.log(Level.INFO, MODULE, sMethod, "FederationUrl=" + sFederationUrl);
            // use metadata
            MetaDataManagerSp metadataManager = MetaDataManagerSp.getHandle();
            String sASelectServerUrl = metadataManager.getLocation(sFederationUrl,
                    ArtifactResolutionService.DEFAULT_ELEMENT_LOCAL_NAME,
                    SAMLConstants.SAML2_SOAP11_BINDING_URI);
            _systemLogger.log(Level.INFO, MODULE, sMethod, "Artifact Resolution at " + sASelectServerUrl);

            if (sASelectServerUrl == null) {
                _systemLogger.log(Level.INFO, MODULE, sMethod, "Artifact NOT found");
                throw new ASelectException(Errors.ERROR_ASELECT_NOT_FOUND);
            }

            SAMLObjectBuilder<Artifact> artifactBuilder = (SAMLObjectBuilder<Artifact>) _oBuilderFactory
                    .getBuilder(Artifact.DEFAULT_ELEMENT_NAME);
            Artifact artifact = artifactBuilder.buildObject();
            artifact.setArtifact(sReceivedArtifact);

            SAMLObjectBuilder<ArtifactResolve> artifactResolveBuilder = (SAMLObjectBuilder<ArtifactResolve>) _oBuilderFactory
                    .getBuilder(ArtifactResolve.DEFAULT_ELEMENT_NAME);
            ArtifactResolve artifactResolve = artifactResolveBuilder.buildObject();

            artifactResolve.setID(SamlTools.generateIdentifier(_systemLogger, MODULE));
            artifactResolve.setVersion(SAMLVersion.VERSION_20);
            artifactResolve.setIssueInstant(new DateTime());

            // We decided that the other side could retrieve public key from metadata
            // by looking up the issuer as an entityID in the metadata
            // So we MUST supply an Issuer (which otherwise would be optional (by SAML standards))
            SAMLObjectBuilder<Issuer> assertionIssuerBuilder = (SAMLObjectBuilder<Issuer>) _oBuilderFactory
                    .getBuilder(Issuer.DEFAULT_ELEMENT_NAME);
            Issuer assertionIssuer = assertionIssuerBuilder.buildObject();

            // 20100312, Bauke: eHerkenning, no assertion issuer format:
            // assertionIssuer.setFormat(NameIDType.ENTITY);
            // 20100311, Bauke: added for eHerkenning: Specific issuer id, independent of the Url
            PartnerData partnerData = MetaDataManagerSp.getHandle().getPartnerDataEntry(sFederationUrl);
            String specialSettings = (partnerData == null) ? null : partnerData.getSpecialSettings();
            if (partnerData != null && partnerData.getLocalIssuer() != null)
                assertionIssuer.setValue(partnerData.getLocalIssuer());
            else
                assertionIssuer.setValue(_sRedirectUrl);
            artifactResolve.setIssuer(assertionIssuer);
            artifactResolve.setArtifact(artifact);

            // Do some logging for testing
            _systemLogger.log(Level.INFO, MODULE, sMethod, "Sign the artifactResolve >======");
            boolean useSha256 = (specialSettings != null && specialSettings.contains("sha256"));
            artifactResolve = (ArtifactResolve) SamlTools.signSamlObject(artifactResolve,
                    useSha256 ? "sha256" : "sha1");
            _systemLogger.log(Level.INFO, MODULE, sMethod, "Signed the artifactResolve ======<");

            // Build the SOAP message
            SoapManager soapManager = null;
            if (isUseBackchannelClientcertificate()) {
                soapManager = new SoapManager(getSslSocketFactory());
            } else {
                soapManager = new SoapManager();
            }
            Envelope envelope = soapManager.buildSOAPMessage(artifactResolve);
            _systemLogger.log(Level.INFO, MODULE, sMethod, "Marshall");
            Element envelopeElem = SamlTools.marshallMessage(envelope);
            _systemLogger.log(Level.INFO, MODULE, sMethod,
                    "Writing SOAP message:\n" + XMLHelper.nodeToString(envelopeElem));
            // XMLHelper.prettyPrintXML(envelopeElem));

            // ------------ Send/Receive the SOAP message
            String sSamlResponse = soapManager.sendSOAP(XMLHelper.nodeToString(envelopeElem),
                    sASelectServerUrl); // x_AssertionConsumer_x
            //byte[] sSamlResponseAsBytes = sSamlResponse.getBytes();
            _systemLogger.log(Level.INFO, MODULE, sMethod,
                    "Received response: " + sSamlResponse + " length=" + sSamlResponse.length());

            // save original, but, for (internal) transport, encode base64 
            auth_proof = new String(
                    org.apache.commons.codec.binary.Base64.encodeBase64(sSamlResponse.getBytes("UTF-8")));

            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            dbFactory.setNamespaceAware(true);
            // dbFactory.setExpandEntityReferences(false);
            // dbFactory.setIgnoringComments(true);
            DocumentBuilder builder = dbFactory.newDocumentBuilder();

            StringReader stringReader = new StringReader(sSamlResponse);
            InputSource inputSource = new InputSource(stringReader);
            Document docReceivedSoap = builder.parse(inputSource);
            _systemLogger.log(Level.INFO, MODULE, sMethod, "parsed=" + docReceivedSoap.toString());
            Element elementReceivedSoap = docReceivedSoap.getDocumentElement();
            _systemLogger.log(Level.INFO, MODULE, sMethod, "getdoc=" + elementReceivedSoap.toString());

            // Remove all SOAP elements
            Node eltArtifactResponse = SamlTools.getNode(elementReceivedSoap, "ArtifactResponse");

            // Unmarshall to the SAMLmessage
            UnmarshallerFactory factory = Configuration.getUnmarshallerFactory();
            Unmarshaller unmarshaller = factory.getUnmarshaller((Element) eltArtifactResponse);
            ArtifactResponse artifactResponse = (ArtifactResponse) unmarshaller
                    .unmarshall((Element) eltArtifactResponse);

            Issuer issuer = artifactResponse.getIssuer();
            String sIssuer = (issuer == null) ? null : issuer.getValue();
            // If issuer is not present in the response, use sASelectServerUrl value retrieved from metadata
            // else use value from the response
            String artifactResponseIssuer = (sIssuer == null || "".equals(sIssuer)) ? sASelectServerUrl
                    : sIssuer;

            _systemLogger.log(Level.INFO, MODULE, sMethod,
                    "Do artifactResponse signature verification=" + is_bVerifySignature());
            //            if (is_bVerifySignature()) {   // RH, 20121205, o
            if (is_bVerifySignature() || isVerifyArtifactResponseSignature()) { // RH, 20121205, n
                // Check signature of artifactResolve here
                // We get the public key from the metadata
                // Therefore we need a valid Issuer to lookup the entityID in the metadata
                // We get the metadataURL from aselect.xml so we consider this safe and authentic
                if (artifactResponseIssuer == null || "".equals(artifactResponseIssuer)) {
                    _systemLogger.log(Level.SEVERE, MODULE, sMethod,
                            "For signature verification the received message must have an Issuer");
                    throw new ASelectException(Errors.ERROR_ASELECT_SERVER_INVALID_REQUEST);
                }

                PublicKey pkey = metadataManager.getSigningKeyFromMetadata(artifactResponseIssuer);
                if (pkey == null || "".equals(pkey)) {
                    _systemLogger.log(Level.SEVERE, MODULE, sMethod, "No valid public key in metadata");
                    throw new ASelectException(Errors.ERROR_ASELECT_SERVER_INVALID_REQUEST);
                }

                if (SamlTools.checkSignature(artifactResponse, pkey)) {
                    _systemLogger.log(Level.INFO, MODULE, sMethod, "artifactResponse was signed OK");
                } else {
                    _systemLogger.log(Level.SEVERE, MODULE, sMethod, "artifactResponse was NOT signed OK");
                    throw new ASelectException(Errors.ERROR_ASELECT_SERVER_INVALID_REQUEST);
                }
            }
            samlResponseObject = artifactResponse.getMessage();
        } else if (!(sReceivedResponse == null || "".equals(sReceivedResponse))) {
            // Handle http-post, can be unsolicited POST as well
            // Could be Base64 encoded
            // RelayState should contain intended application resource URL
            sRelayState = new String(Base64Codec.decode(sRelayState));

            _systemLogger.log(Level.FINER, MODULE, sMethod, "Received Response: " + sReceivedResponse); //   RH, 20130924, n
            //            sReceivedResponse = new String(Base64Codec.decode(sReceivedResponse));   //   RH, 20130924, o
            auth_proof = sReceivedResponse; // save original

            sReceivedResponse = new String(
                    org.apache.commons.codec.binary.Base64.decodeBase64(sReceivedResponse.getBytes("UTF-8"))); //   RH, 20130924, n
            _systemLogger.log(Level.INFO, MODULE, sMethod, "Received Response after base64 decoding: "
                    + sReceivedResponse + " RelayState=" + sRelayState); //   RH, 20130924, n
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            dbFactory.setNamespaceAware(true);
            // dbFactory.setExpandEntityReferences(false);
            // dbFactory.setIgnoringComments(true);
            DocumentBuilder builder = dbFactory.newDocumentBuilder();

            StringReader stringReader = new StringReader(sReceivedResponse);
            InputSource inputSource = new InputSource(stringReader);
            Document docReceived = builder.parse(inputSource);
            Node eltSAMLResponse = SamlTools.getNode(docReceived, "Response");
            _systemLogger.log(Level.INFO, MODULE, sMethod,
                    "Found node Response: " + eltSAMLResponse + ((eltSAMLResponse == null) ? " NULL" : " ok"));

            // Unmarshall to the SAMLmessage
            UnmarshallerFactory factory = Configuration.getUnmarshallerFactory();
            Unmarshaller unmarshaller = factory.getUnmarshaller((Element) eltSAMLResponse);
            _systemLogger.log(Level.INFO, MODULE, sMethod,
                    "Unmarshaller" + ((unmarshaller == null) ? " NULL" : " ok"));
            samlResponseObject = (Response) unmarshaller.unmarshall((Element) eltSAMLResponse);
            _systemLogger.log(Level.INFO, MODULE, sMethod,
                    "Unmarshalling done, VerifySignature=" + is_bVerifySignature());

            // 20120308: Bauke added signature checking
            //   saml-profiles-2.0-os: The <Assertion> element(s) in the <Response> MUST be signed,
            //   if the HTTP POST binding is used, and MAY be signed if the HTTPArtifact binding is used.
            if (is_bVerifySignature())
                checkAssertionSigning = true;

        } else {
            _systemLogger.log(Level.WARNING, MODULE, sMethod,
                    "No Artifact and no Response found in the message.");
            throw new ASelectException(Errors.ERROR_ASELECT_SERVER_INVALID_REQUEST);
        }

        ///////
        // The object can either a Response (SSO case) or a StatusResponseType (SLO case)
        ///////////////////////////////////////////////////////////////////////////
        if (samlResponseObject instanceof Response) {
            // SSO
            Response samlResponse = (Response) samlResponseObject;
            _systemLogger.log(Level.INFO, MODULE, sMethod, "Processing 'Response'"); // +XMLHelper.prettyPrintXML(samlResponse.getDOM()));

            // RH, 20121205, sn
            MetaDataManagerSp metadataManager = MetaDataManagerSp.getHandle();
            _systemLogger.log(Level.INFO, MODULE, sMethod,
                    "Do Response signature verification=" + isVerifyResponseSignature());
            if (isVerifyResponseSignature()) {
                Issuer issuer = samlResponse.getIssuer();
                String sIssuer = (issuer == null) ? null : issuer.getValue();
                // If issuer is not present in the response, use sASelectServerUrl value retrieved from metadata
                // else use value from the response
                //               String responseIssuer = (sIssuer == null || "".equals(sIssuer))? sASelectServerUrl: sIssuer;
                String responseIssuer = (sIssuer == null || "".equals(sIssuer)) ? null : sIssuer; // There must be an issuer for now
                // Check signature of artifactResolve here
                // We get the public key from the metadata
                // Therefore we need a valid Issuer to lookup the entityID in the metadata
                // We get the metadataURL from aselect.xml so we consider this safe and authentic
                if (responseIssuer == null || "".equals(responseIssuer)) {
                    _systemLogger.log(Level.SEVERE, MODULE, sMethod,
                            "For signature verification the received response must have an Issuer");
                    throw new ASelectException(Errors.ERROR_ASELECT_SERVER_INVALID_REQUEST);
                }

                PublicKey pkey = metadataManager.getSigningKeyFromMetadata(responseIssuer);
                if (pkey == null || "".equals(pkey)) {
                    _systemLogger.log(Level.SEVERE, MODULE, sMethod, "No valid public key in metadata");
                    throw new ASelectException(Errors.ERROR_ASELECT_SERVER_INVALID_REQUEST);
                }

                if (SamlTools.checkSignature(samlResponse, pkey)) {
                    _systemLogger.log(Level.INFO, MODULE, sMethod, "Response was signed OK");
                } else {
                    _systemLogger.log(Level.SEVERE, MODULE, sMethod, "Response was NOT signed OK");
                    throw new ASelectException(Errors.ERROR_ASELECT_SERVER_INVALID_REQUEST);
                }
            }
            // RH, 20121205, en

            // Detect if this is a successful or an error Response      
            String sStatusCode = samlResponse.getStatus().getStatusCode().getValue();
            String sRemoteRid = samlResponse.getID();

            // 20100531, Bauke: Remove added timestamp to get our local RID
            String sLocalRid = samlResponse.getInResponseTo();
            int len = sLocalRid.length();
            if (len > 9)
                sLocalRid = sLocalRid.substring(0, len - 9);
            _systemLogger.log(Level.INFO, MODULE, sMethod,
                    "RemoteRid=" + sRemoteRid + " LocalRid=" + sLocalRid + " StatusCode=" + sStatusCode);
            _htSessionContext = _oSessionManager.getSessionContext(sLocalRid);
            if (_htSessionContext == null) {
                _systemLogger.log(Level.WARNING, MODULE, sMethod,
                        "Unknown session in response from cross aselect server");
                throw new ASelectCommunicationException(Errors.ERROR_ASELECT_SERVER_INVALID_REQUEST);
            }

            if (sStatusCode.equals(StatusCode.SUCCESS_URI)) {
                _systemLogger.log(Level.INFO, MODULE, sMethod,
                        "Response was successful " + samlResponse.toString());
                _systemLogger.log(Level.INFO, MODULE, sMethod,
                        "Number of Assertions found:  " + samlResponse.getAssertions().size());
                Assertion samlAssertion = samlResponse.getAssertions().get(0);
                _systemLogger.log(Level.INFO, MODULE, sMethod, "Assertion ID:" + samlAssertion.getID());
                String sAssertIssuer = samlAssertion.getIssuer().getValue();
                _systemLogger.log(Level.INFO, MODULE, sMethod,
                        "Issuer:" + sAssertIssuer + " checkAssertionSigning=" + checkAssertionSigning);

                // 20120308: Bauke added signature checking
                //               if (checkAssertionSigning) {   // RH, 20121205, o
                if (checkAssertionSigning || isVerifyAssertionSignature()) { // RH, 20121205, n
                    // Check signature of artifactResolve here. We get the public key from the metadata
                    // Therefore we need a valid Issuer to lookup the entityID in the metadata
                    // We get the metadataURL from aselect.xml so we consider this safe and authentic
                    _systemLogger.log(Level.INFO, MODULE, sMethod,
                            "Verify assertion signature, issuer=" + sAssertIssuer);
                    if (!Utils.hasValue(sAssertIssuer)) {
                        _systemLogger.log(Level.SEVERE, MODULE, sMethod, "No Issuer present in Assertion");
                        throw new ASelectException(Errors.ERROR_ASELECT_SERVER_INVALID_REQUEST);
                    }

                    //                  MetaDataManagerSp metadataManager = MetaDataManagerSp.getHandle();   // RH, 20121205, n
                    PublicKey pkey = metadataManager.getSigningKeyFromMetadata(sAssertIssuer);
                    if (pkey == null || "".equals(pkey)) {
                        _systemLogger.log(Level.SEVERE, MODULE, sMethod, "No valid public key in metadata");
                        throw new ASelectException(Errors.ERROR_ASELECT_SERVER_INVALID_REQUEST);
                    }
                    if (!SamlTools.checkSignature(samlAssertion, pkey)) {
                        _systemLogger.log(Level.SEVERE, MODULE, sMethod, "Assertion was NOT signed OK");
                        throw new ASelectException(Errors.ERROR_ASELECT_SERVER_INVALID_REQUEST);
                    }
                    _systemLogger.log(Level.INFO, MODULE, sMethod, "Assertion was signed OK");
                }
                // 20120308

                String sNameID = samlAssertion.getSubject().getNameID().getValue();
                _systemLogger.log(Level.INFO, MODULE, sMethod, "NameID:" + sNameID);
                String sNameIDQualifier = samlAssertion.getSubject().getNameID().getNameQualifier();
                _systemLogger.log(Level.INFO, MODULE, sMethod, "NameIDQualifier:" + sNameIDQualifier);

                // Now check for time interval validation
                // We only check first object from the list
                // First the assertion itself
                if (is_bVerifyInterval() && !SamlTools.checkValidityInterval(samlAssertion)) {
                    _systemLogger.log(Level.SEVERE, MODULE, sMethod, "Assertion time interval was NOT valid");
                    throw new ASelectException(Errors.ERROR_ASELECT_SERVER_INVALID_REQUEST);
                }
                // then the AuthnStatement
                if (is_bVerifyInterval()
                        && !SamlTools.checkValidityInterval(samlAssertion.getAuthnStatements().get(0))) {
                    _systemLogger.log(Level.SEVERE, MODULE, sMethod,
                            "AuthnStatement time interval was NOT valid");
                    throw new ASelectException(Errors.ERROR_ASELECT_SERVER_INVALID_REQUEST);
                }
                // check subjectlocalityaddress
                if (isLocalityAddressRequired()
                        && !SamlTools.checkLocalityAddress(samlAssertion.getAuthnStatements().get(0),
                                servletRequest.getRemoteAddr())) {
                    _systemLogger.log(Level.SEVERE, MODULE, sMethod,
                            "AuthnStatement subjectlocalityaddress was NOT valid");
                    throw new ASelectException(Errors.ERROR_ASELECT_SERVER_INVALID_REQUEST);
                }

                // Get the (option) sessionindex from remote
                String sSessionindex = samlAssertion.getAuthnStatements().get(0).getSessionIndex();
                _systemLogger.log(Level.INFO, MODULE, sMethod, "Sessionindex:" + sSessionindex);

                AuthnContext oAuthnContext = samlAssertion.getAuthnStatements().get(0).getAuthnContext();
                List<AuthenticatingAuthority> authAuthorities = oAuthnContext.getAuthenticatingAuthorities();
                String sAuthnAuthority = null;
                if (authAuthorities != null && authAuthorities.size() > 0)
                    sAuthnAuthority = (String) authAuthorities.get(0).getURI();
                String sAuthnContextClassRefURI = oAuthnContext.getAuthnContextClassRef()
                        .getAuthnContextClassRef();
                _systemLogger.log(Level.INFO, MODULE, sMethod,
                        "AuthnContextClassRefURI:" + sAuthnContextClassRefURI);
                ;
                /////////////////////////   digid4   ///////////////////////////////////////////
                /// Digid4 still has to decide how to provide a "face2face" declaration 
                //   String sAuthnContextDeclRefIssueMethod = samlAssertion.getAuthnStatements().get(0).getAuthnContext().
                /////////////////////////   digid4   ///////////////////////////////////////////
                String sSelectedLevel = SecurityLevel
                        .convertAuthnContextClassRefURIToLevel(sAuthnContextClassRefURI, _systemLogger);

                // Check returned security level
                Integer intAppLevel = (Integer) _htSessionContext.get("level");
                if (Integer.parseInt(sSelectedLevel) < intAppLevel) {
                    _systemLogger.log(Level.SEVERE, MODULE, sMethod, "Security level returned ("
                            + sSelectedLevel + ") must be at least: " + intAppLevel);
                    throw new ASelectException(Errors.ERROR_ASELECT_SERVER_INVALID_REQUEST);
                }

                // Retrieve the embedded attributes
                HashMap hmSamlAttributes = new HashMap();
                String sEncodedAttributes = null;
                List<AttributeStatement> lAttrStatList = samlAssertion.getAttributeStatements();
                Iterator<AttributeStatement> iASList = lAttrStatList.iterator();
                while (iASList.hasNext()) {
                    AttributeStatement sAttr = iASList.next();
                    List<Attribute> lAttr = sAttr.getAttributes();
                    Iterator<Attribute> iAttr = lAttr.iterator();
                    while (iAttr.hasNext()) {
                        Attribute attr = iAttr.next();
                        String sAttrName = attr.getName();

                        String sAttrValue = null;// RH, 20120124, sn
                        List<XMLObject> aValues = attr.getAttributeValues();
                        if (aValues != null && aValues.size() == 1) { // For now we only allow single valued simple type xs:string attributes
                            XMLObject xmlObj = aValues.get(0);
                            //                        XSStringImpl xsString = (XSStringImpl) attr.getOrderedChildren().get(0);// RH, 20120124, so
                            //                        String sAttrValue = xsString.getValue();// RH, 20120124, o
                            //                        sAttrValue = xsString.getValue();// RH, 20120124, eo
                            sAttrValue = xmlObj.getDOM().getFirstChild().getTextContent();
                            _systemLogger.log(Level.INFO, MODULE, sMethod,
                                    "Name=" + sAttrName + " Value=" + sAttrValue);
                        } else {
                            _systemLogger.log(Level.INFO, MODULE, sMethod,
                                    "Only single valued attributes allowed, skipped attribute Name="
                                            + sAttrName);
                        } // RH, 20120124, en
                        if ("attributes".equals(sAttrName))
                            sEncodedAttributes = sAttrValue;
                        else
                            hmSamlAttributes.put(sAttrName, sAttrValue);
                    }
                }

                // Since the "attributes" Attribute is used for gathering, add the Saml Attributes to it
                HashMap<String, String> hmAttributes;
                if (sEncodedAttributes != null) {
                    hmAttributes = org.aselect.server.utils.Utils.deserializeAttributes(sEncodedAttributes);
                } else {
                    hmAttributes = new HashMap<String, String>();
                }
                // Add the serialized attributes and a few specials
                hmSamlAttributes.putAll(hmAttributes);
                hmSamlAttributes.put("name_id", sNameID); // "sel_level" was already set by the IdP
                if (sAuthnAuthority != null)
                    hmSamlAttributes.put("authority", sAuthnAuthority);

                // eHerkenning addition: OrgID = KvKnummer+Vestigingsnummer
                // If EntityConcernedID = 00000003123456780000 and EntityConcernedSubID = ...0001,
                // then orgid = 1234567800000001
                //               String sEntityId = (String)hmSamlAttributes.get("urn:nl:eherkenning:0.8def:EntityConcernedID");
                // RH, 20110523, add support for other versions of eHerk
                String sEntityId = null;

                Pattern p = Pattern.compile("urn:nl:eherkenning:(.*):EntityConcernedID");

                Set<String> keys = hmSamlAttributes.keySet();
                Iterator keyIter = keys.iterator();
                String eHerkversion = null;
                while (keyIter.hasNext()) {
                    Matcher m = p.matcher((String) keyIter.next());
                    if (m.find()) {
                        sEntityId = (String) hmSamlAttributes.get(m.group());
                        eHerkversion = m.group(1);
                        _systemLogger.log(Level.INFO, MODULE, sMethod,
                                "Found sEntityId=" + sEntityId + " eHerkversion=" + eHerkversion);
                        break; // just take the first we find
                    }
                }

                if (sEntityId != null) {
                    int idx = sEntityId.length() - 12; // last 12 characters
                    if (idx > 0)
                        sEntityId = sEntityId.substring(idx);

                    //                  String sEntitySubId = (String)hmSamlAttributes.get("urn:nl:eherkenning:0.8def:EntityConcernedSubID");
                    String sEntitySubId = (String) hmSamlAttributes
                            .get("urn:nl:eherkenning:" + eHerkversion + ":EntityConcernedSubID");
                    if (sEntitySubId != null) {
                        _systemLogger.log(Level.INFO, MODULE, sMethod, "Found sEntitySubId=" + sEntitySubId);
                        idx = sEntitySubId.length() - 12; // last 12 characters to be on the safe side
                        if (idx > 0)
                            sEntitySubId = sEntitySubId.substring(idx);
                        sEntityId = sEntitySubId;
                    } else { // ditch the last 4 zeroes
                        idx = sEntityId.length() - 4;
                        if (idx > 0)
                            sEntityId = sEntityId.substring(0, idx);
                    }
                    hmSamlAttributes.put("orgid", sEntityId);
                }

                // eHerkenning: AuthID = Unique Persistent Identifier
                if (isUseNameIDAsAuthID()) { // RH, 20130923, sn
                    hmSamlAttributes.put("authid", sNameID);
                } else { // RH, 20130923, en
                    // Use the fifth word from sAuthnAuthority (split using :) and add sNameID
                    if (sNameIDQualifier != null) {
                        String sAuthID = "", sAuthSubID = "";
                        String[] tokens = sNameIDQualifier.split(":");
                        if (tokens.length > 4)
                            sAuthID = tokens[4];

                        //                  if (tokens.length > 5)
                        //                     sAuthSubID = tokens[5];
                        // Test  new layout of eherkenning
                        // Maybe do something with pattern search here
                        if (tokens.length > 6)
                            sAuthSubID = tokens[6];

                        sAuthID += "_" + sAuthSubID + "_" + sNameID; // add separator
                        hmSamlAttributes.put("authid", sAuthID);
                    }
                } // RH, 20130923, n

                if (isCarryAuthProof()) { // Put the original authentication proof in hmSamlAttributes before serialization in attributes
                                          // so they will be available for gatherer
                    hmSamlAttributes.put("auth_proof", auth_proof); // original response, still base64 encoded
                    //                  _systemLogger.log(Level.FINEST, MODULE, sMethod, "auth_proof=" + auth_proof);
                }
                // And serialize them back to where they came from
                sEncodedAttributes = org.aselect.server.utils.Utils.serializeAttributes(hmSamlAttributes);
                hmSamlAttributes.put("attributes", sEncodedAttributes);

                if (!isCarryAuthProof() && isLogAuthProof()) { // Put the original authentication proof in hmSamlAttributes only temporarily to be removed later
                    // if isCarryAuthProof() true they were already there
                    hmSamlAttributes.put("auth_proof", auth_proof); // original response, still base64 encoded
                    //                  _systemLogger.log(Level.FINEST, MODULE, sMethod, "auth_proof=" + auth_proof);
                }
                // This is the quickest way to get "name_id" into the Context
                hmSamlAttributes.put("name_id", sNameID); // also as plain attribute

                ///////////// Digid4   //////////////////////////////
                // must be made configurable and parameterized, still looking for some reference to identify the service (maybe issuer) 
                String[] splittedNameId = sNameID.split(":");
                if (splittedNameId.length == 2 && splittedNameId[0].toUpperCase().startsWith("S")
                        && splittedNameId[0].length() == 9) { // for now this identifies as digid4
                    hmSamlAttributes.put("uid", splittedNameId[1]);
                    // add special attributes for digid4
                    if ("S00000000".equalsIgnoreCase(splittedNameId[0])) {
                        hmSamlAttributes.put("bsn", splittedNameId[1]);

                    } else if ("S00000001".equalsIgnoreCase(splittedNameId[0])) {
                        hmSamlAttributes.put("sofi", splittedNameId[1]);

                    } else if ("S00000002".equalsIgnoreCase(splittedNameId[0])) {
                        hmSamlAttributes.put("anummer", splittedNameId[1]);

                    } else if ("S00000100".equalsIgnoreCase(splittedNameId[0])) {
                        hmSamlAttributes.put("oeb", splittedNameId[1]);
                    }
                }
                /////////////////////////////////////////////////////

                // 20100422, Bauke: no uid, then use NameID
                String sUid = (String) hmSamlAttributes.get("uid");
                if (sUid == null || sUid.equals(""))
                    hmSamlAttributes.put("uid", sNameID);
                _systemLogger.log(Level.INFO, MODULE, sMethod,
                        "NameID=" + sNameID + " remote_rid=" + sRemoteRid + " local_rid=" + sLocalRid
                                + " sel_level=" + sSelectedLevel + " organization/authsp=" + sAssertIssuer);

                // htRemoteAttributes.put("attributes", HandlerTools.serializeAttributes(htAttributes));
                hmSamlAttributes.put("remote_rid", sRemoteRid);
                hmSamlAttributes.put("local_rid", sLocalRid);

                hmSamlAttributes.put("sel_level", sSelectedLevel);
                hmSamlAttributes.put("authsp_level", sSelectedLevel); // default value, issueTGT will correct this
                hmSamlAttributes.put("organization", sAssertIssuer);
                hmSamlAttributes.put("authsp", sAssertIssuer);

                // RH, 20120201, sn
                // also save the provided session if present, saml2 specs say there might be more than one session to track
                if (isIncludeSessionindexes() && sSessionindex != null && sSessionindex.length() > 0) {
                    Vector sessionindexes = new Vector<String>();
                    sessionindexes.add(sSessionindex);
                    hmSamlAttributes.put("remote_sessionlist", sessionindexes);
                }
                // RH, 20120201, en

                // Bauke, 20081204: If we want to send the IdP token as an attribute
                // to the application, we will need the following code:
                /*
                 * String sAssertion = XMLHelper.nodeToString(samlAssertion.getDOM());
                 * _systemLogger.log(Level.INFO, MODULE, sMethod, "sAssertion="+sAssertion);
                 * BASE64Encoder b64Enc = new BASE64Encoder();
                 * sAssertion = b64Enc.encode(sAssertion.getBytes("UTF-8"));
                 * htRemoteAttributes.put("saml_remote_token", sAssertion);
                 */
                // End of IdP token

                _systemLogger.log(Level.INFO, MODULE, sMethod, "htRemoteAttributes=" + hmSamlAttributes);
                handleSSOResponse(_htSessionContext, hmSamlAttributes, servletRequest, servletResponse);
            } else {
                _systemLogger.log(Level.WARNING, MODULE, sMethod,
                        "Response was not successful: " + sStatusCode);
                // Handle various error conditions here
                String sErrorCode = Errors.ERROR_ASELECT_AUTHSP_COULD_NOT_AUTHENTICATE_USER; // default
                String sErrorSubCode = null;
                if (samlResponse.getStatus().getStatusCode().getStatusCode() != null) { // Get the subcode
                    sErrorSubCode = SamlTools
                            .mapStatus(samlResponse.getStatus().getStatusCode().getStatusCode().getValue());
                    _systemLogger.log(Level.FINER, MODULE, sMethod, "ErrorSubcode: " + sErrorSubCode);
                }
                StatusMessage statMsg = samlResponse.getStatus().getStatusMessage();
                if (statMsg != null) {
                    sErrorCode = statMsg.getMessage();
                    _systemLogger.log(Level.FINER, MODULE, sMethod, "StatusMessage found: " + sErrorCode);
                } else {
                    if (sErrorSubCode != null && !"".equals(sErrorSubCode)) {
                        sErrorCode = sErrorSubCode;
                    }
                }
                _systemLogger.log(Level.INFO, MODULE, sMethod, "ErrorCode=" + sErrorCode);
                //else if (samlResponse.getStatus().getStatusCode().getStatusCode().getValue().equals(StatusCode.AUTHN_FAILED_URI))
                //   sErrorCode = Errors.ERROR_ASELECT_AUTHSP_COULD_NOT_AUTHENTICATE_USER;
                // Expect these codes: Errors.ERROR_ASELECT_SERVER_CANCEL,
                // Errors.ERROR_ASELECT_AUTHSP_COULD_NOT_AUTHENTICATE_USER;

                //HashMap htRemoteAttributes = new HashMap();
                //htRemoteAttributes.put("remote_rid", sRemoteRid);
                //htRemoteAttributes.put("local_rid", sLocalRid);
                //htRemoteAttributes.put("result_code", sErrorCode);

                // Choose your response (3rd is implemented below)
                // 1. handleSSOResponse(htRemoteAttributes, request, response); // Lets application display error
                // 2. throw new ASelectException(Errors.ERROR_ASELECT_AUTHSP_ACCESS_DENIED); // Standard server error
                // 3. Show error page:
                showErrorPage(sErrorCode, _htSessionContext, pwOut, servletRequest);
            }
        } else { // SLO
            _systemLogger.log(Level.WARNING, "Unexpected SAMLObject type: " + samlResponseObject.getClass());
            throw new ASelectException(Errors.ERROR_ASELECT_INTERNAL_ERROR);
        }
    } catch (ASelectException e) {
        throw e;
    } catch (Exception e) {
        _systemLogger.log(Level.WARNING, MODULE, sMethod, "Internal error", e);
        throw new ASelectException(Errors.ERROR_ASELECT_INTERNAL_ERROR, e);
    } finally {
        if (pwOut != null)
            pwOut.close();

        // 20130821, Bauke: save friendly name after session is gone
        if (_htSessionContext != null) {
            String sStatus = (String) _htSessionContext.get("status");
            String sAppId = (String) _htSessionContext.get("app_id");
            if ("del".equals(sStatus) && Utils.hasValue(sAppId)) {
                String sUF = ApplicationManager.getHandle().getFriendlyName(sAppId);
                HandlerTools.setEncryptedCookie(servletResponse, "requestor_friendly_name", sUF,
                        _configManager.getCookieDomain(), -1/*age*/, _systemLogger);
            }
        }
        _oSessionManager.finalSessionProcessing(_htSessionContext, true/*really do it*/);
    }
    return null;
}