Example usage for org.w3c.dom Document getFirstChild

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

Introduction

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

Prototype

public Node getFirstChild();

Source Link

Document

The first child of this node.

Usage

From source file:Main.java

private static String getMetaScriptType(Document doc) {
    // Can not just do a Document.getElementsByTagName(String) as this
    // needs/*ww  w.  j  a va  2s.  c  o m*/
    // to be relatively fast.
    List metas = new ArrayList();
    // check for META tags under the Document
    Node html = null;
    Node head = null;
    Node child = null;
    // ----------------------------------------------------------------------
    // (pa) 20021217
    // cmvc defect 235554
    // performance enhancement: using child.getNextSibling() rather than
    // nodeList(item) for O(n) vs. O(n*n)
    // ----------------------------------------------------------------------

    for (child = doc.getFirstChild(); child != null; child = child.getNextSibling()) {
        if (child.getNodeType() != Node.ELEMENT_NODE) {
            continue;
        }
        if (child.getNodeName().equalsIgnoreCase(META)) {
            metas.add(child);
        } else if (child.getNodeName().equalsIgnoreCase(HTML)) {
            html = child;
        }
    }
    // NodeList children = doc.getChildNodes();
    // for(int i = 0; i < children.getLength(); i++) {
    // child = children.item(i);
    // if(child.getNodeType() != Node.ELEMENT_NODE)
    // continue;
    // if(child.getNodeName().equalsIgnoreCase(META))
    // metas.add(child);
    // else if(child.getNodeName().equalsIgnoreCase(HTML))
    // html = child;
    // }

    // check for META tags under HEAD
    if (html != null) {
        for (child = html.getFirstChild(); (child != null) && (head == null); child = child.getNextSibling()) {
            if (child.getNodeType() != Node.ELEMENT_NODE) {
                continue;
            }
            if (child.getNodeName().equalsIgnoreCase(HEAD)) {
                head = child;
            }
        }
        // children = html.getChildNodes();
        // for(int i = 0; i < children.getLength() && head == null; i++) {
        // child = children.item(i);
        // if(child.getNodeType() != Node.ELEMENT_NODE)
        // continue;
        // if(child.getNodeName().equalsIgnoreCase(HEAD))
        // head = child;
        // }
    }

    if (head != null) {
        for (head.getFirstChild(); child != null; child = child.getNextSibling()) {
            if (child.getNodeType() != Node.ELEMENT_NODE) {
                continue;
            }
            if (child.getNodeName().equalsIgnoreCase(META)) {
                metas.add(child);
            }
        }
        // children = head.getChildNodes();
        // for(int i = 0 ; i < children.getLength(); i++) {
        // child = children.item(i);
        // if(child.getNodeType() != Node.ELEMENT_NODE)
        // continue;
        // if(child.getNodeName().equalsIgnoreCase(META))
        // metas.add(child);
        // }
    }

    return getMetaScriptType(metas);
}

From source file:de.mpg.escidoc.services.common.util.Util.java

public static Node querySSRNId(String conePersonUrl) {
    DocumentBuilder documentBuilder;
    HttpClient client = new HttpClient();
    try {/*from ww w.  ja  v  a 2  s  .  c om*/
        documentBuilder = DocumentBuilderFactoryImpl.newInstance().newDocumentBuilder();

        Document document = documentBuilder.newDocument();
        Element element = document.createElement("cone");
        document.appendChild(element);
        GetMethod detailMethod = new GetMethod(conePersonUrl + "?format=rdf");
        ProxyHelper.setProxy(client, conePersonUrl);
        client.executeMethod(detailMethod);
        if (detailMethod.getStatusCode() == 200) {
            Document details = documentBuilder.parse(detailMethod.getResponseBodyAsStream());
            element.appendChild(document.importNode(details.getFirstChild(), true));
            return document;
        } else {
            logger.error("Error querying CoNE: Status " + detailMethod.getStatusCode() + "\n"
                    + detailMethod.getResponseBodyAsString());
            return null;
        }

    } catch (Exception e) {
        logger.error("Error querying CoNE service. This is normal during unit tests. "
                + "Otherwise it should be clarified if any measures have to be taken.");
        return null;
    }

}

