javax.xml.transform.OutputKeys Java Examples

The following examples show how to use javax.xml.transform.OutputKeys. 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 File: AuroraWrapper.java    From TencentKona-8 with 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 #2
Source File: XsltView.java    From spring-analysis-note with 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 #3
Source File: O365InteractiveAuthenticatorFrame.java    From davmail with GNU General Public License v2.0 6 votes vote down vote up
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 #4
Source File: MarshallerHelper.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
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 #5
Source File: XMLUtils.java    From JavaPackager with 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 #6
Source File: JUnitFormatter.java    From cucumber-performance with 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 #7
Source File: MergerXmlUtils.java    From java-n-IDE-for-Android with 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 #8
Source File: AuroraWrapper.java    From jdk8u60 with 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 #9
Source File: DMLConfig.java    From systemds with 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 #10
Source File: XmlUtils.java    From vividus with 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 #11
Source File: ExclusionFiles.java    From cloud-opensource-java with 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 #12
Source File: JibxMarshaller.java    From java-technology-stack with 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 #13
Source File: XsltView.java    From java-technology-stack with 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 #14
Source File: XMLUtils.java    From aem-component-generator with 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 #15
Source File: DependencyResolver.java    From camel-spring-boot with 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 #16
Source File: SummerXSLTView.java    From GreenSummer with GNU Lesser General Public License v2.1 6 votes vote down vote up
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 File: DPPParameterValueWrapper.java    From mzmine3 with GNU General Public License v2.0 6 votes vote down vote up
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 #18
Source File: XmlUtils.java    From bundletool with 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 #19
Source File: JibxMarshaller.java    From spring-analysis-note with 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 #20
Source File: XMLUtils.java    From MogwaiERDesignerNG with 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 #21
Source File: BaseRequestHandler.java    From butterfly with 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 #22
Source File: XmlInterface.java    From pmd-designer with 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 #23
Source File: DIDLParser.java    From TVRemoteIME with 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 #24
Source File: ConfigFileAppender.java    From hadoop-ozone with 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 #25
Source File: JDK8207760.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider = "xsls")
public final void testBug8207760_cdata(String xsl) throws Exception {
    String[] xmls = prepareXML(true);
    Transformer t = createTransformerFromInputstream(
            new ByteArrayInputStream(xsl.getBytes(StandardCharsets.UTF_8)));
    t.setOutputProperty(OutputKeys.ENCODING, StandardCharsets.UTF_8.name());
    StringWriter sw = new StringWriter();
    t.transform(new StreamSource(new StringReader(xmls[0])), new StreamResult(sw));
    Assert.assertEquals(sw.toString().replaceAll(System.lineSeparator(), "\n"), xmls[1]);
}
 
Example #26
Source File: WXPayUtil.java    From NutzSite with Apache License 2.0 5 votes vote down vote up
/**
 * 将Map转换为XML格式的字符串
 *
 * @param data Map类型数据
 * @return XML格式的字符串
 * @throws Exception
 */
public static String mapToXml(Map<String, String> data) throws Exception {
    org.w3c.dom.Document document = WXPayXmlUtil.newDocument();
    org.w3c.dom.Element root = document.createElement("xml");
    document.appendChild(root);
    for (String key: data.keySet()) {
        String value = data.get(key);
        if (value == null) {
            value = "";
        }
        value = value.trim();
        org.w3c.dom.Element filed = document.createElement(key);
        filed.appendChild(document.createTextNode(value));
        root.appendChild(filed);
    }
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    DOMSource source = new DOMSource(document);
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    StringWriter writer = new StringWriter();
    StreamResult result = new StreamResult(writer);
    transformer.transform(source, result);
    String output = writer.getBuffer().toString(); //.replaceAll("\n|\r", "");
    try {
        writer.close();
    }
    catch (Exception ex) {
    }
    return output;
}
 
Example #27
Source File: XmlContentType.java    From milkman with MIT License 5 votes vote down vote up
public static String toPrettyString(String xml, int indent) {
    try {
        // Turn xml string into a document
        Document document = DocumentBuilderFactory.newInstance()
                .newDocumentBuilder()
                .parse(new InputSource(new ByteArrayInputStream(xml.getBytes("utf-8"))));

        // Remove whitespaces outside tags
        document.normalize();
        XPath xPath = XPathFactory.newInstance().newXPath();
        NodeList nodeList = (NodeList) xPath.evaluate("//text()[normalize-space()='']",
                                                      document,
                                                      XPathConstants.NODESET);

        for (int i = 0; i < nodeList.getLength(); ++i) {
            Node node = nodeList.item(i);
            node.getParentNode().removeChild(node);
        }

        // Setup pretty print options
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        transformerFactory.setAttribute("indent-number", indent);
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");

        // Return pretty print xml string
        StringWriter stringWriter = new StringWriter();
        transformer.transform(new DOMSource(document), new StreamResult(stringWriter));
        return stringWriter.toString();
    } catch (Exception e) {
        log.warn("Failed to format xml", e);
    }
    return xml;
}
 
Example #28
Source File: TopicRule.java    From warnings-ng-plugin with MIT License 5 votes vote down vote up
/**
 * Extracts the node content. Basically returns every character in the subsection element.
 *
 * @param subsection
 *         the subsection of a rule
 *
 * @return the node content
 * @throws TransformerException
 *         in case of an error
 */
private String extractNodeContent(final Element subsection) throws TransformerException {
    StringWriter content = new StringWriter();
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    transformer.transform(new DOMSource(subsection), new StreamResult(content));
    String text = content.toString();
    String prefixRemoved = StringUtils.substringAfter(text, ">");
    String suffixRemoved = StringUtils.substringBeforeLast(prefixRemoved, "<");

    String endSourceRemoved = StringUtils.replace(suffixRemoved, "</source>", "</code></pre>");

    return StringUtils.replace(endSourceRemoved, "<source>", "<pre><code>");
}
 
Example #29
Source File: SaajEmptyNamespaceTest.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
private String nodeToText(Node node) throws TransformerException {
    Transformer trans = TransformerFactory.newInstance().newTransformer();
    trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    StringWriter writer = new StringWriter();
    StreamResult result = new StreamResult(writer);
    trans.transform(new DOMSource(node), result);
    String bodyContent = writer.toString();
    System.out.println("SOAP body content read by SAAJ:"+bodyContent);
    return bodyContent;
}
 
Example #30
Source File: SaajEmptyNamespaceTest.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
private String nodeToText(Node node) throws TransformerException {
    Transformer trans = TransformerFactory.newInstance().newTransformer();
    trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    StringWriter writer = new StringWriter();
    StreamResult result = new StreamResult(writer);
    trans.transform(new DOMSource(node), result);
    String bodyContent = writer.toString();
    System.out.println("SOAP body content read by SAAJ:"+bodyContent);
    return bodyContent;
}