Java Code Examples for javax.xml.transform.TransformerFactory

The following are top voted examples for showing how to use javax.xml.transform.TransformerFactory. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: openjdk-jdk10   File: XSLTFunctionsTest.java   Source Code and License 10 votes vote down vote up
/**
 * @bug 8165116
 * Verifies that redirect works properly when extension function is enabled
 *
 * @param xml the XML source
 * @param xsl the stylesheet that redirect output to a file
 * @param output the output file
 * @param redirect the redirect file
 * @throws Exception if the test fails
 **/
@Test(dataProvider = "redirect")
public void testRedirect(String xml, String xsl, String output, String redirect) throws Exception {

    TransformerFactory tf = TransformerFactory.newInstance();
    tf.setFeature(ORACLE_ENABLE_EXTENSION_FUNCTION, true);
    Transformer t = tf.newTransformer(new StreamSource(new StringReader(xsl)));

    //Transform the xml
    tryRunWithTmpPermission(
            () -> t.transform(new StreamSource(new StringReader(xml)), new StreamResult(new StringWriter())),
            new FilePermission(output, "write"), new FilePermission(redirect, "write"));

    // Verifies that the output is redirected successfully
    String userDir = getSystemProperty("user.dir");
    Path pathOutput = Paths.get(userDir, output);
    Path pathRedirect = Paths.get(userDir, redirect);
    Assert.assertTrue(Files.exists(pathOutput));
    Assert.assertTrue(Files.exists(pathRedirect));
    System.out.println("Output to " + pathOutput + " successful.");
    System.out.println("Redirect to " + pathRedirect + " successful.");
    Files.deleteIfExists(pathOutput);
    Files.deleteIfExists(pathRedirect);
}
 
Example 2
Project: xtf   File: PomModifier.java   Source Code and License 7 votes vote down vote up
public PomModifier(final Path projectDirectory, final Path gitDirectory) {
	if (builderFactory == null) {
		builderFactory = DocumentBuilderFactory.newInstance();
		transformerFactory = TransformerFactory.newInstance();
		try {
			builder = builderFactory.newDocumentBuilder();
			transformer = transformerFactory.newTransformer();
			transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
			transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
			transformer.setOutputProperty(OutputKeys.INDENT, "yes");
			transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
		} catch (ParserConfigurationException | TransformerConfigurationException e) {
			throw new IllegalStateException(e);
		}
	}
	this.projectPomFile = gitDirectory.resolve("pom.xml");
	this.projectDirectory = projectDirectory;
	this.gitDirectory = gitDirectory;
}
 
Example 3
Project: featurea   File: XMLOutputVisitor.java   Source Code and License 6 votes vote down vote up
private void doTransform(String sXSL, OutputStream os) throws javax.xml.transform.TransformerConfigurationException, javax.xml.transform.TransformerException {
    // create the transformerfactory & transformer instance
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer t = tf.newTransformer();

    if (null == sXSL) {
        t.transform(new DOMSource(doc), new StreamResult(os));
        return;
    }

    try {
        Transformer finalTransformer = tf.newTransformer(new StreamSource(sXSL));
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        BufferedOutputStream bos = new BufferedOutputStream(baos);
        t.transform(new DOMSource(doc), new StreamResult(bos));
        bos.flush();
        StreamSource xmlSource = new StreamSource(new BufferedInputStream(new ByteArrayInputStream(baos.toByteArray())));
        finalTransformer.transform(xmlSource, new StreamResult(os));
    } catch (IOException ioe) {
        throw new javax.xml.transform.TransformerException(ioe);
    }
}
 
Example 4
Project: Aurora   File: CharacterHandler.java   Source Code and License 6 votes vote down vote up
/**
 * xml 格式化
 *
 * @param xml
 * @return
 */
public static String xmlFormat(String xml) {
    if (TextUtils.isEmpty(xml)) {
        return "Empty/Null xml content";
    }
    String message;
    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);
        message = xmlOutput.getWriter().toString().replaceFirst(">", ">\n");
    } catch (TransformerException e) {
        message = xml;
    }
    return message;
}
 
Example 5
Project: pay   File: XmlUtils.java   Source Code and License 6 votes vote down vote up
/**
 * Converts the Node/Element instance to XML payload.
 *
 * @param node the node/element instance to convert
 * @return the XML payload representing the node/element
 * @throws AlipayApiException problem converting XML to string
 */
public static String childNodeToString(Node node) throws AlipayApiException {
    String payload = null;

    try {
        Transformer tf = TransformerFactory.newInstance().newTransformer();

        Properties props = tf.getOutputProperties();
        props.setProperty(OutputKeys.OMIT_XML_DECLARATION, LOGIC_YES);
        tf.setOutputProperties(props);

        StringWriter writer = new StringWriter();
        tf.transform(new DOMSource(node), new StreamResult(writer));
        payload = writer.toString();
        payload = payload.replaceAll(REG_INVALID_CHARS, " ");
    } catch (TransformerException e) {
        throw new AlipayApiException("XML_TRANSFORM_ERROR", e);
    }

    return payload;
}
 
Example 6
Project: lams   File: UpdateWarTask.java   Source Code and License 6 votes vote down vote up
/**
    * Writes the modified web.xml back out to war file
    * 
    * @param doc
    *            The application.xml DOM Document
    * @throws org.apache.tools.ant.DeployException
    *             in case of any problems
    */
   protected void writeWebXml(final Document doc, final OutputStream outputStream) throws DeployException {
try {
    doc.normalize();

    // Prepare the DOM document for writing
    DOMSource source = new DOMSource(doc);

    // Prepare the output file
    StreamResult result = new StreamResult(outputStream);

    // Write the DOM document to the file
    // Get Transformer
    Transformer xformer = TransformerFactory.newInstance().newTransformer();
    // Write to a file
    xformer.transform(source, result);
} catch (TransformerException tex) {
    throw new DeployException("Error writing out modified web xml ", tex);
}
   }
 