From source file:de.mpg.escidoc.services.common.util.Util.java

/**
  * Execute the GET-method.//from  ww  w .  ja v  a  2s.co m
  * @param client
  * @param queryUrl
  * @param documentBuilder
  * @param document
  * @param element
  * @return true if the array contains the format object, else false
  */
private static void executeGetMethod(HttpClient client, String queryUrl, DocumentBuilder documentBuilder,
        Document document, Element element) {
    String previousUrl = null;
    try {
        GetMethod method = new GetMethod(queryUrl);
        ProxyHelper.executeMethod(client, method);
        logger.info("queryURL from executeGetMethod  " + queryUrl);

        if (method.getStatusCode() == 200) {
            String[] results = method.getResponseBodyAsString().split("\n");
            for (String result : results) {
                if (!"".equals(result.trim())) {
                    String detailsUrl = result.split("\\|")[1];
                    // if there is an alternative name, take only the first occurrence
                    if (!detailsUrl.equalsIgnoreCase(previousUrl)) {
                        GetMethod detailMethod = new GetMethod(detailsUrl + "?format=rdf");
                        previousUrl = detailsUrl;

                        logger.info(detailMethod.getPath());
                        logger.info(detailMethod.getQueryString());

                        ProxyHelper.setProxy(client, detailsUrl);
                        client.executeMethod(detailMethod);
                        if (detailMethod.getStatusCode() == 200) {
                            Document details = documentBuilder.parse(detailMethod.getResponseBodyAsStream());
                            element.appendChild(document.importNode(details.getFirstChild(), true));
                        } else {
                            logger.error("Error querying CoNE: Status " + detailMethod.getStatusCode() + "\n"
                                    + detailMethod.getResponseBodyAsString());
                        }
                    }
                }
            }

        } else {
            logger.error("Error querying CoNE: Status " + method.getStatusCode() + "\n"
                    + method.getResponseBodyAsString());
        }
    } catch (Exception e) {
        logger.error("Error querying CoNE service. This is normal during unit tests. "
                + "Otherwise it should be clarified if any measures have to be taken.");
    }
}

From source file:com.msopentech.applicationgateway.connection.Router.java

/**
 * Performs HTTP POST request and obtains authentication token.
 * //from   ww w  .ja  v a  2  s. co  m
 * @param credentials Authentication credentials
 * 
 * @return {@link ConnectionTraits} with valid token OR with an error message if exception is caught or token retrieval failed or
 *         token is <code>null</code> or an empty string. Does NOT return <code>null</code>.
 */
