Example usage for org.w3c.dom Element getElementsByTagName

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

Introduction

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

Prototype

public NodeList getElementsByTagName(String name);

Source Link

Document

Returns a NodeList of all descendant Elements with a given tag name, in document order.

Usage

From source file:io.personium.common.auth.token.TransCellAccessToken.java

/**
 * TransCellAccessToken????.//from  w w  w. j a  v  a 2  s  .c  om
 * @param token 
 * @return TransCellAccessToken(?)
 * @throws AbstractOAuth2Token.TokenParseException ?
 * @throws AbstractOAuth2Token.TokenDsigException ???
 * @throws AbstractOAuth2Token.TokenRootCrtException CA?
 */
public static TransCellAccessToken parse(final String token) throws AbstractOAuth2Token.TokenParseException,
        AbstractOAuth2Token.TokenDsigException, AbstractOAuth2Token.TokenRootCrtException {
    try {
        byte[] samlBytes = PersoniumCoreUtils.decodeBase64Url(token);
        ByteArrayInputStream bais = new ByteArrayInputStream(samlBytes);
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder builder = null;
        try {
            builder = dbf.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            // ????????????
            throw new RuntimeException(e);
        }

        Document doc = builder.parse(bais);

        Element assertion = doc.getDocumentElement();
        Element issuer = (Element) (doc.getElementsByTagName("Issuer").item(0));
        Element subject = (Element) (assertion.getElementsByTagName("Subject").item(0));
        Element subjectNameID = (Element) (subject.getElementsByTagName("NameID").item(0));
        String id = assertion.getAttribute("ID");
        String issuedAtStr = assertion.getAttribute("IssueInstant");

        DateTime dt = new DateTime(issuedAtStr);

        NodeList audienceList = assertion.getElementsByTagName("Audience");
        Element aud1 = (Element) (audienceList.item(0));
        String target = aud1.getTextContent();
        String schema = null;
        if (audienceList.getLength() > 1) {
            Element aud2 = (Element) (audienceList.item(1));
            schema = aud2.getTextContent();
        }

        List<Role> roles = new ArrayList<Role>();
        NodeList attrList = assertion.getElementsByTagName("AttributeValue");
        for (int i = 0; i < attrList.getLength(); i++) {
            Element attv = (Element) (attrList.item(i));
            roles.add(new Role(new URL(attv.getTextContent())));
        }

        NodeList nl = assertion.getElementsByTagName("Signature");
        if (nl.getLength() == 0) {
            throw new TokenParseException("Cannot find Signature element");
        }
        Element signatureElement = (Element) nl.item(0);

        // ???????TokenDsigException??
        // Create a DOMValidateContext and specify a KeySelector
        // and document context.
        X509KeySelector x509KeySelector = new X509KeySelector(issuer.getTextContent());
        DOMValidateContext valContext = new DOMValidateContext(x509KeySelector, signatureElement);

        // Unmarshal the XMLSignature.
        XMLSignature signature;
        try {
            signature = xmlSignatureFactory.unmarshalXMLSignature(valContext);
        } catch (MarshalException e) {
            throw new TokenDsigException(e.getMessage(), e);
        }

        // CA??
        try {
            x509KeySelector.readRoot(x509RootCertificateFileNames);
        } catch (CertificateException e) {
            // CA????????500
            throw new TokenRootCrtException(e.getMessage(), e);
        }

        // Validate the XMLSignature x509.
        boolean coreValidity;
        try {
            coreValidity = signature.validate(valContext);
        } catch (XMLSignatureException e) {
            if (e.getCause().getClass() == new KeySelectorException().getClass()) {
                throw new TokenDsigException(e.getCause().getMessage(), e.getCause());
            }
            throw new TokenDsigException(e.getMessage(), e);
        }

        // http://www.w3.org/TR/xmldsig-core/#sec-CoreValidation

        // Check core validation status.
        if (!coreValidity) {
            // ??
            boolean isDsigValid;
            try {
                isDsigValid = signature.getSignatureValue().validate(valContext);
            } catch (XMLSignatureException e) {
                throw new TokenDsigException(e.getMessage(), e);
            }
            if (!isDsigValid) {
                throw new TokenDsigException("Failed signature validation");
            }

            // 
            Iterator i = signature.getSignedInfo().getReferences().iterator();
            for (int j = 0; i.hasNext(); j++) {
                boolean refValid;
                try {
                    refValid = ((Reference) i.next()).validate(valContext);
                } catch (XMLSignatureException e) {
                    throw new TokenDsigException(e.getMessage(), e);
                }
                if (!refValid) {
                    throw new TokenDsigException("Failed to validate reference [" + j + "]");
                }
            }
            throw new TokenDsigException("Signature failed core validation. unkwnon reason.");
        }
        return new TransCellAccessToken(id, dt.getMillis(), issuer.getTextContent(),
                subjectNameID.getTextContent(), target, roles, schema);
    } catch (UnsupportedEncodingException e) {
        throw new TokenParseException(e.getMessage(), e);
    } catch (SAXException e) {
        throw new TokenParseException(e.getMessage(), e);
    } catch (IOException e) {
        throw new TokenParseException(e.getMessage(), e);
    }
}

