Example usage for javax.xml.parsers DocumentBuilder newDocument

List of usage examples for javax.xml.parsers DocumentBuilder newDocument

Introduction

In this page you can find the example usage for javax.xml.parsers DocumentBuilder newDocument.

Prototype


public abstract Document newDocument();

Source Link

Document

Obtain a new instance of a DOM Document object to build a DOM tree with.

Usage

From source file:com.adaptris.core.services.jdbc.XmlPayloadTranslator.java

private DocumentWrapper toDocument(JdbcResult rs, AdaptrisMessage msg)
        throws ParserConfigurationException, SQLException {
    XmlUtils xu = createXmlUtils(msg);/*  w w  w . j av a2  s .c  om*/
    DocumentBuilderFactoryBuilder factoryBuilder = documentFactoryBuilder(msg);
    DocumentBuilderFactory factory = factoryBuilder.configure(DocumentBuilderFactory.newInstance());
    DocumentBuilder builder = factoryBuilder.configure(factory.newDocumentBuilder());
    Document doc = builder.newDocument();
    DocumentWrapper result = new DocumentWrapper(doc, 0);
    ColumnStyle elementNameStyle = getColumnNameStyle();

    Element results = doc.createElement(elementNameStyle.format(ELEMENT_NAME_RESULTS));
    doc.appendChild(results);

    if (isPreserveOriginalMessage()) {
        Element originalMessage = doc.createElement(elementNameStyle.format(ORIGINAL_MESSAGE_ELEMENT));

        if (xu.isDocumentValid()) {
            Node n = xu.getSingleNode("/").getFirstChild();
            originalMessage.appendChild(doc.importNode(n, true));
        } else {
            // Not XML, so let's add it in as a CDATA node.
            originalMessage.appendChild(createTextNode(doc, msg.getContent(), true));
        }
        results.appendChild(originalMessage);
    }
    for (JdbcResultSet rSet : rs.getResultSets()) {
        List<Element> elements = createListFromResultSet(builder, doc, rSet);
        for (Element element : elements) {
            results.appendChild(element);
        }
        result.resultSetCount += elements.size();
    }
    return result;
}

From source file:it.pronetics.madstore.crawler.publisher.impl.AtomPublisherImpl.java

private Element createCollectionElement(String key, String href, String title) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);/*w ww .  j  a va 2 s . c o m*/
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document collectionDocument = builder.newDocument();
    Element collectionelElement = collectionDocument.createElementNS(AtomConstants.APP_NS,
            AtomConstants.ATOM_COLLECTION);
    collectionelElement.setAttribute(AtomConstants.ATOM_KEY, key);
    collectionelElement.setAttribute(AtomConstants.ATOM_COLLECTION_HREF, href);
    Element acceptElement = collectionDocument.createElementNS(AtomConstants.APP_NS,
            AtomConstants.ATOM_COLLECTION_ACCEPT);
    Element titleElement = collectionDocument.createElementNS(AtomConstants.ATOM_NS,
            AtomConstants.ATOM_COLLECTION_TITLE);
    titleElement.setTextContent(title);
    collectionelElement.appendChild(acceptElement);
    collectionelElement.appendChild(titleElement);
    collectionDocument.appendChild(collectionelElement);
    return collectionelElement;
}

From source file:com.msopentech.odatajclient.engine.data.impl.v3.AtomSerializer.java

private Element feed(final AtomFeed feed) throws ParserConfigurationException {
    final DocumentBuilder builder = XMLUtils.DOC_BUILDER_FACTORY.newDocumentBuilder();
    final Document doc = builder.newDocument();

    final Element feedElem = doc.createElement(ODataConstants.ATOM_ELEM_FEED);
    feedElem.setAttribute(XMLConstants.XMLNS_ATTRIBUTE, ODataConstants.NS_ATOM);
    feedElem.setAttribute(ODataConstants.XMLNS_METADATA,
            client.getWorkingVersion().getNamespaceMap().get(ODataVersion.NS_METADATA));
    feedElem.setAttribute(ODataConstants.XMLNS_DATASERVICES,
            client.getWorkingVersion().getNamespaceMap().get(ODataVersion.NS_DATASERVICES));
    feedElem.setAttribute(ODataConstants.XMLNS_GML, ODataConstants.NS_GML);
    feedElem.setAttribute(ODataConstants.XMLNS_GEORSS, ODataConstants.NS_GEORSS);
    if (feed.getBaseURI() != null) {
        feedElem.setAttribute(ODataConstants.ATTR_XMLBASE, feed.getBaseURI().toASCIIString());
    }/* ww w .j ava  2  s  . com*/
    doc.appendChild(feedElem);

    if (StringUtils.isNotBlank(feed.getTitle())) {
        final Element title = doc.createElement(ODataConstants.ATOM_ELEM_TITLE);
        title.appendChild(doc.createTextNode(feed.getTitle()));
        feedElem.appendChild(title);
    }

    if (StringUtils.isNotBlank(feed.getSummary())) {
        final Element summary = doc.createElement(ODataConstants.ATOM_ELEM_SUMMARY);
        summary.appendChild(doc.createTextNode(feed.getSummary()));
        feedElem.appendChild(summary);
    }

    for (AtomEntry entry : feed.getEntries()) {
        feedElem.appendChild(doc.importNode(entry(entry), true));
    }

    return feedElem;
}

