Java Code Examples for javax.xml.transform.Transformer#setOutputProperty()

The following examples show how to use javax.xml.transform.Transformer#setOutputProperty() . 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: XmlHelper.java    From packagedrone with Eclipse Public License 1.0 6 votes vote down vote up
public static void write ( final TransformerFactory transformerFactory, final Node node, final Result result, final Consumer<Transformer> transformerCustomizer ) throws TransformerException
{
    final Transformer transformer = transformerFactory.newTransformer ();
    final DOMSource source = new DOMSource ( node );

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

    if ( transformerCustomizer != null )
    {
        transformerCustomizer.accept ( transformer );
    }

    transformer.transform ( source, result );
}
 
Example 2
Source File: ConnectorXmlUtils.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public static String format(String unformattedXml, Source xslt) {
   try {
      Document doc = parseXmlFile(unformattedXml);
      DOMSource domSource = new DOMSource(doc);
      StringWriter writer = new StringWriter();
      StreamResult result = new StreamResult(writer);
      TransformerFactory tf = TransformerFactory.newInstance();
      Transformer transformer = null;
      if (xslt != null) {
         transformer = tf.newTransformer(xslt);
      } else {
         transformer = tf.newTransformer();
      }

      transformer.setOutputProperty("indent", "yes");
      transformer.setOutputProperty("omit-xml-declaration", "yes");
      transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", String.valueOf(1));
      transformer.transform(domSource, result);
      return writer.toString();
   } catch (Exception var8) {
      throw new InstantiationException(var8);
   }
}
 
Example 3
Source File: XPathMasker.java    From eclair with Apache License 2.0 6 votes vote down vote up
@Override
public String process(String string) {
    if (xPathExpressions.isEmpty()) {
        return string;
    }
    InputStream stream = new ByteArrayInputStream(string.getBytes());
    try {
        Document document = documentBuilderFactory.newDocumentBuilder().parse(stream);
        XPath xPath = xPathfactory.newXPath();
        for (String xPathExpression : xPathExpressions) {
            NodeList nodeList = (NodeList) xPath.compile(xPathExpression).evaluate(document, XPathConstants.NODESET);
            for (int a = 0; a < nodeList.getLength(); a++) {
                nodeList.item(a).setTextContent(replacement);
            }
        }
        StringWriter writer = new StringWriter();
        Transformer transformer = transformerFactory.newTransformer();
        for (Map.Entry<String, String> entry : outputProperties.entrySet()) {
            transformer.setOutputProperty(entry.getKey(), entry.getValue());
        }
        transformer.transform(new DOMSource(document), new StreamResult(writer));
        return writer.getBuffer().toString();
    } catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException | TransformerException e) {
        throw new IllegalArgumentException(e);
    }
}
 
Example 4
Source File: XmlFormatter.java    From journaldev with MIT License 6 votes vote down vote up
public static String prettyFormat(String input, String indent) {
	Source xmlInput = new StreamSource(new StringReader(input));
	StringWriter stringWriter = new StringWriter();
	try {
		TransformerFactory transformerFactory = TransformerFactory.newInstance();
		Transformer transformer = transformerFactory.newTransformer();
		transformer.setOutputProperty(OutputKeys.INDENT, "yes");
		transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "yes");
		transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", indent);
		transformer.transform(xmlInput, new StreamResult(stringWriter));

		return stringWriter.toString().trim();
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
}
 
Example 5
Source File: XmlDocument.java    From JVoiceXML with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Writes the state of the object for its particular class so that the
 * corresponding {@link #readObject(java.io.ObjectInputStream)}
 * method can restore it.
 * @param out the stream to write to
 * @throws IOException
 *         if an error occurs while writing to the stream
 */
private void writeObject(final ObjectOutputStream out)
    throws IOException {
    final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    final Result result = new StreamResult(buffer);
    final TransformerFactory transformerFactory =
        TransformerFactory.newInstance();
    try {
        final Transformer transformer = transformerFactory.newTransformer();
        final String encoding = System.getProperty("jvoicexml.xml.encoding",
            "UTF-8");
        transformer.setOutputProperty(OutputKeys.ENCODING, encoding);
        final Source source = new DOMSource(this);
        transformer.transform(source, result);
    } catch (TransformerException e) {
        throw new IOException(e.getMessage(), e);
    }
    out.writeLong(buffer.size());
    out.write(buffer.toByteArray());
}
 
Example 6
Source File: JkUtilsXml.java    From jeka with Apache License 2.0 5 votes vote down vote up
/**
 * Prints the specified document in the specified output getOutputStream.
 * The output is indented.
 */
public static void output(Document doc, OutputStream outputStream) {
    Transformer transformer;
    try {
        transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        final DOMSource source = new DOMSource(doc);
        final StreamResult console = new StreamResult(outputStream);
        transformer.transform(source, console);
    } catch (final Exception e) {
        throw JkUtilsThrowable.unchecked(e);
    }
}
 
Example 7
Source File: PojoReflector.java    From concierge with Eclipse Public License 1.0 5 votes vote down vote up
@SuppressWarnings("unused")
private final String printDoc(final Document doc) throws Exception {
	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));
	return writer.getBuffer().toString();
}
 