From source file:com.meltmedia.cadmium.core.util.WarUtils.java

/**
 * Removes elements by a specified tag name from the xml Element passed in.
 * @param doc The xml Element to remove from.
 * @param tagname The tag name to remove.
 *//*from w  w w  .  j av a  2s  . co m*/
public static void removeNodesByTagName(Element doc, String tagname) {
    NodeList nodes = doc.getElementsByTagName(tagname);
    for (int i = 0; i < nodes.getLength(); i++) {
        Node n = nodes.item(i);
        doc.removeChild(n);
    }
}

From source file:eu.eidas.configuration.ConfigurationReader.java

/**
 * Read configuration.//from  w  ww  . ja  v  a  2 s  .c o m
 *
 * @return the map< string, instance engine>
 *
 * @throws SAMLEngineException the EIDASSAML engine runtime
 *             exception
 */
public static Map<String, InstanceEngine> readConfiguration() throws SAMLEngineException {

    LOGGER.debug("Init reader: " + ENGINE_CONF_FILE);
    final Map<String, InstanceEngine> instanceConfs = new HashMap<String, InstanceEngine>();

    Document document = null;
    // Load configuration file
    final DocumentBuilderFactory factory = EIDASSAMLEngine.newDocumentBuilderFactory();
    DocumentBuilder builder;

    InputStream engineConf = null;
    try {

        factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);

        builder = factory.newDocumentBuilder();

        engineConf = ConfigurationReader.class.getResourceAsStream("/" + ENGINE_CONF_FILE);

        document = builder.parse(engineConf);

        // Read instance
        final NodeList list = document.getElementsByTagName(NODE_INSTANCE);

        for (int indexElem = 0; indexElem < list.getLength(); ++indexElem) {
            final Element element = (Element) list.item(indexElem);

            final InstanceEngine instanceConf = new InstanceEngine();

            // read every configuration.
            final String instanceName = element.getAttribute(NODE_INST_NAME);

            if (StringUtils.isBlank(instanceName)) {
                throw new EIDASSAMLEngineRuntimeException("Error reader instance name.");
            }
            instanceConf.setName(instanceName.trim());

            final NodeList confNodes = element.getElementsByTagName(NODE_CONF);

            for (int indexNode = 0; indexNode < confNodes.getLength(); ++indexNode) {

                final Element configurationNode = (Element) confNodes.item(indexNode);

                final String configurationName = configurationNode.getAttribute(NODE_CONF_NAME);

                if (StringUtils.isBlank(configurationName)) {
                    throw new EIDASSAMLEngineRuntimeException("Error reader configuration name.");
                }

                final ConfigurationEngine confSamlEngine = new ConfigurationEngine();

                // Set configuration name.
                confSamlEngine.setName(configurationName.trim());

                // Read every parameter for this configuration.
                final Map<String, String> parameters = generateParam(configurationNode);

                // Set parameters
                confSamlEngine.setParameters(parameters);

                // Add parameters to the configuration.
                instanceConf.getConfiguration().add(confSamlEngine);
            }

            // Add to the list of configurations.
            instanceConfs.put(element.getAttribute(NODE_INST_NAME), instanceConf);
        }

    } catch (SAXException e) {
        LOGGER.warn("ERROR : init library parser.", e.getMessage());
        LOGGER.debug("ERROR : init library parser.", e);
        throw new SAMLEngineException(e);
    } catch (ParserConfigurationException e) {
        LOGGER.warn("ERROR : parser configuration file xml.");
        LOGGER.debug("ERROR : parser configuration file xml.", e);
        throw new SAMLEngineException(e);
    } catch (IOException e) {
        LOGGER.warn("ERROR : read configuration file.", e.getMessage());
        LOGGER.debug("ERROR : read configuration file.", e);
        throw new SAMLEngineException(e);
    } finally {
        IOUtils.closeQuietly(engineConf);
    }

    return instanceConfs;
}

