Example usage for javax.xml.transform OutputKeys OMIT_XML_DECLARATION

List of usage examples for javax.xml.transform OutputKeys OMIT_XML_DECLARATION

Introduction

In this page you can find the example usage for javax.xml.transform OutputKeys OMIT_XML_DECLARATION.

Prototype

String OMIT_XML_DECLARATION

To view the source code for javax.xml.transform OutputKeys OMIT_XML_DECLARATION.

Click Source Link

Document

omit-xml-declaration = "yes" | "no".

Usage

From source file:org.dasein.cloud.azure.compute.vm.AzureVM.java

@Override
public VirtualMachine alterVirtualMachineProduct(@Nonnull String virtualMachineId, @Nonnull String productId)
        throws InternalException, CloudException {
    if (logger.isTraceEnabled()) {
        logger.trace("ENTER: " + AzureVM.class.getName() + ".alterVM()");
    }// w ww .  j  a  v  a2  s .  co m

    if (virtualMachineId == null || productId == null) {
        throw new AzureConfigException("No virtual machine id and/or product id set for this operation");
    }

    if (!isValidProductId(productId))
        throw new InternalException(
                "Product id invalid: should be one of ExtraSmall, Small, Medium, Large, ExtraLarge");

    VirtualMachine vm = getVirtualMachine(virtualMachineId);

    if (vm == null) {
        throw new CloudException("No such virtual machine: " + virtualMachineId);
    }
    ProviderContext ctx = getProvider().getContext();

    if (ctx == null) {
        throw new AzureConfigException("No context was set for this request");
    }
    String serviceName, deploymentName, roleName;

    serviceName = vm.getTag("serviceName").toString();
    deploymentName = vm.getTag("deploymentName").toString();
    roleName = vm.getTag("roleName").toString();

    String resourceDir = HOSTED_SERVICES + "/" + serviceName + "/deployments/" + deploymentName + "/roles/"
            + roleName;

    try {
        AzureMethod method = new AzureMethod(getProvider());

        Document doc = method.getAsXML(ctx.getAccountNumber(), resourceDir);
        StringBuilder xml = new StringBuilder();

        NodeList roles = doc.getElementsByTagName("PersistentVMRole");
        Node role = roles.item(0);

        NodeList entries = role.getChildNodes();
        boolean changeProduct = false;

        for (int i = 0; i < entries.getLength(); i++) {
            Node vn = entries.item(i);
            String vnName = vn.getNodeName();

            if (vnName.equalsIgnoreCase("RoleSize") && vn.hasChildNodes()) {
                if (!productId.equals(vn.getFirstChild().getNodeValue())) {
                    vn.getFirstChild().setNodeValue(productId);
                    changeProduct = true;
                } else {
                    logger.info("No product change required");
                }
                break;
            }
        }

        String requestId = null;

        if (changeProduct) {
            String output = "";
            try {
                TransformerFactory tf = TransformerFactory.newInstance();
                Transformer transformer = tf.newTransformer();
                transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
                StringWriter writer = new StringWriter();
                transformer.transform(new DOMSource(doc), new StreamResult(writer));
                output = writer.getBuffer().toString().replaceAll("\n|\r", "");
            } catch (Exception e) {
                System.err.println(e);
            }
            xml.append(output);

            logger.debug(xml);
            logger.debug("___________________________________________________");

            resourceDir = HOSTED_SERVICES + "/" + serviceName + "/deployments/" + deploymentName + "/roles/"
                    + roleName;
            requestId = method.invoke("PUT", ctx.getAccountNumber(), resourceDir, xml.toString());
        } else {
            requestId = "noChange";
        }

        if (requestId != null) {
            int httpCode = -1;
            if (!requestId.equals("noChange")) {
                httpCode = method.getOperationStatus(requestId);
                while (httpCode == -1) {
                    try {
                        Thread.sleep(15000L);
                    } catch (InterruptedException ignored) {
                    }
                    httpCode = method.getOperationStatus(requestId);
                }
            }
        }

        return getVirtualMachine(virtualMachineId);

    } finally {
        if (logger.isTraceEnabled()) {
            logger.trace("EXIT: " + AzureVM.class.getName() + ".alterVM()");
        }
    }
}

From source file:org.dspace.installer_edm.InstallerEDMAskosi.java

/**
 * Modifica el archivo web.xml de Askosi para indicarle el directorio de datos de Askosi
 *
 * @param webXmlFile archivo web.xml de Askosi
 *//*w ww .  j a v a  2s .c o  m*/
