Example usage for org.w3c.dom NamedNodeMap getNamedItem

List of usage examples for org.w3c.dom NamedNodeMap getNamedItem

Introduction

In this page you can find the example usage for org.w3c.dom NamedNodeMap getNamedItem.

Prototype

public Node getNamedItem(String name);

Source Link

Document

Retrieves a node specified by name.

Usage

From source file:com.amalto.core.history.accessor.AttributeAccessor.java

private Node getAttribute() {
    Node parentNode = parent.getNode();
    if (parentNode == null) {
        throw new IllegalStateException(
                "Could not find a parent node in document (check if document has a root element)."); //$NON-NLS-1$
    }//from   w w w. j a  v  a 2  s. co m
    NamedNodeMap attributes = parentNode.getAttributes();
    if (attributes == null) {
        throw new IllegalStateException("Could not find attributes on parent node."); //$NON-NLS-1$
    }

    QName qName = getQName(document.asDOM());
    Node attribute = attributes.getNamedItemNS(qName.getNamespaceURI(), qName.getLocalPart());
    if (attribute == null) {
        // Look up with namespace didn't work, falls back to standard getNamedItem
        attribute = attributes.getNamedItem(qName.getLocalPart());
    }
    return attribute;
}

From source file:org.ambraproject.article.service.FetchArticleServiceImpl.java

/**
 * Get references for a given article//  w w w . j a  va2s.  c o m
 * @param doc article xml
 * @return references
 */
public ArrayList<CitationReference> getReferences(Document doc) {
    ArrayList<CitationReference> list = new ArrayList<CitationReference>();

    if (doc == null) {
        return list;
    }

    try {
        XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath();
        XPathExpression expr = xpath.compile("//back/ref-list[title='References']/ref");
        Object result = expr.evaluate(doc, XPathConstants.NODESET);

        NodeList refList = (NodeList) result;

        if (refList.getLength() == 0) {
            expr = xpath.compile("//back/ref-list/ref");
            result = expr.evaluate(doc, XPathConstants.NODESET);
            refList = (NodeList) result;
        }

        XPathExpression typeExpr = xpath.compile("//citation | //nlm-citation");
        XPathExpression titleExpr = xpath.compile("//article-title");
        XPathExpression authorsExpr = xpath.compile("//person-group[@person-group-type='author']/name");
        XPathExpression journalExpr = xpath.compile("//source");
        XPathExpression volumeExpr = xpath.compile("//volume");
        XPathExpression numberExpr = xpath.compile("//label");
        XPathExpression fPageExpr = xpath.compile("//fpage");
        XPathExpression lPageExpr = xpath.compile("//lpage");
        XPathExpression yearExpr = xpath.compile("//year");
        XPathExpression publisherExpr = xpath.compile("//publisher-name");

        for (int i = 0; i < refList.getLength(); i++) {

            Node refNode = refList.item(i);
            CitationReference citation = new CitationReference();

            DocumentFragment df = doc.createDocumentFragment();
            df.appendChild(refNode);

            // citation type
            Object resultObj = typeExpr.evaluate(df, XPathConstants.NODE);
            Node resultNode = (Node) resultObj;
            if (resultNode != null) {
                NamedNodeMap nnm = resultNode.getAttributes();
                Node nnmNode = nnm.getNamedItem("citation-type");
                // some old articles do not have this attribute
                if (nnmNode != null) {
                    citation.setCitationType(nnmNode.getTextContent());
                }
            }

            // title
            resultObj = titleExpr.evaluate(df, XPathConstants.NODE);
            resultNode = (Node) resultObj;
            if (resultNode != null) {
                citation.setTitle(resultNode.getTextContent());
            }

            // authors
            resultObj = authorsExpr.evaluate(df, XPathConstants.NODESET);
            NodeList resultNodeList = (NodeList) resultObj;
            ArrayList<String> authors = new ArrayList<String>();
            for (int j = 0; j < resultNodeList.getLength(); j++) {
                Node nameNode = resultNodeList.item(j);
                NodeList namePartList = nameNode.getChildNodes();
                String surName = "";
                String givenName = "";
                for (int k = 0; k < namePartList.getLength(); k++) {
                    Node namePartNode = namePartList.item(k);
                    if (namePartNode.getNodeName().equals("surname")) {
                        surName = namePartNode.getTextContent();
                    } else if (namePartNode.getNodeName().equals("given-names")) {
                        givenName = namePartNode.getTextContent();
                    }
                }
                authors.add(givenName + " " + surName);
            }

            citation.setAuthors(authors);

            // journal title
            resultObj = journalExpr.evaluate(df, XPathConstants.NODE);
            resultNode = (Node) resultObj;
            if (resultNode != null) {
                citation.setJournalTitle(resultNode.getTextContent());
            }

            // volume
            resultObj = volumeExpr.evaluate(df, XPathConstants.NODE);
            resultNode = (Node) resultObj;
            if (resultNode != null) {
                citation.setVolume(resultNode.getTextContent());
            }

            // citation number
            resultObj = numberExpr.evaluate(df, XPathConstants.NODE);
            resultNode = (Node) resultObj;
            if (resultNode != null) {
                citation.setNumber(resultNode.getTextContent());
            }

            // citation pages
            String firstPage = null;
            String lastPage = null;
            resultObj = fPageExpr.evaluate(df, XPathConstants.NODE);
            resultNode = (Node) resultObj;
            if (resultNode != null) {
                firstPage = resultNode.getTextContent();
            }

            resultObj = lPageExpr.evaluate(df, XPathConstants.NODE);
            resultNode = (Node) resultObj;
            if (resultNode != null) {
                lastPage = resultNode.getTextContent();
            }

            if (firstPage != null) {
                if (lastPage != null) {
                    citation.setPages(firstPage + "-" + lastPage);
                } else {
                    citation.setPages(firstPage);
                }
            }

            // citation year
            resultObj = yearExpr.evaluate(df, XPathConstants.NODE);
            resultNode = (Node) resultObj;
            if (resultNode != null) {
                citation.setYear(resultNode.getTextContent());
            }

            // citation publisher
            resultObj = publisherExpr.evaluate(df, XPathConstants.NODE);
            resultNode = (Node) resultObj;
            if (resultNode != null) {
                citation.setPublisher(resultNode.getTextContent());
            }

            list.add(citation);
        }

    } catch (Exception e) {
        log.error("Error occurred while gathering the citation references.", e);
    }

    return list;

}