private static ConnectionTraits obtainToken(Credentials credentials) {
    ConnectionTraits connection = new ConnectionTraits();

    try {
        HttpClient client = new DefaultHttpClient();
        HttpPost request = new HttpPost("https://login.microsoftonline.com/extSTS.srf");

        request.addHeader("SOAPAction", "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Issue");
        request.addHeader("Content-Type", "application/soap+xml; charset=utf-8");

        Date now = new Date();
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.sssZ");
        String nowAsString = df.format(now);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(now);
        calendar.add(Calendar.SECOND, 10 * 60);
        Date expires = calendar.getTime();
        String expirationAsString = df.format(expires);

        String message = requestTemplate;

        message = message.replace("#{user}", credentials.getUsername());
        message = message.replace("#{pass}", credentials.getPassword());
        message = message.replace("#{created}", nowAsString);
        message = message.replace("#{expires}", expirationAsString);
        message = message.replace("#{resource}", "appgportal.cloudapp.net");

        StringEntity requestBody = new StringEntity(message, HTTP.UTF_8);
        requestBody.setContentType("text/xml");
        request.setEntity(requestBody);

        BasicHttpResponse response = null;
        response = (BasicHttpResponse) client.execute(request);

        HttpEntity entity = response.getEntity();
        InputStream inputStream = null;
        String token = null;

        inputStream = entity.getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        String line;
        StringBuffer actualResponse = new StringBuffer();
        while ((line = reader.readLine()) != null) {
            actualResponse.append(line);
            actualResponse.append('\r');
        }
        token = actualResponse.toString();

        String start = "<wst:RequestedSecurityToken>";

        int index = token.indexOf(start);

        if (-1 == index) {
            DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder documentBuilder = documentFactory.newDocumentBuilder();
            InputStream errorInputStream = new ByteArrayInputStream(token.getBytes());
            Document currentDoc = documentBuilder.parse(errorInputStream);

            if (currentDoc == null) {
                return null;
            }

            String errorReason = null;
            String errorExplained = null;
            Node rootNode = null;
            if ((rootNode = currentDoc.getFirstChild()) != null && /* <S:Envelope> */
                    (rootNode = XmlUtility.getChildNode(rootNode, "S:Body")) != null
                    && (rootNode = XmlUtility.getChildNode(rootNode, "S:Fault")) != null) {
                Node node = null;
                if ((node = XmlUtility.getChildNode(rootNode, "S:Reason")) != null) {
                    errorReason = XmlUtility.getChildNodeValue(node, "S:Text");
                }
                if ((node = XmlUtility.getChildNode(rootNode, "S:Detail")) != null
                        && (node = XmlUtility.getChildNode(node, "psf:error")) != null
                        && (node = XmlUtility.getChildNode(node, "psf:internalerror")) != null) {
                    errorExplained = XmlUtility.getChildNodeValue(node, "psf:text");
                }
            }

            if (!TextUtils.isEmpty(errorReason) && !TextUtils.isEmpty(errorExplained)) {
                logError(null, Router.class.getSimpleName() + ".obtainToken(): " + errorReason + " - "
                        + errorExplained);
                connection.setError(String.format(ERROR_TOKEN, errorReason + ": " + errorExplained));
                return connection;
            }
        } else {
            token = token.substring(index);

            String end = "</wst:RequestedSecurityToken>";

            index = token.indexOf(end) + end.length();
            token = token.substring(0, index);

            if (!TextUtils.isEmpty(token)) {
                connection.setToken(token);
                return connection;
            }
        }
    } catch (final Exception e) {
        logError(e, Router.class.getSimpleName() + ".obtainToken() Failed");
        return connection.setError(String.format(ERROR_TOKEN, "Token retrieval failed with exception."));
    }
    return connection.setError(String.format(ERROR_TOKEN, "Token retrieval failed."));
}

From source file:de.mpg.escidoc.services.common.util.Util.java

/**
 * Queries CoNE service and returns the result as DOM node.
 * The returned XML has the following structure:
 * <cone>/*from w  w  w.  j  av  a2 s . co m*/
 *   <author>
 *     <familyname>Buxtehude-Mlln</familyname>
 *     <givenname>Heribert</givenname>
 *     <prefix>von und zu</prefix>
 *     <title>Knig</title>
 *   </author>
 *   <author>
 *     <familyname>Mller</familyname>
 *     <givenname>Peter</givenname>
 *   </author>
 * </authors>
 * 
 * @param authors
 * @return 
 */