Example 7
Project: convertigo-engine   File: ProjectUtils.java   Source Code and License 6 votes vote down vote up
public static void getFullProjectDOM(Document document,String projectName, StreamSource xslFilter) throws TransformerFactoryConfigurationError, EngineException, TransformerException{
	Element root = document.getDocumentElement();
	getFullProjectDOM(document,projectName);
	
	// transformation du dom
	Transformer xslt = TransformerFactory.newInstance().newTransformer(xslFilter);				
	Element xsl = document.createElement("xsl");
	xslt.transform(new DOMSource(document), new DOMResult(xsl));
	root.replaceChild(xsl.getFirstChild(), root.getFirstChild());
}
 
Example 8
Project: incubator-netbeans   File: XMLUtil.java   Source Code and License 6 votes vote down vote up
public static void write(Document doc, OutputStream out) throws IOException {
    // XXX note that this may fail to write out namespaces correctly if the document
    // is created with namespaces and no explicit prefixes; however no code in
    // this package is likely to be doing so
    try {
        Transformer t = TransformerFactory.newInstance().newTransformer(
                new StreamSource(new StringReader(IDENTITY_XSLT_WITH_INDENT)));
        DocumentType dt = doc.getDoctype();
        if (dt != null) {
            String pub = dt.getPublicId();
            if (pub != null) {
                t.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, pub);
            }
            t.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, dt.getSystemId());
        }
        t.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); // NOI18N
        Source source = new DOMSource(doc);
        Result result = new StreamResult(out);
        t.transform(source, result);
    } catch (Exception | TransformerFactoryConfigurationError e) {
        throw new IOException(e);
    }
}
 
Example 9
Project: openjdk-jdk10   File: DocumentBuilderFactoryTest.java   Source Code and License 6 votes vote down vote up
/**
 * Test for the isIgnoringElementContentWhitespace and the
 * setIgnoringElementContentWhitespace. The xml file has all kinds of
 * whitespace,tab and newline characters, it uses the MyNSContentHandler
 * which does not invoke the characters callback when this
 * setIgnoringElementContentWhitespace is set to true.
 * @throws Exception If any errors occur.
 */
@Test
public void testCheckElementContentWhitespace() throws Exception {
    String goldFile = GOLDEN_DIR + "dbfactory02GF.out";
    String outputFile = USER_DIR + "dbfactory02.out";
    MyErrorHandler eh = MyErrorHandler.newInstance();
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(true);
    assertFalse(dbf.isIgnoringElementContentWhitespace());
    dbf.setIgnoringElementContentWhitespace(true);
    DocumentBuilder db = dbf.newDocumentBuilder();
    db.setErrorHandler(eh);
    Document doc = db.parse(new File(XML_DIR, "DocumentBuilderFactory06.xml"));
    assertFalse(eh.isErrorOccured());
    DOMSource domSource = new DOMSource(doc);
    TransformerFactory tfactory = TransformerFactory.newInstance();
    Transformer transformer = tfactory.newTransformer();
    SAXResult saxResult = new SAXResult();
    try(MyCHandler handler = MyCHandler.newInstance(new File(outputFile))) {
        saxResult.setHandler(handler);
        transformer.transform(domSource, saxResult);
    }
    assertTrue(compareWithGold(goldFile, outputFile));
}
 
Example 10
Project: incubator-netbeans   File: DesignSupport.java   Source Code and License 6 votes vote down vote up
public static String readMode(FileObject fo) throws IOException {
    final InputStream is = fo.getInputStream();
    try {
        StringWriter w = new StringWriter();
        Source t = new StreamSource(DesignSupport.class.getResourceAsStream("polishing.xsl")); // NOI18N
        Transformer tr = TransformerFactory.newInstance().newTransformer(t);
        Source s = new StreamSource(is);
        Result r = new StreamResult(w);
        tr.transform(s, r);
        return w.toString();
    } catch (TransformerException ex) {
        throw new IOException(ex);
    } finally {
        is.close();
    }
}
 
Example 11
Project: stvs   File: GeTeTaImporter.java   Source Code and License 6 votes vote down vote up
/**
 * Builds a {@link VerificationResult} from a GeTeTa {@link Message}.
 *
 * @param source the original top-level XML node of the verification result
 * @param importedMessage the JAXB-converted GeTeTa {@link Message} object
 * @return the imported result
 * @throws ImportException if an error occurs while importing
 */
private VerificationResult makeVerificationResult(Node source, Message importedMessage)
    throws ImportException {
  try {
    /* Write log to file */
    File logFile = File.createTempFile("log-verification-", ".xml");
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    DOMSource domSource = new DOMSource(source);
    StreamResult result = new StreamResult(logFile);
    transformer.transform(domSource, result);

    /* Return appropriate VerificationResult */
    switch (importedMessage.getReturncode()) {
      case RETURN_CODE_SUCCESS:
        return new VerificationSuccess(logFile);
      case RETURN_CODE_NOT_VERIFIED:
        return new edu.kit.iti.formal.stvs.model.verification.Counterexample(
            parseCounterexample(importedMessage), logFile);
      default:
        return new VerificationError(VerificationError.Reason.ERROR, logFile);
    }
  } catch (TransformerException | IOException exception) {
    throw new ImportException(exception);
  }
}
 
Example 12
Project: pay   File: XmlUtils.java   Source Code and License 6 votes vote down vote up
/**
    * Transforms the XML content to XHTML/HTML format string with the XSL.
    *
    * @param payload the XML payload to convert
    * @param xsltFile the XML stylesheet file
    * @return the transformed XHTML/HTML format string
    * @throws AlipayApiException problem converting XML to HTML
    */
   public static String xmlToHtml(String payload, File xsltFile)
throws AlipayApiException {
       String result = null;

       try {
           Source template = new StreamSource(xsltFile);
           Transformer transformer = TransformerFactory.newInstance()
                   .newTransformer(template);

           Properties props = transformer.getOutputProperties();
           props.setProperty(OutputKeys.OMIT_XML_DECLARATION, LOGIC_YES);
           transformer.setOutputProperties(props);

           StreamSource source = new StreamSource(new StringReader(payload));
           StreamResult sr = new StreamResult(new StringWriter());
           transformer.transform(source, sr);

           result = sr.getWriter().toString();
       } catch (TransformerException e) {
           throw new AlipayApiException("XML_TRANSFORM_ERROR", e);
       }

       return result;
   }
 
Example 13
Project: springboot-shiro-cas-mybatis   File: AbstractSamlObjectBuilder.java   Source Code and License 6 votes vote down vote up
/**
 * Marshal the saml xml object to raw xml.
 *
 * @param object the object
 * @param writer the writer
 * @return the xml string
 */