From source file:com.stratelia.webactiv.util.XMLConfigurationStore.java

/**
 * This method returns the value of an attribute of a given node. If the attribute cannot be found
 * of if the node is null, this method returns null.
 *
 * @param n the node where the attribute is stored
 * @param attributeName the name of the attribute. Case sensitive.
 *//*from   w w w .j  a v  a 2s  . c o m*/
public String getAttributeValue(Node n, String attributeName) {
    if (n == null) {
        return (null);
    }
    NamedNodeMap amap = n.getAttributes();
    if (amap != null) {
        Node n2 = amap.getNamedItem(attributeName);
        if (n2 == null) {
            return (null);
        }
        String v = n2.getNodeValue();
        return (v);
    } else {
        return (null);
    }
}

From source file:it.unibo.alchemist.language.EnvironmentBuilder.java

private Molecule buildMolecule(final Node son, final Map<String, Object> env) throws InstantiationException,
        IllegalAccessException, InvocationTargetException, ClassNotFoundException {
    final NamedNodeMap attributes = son.getAttributes();
    String type = attributes.getNamedItem(TYPE).getNodeValue();
    type = type.contains(".") ? type : "it.unibo.alchemist.model.implementations.molecules." + type;
    return coreOperations(env, son, type, random);
}

From source file:it.unibo.alchemist.language.EnvironmentBuilder.java

private void setConcentration(final Node son) throws ClassNotFoundException {
    final NamedNodeMap attributes = son.getAttributes();
    String type = attributes.getNamedItem(TYPE).getNodeValue();
    type = type.contains(".") ? type : "it.unibo.alchemist.model.implementations.concentrations." + type;
    concentrationClass = Class.forName(type);
    L.debug("Concentration type set to " + concentrationClass);
}

From source file:it.unibo.alchemist.language.EnvironmentBuilder.java

private void setPosition(final Node son) throws ClassNotFoundException {
    final NamedNodeMap attributes = son.getAttributes();
    String type = attributes.getNamedItem(TYPE).getNodeValue();
    if (!type.contains(".")) {
        type = "it.unibo.alchemist.model.implementations.positions." + type;
    }/*  w  w w .  j a  v a  2 s  . c  o m*/
    positionClass = Class.forName(type);
    L.debug("Position type set to " + positionClass);
}

From source file:com.blackbear.flatworm.config.impl.DefaultConfigurationReaderImpl.java

