Example usage for org.w3c.dom Element getNodeName

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

Introduction

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

Prototype

public String getNodeName();

Source Link

Document

The name of this node, depending on its type; see the table above.

Usage

From source file:com.github.lindenb.jvarkit.tools.ensembl.VcfEnsemblVepRest.java

@Override
protected Collection<Throwable> doVcfToVcf(final String inputName, final VcfIterator vcfIn,
        final VariantContextWriter out) throws IOException {
    final java.util.Base64.Encoder base64Encoder = java.util.Base64.getEncoder();
    final SequenceOntologyTree soTree = SequenceOntologyTree.getInstance();
    VCFHeader header = vcfIn.getHeader();
    List<VariantContext> buffer = new ArrayList<>(this.batchSize + 1);
    VCFHeader h2 = new VCFHeader(header);
    addMetaData(h2);/*  w  ww.  j a  va  2 s  .  c  o  m*/

    if (!xmlBase64) {
        h2.addMetaDataLine(new VCFInfoHeaderLine(TAG, VCFHeaderLineCount.UNBOUNDED, VCFHeaderLineType.String,
                "VEP Transcript Consequences. Format :(biotype|cdnaStart|cdnaEnd|cdsStart|cdsEnd|geneId|geneSymbol|geneSymbolSource|hgnc|strand|transcript|variantAllele|so_acns)"));
    } else {
        h2.addMetaDataLine(
                new VCFInfoHeaderLine(TAG, 1, VCFHeaderLineType.String, "VEP xml answer encoded as base 64"));
    }

    out.writeHeader(h2);
    SAMSequenceDictionaryProgress progress = new SAMSequenceDictionaryProgress(header);
    for (;;) {
        VariantContext ctx = null;
        if (vcfIn.hasNext()) {
            buffer.add((ctx = progress.watch(vcfIn.next())));
        }
        if (ctx == null || buffer.size() >= this.batchSize) {
            if (!buffer.isEmpty()) {
                if (!xmlBase64) {
                    Opt opt = vep(buffer);
                    for (VariantContext ctx2 : buffer) {
                        VariantContextBuilder vcb = new VariantContextBuilder(ctx2);
                        final String inputStr = createInputContext(ctx2);
                        Data mydata = null;
                        for (Data data : opt.getData()) {
                            if (!inputStr.equals(data.getInput()))
                                continue;
                            mydata = data;
                            break;
                        }
                        if (mydata == null) {
                            LOG.info("No Annotation found for " + inputStr);
                            out.add(ctx2);
                            continue;
                        }
                        List<String> infoList = new ArrayList<>();
                        List<TranscriptConsequences> csql = mydata.getTranscriptConsequences();
                        for (int i = 0; i < csql.size(); ++i) {
                            TranscriptConsequences csq = csql.get(i);
                            StringBuilder sb = new StringBuilder();
                            sb.append(empty(csq.getBiotype())).append("|").append(empty(csq.getCdnaStart()))
                                    .append("|").append(empty(csq.getCdnaEnd())).append("|")
                                    .append(empty(csq.getCdsStart())).append("|").append(empty(csq.getCdsEnd()))
                                    .append("|").append(empty(csq.getGeneId())).append("|")
                                    .append(empty(csq.getGeneSymbol())).append("|")
                                    .append(empty(csq.getGeneSymbolSource())).append("|")
                                    .append(empty(csq.getHgncId())).append("|").append(empty(csq.getStrand()))
                                    .append("|").append(empty(csq.getTranscriptId())).append("|")
                                    .append(empty(csq.getVariantAllele())).append("|");
                            List<String> terms = csq.getConsequenceTerms();
                            for (int j = 0; j < terms.size(); ++j) {
                                if (j > 0)
                                    sb.append("&");
                                SequenceOntologyTree.Term term = soTree.getTermByLabel(terms.get(j));
                                if (term == null) {
                                    sb.append(terms.get(j));
                                    LOG.warn("No SO:Term found for " + terms.get(j));
                                } else {
                                    sb.append(term.getAcn());
                                }
                            }
                            infoList.add(sb.toString());
                        }
                        if (!infoList.isEmpty()) {
                            vcb.attribute(TAG, infoList);
                        }

                        out.add(vcb.make());
                    }
                } //end of not(XML base 64)
                else {
                    Document opt = vepxml(buffer);
                    Element root = opt.getDocumentElement();
                    if (!root.getNodeName().equals("opt"))
                        throw new IOException("Bad root node " + root.getNodeName());

                    for (VariantContext ctx2 : buffer) {
                        String inputStr = createInputContext(ctx2);
                        Document newdom = null;

                        //loop over <data/>
                        for (Node dataNode = root.getFirstChild(); dataNode != null; dataNode = dataNode
                                .getNextSibling()) {
                            if (dataNode.getNodeType() != Node.ELEMENT_NODE)
                                continue;
                            Attr att = Element.class.cast(dataNode).getAttributeNode("input");
                            if (att == null) {
                                LOG.warn("no @input in <data/>");
                                continue;
                            }

                            if (!att.getValue().equals(inputStr))
                                continue;
                            if (newdom == null) {
                                newdom = this.documentBuilder.newDocument();
                                newdom.appendChild(newdom.createElement("opt"));
                            }
                            newdom.getDocumentElement().appendChild(newdom.importNode(dataNode, true));
                        }
                        if (newdom == null) {
                            LOG.warn("No Annotation found for " + inputStr);
                            out.add(ctx2);
                            continue;
                        }
                        StringWriter sw = new StringWriter();
                        try {
                            this.xmlSerializer.transform(new DOMSource(newdom), new StreamResult(sw));
                        } catch (TransformerException err) {
                            throw new IOException(err);
                        }
                        VariantContextBuilder vcb = new VariantContextBuilder(ctx2);
                        vcb.attribute(TAG, base64Encoder.encodeToString(sw.toString().getBytes())
                                .replaceAll("[\\s=]", ""));
                        out.add(vcb.make());
                    }
                } //end of XML base 64
            }
            if (ctx == null)
                break;
            buffer.clear();
        }
        if (out.checkError())
            break;
    }
    progress.finish();
    return RETURN_OK;
}

