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:org.bibsonomy.scraper.generic.UnAPIScraper.java

/** Extracts the "href" attribute from "link" tags whose "rel" attribute equals "unapi-server".
 * /*  w  w w  .  j ava 2s . co m*/
 * @param document
 * @return The href attribute of the proper link-tag or <code>null</code> if it could not be found.
 */
private String getApiHref(final Document document) {
    final NodeList elementsByTagName = document.getElementsByTagName("link");
    for (int i = 0; i < elementsByTagName.getLength(); i++) {
        final Node node = elementsByTagName.item(i);
        final NamedNodeMap attributes = node.getAttributes();
        final Node relAttribute = attributes.getNamedItem("rel");
        if (relAttribute != null && "unapi-server".equals(relAttribute.getNodeValue())) {
            /*
             * link to server found -> extract href
             */
            final Node href = attributes.getNamedItem("href");
            if (href != null) {
                return href.getNodeValue();
            }
        }
    }
    return null;
}

From source file:org.bibsonomy.scraper.generic.UnAPIScraper.java

/** Extracts the "title" attribute from the first (!) "abbr" tag whose "class" attribute equals "unapi-id".
 * // w  ww. ja  v a  2  s  . c  o m
 * @param document
 * @return The "title" attribute of the proper abbr-tag or <code>null</code> if it could not be found.
 * 
 */
private String getRecordIdentifier(final Document document) {
    /*
     * debug
     */
    final NodeList abbrTags = document.getElementsByTagName("abbr");
    log.debug("found " + abbrTags.getLength() + " abbr nodes.");
    for (int i = 0; i < abbrTags.getLength(); i++) {
        final Node node = abbrTags.item(i);
        final NamedNodeMap attributes = node.getAttributes();
        final Node classAttribute = attributes.getNamedItem("class");
        if (classAttribute != null && "unapi-id".equals(classAttribute.getNodeValue())) {
            /*
             * record found -> extract id
             */
            final Node title = attributes.getNamedItem("title");
            if (title != null) {
                return title.getNodeValue();
            }
        }
    }
    return null;

}

From source file:org.broad.igv.cbio.GeneNetwork.java

/**
 * Load graphml data from provide path./*from  w w w .  j  ava2  s  .c o  m*/
 *
 * @param path
 * @throws IOException If something went wrong loading data.
 *                     Note we wrap other exception types in this.
 */
public int loadNetwork(String path) throws IOException {
    String error = null;
    int numNodes = -1;
    try {
        InputStream cbioStream = ParsingUtils.openInputStreamGZ(new ResourceLocator(path));
        this.sourcePath = path;
        Document document = Utilities.createDOMDocumentFromXmlStream(cbioStream);

        //Cache the file
        if (HttpUtils.isRemoteURL(path)) {
            File cacheFile = getCachedFile(path);
            try {
                this.exportDocument(document, cacheFile.getAbsolutePath());
            } catch (IOException e) {
                //No biggy, we just don't cache the file
                log.error("Error caching file: " + e);
                cacheFile.delete();
            }
            cacheFile.deleteOnExit();
        }

        this.origDocument = document;

        //Read schema from top and save it
        addToSchema(document.getElementsByTagName("key"));

        graphAttr = document.getElementsByTagName("graph").item(0).getAttributes();

        NodeList nodes = document.getElementsByTagName(NODE_TAG);
        //Generate the graph itself. First add the nodes, then the edges
        int docNodes = nodes.getLength();
        nodeTable = new HashMap<String, Node>(docNodes);
        for (int nn = 0; nn < docNodes; nn++) {
            Node node = nodes.item(nn);
            String label = node.getAttributes().getNamedItem("id").getTextContent();
            nodeTable.put(label, node);
            this.addVertex(node);
        }

        NodeList edges = document.getElementsByTagName(EDGE_TAG);
        int docEdges = edges.getLength();
        for (int ee = 0; ee < docEdges; ee++) {
            Node edge = edges.item(ee);
            NamedNodeMap attrs = edge.getAttributes();
            String source = attrs.getNamedItem("source").getTextContent();
            String target = attrs.getNamedItem("target").getTextContent();
            this.addEdge(nodeTable.get(source), nodeTable.get(target), edge);
        }

        numNodes = this.vertexSet().size();
    } catch (ParserConfigurationException e) {
        throw new IOException(e.getMessage());
    } catch (SAXException e) {
        throw new IOException(e.getMessage());
    }
    return numNodes;
}

