/** * @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); }
public static Document loadXML(ByteArrayInputStream byteArrayInputStream) { try { StreamSource streamSource = new StreamSource(byteArrayInputStream); DocumentBuilderFactory dbf = DocumentBuilderFactoryImpl.newInstance() ; DocumentBuilder db = dbf.newDocumentBuilder() ; Document doc = db.newDocument() ; Result res = new DOMResult(doc) ; TransformerFactory tr = TransformerFactory.newInstance(); Transformer xformer = tr.newTransformer(); xformer.transform(streamSource, res); return doc ; } catch (Exception e) { String csError = e.toString(); Log.logImportant(csError); Log.logImportant("ERROR while loading XML from byteArrayInputStream "+byteArrayInputStream.toString()); } return null; }
@Test public void testProperty() throws TransformerConfigurationException { /* Create a transform factory instance */ TransformerFactory tfactory = TransformerFactory.newInstance(); /* Create a StreamSource instance */ StreamSource streamSource = new StreamSource(new StringReader(xslData)); transformer = tfactory.newTransformer(streamSource); transformer.setOutputProperty(INDENT, "no"); transformer.setOutputProperty(ENCODING, "UTF-16"); assertEquals(printPropertyValue(INDENT), "indent=no"); assertEquals(printPropertyValue(ENCODING), "encoding=UTF-16"); transformer.setOutputProperties(null); assertEquals(printPropertyValue(INDENT), "indent=yes"); assertEquals(printPropertyValue(ENCODING), "encoding=UTF-8"); }
@DataProvider(name = "data_ValidatorA") public Object[][] getDataValidator() { DOMSource ds = getDOMSource(xml_val_test, xml_val_test_id, true, true, xml_catalog); SAXSource ss = new SAXSource(new InputSource(xml_val_test)); ss.setSystemId(xml_val_test_id); StAXSource stax = getStaxSource(xml_val_test, xml_val_test_id, true, true, xml_catalog); StAXSource stax1 = getStaxSource(xml_val_test, xml_val_test_id, true, true, xml_catalog); StreamSource source = new StreamSource(new File(xml_val_test)); return new Object[][]{ // use catalog {true, false, true, ds, null, null, xml_catalog, null}, {false, true, true, ds, null, null, null, xml_catalog}, {true, false, true, ss, null, null, xml_catalog, null}, {false, true, true, ss, null, null, null, xml_catalog}, {true, false, true, stax, null, null, xml_catalog, xml_catalog}, {false, true, true, stax1, null, null, xml_catalog, xml_catalog}, {true, false, true, source, null, null, xml_catalog, null}, {false, true, true, source, null, null, null, xml_catalog}, }; }
/** * Tries to convert the given XML file into an HTML file using the given XSLT stylesheet. If * this fails (probably because the given XML file doesn't exist), * {@link #createOfflineFallbackDocumentation(Operator)} will be used to generate a String from * the old local operator description resources. * * @param xmlStream * @param operator * @return * @throws MalformedURLException * @throws IOException */ public static String convert(InputStream xmlStream, Operator operator) throws MalformedURLException, IOException { if (operator == null) { throw new IllegalArgumentException("operator must not be null!"); } if (xmlStream == null) { LogService.getRoot().finer("Failed to load documentation, using online fallback. Reason: xmlStream is null."); return createFallbackDocumentation(operator); } Source xmlSource = new StreamSource(xmlStream); try { return applyXSLTTransformation(xmlSource); } catch (TransformerException e) { LogService.getRoot().log(Level.WARNING, "Failed to load documentation, using online fallback.", e); return createFallbackDocumentation(operator); } }
/** * Returns a Source for reading the XML value designated by this SQLXML * instance. <p> * * @param sourceClass The class of the source, or null. If null, then a * DOMSource is returned. * @return a Source for reading the XML value. * @throws SQLException if there is an error processing the XML value * or if the given <tt>sourceClass</tt> is not supported. */ protected <T extends Source>T getSourceImpl( Class<T> sourceClass) throws SQLException { if (JAXBSource.class.isAssignableFrom(sourceClass)) { // Must go first presently, since JAXBSource extends SAXSource // (purely as an implmentation detail) and it's not possible // to instantiate a valid JAXBSource with a Zero-Args // constructor(or any subclass thereof, due to the finality of // its private marshaller and context object attrbutes) // FALL THROUGH... will throw an exception } else if (StreamSource.class.isAssignableFrom(sourceClass)) { return createStreamSource(sourceClass); } else if ((sourceClass == null) || DOMSource.class.isAssignableFrom(sourceClass)) { return createDOMSource(sourceClass); } else if (SAXSource.class.isAssignableFrom(sourceClass)) { return createSAXSource(sourceClass); } else if (StAXSource.class.isAssignableFrom(sourceClass)) { return createStAXSource(sourceClass); } throw Util.invalidArgument("sourceClass: " + sourceClass); }
/** * 利用xsd验证xml * @param xsdFile xsdFile * @param xmlInput xmlInput * @throws SAXException SAXException * @throws IOException IOException */ public static void validation(String xsdFile, InputStream xmlInput) throws SAXException, IOException { SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); URL xsdURL = Validation.class.getClassLoader().getResource(xsdFile); if(xsdURL != null) { Schema schema = factory.newSchema(xsdURL); Validator validator = schema.newValidator(); // validator.setErrorHandler(new AutoErrorHandler()); Source source = new StreamSource(xmlInput); try(OutputStream resultOut = new FileOutputStream(new File(PathUtil.getRootDir(), xsdFile + ".xml"))) { Result result = new StreamResult(resultOut); validator.validate(source, result); } } else { throw new FileNotFoundException(String.format("can not found xsd file [%s] from classpath.", xsdFile)); } }
/** * Strips namespace information form the given node, to ease further processing. * I took the XSLT transformation from <a href= * "http://clardeur.blogspot.de/2012/11/remove-all-namespaces-from-xml-using.html">here</a>. * * @param node * The node. * @return A transformed node without namespace info. */ public static Node removeNamespaces(Node node) { Objects.requireNonNull(node, "node must not be null"); TransformerFactory transformerFactory = TransformerFactory.newInstance(); InputStream xslt = XmlUtils.class.getResourceAsStream(REMOVE_NAMESPACE_XSLT); if (xslt == null) { throw new IllegalStateException("Could not load " + REMOVE_NAMESPACE_XSLT + " -- InputStream == null"); } DOMResult result = new DOMResult(); try { Transformer transformer = transformerFactory.newTransformer(new StreamSource(xslt)); transformer.transform(new DOMSource(node), result); } catch (TransformerException e) { throw new IllegalStateException(e); } return result.getNode(); }
@Test public final void testTransform() { try { StreamSource input = new StreamSource(getClass().getResourceAsStream("PredicateInKeyTest.xml")); StreamSource stylesheet = new StreamSource(getClass().getResourceAsStream("PredicateInKeyTest.xsl")); CharArrayWriter buffer = new CharArrayWriter(); StreamResult output = new StreamResult(buffer); TransformerFactory.newInstance().newTransformer(stylesheet).transform(input, output); Assert.assertEquals(buffer.toString(), "0|1|2|3", "XSLT xsl:key implementation is broken!"); // expected success } catch (Exception e) { // unexpected failure e.printStackTrace(); Assert.fail(e.toString()); } }
private XMLReader createReader() throws SAXException { try { SAXParserFactory pfactory = SAXParserFactory.newInstance(); pfactory.setValidating(true); pfactory.setNamespaceAware(true); // Enable schema validation SchemaFactory sfactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema"); InputStream stream = Parser.class.getResourceAsStream("graphdocument.xsd"); pfactory.setSchema(sfactory.newSchema(new Source[]{new StreamSource(stream)})); return pfactory.newSAXParser().getXMLReader(); } catch (ParserConfigurationException ex) { throw new SAXException(ex); } }
@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()); } }
private Source[] getSchemaSources() throws Exception { List<Source> list = new ArrayList<Source>(); String file = getClass().getResource("hello_literal.wsdl").getFile(); Source source = new StreamSource(new FileInputStream(file), file); Transformer trans = TransformerFactory.newInstance().newTransformer(); DOMResult result = new DOMResult(); trans.transform(source, result); // Look for <xsd:schema> element in wsdl Element e = ((Document) result.getNode()).getDocumentElement(); NodeList typesList = e.getElementsByTagNameNS("http://schemas.xmlsoap.org/wsdl/", "types"); NodeList schemaList = ((Element) typesList.item(0)).getElementsByTagNameNS("http://www.w3.org/2001/XMLSchema", "schema"); Element elem = (Element) schemaList.item(0); list.add(new DOMSource(elem, file + "#schema0")); // trans.transform(new DOMSource(elem), new StreamResult(System.out)); return list.toArray(new Source[list.size()]); }
@Override public T fromXML(String xml) { try { JAXBContext context = JAXBContext.newInstance(type); Unmarshaller u = context.createUnmarshaller(); if(schemaLocation != null) { SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); StreamSource source = new StreamSource(getClass().getResourceAsStream(schemaLocation)); Schema schema = schemaFactory.newSchema(source); u.setSchema(schema); } StringReader reader = new StringReader(xml); T obj = (T) u.unmarshal(reader); return obj; } catch (Exception e) { System.out.println("ERROR: "+e.toString()); return null; } }
public static String formatXml(String xml) { String formatted = null; if (xml == null || xml.trim().length() == 0) { return formatted; } 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", String.valueOf(XML_INDENT)); transformer.transform(xmlInput, xmlOutput); formatted = xmlOutput.getWriter().toString().replaceFirst(">", ">" + XPrinter.lineSeparator); } catch (Exception e) { e.printStackTrace(); } return formatted; }
protected Source processSource(Source source) { if (source instanceof StreamSource) { StreamSource streamSource = (StreamSource) source; InputSource inputSource = new InputSource(streamSource.getInputStream()); try { XMLReader xmlReader = XMLReaderFactory.createXMLReader(); String featureName = "http://xml.org/sax/features/external-general-entities"; xmlReader.setFeature(featureName, isProcessExternalEntities()); if (!isProcessExternalEntities()) { xmlReader.setEntityResolver(NO_OP_ENTITY_RESOLVER); } return new SAXSource(xmlReader, inputSource); } catch (SAXException ex) { logger.warn("Processing of external entities could not be disabled", ex); return source; } } else { return source; } }
/** * Oveloaded CustomComponent's render */ public final void render(final RenderContext ctx) { StreamSource xslSource = null; StreamSource xmlSource = null; try { xslSource = xslSource(); xmlSource = xmlSource(); final Transformer transformer = TransformerFactory.newInstance().newTransformer(xslSource); final PrintWriter pw = ctx.getWriter(); transformer.transform(xmlSource, new StreamResult(pw)); } catch (Exception e) { showUnexpectedErrorMsg(ctx, e); } finally { closeHard(xslSource); closeHard(xmlSource); } }
/** * 默认转换将指定的xml转化为 * 方法描述 * @param inputStream * @param fileName * @return * @throws JAXBException * @throws XMLStreamException * @创建日期 2016年9月16日 */ public Object baseParseXmlToBean(String fileName) throws JAXBException, XMLStreamException { // 搜索当前转化的文件 InputStream inputStream = XmlProcessBase.class.getResourceAsStream(fileName); // 如果能够搜索到文件 if (inputStream != null) { // 进行文件反序列化信息 XMLInputFactory xif = XMLInputFactory.newFactory(); xif.setProperty(XMLInputFactory.SUPPORT_DTD, false); XMLStreamReader xmlRead = xif.createXMLStreamReader(new StreamSource(inputStream)); return unmarshaller.unmarshal(xmlRead); } return null; }
public Object unmarshal( Source source ) throws JAXBException { if( source == null ) { throw new IllegalArgumentException( Messages.format( Messages.MUST_NOT_BE_NULL, "source" ) ); } if(source instanceof SAXSource) return unmarshal( (SAXSource)source ); if(source instanceof StreamSource) return unmarshal( streamSourceToInputSource((StreamSource)source)); if(source instanceof DOMSource) return unmarshal( ((DOMSource)source).getNode() ); // we don't handle other types of Source throw new IllegalArgumentException(); }
/** * 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; }
/** * print the documentation for the specified type converter. * @param name * @throws UnsupportedServiceException * @throws ServiceInstanciationException * @throws AmbiguousAliasException * @throws TransformerException */ @CLIOption(value="-converterDoc", stop=true) public final void converterDoc(String name) throws UnsupportedServiceException, AmbiguousAliasException, TransformerException { ParamConverter converter = converterFactory.getServiceByAlias(name); Document doc = converter.getDocumentation().getDocument(); // same ClassLoader as this class Source xslt = new StreamSource(getClass().getResourceAsStream(noColors ? "alvisnlp-doc2txt.xslt" : "alvisnlp-doc2ansi.xslt")); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(xslt); transformer.setParameter("name", bundle.getString(DocResourceConstants.MODULE_NAME)); transformer.setParameter("synopsis", bundle.getString(DocResourceConstants.SYNOPSIS)); transformer.setParameter("string-conversion", bundle.getString(DocResourceConstants.STRING_CONVERSION)); transformer.setParameter("xml-conversion", bundle.getString(DocResourceConstants.XML_CONVERSION)); Source source = new DOMSource(doc); Result result = new StreamResult(System.out); transformer.transform(source, result); }
/** * Unit test for transform(StreamSource, StreamResult). * * @throws Exception If any errors occur. */ @Test public void testcase01() throws Exception { String outputFile = USER_DIR + "transformer02.out"; String goldFile = GOLDEN_DIR + "transformer02GF.out"; String xsltFile = XML_DIR + "cities.xsl"; String xmlFile = XML_DIR + "cities.xml"; try (FileInputStream fis = new FileInputStream(xmlFile); FileOutputStream fos = new FileOutputStream(outputFile)) { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DOMSource domSource = new DOMSource(dbf.newDocumentBuilder(). parse(new File(xsltFile))); Transformer transformer = TransformerFactory.newInstance(). newTransformer(domSource); StreamSource streamSource = new StreamSource(fis); StreamResult streamResult = new StreamResult(fos); transformer.setOutputProperty("indent", "no"); transformer.transform(streamSource, streamResult); } assertTrue(compareWithGold(goldFile, outputFile)); }
public static @NotNull Optional<Schema> load(@NotNull JAXBContext context) { try { final List<ByteArrayOutputStream> outputs = new ArrayList<>(); context.generateSchema(new SchemaOutputResolver() { @Override public @NotNull Result createOutput(@NotNull String namespace, @NotNull String suggestedFileName) { final ByteArrayOutputStream output = new ByteArrayOutputStream(); outputs.add(output); final StreamResult result = new StreamResult(output); result.setSystemId(""); return result; } }); return Optional.ofNullable( SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI) .newSchema(outputs.stream() .map(ByteArrayOutputStream::toByteArray) .map(ByteArrayInputStream::new) .map(input -> new StreamSource(input, "")) .toArray(StreamSource[]::new)) ); } catch (IOException | SAXException e) { logger.error("Failed to load schema", e); return Optional.empty(); } }
public void testValidation(boolean setUseCatalog, boolean useCatalog, String catalog, String xsd, LSResourceResolver resolver) throws Exception { SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); // use resolver or catalog if resolver = null if (resolver != null) { factory.setResourceResolver(resolver); } if (setUseCatalog) { factory.setFeature(XMLConstants.USE_CATALOG, useCatalog); } factory.setProperty(CatalogFeatures.Feature.FILES.getPropertyName(), catalog); Schema schema = factory.newSchema(new StreamSource(new StringReader(xsd))); success("XMLSchema.dtd and datatypes.dtd are resolved."); }
/** * Create an object from the input stream */ public Object getContent(DataSource ds) throws IOException { String ctStr = ds.getContentType(); String charset = null; if (ctStr != null) { ContentType ct = new ContentType(ctStr); if (!isXml(ct)) { throw new IOException( "Cannot convert DataSource with content type \"" + ctStr + "\" to object in XmlDataContentHandler"); } charset = ct.getParameter("charset"); } return (charset != null) ? new StreamSource(new InputStreamReader(ds.getInputStream()), charset) : new StreamSource(ds.getInputStream()); }
private void closeSource(final StreamSource source) { if( source != null ) { try { // one of these should be non-null Closeables.close(source.getReader(), true); Closeables.close(source.getInputStream(), true); } catch( Throwable th ) { // Ignore } } }
/** * Validates XML against XSD schema * * @param xml XML in which the element is being searched * @param schemas XSD schemas against which the XML is validated * @throws SAXException if the XSD schema is invalid * @throws IOException if the XML at the specified path is missing */ public static void validateWithXMLSchema(InputStream xml, InputStream[] schemas) throws IOException, SAXException { SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Source[] sources = new Source[schemas.length]; for (int i = 0; i < schemas.length; i++) { sources[i] = new StreamSource(schemas[i]); } Schema schema = factory.newSchema(sources); Validator validator = schema.newValidator(); try { validator.validate(new StreamSource(xml)); } catch (SAXException e) { throw new GeneralException(e); } }
private ValidatorHandler createValidatorHandler(String xsd) throws SAXException { SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema"); StringReader reader = new StringReader(xsd); StreamSource xsdSource = new StreamSource(reader); Schema schema = schemaFactory.newSchema(xsdSource); return schema.newValidatorHandler(); }
@DataProvider(name = "data_ValidatorC") public Object[][] getDataValidator() { DOMSource ds = getDOMSource(xml_val_test, xml_val_test_id, false, true, xml_catalog); SAXSource ss = new SAXSource(new InputSource(xml_val_test)); ss.setSystemId(xml_val_test_id); StAXSource stax = getStaxSource(xml_val_test, xml_val_test_id, false, true, xml_catalog); StAXSource stax1 = getStaxSource(xml_val_test, xml_val_test_id, false, true, xml_catalog); StreamSource source = new StreamSource(new File(xml_val_test)); return new Object[][]{ // use catalog disabled through factory {true, false, false, ds, null, null, xml_catalog, null}, {true, false, false, ds, null, null, null, xml_catalog}, {true, false, false, ss, null, null, xml_catalog, null}, {true, false, false, ss, null, null, null, xml_catalog}, {true, false, false, stax, null, null, xml_catalog, null}, {true, false, false, stax1, null, null, null, xml_catalog}, {true, false, false, source, null, null, xml_catalog, null}, {true, false, false, source, null, null, null, xml_catalog}, // use catalog disabled through validatory {false, true, false, ds, null, null, xml_catalog, null}, {false, true, false, ds, null, null, null, xml_catalog}, {false, true, false, ss, null, null, xml_catalog, null}, {false, true, false, ss, null, null, null, xml_catalog}, {false, true, false, stax, null, null, xml_catalog, null}, {false, true, false, stax1, null, null, null, xml_catalog}, {false, true, false, source, null, null, xml_catalog, null}, {false, true, false, source, null, null, null, xml_catalog}, }; }
private boolean isKnownReadableSource(Source wsdlSource) { if (wsdlSource instanceof StreamSource) { return (((StreamSource) wsdlSource).getInputStream() != null || ((StreamSource) wsdlSource).getReader() != null); } else { return false; } }
private static String formatXml(String xml) { 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", "4"); transformer.transform(xmlInput, xmlOutput); xml = xmlOutput.getWriter().toString().replaceFirst(">", ">" + LINE_SEP); } catch (Exception e) { e.printStackTrace(); } return xml; }
@Test public final void testTransform() { File xml = new File(getClass().getResource("CR6941869.xml").getFile()); File xsl = new File(getClass().getResource("CR6941869.xsl").getFile()); try { TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); StreamSource source = new StreamSource(xsl); transformer = tFactory.newTransformer(source); // the xml result StringWriter xmlResultString = new StringWriter(); StreamResult xmlResultStream = new StreamResult(xmlResultString); transformer.transform(new StreamSource(xml), xmlResultStream); System.out.println(xmlResultString.toString()); String temp = xmlResultString.toString(); int pos = temp.lastIndexOf("count"); if (temp.substring(pos + 8, pos + 9).equals("1")) { Assert.fail("count=1"); } else if (temp.substring(pos + 8, pos + 9).equals("2")) { // expected success System.out.println("count=2"); } } catch (Exception e) { // unexpected failure e.printStackTrace(); Assert.fail(e.toString()); } }
@Test(dataProvider = "data_XSLA") public void testXSLImportA(boolean setUseCatalog, boolean useCatalog, String catalog, SAXSource xsl, StreamSource xml, URIResolver resolver, String expected) throws Exception { testXSLImport(setUseCatalog, useCatalog, catalog, xsl, xml, resolver, expected); }
@Test public final void testTransform() { try { InputStream xin = this.getClass().getResourceAsStream("CR6577667.xsl"); StreamSource xslt = new StreamSource(xin); TransformerFactory fc = TransformerFactory.newInstance(); Transformer transformer = fc.newTransformer(xslt); } catch (Exception e) { // unexpected failure e.printStackTrace(); Assert.fail(e.toString()); } }
private <T> T deserializeInternal(StreamSource streamSource, Class<T> clazz) throws SerializerException { try { Unmarshaller unmarshaller = context.createUnmarshaller(); unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); return unmarshaller.unmarshal(streamSource, clazz).getValue(); } catch (JAXBException e) { log.error("Can't deserialize object of type {}", clazz.getSimpleName()); throw new SerializerException("Can't deserialize object of type " + clazz.getSimpleName(), e); } }
@Override public String onceOffTransform(final InputStream xslt, final InputStream input) { StreamSource xsltSource = null; StreamSource inputSource = null; Thread currentThread = Thread.currentThread(); ClassLoader oldLoader = currentThread.getContextClassLoader(); currentThread.setContextClassLoader(getClass().getClassLoader()); try { xsltSource = getSource(xslt); final Transformer templates = factory.newTransformer(xsltSource); final StringWriter writer = new StringWriter(); inputSource = getSource(input); templates.transform(inputSource, new StreamResult(writer)); return writer.toString(); } catch( final TransformerException ex ) { throw new RuntimeException("Error compiling XSLT", ex); } finally { closeSource(xsltSource); closeSource(inputSource); currentThread.setContextClassLoader(oldLoader); } }
void doOneTestIteration() throws Exception { // Prepare output stream StringWriter xmlResultString = new StringWriter(); StreamResult xmlResultStream = new StreamResult(xmlResultString); // Prepare xml source stream Source src = new StreamSource(new StringReader(xml)); Transformer t = createTransformer(); //Transform the xml t.transform(src, xmlResultStream); }