public String marshalSamlXmlObject(final XMLObject object, final StringWriter writer)  {
    try {
        final MarshallerFactory marshallerFactory = XMLObjectProviderRegistrySupport.getMarshallerFactory();
        final Marshaller marshaller = marshallerFactory.getMarshaller(object);
        if (marshaller == null) {
            throw new IllegalArgumentException("Cannot obtain marshaller for object " + object.getElementQName());
        }
        final Element element = marshaller.marshall(object);
        element.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", SAMLConstants.SAML20_NS);
        element.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xenc", "http://www.w3.org/2001/04/xmlenc#");

        final TransformerFactory transFactory = TransformerFactory.newInstance();
        final Transformer transformer = transFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.transform(new DOMSource(element), new StreamResult(writer));
        return writer.toString();
    } catch (final Exception e) {
        throw new IllegalStateException("An error has occurred while marshalling SAML object to xml", e);
    }
}
 
Example 14
Project: BibliotecaPS   File: JDBC4MysqlSQLXML.java   Source Code and License 6 votes vote down vote up
protected String domSourceToString() throws SQLException {
    try {
        DOMSource source = new DOMSource(this.asDOMResult.getNode());
        Transformer identity = TransformerFactory.newInstance().newTransformer();
        StringWriter stringOut = new StringWriter();
        Result result = new StreamResult(stringOut);
        identity.transform(source, result);

        return stringOut.toString();
    } catch (Throwable t) {
        SQLException sqlEx = SQLError.createSQLException(t.getMessage(), SQLError.SQL_STATE_ILLEGAL_ARGUMENT, this.exceptionInterceptor);
        sqlEx.initCause(t);

        throw sqlEx;
    }
}
 
Example 15
Project: alipay-sdk   File: XmlUtils.java   Source Code and License 6 votes vote down vote up
/**
 * Converts the Node/Element instance to XML payload.
 *
 * @param node the node/element instance to convert
 * @return the XML payload representing the node/element
 * @throws ApiException problem converting XML to string
 */
public static String childNodeToString(Node node) throws AlipayApiException {
    String payload = null;

    try {
        Transformer tf = TransformerFactory.newInstance().newTransformer();

        Properties props = tf.getOutputProperties();
        props.setProperty(OutputKeys.OMIT_XML_DECLARATION, LOGIC_YES);
        tf.setOutputProperties(props);

        StringWriter writer = new StringWriter();
        tf.transform(new DOMSource(node), new StreamResult(writer));
        payload = writer.toString();
        payload = payload.replaceAll(REG_INVALID_CHARS, " ");
    } catch (TransformerException e) {
        throw new AlipayApiException("XML_TRANSFORM_ERROR", e);
    }

    return payload;
}
 
Example 16
Project: openjdk-jdk10   File: Bug6467808.java   Source Code and License 6 votes vote down vote up
@Test
public void test() {
    try {
        SAXParserFactory fac = SAXParserFactory.newInstance();
        fac.setNamespaceAware(true);
        SAXParser saxParser = fac.newSAXParser();

        StreamSource src = new StreamSource(new StringReader(SIMPLE_TESTXML));
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        DOMResult result = new DOMResult();
        transformer.transform(src, result);
    } catch (Throwable ex) {
        // unexpected failure
        ex.printStackTrace();
        Assert.fail(ex.toString());
    }
}
 