From source file:org.broad.igv.cbio.GeneNetwork.java

/**
 * The the value of a child node by the key.
 * If there are multiple matches, the first is returned.
 * Search is not recursive.//from   www.j  a  v a  2s  . c  om
 * <p/>
 * <p/>
 * Example: Say that node has the following XML
 * "&lt;node id="3725"/&gt;
 * &lt;data key="label"&gt;JUN&lt;/data&gt;
 * &lt;data key="type"&gt;Protein&lt;/data&gt;
 * &lt;data key="RELATIONSHIP_XREF"&gt;HGNC:JUN;Entrez Gene:3725&lt;/data&gt;
 * &lt;data key="IN_QUERY"&gt;false&lt;/data&gt;
 * &lt;/node&gt;"
 * So getNodeKeyData(node, "key", "label") returns "JUN".
 *
 * @param node
 * @param attrName
 * @param attrValue
 * @return String value of key found. null if not found
 */
public static String getNodeAttrValue(Node node, String attrName, String attrValue) {
    NodeList elements = node.getChildNodes();
    for (int ee = 0; ee < elements.getLength(); ee++) {
        Node el = elements.item(ee);
        try {
            NamedNodeMap map = el.getAttributes();
            Node label = map.getNamedItem(attrName);
            String textContent = label.getTextContent();
            if (textContent.compareToIgnoreCase(attrValue) == 0) {
                return el.getTextContent();
            }
        } catch (NullPointerException e) {
            //In general these get hit due to newlines and such
            //We simply skip
            continue;
        }
    }
    return null;
}

From source file:org.broad.igv.cbio.GeneNetworkTest.java

@Test
public void testFilter() throws Exception {
    Predicate tPred = new Predicate() {

        public boolean evaluate(Object object) {
            Node node = (Node) object;
            NamedNodeMap map = node.getAttributes();
            if (map == null) {
                return false;
            }//from www . j  a  v  a2s .  c o  m
            int id = Integer.parseInt(map.getNamedItem("id").getTextContent());
            return id % 2 == 0;
        }
    };

    network.loadNetwork(testpath);
    boolean removed = network.filterNodes(tPred) > 0;
    assertTrue(removed);

    //Test that we can get the filtered edges of a node
    Set<Node> keptNodes = new HashSet<Node>();
    for (Node n : network.vertexSetFiltered()) {
        for (Node e : network.edgesOfFiltered(n)) {
            keptNodes.add(network.getEdgeSource(e));
            keptNodes.add(network.getEdgeTarget(e));
        }
    }
    assertEquals(network.vertexSetFiltered().size(), keptNodes.size());
    assertTrue("Soft filtering not performed", keptNodes.size() < network.vertexSet().size());
}

From source file:org.broad.igv.dev.db.SQLCodecSource.java

/**
 * Retrieve a reader from the XML profile located at {@code profilePath}.
 * TODO If {@code tableName == null}, the user is prompted to choose a table from the list
 *
 * @param profilePath/*from  w  ww  . j  a  v a  2s . c o  m*/
 * @param tableName
 * @return
 */
