Example usage for org.w3c.dom Document getDocumentElement

List of usage examples for org.w3c.dom Document getDocumentElement

Introduction

In this page you can find the example usage for org.w3c.dom Document getDocumentElement.

Prototype

public Element getDocumentElement();

Source Link

Document

This is a convenience attribute that allows direct access to the child node that is the document element of the document.

Usage

From source file:Main.java

private static List<Element> getJsModulesForSpecificPlatform(Document doc, String platformName) {
    List<Element> suitableJsModules = new ArrayList<Element>();
    Element documentElement = doc.getDocumentElement();
    NodeList childNodes = documentElement.getChildNodes();

    for (int i = 0; i < childNodes.getLength(); i++) {
        Node node = childNodes.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            Element element = (Element) node;

            if (isJsModuleElement(element)) { // Common js-module for all types of projects (ios, android, wp8 etc.)
                suitableJsModules.add(element);
            } else if (isPlatformElement(element) && (element.getAttribute(ATTRIBUTE_NAME) != null)
                    && element.getAttribute(ATTRIBUTE_NAME).equals(platformName)) { // platform-specific js-module
                List<Element> androidJsModules = getChildElementsByName(element, TAG_JS_MODULE);
                suitableJsModules.addAll(androidJsModules);
            }//from w  ww .  j a  v  a2s . c o  m
        }
    }

    return suitableJsModules;
}

From source file:edu.wustl.cab2b.common.authentication.GTSSynchronizer.java

/**
 * This method generates the globus certificate in user.home folder
 * @param gridType/*  w w  w  . j a  va 2  s  .  c  o  m*/
 */
public static void generateGlobusCertificate() {
    URL signingPolicy = Utility.class.getClassLoader().getResource(CagridPropertyLoader.getSigningPolicy());
    URL certificate = Utility.class.getClassLoader().getResource(CagridPropertyLoader.getCertificate());

    if (signingPolicy != null || certificate != null) {
        copyCACertificates(signingPolicy);
        copyCACertificates(certificate);
    } else {
        logger.error("Could not find CA certificates");
        throw new AuthenticationException("Could not find CA certificates.", ErrorCodeConstants.CDS_016);
    }

    logger.debug("Getting sync-descriptor.xml file");
    try {
        logger.debug("Synchronizing with GTS service");
        URL syncDescFile = Utility.class.getClassLoader().getResource(CagridPropertyLoader.getSyncDesFile());

        Document doc = XMLUtils.newDocument(syncDescFile.openStream());
        Object obj = ObjectDeserializer.toObject(doc.getDocumentElement(), SyncDescription.class);
        SyncDescription description = (SyncDescription) obj;
        SyncGTS.getInstance().syncOnce(description);
        logger.debug("Successfully syncronized with GTS service. Globus certificates generated.");
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        throw new AuthenticationException(
                "Error occurred while generating globus certificates: " + e.getMessage(), e,
                ErrorCodeConstants.CDS_004);
    }
}

From source file:Main.java

public static void serializeXML(Document doc, Writer writer, boolean addXmlDeclaration) throws IOException {
    serializeXML(doc.getDocumentElement(), writer, addXmlDeclaration);
}

From source file:Main.java

private static boolean serializeXmlNode(Node node, Writer writer, boolean includeNode) throws IOException {
    if (node == null) {
        return false;
    }// w ww .j av a2 s.c  o m
    short type = node.getNodeType();
    boolean result = true;
    switch (type) {
    case Node.ATTRIBUTE_NODE: {
        String text = ((Attr) node).getValue();
        writer.write(text);
        break;
    }
    case Node.TEXT_NODE: {
        String text = ((Text) node).getData();
        writer.write(text);
        break;
    }
    case Node.ELEMENT_NODE: {
        Element element = (Element) node;
        if (includeNode) {
            serializeXML(element, writer, false);
        } else {
            Node child = element.getFirstChild();
            while (child != null) {
                serializeXmlNode(child, writer, true);
                child = child.getNextSibling();
            }
        }
        break;
    }
    case Node.DOCUMENT_NODE: {
        Document doc = (Document) node;
        serializeXmlNode(doc.getDocumentElement(), writer, includeNode);
        break;
    }
    default:
        result = false;
        break;
    }
    return result;
}

From source file:Main.java

/**
 * Add the breadcrumbs element to the document. This contains the
 * information for navigating back up through the application hierarchy.
 *
 * This creates a breadcrumbs element with child path elements in order
 * (each with a name and path attribute). The breadcrumbs element itself
 * also has a path attribute that specifies the root path.
 *
 * @param document/*  w  w  w.  j  a  va 2s  .  com*/
 * @param pathPrefix
 * @param relativePath
 */
public static void addBreadcrumbs(Document document, String pathPrefix, String relativePath) {

    if (document != null) {

        Element root = document.getDocumentElement();

        if (root != null) {

            // Create the breadcrumbs element with the associated path being
            // the root path for the set of paths.
            Element element = document.createElement("breadcrumbs");
            element.setAttribute("path", pathPrefix);

            StringBuilder path = new StringBuilder(pathPrefix);
            if (!"".equals(pathPrefix) && !pathPrefix.endsWith("/")) {
                path.append("/");
            }

            boolean first = true;
            for (String term : relativePath.split("/")) {
                if (!"".equals(term) && !".".equals(term)) {
                    if (!first) {
                        path.append("/");
                    }
                    path.append(term);

                    Element pathElement = document.createElement("crumb");
                    pathElement.setAttribute("name", term);
                    pathElement.setAttribute("path", path.toString());
                    element.appendChild(pathElement);

                    first = false;
                }
            }

            root.appendChild(element);
        }
    }
}

From source file:no.digipost.api.xml.Marshalling.java

