Example usage for org.w3c.dom Element getFirstChild

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

Introduction

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

Prototype

public Node getFirstChild();

Source Link

Document

The first child of this node.

Usage

From source file:edu.lternet.pasta.client.EventSubscriptionClient.java

public String subscriptionTableHTML() throws PastaEventException {
    String html = "";

    if (this.uid != null && !this.uid.equals("public")) {
        StringBuilder sb = new StringBuilder("");
        String xmlString = readByFilter("");

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        try {//from w  ww  .  j  a  v a 2 s.c o m
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            InputStream inputStream = IOUtils.toInputStream(xmlString, "UTF-8");
            Document document = documentBuilder.parse(inputStream);
            Element documentElement = document.getDocumentElement();
            NodeList subscriptionList = documentElement.getElementsByTagName("subscription");
            int nSubscriptions = subscriptionList.getLength();

            for (int i = 0; i < nSubscriptions; i++) {
                Node subscriptionNode = subscriptionList.item(i);
                NodeList subscriptionChildren = subscriptionNode.getChildNodes();
                String subscriptionId = "";
                String packageId = "";
                String url = "";
                for (int j = 0; j < subscriptionChildren.getLength(); j++) {
                    Node childNode = subscriptionChildren.item(j);
                    if (childNode instanceof Element) {
                        Element subscriptionElement = (Element) childNode;

                        if (subscriptionElement.getTagName().equals("id")) {
                            Text text = (Text) subscriptionElement.getFirstChild();
                            if (text != null) {
                                subscriptionId = text.getData().trim();
                            }
                        } else if (subscriptionElement.getTagName().equals("packageId")) {
                            Text text = (Text) subscriptionElement.getFirstChild();
                            if (text != null) {
                                packageId = text.getData().trim();
                            }
                        } else if (subscriptionElement.getTagName().equals("url")) {
                            Text text = (Text) subscriptionElement.getFirstChild();
                            if (text != null) {
                                url = text.getData().trim();
                            }
                        }
                    }
                }

                sb.append("<tr>\n");

                sb.append("<td class='nis' align='center'>");
                sb.append(subscriptionId);
                sb.append("</td>\n");

                sb.append("<td class='nis' align='center'>");
                sb.append(packageId);
                sb.append("</td>\n");

                sb.append("<td class='nis'>");
                sb.append(url);
                sb.append("</td>\n");

                sb.append("</tr>\n");
            }

            html = sb.toString();
        } catch (Exception e) {
            logger.error("Exception:\n" + e.getMessage());
            e.printStackTrace();
            throw new PastaEventException(e.getMessage());
        }
    }

    return html;
}

From source file:org.jasig.portal.security.provider.saml.SAMLDelegatedAuthenticationService.java

private void removeAllChildren(Element element) {
    Node child = element.getFirstChild();

    while (child != null) {
        Node next = child.getNextSibling();
        element.removeChild(child);//from   w w  w. j a va2 s .c o m
        child = next;
    }
}

From source file:dk.dbc.rawrepo.oai.OAIWorker.java

private void fixXmlNamespacePrefix(Element element, String metadataPrefix, String namespaceURI)
        throws DOMException {
    String prefix = null;//  w w w  .  j a v a  2  s  . c o  m
    if (namespaceURI.equals(element.getNamespaceURI())) {
        prefix = element.getPrefix();
        if (prefix == null) {
            prefix = "";
        }
        element.setPrefix(metadataPrefix);
    }
    for (Node child = element.getFirstChild(); child != null; child = child.getNextSibling()) {
        if (child.getNodeType() == Node.ELEMENT_NODE) {
            fixXmlNamespacePrefix((Element) child, metadataPrefix, namespaceURI);
        }
    }
    if (prefix != null) {
        element.removeAttribute(prefix.isEmpty() ? "xmlns" : ("xmlns:" + prefix));
    }
}

From source file:org.dataone.proto.trove.mn.http.client.HttpExceptionHandler.java