From source file:com.espertech.esper.client.ConfigurationParser.java

private static void handleMetricsReporting(Configuration configuration, Element parentElement) {
    String enabled = getRequiredAttribute(parentElement, "enabled");
    boolean isEnabled = Boolean.parseBoolean(enabled);
    configuration.getEngineDefaults().getMetricsReporting().setEnableMetricsReporting(isEnabled);

    String engineInterval = getOptionalAttribute(parentElement, "engine-interval");
    if (engineInterval != null) {
        configuration.getEngineDefaults().getMetricsReporting()
                .setEngineInterval(Long.parseLong(engineInterval));
    }/*  w w  w . j a  v  a2  s .co m*/

    String statementInterval = getOptionalAttribute(parentElement, "statement-interval");
    if (statementInterval != null) {
        configuration.getEngineDefaults().getMetricsReporting()
                .setStatementInterval(Long.parseLong(statementInterval));
    }

    String threading = getOptionalAttribute(parentElement, "threading");
    if (threading != null) {
        configuration.getEngineDefaults().getMetricsReporting().setThreading(Boolean.parseBoolean(threading));
    }

    String jmxEngineMetrics = getOptionalAttribute(parentElement, "jmx-engine-metrics");
    if (jmxEngineMetrics != null) {
        configuration.getEngineDefaults().getMetricsReporting()
                .setJmxEngineMetrics(Boolean.parseBoolean(jmxEngineMetrics));
    }

    DOMElementIterator nodeIterator = new DOMElementIterator(parentElement.getChildNodes());
    while (nodeIterator.hasNext()) {
        Element subElement = nodeIterator.next();
        if (subElement.getNodeName().equals("stmtgroup")) {
            String name = getRequiredAttribute(subElement, "name");
            long interval = Long.parseLong(getRequiredAttribute(subElement, "interval"));

            ConfigurationMetricsReporting.StmtGroupMetrics metrics = new ConfigurationMetricsReporting.StmtGroupMetrics();
            metrics.setInterval(interval);
            configuration.getEngineDefaults().getMetricsReporting().addStmtGroup(name, metrics);

            String defaultInclude = getOptionalAttribute(subElement, "default-include");
            if (defaultInclude != null) {
                metrics.setDefaultInclude(Boolean.parseBoolean(defaultInclude));
            }

            String numStmts = getOptionalAttribute(subElement, "num-stmts");
            if (numStmts != null) {
                metrics.setNumStatements(Integer.parseInt(numStmts));
            }

            String reportInactive = getOptionalAttribute(subElement, "report-inactive");
            if (reportInactive != null) {
                metrics.setReportInactive(Boolean.parseBoolean(reportInactive));
            }

            handleMetricsReportingPatterns(metrics, subElement);
        }
    }
}