/**
 * Retrieve an attribute by name as a {@link Node}.
 *
 * @param node The node that may contain the attribute.
 * @param name The name of the attribute.
 * @return The attribute as a {@link Node} instance if found and {@code null} if not.
 *//*  w w  w.j  a  va2  s. c o  m*/
protected Node getAttributeNamed(Node node, String name) {
    NamedNodeMap map = node.getAttributes();
    return map.getNamedItem(name);
}

From source file:br.org.indt.ndg.common.ResultParser.java

private ResultXml processResult() {
    TreeMap<Integer, Category> categories;
    ResultXml result = new ResultXml();
    result.setXmldoc(document);/* w w w  . ja  v a 2 s .  c o  m*/

    logger.info("loading result attributes");
    NodeList nodeSurvey = document.getElementsByTagName("result");
    NamedNodeMap resultAttr = nodeSurvey.item(0).getAttributes();
    result.setResultId(resultAttr.getNamedItem("r_id").getNodeValue());
    result.setSurveyId(resultAttr.getNamedItem("s_id").getNodeValue());
    result.setImei(resultAttr.getNamedItem("u_id").getNodeValue());
    result.setTime(resultAttr.getNamedItem("time").getNodeValue());

    NodeList resultChild = nodeSurvey.item(0).getChildNodes();
    for (int i = 0; i < resultChild.getLength(); i++) {
        if (resultChild.item(i).getNodeName().equals("title")) {
            result.setTitle(resultChild.item(i).getTextContent());
        } else if (resultChild.item(i).getNodeName().equals("latitude")) {
            result.setLatitude(resultChild.item(i).getTextContent());
        } else if (resultChild.item(i).getNodeName().equals("longitude")) {
            result.setLongitude(resultChild.item(i).getTextContent());
        }
    }

    logger.info("loading categories attributes");
    categories = new TreeMap<Integer, Category>();
    NodeList nodesCategory = document.getElementsByTagName("category");
    int countCategory = nodesCategory.getLength();
    for (int c = 0; c < countCategory; ++c) {
        Category category = new Category();
        NamedNodeMap categoryAttr = nodesCategory.item(c).getAttributes();
        category.setId(Integer.parseInt(categoryAttr.getNamedItem("id").getNodeValue()));
        category.setName(categoryAttr.getNamedItem("name").getNodeValue());
        categories.put(category.getId(), category);
    }

    logger.info("loading answers attributes");
    NodeList nodesAnswer = document.getElementsByTagName("answer");
    int countAnswer = nodesAnswer.getLength();
    logger.info("countAnswer = " + nodesAnswer);
    for (int a = 0; a < countAnswer; ++a) {
        NamedNodeMap answerAttr = nodesAnswer.item(a).getAttributes();
        Field answer = new Field();
        String answerId = answerAttr.getNamedItem("id").getNodeValue();
        answer.setId(Integer.parseInt(answerId));
        String answerType = answerAttr.getNamedItem("type").getNodeValue();
        answer.setXmlType(answerType);
        if (answer.getXmlType().equals("_choice")) {
            NodeList answerChild = nodesAnswer.item(a).getChildNodes();
            Choice choice = new Choice();
            for (int i = 0; i < answerChild.getLength(); i++) {
                if (answerChild.item(i).getNodeName().equals("item")) {
                    try {
                        int index = Integer.parseInt(answerChild.item(i).getTextContent());
                        Item item = new Item();
                        item.setIndex(index);
                        item.setOtr("0");
                        choice.addItem(item);
                    } catch (Exception e) {
                        logger.error("Choice with <item></item>, must have a value " + e);
                    }
                } else if (answerChild.item(i).getNodeName().equals("other")) {
                    try {
                        NamedNodeMap itemAttr = answerChild.item(i).getAttributes();
                        int index = Integer.parseInt(itemAttr.getNamedItem("index").getNodeValue());
                        String value = answerChild.item(i).getTextContent();
                        Item item = new Item();
                        item.setIndex(index);
                        item.setValue(value);
                        item.setOtr("1");
                        choice.addItem(item);
                    } catch (Exception e) {
                        logger.error("Other with <index></index>, must have a value " + e);
                    }
                }
            }
            answer.setChoice(choice);
        } else {
            String value = null;

            try {
                Node nodeAnswerItem = nodesAnswer.item(a);
                if (nodeAnswerItem != null) {
                    NodeList nodeList = nodeAnswerItem.getChildNodes();
                    Node nodeAnswerItemItem = nodeList.item(1);
                    value = nodeAnswerItemItem.getTextContent();
                    //                     value = nodesAnswer.item(a).getChildNodes().item(1).getTextContent();
                } else {
                    value = "";
                }
            } catch (Exception e) {
                value = "";
            }
            answer.setValue(value);
            logger.info("Value = " + value);
        }
        String categoryName = nodesAnswer.item(a).getParentNode().getAttributes().getNamedItem("name")
                .getNodeValue();
        int categoryId = Integer.parseInt(
                nodesAnswer.item(a).getParentNode().getAttributes().getNamedItem("id").getNodeValue());
        logger.debug(categoryName + " | " + answerId + " | " + answerType);
        Category category = categories.get(categoryId);
        logger.debug("category name: " + category.getName());
        answer.setCategoryId(categoryId);
        category.addField(answer);
        categories.put(categoryId, category);
    }
    result.setCategories(categories);
    return result;
}

