Java Code Examples for javax.xml.transform.OutputKeys

The following examples show how to use javax.xml.transform.OutputKeys. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: JavaPackager   Source File: XMLUtils.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Pretiffy an XML file
 * @param file Xml file
 * @throws MojoExecutionException Something went wrong
 */
public static final void prettify(File file) throws MojoExecutionException {
	try {

		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		Document document = builder.parse(file);

		trimWhitespace(document);
		
		Transformer transformer = TransformerFactory.newInstance().newTransformer();
		transformer.setOutputProperty(OutputKeys.INDENT, "yes");
		transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
		transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC,"yes");			
		transformer.transform(new DOMSource(document), new StreamResult(file));

	} catch (Exception e) {

		throw new MojoExecutionException(e.getMessage(), e);

	}
}
 
Example 2
Source Project: hadoop-ozone   Source File: ConfigFileAppender.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Write out the XML content to a writer.
 */
public void write(Writer writer) {
  try {
    TransformerFactory factory = TransformerFactory.newInstance();
    factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
    Transformer transformer = factory.newTransformer();

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

    transformer.transform(new DOMSource(document), new StreamResult(writer));
  } catch (TransformerException e) {
    throw new ConfigurationException("Can't write the configuration xml", e);
  }
}
 
Example 3
Source Project: vividus   Source File: XmlUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Search by XPath in XML
 * @param xml XML
 * @param xpath xpath
 * @return Search result
 */
public static Optional<String> getXmlByXpath(String xml, String xpath)
{
    return XPATH_FACTORY.apply(xPathFactory -> {
        try
        {
            InputSource source = createInputSource(xml);
            NodeList nodeList = (NodeList) xPathFactory.newXPath().evaluate(xpath, source, XPathConstants.NODESET);
            Node singleNode = nodeList.item(0);
            Properties outputProperties = new Properties();
            outputProperties.setProperty(OutputKeys.OMIT_XML_DECLARATION, YES);
            return transform(new DOMSource(singleNode), outputProperties);
        }
        catch (XPathExpressionException e)
        {
            throw new IllegalStateException(e.getMessage(), e);
        }
    });
}
 
Example 4
Source Project: spring-analysis-note   Source File: XsltView.java    License: MIT License 6 votes vote down vote up
/**
 * Configure the supplied {@link HttpServletResponse}.
 * <p>The default implementation of this method sets the
 * {@link HttpServletResponse#setContentType content type} and
 * {@link HttpServletResponse#setCharacterEncoding encoding}
 * from the "media-type" and "encoding" output properties
 * specified in the {@link Transformer}.
 * @param model merged output Map (never {@code null})
 * @param response current HTTP response
 * @param transformer the target transformer
 */
protected void configureResponse(Map<String, Object> model, HttpServletResponse response, Transformer transformer) {
	String contentType = getContentType();
	String mediaType = transformer.getOutputProperty(OutputKeys.MEDIA_TYPE);
	String encoding = transformer.getOutputProperty(OutputKeys.ENCODING);
	if (StringUtils.hasText(mediaType)) {
		contentType = mediaType;
	}
	if (StringUtils.hasText(encoding)) {
		// Only apply encoding if content type is specified but does not contain charset clause already.
		if (contentType != null && !contentType.toLowerCase().contains(WebUtils.CONTENT_TYPE_CHARSET_PREFIX)) {
			contentType = contentType + WebUtils.CONTENT_TYPE_CHARSET_PREFIX + encoding;
		}
	}
	response.setContentType(contentType);
}
 
Example 5
Source Project: spring-analysis-note   Source File: JibxMarshaller.java    License: MIT License 6 votes vote down vote up
private Object transformAndUnmarshal(Source source, @Nullable String encoding) throws IOException {
	try {
		Transformer transformer = this.transformerFactory.newTransformer();
		if (encoding != null) {
			transformer.setOutputProperty(OutputKeys.ENCODING, encoding);
		}
		ByteArrayOutputStream os = new ByteArrayOutputStream(1024);
		transformer.transform(source, new StreamResult(os));
		ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
		return unmarshalInputStream(is);
	}
	catch (TransformerException ex) {
		throw new MarshallingFailureException(
				"Could not transform from [" + ClassUtils.getShortName(source.getClass()) + "]", ex);
	}
}
 