Example 17
Project: TextHIN   File: SparqlExecutor.java   Source Code and License 6 votes vote down vote up
public static void printDocument(Node node, OutputStream out) {
  try {
    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("{http://xml.apache.org/xslt}indent-amount", "4");

    transformer.transform(
        new DOMSource(node),
        new StreamResult(new OutputStreamWriter(out, "UTF-8")));
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}
 
Example 18
Project: framework   File: XmlUtils.java   Source Code and License 6 votes vote down vote up
/**
 * Converts the Node/Element instance to XML payload.
 *
 * @param node the node/element instance to convert
 * @return the XML payload representing the node/element
 * @throws AlipayApiException problem converting XML to string
 */
public static String childNodeToString(Node node) throws AlipayApiException {
	String payload = null;

	try {
		Transformer tf = TransformerFactory.newInstance().newTransformer();

		Properties props = tf.getOutputProperties();
		props.setProperty(OutputKeys.OMIT_XML_DECLARATION, LOGIC_YES);
		tf.setOutputProperties(props);

		StringWriter writer = new StringWriter();
		tf.transform(new DOMSource(node), new StreamResult(writer));
		payload = writer.toString();
		payload = payload.replaceAll(REG_INVALID_CHARS, " ");
	} catch (TransformerException e) {
		throw new AlipayApiException("XML_TRANSFORM_ERROR", e);
	}

	return payload;
}
 
Example 19
Project: iot-plat   File: ConfigManager.java   Source Code and License 6 votes vote down vote up
public static boolean saveFile(Document document, File file) {
	boolean flag = true;
	try {
		/** 将document中的内容写入文件中 */
		TransformerFactory tFactory = TransformerFactory.newInstance();
		Transformer transformer = tFactory.newTransformer();
		/** 编码 */
		transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
		DOMSource source = new DOMSource(document);
		StreamResult result = new StreamResult(file);
		transformer.transform(source, result);
	} catch (Exception ex) {
		flag = false;
		ex.printStackTrace();
	}
	return flag;
}
 
Example 20
Project: cas-5.1.0   File: SamlUtils.java   Source Code and License 6 votes vote down vote up
/**
 * Transform saml object to String.
 *
 * @param configBean the config bean
 * @param samlObject the saml object
 * @return the string
 * @throws SamlException the saml exception
 */
public static StringWriter transformSamlObject(final OpenSamlConfigBean configBean, final XMLObject samlObject) throws SamlException {
    final StringWriter writer = new StringWriter();
    try {
        final Marshaller marshaller = configBean.getMarshallerFactory().getMarshaller(samlObject.getElementQName());
        if (marshaller != null) {
            final Element element = marshaller.marshall(samlObject);
            final DOMSource domSource = new DOMSource(element);

            final StreamResult result = new StreamResult(writer);
            final TransformerFactory tf = TransformerFactory.newInstance();
            final Transformer transformer = tf.newTransformer();
            transformer.transform(domSource, result);
        }
    } catch (final Exception e) {
        throw new SamlException(e.getMessage(), e);
    }
    return writer;
}
 
Example 21
Project: openjdk-jdk10   File: TemplatesFilterFactoryImpl.java   Source Code and License 6 votes vote down vote up
@Override
protected TransformerHandler getTransformerHandler(String xslFileName) throws SAXException, ParserConfigurationException,
        TransformerConfigurationException, IOException {
    SAXTransformerFactory factory = (SAXTransformerFactory) TransformerFactory.newInstance();
    factory.setURIResolver(uriResolver);

    TemplatesHandler templatesHandler = factory.newTemplatesHandler();

    SAXParserFactory pFactory = SAXParserFactory.newInstance();
    pFactory.setNamespaceAware(true);

    XMLReader xmlreader = pFactory.newSAXParser().getXMLReader();

    // create the stylesheet input source
    InputSource xslSrc = new InputSource(xslFileName);

    xslSrc.setSystemId(filenameToURL(xslFileName));
    // hook up the templates handler as the xsl content handler
    xmlreader.setContentHandler(templatesHandler);
    // call parse on the xsl input source

    xmlreader.parse(xslSrc);

    // extract the Templates object created from the xsl input source
    return factory.newTransformerHandler(templatesHandler.getTemplates());
}
 
Example 22
Project: openjdk-jdk10   File: Bug6565260.java   Source Code and License 6 votes vote down vote up
@Test
public void test() {
    try {
        String xmlFile = "attribset27.xml";
        String xslFile = "attribset27.xsl";

        TransformerFactory tFactory = TransformerFactory.newInstance();
        // tFactory.setAttribute("generate-translet", Boolean.TRUE);
        Transformer t = tFactory.newTransformer(new StreamSource(getClass().getResourceAsStream(xslFile)));
        StringWriter sw = new StringWriter();
        t.transform(new StreamSource(getClass().getResourceAsStream(xmlFile)), new StreamResult(sw));
        String s = sw.getBuffer().toString();
        Assert.assertFalse(s.contains("color") || s.contains("font-size"));
    } catch (Exception e) {
        Assert.fail(e.getMessage());
    }
}
 
Example 23
Project: stvs   File: XmlExporter.java   Source Code and License 6 votes vote down vote up
/**
 * Exports an Object as xml.
 *
 * @param source Object to export
 * @return The output xml is written to this stream
 * @throws ExportException Exception while exporting
 */
public ByteArrayOutputStream export(F source) throws ExportException {
    Node xmlNode = exportToXmlNode(source);
    StringWriter writer = new StringWriter();
    try {
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.transform(new DOMSource(xmlNode), new StreamResult(writer));
        String xmlString = writer.toString();
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        stream.write(xmlString.getBytes("utf-8"));
        return stream;
    } catch (TransformerException | IOException e) {
        throw new ExportException(e);
    }
}
 
Example 24
Project: NeiHanDuanZiTV   File: CharacterHandler.java   Source Code and License 6 votes vote down vote up
/**
 * xml 格式化
 *
 * @param xml
 * @return
 */
public static String xmlFormat(String xml) {
    if (TextUtils.isEmpty(xml)) {
        return "Empty/Null xml content";
    }
    String message;
    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);
        message = xmlOutput.getWriter().toString().replaceFirst(">", ">\n");
    } catch (TransformerException e) {
        message = xml;
    }
    return message;
}
 
Example 25
Project: KeYExperienceReport   File: SPLOpltionGenerator.java   Source Code and License 6 votes vote down vote up
private static void writeOut(Document doc) throws TransformerException {
	TransformerFactory transformerFactory = TransformerFactory
			.newInstance();
	Transformer transformer = transformerFactory.newTransformer();
	transformer.setOutputProperty(OutputKeys.INDENT, "yes");
	transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
	transformer.setOutputProperty(OutputKeys.STANDALONE, "no");
	DOMSource source = new DOMSource(doc);
	File f = new File("splFile.xml");
	f.delete();
	StreamResult result = new StreamResult(f);

	// Output to console for testing
	// StreamResult result = new StreamResult(System.out);

	transformer.transform(source, result);

	System.out.println("File saved!");

}
 
Example 26
Project: KeYExperienceReport   File: SPL2OpltionGenerator.java   Source Code and License 6 votes vote down vote up
private static void writeOut(Document doc) throws TransformerException {
	TransformerFactory transformerFactory = TransformerFactory
			.newInstance();
	Transformer transformer = transformerFactory.newTransformer();
	transformer.setOutputProperty(OutputKeys.INDENT, "yes");
	transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
	transformer.setOutputProperty(OutputKeys.STANDALONE, "no");
	DOMSource source = new DOMSource(doc);
	File f = new File("splFile.xml");
	f.delete();
	StreamResult result = new StreamResult(f);

	// Output to console for testing
	// StreamResult result = new StreamResult(System.out);

	transformer.transform(source, result);

	System.out.println("File saved!");

}
 