private void changeWebXml(File webXmlFile, String webXmlFileName) {
    try {
        // se abre con DOM el archivo web.xml
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(webXmlFile);
        XPath xpathInputForms = XPathFactory.newInstance().newXPath();

        // se busca el elemento SKOSdirectory
        NodeList results = (NodeList) xpathInputForms.evaluate("//*[contains(*,\"SKOSdirectory\")]", doc,
                XPathConstants.NODESET);
        if (results.getLength() > 0) {
            Element contextParam = (Element) results.item(0);

            // se busca el elemento context-param como hijo del anterior
            if (contextParam.getTagName().equals("context-param")) {

                // se busca el elemento param-value como hijo del anterior
                NodeList resultsParamValue = contextParam.getElementsByTagName("param-value");
                if (resultsParamValue.getLength() > 0) {

                    // se modifica con la ruta del directorio de datos de Askosi
                    Element valueParam = (Element) resultsParamValue.item(0);
                    Text text = doc.createTextNode(finalAskosiDataDestDirFile.getAbsolutePath());
                    valueParam.replaceChild(text, valueParam.getFirstChild());

                    // se guarda
                    TransformerFactory transformerFactory = TransformerFactory.newInstance();
                    Transformer transformer = transformerFactory.newTransformer();
                    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
                    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
                    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
                    //transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
                    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
                    DocumentType docType = doc.getDoctype();
                    if (docType != null) {
                        if (docType.getPublicId() != null)
                            transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, docType.getPublicId());
                        transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, docType.getSystemId());
                    }
                    DOMSource source = new DOMSource(doc);
                    StreamResult result = (fileSeparator.equals("\\")) ? new StreamResult(webXmlFileName)
                            : new StreamResult(webXmlFile);
                    transformer.transform(source, result);
                }
            }
        } else
            installerEDMDisplay.showQuestion(currentStepGlobal, "changeWebXml.noSKOSdirectory",
                    new String[] { webXmlFile.getAbsolutePath() });
    } catch (ParserConfigurationException e) {
        showException(e);
    } catch (SAXException e) {
        showException(e);
    } catch (IOException e) {
        showException(e);
    } catch (XPathExpressionException e) {
        showException(e);
    } catch (TransformerConfigurationException e) {
        showException(e);
    } catch (TransformerException e) {
        showException(e);
    }

}

From source file:org.dspace.installer_edm.InstallerEDMConfEDMExport.java

/**
 * Aadimos el contenido del documento jdom como archivo web.xml al flujo de escritura del war
 *
 * @param jarOutputStream flujo de escritura del war
 * @throws TransformerException//ww  w .  j a  v a 2s.  c  o m
 * @throws IOException
 */
private void addNewWebXml(JarOutputStream jarOutputStream) throws TransformerException, IOException {
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    //transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    DocumentType docType = eDMExportDocument.getDoctype();
    if (docType != null) {
        if (docType.getPublicId() != null)
            transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, docType.getPublicId());
        transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, docType.getSystemId());
    }
    StringWriter sw = new StringWriter();
    StreamResult result = new StreamResult(sw);
    DOMSource source = new DOMSource(eDMExportDocument);
    transformer.transform(source, result);
    String xmlString = sw.toString();
    jarOutputStream.putNextEntry(new JarEntry("WEB-INF/web.xml"));
    jarOutputStream.write(xmlString.getBytes());
    jarOutputStream.closeEntry();
}

From source file:org.easyrec.service.core.impl.ProfileServiceImpl.java

public ProfileServiceImpl(ProfileDAO profileDAO, String docBuilderFactory, IDMappingDAO idMappingDAO,
        TypeMappingService typeMappingService) {

    this.profileDAO = profileDAO;
    this.idMappingDAO = idMappingDAO;
    this.typeMappingService = typeMappingService;
    if (docBuilderFactory != null)
        System.setProperty("javax.xml.parsers.DocumentBuilderFactory", docBuilderFactory);
    dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);/*from w  ww .j ava 2  s .c  o  m*/
    sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    if (logger.isDebugEnabled()) {
        logger.debug("DocumentBuilderFactory: " + dbf.getClass().getName());
        ClassLoader cl = Thread.currentThread().getContextClassLoader().getSystemClassLoader();
        URL url = cl.getResource("org/apache/xerces/jaxp/DocumentBuilderFactoryImpl.class");
        logger.debug("Parser loaded from: " + url);
    }

    TransformerFactory tf = TransformerFactory.newInstance();
    try {
        trans = tf.newTransformer();
        trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    } catch (Exception e) {
        logger.warn("An error occurred!", e);
    }
}

From source file:org.easyrec.service.domain.profile.impl.ProfileServiceImpl.java

