Example usage for org.w3c.dom Element getAttributes

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

Introduction

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

Prototype

public NamedNodeMap getAttributes();

Source Link

Document

A NamedNodeMap containing the attributes of this node (if it is an Element) or null otherwise.

Usage

From source file:ucar.unidata.idv.ui.ImageGenerator.java

/**
 * process the given node//from  w w  w  .  ja v  a2 s  . c o m
 *
 * @param node Node to process
 *
 * @return keep going
 *
 * @throws Throwable On badness
 */
protected boolean processTagForeach(Element node) throws Throwable {
    pushProperties();
    List allValues = new ArrayList();
    int numElements = 0;
    int cnt = 1;
    NamedNodeMap attrs = node.getAttributes();
    if (attrs == null) {
        return error("No values in foreach tag");
    }

    for (int i = 0; i < attrs.getLength(); i++) {
        Attr attr = (Attr) attrs.item(i);
        String var = attr.getNodeName();
        String values = applyMacros(attr.getNodeValue());
        List tokens;
        //Check if it starts with file:, if so read the contents and split on new line
        if (values.startsWith("file:")) {
            String filename = applyMacros(values.substring("file:".length()));
            values = IOUtil.readContents(filename, getClass()).trim();
            tokens = StringUtil.split(values, "\n");
        } else {
            tokens = StringUtil.split(values, ",");
        }

        if (allValues.size() == 0) {
            numElements = tokens.size();
        } else if (numElements != tokens.size()) {
            return error("Bad number of tokens (" + tokens.size() + " should be:" + numElements
                    + ") in foreach argument:\n" + var + "=" + tokens);
        }
        allValues.add(new Object[] { var, tokens });
        cnt++;
    }
    for (int tokIdx = 0; tokIdx < numElements; tokIdx++) {
        for (int valueIdx = 0; valueIdx < allValues.size(); valueIdx++) {
            Object[] tuple = (Object[]) allValues.get(valueIdx);
            putProperty(tuple[0], ((List) tuple[1]).get(tokIdx));
        }
        try {
            if (!processChildren(node)) {
                return false;
            }
        } catch (MyBreakException be) {
            break;
        } catch (MyContinueException ce) {
        }
    }
    popProperties();
    return true;
}