From source file:com.sqewd.os.maracache.core.Config.java

/**
 * Load the configuration from the path and file specified.
 *
 * @throws ConfigException/*w  w  w .j ava  2s  . c o m*/
 */
public void load() throws ConfigException {
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(filePath);

        //optional, but recommended
        //read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
        doc.getDocumentElement().normalize();

        XPath xp = XPathFactory.newInstance().newXPath();
        Element root = (Element) xp.compile(configPath).evaluate(doc, XPathConstants.NODE);
        if (root == null) {
            throw new ConfigException("Cannot find specified path in document. [path=" + configPath + "]");
        }

        node = new ConfigPath(root.getNodeName(), null);
        load(node, root);

        state = EObjectState.Available;
    } catch (ParserConfigurationException pse) {
        state = EObjectState.Exception;
        state.setException(pse);
        throw new ConfigException("Error building the configuration document.", pse);
    } catch (IOException ioe) {
        state = EObjectState.Exception;
        state.setException(ioe);
        throw new ConfigException("Error reading configuration file [path=" + filePath + "]", ioe);
    } catch (SAXException se) {
        state = EObjectState.Exception;
        state.setException(se);
        throw new ConfigException("Error parsing document [document=" + filePath + "]", se);
    } catch (XPathExpressionException xpe) {
        state = EObjectState.Exception;
        state.setException(xpe);
        throw new ConfigException("Error parsing specified XPath expression.", xpe);
    }
}

From source file:com.espertech.esper.client.ConfigurationParser.java