public ProfileServiceImpl(TypedProfileDAO profileDAO, ProfiledItemTypeDAO profiledItemTypeDAO,
        String docBuilderFactory) {

    this.typedProfileDAO = profileDAO;
    this.profiledItemTypeDAO = profiledItemTypeDAO;
    if (docBuilderFactory != null)
        System.setProperty("javax.xml.parsers.DocumentBuilderFactory", docBuilderFactory);
    dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);// www.  ja v a 2s .c om
    sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    if (logger.isDebugEnabled()) {
        logger.debug("DocumentBuilderFactory: " + dbf.getClass().getName());
        ClassLoader cl = Thread.currentThread().getContextClassLoader().getSystemClassLoader();
        URL url = cl.getResource("org/apache/xerces/jaxp/DocumentBuilderFactoryImpl.class");
        logger.debug("Parser loaded from: " + url);
    }
    validationParsers = new HashMap<Integer, Map<String, DocumentBuilder>>();

    loadSchemas();
    TransformerFactory tf = TransformerFactory.newInstance();
    try {
        trans = tf.newTransformer();
        trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    } catch (Exception e) {

    }
}

From source file:org.ebayopensource.turmeric.eclipse.utils.xml.XMLUtil.java

/**
 * Convert xml to string./*from   ww w . j ava 2 s .com*/
 *
 * @param node the node
 * @return the string
 * @throws TransformerFactoryConfigurationError the transformer factory configuration error
 * @throws TransformerException the transformer exception
 */
public static String convertXMLToString(final Node node)
        throws TransformerFactoryConfigurationError, TransformerException {
    if (node == null)
        return "";

    final Transformer t = TransformerFactory.newInstance().newTransformer();
    StringWriter sw = null;
    try {
        sw = new StringWriter();
        t.setOutputProperty(OutputKeys.INDENT, "yes");
        t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        if ((node instanceof Document) == false) {
            t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        }
        t.transform(new DOMSource(node), new StreamResult(sw));
    } finally {
        IOUtils.closeQuietly(sw);
    }

    return sw.toString();
}

From source file:org.ebayopensource.turmeric.eclipse.utils.xml.XMLUtil.java

/**
 * Write xml.//  w ww .  ja  v  a2s.  com
 *
 * @param node the node
 * @param writer the writer
 * @throws TransformerFactoryConfigurationError the transformer factory configuration error
 * @throws TransformerException the transformer exception
 */
public static void writeXML(final Node node, final Writer writer)
        throws TransformerFactoryConfigurationError, TransformerException {
    if (node == null || writer == null)
        return;

    final Transformer t = TransformerFactory.newInstance().newTransformer();
    try {
        t.setOutputProperty(OutputKeys.INDENT, "yes");
        t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        if ((node instanceof Document) == false) {
            t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        }
        t.transform(new DOMSource(node), new StreamResult(writer));
    } finally {
        IOUtils.closeQuietly(writer);
    }

}

From source file:org.eclipse.skalli.view.internal.servlet.StaticContentServlet.java

/**
 * Resolves all &lt;include&gt; in a given schema and writes the
 * result to the given output stream. Includes that can't be resolved
 * are removed from the schema./* w ww.j ava 2  s.  c o  m*/
 * @param in  the input stream providing the schema to resolve.
 * @param out  the output stream to write the result to.
 * @throws IOException  if an i/o error occured.
 * @throws SAXException  if parsing of the schema failed.
 * @throws ParserConfigurationException  indicates a serious parser configuration error.
 * @throws TransformerException  if transforming the schema DOM to a character stream failed.
 * @throws TransformerConfigurationException  indicates a serious transformer configuration error.
 */
private void resolveIncludes(InputStream in, OutputStream out) throws IOException, SAXException,
        ParserConfigurationException, TransformerConfigurationException, TransformerException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    Document schemaDOM = dbf.newDocumentBuilder().parse(new InputSource(in));
    Element schemaRoot = schemaDOM.getDocumentElement();

    // iterate all <include> tags and resolve them if possible
    NodeList includes = schemaDOM.getElementsByTagName("xsd:include");
    while (includes.getLength() > 0) {
        for (int i = 0; i < includes.getLength(); ++i) {
            Node includeNode = includes.item(i);
            Node includeParent = includeNode.getParentNode();
            Node schemaLocation = includeNode.getAttributes().getNamedItem("schemaLocation");
            if (schemaLocation != null) {
                // extract the pure file name from the schemaLocation and
                // try to find an XSD resource in all model extensions matching
                // the given schemaLocation attribute -> if found, replace the include tag
                // with the DOM of the include (without the root tag, of course!)
                URL includeFile = RestUtils.findSchemaResource(schemaLocation.getTextContent());
                if (includeFile != null) {
                    Document includeDOM = dbf.newDocumentBuilder()
                            .parse(new InputSource(includeFile.openStream()));
                    NodeList includeNodes = includeDOM.getDocumentElement().getChildNodes();
                    for (int j = 0; j < includeNodes.getLength(); ++j) {
                        // import and insert the tag before <include>
                        schemaRoot.insertBefore(schemaDOM.importNode(includeNodes.item(j), true), includeNode);
                    }
                }

                // in any case: remove the <include> tag
                includeParent.removeChild(includeNode);
            }
        }
        // resolve includes of includes (if any)
        includes = schemaDOM.getElementsByTagName("xsd:include");
    }

    // serialize the schema DOM to the given output stream
    Transformer xform = TransformerFactory.newInstance().newTransformer();
    xform.setOutputProperty(OutputKeys.INDENT, "yes");
    xform.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    xform.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
    xform.transform(new DOMSource(schemaDOM), new StreamResult(out));
}