private static ErrorElements deserializeXml(HttpResponse response) throws IllegalStateException, IOException //    throws NotFound, InvalidToken, ServiceFailure, NotAuthorized,
//    NotFound, IdentifierNotUnique, UnsupportedType,
//    InsufficientResources, InvalidSystemMetadata, NotImplemented,
//    InvalidCredentials, InvalidRequest, IOException {
{
    ErrorElements ee = new ErrorElements();

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    Document doc;/*from   w ww.java  2s  .c om*/

    int httpCode = response.getStatusLine().getStatusCode();
    if (response.getEntity() != null) {
        BufferedInputStream bErrorStream = new BufferedInputStream(response.getEntity().getContent());
        bErrorStream.mark(5000); // good for resetting up to 5000 bytes

        String detailCode = null;
        String description = null;
        String name = null;
        int errorCode = -1;
        try {
            DocumentBuilder db = dbf.newDocumentBuilder();
            doc = db.parse(bErrorStream);
            Element root = doc.getDocumentElement();
            root.normalize();
            if (root.getNodeName().equalsIgnoreCase("error")) {
                if (root.hasAttribute("errorCode")) {
                    try {
                        errorCode = Integer.getInteger(root.getAttribute("errorCode"));
                    } catch (NumberFormatException nfe) {
                        System.out.println("errorCode unexpectedly not able to parse to int,"
                                + " using http status for creating exception");
                        errorCode = httpCode;
                    }
                }
                if (errorCode != httpCode) //            throw new ServiceFailure("1000","errorCode in message body doesn't match httpStatus");
                {
                    System.out.println("errorCode in message body doesn't match httpStatus,"
                            + " using errorCode for creating exception");
                }
                if (root.hasAttribute("detailCode")) {
                    detailCode = root.getAttribute("detailCode");
                } else {
                    detailCode = "detail code is Not Set!";
                }
                if (root.hasAttribute("name")) {
                    name = root.getAttribute("name");
                } else {
                    name = "Exception";
                }
                Node child = root.getFirstChild();
                do {
                    if (child.getNodeType() == Node.ELEMENT_NODE) {
                        if (child.getNodeName().equalsIgnoreCase("description")) {
                            Element element = (Element) child;
                            description = element.getTextContent();
                            break;
                        }
                    }
                } while ((child = child.getNextSibling()) != null);
            } else {
                description = domToString(doc);
                detailCode = "detail code was never Set!";
            }
        } catch (TransformerException e) {
            description = deserializeNonXMLErrorStream(bErrorStream, e);
        } catch (SAXException e) {
            description = deserializeNonXMLErrorStream(bErrorStream, e);
        } catch (IOException e) {
            description = deserializeNonXMLErrorStream(bErrorStream, e);
        } catch (ParserConfigurationException e) {
            description = deserializeNonXMLErrorStream(bErrorStream, e);
        }

        ee.setCode(errorCode);
        ee.setName(name);
        ee.setDetailCode(detailCode);
        ee.setDescription(description);
    }
    return ee;
}

From source file:com.verisign.epp.codec.gen.EPPUtil.java

/**
 * Decode <code>String</code>, by XML namespace and tag name, from an XML
 * Element. The children elements of <code>aElement</code> will be searched
 * for the specified <code>aNS</code> namespace URI and the specified
 * <code>aTagName</code>. The first XML element found will be decoded and
 * returned. If no element is found, <code>null</code> is returned.
 * /*from  ww w  . j a v  a 2 s. c  o m*/
 * @param aElement
 *            XML Element to scan. For example, the element could be
 *            &ltdomain:create&gt
 * @param aNS
 *            XML namespace of the elements. For example, for domain element
 *            this is "urn:iana:xmlns:domain".
 * @param aTagName
 *            Tag name of the element including an optional namespace
 *            prefix. For example, the tag name for the domain name is
 *            "domain:name".
 * @return <code>String</code> value if found; <code>null</code> otherwise.
 * @exception EPPDecodeException
 *                Error decoding <code>aElement</code>.
 */
public static String decodeString(Element aElement, String aNS, String aTagName) throws EPPDecodeException {
    String retVal = null;

    Element theElm = EPPUtil.getElementByTagNameNS(aElement, aNS, aTagName);

    if (theElm != null) {
        Node textNode = theElm.getFirstChild();

        // Element does have a text node?
        if (textNode != null) {
            retVal = textNode.getNodeValue();
        } else {
            retVal = "";
        }
    }

    // end if (currElm != null)
    return retVal;
}

From source file:com.verisign.epp.codec.gen.EPPUtil.java

/**
 * Decode <code>Date</code>, by XML namespace and tag name, from an XML
 * Element. The children elements of <code>aElement</code> will be searched
 * for the specified <code>aNS</code> namespace URI and the specified
 * <code>aTagName</code>. The first XML element found will be decoded and
 * returned. If no element is found, <code>null</code> is returned. The
 * format used for decoding the date is defined by the constant
 * <code>EPPUtil.DATE_FORMAT</code>.
 * /*from w  w  w. j ava2  s . co m*/
 * @param aElement
 *            XML Element to scan. For example, the element could be
 *            &lttrans-id&gt
 * @param aNS
 *            XML namespace of the elements. For example, for domain element
 *            this is "urn:iana:xmlns:epp".
 * @param aTagName
 *            Tag name of the element including an optional namespace
 *            prefix. For example, the tag name for the transaction Id date
 *            is "date".
 * @return <code>Date</code> value if found; <code>null</code> otherwise.
 * @exception EPPDecodeException
 *                Error decoding <code>aElement</code>.
 */
public static Date decodeDate(Element aElement, String aNS, String aTagName) throws EPPDecodeException {
    Date retVal = null;

    Element theElm = EPPUtil.getElementByTagNameNS(aElement, aNS, aTagName);

    if (theElm != null) {
        retVal = EPPUtil.decodeDate(theElm.getFirstChild().getNodeValue());
    }

    return retVal;
}

From source file:com.verisign.epp.codec.gen.EPPUtil.java