Example 6
Source Project: camel-spring-boot   Source File: DependencyResolver.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Retrieves a list of dependencies of the given scope
 */
public static List<String> getDependencies(String pom, String scope) throws Exception {
    String expression = "/project/dependencies/dependency[scope='" + scope + "']";

    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(pom);
    XPath xpath = xPathfactory.newXPath();
    XPathExpression expr = xpath.compile(expression);

    List<String> dependencies = new LinkedList<>();
    NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
    for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        try (StringWriter writer = new StringWriter()) {
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            transformer.transform(new DOMSource(node), new StreamResult(writer));
            String xml = writer.toString();
            dependencies.add(xml);
        }
    }

    return dependencies;
}
 
Example 7
Source Project: bundletool   Source File: XmlUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static String documentToString(Node document) {
  StringWriter sw = new StringWriter();
  try {
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    transformer.transform(new DOMSource(document), new StreamResult(sw));
  } catch (TransformerException e) {
    throw new IllegalStateException("An error occurred while converting the XML to a string", e);
  }
  return sw.toString();
}
 
Example 8
Source Project: MogwaiERDesignerNG   Source File: XMLUtils.java    License: GNU General Public License v3.0 6 votes vote down vote up
public void transform(Document aDocument, Writer aWriter)
		throws TransformerException {

	ApplicationPreferences thePreferences = ApplicationPreferences
			.getInstance();

	Transformer theTransformer = transformerFactory.newTransformer();
	theTransformer.setOutputProperty(OutputKeys.INDENT, "yes");
	theTransformer.setOutputProperty(OutputKeys.METHOD, "xml");
	theTransformer.setOutputProperty(OutputKeys.ENCODING, PlatformConfig
			.getXMLEncoding());
	theTransformer.setOutputProperty(
			"{http://xml.apache.org/xslt}indent-amount", ""
					+ thePreferences.getXmlIndentation());
	theTransformer.transform(new DOMSource(aDocument), new StreamResult(
			aWriter));
}
 
Example 9
Source Project: pmd-designer   Source File: XmlInterface.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
/** Saves parameters to disk. */
private void save(Document document, File outputFile) throws IOException {
    try {
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();

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

        Source source = new DOMSource(document);
        outputFile.getParentFile().mkdirs();
        Result result = new StreamResult(Files.newBufferedWriter(outputFile.toPath(), StandardCharsets.UTF_8));
        transformer.transform(source, result);
    } catch (TransformerException e) {
        throw new IOException("Failed to save settings", e);
    }
}
 
Example 10
public void saveToFile(final @Nonnull File file) {
  try {
    Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    final Element element = document.createElement(MAINFILE_ELEMENT);
    document.appendChild(element);

    this.saveValueToXML(element);

    // Create transformer.
    final Transformer transformer = TransformerFactory.newInstance().newTransformer();
    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", "4");

    // Write to file and transform.
    transformer.transform(new DOMSource(document), new StreamResult(new FileOutputStream(file)));

  } catch (ParserConfigurationException | TransformerFactoryConfigurationError
      | FileNotFoundException | TransformerException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
  }
}
 
Example 11
Source Project: aem-component-generator   Source File: XMLUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Method will transform Document structure by prettify xml elements to file.
 *
 * @param document The {@link Document} object
 * @param filePath The path to the file
 */
public static void transformDomToFile(Document document, String filePath) {
    try {
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer tr = tf.newTransformer();

        //config for beautify/prettify xml content.
        tr.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        tr.setOutputProperty(OutputKeys.INDENT, "yes");
        tr.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

        DOMSource source = new DOMSource(document);
        File file = CommonUtils.getNewFileAtPathAndRenameExisting(filePath);
        StreamResult result = new StreamResult(file);

        //transform your DOM source to the given file location.
        tr.transform(source, result);

    } catch (Exception e) {
        throw new GeneratorException("Exception while DOM conversion to file : " + filePath);
    }
}
 
Example 12
Source Project: java-n-IDE-for-Android   Source File: MergerXmlUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Outputs the given XML {@link Document} as a string.
 *
 * TODO right now reformats the document. Needs to output as-is, respecting white-space.
 *
 * @param doc The document to output. Must not be null.
 * @param log A log in case of error.
 * @return A string representation of the XML. Null in case of error.
 */