From source file:moskitt4me.repositoryClient.core.util.RepositoryClientUtil.java

private static String getToolId(TechnicalFragment tf) {

    String type = tf.getType();/*from ww w  .  ja v a  2 s .  co  m*/

    if (type.equals("Others") || type.equals("Internal Tool")) {
        return "";
    }
    if (type.equals("External Tool")) {
        ExternalToolFragment etf = (ExternalToolFragment) tf;
        String fileExtension = etf.getFileExtension();
        if (!fileExtension.startsWith(".")) {
            fileExtension = "." + fileExtension;
        }
        return fileExtension;
    }

    List<IProject> plugins = tf.getPlugins();

    for (IProject plugin : plugins) {
        String pluginLocation = plugin.getLocation().toString();
        String pluginXMLLocation = pluginLocation + "/plugin.xml";

        Document pluginXMLDocument = getDocument(pluginXMLLocation);
        if (pluginXMLDocument != null) {

            String extensionPointId = "";
            String elementId = "";
            String attribute = "";

            if (type.equals("Graphical Editor") || type.equals("Meta-Model")
                    || type.equals("Form-based Editor")) {
                extensionPointId = "org.eclipse.ui.newWizards";
                elementId = "wizard";
                attribute = "id";
            } else if (type.equals("Model transformation")) {
                extensionPointId = "es.cv.gvcase.trmanager.transformation";
                elementId = "transformation";
                attribute = "id";
            } else if (type.equals("Guidance")) {
                extensionPointId = "org.eclipse.epf.authoring.ui.helpcontextprovider";
                elementId = "helpContextProviderDesc";
                attribute = "idContext";
            }

            if (!extensionPointId.equals("")) {
                NodeList extension = pluginXMLDocument.getElementsByTagName("extension");
                int length = extension.getLength();
                for (int i = 0; i < length; i++) {
                    Node extensionNode = extension.item(i);
                    if (extensionNode.getAttributes().getNamedItem("point").getNodeValue()
                            .equals(extensionPointId) && extensionNode.getNodeType() == Node.ELEMENT_NODE) {
                        Element extensionElement = (Element) extensionNode;
                        NodeList elements = extensionElement.getElementsByTagName(elementId);
                        if (elements.getLength() > 0) {
                            Node element = elements.item(0);
                            String attValue = element.getAttributes().getNamedItem(attribute).getNodeValue();
                            if (type.equals("Guidance")) {
                                return plugin.getName() + "." + attValue;
                            } else {
                                return attValue;
                            }
                        }
                    }
                }
            }
        }
    }

    return "";
}

From source file:eu.eidas.auth.engine.configuration.dom.DOMConfigurationParser.java