/**
 * Decode <code>Boolean</code>, by XML namespace and tag name, from an XML
 * Element. The children elements of <code>aElement</code> will be searched
 * for the specified <code>aNS</code> namespace URI and the specified
 * <code>aTagName</code>. The first XML element found will be decoded and
 * returned. If no element is found, <code>null</code> is returned.
 * //  ww w  .  j av  a  2s  .  c  o m
 * @param aElement
 *            XML Element to scan. For example, the element could be
 *            &ltdomain:create&gt
 * @param aNS
 *            XML namespace of the elements. For example, for domain element
 *            this is "urn:iana:xmlns:domain".
 * @param aTagName
 *            Tag name of the element including an optional namespace
 *            prefix. For example, the tag name for the domain name is
 *            "domain:name".
 * @return <code>Boolean</code> value if found; <code>null</code> otherwise.
 * @exception EPPDecodeException
 *                Error decoding <code>aElement</code>.
 */
public static Boolean decodeBoolean(Element aElement, String aNS, String aTagName) throws EPPDecodeException {
    Boolean retVal = null;
    String theVal = null;

    Element theElm = EPPUtil.getElementByTagNameNS(aElement, aNS, aTagName);

    if (theElm != null) {
        Node textNode = theElm.getFirstChild();

        // Element does have a text node?
        if (textNode != null) {
            theVal = textNode.getNodeValue();

            if (theVal.equalsIgnoreCase("true") || theVal.equals("1")) {
                retVal = new Boolean(true);
            } else {
                retVal = new Boolean(false);
            }
        } else {
            retVal = null;
        }
    }

    return retVal;
}

From source file:com.verisign.epp.codec.gen.EPPUtil.java

/**
 * Decode a <code>List</code> of <code>Integer</code>'s by XML namespace and
 * tag name, from an XML Element. The children elements of
 * <code>aElement</code> will be searched for the specified <code>aNS</code>
 * namespace URI and the specified <code>aTagName</code>. Each XML element
 * found will be decoded and added to the returned <code>List</code>. Empty
 * child elements, will result in an <code>EPPDecodeException</code>.
 * /*  w w w.  j a  va  2 s  .c  om*/
 * @param aElement
 *            XML Element to scan. For example, the element could be
 *            &ltdomain:update&gt
 * @param aNS
 *            XML namespace of the elements. For example, for domain element
 *            this is "urn:iana:xmlns:domain".
 * @param aTagName
 *            Tag name of the element including an optional namespace
 *            prefix. For example, the tag name for the domain name servers
 *            is "domain:server".
 * 
 * @return <code>List</code> of <code>Integer</code> elements representing
 *         the text nodes of the found XML elements.
 * 
 * @exception EPPDecodeException
 *                Error decoding <code>aElement</code>.
 */
public static List decodeIntegerList(Element aElement, String aNS, String aTagName) throws EPPDecodeException {

    List retVal = new ArrayList();

    Vector theChildren = EPPUtil.getElementsByTagNameNS(aElement, aNS, aTagName);

    for (int i = 0; i < theChildren.size(); i++) {
        Element currChild = (Element) theChildren.elementAt(i);

        Integer retInteger = null;

        Node textNode = currChild.getFirstChild();

        // Element does have a text node?
        if (textNode != null) {

            String intValStr = textNode.getNodeValue();
            try {
                retInteger = Integer.valueOf(intValStr);
            } catch (NumberFormatException e) {

                throw new EPPDecodeException(
                        "EPPUtil.decodeIntegerList Can't convert value to Integer: " + intValStr + e);
            }
        } else {
            throw new EPPDecodeException(
                    "EPPUtil.decodeIntegerList Can't decode numeric value from non-existant text node");
        }

        retVal.add(retInteger);
    }

    return retVal;
}

From source file:com.verisign.epp.codec.gen.EPPUtil.java

/**
 * Decode <code>Date</code>, as date and time, by XML namespace and tag
 * name, from an XML Element. The children elements of <code>aElement</code>
 * will be searched for the specified <code>aNS</code> namespace URI and the
 * specified <code>aTagName</code>. The first XML element found will be
 * decoded and returned. If no element is found, <code>null</code> is
 * returned. The format used for decoding the date is defined by the
 * constant <code>EPPUtil.TIME_INSTANT_FORMAT</code>.
 * // w  w w .  j a  v  a  2  s .com
 * @param aElement
 *            XML Element to scan. For example, the element could be
 *            &lttrans-id&gt
 * @param aNS
 *            XML namespace of the elements. For example, for domain element
 *            this is "urn:iana:xmlns:epp".
 * @param aTagName
 *            Tag name of the element including an optional namespace
 *            prefix. For example, the tag name for the transaction Id date
 *            is "date".
 * @return <code>Date</code> value as date and time if found;
 *         <code>null</code> otherwise.
 * @exception EPPDecodeException
 *                Error decoding <code>aElement</code>.
 */
public static Date decodeTimeInstant(Element aElement, String aNS, String aTagName) throws EPPDecodeException {
    Date retVal = null;

    Element theElm = EPPUtil.getElementByTagNameNS(aElement, aNS, aTagName);

    if (theElm != null) {
        retVal = EPPUtil.decodeTimeInstant(theElm.getFirstChild().getNodeValue());
    }

    return retVal;
}

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  w w.j  a v a2  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;
}