static String printXmlString(
        @NonNull Document doc,
        @NonNull IMergerLog log) {
    try {
        Transformer tf = TransformerFactory.newInstance().newTransformer();
        tf.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");        //$NON-NLS-1$
        tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");                  //$NON-NLS-1$
        tf.setOutputProperty(OutputKeys.INDENT, "yes");                      //$NON-NLS-1$
        tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount",    //$NON-NLS-1$
                             "4");                                           //$NON-NLS-1$
        StringWriter sw = new StringWriter();
        tf.transform(new DOMSource(doc), new StreamResult(sw));
        return sw.toString();
    } catch (TransformerException e) {
        log.error(Severity.ERROR,
                new FileAndLine(extractXmlFilename(doc), 0),
                "Failed to write XML file: %1$s",
                e.toString());
        return null;
    }
}
 
Example 13
Source Project: butterfly   Source File: BaseRequestHandler.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Sends the response to the client.
 * @param request The original request.
 * @param response The response object we can use to send the data.
 * @param respBody The XML document of the response.
 * @return A response object for Spark
 */
protected Object sendResponse(final Request request, final Response response, final BaseXMLBuilder respBody) {
    // get the bytes of the XML document
    final ByteArrayOutputStream bos = new ByteArrayOutputStream();

    try {
        final TransformerFactory transformerFactory = TransformerFactory.newInstance();
        final Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");

        final DOMSource source = new DOMSource(respBody.getDocument());
        final StreamResult result = new StreamResult(bos);
        transformer.transform(source, result);
    } catch (TransformerException e) {
        e.printStackTrace();
        return 500;
    }

    byte[] respBytes = bos.toByteArray();
    return this.sendBytesToClient(respBytes, request, response);
}
 
Example 14
Source Project: TencentKona-8   Source File: AuroraWrapper.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Test
 */
@SuppressWarnings("UseSpecificCatch")
public static void main(final String... args) {
    try {
        deleteReportDocument();
        Document document = createOrOpenDocument();
        addResults(document, "benchmark1", "0.01");
        document = createOrOpenDocument();
        addResults(document, "benchmark2", "0.02");
        document = createOrOpenDocument();
        addResults(document, "benchmark3", "0.03");

        final TransformerFactory tranformerFactory = TransformerFactory.newInstance();
        final Transformer tr = tranformerFactory.newTransformer();
        tr.setOutputProperty(OutputKeys.INDENT, "yes");
        tr.transform(new DOMSource(document), new StreamResult(System.out));
    } catch (final Exception e) {
        e.printStackTrace();
    }
}
 
Example 15
Source Project: TVRemoteIME   Source File: DIDLParser.java    License: GNU General Public License v2.0 6 votes vote down vote up
protected String documentToString(Document document, boolean omitProlog) throws Exception {
    TransformerFactory transFactory = TransformerFactory.newInstance();

    // Indentation not supported on Android 2.2
    //transFactory.setAttribute("indent-number", 4);

    Transformer transformer = transFactory.newTransformer();

    if (omitProlog) {
        // TODO: UPNP VIOLATION: Terratec Noxon Webradio fails when DIDL content has a prolog
        // No XML prolog! This is allowed because it is UTF-8 encoded and required
        // because broken devices will stumble on SOAP messages that contain (even
        // encoded) XML prologs within a message body.
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    }

    // Again, Android 2.2 fails hard if you try this.
    //transformer.setOutputProperty(OutputKeys.INDENT, "yes");

    StringWriter out = new StringWriter();
    transformer.transform(new DOMSource(document), new StreamResult(out));
    return out.toString();
}
 
Example 16
private Transformer getTransformer(Map<String, Object> model, HttpServletRequest request) throws TransformerConfigurationException {
    Transformer transformer = null;
    boolean showXML = Boolean.TRUE.equals(model.get(XsltConfiguration.SHOW_XML_SOURCE_FLAG));
    boolean refreshXSLT = devMode || Boolean.TRUE.equals(model.get(XsltConfiguration.REFRESH_XSLT_FLAG));
    if (!showXML && devMode) {
        String showXMLString = request.getParameter(XsltConfiguration.SHOW_XML_SOURCE_FLAG);
        if (showXMLString == null) {
            showXMLString = (String) request.getAttribute(XsltConfiguration.SHOW_XML_SOURCE_FLAG);
        }
        showXML = Boolean.parseBoolean(showXMLString);
    }
    if (!refreshXSLT) {
        String refreshXSLTString = request.getParameter(XsltConfiguration.REFRESH_XSLT_FLAG);
        if (refreshXSLTString == null) {
            refreshXSLTString = (String) request.getAttribute(XsltConfiguration.REFRESH_XSLT_FLAG);
        }
        refreshXSLT = Boolean.parseBoolean(refreshXSLTString);
    }
    if (showXML) {
        transformer = getTransformerFactory().newTransformer();
        transformer.setOutputProperty(OutputKeys.MEDIA_TYPE, "text/xml");
    } else {
        transformer = createTransformer(loadTemplates(!refreshXSLT));
    }
    return transformer;
}
 
