Example usage for javax.xml.transform OutputKeys STANDALONE

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

Introduction

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

Prototype

String STANDALONE

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

Click Source Link

Document

standalone = "yes" | "no".

Usage

From source file:ambit.data.qmrf.QMRFObject.java

protected void write(Document doc, Writer out) throws Exception {
    Source source;//from w w w . j a v  a 2s. c  o  m
    try {
        DOMResult result = transform_help(doc, false);
        Document newdoc = (Document) result.getNode();
        newdoc.normalize();
        source = new DOMSource(newdoc);
    } catch (Exception x) {
        source = new DOMSource(doc);
    }

    Transformer xformer = TransformerFactory.newInstance().newTransformer();
    xformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, dtdSchema);
    xformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "qmrf.dtd");
    xformer.setOutputProperty(OutputKeys.INDENT, "Yes");
    xformer.setOutputProperty(OutputKeys.STANDALONE, "No");

    Result result = new StreamResult(out);
    xformer.transform(source, result);
    out.flush();
    setNotModified();
    fireAmbitObjectEvent();
}

From source file:net.sf.joost.stx.Processor.java

/**
 * Initialize the output properties to the values specified in the
 * transformation sheet or to their default values, resp.
 *//*  w  w w  .  j  a  v  a 2  s  . co  m*/
public void initOutputProperties() {
    outputProperties = new Properties();
    outputProperties.setProperty(OutputKeys.ENCODING, transformNode.outputEncoding);
    outputProperties.setProperty(OutputKeys.MEDIA_TYPE, "text/xml");
    outputProperties.setProperty(OutputKeys.METHOD, transformNode.outputMethod);
    outputProperties.setProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
    outputProperties.setProperty(OutputKeys.STANDALONE, "no");
    outputProperties.setProperty(OutputKeys.VERSION, "1.0");
}

From source file:com.ggvaidya.scinames.model.Project.java

public void saveToFile() throws IOException {
    File saveToFile = projectFile.getValue();

    if (saveToFile == null)
        throw new IOException("Project file not set: nowhere to save to!");

    /*//from w  w w . j a v  a 2s.  com
    XMLOutputFactory factory = XMLOutputFactory.newFactory();
            
    try {
       XMLStreamWriter writer = factory.createXMLStreamWriter(new FileWriter(saveToFile));
               
       writer.writeStartDocument();
               
       serializeToXMLStream(writer);
               
       writer.writeEndDocument();
       writer.flush();
               
       // Success!
       lastModified.saved();
               
    } catch (XMLStreamException ex) {
       throw new IOException("Could not write project to XML file '" + saveToFile + "': " + ex);
    }*/

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

    // Create a document representation of this project.
    Document docProject;
    try {
        DocumentBuilder db = dbf.newDocumentBuilder();
        docProject = db.newDocument();
        serializeToDocument(docProject);

    } catch (ParserConfigurationException ex) {
        Logger.getLogger(Project.class.getName()).log(Level.SEVERE, null, ex);
        return;
    }

    // Write the document representation of this project
    // as XML.
    TransformerFactory tfc = TransformerFactory.newInstance();
    try {
        OutputStream outputStream = new GZIPOutputStream(new FileOutputStream(saveToFile));
        StreamResult res = new StreamResult(outputStream);

        Transformer t = tfc.newTransformer();
        DOMSource ds = new DOMSource(docProject);

        t.setOutputProperty(OutputKeys.METHOD, "xml");
        t.setOutputProperty(OutputKeys.VERSION, "1.0"); // Do NOT change to 1.1 -- this leads to complex problems!
        t.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        t.setOutputProperty(OutputKeys.STANDALONE, "yes");
        t.setOutputProperty(OutputKeys.INDENT, "yes");
        t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        t.transform(ds, res);

        // Success!
        lastModified.saved();
        outputStream.close();
    } catch (TransformerConfigurationException ex) {
        throw new IOException("Could not write out XML to '" + saveToFile + "': " + ex);
    } catch (TransformerException ex) {
        throw new IOException("Could not write out XML to '" + saveToFile + "': " + ex);
    }
}

From source file:com.haulmont.cuba.restapi.XMLConverter.java