private static void handleLegacy(String name, String className, Configuration configuration,
        Element xmldomElement) {//from w  ww.j  a v  a 2  s . c  o  m
    // Class name is required for legacy classes
    if (className == null) {
        throw new ConfigurationException("Required class name not supplied for legacy type definition");
    }

    String accessorStyle = getRequiredAttribute(xmldomElement, "accessor-style");
    String codeGeneration = getRequiredAttribute(xmldomElement, "code-generation");
    String propertyResolution = getRequiredAttribute(xmldomElement, "property-resolution-style");
    String factoryMethod = getOptionalAttribute(xmldomElement, "factory-method");
    String copyMethod = getOptionalAttribute(xmldomElement, "copy-method");
    String startTimestampProp = getOptionalAttribute(xmldomElement, "start-timestamp-property-name");
    String endTimestampProp = getOptionalAttribute(xmldomElement, "end-timestamp-property-name");

    ConfigurationEventTypeLegacy legacyDesc = new ConfigurationEventTypeLegacy();
    if (accessorStyle != null) {
        legacyDesc.setAccessorStyle(
                ConfigurationEventTypeLegacy.AccessorStyle.valueOf(accessorStyle.toUpperCase()));
    }
    if (codeGeneration != null) {
        legacyDesc.setCodeGeneration(
                ConfigurationEventTypeLegacy.CodeGeneration.valueOf(codeGeneration.toUpperCase()));
    }
    if (propertyResolution != null) {
        legacyDesc.setPropertyResolutionStyle(
                Configuration.PropertyResolutionStyle.valueOf(propertyResolution.toUpperCase()));
    }
    legacyDesc.setFactoryMethod(factoryMethod);
    legacyDesc.setCopyMethod(copyMethod);
    legacyDesc.setStartTimestampPropertyName(startTimestampProp);
    legacyDesc.setEndTimestampPropertyName(endTimestampProp);
    configuration.addEventType(name, className, legacyDesc);

    DOMElementIterator propertyNodeIterator = new DOMElementIterator(xmldomElement.getChildNodes());
    while (propertyNodeIterator.hasNext()) {
        Element propertyElement = propertyNodeIterator.next();
        if (propertyElement.getNodeName().equals("method-property")) {
            String nameProperty = getRequiredAttribute(propertyElement, "name");
            String method = getRequiredAttribute(propertyElement, "accessor-method");
            legacyDesc.addMethodProperty(nameProperty, method);
        } else if (propertyElement.getNodeName().equals("field-property")) {
            String nameProperty = getRequiredAttribute(propertyElement, "name");
            String field = getRequiredAttribute(propertyElement, "accessor-field");
            legacyDesc.addFieldProperty(nameProperty, field);
        } else {
            throw new ConfigurationException("Invalid node " + propertyElement.getNodeName()
                    + " encountered while parsing legacy type definition");
        }
    }
}

From source file:com.servoy.extension.install.LibActivationHandler.java

protected void replaceReferencesInJNLP(File jnlp, File libFileToBeRemoved,
        FullLibDependencyDeclaration toActivate) {
    try {//from w  ww. j a  va  2 s  . c  o m
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        db.setErrorHandler(new XMLErrorHandler(jnlp.getName()));

        Document doc = db.parse(jnlp);
        Element root = doc.getDocumentElement();
        root.normalize();

        NodeList list;
        if ("jnlp".equals(root.getNodeName())) //$NON-NLS-1$
        {
            list = root.getElementsByTagName("resources"); //$NON-NLS-1$
            if (list != null && list.getLength() == 1 && list.item(0).getNodeType() == Node.ELEMENT_NODE) {
                File appServerDir = new File(installDir, APP_SERVER_DIR);
                Element resourcesNode = (Element) list.item(0);
                boolean replaced1 = findAndReplaceReferences(resourcesNode, "jar", appServerDir, //$NON-NLS-1$
                        libFileToBeRemoved, toActivate);
                boolean replaced2 = findAndReplaceReferences(resourcesNode, "nativelib", appServerDir, //$NON-NLS-1$
                        libFileToBeRemoved, toActivate);

                if (replaced1 || replaced2) {
                    // save back the jnlp file
                    try {
                        writeBackXML(doc, jnlp, doc.getXmlEncoding());
                    } catch (Exception e) {
                        messages.addError("Cannot write back jnlp file (when deactivating lib): " + jnlp); //$NON-NLS-1$ 
                        Debug.error(e);
                    }
                }
            }
        }
    } catch (ParserConfigurationException e) {
        String msg = "Cannot parse jnlp '" + jnlp.getName() + "'."; //$NON-NLS-1$ //$NON-NLS-2$
        Debug.log(msg, e);
    } catch (SAXException e) {
        String msg = "Cannot parse jnlp '" + jnlp.getName() + "'."; //$NON-NLS-1$ //$NON-NLS-2$
        Debug.log(msg, e);
    } catch (IOException e) {
        String msg = "Cannot parse jnlp '" + jnlp.getName() + "'."; //$NON-NLS-1$ //$NON-NLS-2$
        Debug.log(msg, e);
    } catch (FactoryConfigurationError e) {
        String msg = "Cannot parse jnlp '" + jnlp.getName() + "'. Please report this problem to Servoy."; //$NON-NLS-1$ //$NON-NLS-2$
        Debug.error(msg, e);
    }
}