From source file:com.graphhopper.http.GraphHopperServlet.java

String errorsToXML(List<Throwable> list) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.newDocument();
    Element gpxElement = doc.createElement("gpx");
    gpxElement.setAttribute("creator", "GraphHopper");
    gpxElement.setAttribute("version", "1.1");
    doc.appendChild(gpxElement);/*from  w  w w .ja va 2s .c  o m*/

    Element mdElement = doc.createElement("metadata");
    gpxElement.appendChild(mdElement);

    Element errorsElement = doc.createElement("extensions");
    mdElement.appendChild(errorsElement);

    for (Throwable t : list) {
        Element error = doc.createElement("error");
        errorsElement.appendChild(error);
        error.setAttribute("message", t.getMessage());
        error.setAttribute("details", t.getClass().getName());
    }
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    StringWriter writer = new StringWriter();
    transformer.transform(new DOMSource(doc), new StreamResult(writer));
    return writer.toString();
}

From source file:eu.eexcess.zbw.recommender.PartnerConnector.java

@Override
public Document queryPartner(PartnerConfiguration partnerConfiguration, SecureUserProfile userProfile,
        PartnerdataLogger logger) throws IOException {

    // Configure/*from   w ww. j  a  v  a 2s .co m*/
    try {
        Client client = new Client(PartnerConfigurationEnum.CONFIG.getClientJAXBContext());
        queryGenerator = PartnerConfigurationEnum.CONFIG.getQueryGenerator();

        String query = getQueryGenerator().toQuery(userProfile);
        query = query.replaceAll("\"", "");
        query = query.replaceAll("\\(", " ");
        query = query.replaceAll("\\)", " ");
        query = URLEncoder.encode(query, "UTF-8");
        Map<String, String> valuesMap = new HashMap<String, String>();
        valuesMap.put("query", query);
        if (userProfile.numResults != null)
            valuesMap.put("size", userProfile.numResults.toString());
        else
            valuesMap.put("size", "10");
        String searchRequest = StrSubstitutor.replace(partnerConfiguration.searchEndpoint, valuesMap);

        WebResource service = client.resource(searchRequest);
        log.log(Level.INFO, "SearchRequest: " + searchRequest);

        Builder builder = service.accept(MediaType.APPLICATION_XML);
        String response = builder.get(String.class);
        StringReader respStringReader = new StringReader(response);
        client.destroy();
        JAXBContext jaxbContext = JAXBContext.newInstance(ZBWDocument.class);
        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        ZBWDocument zbwResponse = (ZBWDocument) jaxbUnmarshaller.unmarshal(respStringReader);
        for (ZBWDocumentHit hit : zbwResponse.hits.hit) {
            try {
                if (hit.element.type.equals("event")) {
                    Document detail = fetchDocumentDetails(hit.element.id);
                    PartnerdataTracer.dumpFile(this.getClass(), partnerConfiguration, detail, "detail-response",
                            logger);
                    String latValue = getValueWithXPath("/doc/record/geocode/lat", detail);
                    String longValue = getValueWithXPath("/doc/record/geocode/lng", detail);
                    hit.element.lat = latValue;
                    hit.element.lng = longValue;
                }
            } catch (Exception e) {
                log.log(Level.WARNING,
                        "Could not get longitude and latitude for event element " + hit.element.id, e);
            }
            // put all creators in the creatorString
            if (hit.element.creator != null) {
                for (String creator : hit.element.creator) {
                    if (hit.element.creatorString == null)
                        hit.element.creatorString = "";
                    if (hit.element.creatorString.length() > 0)
                        hit.element.creatorString += ", ";
                    hit.element.creatorString += creator;
                }
            }
        }
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document document = db.newDocument();
        Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.marshal(zbwResponse, document);

        return document;
    } catch (Exception e) {
        throw new IOException("Cannot query partner REST API!", e);
    }

}

From source file:com.weaforce.system.component.fckeditor.response.XmlResponse.java

/**
 * //www. ja v a 2s .c  om
 * Use this contructor if want to respond a negative/error message with
 * custom text.
 * 
 * @param number
 * @param text
 */
public XmlResponse(int number, String text) {
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        document = builder.newDocument();
    } catch (ParserConfigurationException e) {
        throw new RuntimeException(e);
    }

    Element root = document.createElement("Connector");
    document.appendChild(root);
    setError(number, text);
}