From source file:org.eclipse.swordfish.p2.internal.deploy.server.MetadataProcessor.java

/**
 * Write a document to an output stream//w w w  .  j av  a  2  s.com
 * 
 * NOTE: Package visibility to enable unit testing only!
 * 
 * @param doc - the document
 * @param isSimpleOutput - false = no idention
 * @param sink - the out put stream to write to
 * @throws IOException - on write errors.
 */
final void document2OutputStream(Document doc, boolean isSimpleOutput, OutputStream sink) throws IOException {
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer t;

    try {
        t = tf.newTransformer();
        t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");

        if (!isSimpleOutput) {
            t.setOutputProperty(OutputKeys.METHOD, "xml");
            t.setOutputProperty(OutputKeys.INDENT, "yes");
        }

        StreamResult sr = new StreamResult(sink);
        t.transform(new DOMSource(doc), sr);

    } catch (TransformerException e) {
        logAndRethrowAsIOException("Error serializing document", e);
    }

}

From source file:org.exist.http.SOAPServer.java

/**
 * Writes the value of a parameter for an XQuery function call
 * /*from  www .  jav a2s .  c o  m*/
 * @param param   This StringBuffer contains the serialization of the value for XQuery
 * @param nParamSeqItem   The parameter value node from the SOAP Message
 * @param prefix   The prefix for the value (casting syntax)
 * @param postfix   The postfix for the value (casting syntax)
 * @param isAtomic   Whether the value of this type should be atomic or not (or even both)
 */
private void processParameterValue(StringBuffer param, Node nParamSeqItem, String prefix, String postfix,
        int isAtomic) throws XPathException {
    boolean justOnce = false;
    final StringBuilder whiteContent = new StringBuilder();

    try {
        final Transformer tr = TransformerFactory.newInstance().newTransformer();
        tr.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");

        Node n = nParamSeqItem.getFirstChild();
        final StringWriter sw = new StringWriter();
        final StreamResult result = new StreamResult(sw);
        final StringBuffer psw = sw.getBuffer();
        while (n != null) {
            switch (n.getNodeType()) {
            case Node.ELEMENT_NODE:
                if (isAtomic > 0) {
                    throw new Exception(
                            "Content of " + nParamSeqItem.getNodeName() + " must be an atomic value");
                }
                isAtomic = -1;
                if (justOnce) {
                    throw new Exception(nParamSeqItem.getNodeName() + " must have ONLY ONE element child");
                }
                final DOMSource source = new DOMSource(n);
                tr.transform(source, result);
                // Only once!
                justOnce = true;
                break;
            case Node.TEXT_NODE:
            case Node.CDATA_SECTION_NODE:
                final String nodeValue = n.getNodeValue();
                final boolean isNotWhite = !nodeValue.matches("[ \n\r\t]+");
                if (isAtomic >= 0) {
                    if (isNotWhite || isAtomic > 0) {
                        if (isAtomic == 0) {
                            isAtomic = 1;
                        }
                        psw.append(nodeValue);
                    } else if (isAtomic == 0) {
                        whiteContent.append(nodeValue);
                    }
                } else if (isNotWhite) {
                    throw new Exception(nParamSeqItem.getNodeName()
                            + " has mixed content, but it must have only one element child");
                }
                break;
            }
            n = n.getNextSibling();
        }
        if (isAtomic >= 0) {
            param.append(prefix);
        }
        if (isAtomic == 0) {
            param.append(whiteContent);
        } else {
            param.append(psw);
        }
        if (isAtomic >= 0) {
            param.append(postfix);
        }
    } catch (final Exception e) {
        LOG.debug(e.getMessage());
        throw new XPathException(e.getMessage());
    }
}