From source file:org.finra.jtaf.core.parsing.CommandLibraryParser.java

private final InvocationTarget processInvocationTarget(Element elem, MessageCollector mc)
        throws ParsingException {
    InvocationTarget retval = null;/* w w w . j a  va 2  s.  c  om*/
    final String name = elem.getNodeName().toLowerCase();
    if (name.equals("command")) {
        retval = processCommand(elem, mc);
    } else if (name.equals("function")) {
        retval = processFunction(elem, mc);
    } else {
        throw new UnexpectedElementException(elem);
    }

    final Element usage = ParserHelper.getOptionalElement(elem, "usage");
    if (usage != null) {
        retval.setUsage(usage.getTextContent());
    }

    final Element requiredParameters = ParserHelper.getOptionalElement(elem, "requiredParameters");
    if (requiredParameters != null) {
        for (Element child : ParserHelper.getChildren(requiredParameters)) {
            AttributeHelper ah = new AttributeHelper(child);
            retval.addRequiredParameter(ah.getRequiredString("name"));
        }
    }

    final Element optionalParameters = ParserHelper.getOptionalElement(elem, "optionalParameters");
    if (optionalParameters != null) {
        for (Element child : ParserHelper.getChildren(optionalParameters)) {
            AttributeHelper ah = new AttributeHelper(child);
            retval.addOptionalParameter(ah.getRequiredString("name"));
        }
    }

    final Element produces = ParserHelper.getOptionalElement(elem, "produces");
    if (produces != null) {
        for (Element child : ParserHelper.getChildren(produces)) {
            AttributeHelper ah = new AttributeHelper(child);
            retval.addProduction(ah.getRequiredString("name"));
        }
    }

    return retval;
}

From source file:com.espertech.esper.client.ConfigurationParser.java

/**
 * Parse the W3C DOM document./*from   www. j a v  a  2  s .  c  o m*/
 * @param configuration is the configuration object to populate
 * @param doc to parse
 * @throws EPException to indicate parse errors
 */
protected static void doConfigure(Configuration configuration, Document doc) throws EPException {
    Element root = doc.getDocumentElement();

    DOMElementIterator eventTypeNodeIterator = new DOMElementIterator(root.getChildNodes());
    while (eventTypeNodeIterator.hasNext()) {
        Element element = eventTypeNodeIterator.next();
        String nodeName = element.getNodeName();
        if (nodeName.equals("event-type-auto-name")) {
            handleEventTypeAutoNames(configuration, element);
        } else if (nodeName.equals("event-type")) {
            handleEventTypes(configuration, element);
        } else if (nodeName.equals("auto-import")) {
            handleAutoImports(configuration, element);
        } else if (nodeName.equals("method-reference")) {
            handleMethodReference(configuration, element);
        } else if (nodeName.equals("database-reference")) {
            handleDatabaseRefs(configuration, element);
        } else if (nodeName.equals("plugin-view")) {
            handlePlugInView(configuration, element);
        } else if (nodeName.equals("plugin-virtualdw")) {
            handlePlugInVirtualDW(configuration, element);
        } else if (nodeName.equals("plugin-aggregation-function")) {
            handlePlugInAggregation(configuration, element);
        } else if (nodeName.equals("plugin-aggregation-multifunction")) {
            handlePlugInMultiFunctionAggregation(configuration, element);
        } else if (nodeName.equals("plugin-singlerow-function")) {
            handlePlugInSingleRow(configuration, element);
        } else if (nodeName.equals("plugin-pattern-guard")) {
            handlePlugInPatternGuard(configuration, element);
        } else if (nodeName.equals("plugin-pattern-observer")) {
            handlePlugInPatternObserver(configuration, element);
        } else if (nodeName.equals("variable")) {
            handleVariable(configuration, element);
        } else if (nodeName.equals("plugin-loader")) {
            handlePluginLoaders(configuration, element);
        } else if (nodeName.equals("engine-settings")) {
            handleEngineSettings(configuration, element);
        } else if (nodeName.equals("plugin-event-representation")) {
            handlePlugInEventRepresentation(configuration, element);
        } else if (nodeName.equals("plugin-event-type")) {
            handlePlugInEventType(configuration, element);
        } else if (nodeName.equals("plugin-event-type-name-resolution")) {
            handlePlugIneventTypeNameResolution(configuration, element);
        } else if (nodeName.equals("revision-event-type")) {
            handleRevisionEventType(configuration, element);
        } else if (nodeName.equals("variant-stream")) {
            handleVariantStream(configuration, element);
        }
    }
}

