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(); } }
/** * 利用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)); } }
/** * Save a single emitter to the XML file * * @param out * The location to which we should save * @param emitter * The emitter to store to the XML file * @throws IOException * Indicates a failure to write or encode the XML */ public static void saveEmitter(OutputStream out, ConfigurableEmitter emitter) throws IOException { try { DocumentBuilder builder = DocumentBuilderFactory.newInstance() .newDocumentBuilder(); Document document = builder.newDocument(); document.appendChild(emitterToElement(document, emitter)); Result result = new StreamResult(new OutputStreamWriter(out, "utf-8")); DOMSource source = new DOMSource(document); TransformerFactory factory = TransformerFactory.newInstance(); Transformer xformer = factory.newTransformer(); xformer.setOutputProperty(OutputKeys.INDENT, "yes"); xformer.transform(source, result); } catch (Exception e) { Log.error(e); throw new IOException("Failed to save emitter"); } }
/** * Write an XML document to a Writer */ public static void writeDocument(Document doc, Writer writer) throws IOException { final Source source = new DOMSource(doc); // Prepare the output file final Result result = new StreamResult(writer); // Write the DOM document to the file try { final Transformer xformer = TransformerFactory.newInstance().newTransformer(); xformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$ xformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); //$NON-NLS-1$ //$NON-NLS-2$ xformer.transform(source, result); } catch (TransformerException e) { // FIXME: switch to IOException(Throwable) ctor in Java 1.6 throw (IOException) new IOException().initCause(e); } }
/** * Renders an input file (XML or XSL-FO) into a PDF file. It uses the JAXP * transformer given to optionally transform the input document to XSL-FO. * The transformer may be an identity transformer in which case the input * must already be XSL-FO. The PDF is written to a byte array that is * returned as the method's result. * @param src Input XML or XSL-FO * @param transformer Transformer to use for optional transformation * @param response HTTP response object * @throws FOPException If an error occurs during the rendering of the * XSL-FO * @throws TransformerException If an error occurs during XSL * transformation * @throws IOException In case of an I/O problem */ public void render(Source src, Transformer transformer, HttpServletResponse response, String realpath) throws FOPException, TransformerException, IOException { FOUserAgent foUserAgent = getFOUserAgent(realpath); //Setup output ByteArrayOutputStream out = new ByteArrayOutputStream(); //Setup FOP fopFactory.setBaseURL(realpath); Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out); //Make sure the XSL transformation's result is piped through to FOP Result res = new SAXResult(fop.getDefaultHandler()); //Start the transformation and rendering process transformer.transform(src, res); //Return the result sendPDF(out.toByteArray(), response); }
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(); } }
/** * CLI option: print the documentation for the specified module. * @param name * @throws TransformerException * @throws XPathExpressionException * @throws UnsupportedServiceException * @throws ServiceInstanciationException * @throws AmbiguousAliasException */ @CLIOption(value="-moduleDoc", stop=true) public final void moduleDoc(String name) throws TransformerException, XPathExpressionException, UnsupportedServiceException, AmbiguousAliasException { Document doc = getModuleDocumentation(name); // 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).toUpperCase(locale)); transformer.setParameter("synopsis", bundle.getString(DocResourceConstants.SYNOPSIS).toUpperCase(locale)); transformer.setParameter("description", bundle.getString(DocResourceConstants.MODULE_DESCRIPTION).toUpperCase(locale)); transformer.setParameter("parameters", bundle.getString(DocResourceConstants.MODULE_PARAMETERS).toUpperCase(locale)); Source source = new DOMSource(doc); Result result = new StreamResult(System.out); transformer.transform(source, result); }
/** * Performs identity transformation. */ public static <T extends Result> T identityTransform(Source src, T result) throws TransformerException, SAXException, ParserConfigurationException, IOException { if (src instanceof StreamSource) { // work around a bug in JAXP in JDK6u4 and earlier where the namespace processing // is not turned on by default StreamSource ssrc = (StreamSource) src; TransformerHandler th = ((SAXTransformerFactory) transformerFactory.get()).newTransformerHandler(); th.setResult(result); XMLReader reader = saxParserFactory.get().newSAXParser().getXMLReader(); reader.setContentHandler(th); reader.setProperty(LEXICAL_HANDLER_PROPERTY, th); reader.parse(toInputSource(ssrc)); } else { newTransformer().transform(src, result); } return result; }
/** * SAXTFactory.newTransformerhandler() method which takes SAXSource as * argument can be set to XMLReader. SAXSource has input XML file as its * input source. XMLReader has a content handler which write out the result * to output file. Test verifies output file is same as golden file. * * @throws Exception If any errors occur. */ @Test public void testcase02() throws Exception { String outputFile = USER_DIR + "saxtf002.out"; String goldFile = GOLDEN_DIR + "saxtf002GF.out"; try (FileOutputStream fos = new FileOutputStream(outputFile); FileInputStream fis = new FileInputStream(XSLT_FILE)) { XMLReader reader = XMLReaderFactory.createXMLReader(); SAXTransformerFactory saxTFactory = (SAXTransformerFactory) TransformerFactory.newInstance(); SAXSource ss = new SAXSource(); ss.setInputSource(new InputSource(fis)); TransformerHandler handler = saxTFactory.newTransformerHandler(ss); Result result = new StreamResult(fos); handler.setResult(result); reader.setContentHandler(handler); reader.parse(XML_FILE); } assertTrue(compareWithGold(goldFile, outputFile)); }
/** * Creates the {@link Result} object used by JAXB to generate a schema for the * namesapceUri namespace. * @param namespaceUri The namespace for the schema being generated * @param suggestedFileName the JAXB suggested file name for the schema file * @return the {@link Result} for JAXB to generate the schema into * @throws java.io.IOException thrown if on IO error occurs */ public Result createOutputFile(String namespaceUri, String suggestedFileName) throws IOException { Result result; if (namespaceUri == null) { return null; } Holder<String> fileNameHolder = new Holder<String>(); fileNameHolder.value = schemaPrefix + suggestedFileName; result = wsdlResolver.getSchemaOutput(namespaceUri, fileNameHolder); // System.out.println("schema file: "+fileNameHolder.value); // System.out.println("result: "+result); String schemaLoc; if (result == null) schemaLoc = fileNameHolder.value; else schemaLoc = relativize(result.getSystemId(), wsdlLocation); boolean isEmptyNs = namespaceUri.trim().equals(""); if (!isEmptyNs) { com.sun.xml.internal.ws.wsdl.writer.document.xsd.Import _import = types.schema()._import(); _import.namespace(namespaceUri); _import.schemaLocation(schemaLoc); } return result; }
public static String xmlToString(Node node) { try { Source source = new DOMSource(node); StringWriter writer = new StringWriter(); Result result = new StreamResult(writer); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.transform(source, result); return writer.toString(); } catch( Exception e ) { throw new RuntimeException(e); } }
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; } }
private void validate(final String xsdFile, final Source src, final Result result) throws Exception { try { SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = sf.newSchema(new File(ValidatorTest.class.getResource(xsdFile).toURI())); // Get a Validator which can be used to validate instance document // against this grammar. Validator validator = schema.newValidator(); ErrorHandler eh = new ErrorHandlerImpl(); validator.setErrorHandler(eh); // Validate this instance document against the // Instance document supplied validator.validate(src, result); } catch (Exception ex) { throw ex; } }
/** * Retrieves a new Result for setting the XML value designated by this * SQLXML instance. * * @param resultClass The class of the result, or null. * @throws java.sql.SQLException if there is an error processing the XML * value or the state is not writable * @return for setting the XML value designated by this SQLXML instance. */ protected <T extends Result>T createResult( Class<T> resultClass) throws SQLException { checkWritable(); setWritable(false); setReadable(true); if (JAXBResult.class.isAssignableFrom(resultClass)) { // Must go first presently, since JAXBResult extends SAXResult // (purely as an implmentation detail) and it's not possible // to instantiate a valid JAXBResult with a Zero-Args // constructor(or any subclass thereof, due to the finality of // its private UnmarshallerHandler) // FALL THROUGH... will throw an exception } else if ((resultClass == null) || StreamResult.class.isAssignableFrom(resultClass)) { return createStreamResult(resultClass); } else if (DOMResult.class.isAssignableFrom(resultClass)) { return createDOMResult(resultClass); } else if (SAXResult.class.isAssignableFrom(resultClass)) { return createSAXResult(resultClass); } else if (StAXResult.class.isAssignableFrom(resultClass)) { return createStAXResult(resultClass); } throw JDBCUtil.invalidArgument("resultClass: " + resultClass); }
public InputStream upsetTheNorm(String xPath, boolean remove) { try { document = dbf.newDocumentBuilder().parse(new File(pathname)); XPath xpath = xpf.newXPath(); XPathExpression expression = xpath.compile(xPath); NodeList searchedNodes = (NodeList) expression.evaluate(document, XPathConstants.NODESET); if (searchedNodes == null) { System.out.println("bad path: " + xPath); } else { for (int i = 0; i < searchedNodes.getLength(); i++) { Node searched = searchedNodes.item(i); Node owningElement = (searched instanceof ElementImpl) ? searched : ((AttrImpl) searched).getOwnerElement(); Node containingParent = owningElement.getParentNode(); if (remove) { containingParent.removeChild(owningElement); } else { containingParent.appendChild(owningElement.cloneNode(true)); } } } Transformer t = tf.newTransformer(); ByteArrayOutputStream os = new ByteArrayOutputStream(); Result result = new StreamResult(os); t.transform(new DOMSource(document), result); return new ByteArrayInputStream(os.toByteArray()); } catch (ParserConfigurationException | IOException | SAXException | XPathExpressionException | TransformerException ex) { throw new RuntimeException(ex); } }
public static void write(Element el, OutputStream out) throws IOException { try { Transformer t = TransformerFactory.newInstance().newTransformer( new StreamSource(new StringReader(IDENTITY_XSLT_WITH_INDENT))); t.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); // NOI18N t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); Source source = new DOMSource(el); Result result = new StreamResult(out); t.transform(source, result); } catch (Exception | TransformerFactoryConfigurationError e) { throw new IOException(e); } }
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); } }
public void saveXML() { //close file try { Source source = new DOMSource(document); // Prepare the output file File temp = File.createTempFile("~jmt_measure", ".xml", file.getParentFile()); Result result = new StreamResult(temp); // Write the DOM document to the file Transformer xformer = TransformerFactory.newInstance().newTransformer(); xformer.transform(source, result); /* validate the xml stream */ FileReader fr = new FileReader(temp); InputSource in_source = new InputSource(fr); //TODO: il parser va prima creato!! parser.parse(in_source); /* commit */ if (file.exists()) { file.delete(); } temp.renameTo(file); } catch (Exception e) { e.printStackTrace(); System.out.println("error in closing file.."); } }
/** * Retrieves a new Result for setting the XML value designated by this * SQLXML instance. * * @param resultClass The class of the result, or null. * @throws java.sql.SQLException if there is an error processing the XML * value or the state is not writable * @return for setting the XML value designated by this SQLXML instance. */ protected <T extends Result>T createResult( Class<T> resultClass) throws SQLException { checkWritable(); setWritable(false); setReadable(true); if (JAXBResult.class.isAssignableFrom(resultClass)) { // Must go first presently, since JAXBResult extends SAXResult // (purely as an implementation detail) and it's not possible // to instantiate a valid JAXBResult with a Zero-Args // constructor(or any subclass thereof, due to the finality of // its private UnmarshallerHandler) // FALL THROUGH... will throw an exception } else if ((resultClass == null) || StreamResult.class.isAssignableFrom(resultClass)) { return createStreamResult(resultClass); } else if (DOMResult.class.isAssignableFrom(resultClass)) { return createDOMResult(resultClass); } else if (SAXResult.class.isAssignableFrom(resultClass)) { return createSAXResult(resultClass); } else if (StAXResult.class.isAssignableFrom(resultClass)) { return createStAXResult(resultClass); } throw JDBCUtil.invalidArgument("resultClass: " + resultClass); }
@Test public final void testTransform() { try { String inFilename = "CR6935697.xml"; String xslFilename = "CR6935697.xsl"; String outFilename = "CR6935697.out"; // 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(xslFilename))); // Use the template to create a transformer Transformer xformer = template.newTransformer(); // Prepare the input and output files Source source = new StreamSource(getClass().getResourceAsStream(inFilename)); Result result = new StreamResult(new FileOutputStream(USER_DIR + outFilename)); // Apply the xsl file to the source file and write the result to the // output file xformer.transform(source, result); } catch (Exception e) { // unexpected failure e.printStackTrace(); Assert.fail(e.toString()); } }
public void generateSimpleReport(Document dom, OutputStream os) throws Exception { Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, os); Result res = new SAXResult(fop.getDefaultHandler()); Transformer transformer = templateSimpleReport.newTransformer(); transformer.setErrorListener(new DSSXmlErrorListener()); transformer.transform(new DOMSource(dom), res); }
public void generateDetailedReport(String detailedReport, OutputStream os) throws Exception { Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, os); Result res = new SAXResult(fop.getDefaultHandler()); Transformer transformer = templateDetailedReport.newTransformer(); transformer.setErrorListener(new DSSXmlErrorListener()); transformer.transform(new StreamSource(new StringReader(detailedReport)), res); }
/** * @see SerializationHandler#setEscaping(boolean) */ public boolean setEscaping(boolean escape) throws SAXException { boolean oldEscapeSetting = m_escapeSetting; m_escapeSetting = escape; if (escape) { processingInstruction(Result.PI_ENABLE_OUTPUT_ESCAPING, ""); } else { processingInstruction(Result.PI_DISABLE_OUTPUT_ESCAPING, ""); } return oldEscapeSetting; }
/** * {@inheritDoc} */ public void writeTo(Result result){ try { Marshaller marshaller = w3cjc.createMarshaller(); marshaller.marshal(this, result); } catch (JAXBException e) { throw new WebServiceException("Error marshalling W3CEndpointReference. ", e); } }
private Result buildPipeline(Result result) { if (this.transformers.isEmpty()) { return buildSingleTransformerPipeline(result); } else { return buildChainedTransformersPipeline(result); } }
private Result buildChainedTransformersPipeline(Result result) { TransformerAdapter prevTransformer = null; TransformerAdapter firstTransformer = null; for (TransformerAdapter currTransformer : transformers) { if (firstTransformer == null) { firstTransformer = currTransformer; } if (prevTransformer != null) { prevTransformer.setNext(currTransformer.asResult()); } prevTransformer = currTransformer; } if (prevTransformer == null) { throw new IllegalStateException("Internal problem: No previous transformer."); } if (result != null) { prevTransformer.setNext(result); } return firstTransformer.asResult(); }
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"); } }
/** * Turns special character escaping on/off. * * * @param escape true if escaping is to be set on. * * @see SerializationHandler#setEscaping(boolean) */ public boolean setEscaping(boolean escape) throws SAXException { boolean oldEscapeSetting = m_escapeSetting; m_escapeSetting = escape; if (escape) { processingInstruction(Result.PI_ENABLE_OUTPUT_ESCAPING, ""); } else { processingInstruction(Result.PI_DISABLE_OUTPUT_ESCAPING, ""); } return oldEscapeSetting; }
/** * Factory method for producing {@link XmlSerializer) from {@link javax.xml.transform.Result}. * * This method supports {@link javax.xml.transform.sax.SAXResult}, * {@link javax.xml.transform.stream.StreamResult}, and {@link javax.xml.transform.dom.DOMResult}. * * @param result the Result that will receive output from the XmlSerializer * @return an implementation of XmlSerializer that will produce output on the supplied Result */ public static XmlSerializer createSerializer(Result result) { if (result instanceof SAXResult) return new SaxSerializer((SAXResult) result); if (result instanceof DOMResult) return new DomSerializer((DOMResult) result); if (result instanceof StreamResult) return new StreamSerializer((StreamResult) result); if (result instanceof TXWResult) return new TXWSerializer(((TXWResult)result).getWriter()); throw new UnsupportedOperationException("Unsupported Result type: " + result.getClass().getName()); }
public Result resolve(String href, String base) throws TransformerException { try { this.base = new URI(base); this.path = new URI(href); } catch (URISyntaxException exception) { throw new TransformerException(exception); } return new StreamResult(new StringWriter()); }
@CLIOption(value="-supportedModulesXML", stop=true) public final void supportedModulesXML() throws TransformerException { Document doc = XMLUtils.docBuilder.newDocument(); Element root = XMLUtils.createRootElement(doc, "alvisnlp-supported-modules"); for (Class<? extends Module<A>> mod : moduleFactory.supportedServices()) { Element item = XMLUtils.createElement(doc, root, 1, "module-item"); item.setAttribute("target", mod.getCanonicalName()); item.setAttribute("short-target", mod.getSimpleName()); } Source source = new DOMSource(doc); Result result = new StreamResult(System.out); xmlDocTransformer.transform(source, result); }
@CLIOption(value="-supportedLibrariesXML", stop=true) public final void supportedLibrariesXML() throws TransformerException { Document doc = XMLUtils.docBuilder.newDocument(); Element root = XMLUtils.createRootElement(doc, "alvisnlp-supported-libraries"); Class<FunctionLibrary> klass = FunctionLibrary.class; for (FunctionLibrary lib : ServiceLoader.load(klass, klass.getClassLoader())) { Element item = XMLUtils.createElement(doc, root, 1, "library-item"); item.setAttribute("target", lib.getName()); item.setAttribute("short-target", lib.getName()); } Source source = new DOMSource(doc); Result result = new StreamResult(System.out); xmlDocTransformer.transform(source, result); }
/** * Generates the concrete WSDL that contains service element. * * @return Result the generated concrete WSDL */ public Result getWSDL(String filename) { URL url = createURL(filename); MutableXMLStreamBuffer xsb = new MutableXMLStreamBuffer(); xsb.setSystemId(url.toExternalForm()); concreteWsdlSource = SDDocumentSource.create(url,xsb); newDocs.add(concreteWsdlSource); XMLStreamBufferResult r = new XMLStreamBufferResult(xsb); r.setSystemId(filename); return r; }
@Override public void process(ProcessingContext<Corpus> ctx, Corpus corpus) throws ModuleException { try { Logger logger = getLogger(ctx); TransformerFactory factory = TransformerFactory.newInstance(); InputStream is = xslTransform.getInputStream(); Source transformerSource = new StreamSource(is); Transformer transformer = factory.newTransformer(transformerSource); is.close(); transformer.setErrorListener(new ListingErrorHandler()); libraryResolver = getLibraryResolver(ctx); Evaluator roots = libraryResolver.resolveNullable(this.roots); Evaluator fileName = this.fileName.resolveExpressions(libraryResolver); EvaluationContext evalCtx = new EvaluationContext(logger); for (Element root : Iterators.loop(getRoots(roots, evalCtx, corpus))) { transformer.reset(); Document doc = XMLUtils.docBuilder.newDocument(); doc.setUserData(ELEMENT_USER_DATA, root, null); // org.w3c.dom.Element elt = getElementProxy(doc, root); // doc.appendChild(elt); Source source = new DOMSource(doc); String fileNameString = fileName.evaluateString(evalCtx, root); // System.out.println("creating file: " + fileNameString); File outFile = new File(outDir, fileNameString); Result result = new StreamResult(outFile); transformer.transform(source, result); } } catch (DOMException | TransformerException | IOException e) { rethrow(e); } }
@Override public void process(ProcessingContext<Corpus> ctx, Corpus corpus) throws ModuleException { try { Logger logger = getLogger(ctx); EVALUATION_CONTEXT = new EvaluationContext(logger); Transformer transformer = getTransformer(ctx); XMLWriterResolvedObjects resObj = getResolvedObjects(); EvaluationContext evalCtx = new EvaluationContext(logger); outDir.mkdirs(); for (Element root : Iterators.loop(getRoots(evalCtx, corpus))) { transformer.reset(); Document doc = XMLUtils.docBuilder.newDocument(); doc.setUserData(ELEMENT_USER_DATA, root, null); // org.w3c.dom.Element elt = getElementProxy(doc, root); // doc.appendChild(elt); Source source = new DOMSource(doc); String fileNameString = resObj.fileName.evaluateString(evalCtx, root); File outFile = new File(outDir, fileNameString); Result result = new StreamResult(outFile); doTransform(ctx, transformer, source, result); } } catch (DOMException|TransformerException|IOException e) { rethrow(e); } }
protected Schema create(String tns) { try { Result res = xsdResolver.createOutput(tns, FilePrefix + (fileIndex++) + ".xsd"); return TXW.create(Schema.class, ResultFactory.createSerializer(res)); } catch (IOException e) { // TODO Auto-generated catch block throw new WebServiceException(e); } }
@Override public SqlXmlValue newSqlXmlValue(final Class<? extends Result> resultClass, final XmlResultProvider provider) { return new AbstractJdbc4SqlXmlValue() { @Override protected void provideXml(SQLXML xmlObject) throws SQLException, IOException { provider.provideXml(xmlObject.setResult(resultClass)); } }; }
@Override protected void writeInternal(T t, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { try { Result result = new StreamResult(outputMessage.getBody()); transform(t, result); } catch (TransformerException ex) { throw new HttpMessageNotWritableException("Could not transform [" + t + "] to output message", ex); } }
/** * Factory method for producing {@link XmlSerializer} from {@link javax.xml.transform.Result}. * * This method supports {@link javax.xml.transform.sax.SAXResult}, * {@link javax.xml.transform.stream.StreamResult}, and {@link javax.xml.transform.dom.DOMResult}. * * @param result the Result that will receive output from the XmlSerializer * @return an implementation of XmlSerializer that will produce output on the supplied Result */ public static XmlSerializer createSerializer(Result result) { if (result instanceof SAXResult) return new SaxSerializer((SAXResult) result); if (result instanceof DOMResult) return new DomSerializer((DOMResult) result); if (result instanceof StreamResult) return new StreamSerializer((StreamResult) result); if (result instanceof TXWResult) return new TXWSerializer(((TXWResult)result).getWriter()); throw new UnsupportedOperationException("Unsupported Result type: " + result.getClass().getName()); }