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:mx.bigdata.sat.cfdi.TFDv1.java

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

From source file:it.pronetics.madstore.repository.jcr.impl.AbstractJcrRepository.java

private Document getDomDocument() throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);/*from   www .  j  a va  2  s . co m*/
    DocumentBuilder builder = factory.newDocumentBuilder();
    return builder.newDocument();
}

From source file:de.mpg.mpdl.inge.transformation.Util.java

/**
 * Queries the CoNE service and transforms the result into a DOM node.
 * // w  w w. ja  v  a  2  s  . c om
 * @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 {
        logger.info("queryConeExactWithIdentifier: " + model + " identifier: " + identifier + " ou: " + ou);

        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/" + URLEncoder.encode("rdf:value", "UTF-8") + "="
                + URLEncoder.encode("\"" + identifier + "\"", "UTF-8") + "&"
                + URLEncoder.encode("escidoc:position/eprints:affiliatedInstitution", "UTF-8") + "="
                + URLEncoder.encode("\"*" + ou + "*\"", "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);
        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)) {
                        // 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);

                        ProxyHelper.setProxy(client, detailsUrl.replace("$1", id));
                        client.executeMethod(detailMethod);
                        // TODO "&redirect=true" must be reinserted again
                        logger.info("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());
                        }
                        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.", e);
        return null;
        // throw new RuntimeException(e);
    }
}

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

public static Node querySSRNId(String conePersonUrl) {
    DocumentBuilder documentBuilder;
    HttpClient client = new HttpClient();

    logger.info("querySSRNId: " + conePersonUrl);

    try {/*from   w  w w. j a  v  a  2s .  c  o  m*/
        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.", e);
        return null;
    }

}

From source file:com.action.ExportAction.java

public File exportXMLAction(File file) throws Exception {
    //document//w w w.ja  va 2s  .c o  m
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document document = builder.newDocument();
    Element reportsElement = document.createElement("reports");//
    reportsElement.setAttribute("date", (new Date()).toString());
    document.appendChild(reportsElement);
    System.out.println("exportXMLAction:" + tableCode);
    String[] ids = tableCode.split(",");
    for (String id : ids) {
        System.out.println("id:" + id);
        List<JQ_zhibiao_entity> list = Export.getDuizhaoByJqTbCode(id);
        document = Export.exportXML(reportsElement, document, list, id);
    }

    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    DOMSource source = new DOMSource(document);
    transformer.setOutputProperty(OutputKeys.ENCODING, "GB2312");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    PrintWriter pw = new PrintWriter(new FileOutputStream(file));
    StreamResult result = new StreamResult(pw);
    transformer.transform(source, result);
    pw.close();
    return file;
}

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