Example 27
Project: karate   File: XmlUtils.java   Source Code and License 6 votes vote down vote up
public static String toString(Node node, boolean pretty) {
    if (pretty) {
        trimWhiteSpace(node);
    }
    DOMSource domSource = new DOMSource(node);
    StringWriter writer = new StringWriter();
    StreamResult result = new StreamResult(writer);
    TransformerFactory tf = TransformerFactory.newInstance();
    try {
        Transformer transformer = tf.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        if (pretty) {
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        }
        transformer.transform(domSource, result);
        return writer.toString();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 28
Project: openjdk-jdk10   File: Bug6451633.java   Source Code and License 6 votes vote down vote up
@Test
public void test() throws Exception {
    TransformerHandler th = ((SAXTransformerFactory) TransformerFactory.newInstance()).newTransformerHandler();

    DOMResult result = new DOMResult();
    th.setResult(result);

    th.startDocument();
    th.startElement("", "root", "root", new AttributesImpl());
    th.characters(new char[0], 0, 0);
    th.endElement("", "root", "root");
    th.endDocument();

    // there's no point in having empty text --- we should remove it
    Assert.assertEquals(0, ((Document) result.getNode()).getDocumentElement().getChildNodes().getLength());
}
 
Example 29
Project: openjdk-jdk10   File: Bug6388460.java   Source Code and License 6 votes vote down vote up
@Test
public void test() {
    try {

        Source source = new StreamSource(util.BOMInputStream.createStream("UTF-16BE", this.getClass().getResourceAsStream("Hello.wsdl.data")),
                    this.getClass().getResource("Hello.wsdl.data").toExternalForm());
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer();
        transformer.transform(source, new StreamResult(baos));
        System.out.println(new String(baos.toByteArray()));
        ByteArrayInputStream bis = new ByteArrayInputStream(baos.toByteArray());
        InputSource inSource = new InputSource(bis);

        XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
        xmlInputFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.TRUE);
        XMLStreamReader reader = xmlInputFactory.createXMLStreamReader(inSource.getSystemId(), inSource.getByteStream());
        while (reader.hasNext()) {
            reader.next();
        }
    } catch (Exception ex) {
        ex.printStackTrace(System.err);
        Assert.fail("Exception occured: " + ex.getMessage());
    }
}
 
Example 30
Project: lams   File: LearningDesignRepositoryServlet.java   Source Code and License 6 votes vote down vote up
/**
 * the format should be something like this: [ ['My Workspace', null, ['Mary Morgan Folder', null, ['3 activity
 * sequence','1024'] ], ['Organisations', null, ['Developers Playpen', null, ['Lesson Sequence Folder', null,
 * ['',null] ] ], ['MATH111', null, ['Lesson Sequence Folder', null, ['',null] ] ] ] ] ]
 */
@Override
public String toString() {
    // return '[' + convert() + ']';

    Document document = getDocument();

    try {
	DOMSource domSource = new DOMSource(document);
	StringWriter writer = new StringWriter();
	StreamResult result = new StreamResult(writer);
	TransformerFactory tf = TransformerFactory.newInstance();
	Transformer transformer = tf.newTransformer();
	transformer.transform(domSource, result);
	return writer.toString();
    } catch (TransformerException ex) {
	ex.printStackTrace();
	return null;
    }
}
 
Example 31
Project: sirocco   File: XmlDocument.java   Source Code and License 6 votes vote down vote up
public void save(String fileName)
{
	try
	{
       // Use a Transformer for output
       TransformerFactory tFactory = TransformerFactory.newInstance();
       Transformer transformer = tFactory.newTransformer();

       // Get (and preserve) Document's DOCTYPE attribute
       /// TODO: keving: String systemValue = (new File(((Document) getNode()).getDoctype().getSystemId())).getName(); 
       // transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, systemValue);

       DOMSource source = new DOMSource((Document)getNode());
       StreamResult result = new StreamResult(fileName);
       transformer.transform(source, result);
	}
	catch (Exception e)
	{			
		logger.log(Level.INFO, "ERROR: Exception while saving XML document " + e.getMessage());
	}

}
 
Example 32
Project: minijax   File: LiquibaseHelper.java   Source Code and License 6 votes vote down vote up
private static void writeXml(final Document doc, final File file) throws IOException {
    doc.normalize();

    final TransformerFactory transformerFactory = TransformerFactory.newInstance(XML_FACTORY, null);

    try {
        final Transformer transformer = transformerFactory.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");
        transformer.transform(new DOMSource(doc), new StreamResult(file));
    } catch (final TransformerException ex) {
        throw new IOException(ex.getMessage(), ex);
    }
}
 
Example 33
Project: OperatieBRP   File: AbstractDienstVerzoekParser.java   Source Code and License 6 votes vote down vote up
/**
 * Hulpmethode om een xml fragment uit een node te halen middels xpath.
 * @param locatie de locatie van de node als xpath.
 * @param xPath een XPath instantie
 * @param node de basis node
 * @return de text
 */
protected static String getXmlFragment(final String locatie, final XPath xPath, final Node node) {
    try {
        final Node xPathNode = (Node) xPath.evaluate(locatie, node, XPathConstants.NODE);
        if (xPathNode != null) {
            final StringWriter buf = new StringWriter();
            final Transformer xform = TransformerFactory.newInstance().newTransformer();
            xform.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            xform.transform(new DOMSource(xPathNode), new StreamResult(buf));
            return buf.toString();
        }
    } catch (final XPathExpressionException | TransformerException e) {
        LOGGER.error("XPath voor text content kon niet worden geëvalueerd voor locatie {}.", locatie);
        throw new UnsupportedOperationException(e);
    }
    return null;
}
 
Example 34
Project: openjdk-jdk10   File: StAXSourceTest.java   Source Code and License 6 votes vote down vote up
/**
 * @bug 8152530
 * Verifies that StAXSource handles empty namespace properly. NPE was thrown
 * before the fix.
 * @throws Exception if the test fails
 */
@Test
public final void testStAXSourceWEmptyNS() throws Exception {
    String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
        + "<EntityList>\n"
        + "  <Entity xmlns=\"\">\n"
        + "  </Entity>\n"
        + "  <Entity xmlns=\"\">\n"
        + "  </Entity>\n"
        + "</EntityList> ";

    XMLInputFactory xif = XMLInputFactory.newInstance();
    XMLStreamReader xsr = xif.createXMLStreamReader(new StringReader(xml));
    xsr.nextTag();
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer t = tf.newTransformer();
    while (xsr.nextTag() == XMLStreamConstants.START_ELEMENT && xsr.getLocalName().equals("Entity")) {
        StringWriter stringResult = new StringWriter();
        t.transform(new StAXSource(xsr), new StreamResult(stringResult));
        System.out.println("result: \n" + stringResult.toString());
    }
}
 
Example 35
Project: openjdk-jdk10   File: XmlFactory.java   Source Code and License 6 votes vote down vote up
/**
 * Returns properly configured (e.g. security features) factory
 * - securityProcessing == is set based on security processing property, default is true
 */
public static TransformerFactory createTransformerFactory(boolean disableSecureProcessing) throws IllegalStateException {
    try {
        TransformerFactory factory = TransformerFactory.newInstance();
        if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.log(Level.FINE, "TransformerFactory instance: {0}", factory);
        }
        factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, !isXMLSecurityDisabled(disableSecureProcessing));
        return factory;
    } catch (TransformerConfigurationException ex) {
        LOGGER.log(Level.SEVERE, null, ex);
        throw new IllegalStateException( ex);
    } catch (AbstractMethodError er) {
        LOGGER.log(Level.SEVERE, null, er);
        throw new IllegalStateException(Messages.INVALID_JAXP_IMPLEMENTATION.format(), er);
    }
}
 