From source file:com.google.enterprise.connector.salesforce.BaseTraversalManager.java

/**
 * Converts the <document></document> xml into a BaseSimpleDocument object
 * that we can send into a documentList object that ultimately gets returned
 * to the connector-manager//from  ww w  .  j a  va  2s  . c om
 * 
 * @param inxml
 *            the xml form of and individual <document></document> object
 */

private BaseSimpleDocument convertXMLtoBaseDocument(Document doc) {
    try {

        HashMap hm_spi = new HashMap();
        HashMap hm_meta_tags = new HashMap();
        Map props = new HashMap();
        String content_value = "";

        TransformerFactory transfac = TransformerFactory.newInstance();
        Transformer trans = transfac.newTransformer();
        trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        trans.setOutputProperty(OutputKeys.INDENT, "yes");
        trans.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

        // TODO: figure out why the initial doc passed in to the method
        // doesn't have the stylesheet 'fully' applied
        // this is why we do the conversion back and forth below
        // because for some reason the doc->string->doc has the stylesheet
        // applied.
        String sdoc = Util.XMLDoctoString(doc);
        logger.log(Level.FINEST, "About to convert STORE XML to BaseDocument " + sdoc);
        doc = Util.XMLStringtoDoc(sdoc);

        NodeList nl_document = doc.getElementsByTagName("document");

        Node ndoc = nl_document.item(0);

        NodeList nl_doc_child = ndoc.getChildNodes();

        for (int j = 0; j < nl_doc_child.getLength(); j++) {
            Node cnode = nl_doc_child.item(j);
            String doc_child_node_name = cnode.getNodeName();

            if (doc_child_node_name.equalsIgnoreCase("spiheaders")) {
                NodeList nl_spi = cnode.getChildNodes();
                for (int k = 0; k < nl_spi.getLength(); k++) {
                    Node n_spi = nl_spi.item(k);
                    if (n_spi.getNodeType() == Node.ELEMENT_NODE) {
                        String spi_name = n_spi.getAttributes().getNamedItem("name").getNodeValue();
                        String spi_value = "";
                        if (n_spi.getFirstChild() != null) {
                            spi_value = n_spi.getFirstChild().getNodeValue();
                            logger.log(Level.FINEST, "Adding SPI " + spi_name + " " + spi_value);
                        }
                        hm_spi.put(spi_name, spi_value);
                    }
                }
            }

            if (doc_child_node_name.equalsIgnoreCase("metadata")) {
                NodeList nl_meta = cnode.getChildNodes();
                for (int k = 0; k < nl_meta.getLength(); k++) {
                    Node n_meta = nl_meta.item(k);
                    if (n_meta.getNodeType() == Node.ELEMENT_NODE) {
                        String meta_name = n_meta.getAttributes().getNamedItem("name").getNodeValue();
                        String meta_value = "";
                        if (n_meta.getFirstChild() != null) {
                            meta_value = n_meta.getFirstChild().getNodeValue();
                            logger.log(Level.FINEST, "Adding METATAG " + meta_name + " " + meta_value);
                        }
                        hm_meta_tags.put(meta_name, meta_value);
                    }
                }
            }

            if (doc_child_node_name.equalsIgnoreCase("content")) {
                content_value = cnode.getChildNodes().item(0).getNodeValue();
                String encoding_type = "";
                NamedNodeMap attribs = cnode.getAttributes();
                if (attribs.getLength() > 0) {
                    Node attrib = attribs.getNamedItem("encoding");
                    if (attrib != null)
                        encoding_type = attrib.getNodeValue();

                    if (encoding_type.equalsIgnoreCase("base64")
                            || encoding_type.equalsIgnoreCase("base64binary")) {
                        byte[] b = org.apache.commons.codec.binary.Base64
                                .decodeBase64(content_value.getBytes());
                        ByteArrayInputStream input1 = new ByteArrayInputStream(b);
                        logger.log(Level.FINEST, "Adding base64 encoded CONTENT " + content_value);
                        props.put(SpiConstants.PROPNAME_CONTENT, input1);
                    } else {
                        logger.log(Level.FINEST, "Adding Text/HTML CONTENT " + content_value);
                        props.put(SpiConstants.PROPNAME_CONTENT, content_value);
                    }
                } else {
                    logger.log(Level.FINEST, "Adding default Text/HTML CONTENT " + content_value);
                    props.put(SpiConstants.PROPNAME_CONTENT, content_value);
                }
            }
        }

        // the hashmap holding the spi headers
        Iterator itr_spi = hm_spi.keySet().iterator();

        while (itr_spi.hasNext()) {
            String key = (String) itr_spi.next();
            String value = (String) hm_spi.get(key);

            if (key.equals("DEFAULT_MIMETYPE"))
                props.put(SpiConstants.DEFAULT_MIMETYPE, value);

            if (key.equals("PROPNAME_ACTION"))
                props.put(SpiConstants.PROPNAME_ACTION, value);

            if (key.equals("PROPNAME_CONTENTURL"))
                props.put(SpiConstants.PROPNAME_CONTENTURL, value);

            if (key.equals("PROPNAME_DISPLAYURL"))
                props.put(SpiConstants.PROPNAME_DISPLAYURL, value);

            if (key.equals("PROPNAME_DOCID"))
                props.put(SpiConstants.PROPNAME_DOCID, value);

            if (key.equals("PROPNAME_ISPUBLIC"))
                props.put(SpiConstants.PROPNAME_ISPUBLIC, value);

            if (key.equals("PROPNAME_LASTMODIFIED"))
                props.put(SpiConstants.PROPNAME_LASTMODIFIED, value);

            if (key.equals("PROPNAME_MIMETYPE"))
                props.put(SpiConstants.PROPNAME_MIMETYPE, value);

            // if (key.equals("PROPNAME_SEARCHURL"))
            // props.put(SpiConstants.PROPNAME_SEARCHURL, value);

            // if (key.equals("PROPNAME_SECURITYTOKEN"))
            // props.put(SpiConstants.PROPNAME_SECURITYTOKEN, value);

        }

        // hashmap holding the custom metatags
        Iterator itr_meta = hm_meta_tags.keySet().iterator();

        while (itr_meta.hasNext()) {
            String key = (String) itr_meta.next();
            String value = (String) hm_meta_tags.get(key);
            props.put(key, value);
        }

        BaseSimpleDocument bsd = createSimpleDocument(new Date(), props);
        return bsd;
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "Error " + ex);
    }
    return null;

}