private Element marshalTFD() throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);/*  w ww.j  a v a2  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(CFDv3.PREFIXES));
    m.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
    m.setProperty(Marshaller.JAXB_SCHEMA_LOCATION,
            "http://www.sat.gob.mx/TimbreFiscalDigital TimbreFiscalDigitalv11.xsd");
    m.marshal(tfd, doc);
    return doc.getDocumentElement();
}

From source file:mx.bigdata.cfdi.TFDv1.java

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

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

@Override
protected JSONProperty doDeserialize(final JsonParser parser, final DeserializationContext ctxt)
        throws IOException, JsonProcessingException {

    final ObjectNode tree = (ObjectNode) parser.getCodec().readTree(parser);

    final JSONProperty property = new JSONProperty();

    if (tree.hasNonNull(ODataConstants.JSON_METADATA)) {
        property.setMetadata(URI.create(tree.get(ODataConstants.JSON_METADATA).textValue()));
        tree.remove(ODataConstants.JSON_METADATA);
    }/* w  w  w  .  ja v  a 2  s.  com*/

    try {
        final DocumentBuilder builder = XMLUtils.DOC_BUILDER_FACTORY.newDocumentBuilder();
        final Document document = builder.newDocument();

        Element content = document.createElement(ODataConstants.ELEM_PROPERTY);

        if (property.getMetadata() != null) {
            final String metadataURI = property.getMetadata().toASCIIString();
            final int dashIdx = metadataURI.lastIndexOf('#');
            if (dashIdx != -1) {
                content.setAttribute(ODataConstants.ATTR_M_TYPE, metadataURI.substring(dashIdx + 1));
            }
        }

        JsonNode subtree = null;
        if (tree.has(ODataConstants.JSON_VALUE)) {
            if (tree.has(ODataConstants.JSON_TYPE)
                    && StringUtils.isBlank(content.getAttribute(ODataConstants.ATTR_M_TYPE))) {

                content.setAttribute(ODataConstants.ATTR_M_TYPE, tree.get(ODataConstants.JSON_TYPE).asText());
            }

            final JsonNode value = tree.get(ODataConstants.JSON_VALUE);
            if (value.isValueNode()) {
                content.appendChild(document.createTextNode(value.asText()));
            } else if (EdmSimpleType.isGeospatial(content.getAttribute(ODataConstants.ATTR_M_TYPE))) {
                subtree = tree.objectNode();
                ((ObjectNode) subtree).put(ODataConstants.JSON_VALUE, tree.get(ODataConstants.JSON_VALUE));
                if (StringUtils.isNotBlank(content.getAttribute(ODataConstants.ATTR_M_TYPE))) {
                    ((ObjectNode) subtree).put(ODataConstants.JSON_VALUE + "@" + ODataConstants.JSON_TYPE,
                            content.getAttribute(ODataConstants.ATTR_M_TYPE));
                }
            } else {
                subtree = tree.get(ODataConstants.JSON_VALUE);
            }
        } else {
            subtree = tree;
        }

        if (subtree != null) {
            JSONDOMTreeUtils.buildSubtree(client, content, subtree);
        }

        final List<Node> children = XMLUtils.getChildNodes(content, Node.ELEMENT_NODE);
        if (children.size() == 1) {
            final Element value = (Element) children.iterator().next();
            if (ODataConstants.JSON_VALUE.equals(XMLUtils.getSimpleName(value))) {
                if (StringUtils.isNotBlank(content.getAttribute(ODataConstants.ATTR_M_TYPE))) {
                    value.setAttribute(ODataConstants.ATTR_M_TYPE,
                            content.getAttribute(ODataConstants.ATTR_M_TYPE));
                }
                content = value;
            }
        }

        property.setContent(content);
    } catch (ParserConfigurationException e) {
        throw new JsonParseException("Cannot build property", parser.getCurrentLocation(), e);
    }

    return property;
}

From source file:com.alfaariss.oa.util.configuration.handler.dummy.DummyConfigurationHandler.java

/**
 * Parse the configuration from the file.
 * @see IConfigurationHandler#parseConfiguration()
 *///from   www.j  a v a2s  . co m
public Document parseConfiguration() throws ConfigurationException {
    Document dRet = null;
    //create DocumentBuilderFactory to parse config file.
    DocumentBuilderFactory oDocumentBuilderFactory = DocumentBuilderFactory.newInstance();

    //Create parser
    DocumentBuilder oDocumentBuilder = null;
    try {
        oDocumentBuilder = oDocumentBuilderFactory.newDocumentBuilder();
        //parse
        dRet = oDocumentBuilder.newDocument();

        Element eRoot = dRet.createElement("config");
        eRoot.appendChild(dRet.createElement(_root));
        dRet.appendChild(eRoot);
    } catch (ParserConfigurationException e) {
        _logger.error("Error reading configuration, parse error", e);
        throw new ConfigurationException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
    }
    return dRet;
}

From source file:com.action.ExportAction.java

public String exportXMLAction() {
    try {//from   www.  j a va 2  s  . c  o  m
        //document
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.newDocument();
        Element reportsElement = document.createElement("project");//
        reportsElement.setAttribute("date", (new Date()).toString());
        document.appendChild(reportsElement);
        System.out.println("exportXMLAction:" + tableCode);
        String[] ids = tableCode.split(",");
        for (String id : ids) {
            System.out.println("id:" + id);
            List<JQ_zhibiao_entity> list = Export.getDuizhaoByJqTbCode(id);
            document = Export.exportXML(reportsElement, document, list, id);
        }
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        DOMSource source = new DOMSource(document);
        transformer.setOutputProperty(OutputKeys.ENCODING, "GB2312");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");

        PrintWriter pw = new PrintWriter(new FileOutputStream(realPath + "test.xml"));
        StreamResult result = new StreamResult(pw);
        transformer.transform(source, result);
        pw.close();
    } catch (Exception e) {
        ActionContext.getContext().put("message", "??" + e);
        return ERROR;
    }
    return SUCCESS;
}