From source file:umu.eadmin.servicios.umu2stork.ReturnPage.java

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 *///  w  ww. j  ava  2  s. com
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    i18n = new Properties();
    i18n.load(ReturnPage.class.getClassLoader().getResourceAsStream("en.properties")); //default

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.println(HTML_START);
    out.println(HTML_HEAD);
    // AUTO-LOAD Form header
    //out.println("<body style=\"background-image:url(webapp/img/background.png); background-size:scale; background-repeat: no-repeat;background-position: center top\" onload=\"document.createElement('form').submit.call(document.getElementById('myForm'))\">");
    // NO AUTO-LOAD
    out.println(
            "<body style=\"background-image:url(webapp/img/background.png); background-size:scale; background-repeat: no-repeat;background-position: center top\">");

    logger.info("---- edupeps::ReturnPage::doPost() ----");
    Map<String, String> map = new HashMap<String, String>();
    Enumeration<String> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String key = (String) headerNames.nextElement();
        String value = request.getHeader(key);
        map.put(key, value);
    }
    String jsessionid = "";
    try {
        String cookie = map.get("cookie");
        String[] cookiesplt = cookie.split("=");
        if (cookiesplt.length < 1)
            throw new ServletException("Unable to recover jsessionid, regex problem over: " + cookie);
        jsessionid = cookiesplt[1];
    } catch (ClassCastException cce) {
        logger.severe("Unable to recover jsessionid\n" + cce);
        throw new ServletException("ReturnPage::DoPost() - Unable to recover jsessionid (InvalidCast)\n" + cce);
    } catch (NullPointerException npe) {
        logger.severe("Unable to recover jsessionid\n" + npe);
        throw new ServletException("ReturnPage::DoPost() - Unable to recover jsessionid (null)\n" + npe);
    } catch (java.lang.IndexOutOfBoundsException iobe) {
        logger.severe("Unable to recover jsessionid - Malformed cookie\n" + iobe);
        throw new ServletException(
                "ReturnPage::DoPost() - Unable to recover jsessionid (IndexOutOfBoundsException)\n" + iobe);
    }

    String paramSAMLResponse = null;

    logger.info("Parameters Received:");
    Enumeration<String> parameterNames = request.getParameterNames();
    while (parameterNames.hasMoreElements()) {
        String paramName = parameterNames.nextElement();
        logger.info(paramName + ":");
        String[] paramValues = request.getParameterValues(paramName);
        for (int i = 0; i < paramValues.length; i++) {
            String paramValue = paramValues[i];
            logger.info("    " + paramValue);
        }
        if (paramName.compareTo("SAMLResponse") == 0)
            paramSAMLResponse = paramValues[0];
    }

    String appparam = "";
    String dataparam = "";
    String returnURLparam = "";
    String serviceparam = "";

    // Recover session or abort if timeout
    Stork2ProxyH2DB.Stork2ProxyH2DBSession session = null;
    try {
        session = proxyH2db.getSession(jsessionid);
    } catch (Exception e) {
        closeWithError(out, i18n, "error.return.jsession");
        throw new ServletException("Unable to recover session: " + jsessionid);
    }
    // Multi Language i18n
    String langparam = session.getLang();
    if (langparam.equals("es")) {
        i18n = new Properties();
        i18n.load(ReturnPage.class.getClassLoader().getResourceAsStream("es.properties"));
    }

    Date maxallowedtime = new Date(session.getSessiontime().getTime() + MAX_SESSION_TIME);
    Date actualtime = new Date();
    out.println("ActualTime: " + actualtime + "\nsessiontime: " + session.getSessiontime() + "/"
            + session.getSessiontimestr() + "\n maxallowedtime: " + maxallowedtime);
    if (actualtime.after(maxallowedtime)) {
        // closeWithError(out, i18n, "error.return.timeout");
        logger.severe("Session TimedOut " + jsessionid);
        if (!proxyH2db.deleteSession(jsessionid))
            logger.severe("Unable to remove session: " + jsessionid);
        out.println("WARNING: Ignoring session timeout!");
        // return;
    }
    logger.info("Session OK, deleting session from database");
    if (!proxyH2db.deleteSession(jsessionid)) {
        logger.severe("Unable to remove session after successfully found: " + jsessionid);
        closeWithError(out, i18n, "error.return.jsession");
        return;
    }

    appparam = session.getAppname();
    dataparam = session.getUuid();
    returnURLparam = session.getUrl();
    serviceparam = session.getService();

    //STORKAttrQueryResponse response = new STORKAttrQueryResponse();
    STORKAuthnResponse authnResponse = null;
    IPersonalAttributeList personalAttributeList = null;

    String proxyID = properties.getProperty("proxy.entityID");
    logger.info("proxy.entityID: " + proxyID);
    //Decodes SAML Response
    byte[] decSamlToken = PEPSUtil.decodeSAMLToken(paramSAMLResponse);

    //Get SAMLEngine instance
    STORKSAMLEngine engine = STORKSAMLEngine.getInstance("SP");
    if (engine != null) {
        try {
            //validate SAML Token
            authnResponse = engine.validateSTORKAuthnResponse(decSamlToken, (String) request.getRemoteHost());
            logger.info("STORKAuthnResponse Id: " + authnResponse.getSamlId());
            logger.info("Base64 SAML Response: " + new String(authnResponse.getTokenSaml()));

            //response = engine.validateSTORKAttrQueryResponse(decSamlToken, (String) request.getRemoteHost());
        } catch (STORKSAMLEngineException e) {
            logger.severe("Could not validate token for Saml Response: \n" + e.getErrorMessage());
        }

        if (authnResponse.isFail()) {
            logger.severe("Saml Response is fail:\n" + authnResponse.getMessage());
            closeWithError(out, i18n, "error.return.saml");
            return;
        } else {
            // Generate output form
            out.println("<center><h1>" + i18n.getProperty("info.return.form") + "</h1></br><h2>"
                    + new Date().toString() + "</h2></center>");
            out.println("<form id='myForm' name='myForm' action='" + returnURLparam + "' method='post'>");

            // Get PersonalAttributeList form StorkResponse
            personalAttributeList = authnResponse.getPersonalAttributeList();

            // Initialise OpenSAML
            BasicParserPool ppMgr = null;

            try {
                DefaultBootstrap.bootstrap();
                ppMgr = new BasicParserPool();
            } catch (Exception e) {
                // TODO
            }
            byte[] samlreqbase64decoded = Base64.decodeBase64(paramSAMLResponse);
            InputStream samlrespstream = new ByteArrayInputStream(samlreqbase64decoded);

            try {
                Document samlrespdoc = ppMgr.parse(samlrespstream);
                Element samlelement = samlrespdoc.getDocumentElement();
                NamedNodeMap attrmap = samlelement.getAttributes();
                for (int i = 0; i < attrmap.getLength(); i++) {
                    Node n = attrmap.item(i);
                    if (n.getNodeName().equals("AssertionConsumerServiceURL")) {
                        logger.info("Esta es la assertion url:" + n.getNodeValue());
                    }
                    logger.info(" " + attrmap.item(i));
                }
                logger.info(attrmap.toString());

                UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory();
                Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(samlelement);

                Response responseSAML = null;
                Response responseSAMLfromPEPS = null;
                try {
                    responseSAMLfromPEPS = (Response) unmarshaller.unmarshall(samlelement);
                } catch (UnmarshallingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                Assertion assertionPEPS = responseSAMLfromPEPS.getAssertions().get(0);
                XMLObjectBuilderFactory builderFactory = Configuration.getBuilderFactory();

                String statusCode = responseSAMLfromPEPS.getStatus().getStatusCode().getValue();
                logger.info("responseSAMLfromPEPS status: " + statusCode);
                SAMLObjectBuilder<Issuer> issuerbuilder = (SAMLObjectBuilder<Issuer>) builderFactory
                        .getBuilder(Issuer.DEFAULT_ELEMENT_NAME);
                Issuer issuerobj = issuerbuilder.buildObject();
                issuerobj.setValue(proxyID);
                responseSAMLfromPEPS.setIssuer(issuerobj);
                logger.info("responseSAMLfromPEPS Issuer: " + issuerobj.getValue());
                responseSAMLfromPEPS.setDestination(returnURLparam);

                String subject = assertionPEPS.getSubject().getNameID().getValue();
                logger.info("assertionPEPS old subject: " + subject);
                SAMLObjectBuilder<NameID> nameidbuilder = (SAMLObjectBuilder<NameID>) builderFactory
                        .getBuilder(NameID.DEFAULT_ELEMENT_NAME);
                NameID nameid = nameidbuilder.buildObject();
                nameid.setFormat(NameID.TRANSIENT);
                nameid.setValue(UUID.randomUUID().toString());
                assertionPEPS.getSubject().setNameID(nameid);
                logger.info("assertionPEPS new nameID: " + assertionPEPS.getSubject().getNameID());

                assertionPEPS.getSubject().getSubjectConfirmations().get(0).getSubjectConfirmationData()
                        .setRecipient(returnURLparam);
                logger.info("assertionPEPS subject recipient: " + assertionPEPS.getSubject()
                        .getSubjectConfirmations().get(0).getSubjectConfirmationData().getRecipient());
                Issuer assertionIssuer = ((SAMLObjectBuilder<Issuer>) builderFactory
                        .getBuilder(Issuer.DEFAULT_ELEMENT_NAME)).buildObject();
                assertionIssuer.setValue(proxyID);
                assertionPEPS.setIssuer(assertionIssuer);
                logger.info("assertionPEPS issuer: " + assertionPEPS.getIssuer().getValue());
                assertionPEPS.getConditions().getAudienceRestrictions().get(0).getAudiences().get(0)
                        .setAudienceURI(serviceparam);
                logger.info("assertionPEPS audience: " + assertionPEPS.getConditions().getAudienceRestrictions()
                        .get(0).getAudiences().get(0).getAudienceURI());
                assertionPEPS.getConditions().getConditions()
                        .remove(assertionPEPS.getConditions().getOneTimeUse());

                // Attribute translation from stork format to edugain format
                logger.info(" personalAttributeList: \n" + personalAttributeList.size());
                logger.info(
                        " personalAttributeList get(0): " + personalAttributeList.iterator().next().getName());
                ArrayList<Attribute>[] aledugain = eu.storkWebedu.translator.Translator
                        .translateToOpenSAML(personalAttributeList);
                if (aledugain != null)
                    logger.info("aledugain not null");
                else
                    logger.info("aledugain is null");

                logger.info(" aledugain: \ntranslated: " + aledugain[0].size() + "\tpassthrough: "
                        + aledugain[1].size());
                logger.info(" aledugain get(0): \n" + aledugain[0].get(0).getName());

                assertionPEPS.getAttributeStatements().get(0).getAttributes().clear();
                assertionPEPS.getAttributeStatements().get(0).getAttributes().addAll(aledugain[0]);
                assertionPEPS.getAttributeStatements().get(0).getAttributes().addAll(aledugain[1]);

                Assertion assertionSign = assertionPEPS;
                Response responseSign = responseSAMLfromPEPS;

                SigningCredential sign = new SigningCredential();
                sign.intializeCredentials("edupeps", "edupeps-cert", "edupeps", "/opt/keystores/edupeps.jks");

                Signature signatureAssertion = (Signature) Configuration.getBuilderFactory()
                        .getBuilder(Signature.DEFAULT_ELEMENT_NAME).buildObject(Signature.DEFAULT_ELEMENT_NAME);

                Signature signatureResponse = (Signature) Configuration.getBuilderFactory()
                        .getBuilder(Signature.DEFAULT_ELEMENT_NAME).buildObject(Signature.DEFAULT_ELEMENT_NAME);

                signatureAssertion.setSigningCredential(sign.getSigningCredential());
                signatureResponse.setSigningCredential(sign.getSigningCredential());

                // This is also the default if a null SecurityConfiguration is specified
                SecurityConfiguration secConfig = Configuration.getGlobalSecurityConfiguration();
                // If null this would result in the default KeyInfoGenerator being used
                String keyInfoGeneratorProfile = "XMLSignature";

                try {
                    SecurityHelper.prepareSignatureParams(signatureAssertion, sign.getSigningCredential(),
                            secConfig, null);
                    SecurityHelper.prepareSignatureParams(signatureResponse, sign.getSigningCredential(),
                            secConfig, null);
                } catch (SecurityException e) {
                    e.printStackTrace();
                } catch (org.opensaml.xml.security.SecurityException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                assertionSign.setSignature(signatureAssertion);
                responseSign.setSignature(signatureResponse);

                try {
                    Configuration.getMarshallerFactory().getMarshaller(assertionSign).marshall(assertionSign);
                } catch (MarshallingException e) {
                    e.printStackTrace();
                }

                try {
                    Signer.signObject(signatureAssertion);
                } catch (SignatureException e) {
                    e.printStackTrace();
                }

                try {
                    Configuration.getMarshallerFactory().getMarshaller(assertionSign).marshall(assertionSign);
                    Configuration.getMarshallerFactory().getMarshaller(responseSign).marshall(responseSign);
                } catch (MarshallingException e) {
                    e.printStackTrace();
                }

                try {
                    Signer.signObject(signatureResponse);
                } catch (SignatureException e) {
                    e.printStackTrace();
                }

                ResponseMarshaller marshaller = new ResponseMarshaller();
                Element plain = null;
                try {
                    plain = marshaller.marshall(responseSign);
                } catch (MarshallingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                String samlResponse = XMLHelper.nodeToString(plain);
                String xml = samlResponse;
                logger.info("response-xml:\n" + xml);
                String eduresponseEncoded = org.opensaml.xml.util.Base64.encodeBytes(xml.getBytes(),
                        org.opensaml.xml.util.Base64.DONT_BREAK_LINES);
                // Parameter saml response to form
                out.println("<input type='hidden' name='SAMLRequest' value='" + eduresponseEncoded + "'>");

            } catch (XMLParserException xmlparsee) {
                System.err.println("Unable to xml parse SAMLint Request)" + xmlparsee);
            }

            out.println("<input type='hidden' name='" + EduGAIN2StorkProxy.SERVICEHEADERSTR + "' value='"
                    + serviceparam + "'>");
            out.println(
                    "<center><button type='submit' value='Send' method='post'><img src='webapp/img/send.png' width=25 border=3></button></center>");
            out.println("</form>");
        }
    }
    out.println(HTML_END);
}

From source file:util.XmlWriter.java

private String writeAttributes(Element element) {
    StringBuilder attributeString = new StringBuilder();
    NamedNodeMap attributeMap = element.getAttributes();
    int length = attributeMap.getLength();
    for (int i = 0; i < length; i++) {
        Attr attributeNode = (Attr) attributeMap.item(i);
        String name = attributeNode.getName();
        String value = attributeNode.getValue();
        attributeString.append(" ").append(name).append("=\"").append(value).append("\"");
    }//w w w.jav  a2 s. c om
    return attributeString.toString();
}

From source file:VASSAL.build.module.GlobalOptions.java

public void build(Element e) {
    if (e == null)
        return;/*w  w  w  .j  av a 2 s.c o m*/

    final NamedNodeMap nnm = e.getAttributes();
    for (int i = 0; i < nnm.getLength(); ++i) {
        final Attr att = (Attr) nnm.item(i);
        setAttribute(att.getName(), att.getValue());
    }

    for (Node n = e.getFirstChild(); n != null; n = n.getNextSibling()) {
        if (n.getNodeType() == Node.ELEMENT_NODE) {
            final Element element = (Element) n;
            if ("option".equals(element.getTagName())) { //$NON-NLS-1$
                final String optionName = element.getAttribute("name"); //$NON-NLS-1$
                final String value = Builder.getText(element);
                optionInitialValues.put(optionName, value);
                // Update the Configurer value if it is already registered
                final Configurer config = optionConfigurers.get(optionName);
                if (config != null) {
                    config.setValue(value);
                }
            } else {
                try {
                    final Buildable b = Builder.create(element);
                    b.addTo(this);
                    add(b);
                } catch (IllegalBuildException ex) {
                    ErrorDialog.bug(ex);
                }
            }
        }
    }
}

From source file:yax.test.XmlTest.java

static void dumpnode(Node node, int depth, StringBuilder buf) throws Exception {
    switch (node.getNodeType()) {
    case DOCUMENT_NODE:
        Node root = ((Document) node).getDocumentElement();
        buf.append("<?xml version=\"1.0\"?>\n");
        buf.append("<!DOCTYPE>\n");
        dumpnode(root, 0, buf);//  w w w .jav a 2 s  .c  o  m
        break;
    case ELEMENT_NODE:
        Element enode = (Element) node;
        buf.append(String.format("%s<%s", indent(depth), enode.getTagName()));
        NamedNodeMap attrs = enode.getAttributes();
        if (attrs != null) {
            for (int i = 0; i < attrs.getLength(); i++) {
                Attr attr = (Attr) attrs.item(i);
                buf.append(String.format(" %s=\"%s\"", attr.getName(), attr.getValue()));
            }
        }
        buf.append(">\n");
        NodeList children = enode.getChildNodes();
        if (children != null) {
            for (int i = 0; i < children.getLength(); i++) {
                Node child = children.item(i);
                dumpnode(child, depth + 1, buf);
            }
        }
        buf.append(String.format("%s</%s>", indent(depth), enode.getTagName()));
        break;
    case TEXT_NODE:
        buf.append(String.format("%s|%s|", indent(depth), ((Text) node).getData()));
        break;
    default:
        String typename = node.getNodeName();
        throw new Exception("dumpnode: unexpected node type: " + typename);
    }
}