protected String documentToString(Document document) {
    try {//w w w . j av a2  s .c  o  m
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.ENCODING, StandardCharsets.UTF_8.name());
        transformer.setOutputProperty(OutputKeys.STANDALONE, "no");
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        transformer.setOutputProperty(OutputKeys.INDENT, "no");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

        StringWriter sw = new StringWriter();
        transformer.transform(new DOMSource(document), new StreamResult(sw));
        return sw.toString();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:it.imtech.metadata.MetaUtility.java

/**
 * Metodo adibito all'esportazione dei metadati su oggetto Document a
 * partire dai valori dell'interfaccia//  w  ww .  j a va 2  s.  co  m
 *
 * @param pid PID del libro durante upload
 * @param pagenum Numero pagina corrente di esportazione
 * @param objectDefaultValues Valori di default durante upload
 * @return Oggetto xml contenente i metadati inseriti nei campi
 * dell'interfaccia
 * @throws Exception
 */
public Document create_uwmetadata(String pid, int pagenum, HashMap<String, String> objectDefaultValues,
        String collTitle, String panelname) throws Exception {
    String xmlFile = "";

    if (objectDefaultValues != null) {
        this.objectDefaultValues = objectDefaultValues;
    }

    StreamResult result = new StreamResult(new StringWriter());

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    // set the factory to be namespace aware
    factory.setNamespaceAware(true);

    // create the xml document builder object and get the DOMImplementation object
    DocumentBuilder builder = factory.newDocumentBuilder();
    DOMImplementation domImpl = builder.getDOMImplementation();
    Document xmlDoc = domImpl.createDocument("http://phaidra.univie.ac.at/XML/metadata/V1.0", "ns0:uwmetadata",
            null);

    try {
        Transformer t = TransformerFactory.newInstance().newTransformer();
        t.setOutputProperty(OutputKeys.INDENT, "yes");
        t.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        t.setOutputProperty(OutputKeys.STANDALONE, "");
        t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

        // get the root element
        Element rootElement = xmlDoc.getDocumentElement();

        //Add namespaces in XML Root
        for (Map.Entry<String, String> field : metadata_namespaces.entrySet()) {
            rootElement.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:" + field.getKey().toString(),
                    field.getValue().toString());
        }
        create_uwmetadata_recursive(xmlDoc, rootElement, BookImporter.getInstance().getMetadata(),
                this.objectDefaultValues, pagenum, collTitle, panelname);
    } catch (TransformerConfigurationException e) {
    } catch (Exception e) {
        throw new Exception(e.getMessage());
    }

    return xmlDoc;
}

From source file:org.apache.cocoon.serialization.AbstractTextSerializer.java

/**
 * Set the configurations for this serializer.
 *///from  w ww.  j a  va2 s .co m
public void configure(Configuration conf) throws ConfigurationException {
    // configure buffer size
    //   Configuration bsc = conf.getChild("buffer-size", false);
    //   if(null != bsc)
    //    outputBufferSize = bsc.getValueAsInteger(DEFAULT_BUFFER_SIZE);

    // configure xalan
    String cdataSectionElements = conf.getChild("cdata-section-elements").getValue(null);
    String dtPublic = conf.getChild("doctype-public").getValue(null);
    String dtSystem = conf.getChild("doctype-system").getValue(null);
    String encoding = conf.getChild("encoding").getValue(null);
    String indent = conf.getChild("indent").getValue(null);
    String mediaType = conf.getChild("media-type").getValue(null);
    String method = conf.getChild("method").getValue(null);
    String omitXMLDeclaration = conf.getChild("omit-xml-declaration").getValue(null);
    String standAlone = conf.getChild("standalone").getValue(null);
    String version = conf.getChild("version").getValue(null);

    final StringBuffer buffer = new StringBuffer();

    if (cdataSectionElements != null) {
        format.put(OutputKeys.CDATA_SECTION_ELEMENTS, cdataSectionElements);
        buffer.append(";cdata-section-elements=").append(cdataSectionElements);
    }
    if (dtPublic != null) {
        format.put(OutputKeys.DOCTYPE_PUBLIC, dtPublic);
        buffer.append(";doctype-public=").append(dtPublic);
    }
    if (dtSystem != null) {
        format.put(OutputKeys.DOCTYPE_SYSTEM, dtSystem);
        buffer.append(";doctype-system=").append(dtSystem);
    }
    if (encoding != null) {
        format.put(OutputKeys.ENCODING, encoding);
        buffer.append(";encoding=").append(encoding);
    }
    if (indent != null) {
        format.put(OutputKeys.INDENT, indent);
        buffer.append(";indent=").append(indent);
    }
    if (mediaType != null) {
        format.put(OutputKeys.MEDIA_TYPE, mediaType);
        buffer.append(";media-type=").append(mediaType);
    }
    if (method != null) {
        format.put(OutputKeys.METHOD, method);
        buffer.append(";method=").append(method);
    }
    if (omitXMLDeclaration != null) {
        format.put(OutputKeys.OMIT_XML_DECLARATION, omitXMLDeclaration);
        buffer.append(";omit-xml-declaration=").append(omitXMLDeclaration);
    }
    if (standAlone != null) {
        format.put(OutputKeys.STANDALONE, standAlone);
        buffer.append(";standalone=").append(standAlone);
    }
    if (version != null) {
        format.put(OutputKeys.VERSION, version);
        buffer.append(";version=").append(version);
    }

    if (buffer.length() > 0) {
        this.cachingKey = buffer.toString();
    }

    String tFactoryClass = conf.getChild("transformer-factory").getValue(null);
    if (tFactoryClass != null) {
        try {
            this.tfactory = (SAXTransformerFactory) ClassUtils.newInstance(tFactoryClass);
            if (getLogger().isDebugEnabled()) {
                getLogger().debug("Using transformer factory " + tFactoryClass);
            }
        } catch (Exception e) {
            throw new ConfigurationException("Cannot load transformer factory " + tFactoryClass, e);
        }
    } else {
        // Standard TrAX behaviour
        this.tfactory = (SAXTransformerFactory) TransformerFactory.newInstance();
    }
    tfactory.setErrorListener(new TraxErrorHandler(getLogger()));

    // Check if we need namespace as attributes.
    try {
        if (needsNamespacesAsAttributes()) {
            // Setup a correction pipe
            this.namespacePipe = new NamespaceAsAttributes();
            this.namespacePipe.enableLogging(getLogger());
        }
    } catch (Exception e) {
        getLogger().warn("Cannot know if transformer needs namespaces attributes - assuming NO.", e);
    }
}