Example 8
Source File: XMLSerializerTest.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
public void testXml11() throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    XMLSerializer sax2xml = new XMLSerializer(baos, false);
    sax2xml.setOutputProperty(OutputKeys.VERSION, "1.1");
    ContentHandler ch = sax2xml.getContentHandler();    
    ch.startDocument();
    ch.startElement("","foo","foo", new AttributesImpl());
    ch.endElement("", "foo", "foo");
    ch.endDocument();
    String xmlStr = new String(baos.toByteArray(), StandardCharsets.UTF_8);
//    if (xmlStr.contains("1.0")) {
    // useful to investigate issues when bad XML output is produced
    //   related to which Java implementation is being used
      TransformerFactory transformerFactory = XMLUtils.createTransformerFactory();
      Transformer t = transformerFactory.newTransformer();
      t.setOutputProperty(OutputKeys.VERSION, "1.1");
      
      System.out.println("Java version is " + 
                            System.getProperty("java.vendor") + " " +
                            System.getProperty("java.version") + " " +
                            System.getProperty("java.vm.name") + " " +
                            System.getProperty("java.vm.version") + 
                         "\n  javax.xml.transform.TransformerFactory: " +
                            System.getProperty("javax.xml.transform.TransformerFactory") + 
                         "\n  Transformer version: " +
                            t.getOutputProperty(OutputKeys.VERSION));
//    }
    assertEquals("<?xml version=\"1.1\" encoding=\"UTF-8\"?><foo/>", xmlStr);
  }
 
Example 9
Source File: LogUtil.java    From gank with GNU General Public License v3.0 5 votes vote down vote up
private static void printXml(String tag, String xml, String headString) {
    if (TextUtils.isEmpty(tag)) {
        tag = TAG;
    }
    if (xml != null) {
        try {
            Source xmlInput = new StreamSource(new StringReader(xml));
            StreamResult xmlOutput = new StreamResult(new StringWriter());
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
            transformer.transform(xmlInput, xmlOutput);
            xml = xmlOutput.getWriter().toString().replaceFirst(">", ">\n");
        } catch (Exception e) {
            e.printStackTrace();
        }
        xml = headString + "\n" + xml;
    } else {
        xml = headString + "Log with null object";
    }

    printLine(tag, true);
    String[] lines = xml.split(LINE_SEPARATOR);
    for (String line : lines) {
        if (!TextUtils.isEmpty(line)) {
            Log.d(tag, "|" + line);
        }
    }
    printLine(tag, false);
}
 
Example 10
Source File: DbObjectXMLTransformerTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Before
public void setUp()
{   
    final SAXTransformerFactory stf = (SAXTransformerFactory) TransformerFactory.newInstance();
    try
    {
        xmlOut = stf.newTransformerHandler();
    }
    catch (TransformerConfigurationException error)
    {
        throw new RuntimeException("Unable to create TransformerHandler.", error);
    }
    final Transformer t = xmlOut.getTransformer();
    try
    {
        t.setOutputProperty("{http://xml.apache.org/xalan}indent-amount", "2");
    }
    catch (final IllegalArgumentException e)
    {
        // It was worth a try
    }
    t.setOutputProperty(OutputKeys.INDENT, "yes");
    t.setOutputProperty(OutputKeys.STANDALONE, "no");

    writer = new StringWriter();
    xmlOut.setResult(new StreamResult(writer));
    
    transformer = new DbObjectXMLTransformer(xmlOut);        
}
 
Example 11
Source File: XMLUtil.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static void write(Element el, OutputStream out) throws IOException {
    try {
        Transformer t = TransformerFactory.newInstance().newTransformer(
                new StreamSource(new StringReader(IDENTITY_XSLT_WITH_INDENT)));
        t.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); // NOI18N
        t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        Source source = new DOMSource(el);
        Result result = new StreamResult(out);
        t.transform(source, result);
    } catch (Exception | TransformerFactoryConfigurationError e) {
        throw new IOException(e);
    }
}
 
Example 12
Source File: ParsingServlet.java    From sc2gears with Apache License 2.0 5 votes vote down vote up
/**
 * Prints the document to the specified HTTP servlet response.
 * @param response response to print the document to
 */
