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.photon.phresco.framework.impl.ServerPluginUtil.java

private void addTomcatPlugin(File pomFile) throws PhrescoException {
    try {/* ww w . j a v  a  2 s .c  o m*/
        PomProcessor pomProcessor = new PomProcessor(pomFile);
        Plugin plugin = pomProcessor.getPlugin("org.codehaus.mojo", "tomcat-maven-plugin");
        if (plugin != null) {
            return;
        }
        pomProcessor.addPlugin("org.codehaus.mojo", "tomcat-maven-plugin", "1.1");
        List<Element> configList = new ArrayList<Element>();
        DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
        Document doc = docBuilder.newDocument();
        Element userNameElem = doc.createElement("username");
        userNameElem.setTextContent("${server.username}");
        Element passwordElem = doc.createElement("password");
        passwordElem.setTextContent("${server.password}");
        Element urlElem = doc.createElement("url");
        urlElem.setTextContent("http://${server.host}:${server.port}/manager/html");
        Element pathElem = doc.createElement("path");
        pathElem.setTextContent("/${project.build.finalName}");
        Element argLineElem = doc.createElement("argLine");
        argLineElem.setTextContent("-Xmx512m");

        configList.add(userNameElem);
        configList.add(passwordElem);
        configList.add(urlElem);
        configList.add(pathElem);
        configList.add(argLineElem);

        pomProcessor.addConfiguration("org.codehaus.mojo", "tomcat-maven-plugin", configList);
        pomProcessor.save();

    } catch (ParserConfigurationException e) {
        throw new PhrescoException(e);
    } catch (PhrescoPomException e) {
        throw new PhrescoException(e);
    } catch (JAXBException e) {
        throw new PhrescoException(e);
    } catch (IOException e) {
        throw new PhrescoException(e);
    }
}

From source file:de.crowdcode.movmvn.plugin.general.GeneralPlugin.java

private Document createDocument() throws ParserConfigurationException {
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    Document doc = docBuilder.newDocument();
    return doc;/*from   w  ww  .  ja  v a 2s.  com*/
}

From source file:Exporters.SaveFileExporter.java

public void save(File outfile, DefaultMutableTreeNode root) throws Exception {
    System.out.println("===SaveFileExporter==save:" + outfile.getAbsolutePath());

    // Create new XML document
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

    // Create the root element
    Document doc = docBuilder.newDocument();
    Element rootElement = doc.createElement("reportCompiler");
    rootElement.setAttribute("date", getNow()); // Debugging to say when saved
    // TODO - figure out a universal means to get the current version of the generating tool
    // Initial thoughts would be to create a convenience class in Utils package with some
    // final variables that can be updated when issuing a release.
    doc.appendChild(rootElement);//from   ww  w .  j  av  a  2s. com

    Element vulnerabilitiesElement = doc.createElement("vulnerabilities");

    Enumeration enums = root.children();
    while (enums.hasMoreElements()) {
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) enums.nextElement();
        Object obj = node.getUserObject();
        if (obj instanceof Vulnerability) {
            Vulnerability vuln = (Vulnerability) obj;
            Element vulnElement = getVulnAsElement(vuln, doc);
            if (vulnElement != null) {
                vulnerabilitiesElement.appendChild(vulnElement);
            }
        }
    }

    rootElement.appendChild(vulnerabilitiesElement);

    // now write the XML file
    // write the content into xml file
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();

    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(outfile);

    // Output to console for testing
    //StreamResult result = new StreamResult(System.out);
    transformer.transform(source, result);

    System.out.println("File saved!");

}

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