From source file:org.apache.hadoop.gateway.filter.rewrite.impl.xml.XmlUrlRewriteRulesExporter.java

@Override
public void store(UrlRewriteRulesDescriptor descriptor, Writer writer) throws IOException {
    try {/*ww  w  . j  ava 2s .c o m*/
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = builderFactory.newDocumentBuilder();
        Document document = builder.newDocument();
        document.setXmlStandalone(true);

        Element root = document.createElement(ROOT);
        document.appendChild(root);

        if (!descriptor.getFunctions().isEmpty()) {
            Element functionsElement = document.createElement(FUNCTIONS);
            root.appendChild(functionsElement);
            for (UrlRewriteFunctionDescriptor function : descriptor.getFunctions()) {
                Element functionElement = createElement(document, function.name(), function);
                functionsElement.appendChild(functionElement);
            }
        }

        if (!descriptor.getRules().isEmpty()) {
            for (UrlRewriteRuleDescriptor rule : descriptor.getRules()) {
                Element ruleElement = createRule(document, rule);
                root.appendChild(ruleElement);
            }
        }

        if (!descriptor.getFilters().isEmpty()) {
            for (UrlRewriteFilterDescriptor filter : descriptor.getFilters()) {
                Element filterElement = createFilter(document, filter);
                root.appendChild(filterElement);
            }
        }

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        transformerFactory.setAttribute("indent-number", 2);
        Transformer transformer = transformerFactory.newTransformer();
        //transformer.setOutputProperty( OutputKeys.OMIT_XML_DECLARATION, "yes" );
        transformer.setOutputProperty(OutputKeys.STANDALONE, "yes");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");

        StreamResult result = new StreamResult(writer);
        DOMSource source = new DOMSource(document);
        transformer.transform(source, result);

    } catch (ParserConfigurationException e) {
        throw new IOException(e);
    } catch (TransformerException e) {
        throw new IOException(e);
    } catch (InvocationTargetException e) {
        LOG.failedToWriteRulesDescriptor(e);
    } catch (NoSuchMethodException e) {
        LOG.failedToWriteRulesDescriptor(e);
    } catch (IntrospectionException e) {
        LOG.failedToWriteRulesDescriptor(e);
    } catch (IllegalAccessException e) {
        LOG.failedToWriteRulesDescriptor(e);
    }
}

From source file:org.cruk.genologics.api.jaxb.JaxbAnnotationTest.java