public void printDocument( final HttpServletResponse response ) throws TransformerFactoryConfigurationError, TransformerException, IOException {
	response.setContentType( "text/xml" );
	response.setCharacterEncoding( "UTF-8" );
	setNoCache( response );
	
	final Transformer transformer = TransformerFactory.newInstance().newTransformer();
	transformer.setOutputProperty( OutputKeys.ENCODING, "UTF-8" );
	transformer.transform( new DOMSource( document ), new StreamResult( response.getOutputStream() ) );
}
 
Example 13
Source File: SaajEmptyNamespaceTest.java    From jdk8u-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 14
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;
}
 
Example 15
Source File: ReportGenerator.java    From zap-extensions with Apache License 2.0 5 votes vote down vote up
public static String getDebugXMLString(Document doc) throws TransformerException {
    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));
    return writer.getBuffer().toString().replaceAll("\n|\r", "");
}
 
Example 16
Source File: XMLUtil.java    From Cynthia with GNU General Public License v2.0 5 votes vote down vote up
/**
 * @description:transfer document to string 
 * @date:2014-11-11 下午4:09:14
 * @version:v1.0
 * @param document
 * @param encode
 * @return
 * @throws TransformerException
 */
public static String document2String(Document document, String encode) throws TransformerException
{
    String xml = null;
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    DOMSource source = new DOMSource(document);
    transformer.setOutputProperty("encoding", encode);
    transformer.setOutputProperty("indent", "yes");
    StringWriter sw = new StringWriter();
    transformer.transform(source, new StreamResult(sw));
    xml = sw.toString();
    return xml;
}
 
Example 17
Source File: JDK8207760.java    From jdk8u_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 18
Source File: TestBulkWriteWithTransformations.java    From java-client-api with Apache License 2.0 4 votes vote down vote up
@Test
public void testBulkLoadWithXSLTClientSideTransform() throws KeyManagementException, NoSuchAlgorithmException, Exception {
  String docId[] = { "/transform/emp.xml", "/transform/food1.xml", "/transform/food2.xml" };
  Source s[] = new Source[3];
  Scanner scanner=null, sc1 = null, sc2 = null;
  s[0] = new StreamSource("src/test/java/com/marklogic/client/functionaltest/data/employee.xml");
  s[1] = new StreamSource("src/test/java/com/marklogic/client/functionaltest/data/xml-original.xml");
  s[2] = new StreamSource("src/test/java/com/marklogic/client/functionaltest/data/xml-original-test.xml");
  // get the xslt
  Source xsl = new StreamSource("src/test/java/com/marklogic/client/functionaltest/data/employee-stylesheet.xsl");

  // create transformer
  TransformerFactory factory = TransformerFactory.newInstance();
  Transformer transformer = factory.newTransformer(xsl);
  transformer.setOutputProperty(OutputKeys.INDENT, "yes");

  XMLDocumentManager docMgr = client.newXMLDocumentManager();
  DocumentWriteSet writeset = docMgr.newWriteSet();
  for (int i = 0; i < 3; i++) {
    SourceHandle handle = new SourceHandle();
    handle.set(s[i]);
    // set the transformer
    handle.setTransformer(transformer);
    writeset.add(docId[i], handle);
    // Close handle.
    handle.close();
  }
  docMgr.write(writeset);
  FileHandle dh = new FileHandle();
  
  try {
  docMgr.read(docId[0], dh);
  scanner = new Scanner(dh.get()).useDelimiter("\\Z");
  String readContent = scanner.next();
  assertTrue("xml document contains firstname", readContent.contains("firstname"));
  docMgr.read(docId[1], dh);
  sc1 = new Scanner(dh.get()).useDelimiter("\\Z");
  readContent = sc1.next();
  assertTrue("xml document contains firstname", readContent.contains("firstname"));
  docMgr.read(docId[2], dh);
  sc2 = new Scanner(dh.get()).useDelimiter("\\Z");
  readContent = sc2.next();
  assertTrue("xml document contains firstname", readContent.contains("firstname"));
  }
  catch (Exception e) {
  	e.printStackTrace();
  }
  finally {
  	scanner.close();
  	sc1.close();
  	sc2.close();
  }

}
 