@Nonnull
private static InstanceEntry parseInstanceEntry(@Nonnull String configurationFileName,
        @Nonnull Element instanceTag) throws SamlEngineConfigurationException {
    // read every configuration.
    String instanceName = instanceTag.getAttribute(InstanceTag.Attribute.NAME);

    if (StringUtils.isBlank(instanceName)) {
        String message = "SAML engine configuration file \"" + configurationFileName
                + "\" contains a blank instance name";
        LOG.error(message);//from w  w  w .  ja  v a 2 s  .  co m
        throw new SamlEngineConfigurationException(message);
    }
    instanceName = instanceName.trim();

    NodeList configurationTags = instanceTag.getElementsByTagName(InstanceTag.ConfigurationTag.TAG_NAME);

    Map<String, ConfigurationEntry> configurationEntries = new LinkedHashMap<>();

    for (int i = 0, n = configurationTags.getLength(); i < n; i++) {
        Element configurationTag = (Element) configurationTags.item(i);

        ConfigurationEntry configurationEntry = parseConfigurationEntry(configurationFileName, instanceName,
                configurationTag);

        ConfigurationEntry previous = configurationEntries.put(configurationEntry.getName(),
                configurationEntry);
        if (null != previous) {
            String message = "Duplicate configuration entry names \"" + configurationEntry.getName()
                    + "\" in SAML engine configuration file \"" + configurationFileName + "\"";
            LOG.error(message);
            throw new SamlEngineConfigurationException(message);
        }
    }

    return new InstanceEntry(instanceName, ImmutableMap.copyOf(configurationEntries));
}

From source file:Main.java

public static String argumentTagToCmd(Element jobElement) {
    //        NodeList nl = jobElement.getChildNodes();
    //        for(int i=0;i<nl.getLength();i++)
    //        {/*from w  ww. ja v a 2  s.  c  o m*/
    //            System.out.println(nl.item(i).getTextContent());
    //        }
    //        System.exit(1);

    //        Node n = jobElement.getElementsByTagName("argument").item(0);
    String taskName = jobElement.getAttribute("name");
    //        String nodeString = nodeToString(n);
    //        nodeString = nodeString.replace("<"+n.getNodeName()+">", "");
    //        nodeString = nodeString.replace("</"+n.getNodeName()+">", "");
    //        nodeString = nodeString.trim();
    //        String[] lines = nodeString.split("\n");
    StringBuilder cmd = new StringBuilder(taskName).append(";");

    NodeList argList = jobElement.getElementsByTagName("argument").item(0).getChildNodes();
    for (int i = 0; i < argList.getLength(); i++) {
        Node c = argList.item(i);
        String cStr;
        if (c.getNodeName().equals("file")) {
            Element ec = (Element) c;
            cStr = (ec.getAttribute("name")).trim();
            if (!cStr.isEmpty()) {
                cmd.append(cStr).append(";");
            }
        } else {
            cStr = (c.getTextContent().trim());
            String[] cStrs = cStr.split("\\s+");
            for (String cs : cStrs) {
                cs = cs.trim();
                if (!cs.isEmpty()) {
                    cmd.append(cs).append(";");
                }
            }
        }

    }

    cmd.replace(cmd.length() - 1, cmd.length(), "");
    return cmd.toString();
}

From source file:org.opencastproject.analytics.impl.AnalyticsServiceImpl.java

/**
 * Get the value of an xml tag. /*from   w ww .j  av a2  s . c  om*/
 * 
 * @param sTag
 *          The xml tag to look for and get the first result.
 * @param eElement
 *          The element to check for the tag.
 * @return The value associated with the xml tag.
 */
private static String getTagValue(String sTag, Element eElement) {
    Node nodeValue = eElement.getElementsByTagName(sTag).item(0);
    return nodeValue.getFirstChild().getNodeValue();
}

From source file:canreg.client.dataentry.Convert.java