Example 36
Project: openjdk-jdk10   File: Bug6540545.java   Source Code and License 6 votes vote down vote up
@Test
public void test() {
    try {
        String xmlFile = "numbering63.xml";
        String xslFile = "numbering63.xsl";

        TransformerFactory tFactory = TransformerFactory.newInstance();
        // tFactory.setAttribute("generate-translet", Boolean.TRUE);
        Transformer t = tFactory.newTransformer(new StreamSource(getClass().getResourceAsStream(xslFile), getClass().getResource(xslFile).toString()));
        StringWriter sw = new StringWriter();
        t.transform(new StreamSource(getClass().getResourceAsStream(xmlFile)), new StreamResult(sw));
        String s = sw.getBuffer().toString();
        Assert.assertFalse(s.contains("1: Level A"));
    } catch (Exception e) {
        Assert.fail(e.getMessage());
    }
}
 
Example 37
Project: FreeCol   File: Utils.java   Source Code and License 6 votes vote down vote up
/**
 * Helper to make an XML Transformer.
 *
 * @param declaration If true, include the XML declaration.
 * @param indent If true, set up the transformer to indent.
 * @return A suitable {@code Transformer}.
 */
public static Transformer makeTransformer(boolean declaration,
                                          boolean indent) {
    Transformer tf = null;
    try {
        TransformerFactory factory = TransformerFactory.newInstance();
        factory.setAttribute("indent-number", new Integer(2));
        tf = factory.newTransformer();
        tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        tf.setOutputProperty(OutputKeys.METHOD, "xml");
        if (!declaration) {
            tf.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        }
        if (indent) {
            tf.setOutputProperty(OutputKeys.INDENT, "yes");
            tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        }
    } catch (TransformerException e) {
        logger.log(Level.WARNING, "Failed to install transformer!", e);
    }
    return tf;
}
 
Example 38
Project: openjdk-jdk10   File: OpenJDK100017Test.java   Source Code and License 6 votes vote down vote up
@Test
public final void testXMLStackOverflowBug() throws TransformerConfigurationException, IOException, SAXException {
    try {
        SAXTransformerFactory stf = (SAXTransformerFactory) TransformerFactory.newInstance();
        TransformerHandler ser = stf.newTransformerHandler();
        ser.setResult(new StreamResult(System.out));

        StringBuilder sb = new StringBuilder(4096);
        for (int x = 4096; x > 0; x--) {
            sb.append((char) x);
        }
        ser.characters(sb.toString().toCharArray(), 0, sb.toString().toCharArray().length);
        ser.endDocument();
    } catch (StackOverflowError se) {
        se.printStackTrace();
        Assert.fail("StackOverflow");
    }
}
 
Example 39
Project: the-vigilantes   File: JDBC4MysqlSQLXML.java   Source Code and License 6 votes vote down vote up
protected String domSourceToString() throws SQLException {
    try {
        DOMSource source = new DOMSource(this.asDOMResult.getNode());
        Transformer identity = TransformerFactory.newInstance().newTransformer();
        StringWriter stringOut = new StringWriter();
        Result result = new StreamResult(stringOut);
        identity.transform(source, result);

        return stringOut.toString();
    } catch (Throwable t) {
        SQLException sqlEx = SQLError.createSQLException(t.getMessage(), SQLError.SQL_STATE_ILLEGAL_ARGUMENT, this.exceptionInterceptor);
        sqlEx.initCause(t);

        throw sqlEx;
    }
}
 
Example 40
Project: bohemia   File: XmlUtils.java   Source Code and License 6 votes vote down vote up
/** 
 * Converts the Node/Element instance to XML payload. 
 * 
 * @param node the node/element instance to convert 
 * @return the XML payload representing the node/element 
 * @throws XmlException problem converting XML to string 
 */  
public static String childNodeToString(Node node) throws XmlException {  
    String payload = null;  
  
    try {  
        Transformer tf = TransformerFactory.newInstance().newTransformer();  
  
        Properties props = tf.getOutputProperties();  
        props.setProperty(OutputKeys.OMIT_XML_DECLARATION, LOGIC_YES);  
        tf.setOutputProperties(props);  
  
        StringWriter writer = new StringWriter();  
        tf.transform(new DOMSource(node), new StreamResult(writer));  
        payload = writer.toString();  
        payload = payload.replaceAll(REG_INVALID_CHARS, " ");  
    } catch (TransformerException e) {  
        throw new XmlException(XmlException.XML_TRANSFORM_ERROR, e);  
    }  
  
    return payload;  
}
 
Example 41
Project: bohemia   File: XmlUtils.java   Source Code and License 6 votes vote down vote up
/** 
 * Transforms the XML content to XHTML/HTML format string with the XSL. 
 * 
 * @param payload the XML payload to convert 
 * @param xsltFile the XML stylesheet file 
 * @return the transformed XHTML/HTML format string 
 * @throws XmlException problem converting XML to HTML 
 */  
public static String xmlToHtml(String payload, File xsltFile)  
        throws XmlException {  
    String result = null;  
  
    try {  
        Source template = new StreamSource(xsltFile);  
        Transformer transformer = TransformerFactory.newInstance()  
                .newTransformer(template);  
  
        Properties props = transformer.getOutputProperties();  
        props.setProperty(OutputKeys.OMIT_XML_DECLARATION, LOGIC_YES);  
        transformer.setOutputProperties(props);  
  
        StreamSource source = new StreamSource(new StringReader(payload));  
        StreamResult sr = new StreamResult(new StringWriter());  
        transformer.transform(source, sr);  
  
        result = sr.getWriter().toString();  
    } catch (TransformerException e) {  
        throw new XmlException(XmlException.XML_TRANSFORM_ERROR, e);  
    }  
  
    return result;  
}
 
