Java Code Examples for javax.xml.transform.TransformerFactory#newTransformer()
The following examples show how to use
javax.xml.transform.TransformerFactory#newTransformer() .
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: FXml.java From pra with MIT License | 6 votes |
public static void sample()throws Exception { int no = 2; String root = "EnterRoot"; DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document d = db.newDocument(); Element eRoot = d.createElement(root); d.appendChild(eRoot); for (int i = 1; i <= no; i++){ String element = "EnterElement"; String data = "Enter the data"; Element e = d.createElement(element); e.appendChild(d.createTextNode(data)); eRoot.appendChild(e); } TransformerFactory tf = TransformerFactory.newInstance(); Transformer t = tf.newTransformer(); DOMSource source = new DOMSource(d); StreamResult result = new StreamResult(System.out); t.transform(source, result); }
Example 2
Source File: SoapUtils.java From teamengine with Apache License 2.0 | 6 votes |
/** * A method to get the SOAP message from the input stream. * * @param in * the input stream to be used to get the SOAP message. * * @return the SOAP message * * @author Simone Gianfranceschi */ public static Document getSOAPMessage(InputStream in) throws Exception { /* * ByteArrayOutputStream out = new ByteArrayOutputStream(); int b; while * ((b = in.read()) != -1) { out.write(b); } * * System.out.println("OUT:" + out.toString()); */ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); // Fortify Mod: Disable entity expansion to foil External Entity Injections dbf.setExpandEntityReferences(false); DocumentBuilder db = dbf.newDocumentBuilder(); Document soapMessage = db.newDocument(); // Fortify Mod: prevent external entity injection TransformerFactory tf = TransformerFactory.newInstance(); tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); Transformer t = tf.newTransformer(); // End Fortify Mod t.transform(new StreamSource(in), new DOMResult(soapMessage)); return soapMessage; }
Example 3
Source File: JUDDIRequestsAsXML.java From juddi with Apache License 2.0 | 6 votes |
private static String PrettyPrintXML(String input) { if (input == null || input.length() == 0) { return ""; } try { TransformerFactory transFactory = TransformerFactory.newInstance(); transFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); transFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, ""); Transformer transformer = transFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); //initialize StreamResult with File object to save to file StreamResult result = new StreamResult(new StringWriter()); StreamSource source = new StreamSource(new StringReader(input.trim())); transformer.transform(source, result); String xmlString = result.getWriter().toString(); return (xmlString); } catch (Exception ex) { } return null; }
Example 4
Source File: Assinar.java From Java_CTe with MIT License | 6 votes |
private static String outputXML(Document doc) throws CteException { try { ByteArrayOutputStream os = new ByteArrayOutputStream(); TransformerFactory tf = TransformerFactory.newInstance(); Transformer trans = tf.newTransformer(); trans.transform(new DOMSource(doc), new StreamResult(os)); String xml = os.toString(); xml = xml.replaceAll(System.lineSeparator(), ""); xml = xml.replaceAll(" standalone=\"no\"", ""); return xml; } catch (TransformerException e) { throw new CteException("Erro ao Transformar Documento:" + e.getMessage()); } }
Example 5
Source File: GreeterDOMSourcePayloadProvider.java From cxf with Apache License 2.0 | 6 votes |
public DOMSource invoke(DOMSource request) { DOMSource response = new DOMSource(); try { System.out.println("Incoming Client Request as a DOMSource data in PAYLOAD Mode"); TransformerFactory transformerFactory = TransformerFactory.newInstance(); transformerFactory.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true); Transformer transformer = transformerFactory.newTransformer(); StreamResult result = new StreamResult(System.out); transformer.transform(request, result); System.out.println("\n"); SOAPMessage greetMeResponse = null; try (InputStream is = getClass().getResourceAsStream("/GreetMeDocLiteralResp3.xml")) { greetMeResponse = MessageFactory.newInstance().createMessage(null, is); } response.setNode(greetMeResponse.getSOAPBody().extractContentAsDocument()); } catch (Exception ex) { ex.printStackTrace(); } return response; }
Example 6
Source File: HQMFProvider.java From cqf-ruler with Apache License 2.0 | 6 votes |
private String writeDocument(Document d) { try { DOMSource source = new DOMSource(d); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); transformer.setOutputProperty(OutputKeys.STANDALONE, "yes"); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); transformer.transform(source, result); return writer.toString(); } catch (Exception e) { return null; } }
Example 7
Source File: XmlExtensionNotificationDataConverterTest.java From JVoiceXML with GNU Lesser General Public License v2.1 | 6 votes |
public String toString(Element element) { final ByteArrayOutputStream out = new ByteArrayOutputStream(); final Result result = new StreamResult(out); final TransformerFactory transformerFactory = TransformerFactory .newInstance(); try { final Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); final Source source = new DOMSource(element); transformer.transform(source, result); return out.toString(); } catch (TransformerException e) { return super.toString(); } }
Example 8
Source File: MCRDerivateCommands.java From mycore with GNU General Public License v3.0 | 6 votes |
/** * @param style * @return * @throws TransformerFactoryConfigurationError */ private static Transformer getTransformer(String style) throws TransformerFactoryConfigurationError { String xslfile = DEFAULT_TRANSFORMER; if (style != null && style.trim().length() != 0) { xslfile = style + "-derivate.xsl"; } Transformer trans = null; try { URL xslURL = MCRDerivateCommands.class.getResource("/" + xslfile); if (xslURL != null) { StreamSource source = new StreamSource(xslURL.toURI().toASCIIString()); TransformerFactory transfakt = TransformerFactory.newInstance(); transfakt.setURIResolver(MCRURIResolver.instance()); trans = transfakt.newTransformer(source); } } catch (Exception e) { LOGGER.debug("Cannot build Transformer.", e); } return trans; }
Example 9
Source File: JAXPSAXParserTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
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 10
Source File: GatewayUtil.java From carbon-apimgt with Apache License 2.0 | 5 votes |
/** * Method to convert a Document to string * * @param doc Document to be converted * @return string representation of the given document */ private static String convertDocumentToString(Document doc) throws TransformerException { TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); StringWriter writer = new StringWriter(); transformer.transform(new DOMSource(doc), new StreamResult(writer)); return writer.getBuffer().toString(); }
Example 11
Source File: CuentasContablesv11.java From factura-electronica with Apache License 2.0 | 5 votes |
byte[] getOriginalBytes() throws Exception { JAXBSource in = new JAXBSource(context, document); ByteArrayOutputStream baos = new ByteArrayOutputStream(); Result out = new StreamResult(baos); TransformerFactory factory = tf; if (factory == null) { factory = TransformerFactory.newInstance(); factory.setURIResolver(new URIResolverImpl()); } Transformer transformer = factory.newTransformer(new StreamSource(getClass().getResourceAsStream(XSLT))); transformer.transform(in, out); return baos.toByteArray(); }
Example 12
Source File: XSLT.java From jdk8u-jdk with GNU General Public License v2.0 | 5 votes |
public static void main(String[] args) throws Exception { ByteArrayOutputStream resStream = new ByteArrayOutputStream(); TransformerFactory trf = TransformerFactory.newInstance(); Transformer tr = trf.newTransformer(new StreamSource(System.getProperty("test.src", ".")+"/"+args[1])); String res, expectedRes; tr.transform( new StreamSource(System.getProperty("test.src", ".")+"/"+args[0]), new StreamResult(resStream)); res = resStream.toString(); System.out.println("Transformation completed. Result:"+res); if (!res.replaceAll("\\s","").equals(args[2])) throw new RuntimeException("Incorrect transformation result. Expected:"+args[2]+" Observed:"+res); }
Example 13
Source File: XSLT.java From jdk8u-jdk with GNU General Public License v2.0 | 5 votes |
public static void main(String[] args) throws TransformerException { ByteArrayOutputStream resStream = new ByteArrayOutputStream(); TransformerFactory trf = TransformerFactory.newInstance(); Transformer tr = trf.newTransformer(new StreamSource(System.getProperty("test.src", ".") + XSLTRANSFORMER)); tr.transform(new StreamSource(System.getProperty("test.src", ".") + XMLTOTRANSFORM), new StreamResult(resStream)); System.out.println("Transformation completed. Result:" + resStream.toString()); if (!resStream.toString().equals(EXPECTEDRESULT)) { throw new RuntimeException("Incorrect transformation result"); } }
Example 14
Source File: XMLUtil.java From EasyML with Apache License 2.0 | 5 votes |
/** Transform a XML Document to String */ public static String toString(Document doc) { try { DOMSource domSource = new DOMSource(doc); 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 (Exception e) { e.printStackTrace(); return ""; } }
Example 15
Source File: ProjectUtil.java From AndroidRobot with Apache License 2.0 | 5 votes |
public static void addApp(String file,String name,Hashtable<String,String> attri) throws Exception{ DocumentBuilderFactory domfac=DocumentBuilderFactory.newInstance(); DocumentBuilder dombuilder=domfac.newDocumentBuilder(); FileInputStream is=new FileInputStream(file); Document doc=dombuilder.parse(is); NodeList nodeList = doc.getElementsByTagName("app"); if(nodeList != null && nodeList.getLength()>=1){ Node deviceNode = nodeList.item(0); Element device = doc.createElement("aut"); device.setTextContent(name); for(Iterator itrName=attri.keySet().iterator();itrName.hasNext();){ String attriKey = (String)itrName.next(); String attriValue = (String)attri.get(attriKey); device.setAttribute(attriKey, attriValue); } deviceNode.appendChild(device); } //save TransformerFactory tf=TransformerFactory.newInstance(); Transformer t=tf.newTransformer(); Properties props=t.getOutputProperties(); props.setProperty(OutputKeys.ENCODING, "GB2312"); t.setOutputProperties(props); DOMSource dom=new DOMSource(doc); StreamResult sr=new StreamResult(file); t.transform(dom, sr); }
Example 16
Source File: AtomTest.java From olingo-odata4 with Apache License 2.0 | 5 votes |
private String cleanup(final String input) throws Exception { final TransformerFactory factory = TransformerFactory.newInstance(); final Source xslt = new StreamSource(getClass().getResourceAsStream("atom_cleanup.xsl")); final Transformer transformer = factory.newTransformer(xslt); final StringWriter result = new StringWriter(); transformer.transform(new StreamSource(new ByteArrayInputStream(input.getBytes())), new StreamResult(result)); return result.toString(); }
Example 17
Source File: TransformerTestTemplate.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
public Transformer getTransformer(TransformerFactory tf) throws TransformerConfigurationException { if (tf == null) { tf = TransformerFactory.newInstance(); } if (xsl == null) { return tf.newTransformer(); } else { return tf.newTransformer( new StreamSource(new ByteArrayInputStream(xsl.getBytes())) ); } }
Example 18
Source File: DataIntegrationServlet.java From ontopia with Apache License 2.0 | 5 votes |
public TopicMapIF transformRequest(String transformId, InputStream xmlstream, LocatorIF base) throws Exception { InputStream xsltstream = StreamUtils.getInputStream("classpath:" + transformId + ".xsl"); if (xsltstream == null) throw new ServletException("Could not find style sheet '" + transformId + ".xsl'"); // set up source and target streams // Source xmlSource = new StreamSource(xmlstream); Source xmlSource = new StreamSource(xmlstream); Source xsltSource = new StreamSource(xsltstream); // the factory pattern supports different XSLT processors TransformerFactory transFact = TransformerFactory.newInstance(); Transformer trans = transFact.newTransformer(xsltSource); CharArrayWriter cw = new CharArrayWriter(); trans.transform(xmlSource, new StreamResult(cw)); CharArrayReader cr = new CharArrayReader(cw.toCharArray()); TopicMapStoreIF store = new InMemoryTopicMapStore(); TopicMapIF topicmap = store.getTopicMap(); store.setBaseAddress(base); XTMTopicMapReader xr = new XTMTopicMapReader(cr, base); xr.setValidation(false); xr.importInto(topicmap); return topicmap; }
Example 19
Source File: PdfRenderer.java From roboconf-platform with Apache License 2.0 | 4 votes |
@Override protected File writeFileContent( String fileContent ) throws IOException { // Generate FOP rendering new RenderingManager().render( this.outputDirectory, this.applicationTemplate, this.applicationDirectory, Renderer.FOP, this.options, this.typeAnnotations ); File index_fo = new File( this.outputDirectory, "index.fo" ); File index_pdf = new File( this.outputDirectory, "index.pdf" ); // Copy the FOP configuration file in outputDirectory InputStream conf = getClass().getResourceAsStream( "/fop.xconf" ); File fopConfig = new File( this.outputDirectory, "fop.xconf" ); Utils.copyStream( conf, fopConfig ); // Generate the PDF rendering OutputStream out = null; try { out = new BufferedOutputStream( new FileOutputStream(index_pdf) ); FopFactory fopFactory = FopFactory.newInstance( fopConfig ); Fop fop = fopFactory.newFop( "application/pdf", out ); Source src = new StreamSource( index_fo ); TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(); Result res = new SAXResult(fop.getDefaultHandler()); transformer.transform(src, res); } catch ( Exception e) { throw new IOException( e ); } finally { Utils.closeQuietly ( out ); } return index_pdf; }
Example 20
Source File: LoadDataSchemaTest.java From incubator-retired-pirk with Apache License 2.0 | 4 votes |
private void createDataSchemaIncorrectJavaType(String schemaFile) throws IOException { // Create a temporary file for the test schema, set in the properties File file = File.createTempFile(schemaFile, ".xml"); file.deleteOnExit(); logger.info("file = " + file.toString()); SystemConfiguration.setProperty("data.schemas", file.toString()); // Write to the file try { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.newDocument(); // root element Element rootElement = doc.createElement("schema"); doc.appendChild(rootElement); // Add the schemaName Element schemaNameElement = doc.createElement("schemaName"); schemaNameElement.appendChild(doc.createTextNode(dataSchemaName)); rootElement.appendChild(schemaNameElement); // Add the element - unknown Java type TestUtils.addElement(doc, rootElement, element1, "bogus", "false", PrimitiveTypePartitioner.class.getName()); // Write to a xml file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(file); transformer.transform(source, result); // Output for testing StreamResult consoleResult = new StreamResult(System.out); transformer.transform(source, consoleResult); System.out.println(); } catch (Exception e) { e.printStackTrace(); } }