Example 17
Source Project: java-technology-stack   Source File: XsltView.java    License: MIT License 6 votes vote down vote up
/**
 * Configure the supplied {@link HttpServletResponse}.
 * <p>The default implementation of this method sets the
 * {@link HttpServletResponse#setContentType content type} and
 * {@link HttpServletResponse#setCharacterEncoding encoding}
 * from the "media-type" and "encoding" output properties
 * specified in the {@link Transformer}.
 * @param model merged output Map (never {@code null})
 * @param response current HTTP response
 * @param transformer the target transformer
 */
protected void configureResponse(Map<String, Object> model, HttpServletResponse response, Transformer transformer) {
	String contentType = getContentType();
	String mediaType = transformer.getOutputProperty(OutputKeys.MEDIA_TYPE);
	String encoding = transformer.getOutputProperty(OutputKeys.ENCODING);
	if (StringUtils.hasText(mediaType)) {
		contentType = mediaType;
	}
	if (StringUtils.hasText(encoding)) {
		// Only apply encoding if content type is specified but does not contain charset clause already.
		if (contentType != null && !contentType.toLowerCase().contains(WebUtils.CONTENT_TYPE_CHARSET_PREFIX)) {
			contentType = contentType + WebUtils.CONTENT_TYPE_CHARSET_PREFIX + encoding;
		}
	}
	response.setContentType(contentType);
}
 
Example 18
Source Project: java-technology-stack   Source File: JibxMarshaller.java    License: MIT License 6 votes vote down vote up
private Object transformAndUnmarshal(Source source, @Nullable String encoding) throws IOException {
	try {
		Transformer transformer = this.transformerFactory.newTransformer();
		if (encoding != null) {
			transformer.setOutputProperty(OutputKeys.ENCODING, encoding);
		}
		ByteArrayOutputStream os = new ByteArrayOutputStream(1024);
		transformer.transform(source, new StreamResult(os));
		ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
		return unmarshalInputStream(is);
	}
	catch (TransformerException ex) {
		throw new MarshallingFailureException(
				"Could not transform from [" + ClassUtils.getShortName(source.getClass()) + "]", ex);
	}
}
 
Example 19
public String dumpDocument(Document document) {
    String result;
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
        transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, "");
        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", "4");

        transformer.transform(new DOMSource(document),
                new StreamResult(new OutputStreamWriter(baos, StandardCharsets.UTF_8)));
        result = baos.toString("UTF-8");
    } catch (Exception e) {
        result = e + " " + e.getMessage();
    }
    return result;
}
 
Example 20
public X toObject(Node source) {
   try {
      StringWriter sw = new StringWriter();
      try {
         Transformer t = TransformerFactory.newInstance().newTransformer();
         t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
         t.transform(new DOMSource(source), new StreamResult(sw));
      } catch (TransformerException te) {
         System.out.println("nodeToString Transformer Exception");
      }
      String content =  sw.toString();

      return (X) this.getUnMarshaller().unmarshal(source);
   } catch (JAXBException var5) {
      JAXBException e = var5;

      try {
         LOG.debug("Unable to unmarshall class from source.", e);
         return this.getUnMarshaller().unmarshal(source, this.unmarshallClass).getValue();
      } catch (JAXBException var4) {
         var4.setLinkedException(var5);
         throw handleException(var4);
      }
   }
}
 