Example 42
Project: openjdk-jdk10   File: StAXSourceTest.java   Source Code and License 5 votes vote down vote up
@Test
public final void testStAXSource2() throws XMLStreamException {
    XMLInputFactory ifactory = XMLInputFactory.newInstance();
    ifactory.setProperty("javax.xml.stream.supportDTD", Boolean.TRUE);

    StAXSource ss = new StAXSource(ifactory.createXMLStreamReader(getClass().getResource("5368141.xml").toString(),
            getClass().getResourceAsStream("5368141.xml")));
    DOMResult dr = new DOMResult();

    TransformerFactory tfactory = TransformerFactory.newInstance();
    try {
        Transformer transformer = tfactory.newTransformer();
        transformer.transform(ss, dr);
    } catch (Exception e) {
        Assert.fail(e.getMessage());
    }
}
 
Example 43
Project: jetfuel   File: StringAdapter.java   Source Code and License 5 votes vote down vote up
/**
 * Converts an xml node to a string.
 * 
 * @param node
 * @return
 */
public String convertXml(Node node) {
	try {
		TransformerFactory transformerFactory = TransformerFactory.newInstance();
		Transformer transformer = transformerFactory.newTransformer();
		DOMSource source = new DOMSource(node);
		StringWriter sw = new StringWriter();
		StreamResult result = new StreamResult(sw);
		transformer.transform(source, result);
		return sw.toString();
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
}
 
Example 44
Project: openjdk-jdk10   File: Bug6350682.java   Source Code and License 5 votes vote down vote up
@Test
public void testTransformerFactory() {
    try {
        runWithAllPerm(() -> Thread.currentThread().setContextClassLoader(null));
        TransformerFactory factory = TransformerFactory.newInstance();
        Assert.assertTrue(factory != null, "Failed to get an instance of a TransformerFactory");
    } catch (Exception e) {
        e.printStackTrace();
        Assert.fail("Exception occured: " + e.getMessage());
    } catch (TransformerFactoryConfigurationError error) {
        error.printStackTrace();
        Assert.fail(error.toString());
    }
}
 
Example 45
Project: jetfuel   File: XmlSignatureHandler.java   Source Code and License 5 votes vote down vote up
public XmlSignatureHandler() throws NoSuchAlgorithmException,
		InvalidAlgorithmParameterException {
	this.builderFactory = DocumentBuilderFactory.newInstance();
	this.builderFactory.setNamespaceAware(true);
	this.transformerFactory = TransformerFactory.newInstance();
	this.signatureFactory = XMLSignatureFactory.getInstance("DOM");
	this.digestMethod = signatureFactory.newDigestMethod(DigestMethod.SHA1, null);
	this.transformList = new ArrayList<Transform>(2);

	this.transformList.add(
			signatureFactory.newTransform(
					Transform.ENVELOPED,
					(TransformParameterSpec) null));

	this.transformList.add(
			signatureFactory.newTransform(
					"http://www.w3.org/TR/2001/REC-xml-c14n-20010315",
					(TransformParameterSpec) null));

	this.canonicalizationMethod = this.signatureFactory.newCanonicalizationMethod(
			CanonicalizationMethod.INCLUSIVE,
			(C14NMethodParameterSpec) null);

	this.signatureMethod = this.signatureFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null);
	this.keyInfoFactory = this.signatureFactory.getKeyInfoFactory();

}
 
Example 46
Project: jdk8u-jdk   File: SaajEmptyNamespaceTest.java   Source Code and License 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 47
Project: openjdk-jdk10   File: Bug6465722.java   Source Code and License 5 votes vote down vote up
@Test
public void test() {
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        Document d = dbf.newDocumentBuilder().getDOMImplementation().createDocument(null, "r", null);
        d.getDocumentElement().setAttributeNS("http://nowhere.net/", "id", "1");

        Transformer t = TransformerFactory.newInstance().newTransformer(new StreamSource(new StringReader(IDENTITY_XSLT)));
        t.transform(new DOMSource(d), new StreamResult(new StringWriter()));
    } catch (Throwable ex) {
        Assert.fail("Exception: " + ex.getMessage());
    }
}
 
Example 48
Project: openjdk-jdk10   File: Test.java   Source Code and License 5 votes vote down vote up
private static String toString(Source response) throws TransformerException, IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.transform(response, new StreamResult(bos));
    bos.close();
    return new String(bos.toByteArray());
}
 
Example 49
Project: openjdk-jdk10   File: AuroraWrapper.java   Source Code and License 5 votes vote down vote up
public static void addResults(final Document doc, final String _benchmark, final String _score) throws TransformerConfigurationException, TransformerException, IOException {
    final Element result = getRootEntity(doc);

    addBenchmarkResults(doc, result, _benchmark, _score, "1");

    final TransformerFactory tranformerFactory = TransformerFactory.newInstance();
    final Transformer tr = tranformerFactory.newTransformer();
    tr.setOutputProperty(OutputKeys.INDENT, "yes");
    try (FileOutputStream fos = new FileOutputStream(fileName)) {
        tr.transform(new DOMSource(doc), new StreamResult(fos));
    }
}
 
Example 50
Project: incubator-netbeans   File: Arch.java   Source Code and License 5 votes vote down vote up
private static String elementToString(Element e) throws IOException {
    try {
        Transformer t = TransformerFactory.newInstance().newTransformer();
        t.setOutputProperty(OutputKeys.INDENT, "no"); // NOI18N
        t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); // NOI18N
        Source source = new DOMSource(e);
        StringWriter w = new StringWriter();
        Result result = new StreamResult(w);
        t.transform(source, result);
        return w.toString();
    } catch (Exception x) {
        throw (IOException)new IOException(x.toString()).initCause(x);
    }
}
 
Example 51
Project: ibench   File: AbstractCheckExpectedOutputTester.java   Source Code and License 5 votes vote down vote up
public String docToString(final Document doc) throws TransformerException {
 DOMSource domSource = new DOMSource(doc);
 Transformer transformer = TransformerFactory.newInstance().newTransformer();
 transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
 transformer.setOutputProperty(OutputKeys.METHOD, "xml");
 transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
 transformer.setOutputProperty(OutputKeys.INDENT, "no");
 StringWriter sw = new StringWriter();
 StreamResult sr = new StreamResult(sw);
 transformer.transform(domSource, sr);
 
    return sw.toString();
}
 