@Override
protected JSONProperty doDeserializeV3(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);
    }//from w w  w.j  av a2s. c  o  m

    try {
        final DocumentBuilder builder = ODataConstants.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) {
            DOMTreeUtilsV3.buildSubtree(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.photon.phresco.framework.impl.ServerPluginUtil.java

private void addWebLogicPlugin(File pomFile) throws PhrescoException {
    try {/*from  www  .  j  a v a 2s.  c o  m*/
        PomProcessor pomProcessor = new PomProcessor(pomFile);
        pomProcessor.addPlugin("com.oracle.weblogic", "weblogic-maven-plugin", "12.1.1.0");
        List<Element> configList = new ArrayList<Element>();
        DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
        Document doc = docBuilder.newDocument();
        Element adminUrl = doc.createElement("adminurl");
        adminUrl.setTextContent("t3://${server.host}:${server.port}");
        Element user = doc.createElement("user");
        user.setTextContent("${server.username}");
        Element password = doc.createElement("password");
        password.setTextContent("${server.password}");
        Element upload = doc.createElement("upload");
        upload.setTextContent("true");
        Element action = doc.createElement("action");
        action.setTextContent("deploy");
        Element remote = doc.createElement("remote");
        remote.setTextContent("true");
        Element verbose = doc.createElement("verbose");
        verbose.setTextContent("false");
        Element source = doc.createElement("source");
        source.setTextContent(".\\do_not_checkin\\target\\${project.build.finalName}.war");
        Element name = doc.createElement("name");
        name.setTextContent("${project.build.finalName}");
        Element argLineElem = doc.createElement("argLine");
        argLineElem.setTextContent("-Xmx512m");

        configList.add(adminUrl);
        configList.add(user);
        configList.add(password);
        configList.add(upload);
        configList.add(action);
        configList.add(remote);
        configList.add(verbose);
        configList.add(source);
        configList.add(name);
        configList.add(argLineElem);

        pomProcessor.addConfiguration("com.oracle.weblogic", "weblogic-maven-plugin", configList);
        pomProcessor.save();

    } catch (ParserConfigurationException e) {
        throw new PhrescoException(e);
    } catch (PhrescoPomException e) {
        throw new PhrescoException(e);
    } catch (JAXBException e) {
        throw new PhrescoException(e);
    } catch (IOException e) {
        throw new PhrescoException(e);
    }
}

From source file:com.cordys.coe.ac.httpconnector.samples.JIRAResponseHandler.java

/**
 * This method parses the response HTML into a DOM tree.
 * //  w w w  . ja v a  2  s .com
 * @param responseBody
 *            The response HTML.
 * 
 * @return The parsed document.
 * 
 * @throws Exception
 *             In case the parsing fails.
 */
protected org.w3c.dom.Document parseResponse(byte[] responseBody) throws Exception {
    // Parse the HTML response to be able to find errors.
    // Disable most Cobra logging.
    UserAgentContext uacontext = new SimpleUserAgentContext();

    // In this case we will use a standard XML document
    // as opposed to Cobra's HTML DOM implementation.
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();

    ByteArrayInputStream bais = new ByteArrayInputStream(responseBody);
    org.w3c.dom.Document document = builder.newDocument();

    // Here is where we use Cobra's HTML parser.
    HtmlParser parser = new HtmlParser(uacontext, document);
    parser.parse(bais);

    return document;
}

From source file:gool.generator.xml.XmlCodePrinter.java

@Override
public List<File> print(ClassDef pclass) throws FileNotFoundException {
    Document document = null;/*  w ww .j  a va  2s.com*/
    DocumentBuilderFactory fabrique = null;
    List<File> result = new ArrayList<File>();
    // Debugging info
    // nbNode = 0;

    try {
        // creat document structure
        fabrique = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = fabrique.newDocumentBuilder();
        document = builder.newDocument();
        Element racine = (Element) document.createElement("file");
        Element el = NodeToElement(pclass, document);
        if (el != null)
            racine.appendChild(el);
        document.appendChild(racine);

        // file separator is just a slash in Unix
        // so the second argument to File() is just the directory
        // that corresponds to the package name
        // the first argument is the default output directory of the
        // platform
        // so the directory name ends up being something like
        // GOOLOUPTUTTARGET/pack/age
        File dir = new File(getOutputDir().getAbsolutePath(),
                StringUtils.replace(pclass.getPackageName(), ".", File.separator));
        // Typically the outputdir was created before, but not the package
        // subdirs
        dir.mkdirs();
        // Create the file for the class, fill it in, close it
        File classFile = new File(dir, getFileName(pclass.getName()));
        Log.i(String.format("Writing to file %s", classFile));

        // Create formating output
        OutputFormat format = new OutputFormat(document);
        format.setEncoding("UTF-8");
        format.setLineWidth(80);
        format.setIndenting(true);
        format.setIndent(4);

        // save to output file
        Writer out = new PrintWriter(classFile);
        XMLSerializer serializer = new XMLSerializer(out, format);
        serializer.serialize(document);

        // Remember that you did the generation for this one abstract GOOL
        // class
        printedClasses.add(pclass);
        result.add(classFile);
        classdefok = true;
    } catch (Exception e) {
        Log.e(e);
        System.exit(1);
    }

    return result;
}

From source file:gov.medicaid.services.impl.FileNetServiceBean.java

/**
 * Creates the XML./*  w  w w.ja  va  2s . c om*/
 * 
 * @param outFile
 *            the output file handler
 * @param attributes
 *            the content
 * @throws PortalServiceException
 *             if any error occurs
 */
private void createXML(File outFile, Map<String, String> attributes) throws PortalServiceException {
    try {
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

        // root elements
        Document doc = docBuilder.newDocument();
        Element rootElement = doc.createElement("Document");
        doc.appendChild(rootElement);
        for (String key : attributes.keySet()) {
            Element indexVal = doc.createElement("Indexvalue");
            Attr attr = doc.createAttribute("name");
            attr.setValue(key);
            indexVal.setAttributeNode(attr);
            if (attributes.get(key) != null) {
                indexVal.appendChild(doc.createTextNode(attributes.get(key)));
            }
            rootElement.appendChild(indexVal);
        }
        // write the content into xml file
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(outFile);

        transformer.transform(source, result);

    } catch (ParserConfigurationException e) {
        throw new PortalServiceException("Failed to create FileNet xml", e);
    } catch (TransformerException e) {
        throw new PortalServiceException("Failed to create FileNet xml", e);
    }

}

From source file:com.photon.phresco.framework.impl.ServerPluginUtil.java

private void addJBossPlugin(File pomFile) throws PhrescoException {
    try {//from  w  ww  .  j  av  a2 s .  c  om
        PomProcessor pomProcessor = new PomProcessor(pomFile);
        Plugin plugin = pomProcessor.getPlugin("org.codehaus.cargo", "cargo-maven2-plugin");
        if (plugin != null) {
            return;
        }
        pomProcessor.addPlugin("org.codehaus.cargo", "cargo-maven2-plugin", "1.1.3");
        List<Element> configList = new ArrayList<Element>();
        DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
        Document doc = docBuilder.newDocument();
        Element containerElement = doc.createElement("container");
        Element containerId = doc.createElement("containerId");
        containerId.setTextContent("jboss7x");
        containerElement.appendChild(containerId);
        Element type = doc.createElement("type");
        type.setTextContent("remote");
        containerElement.appendChild(type);
        Element home = doc.createElement("home");
        home.setTextContent("${jboss.home}\\standalone\\deployments");
        containerElement.appendChild(home);

        Element configurationElement = doc.createElement("configuration");
        Element innerType = doc.createElement("type");
        innerType.setTextContent("runtime");
        configurationElement.appendChild(innerType);

        Element propertyElement = doc.createElement("properties");
        configurationElement.appendChild(propertyElement);
        Element cargoHome = doc.createElement("cargo.hostname");
        cargoHome.setTextContent("${server.host}");
        propertyElement.appendChild(cargoHome);
        Element cargoMgmtPort = doc.createElement("cargo.jboss.management.port");
        cargoMgmtPort.setTextContent("9999");
        propertyElement.appendChild(cargoMgmtPort);
        Element cargoRmiPort = doc.createElement("cargo.rmi.port");
        cargoRmiPort.setTextContent("1099");
        propertyElement.appendChild(cargoRmiPort);
        Element cargoUserName = doc.createElement("cargo.remote.username");
        cargoUserName.setTextContent("${server.username}");
        propertyElement.appendChild(cargoUserName);
        Element cargoPwd = doc.createElement("cargo.remote.password");
        cargoPwd.setTextContent("${server.password}");
        propertyElement.appendChild(cargoPwd);
        configurationElement.appendChild(propertyElement);

        configList.add(containerElement);
        configList.add(configurationElement);
        pomProcessor.addConfiguration("org.codehaus.cargo", "cargo-maven2-plugin", configList);

        Dependency dependency = new Dependency();
        dependency.setGroupId("org.jboss.as");
        dependency.setArtifactId("jboss-as-controller-client");
        dependency.setVersion("7.0.2.Final");

        pomProcessor.addPluginDependency("org.codehaus.cargo", "cargo-maven2-plugin", dependency);
        pomProcessor.save();

    } catch (JAXBException e) {
        throw new PhrescoException(e);
    } catch (IOException e) {
        throw new PhrescoException(e);
    } catch (ParserConfigurationException e) {
        throw new PhrescoException(e);
    } catch (PhrescoPomException e) {
        throw new PhrescoException(e);
    }
}

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

public static Node getSize(String url) {
    DocumentBuilder documentBuilder;

    HttpClient httpClient = new HttpClient();
    HeadMethod headMethod = new HeadMethod(url);

    try {/*  ww  w  .  j  a  v a 2 s  .c om*/
        logger.info("Getting size of " + url);
        ProxyHelper.executeMethod(httpClient, headMethod);

        if (headMethod.getStatusCode() != 200) {
            logger.warn("Wrong status code " + headMethod.getStatusCode() + " at " + url);
        }

        documentBuilder = DocumentBuilderFactoryImpl.newInstance().newDocumentBuilder();
        Document document = documentBuilder.newDocument();
        Element element = document.createElement("size");
        document.appendChild(element);
        Header header = headMethod.getResponseHeader("Content-Length");
        if (header != null) {
            element.setTextContent(header.getValue());
            return document;
        } else {
            element.setTextContent("0");
            return document;
        }

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}