From source file:it.unibo.alchemist.language.EnvironmentBuilder.java

private void setRandom(final Node son, final Map<String, Object> env) throws InstantiationException,
        IllegalAccessException, InvocationTargetException, ClassNotFoundException {
    final NamedNodeMap attributes = son.getAttributes();
    String type = attributes.getNamedItem(TYPE).getNodeValue();
    String seed = attributes.getNamedItem("seed").getNodeValue();
    /*/* w  w w.ja v  a 2s  .com*/
     * This workaround ensures compatibility with pre-PVeStA integration
     * XMLs generated with the SAPERE DSL.
     */
    if (type.equals("cern.jet.random.engine.MersenneTwister")) {
        type = "org.apache.commons.math3.random.MersenneTwister";
    }
    type = type.contains(".") ? type : "org.apache.commons.math3.random." + type;
    seed = seed.equalsIgnoreCase("RANDOM") ? Integer.toString(internalRandom.nextInt()) : seed;
    final List<String> params = new ArrayList<>(1);
    params.add(seed);
    final Class<?> randomEngineClass = Class.forName(type);
    final List<Constructor<RandomGenerator>> consList = unsafeExtractConstructors(randomEngineClass);
    random = tryToBuild(consList, params, env, null);
    this.seed = Integer.parseInt(seed);
}