Example 21
Source Project: cucumber-performance   Source File: JUnitFormatter.java    License: MIT License 6 votes vote down vote up
private void finishReport() {
	try {
		this.out = this.builder.build();
		// set up a transformer
		rootElement.setAttribute("name", JUnitFormatter.class.getName());
		rootElement.setAttribute("failures",
				String.valueOf(rootElement.getElementsByTagName("failure").getLength()));
		rootElement.setAttribute("skipped",
				String.valueOf(rootElement.getElementsByTagName("skipped").getLength()));
		rootElement.setAttribute("time", sumTimes(rootElement.getElementsByTagName("testcase")));
		if (rootElement.getElementsByTagName("testcase").getLength() == 0) {
			addDummyTestCase(); // to avoid failed Jenkins jobs
		}
		TransformerFactory transfac = TransformerFactory.newInstance();
		Transformer trans = transfac.newTransformer();
		trans.setOutputProperty(OutputKeys.INDENT, "yes");
		StreamResult result = new StreamResult(out);
		DOMSource source = new DOMSource(doc);
		trans.transform(source, result);
		closeQuietly(out);
	} catch (TransformerException e) {
		throw new CucumberException("Error while transforming.", e);
	}
}
 
Example 22
Source Project: jdk8u60   Source File: AuroraWrapper.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Test
 */
@SuppressWarnings("UseSpecificCatch")
public static void main(final String... args) {
    try {
        deleteReportDocument();
        Document document = createOrOpenDocument();
        addResults(document, "benchmark1", "0.01");
        document = createOrOpenDocument();
        addResults(document, "benchmark2", "0.02");
        document = createOrOpenDocument();
        addResults(document, "benchmark3", "0.03");

        final TransformerFactory tranformerFactory = TransformerFactory.newInstance();
        final Transformer tr = tranformerFactory.newTransformer();
        tr.setOutputProperty(OutputKeys.INDENT, "yes");
        tr.transform(new DOMSource(document), new StreamResult(System.out));
    } catch (final Exception e) {
        e.printStackTrace();
    }
}
 
Example 23
Source Project: systemds   Source File: DMLConfig.java    License: Apache License 2.0 6 votes vote down vote up
public synchronized String serializeDMLConfig() 
{
	String ret = null;
	try {
		Transformer transformer = TransformerFactory.newInstance().newTransformer();
		transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
		//transformer.setOutputProperty(OutputKeys.INDENT, "yes");
		StreamResult result = new StreamResult(new StringWriter());
		DOMSource source = new DOMSource(_xmlRoot);
		transformer.transform(source, result);
		ret = result.getWriter().toString();
	}
	catch(Exception ex) {
		throw new DMLRuntimeException("Unable to serialize DML config.", ex);
	}
	
	return ret;
}
 
Example 24
Source Project: cloud-opensource-java   Source File: ExclusionFiles.java    License: Apache License 2.0 6 votes vote down vote up
private static void insertIndent(InputStream inputStream, OutputStream outputStream)
    throws TransformerException {
  // Prefer Open JDK's default Transformer, rather than the one in net.sf.saxon:Saxon-HE. The
  // latter does not recognize "{http://xml.apache.org/xslt}indent-amount" property.
  System.setProperty(
      "javax.xml.transform.TransformerFactory",
      "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl");

  TransformerFactory transformerFactory = TransformerFactory.newInstance();
  Transformer indentTransformer = transformerFactory.newTransformer();
  indentTransformer.setOutputProperty(OutputKeys.INDENT, "yes");
  // OpenJDK's default Transformer recognizes this property
  indentTransformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
  // Add new line character after doctype declaration
  indentTransformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "yes");

  indentTransformer.transform(new StreamSource(inputStream), new StreamResult(outputStream));
}
 
Example 25
Source Project: openvsx   Source File: SitemapController.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@GetMapping(path = "/sitemap.xml", produces = MediaType.APPLICATION_XML_VALUE)
public ResponseEntity<StreamingResponseBody> getSitemap() throws ParserConfigurationException {
    var document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    document.setXmlStandalone(true);
    var urlset = document.createElementNS(NAMESPACE_URI, "urlset");
    document.appendChild(urlset);
    
    var baseUrl = getBaseUrl();
    var timestampFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    repositories.findAllExtensions().forEach(extension -> {
        var entry = document.createElement("url");
        var loc = document.createElement("loc");
        loc.setTextContent(UrlUtil.createApiUrl(baseUrl, "extension", extension.getNamespace().getName(), extension.getName()));
        entry.appendChild(loc);
        var lastmod = document.createElement("lastmod");
        lastmod.setTextContent(extension.getLatest().getTimestamp().format(timestampFormatter));
        entry.appendChild(lastmod);
        urlset.appendChild(entry);
    });

    StreamingResponseBody stream = out -> {
        try {
            var transformer = TransformerFactory.newInstance().newTransformer();
            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
            transformer.transform(new DOMSource(document), new StreamResult(out));
        } catch (TransformerException exc) {
            throw new RuntimeException(exc);
        }
    };
    return new ResponseEntity<>(stream, HttpStatus.OK);
}
 