public static void trimNamespaces(final Document doc) {
    NamedNodeMap attributes = doc.getDocumentElement().getAttributes();
    List<Attr> attrsToRemove = new ArrayList<Attr>();
    for (int i = 0; i < attributes.getLength(); i++) {
        if (doc.getElementsByTagNameNS(attributes.item(i).getNodeValue(), "*").getLength() == 0) {
            attrsToRemove.add((Attr) attributes.item(i));
        }/*from   w  w  w .ja  v a  2s  .c o m*/
    }
    for (Attr a : attrsToRemove) {
        doc.getDocumentElement().removeAttributeNode(a);
    }
}

From source file:com.wso2telco.workflow.utils.WorkflowProperties.java

public static Map<String, String> loadWorkflowPropertiesFromXML() {
    if (propertiesMap == null) {
        try {//from w w w.j a  va  2s.com
            propertiesMap = new HashMap<String, String>();

            DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();

            String carbonHome = System.getProperty("carbon.home");
            String workflowPropertiesFile = carbonHome + "/repository/conf/"
                    + Constants.WORKFLOW_PROPERTIES_XML_FILE;

            Document document = builder.parse(new File(workflowPropertiesFile));
            Element rootElement = document.getDocumentElement();

            NodeList nodeList = rootElement.getElementsByTagName("Property");
            if (nodeList != null && nodeList.getLength() > 0) {
                for (int i = 0; i < nodeList.getLength(); i++) {
                    Node node = nodeList.item(i);
                    String nodeName = node.getAttributes().getNamedItem("name").getNodeValue();
                    if (nodeName.equalsIgnoreCase(Constants.SERVICE_HOST)
                            || nodeName.equalsIgnoreCase(Constants.KEY_WORKFLOW_EMAIL_NOTIFICATION_HOST)
                            || nodeName.equalsIgnoreCase(Constants.KEY_WORKFLOW_EMAIL_NOTIFICATION_FROM_ADDRESS)
                            || nodeName
                                    .equalsIgnoreCase(Constants.KEY_WORKFLOW_EMAIL_NOTIFICATION_FROM_PASSWORD)
                            || nodeName.equalsIgnoreCase(Constants.PUBLISHER_ROLE_START_WITH)
                            || nodeName.equalsIgnoreCase(Constants.PUBLISHER_ROLE_END_WITH)
                            || nodeName.equalsIgnoreCase(Constants.MANDATE_SERVICE_HOST)) {
                        String value = ((Element) node).getTextContent();
                        propertiesMap.put(nodeName, value);
                    } else {
                        //Not a matching property
                    }
                }
            }
        } catch (Exception e) {
            String errorMessage = "Error in WorkflowProperties.loadWorkflowPropertiesFromXML";
            log.error(errorMessage, e);
        }
    } else {
        //Return already loaded propertiesMap
    }
    return propertiesMap;
}

From source file:de.tudarmstadt.ukp.shibhttpclient.Utils.java

/**
 * Helper method that deserializes and unmarshalls the message from the given stream. This method has been adapted from
 * {@code org.opensaml.ws.message.decoder.BaseMessageDecoder}.
 * /*from  w  w  w .  j  a  v  a  2s .com*/
 * @param messageStream
 *            input stream containing the message
 * 
 * @return the inbound message
 * 
 * @throws MessageDecodingException
 *             thrown if there is a problem deserializing and unmarshalling the message
 */
public static XMLObject unmarshallMessage(ParserPool parserPool, InputStream messageStream)
        throws ClientProtocolException {
    try {
        Document messageDoc = parserPool.parse(messageStream);
        Element messageElem = messageDoc.getDocumentElement();

        Unmarshaller unmarshaller = Configuration.getUnmarshallerFactory().getUnmarshaller(messageElem);
        if (unmarshaller == null) {
            throw new ClientProtocolException(
                    "Unable to unmarshall message, no unmarshaller registered for message element "
                            + XMLHelper.getNodeQName(messageElem));
        }

        XMLObject message = unmarshaller.unmarshall(messageElem);

        return message;
    } catch (XMLParserException e) {
        throw new ClientProtocolException("Encountered error parsing message into its DOM representation", e);
    } catch (UnmarshallingException e) {
        throw new ClientProtocolException("Encountered error unmarshalling message from its DOM representation",
                e);
    }
}

From source file:Main.java

/**
 * returns a XML node value./* w w  w.j  a  v  a  2 s .  c o  m*/
 *
 * @param pDocument         Document XML DOM document
 * @param psTagName         String XML node name
 * @return                  String XML node value
 */
public static String getValue(Document pDocument, String psTagName) throws Exception {
    String s = null;
    try {
        NodeList elements = pDocument.getDocumentElement().getElementsByTagName(psTagName);
        Node node = elements.item(0);
        NodeList nodes = node.getChildNodes();
        //find a value whose value is non-whitespace
        for (int i = 0; i < nodes.getLength(); i++) {
            s = ((Node) nodes.item(i)).getNodeValue().trim();
            if (s.equals("") || s.equals("\r"))
                continue;
        }
    } catch (Exception ex) {
        throw new Exception(ex.getMessage());
    }
    return s;
}

From source file:Main.java

/**
 * Select node list what matches given xpath query
 *
 * @param doc        xml document//from w w  w .j a  v a 2 s.  c o m
 * @param expression xpath query
 * @return nodes which confirms given xpath query.
 * @throws XPathExpressionException in case of any errors.
 */
public static NodeList query(final Document doc, final String expression) throws XPathExpressionException {
    final XPath xpath = XPathFactory.newInstance().newXPath();
    return (NodeList) xpath.evaluate(expression, doc.getDocumentElement(), XPathConstants.NODESET);
}