public static boolean convertDictionary(
        canreg.client.gui.management.CanReg4MigrationInternalFrame.MigrationTask task, String filepath,
        String dictionaryfile, String regcode) {
    Connection conn = null;/*from w  ww  .j a  v  a 2 s.  c o m*/
    Statement stmt = null;
    ResultSet rs = null;
    boolean success = false;

    String xml = Globals.CANREG_SERVER_SYSTEM_CONFIG_FOLDER + Globals.FILE_SEPARATOR + regcode + ".xml";
    String dic = filepath + Globals.FILE_SEPARATOR + regcode + ".txt";

    File xmlfile = new File(xml);
    File dicfile = new File(dic);

    try {
        String query = "SELECT * FROM \"" + dictionaryfile + "\"";
        conn = DriverManager.getConnection("jdbc:paradox:///" + filepath.replaceAll("\\\\", "/"));
        stmt = conn.createStatement();
        rs = stmt.executeQuery(query);

        txt_fw = new FileWriter(dicfile);
        txt_bw = new BufferedWriter(txt_fw);

        if (xmlfile.exists()) {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            // Use the factory to create a builder
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(xmlfile);
            doc.getDocumentElement().normalize();
            // Get a list of all elements in the document
            debugOut("Migrating dictionary " + dictionaryfile);
            NodeList nlist = doc.getElementsByTagName("ns3:dictionary");
            for (int i = 0; i < nlist.getLength(); i++) {
                Node nNode = nlist.item(i);
                if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                    Element eElement = (Element) nNode;
                    int dicId = Integer.parseInt(
                            eElement.getElementsByTagName("ns3:dictionary_id").item(0).getTextContent());
                    String dicName = eElement.getElementsByTagName("ns3:name").item(0).getTextContent();
                    String dicType = eElement.getElementsByTagName("ns3:type").item(0).getTextContent();
                    String dic_head = "#" + dicId + " ----" + dicName + "\n";
                    txt_bw.write(dic_head);
                    // Processing dictionary child nodes.
                    processChildNodes(task, dicId, dicType, filepath, dictionaryfile);
                } //if node ends
            } //for ends
        } //file if ends
        else {
            debugOut("Files not found");
        }
        txt_bw.close();
        success = true;
    } catch (SQLException ex) {
        Logger.getLogger(Convert.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(Convert.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NumberFormatException ex) {
        Logger.getLogger(Convert.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ParserConfigurationException ex) {
        Logger.getLogger(Convert.class.getName()).log(Level.SEVERE, null, ex);
    } catch (DOMException ex) {
        Logger.getLogger(Convert.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SAXException ex) {
        Logger.getLogger(Convert.class.getName()).log(Level.SEVERE, null, ex);
    }
    return success;
}

From source file:eu.elf.license.LicenseParser.java

/**
 * Creates LicenseConcludeResponseObject from the concludeLicense operation's response string
 * /*from w  w w .  j  a  v  a2  s. c o  m*/
 * @param response
 * @return
 * @throws Exception
 */
public static LicenseConcludeResponseObject parseConcludeLicenseResponse(String response) throws Exception {
    LicenseConcludeResponseObject lcro = new LicenseConcludeResponseObject();

    try {
        Document xmlDoc = LicenseParser.createXMLDocumentFromString(response);
        NodeList LicenseReferenceNL = xmlDoc.getElementsByTagNameNS("http://www.52north.org/license/0.3.2",
                "LicenseReference");

        for (int i = 0; i < LicenseReferenceNL.getLength(); i++) {
            Element attributeStatementElement = (Element) LicenseReferenceNL.item(i);

            NodeList attributeElementList = attributeStatementElement
                    .getElementsByTagNameNS("urn:oasis:names:tc:SAML:2.0:assertion", "Attribute");

            for (int j = 0; j < attributeElementList.getLength(); j++) {
                Element attributeElement = (Element) attributeElementList.item(j);
                Element AttributeValueElement = (Element) attributeElement
                        .getElementsByTagName("AttributeValue").item(0);

                NamedNodeMap licenseReferenceElementAttributeMap = attributeElement.getAttributes();

                for (int k = 0; k < licenseReferenceElementAttributeMap.getLength(); k++) {
                    Attr attrs = (Attr) licenseReferenceElementAttributeMap.item(k);

                    if (attrs.getNodeName().equals("Name")) {
                        if (attrs.getNodeValue().equals("urn:opengeospatial:ows4:geodrm:NotOnOrAfter")) {
                            lcro.setValidTo(AttributeValueElement.getTextContent());
                        }
                        if (attrs.getNodeValue().equals("urn:opengeospatial:ows4:geodrm:ProductID")) {
                            lcro.setProductId(AttributeValueElement.getTextContent());
                        }
                        if (attrs.getNodeValue().equals("urn:opengeospatial:ows4:geodrm:LicenseID")) {
                            lcro.setLicenseId(AttributeValueElement.getTextContent());
                        }
                    }

                }

            }

        }

    } catch (Exception e) {
        throw e;
    }

    return lcro;
}

From source file:com.krawler.esp.handlers.basecampHandler.java

public static String importUserFromBaseCamp(javax.servlet.http.HttpServletRequest request) {
    String result = "";
    JSONObject res = new JSONObject();
    String errorString = "";
    try {// w ww.  j a  v  a2  s  .  com
        res.put("error", "%s");
        String docid = java.util.UUID.randomUUID().toString();
        File f1 = getfile(request, docid);

        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
        //                Document doc = docBuilder.parse (new File("/home/mosin/krawlercom-20081201125009.xml"));
        Document doc = docBuilder.parse(f1);
        doc.getDocumentElement().normalize();
        NodeList firmInfo = doc.getElementsByTagName("firm");
        NodeList peopel = (getElementFromNodeList(firmInfo)).getElementsByTagName("people");
        NodeList personList = (getElementFromNodeList(peopel)).getElementsByTagName("person");
        int len = personList.getLength();
        for (int i = 0; i < len; i++) {
            if (checkNodeType(personList.item(i))) {
                Element person = (Element) personList.item(i);
                JSONObject temp = new JSONObject();
                temp.put("firstName", person.getElementsByTagName("first-name").item(0).getChildNodes().item(0)
                        .getNodeValue());
                temp.put("lastName", person.getElementsByTagName("last-name").item(0).getChildNodes().item(0)
                        .getNodeValue());
                temp.put("id",
                        person.getElementsByTagName("id").item(0).getChildNodes().item(0).getNodeValue());
                try {
                    temp.put("username", person.getElementsByTagName("user-name").item(0).getChildNodes()
                            .item(0).getNodeValue());
                } catch (Exception e) {
                    temp.put("username", person.getElementsByTagName("first-name").item(0).getChildNodes()
                            .item(0).getNodeValue());
                }
                temp.put("email", person.getElementsByTagName("email-address").item(0).getChildNodes().item(0)
                        .getNodeValue());
                res.append("data", temp);
            }
        }

        NodeList projects = doc.getElementsByTagName("projects");
        NodeList projectList = (getElementFromNodeList(projects)).getElementsByTagName("project");
        len = projectList.getLength();
        for (int j = 0; j < len; j++) {
            if (checkNodeType(projectList.item(j))) {
                Element project = (Element) projectList.item(j);
                JSONObject temp = new JSONObject();
                temp.put("projectname",
                        project.getElementsByTagName("name").item(0).getChildNodes().item(0).getNodeValue());
                temp.put("projectid",
                        project.getElementsByTagName("id").item(0).getChildNodes().item(0).getNodeValue());
                temp.put("status",
                        project.getElementsByTagName("status").item(0).getChildNodes().item(0).getNodeValue());
                res.append("projdata", temp);
            }
        }
        res.put("docid", docid);
        result = res.toString();
    } catch (Exception ex) {
        errorString = MessageSourceProxy.getMessage("", null, request);
        result = res.toString();
        KrawlerLog.op.warn("Problem Occured while importing project from base camp from " + ex.toString());
    } finally {

        result = String.format(result, errorString);
        return result;
    }
}