Java Code Examples for javax.xml.transform.TransformerFactory#newInstance()
The following examples show how to use
javax.xml.transform.TransformerFactory#newInstance() .
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: PDFExportService.java From sakai with Educational Community License v2.0 | 6 votes |
public PDFExportService(TimeService timeService, ResourceLoader rb) { this.timeService = timeService; this.rb = rb; transformerFactory = TransformerFactory.newInstance(); transformerFactory.setURIResolver( new MyURIResolver(getClass().getClassLoader()) ); try { URI baseDir = getClass().getClassLoader().getResource(FOP_FONTBASEDIR).toURI(); FopFactoryBuilder builder = new FopFactoryBuilder(baseDir, new ClassPathResolver()); InputStream userConfig = getClass().getClassLoader().getResourceAsStream(FOP_USERCONFIG); fopFactory = builder.setConfiguration(new DefaultConfigurationBuilder().build(userConfig)).build(); } catch (IOException | URISyntaxException | SAXException | ConfigurationException e) { // We won't be able to do anything if we can't create a FopFactory so may as well get caller to handle. throw new RuntimeException("Failed to setup Apache FOP for calendar PDF exports.", e); } }
Example 2
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 3
Source File: NamespacePrefixTest.java From openjdk-jdk8u with GNU General Public License v2.0 | 6 votes |
@Test public void testConcurrentTransformations() throws Exception { final TransformerFactory tf = TransformerFactory.newInstance(); final Source xslsrc = new StreamSource(new StringReader(XSL)); final Templates tmpl = tf.newTemplates(xslsrc); concurrentTestPassed.set(true); // Execute multiple TestWorker tasks for (int id = 0; id < THREADS_COUNT; id++) { EXECUTOR.execute(new TransformerThread(tmpl.newTransformer(), id)); } // Initiate shutdown of previously submitted task EXECUTOR.shutdown(); // Wait for termination of submitted tasks if (!EXECUTOR.awaitTermination(THREADS_COUNT, TimeUnit.SECONDS)) { // If not all tasks terminates during the time out force them to shutdown EXECUTOR.shutdownNow(); } // Check if all transformation threads generated the correct namespace prefix assertTrue(concurrentTestPassed.get()); }
Example 4
Source File: ConnectorXmlUtils.java From freehealth-connector with GNU Affero General Public License v3.0 | 6 votes |
public static String toString(Source source) throws TechnicalConnectorException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); String var5; try { TransformerFactory tff = TransformerFactory.newInstance(); Transformer tf = tff.newTransformer(); tf.setOutputProperty("omit-xml-declaration", "yes"); Result result = new StreamResult(outputStream); tf.transform(source, result); var5 = new String(outputStream.toByteArray(), "UTF-8"); } catch (Exception var9) { throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_GENERAL, var9, new Object[]{var9.getMessage()}); } finally { ConnectorIOUtils.closeQuietly((Object)outputStream); } return var5; }
Example 5
Source File: XmlUtil.java From jsons2xsd with MIT License | 6 votes |
public static String asXmlString(Node node) { final Source source = new DOMSource(node); final StringWriter stringWriter = new StringWriter(); final Result result = new StreamResult(stringWriter); final TransformerFactory factory = TransformerFactory.newInstance(); try { final Transformer transformer = factory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); transformer.transform(source, result); return stringWriter.getBuffer().toString(); } catch (TransformerException exc) { throw new UncheckedIOException(exc.getMessage(), new IOException(exc)); } }
Example 6
Source File: CCOMMONS8SetTenantDomainTest.java From product-ei with Apache License 2.0 | 5 votes |
/** * Helper method to change the remote instance url of the registry mount in registry.xml file * * @param path * @param url */ private void changeRegistryFile(String path, String url) { try { File inputFile = new File(path); DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.parse(inputFile); Node remoteInstance = doc.getElementsByTagName("remoteInstance").item(0); // update remoteInstance attribute NamedNodeMap attr = remoteInstance.getAttributes(); Node nodeAttr = attr.getNamedItem("url"); nodeAttr.setTextContent(url); // write the content on registry.xml file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult consoleResult = new StreamResult(new FileOutputStream(path.substring(0, path.length() - 21) + "registry.xml")); transformer.transform(source, consoleResult); } catch (Exception e) { System.out.println("Error in changing the registry.xml file"); e.printStackTrace(); Assert.fail("Error in modifying registry.xml file as required"); } }
Example 7
Source File: TransformationWarningsTest.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 5 votes |
Transformer createTransformer() throws Exception { // Prepare sources for transormation Source xslsrc = new StreamSource(new StringReader(xsl)); // Create factory and transformer TransformerFactory tf = TransformerFactory.newInstance(); Transformer t = tf.newTransformer(xslsrc); // Set URI Resolver to return the newly constructed xml // stream source object from xml test string t.setURIResolver((String href, String base) -> new StreamSource(new StringReader(xml))); return t; }
Example 8
Source File: XSLT.java From jdk8u-dev-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 9
Source File: StaxSourceTests.java From spring-analysis-note with MIT License | 5 votes |
@Before public void setUp() throws Exception { TransformerFactory transformerFactory = TransformerFactory.newInstance(); transformer = transformerFactory.newTransformer(); inputFactory = XMLInputFactory.newInstance(); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); documentBuilder = documentBuilderFactory.newDocumentBuilder(); }
Example 10
Source File: STSHelper.java From freehealth-connector with GNU Affero General Public License v3.0 | 5 votes |
/** * Convert. * * @param stsResponse the sts response * @return the element * @throws IntegrationModuleException the integration module exception */ public static Element convert(Source stsResponse) throws IntegrationModuleException { try { StringWriter stringWriter = new StringWriter(); Result result = new StreamResult(stringWriter); TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(); transformer.transform(stsResponse, result); final String xmlResponse = stringWriter.getBuffer().toString(); return SAML10Converter.toElement(xmlResponse); } catch (TransformerException e) { throw new IntegrationModuleException(e); } }
Example 11
Source File: JSONDocument.java From marklogic-contentpump with Apache License 2.0 | 5 votes |
private static synchronized TransformerFactory getTransformerFactory() { if (transformerFactory == null) { transformerFactory = TransformerFactory.newInstance(); } return transformerFactory; }
Example 12
Source File: WXPayUtil.java From common-project with Apache License 2.0 | 5 votes |
/** * 将Map转换为XML格式的字符串 * * @param data Map类型数据 * @return XML格式的字符串 * @throws Exception */ public static String mapToXml(Map<String, String> data) throws Exception { org.w3c.dom.Document document = WXPayXmlUtil.newDocument(); org.w3c.dom.Element root = document.createElement("xml"); document.appendChild(root); for (String key: data.keySet()) { String value = data.get(key); if (value == null) { value = ""; } value = value.trim(); org.w3c.dom.Element filed = document.createElement(key); filed.appendChild(document.createTextNode(value)); root.appendChild(filed); } TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); DOMSource source = new DOMSource(document); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); transformer.transform(source, result); String output = writer.getBuffer().toString(); //.replaceAll("\n|\r", ""); try { writer.close(); } catch (Exception ex) { } return output; }
Example 13
Source File: BPELRESTLightUpdater.java From container with Apache License 2.0 | 5 votes |
public BPELRESTLightUpdater(ICoreEndpointService endpointService) throws ParserConfigurationException, TransformerConfigurationException { // initialize parsers this.endpointService = endpointService; this.domFactory = DocumentBuilderFactory.newInstance(); this.domFactory.setNamespaceAware(true); this.builder = this.domFactory.newDocumentBuilder(); this.factory = XPathFactory.newInstance(); this.transformerFactory = TransformerFactory.newInstance(); this.transformer = this.transformerFactory.newTransformer(); }
Example 14
Source File: OfficeHtmlUtil.java From jeewx with Apache License 2.0 | 5 votes |
/** * WORD转HTML * * @param docfile * WORD文件全路径 * @param htmlfile * 转换后HTML存放路径 * @throws Throwable * add by duanql 2013-07-17 */ public void WordConverterHtml(String docfile, String htmlfile){ try { InputStream input = new FileInputStream(docfile); HWPFDocument wordDocument = new HWPFDocument(input); WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument()); wordToHtmlConverter.processDocument(wordDocument); Document htmlDocument = wordToHtmlConverter.getDocument(); ByteArrayOutputStream outStream = new ByteArrayOutputStream(); DOMSource domSource = new DOMSource(htmlDocument); StreamResult streamResult = new StreamResult(outStream); TransformerFactory tf = TransformerFactory.newInstance(); Transformer serializer = tf.newTransformer(); serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); serializer.setOutputProperty(OutputKeys.METHOD, "html"); serializer.transform(domSource, streamResult); outStream.close(); String content = new String(outStream.toByteArray(), "UTF-8"); stringToFile(content,htmlfile); } catch (Exception e) { e.printStackTrace(); } }
Example 15
Source File: Playlist.java From MusicPlayer with MIT License | 5 votes |
public void addSong(Song song) { if (!songs.contains(song)) { songs.add(song); try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.parse(Resources.JAR + "library.xml"); XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); XPathExpression expr = xpath.compile("/library/playlists/playlist[@id=\"" + this.id + "\"]"); Node playlist = ((NodeList) expr.evaluate(doc, XPathConstants.NODESET)).item(0); Element songId = doc.createElement("songId"); songId.setTextContent(Integer.toString(song.getId())); playlist.appendChild(songId); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); DOMSource source = new DOMSource(doc); File xmlFile = new File(Resources.JAR + "library.xml"); StreamResult result = new StreamResult(xmlFile); transformer.transform(source, result); } catch (Exception ex) { ex.printStackTrace(); } } }
Example 16
Source File: PolizasPeriodov11.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 17
Source File: AppCollection.java From MeteoInfo with GNU Lesser General Public License v3.0 | 4 votes |
/** * Save plugin configure file * * @param fileName File name * @throws javax.xml.parsers.ParserConfigurationException */ public void saveConfigFile(String fileName) throws ParserConfigurationException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.newDocument(); //Plugins Element pluginsElem = doc.createElement("Applications"); for (Application app : this){ Element pluginElem = doc.createElement("Application"); Attr pluginNameAttr = doc.createAttribute("Name"); Attr pluginAuthorAttr = doc.createAttribute("Author"); Attr pluginVersionAttr = doc.createAttribute("Version"); Attr pluginDescriptionAttr = doc.createAttribute("Description"); Attr pluginPathAttr = doc.createAttribute("Path"); Attr pluginClassNameAttr = doc.createAttribute("ClassName"); Attr pluginIsLoadAttr = doc.createAttribute("IsLoad"); pluginNameAttr.setValue(app.getName()); pluginAuthorAttr.setValue(app.getAuthor()); pluginVersionAttr.setValue(app.getVersion()); pluginDescriptionAttr.setValue(app.getDescription()); pluginPathAttr.setValue(app.getPath()); pluginClassNameAttr.setValue(app.getClassName()); pluginIsLoadAttr.setValue(String.valueOf(app.isLoad())); pluginElem.setAttributeNode(pluginNameAttr); pluginElem.setAttributeNode(pluginAuthorAttr); pluginElem.setAttributeNode(pluginVersionAttr); pluginElem.setAttributeNode(pluginDescriptionAttr); pluginElem.setAttributeNode(pluginPathAttr); pluginElem.setAttributeNode(pluginClassNameAttr); pluginElem.setAttributeNode(pluginIsLoadAttr); pluginsElem.appendChild(pluginElem); } doc.appendChild(pluginsElem); try { TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); DOMSource source = new DOMSource(doc); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); PrintWriter pw = new PrintWriter(new FileOutputStream(fileName)); StreamResult result = new StreamResult(pw); transformer.transform(source, result); } catch (TransformerException mye) { } catch (IOException exp) { } }
Example 18
Source File: XMLStreamBuffer.java From TencentKona-8 with GNU General Public License v2.0 | 4 votes |
@Override protected TransformerFactory initialValue() throws Exception { return TransformerFactory.newInstance(); }
Example 19
Source File: SortTest.java From openjdk-jdk8u with GNU General Public License v2.0 | 4 votes |
@Test(dataProvider = "parameters") public final void testTransform(String lang, String xml, String xsl, String gold) throws Exception { StringWriter sw = new StringWriter(); // Create transformer factory TransformerFactory factory = TransformerFactory.newInstance(); // Use the factory to create a template containing the xsl file Templates template = factory.newTemplates(new StreamSource(getClass().getResourceAsStream(xsl))); // Use the template to create a transformer Transformer xformer = template.newTransformer(); xformer.setParameter("lang", lang); // Prepare the input and output files Source source = new StreamSource(getClass().getResourceAsStream(xml)); /* * The following may be used to produce gold files. * Using however the original gold files, and compare without considering * the format */ //String output = getClass().getResource(gold).getPath(); //Result result = new StreamResult(new FileOutputStream(output)); // use the following to verify the output against the pre-generated one Result result = new StreamResult(sw); // Apply the xsl file to the source file and write the result to the // output file xformer.transform(source, result); String out = sw.toString(); List<String> lines = Files.readAllLines(Paths.get(filepath + gold)); String[] resultLines = out.split("\n"); int i = 0; // the purpose is to test sort, so ignore the format of the output for (String line : lines) { Assert.assertEquals(resultLines[i++].trim(), line.trim()); } }
Example 20
Source File: TagSoupDocumentParser.java From android-test with Apache License 2.0 | 4 votes |
@Override protected TransformerFactory initialValue() { return TransformerFactory.newInstance(); }