Example 26
/**
 * Internal method to create the initial set of properties. There
 * are two layers of properties: the default layer and the base layer.
 * The latter contains properties defined in the stylesheet or by
 * the user using this API.
 */
private Properties createOutputProperties(Properties outputProperties) {
    final Properties defaults = new Properties();
    setDefaults(defaults, "xml");

    // Copy propeties set in stylesheet to base
    final Properties base = new Properties(defaults);
    if (outputProperties != null) {
        final Enumeration names = outputProperties.propertyNames();
        while (names.hasMoreElements()) {
            final String name = (String) names.nextElement();
            base.setProperty(name, outputProperties.getProperty(name));
        }
    }
    else {
        base.setProperty(OutputKeys.ENCODING, _translet._encoding);
        if (_translet._method != null)
            base.setProperty(OutputKeys.METHOD, _translet._method);
    }

    // Update defaults based on output method
    final String method = base.getProperty(OutputKeys.METHOD);
    if (method != null) {
        if (method.equals("html")) {
            setDefaults(defaults,"html");
        }
        else if (method.equals("text")) {
            setDefaults(defaults,"text");
        }
    }

    return base;
}
 
Example 27
Source Project: localization_nifi   Source File: TestEvaluateXQuery.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSetTransformerProperties() throws Exception {

    for (int i = 0; i < methods.length; i++) {
        for (int j = 0; j < booleans.length; j++) {
            for (int k = 0; k < booleans.length; k++) {
                Properties props = EvaluateXQuery.getTransformerProperties(methods[i], booleans[j], booleans[k]);
                assertEquals(3, props.size());
                assertEquals(methods[i], props.getProperty(OutputKeys.METHOD));
                assertEquals(booleans[j] ? "yes" : "no", props.getProperty(OutputKeys.INDENT));
                assertEquals(booleans[k] ? "yes" : "no", props.getProperty(OutputKeys.OMIT_XML_DECLARATION));
            }
        }
    }
}
 
Example 28
Source Project: CQL   Source File: OverviewFileIO.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Output the document as XML
 *
 * @param outputFile output file
 * @param xml        output XML
 */
private static void outputXMLtoFile(File outputFile, Document xml) {
	try {
		TransformerFactory tFactory = TransformerFactory.newInstance();
		Transformer transformer = tFactory.newTransformer();

		transformer.setOutputProperty(OutputKeys.INDENT, "yes");
		transformer.transform(new DOMSource(xml), new StreamResult(outputFile));
	} catch (Exception e) {
		System.err.println("Error exporting data.");
	}
}
 
Example 29
Source Project: spring-analysis-note   Source File: TransformerUtilsTests.java    License: MIT License 5 votes vote down vote up
@Test
public void enableIndentingSunnyDay() throws Exception {
	Transformer transformer = new StubTransformer();
	TransformerUtils.enableIndenting(transformer);
	String indent = transformer.getOutputProperty(OutputKeys.INDENT);
	assertNotNull(indent);
	assertEquals("yes", indent);
	String indentAmount = transformer.getOutputProperty("{http://xml.apache.org/xalan}indent-amount");
	assertNotNull(indentAmount);
	assertEquals(String.valueOf(TransformerUtils.DEFAULT_INDENT_AMOUNT), indentAmount);
}
 
Example 30
Source Project: spring-analysis-note   Source File: TransformerUtilsTests.java    License: MIT License 5 votes vote down vote up
@Test
public void disableIndentingSunnyDay() throws Exception {
	Transformer transformer = new StubTransformer();
	TransformerUtils.disableIndenting(transformer);
	String indent = transformer.getOutputProperty(OutputKeys.INDENT);
	assertNotNull(indent);
	assertEquals("no", indent);
}