From source file:MSUmpire.SearchResultParser.PepXMLParseHandler.java

@Override
public void handle(Element node) throws Exception {
    switch (node.getNodeName()) {
    case "spectrum_query": {
        ParseSpectrumNode(node);/*from   w  w  w  .j  ava  2  s  . c  o  m*/
        break;
    }
    case "search_summary": {
        ParseSearchSummary(node);
        break;
    }
    }
}

From source file:com.bstek.dorado.config.xml.DispatchableXmlParser.java

private boolean isTagElement(Element element) {
    String nodeName = element.getNodeName();
    return (XmlConstants.PROPERTY.equals(nodeName) || XmlConstants.GROUP_START.equals(nodeName)
            || XmlConstants.GROUP_END.equals(nodeName) || XmlConstants.IMPORT.equals(nodeName)
            || XmlConstants.PLACE_HOLDER.equals(nodeName) || XmlConstants.PLACE_HOLDER_START.equals(nodeName)
            || XmlConstants.PLACE_HOLDER_END.equals(nodeName));
}

From source file:cc.siara.csv_ml.ParsedObject.java

/**
 * Performas any pending activity against an element to finalize it. In this
 * case, it adds any pending attributes needing namespace mapping.
 * //from   w w  w  .ja  v a2 s  .c o  m
 * Also if the node has a namespace attached, it recreates the node with
 * specific URI.
 */
public void finalizeElement() {
    // Add all remaining attributes
    for (String col_name : pendingAttributes.keySet()) {
        String value = pendingAttributes.get(col_name);
        int cIdx = col_name.indexOf(':');
        String ns = col_name.substring(0, cIdx);
        String nsURI = nsMap.get(ns);
        if (nsURI == null)
            nsURI = generalNSURI;
        Attr attr = doc.createAttributeNS(nsURI, col_name.substring(cIdx + 1));
        attr.setPrefix(ns);
        attr.setValue(value);
        ((Element) cur_element).setAttributeNodeNS(attr);
    }
    // If the element had a namespace prefix, it has to be recreated.
    if (!currentElementNS.equals("") && !doc.getDocumentElement().equals(cur_element)) {
        Node parent = cur_element.getParentNode();
        Element cur_ele = (Element) parent.removeChild(cur_element);
        String node_name = cur_ele.getNodeName();
        String nsURI = nsMap.get(currentElementNS);
        if (nsURI == null)
            nsURI = generalNSURI;
        Element new_node = doc.createElementNS(nsURI, currentElementNS + ":" + node_name);
        parent.appendChild(new_node);
        // Add all attributes
        NamedNodeMap attrs = cur_ele.getAttributes();
        while (attrs.getLength() > 0) {
            Attr attr = (Attr) attrs.item(0);
            cur_ele.removeAttributeNode(attr);
            nsURI = attr.getNamespaceURI();
            new_node.setAttributeNodeNS(attr);
        }
        // Add all CData sections
        NodeList childNodes = cur_ele.getChildNodes();
        for (int i = 0; i < childNodes.getLength(); i++) {
            Node node = childNodes.item(i);
            if (node.getNodeType() == Node.CDATA_SECTION_NODE)
                new_node.appendChild(node);
        }
        cur_element = new_node;
    }
    pendingAttributes = new Hashtable<String, String>();
}