// IMPORTANT!!! Currently not working due to missing userHnadle info
public static Node queryCone(String model, String query) {
    DocumentBuilder documentBuilder;
    String queryUrl = null;
    try {
        System.out.println("queryCone: " + model);

        documentBuilder = DocumentBuilderFactoryImpl.newInstance().newDocumentBuilder();

        Document document = documentBuilder.newDocument();
        Element element = document.createElement("cone");
        document.appendChild(element);

        queryUrl = PropertyReader.getProperty("escidoc.cone.service.url") + model + "/query?format=jquery&q="
                + URLEncoder.encode(query, "UTF-8");
        String detailsUrl = PropertyReader.getProperty("escidoc.cone.service.url") + model
                + "/resource/$1?format=rdf";
        HttpClient client = new HttpClient();
        GetMethod method = new GetMethod(queryUrl);

        String coneSession = getConeSession();

        if (coneSession != null) {
            method.setRequestHeader("Cookie", "JSESSIONID=" + coneSession);
        }
        ProxyHelper.executeMethod(client, method);

        if (method.getStatusCode() == 200) {
            String[] results = method.getResponseBodyAsString().split("\n");
            for (String result : results) {
                if (!"".equals(result.trim())) {
                    String id = result.split("\\|")[1];
                    GetMethod detailMethod = new GetMethod(id + "?format=rdf&eSciDocUserHandle=" + "TODO");
                    logger.info(detailMethod.getPath());
                    logger.info(detailMethod.getQueryString());

                    if (coneSession != null) {
                        detailMethod.setRequestHeader("Cookie", "JSESSIONID=" + coneSession);
                    }
                    ProxyHelper.executeMethod(client, detailMethod);

                    if (detailMethod.getStatusCode() == 200) {
                        Document details = documentBuilder.parse(detailMethod.getResponseBodyAsStream());
                        element.appendChild(document.importNode(details.getFirstChild(), true));
                    } else {
                        logger.error("Error querying CoNE: Status " + detailMethod.getStatusCode() + "\n"
                                + detailMethod.getResponseBodyAsString());
                    }
                }
            }
        } else {
            logger.error("Error querying CoNE: Status " + method.getStatusCode() + "\n"
                    + method.getResponseBodyAsString());
        }

        return document;
    } catch (Exception e) {
        logger.error("Error querying CoNE service. This is normal during unit tests. (" + queryUrl
                + ") .Otherwise it should be clarified if any measures have to be taken.");
        logger.debug("Stacktrace", e);
        return null;
        //throw new RuntimeException(e);
    }
}

From source file:de.mpg.escidoc.services.common.util.Util.java

/**
 * Queries the CoNE service and transforms the result into a DOM node.
 * /*from   w  ww  . jav  a2s.  c  o m*/
 * @param model The type of object (e.g. "persons")
 * @param name The query string.
 * @param ou Specialty for persons
 * @param coneSession A JSESSIONID to not produce a new session with each call.
 * @return A DOM node containing the results.
 */
public static Node queryConeExactWithIdentifier(String model, String identifier, String ou) {
    DocumentBuilder documentBuilder;

    try {
        System.out.println("queryConeExact: " + model);

        documentBuilder = DocumentBuilderFactoryImpl.newInstance().newDocumentBuilder();

        Document document = documentBuilder.newDocument();
        Element element = document.createElement("cone");
        document.appendChild(element);

        String queryUrl = PropertyReader.getProperty("escidoc.cone.service.url") + model
                + "/query?format=jquery&dc:identifier/rdf:value=\"" + URLEncoder.encode(identifier, "UTF-8")
                + "\"&escidoc:position/eprints:affiliatedInstitution=" + URLEncoder.encode(ou, "UTF-8") + "";
        String detailsUrl = PropertyReader.getProperty("escidoc.cone.service.url") + model
                + "/resource/$1?format=rdf";
        HttpClient client = new HttpClient();
        GetMethod method = new GetMethod(queryUrl);

        String coneSession = getConeSession();

        if (coneSession != null) {
            method.setRequestHeader("Cookie", "JSESSIONID=" + coneSession);
        }
        ProxyHelper.executeMethod(client, method);
        logger.info("CoNE query: " + queryUrl + " returned " + method.getResponseBodyAsString());
        if (method.getStatusCode() == 200) {
            ArrayList<String> results = new ArrayList<String>();
            results.addAll(Arrays.asList(method.getResponseBodyAsString().split("\n")));
            Set<String> oldIds = new HashSet<String>();
            for (String result : results) {
                if (!"".equals(result.trim())) {
                    String id = result.split("\\|")[1];
                    if (!oldIds.contains(id)) {
                        GetMethod detailMethod = new GetMethod(id + "?format=rdf&eSciDocUserHandle=" + "TODO");

                        ProxyHelper.setProxy(client, detailsUrl.replace("$1", id));
                        client.executeMethod(detailMethod);
                        logger.info("CoNE query: " + id + "?format=rdf&eSciDocUserHandle=" + "TODO"
                                + " returned " + detailMethod.getResponseBodyAsString());
                        if (detailMethod.getStatusCode() == 200) {
                            Document details = documentBuilder.parse(detailMethod.getResponseBodyAsStream());
                            element.appendChild(document.importNode(details.getFirstChild(), true));
                        } else {
                            logger.error("Error querying CoNE: Status " + detailMethod.getStatusCode() + "\n"
                                    + detailMethod.getResponseBodyAsString());
                        }
                        oldIds.add(id);
                    }
                }
            }
        } else {
            logger.error("Error querying CoNE: Status " + method.getStatusCode() + "\n"
                    + method.getResponseBodyAsString());
        }
        return document;
    } catch (Exception e) {
        logger.error("Error querying CoNE service. This is normal during unit tests. "
                + "Otherwise it should be clarified if any measures have to be taken.");
        return null;
        //throw new RuntimeException(e);
    }
}