From source file:mx.bigdata.sat.cfd.CFDv2.java

private Comprobante copy(Comprobante comprobante) throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);/* w w w  . j  a v a2s  .co m*/
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.newDocument();
    Marshaller m = context.createMarshaller();
    m.marshal(comprobante, doc);
    Unmarshaller u = context.createUnmarshaller();
    return (Comprobante) u.unmarshal(doc);
}

From source file:mx.bigdata.sat.cfdi.TFDv1_v32.java

private Element marshalTFD() throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);//from  w  w  w .  java2 s.c  o  m
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.newDocument();
    Marshaller m = CONTEXT.createMarshaller();
    m.setProperty("com.sun.xml.bind.namespacePrefixMapper", new NamespacePrefixMapperImpl(CFDv32.PREFIXES));
    m.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
    m.setProperty(Marshaller.JAXB_SCHEMA_LOCATION,
            "http://www.sat.gob.mx/TimbreFiscalDigital http://www.sat.gob.mx/sitio_internet/TimbreFiscalDigital/TimbreFiscalDigital.xsd");
    m.marshal(tfd, doc);
    return doc.getDocumentElement();
}

From source file:de.mpg.escidoc.services.transformation.Util.java

/**
 * Queries CoNE service and returns the result as DOM node.
 * The returned XML has the following structure:
 * <cone>//  w  w w .ja v a  2 s.  c  o 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 
 */
public static Node queryCone(String model, String query) {
    DocumentBuilder documentBuilder;
    String queryUrl = null;
    try {
        logger.info("queryCone: " + model + " query: " + query);

        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();
        client.getParams().setParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true);
        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];
                    // TODO "&redirect=true" must be reinserted again
                    GetMethod detailMethod = new GetMethod(id + "?format=rdf&eSciDocUserHandle="
                            + Base64.encode(AdminHelper.getAdminUserHandle().getBytes("UTF-8")));
                    detailMethod.setFollowRedirects(true);

                    if (coneSession != null) {
                        detailMethod.setRequestHeader("Cookie", "JSESSIONID=" + coneSession);
                    }
                    ProxyHelper.executeMethod(client, detailMethod);
                    if (logger.isDebugEnabled()) {
                        logger.debug("CoNE query: " + id + "?format=rdf&eSciDocUserHandle="
                                + Base64.encode(AdminHelper.getAdminUserHandle().getBytes("UTF-8"))
                                + " 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());
                    }
                }
            }
        } 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.", e);
        logger.debug("Stacktrace", e);
        return null;
        //throw new RuntimeException(e);
    }
}

From source file:de.pixida.logtest.reporting.XUnitReportGenerator.java

@Override
public void finish() {
    try {//from   w w  w .  j  a va  2s  . com
        // Create document
        final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        docFactory.setNamespaceAware(true);
        final DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

        // Create root element
        final Document doc = docBuilder.newDocument();
        final Element rootElement = doc.createElement("testsuite");
        rootElement.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
        rootElement.setAttribute("xsi:schemaLocation",
                "https://maven.apache.org/surefire/maven-surefire-plugin/xsd/surefire-test-report.xsd");
        rootElement.setAttribute("name", "LogFileAnalysisTestsuite");
        final double msToSec = 1000.0;
        rootElement.setAttribute("time", String.valueOf(this.totalTimeMs / msToSec));
        final long numTests = this.results.size();
        final long numSuccesses = this.results.values().stream()
                .mapToLong(result -> result.stream().filter(r -> r.getMiddle().isSuccess()).count()).sum();
        final long numFailures = this.results.values().stream()
                .mapToLong(result -> result.stream().filter(r -> r.getMiddle().isFailure()).count()).sum();
        final long numSkipped = 0L;
        final long numErrors = numTests - numSuccesses - numFailures;
        rootElement.setAttribute("tests", String.valueOf(numTests));
        rootElement.setAttribute("errors", String.valueOf(numErrors));
        rootElement.setAttribute("skipped", String.valueOf(numSkipped));
        rootElement.setAttribute("failures", String.valueOf(numFailures));
        doc.appendChild(rootElement);

        // Create payload
        this.addProperties(doc, rootElement);
        this.addTestCases(doc, rootElement);

        // Dump results into file
        final TransformerFactory transformerFactory = TransformerFactory.newInstance();
        final Transformer transformer = transformerFactory.newTransformer();
        final DOMSource source = new DOMSource(doc);
        final File parentFile = this.destFile.getParentFile();
        if (parentFile != null) {
            parentFile.mkdirs(); // If fails, will be caught by the following operations
        }
        final StreamResult result = new StreamResult(this.destFile);
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        transformer.transform(source, result);
    } catch (final DOMException | TransformerException | ParserConfigurationException e) {
        LOG.error("Failed to write results", e);
    }
}