public static List<SQLCodecSource> getFromProfile(String profilePath, String tableName) {
    ResourceLocator dbLocator = DBManager.getStoredConnection(profilePath);
    InputStream profileStream = null;
    try {
        profileStream = new FileInputStream(profilePath);
        Document document = Utilities.createDOMDocumentFromXmlStream(profileStream);
        NodeList nodes = document.getElementsByTagName("table");
        List<SQLCodecSource> sources = new ArrayList<SQLCodecSource>(nodes.getLength());

        for (int tnum = 0; tnum < nodes.getLength(); tnum++) {
            Node n = nodes.item(tnum);
            NamedNodeMap attr = n.getAttributes();
            String tabName = attr.getNamedItem("name").getTextContent();
            if (tableName == null || tableName.equals(tabName)) {

                String chromoColName = attr.getNamedItem("chromoColName").getTextContent();
                String posStartColName = attr.getNamedItem("posStartColName").getTextContent();
                String posEndColName = attr.getNamedItem("posEndColName").getTextContent();
                String format = attr.getNamedItem("format").getTextContent();
                String startColString = Utilities.getNullSafe(attr, "startColIndex");
                String endColString = Utilities.getNullSafe(attr, "endColIndex");
                String binColName = Utilities.getNullSafe(attr, "binColName");
                int startColIndex = startColString != null ? Integer.parseInt(startColString) : 1;
                int endColIndex = endColString != null ? Integer.parseInt(endColString) : Integer.MAX_VALUE;
                AsciiFeatureCodec codec = CodecFactory.getCodec("." + format,
                        GenomeManager.getInstance().getCurrentGenome());
                SQLCodecSource source = new SQLCodecSource(dbLocator, codec, tabName, chromoColName,
                        posStartColName, posEndColName, startColIndex, endColIndex);
                source.binColName = binColName;
                sources.add(source);
            }
        }

        return sources;

    } catch (Exception e) {
        e.printStackTrace();
        return null;
    } finally {
        try {
            if (profileStream != null)
                profileStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

From source file:org.broad.igv.util.Utilities.java

/**
 * Get the text content of the attribute {@code key} from
 * the set {@code attr}. If that attribute is not present, null is returned
 *
 * @param attr//w  w w. jav  a 2s. c o  m
 * @param key
 * @return
 */
public static String getNullSafe(NamedNodeMap attr, String key) {
    Node node = attr.getNamedItem(key);
    return node != null ? node.getTextContent() : null;
}

From source file:org.deegree.framework.xml.XMLFragment.java

/**
 * Determines the namespace <code>URI</code>s and the bound schema <code>URL</code>s from the 'xsi:schemaLocation'
 * attribute of the document element.//from w w  w  . j a v a 2 s .  c  o  m
 * 
 * @return keys are URIs (namespaces), values are URLs (schema locations)
 * @throws XMLParsingException
 */
public Map<URI, URL> getAttachedSchemas() throws XMLParsingException {

    Map<URI, URL> schemaMap = new HashMap<URI, URL>();

    NamedNodeMap attrMap = rootElement.getAttributes();
    Node schemaLocationAttr = attrMap.getNamedItem("xsi:schemaLocation");
    if (schemaLocationAttr == null) {
        return schemaMap;
    }

    String target = schemaLocationAttr.getNodeValue();
    StringTokenizer tokenizer = new StringTokenizer(target);

    while (tokenizer.hasMoreTokens()) {
        URI nsURI = null;
        String token = tokenizer.nextToken();
        try {
            nsURI = new URI(token);
        } catch (URISyntaxException e) {
            String msg = "Invalid 'xsi:schemaLocation' attribute: namespace " + token + "' is not a valid URI.";
            LOG.logError(msg);
            throw new XMLParsingException(msg);
        }

        URL schemaURL = null;
        try {
            token = tokenizer.nextToken();
            schemaURL = resolve(token);
        } catch (NoSuchElementException e) {
            String msg = "Invalid 'xsi:schemaLocation' attribute: namespace '" + nsURI
                    + "' is missing a schema URL.";
            LOG.logError(msg);
            throw new XMLParsingException(msg);
        } catch (MalformedURLException ex) {
            String msg = "Invalid 'xsi:schemaLocation' attribute: '" + token + "' for namespace '" + nsURI
                    + "' could not be parsed as URL.";
            throw new XMLParsingException(msg);
        }
        schemaMap.put(nsURI, schemaURL);
    }
    return schemaMap;
}

From source file:org.deri.any23.extractor.html.HCardExtractor.java

private void fixIncludes(HTMLDocument document, Node node) {
    NamedNodeMap attributes = node.getAttributes();
    // header case test 32
    if ("TD".equals(node.getNodeName()) && (null != attributes.getNamedItem("headers"))) {
        String id = attributes.getNamedItem("headers").getNodeValue();
        Node header = document.findNodeById(id);
        if (null != header) {
            node.appendChild(header.cloneNode(true));
            attributes.removeNamedItem("headers");
        }//from   www .  jav  a2  s.  c  o  m
    }
    // include pattern, test 31

    for (Node current : document.findAll("//*[@class]")) {
        if (!DomUtils.hasClassName(current, "include"))
            continue;
        // we have to remove the field soon to avoid infinite loops
        // no null check, we know it's there or we won't be in the loop
        current.getAttributes().removeNamedItem("class");
        ArrayList<TextField> res = new ArrayList<TextField>();
        HTMLDocument.readUrlField(res, current);
        TextField id = res.get(0);
        if (null == id)
            continue;
        id = new TextField(StringUtils.substringAfter(id.value(), "#"), id.source());
        Node included = document.findNodeById(id.value());
        if (null == included)
            continue;
        current.appendChild(included.cloneNode(true));
    }
}

From source file:org.dita.dost.util.DitaUtil.java

private static String getFileNameFromMap(String ditaMapPath) {

    StringBuffer fileName = new StringBuffer();

    try {//from   w  ww  .  j  a v a 2s. c om

        FileInputStream ditaMapStream;

        ditaMapStream = new FileInputStream(ditaMapPath);

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        factory.setNamespaceAware(true);

        factory.setValidating(false);

        factory.setFeature("http://xml.org/sax/features/namespaces", false);
        factory.setFeature("http://xml.org/sax/features/validation", false);
        factory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
        factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);

        DocumentBuilder builder;

        Document doc = null;

        XPathExpression expr = null;

        builder = factory.newDocumentBuilder();

        doc = builder.parse(new InputSource(ditaMapStream));

        XPathFactory xFactory = XPathFactory.newInstance();

        XPath xpath = xFactory.newXPath();

        expr = xpath.compile("//bookmap/bookmeta/prodinfo/prodname");

        Node prodNameNode = (Node) expr.evaluate(doc, XPathConstants.NODE);

        if (prodNameNode != null) {

            fileName.append(prodNameNode.getTextContent());

            expr = xpath.compile("//bookmap/bookmeta/prodinfo/vrmlist");

            Element vrmlistNode = (Element) expr.evaluate(doc, XPathConstants.NODE);

            if (vrmlistNode != null) {
                NodeList versions = vrmlistNode.getElementsByTagName("vrm");
                if (versions.getLength() > 0) {

                    NamedNodeMap versionAttributes = versions.item(0).getAttributes();
                    Attr releaseAttr = (Attr) versionAttributes.getNamedItem("release");

                    if (releaseAttr != null) {
                        fileName.append(String.format("_%s", releaseAttr.getValue()));
                    }

                    Attr versionAttr = (Attr) versionAttributes.getNamedItem("version");

                    if (versionAttr != null) {
                        fileName.append(String.format("_%s", versionAttr.getValue()));
                    }
                }
            }
        } else {
            expr = xpath.compile("/bookmap");
            prodNameNode = (Node) expr.evaluate(doc, XPathConstants.NODE);
            if (prodNameNode != null) {
                Node node = prodNameNode.getAttributes().getNamedItem("id");
                if (node != null) {
                    fileName.append(node.getTextContent());
                }
            } else {
                expr = xpath.compile("/map");
                prodNameNode = (Node) expr.evaluate(doc, XPathConstants.NODE);
                if (prodNameNode != null) {
                    Node node = prodNameNode.getAttributes().getNamedItem("title");
                    if (node != null) {
                        fileName.append(node.getTextContent());
                    }
                }
            }
        }
    } catch (FileNotFoundException e) {
    } catch (ParserConfigurationException e) {
    } catch (SAXException e) {
    } catch (IOException e) {
    } catch (XPathExpressionException e) {
    }
    return fileName.toString();
}