From source file:edu.virginia.speclab.juxta.author.model.JuxtaXMLParser.java

static public String getIndexBasedXPathForGeneralXPath(String xpathString, String xml) {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    try {/*from  w w  w  .ja v a 2 s. c  om*/
        factory.setNamespaceAware(false); // ignore the horrible issues of namespacing
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(new InputSource(new StringReader(xml)));
        XPathFactory xpathFactory = XPathFactory.newInstance();
        XPath xpath = xpathFactory.newXPath();
        Node root = doc.getFirstChild();
        XPathExpression expr = xpath.compile(xpathString);
        Node node = (Node) expr.evaluate(doc, XPathConstants.NODE);
        return nodeToSimpleXPath(node, root);
    } catch (SAXException ex) {
    } catch (IOException ex) {
    } catch (XPathExpressionException ex) {
    } catch (ParserConfigurationException ex) {
    }
    return null;
}

From source file:de.mpg.escidoc.services.common.util.Util.java

/**
 * Queries the CoNE service and transforms the result into a DOM node.
 * //from   w  w  w. java2 s . c o m
 * @param model The type of object (e.g. "persons")
 * @param name The query string.
 * @param ou Specialty for persons
 * @param coneSession A JSESSIONID to not produce a new session with each call.
 * @return A DOM node containing the results.
 */