Example 19
Source File: StaEDIXMLStreamReaderTest.java    From staedi with Apache License 2.0 4 votes vote down vote up
@Test
void testEDIReporterSet() throws Exception {
    EDIInputFactory ediFactory = EDIInputFactory.newFactory();
    Map<String, Set<EDIStreamValidationError>> errors = new LinkedHashMap<>();
    ediFactory.setEDIReporter((errorEvent, reader) -> {
        Location location = reader.getLocation();
        String key;

        if (location.getElementPosition() > 0) {
            key = String.format("%s%02d@%d",
                                location.getSegmentTag(),
                                location.getElementPosition(),
                                location.getSegmentPosition());
        } else {
            key = String.format("%s@%d",
                                location.getSegmentTag(),
                                location.getSegmentPosition());
        }

        if (!errors.containsKey(key)) {
            errors.put(key, new HashSet<EDIStreamValidationError>(2));
        }

        errors.get(key).add(errorEvent);
    });
    InputStream stream = getClass().getResourceAsStream("/x12/invalid999.edi");
    SchemaFactory schemaFactory = SchemaFactory.newFactory();
    Schema schema = schemaFactory.createSchema(getClass().getResource("/x12/EDISchema999.xml"));

    EDIStreamReader ediReader = ediFactory.createEDIStreamReader(stream);
    ediReader = ediFactory.createFilteredReader(ediReader, (reader) -> {
        if (reader.getEventType() == EDIStreamEvent.START_TRANSACTION) {
            reader.setTransactionSchema(schema);
        }
        return true;
    });

    XMLStreamReader xmlReader = new StaEDIXMLStreamReader(ediReader);

    xmlReader.next(); // Per StAXSource JavaDoc, put in START_DOCUMENT state
    TransformerFactory factory = TransformerFactory.newInstance();
    Transformer transformer = factory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    StringWriter result = new StringWriter();
    transformer.transform(new StAXSource(xmlReader), new StreamResult(result));
    String resultString = result.toString();
    System.out.println("Errors: " + errors);
    System.out.println(resultString);

    Iterator<Entry<String, Set<EDIStreamValidationError>>> errorSet = errors.entrySet().iterator();
    Entry<String, Set<EDIStreamValidationError>> error = errorSet.next();
    assertEquals("IK5@4", error.getKey());
    assertEquals(EDIStreamValidationError.UNEXPECTED_SEGMENT, error.getValue().iterator().next());
    error = errorSet.next();
    assertEquals("AK101@5", error.getKey());
    assertEquals(EDIStreamValidationError.DATA_ELEMENT_TOO_LONG, error.getValue().iterator().next());
    error = errorSet.next();
    assertEquals("AK204@6", error.getKey());
    assertEquals(EDIStreamValidationError.TOO_MANY_DATA_ELEMENTS, error.getValue().iterator().next());
    error = errorSet.next();
    assertEquals("AK205@6", error.getKey());
    assertEquals(EDIStreamValidationError.TOO_MANY_DATA_ELEMENTS, error.getValue().iterator().next());
    error = errorSet.next();
    assertEquals("IK501@7", error.getKey());
    assertEquals(EDIStreamValidationError.INVALID_CODE_VALUE, error.getValue().iterator().next());
    error = errorSet.next();
    assertEquals("IK5@8", error.getKey());
    assertEquals(EDIStreamValidationError.SEGMENT_EXCEEDS_MAXIMUM_USE, error.getValue().iterator().next());

    Diff d = DiffBuilder.compare(Input.fromFile("src/test/resources/x12/invalid999_transformed.xml"))
                        .withTest(resultString).build();
    assertTrue(!d.hasDifferences(), () -> "XML unexpectedly different:\n" + d.toString(new DefaultComparisonFormatter()));
}
 
Example 20
Source File: UserParameterSaveHandler.java    From mzmine2 with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Function which creates an XML file with user parameters
 */
void saveParameters() throws SAXException, IOException, TransformerConfigurationException {

  logger.info("Saving user parameters");

  StreamResult streamResult = new StreamResult(finalStream);
  SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();

  TransformerHandler hd = tf.newTransformerHandler();

  Transformer serializer = hd.getTransformer();
  serializer.setOutputProperty(OutputKeys.INDENT, "yes");
  serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

  hd.setResult(streamResult);
  hd.startDocument();

  UserParameter<?, ?> projectParameters[] = project.getParameters();

  AttributesImpl atts = new AttributesImpl();

  atts.addAttribute("", "", UserParameterElementName.COUNT.getElementName(), "CDATA",
      String.valueOf(projectParameters.length));

  hd.startElement("", "", UserParameterElementName.PARAMETERS.getElementName(), atts);

  atts.clear();

  // <PARAMETER>
  for (UserParameter<?, ?> parameter : project.getParameters()) {

    if (canceled)
      return;

    logger.finest("Saving user parameter " + parameter.getName());

    atts.addAttribute("", "", UserParameterElementName.NAME.getElementName(), "CDATA",
        parameter.getName());

    atts.addAttribute("", "", UserParameterElementName.TYPE.getElementName(), "CDATA",
        parameter.getClass().getSimpleName());

    hd.startElement("", "", UserParameterElementName.PARAMETER.getElementName(), atts);

    atts.clear();

    fillParameterElement(parameter, hd);

    hd.endElement("", "", UserParameterElementName.PARAMETER.getElementName());
    completedParameters++;
  }

  hd.endElement("", "", UserParameterElementName.PARAMETERS.getElementName());

  hd.endDocument();

}