Example 52
Project: incubator-netbeans   File: ActionTracker.java   Source Code and License 5 votes vote down vote up
TransformerFactory getTransformerFactory() throws TransformerConfigurationException {
    if (tfactory == null) {
        tfactory = TransformerFactory.newInstance();
    }

    return tfactory;
}
 
Example 53
Project: oscm   File: Transformers.java   Source Code and License 5 votes vote down vote up
/**
 * Creates a XML transformer with the following properties:<br />
 * <br />
 * character encoding: UTF-8<br />
 * output method: xml<br />
 * output version: 1.0
 */
public static Transformer newTransformer()
        throws TransformerConfigurationException {

    TransformerFactory factory = TransformerFactory.newInstance();
    Transformer transformer = factory.newTransformer();
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    transformer.setOutputProperty(OutputKeys.VERSION, "1.0");
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    return transformer;
}
 
Example 54
Project: jdk8u-jdk   File: Test.java   Source Code and License 5 votes vote down vote up
private static String toString(Source response) throws TransformerException, IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.transform(response, new StreamResult(bos));
    bos.close();
    return new String(bos.toByteArray());
}
 
Example 55
Project: jdk8u-jdk   File: JAXPSAXParserTest.java   Source Code and License 5 votes vote down vote up
public final void testTransform() {
    String data =
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
            + "<r>\n"
            + "    <e/>\n"
            + "</r>\n";
    String IDENTITY_XSLT_WITH_INDENT = // #5064280 workaround
            "<xsl:stylesheet version='1.0' "
            + "xmlns:xsl='http://www.w3.org/1999/XSL/Transform' "
            + "xmlns:xalan='http://xml.apache.org/xslt' "
            + "exclude-result-prefixes='xalan'>"
            + "<xsl:output method='xml' indent='yes' xalan:indent-amount='4'/>"
            + "<xsl:template match='@*|node()'>"
            + "<xsl:copy>"
            + "<xsl:apply-templates select='@*|node()'/>"
            + "</xsl:copy>"
            + "</xsl:template>"
            + "</xsl:stylesheet>";
    try {
        //Skip the default XMLReader
        System.setProperty("org.xml.sax.driver", "com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser");

        StringWriter sw = new StringWriter();
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer t = tf.newTransformer(new StreamSource(new StringReader(IDENTITY_XSLT_WITH_INDENT)));
        Result result = new StreamResult(sw);
        t.transform(new StreamSource(new StringReader(data)), result);
        success("JAXPSAXParserTest passed");
    } catch (Exception e) {
        /**
         * JAXPSAXParser throws NullPointerException since the jaxp 1.5 security
         * manager is not initialized when JAXPSAXParser is instantiated using
         * the default constructor.
        */
        fail(e.toString());
    } finally {
        System.clearProperty("org.xml.sax.driver");
    }
}
 
Example 56
Project: cas-server-4.2.1   File: AbstractSamlObjectBuilder.java   Source Code and License 5 votes vote down vote up
/**
 * Marshal the saml xml object to raw xml.
 *
 * @param object the object
 * @param writer the writer
 * @return the xml string
 */
public String marshalSamlXmlObject(final XMLObject object, final StringWriter writer)  {
    try {
        final MarshallerFactory marshallerFactory = XMLObjectProviderRegistrySupport.getMarshallerFactory();
        final Marshaller marshaller = marshallerFactory.getMarshaller(object);
        if (marshaller == null) {
            throw new IllegalArgumentException("Cannot obtain marshaller for object " + object.getElementQName());
        }
        final Element element = marshaller.marshall(object);
        element.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", SAMLConstants.SAML20_NS);
        element.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xenc", "http://www.w3.org/2001/04/xmlenc#");

        final TransformerFactory transFactory = TransformerFactory.newInstance();
        final Transformer transformer = transFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.transform(new DOMSource(element), new StreamResult(writer));
        return writer.toString();
    } catch (final Exception e) {
        throw new IllegalStateException("An error has occurred while marshalling SAML object to xml", e);
    }
}
 
Example 57
Project: ProyectoPacientes   File: JDBC4MysqlSQLXML.java   Source Code and License 5 votes vote down vote up
protected String domSourceToString() throws SQLException {
    try {
        DOMSource source = new DOMSource(this.asDOMResult.getNode());
        Transformer identity = TransformerFactory.newInstance().newTransformer();
        StringWriter stringOut = new StringWriter();
        Result result = new StreamResult(stringOut);
        identity.transform(source, result);

        return stringOut.toString();
    } catch (Throwable t) {
        SQLException sqlEx = SQLError.createSQLException(t.getMessage(), SQLError.SQL_STATE_ILLEGAL_ARGUMENT, this.exceptionInterceptor);
        sqlEx.initCause(t);

        throw sqlEx;
    }
}
 
Example 58
Project: jdk8u-jdk   File: NamespacePrefixTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testReuseTransformer() throws Exception {
    final TransformerFactory tf = TransformerFactory.newInstance();
    final Source xslsrc = new StreamSource(new StringReader(XSL));
    final Transformer t = tf.newTransformer(xslsrc);
    for (int i = 0; i < TRANSF_COUNT; i++) {
        checkResult(doTransformation(t));
    }
}
 
Example 59
Project: openjdk-jdk10   File: XmlUtil.java   Source Code and License 5 votes vote down vote up
public static TransformerFactory newTransformerFactory(boolean disableSecurity) {
    TransformerFactory factory = TransformerFactory.newInstance();
    try {
        factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, !xmlSecurityDisabled(disableSecurity));
    } catch (TransformerConfigurationException e) {
        LOGGER.log(Level.WARNING, "Factory [{0}] doesn't support secure xml processing!", new Object[]{factory.getClass().getName()});
    }
    return factory;
}
 
Example 60
Project: cas-5.1.0   File: DefaultRelyingPartyTokenProducer.java   Source Code and License 5 votes vote down vote up
private static String serializeRelyingPartyToken(final Element rpToken) {
    try {
        final StringWriter sw = new StringWriter();
        final Transformer t = TransformerFactory.newInstance().newTransformer();
        t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, BooleanUtils.toStringYesNo(Boolean.TRUE));
        t.transform(new DOMSource(rpToken), new StreamResult(sw));
        return sw.toString();
    } catch (final TransformerException e) {
        throw Throwables.propagate(e);
    }
}