public static Node queryConeExact(String model, String name, String ou) {
    DocumentBuilder documentBuilder;

    try {
        System.out.println("queryConeExact: " + model);

        documentBuilder = DocumentBuilderFactoryImpl.newInstance().newDocumentBuilder();

        Document document = documentBuilder.newDocument();
        Element element = document.createElement("cone");
        document.appendChild(element);

        String queryUrl = PropertyReader.getProperty("escidoc.cone.service.url") + model
                + "/query?format=jquery&dc:title=\"" + URLEncoder.encode(name, "UTF-8")
                + "\"&escidoc:position/eprints:affiliatedInstitution=" + URLEncoder.encode(ou, "UTF-8") + "";
        String detailsUrl = PropertyReader.getProperty("escidoc.cone.service.url") + model
                + "/resource/$1?format=rdf";
        HttpClient client = new HttpClient();
        GetMethod method = new GetMethod(queryUrl);

        String coneSession = getConeSession();

        if (coneSession != null) {
            method.setRequestHeader("Cookie", "JSESSIONID=" + coneSession);
        }
        ProxyHelper.executeMethod(client, method);
        logger.info("CoNE query: " + queryUrl + " returned " + method.getResponseBodyAsString());
        if (method.getStatusCode() == 200) {
            ArrayList<String> results = new ArrayList<String>();
            results.addAll(Arrays.asList(method.getResponseBodyAsString().split("\n")));
            queryUrl = PropertyReader.getProperty("escidoc.cone.service.url") + model
                    + "/query?format=jquery&dcterms:alternative=\"" + URLEncoder.encode(name, "UTF-8")
                    + "\"&escidoc:position/eprints:affiliatedInstitution=" + URLEncoder.encode(ou, "UTF-8");
            client = new HttpClient();
            method = new GetMethod(queryUrl);
            if (coneSession != null) {
                method.setRequestHeader("Cookie", "JSESSIONID=" + coneSession);
            }
            ProxyHelper.executeMethod(client, method);
            logger.info("CoNE query: " + queryUrl + " returned " + method.getResponseBodyAsString());
            if (method.getStatusCode() == 200) {
                results.addAll(Arrays.asList(method.getResponseBodyAsString().split("\n")));
                Set<String> oldIds = new HashSet<String>();
                for (String result : results) {
                    if (!"".equals(result.trim())) {
                        String id = result.split("\\|")[1];
                        if (!oldIds.contains(id)) {
                            GetMethod detailMethod = new GetMethod(
                                    id + "?format=rdf&eSciDocUserHandle=" + "TODO");

                            ProxyHelper.setProxy(client, detailsUrl.replace("$1", id));
                            client.executeMethod(detailMethod);
                            logger.info("CoNE query: " + id + "?format=rdf&eSciDocUserHandle=" + "TODO"
                                    + " returned " + detailMethod.getResponseBodyAsString());
                            if (detailMethod.getStatusCode() == 200) {
                                Document details = documentBuilder
                                        .parse(detailMethod.getResponseBodyAsStream());
                                element.appendChild(document.importNode(details.getFirstChild(), true));
                            } else {
                                logger.error("Error querying CoNE: Status " + detailMethod.getStatusCode()
                                        + "\n" + detailMethod.getResponseBodyAsString());
                            }
                            oldIds.add(id);
                        }
                    }
                }
            }
        } else {
            logger.error("Error querying CoNE: Status " + method.getStatusCode() + "\n"
                    + method.getResponseBodyAsString());
        }
        return document;
    } catch (Exception e) {
        logger.error("Error querying CoNE service. This is normal during unit tests. "
                + "Otherwise it should be clarified if any measures have to be taken.");
        return null;
        //throw new RuntimeException(e);
    }
}

From source file:com.wavemaker.tools.ws.WebServiceToolsManager.java

/**
 * Returns the XML qualified name of the root element type for the given XML.
 *///w  ww  . j a va  2  s  .  co  m
public static String getXmlRootElementType(String xml)
        throws ParserConfigurationException, SAXException, IOException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    DocumentBuilder db = dbf.newDocumentBuilder();
    Reader reader = new StringReader(xml);
    Document doc = db.parse(new InputSource(reader));
    Node node = doc.getFirstChild();
    if (node != null) {
        String namespaceURI = node.getNamespaceURI();
        String localName = node.getLocalName();
        if (localName != null) {
            return namespaceURI == null ? localName : namespaceURI + ":" + localName;
        }
    }
    return null;
}

From source file:net.javacrumbs.smock.common.groovy.GroovyTemplateProcessor.java

public Source processTemplate(Source template, Source input, Map<String, Object> parameters) {
    try {//from w  w  w . j a v a2 s  . co  m
        String templateText = serialize(template);
        HashMap<String, Object> binding = new HashMap<String, Object>(parameters);
        if (input != null) {
            Document inputDocument = loadDocument(input);
            binding.put(inputDocument.getFirstChild().getLocalName(),
                    new XmlSlurper().parse(new StringReader(serialize(inputDocument))));
        }
        binding.put("IGNORE", "${IGNORE}");
        return new StringSource(templateEngine.createTemplate(templateText).make(binding).toString());
    } catch (Exception e) {
        throw new IllegalArgumentException("Can not process Groovy template.", e);
    }
}