@SuppressWarnings("unused")
private String reformat(String xml) throws Exception {
    byte[] xmlBytes = xml.getBytes("UTF8");
    Document doc = docBuilder.parse(new ByteArrayInputStream(xmlBytes));

    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.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(OutputKeys.STANDALONE, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

    StringWriter writer = new StringWriter();
    transformer.transform(new DOMSource(doc), new StreamResult(writer));
    return writer.toString();
}

From source file:org.expath.tools.model.exist.EXistSequence.java

/**
 * Borrowed from {@link org.expath.tools.saxon.model.SaxonSequence}
 *//*from w w w.ja  v a2s  . c  o m*/
private Properties makeOutputProperties(final SerialParameters params) throws ToolsException {
    final Properties props = new Properties();

    setOutputKey(props, OutputKeys.METHOD, params.getMethod());
    setOutputKey(props, OutputKeys.MEDIA_TYPE, params.getMediaType());
    setOutputKey(props, OutputKeys.ENCODING, params.getEncoding());
    setOutputKey(props, OutputKeys.CDATA_SECTION_ELEMENTS, params.getCdataSectionElements());
    setOutputKey(props, OutputKeys.DOCTYPE_PUBLIC, params.getDoctypePublic());
    setOutputKey(props, OutputKeys.DOCTYPE_SYSTEM, params.getDoctypeSystem());
    setOutputKey(props, OutputKeys.INDENT, params.getIndent());
    setOutputKey(props, OutputKeys.OMIT_XML_DECLARATION, params.getOmitXmlDeclaration());
    setOutputKey(props, OutputKeys.STANDALONE, params.getStandalone());
    setOutputKey(props, OutputKeys.VERSION, params.getVersion());

    return props;
}

From source file:org.jboss.tools.tycho.sitegenerator.GenerateRepositoryFacadeMojo.java

/**
 * Alter content.xml, content.jar, content.xml.xz to:
 * remove default "Uncategorized" category, 
 * remove 3rd party associate sites, and 
 * add associate sites defined in site's pom.xml
 *
 * @param p2repository//w w w  .  j a v  a  2 s.co m
 * @throws FileNotFoundException
 * @throws IOException
 * @throws SAXException
 * @throws ParserConfigurationException
 * @throws TransformerFactoryConfigurationError
 * @throws TransformerConfigurationException
 * @throws TransformerException
 * @throws MojoFailureException
 */
private void alterContentJar(File p2repository) throws FileNotFoundException, IOException, SAXException,
        ParserConfigurationException, TransformerFactoryConfigurationError, TransformerConfigurationException,
        TransformerException, MojoFailureException {
    File contentJar = new File(p2repository, "content.jar");
    ZipInputStream contentStream = new ZipInputStream(new FileInputStream(contentJar));
    ZipEntry entry = null;
    Document contentDoc = null;
    boolean done = false;
    while (!done && (entry = contentStream.getNextEntry()) != null) {
        if (entry.getName().equals("content.xml")) {
            contentDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(contentStream);
            Element repoElement = (Element) contentDoc.getElementsByTagName("repository").item(0);
            {
                NodeList references = repoElement.getElementsByTagName("references");
                // remove default references
                for (int i = 0; i < references.getLength(); i++) {
                    Node currentRef = references.item(i);
                    currentRef.getParentNode().removeChild(currentRef);
                }
                // add associateSites
                if (this.associateSites != null && this.associateSites.size() > 0
                        && this.referenceStrategy == ReferenceStrategy.embedReferences) {
                    Element refElement = contentDoc.createElement("references");
                    refElement.setAttribute("size", Integer.valueOf(2 * associateSites.size()).toString());
                    for (String associate : associateSites) {
                        Element rep0 = contentDoc.createElement("repository");
                        rep0.setAttribute("uri", associate);
                        rep0.setAttribute("url", associate);
                        rep0.setAttribute("type", "0");
                        rep0.setAttribute("options", "1");
                        refElement.appendChild(rep0);
                        Element rep1 = (Element) rep0.cloneNode(true);
                        rep1.setAttribute("type", "1");
                        refElement.appendChild(rep1);
                    }
                    repoElement.appendChild(refElement);
                }
            }
            // remove default "Uncategorized" category
            if (this.removeDefaultCategory) {
                Element unitsElement = (Element) repoElement.getElementsByTagName("units").item(0);
                NodeList units = unitsElement.getElementsByTagName("unit");
                for (int i = 0; i < units.getLength(); i++) {
                    Element unit = (Element) units.item(i);
                    String id = unit.getAttribute("id");
                    if (id != null && id.contains(".Default")) {
                        unit.getParentNode().removeChild(unit);
                    }
                }
                unitsElement.setAttribute("size",
                        Integer.toString(unitsElement.getElementsByTagName("unit").getLength()));
            }
            done = true;
        }
    }
    // .close and .closeEntry raise exception:
    // https://issues.apache.org/bugzilla/show_bug.cgi?id=3862
    ZipOutputStream outContentStream = new ZipOutputStream(new FileOutputStream(contentJar));
    ZipEntry contentXmlEntry = new ZipEntry("content.xml");
    outContentStream.putNextEntry(contentXmlEntry);
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    transformer.setOutputProperty(OutputKeys.STANDALONE, "yes");
    DOMSource source = new DOMSource(contentDoc);
    StreamResult result = new StreamResult(outContentStream);
    transformer.transform(source, result);
    contentStream.close();
    outContentStream.closeEntry();
    outContentStream.close();
    alterXzFile(new File(p2repository, "content.xml"), new File(p2repository, "content.xml.xz"), transformer,
            source);
}