public static void writeXmlFile(Document doc, File saveFile, boolean systemOut) { try { Source source = new DOMSource(doc); Transformer xformer = TransformerFactory.newInstance().newTransformer(); xformer.setParameter(OutputKeys.INDENT, "yes"); xformer.setOutputProperty(OutputKeys.INDENT, "yes"); xformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); if (saveFile != null) { Result result = new StreamResult(saveFile); xformer.transform(source, result); } Writer outputWriter = new StringWriter(); Result stringOut = new StreamResult(outputWriter); xformer.transform(source, stringOut); // new SinglePanelPopup(new TextAreaPane(outputWriter.toString())); if (systemOut) { Result system = new StreamResult(System.out); xformer.transform(source, system); } } catch (TransformerConfigurationException e) { } catch (TransformerException e) { } }
/** * Parses an XML file on disk into a Writer * * @param fromPath the file to use as the source * @param toWriter the destination Writer * @throws javax.xml.transform.TransformerException * @throws java.io.IOException */ public static void transform(File fromPath, Writer toWriter) throws TransformerException, IOException { Reader reader = bomCheck(fromPath); TransformerFactory.newInstance() .newTransformer() .transform(new StreamSource(reader), new StreamResult(toWriter)); }
private InputStream getInputStream(Source source) throws Exception { Transformer trans = TransformerFactory.newInstance().newTransformer(); ByteArrayBuffer bab = new ByteArrayBuffer(); StreamResult result = new StreamResult(bab); trans.transform(source, result); return bab.newInputStream(); }
public void configure(final JSONObject config) throws PluginBuildException { if (null == config) { throw new PluginBuildException("Cannot build plugin with null configuration"); } String xsltUrl = config.getString("stylesheet_url"); InputStream content; try { URLConnection connection = new URL(xsltUrl).openConnection(); connection.connect(); content = (InputStream) connection.getContent(); } catch (IOException e) { log.fatal(e); String msg = "Unable to read stylesheet"; notifier.notify(NotificationType.Unavailable, msg + ": " + e.getMessage()); throw new PluginBuildException(msg + ".", e); } StreamSource xsltSource = new StreamSource(content); TransformerFactory factory = TransformerFactory.newInstance(); factory.setErrorListener(xsltErrorLogger); Transformer temp; try { temp = factory.newTransformer(xsltSource); } catch (TransformerConfigurationException e) { log.fatal(e); String msg = "Cannot compile configured stylesheet"; notifier.notify(NotificationType.FatalError, msg + ":" + e.getMessage()); throw new PluginBuildException(msg, e); } transformer = temp; transformer.setErrorListener(xsltErrorLogger); registerInput("input", input); }
/** * Write the XML document to the file trace.xml from * http://java.developpez.com/faq/xml/?page=xslt#creerXmlDom */ public boolean close() { boolean status = true; try { // Create the DOM source Source source = new DOMSource(m_document); // Create the output file File file = new File(m_fileName); Result resultat = new StreamResult(m_fileName); // Create the transformer TransformerFactory fabrique = TransformerFactory.newInstance(); Transformer transformer = fabrique.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1"); // Transformation transformer.transform(source, resultat); } catch (Exception e) { System.out.println("Error creating the file trace.xml"); status = false; e.printStackTrace(); } return status; }
public static String format(String xmlStr) { // Instantiate transformer input Source xmlInput = new StreamSource(new StringReader(xmlStr)); StreamResult xmlOutput = new StreamResult(new StringWriter()); // Configure transformer Transformer transformer; try { transformer = TransformerFactory.newInstance().newTransformer(); } catch (TransformerConfigurationException e) { logger.error(e.getMessage(), e); return xmlStr; } catch (TransformerFactoryConfigurationError e) { // TODO Auto-generated catch block logger.error(e.getMessage(), e); return xmlStr; } // An identity transformer try { transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); transformer.transform(xmlInput, xmlOutput); } catch (TransformerException e) { logger.error(e.getMessage(), e); return xmlStr; } return xmlOutput.getWriter().toString(); }
private void soapMessage(String path, String wsName, String wsPortName) { try { URL wsdlURL = new URL(APP_SERVER + path); final String NS = AbstractServiceImpl.WS_TARGET_NAMESPACE; Service service = Service.create(wsdlURL, new QName(NS, wsName)); Dispatch<Source> dispatcher = service.createDispatch(new QName(NS, wsPortName), Source.class, Service.Mode.PAYLOAD); Source request = new StreamSource(new StringReader("<hello/>")); Source response = dispatcher.invoke(request); assertNotNull(response); Transformer transformer = TransformerFactory.newInstance().newTransformer(); final StringWriter writer = new StringWriter(); Result output = new StreamResult(writer); transformer.transform(response, output); Message message = new Message("clientMessages"); message.dumpFormattedMessage( EchoServiceClient.class, Message.LevelEnum.INFO, "receivedAnswer", writer.toString()); } catch (MalformedURLException e) { e.printStackTrace(); fail(String.valueOf(e)); } catch (TransformerConfigurationException e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } }
@Override public Transformer newTransformer(Source source, ByteArrayOutputStream errors) throws TransformerConfigurationException { TransformerFactory transformerFactory = TransformerFactory.newInstance(TRANSFORMER_FACTORY_CLASS_NAME, saxon6ClassLoader); try { ErrorListener errorListener = transformerFactory.getErrorListener(); Class StandardErrorListenerClass = saxon6ClassLoader.loadClass(STANDARD_ERROR_LISTENER_CLASS_NAME); StandardErrorListenerClass.getMethod(SET_ERROR_OUTPUT_METHOD, PrintStream.class) .invoke(errorListener, new PrintStream(errors)); return transformerFactory.newTransformer(source); } catch (ClassNotFoundException e) { throw new TransformerConfigurationException(TRANSFORMER_FACTORY_CLASS_NAME + " not found"); } catch (NoSuchMethodException e) { throw new TransformerConfigurationException( TRANSFORMER_FACTORY_CLASS_NAME + ": no such method for error listener"); } catch (IllegalAccessException e) { throw new TransformerConfigurationException( TRANSFORMER_FACTORY_CLASS_NAME + " not accessible"); } catch (InvocationTargetException e) { throw new TransformerConfigurationException( TRANSFORMER_FACTORY_CLASS_NAME + ": could invoke method for error listener"); } }
/** * Transforms the given XML string using the XSL string. * * @param xmlString The String containg the XML to transform * @param xslString The XML Stylesheet String containing the transform instructions * @return String representation of the transformation */ public static String transform(String xmlString, String xslString) { String shortString = new String(xmlString); if (shortString.length() > 100) shortString = shortString.substring(0, 100) + "..."; try { TransformerFactory tFactory = TransformerFactory.newInstance(); logger.logComment("Transforming string: " + shortString); StreamSource xslFileSource = new StreamSource(new StringReader(xslString)); Transformer transformer = tFactory.newTransformer(xslFileSource); StringWriter writer = new StringWriter(); transformer.transform( new StreamSource(new StringReader(xmlString)), new StreamResult(writer)); String shortResult = writer.toString(); if (shortResult.length() > 100) shortResult = shortResult.substring(0, 100) + "..."; logger.logComment("Result: " + shortResult); return writer.toString(); } catch (TransformerException e) { GuiUtils.showErrorMessage(logger, "Error when transforming the XML: " + shortString, e, null); return null; } }
public void saveToXml(String fileName) throws ParserConfigurationException, FileNotFoundException, TransformerException, TransformerConfigurationException { System.out.println("Saving network topology to file " + fileName); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); Document doc = parser.newDocument(); Element root = doc.createElement("neuralNetwork"); root.setAttribute("dateOfExport", new Date().toString()); Element layers = doc.createElement("structure"); layers.setAttribute("numberOfLayers", Integer.toString(this.numberOfLayers())); for (int il = 0; il < this.numberOfLayers(); il++) { Element layer = doc.createElement("layer"); layer.setAttribute("index", Integer.toString(il)); layer.setAttribute("numberOfNeurons", Integer.toString(this.getLayer(il).numberOfNeurons())); for (int in = 0; in < this.getLayer(il).numberOfNeurons(); in++) { Element neuron = doc.createElement("neuron"); neuron.setAttribute("index", Integer.toString(in)); neuron.setAttribute( "NumberOfInputs", Integer.toString(this.getLayer(il).getNeuron(in).numberOfInputs())); neuron.setAttribute( "threshold", Double.toString(this.getLayer(il).getNeuron(in).threshold)); for (int ii = 0; ii < this.getLayer(il).getNeuron(in).numberOfInputs(); ii++) { Element input = doc.createElement("input"); input.setAttribute("index", Integer.toString(ii)); input.setAttribute( "weight", Double.toString(this.getLayer(il).getNeuron(in).getInput(ii).weight)); neuron.appendChild(input); } layer.appendChild(neuron); } layers.appendChild(layer); } root.appendChild(layers); doc.appendChild(root); // save File xmlOutputFile = new File(fileName); FileOutputStream fos; Transformer transformer; fos = new FileOutputStream(xmlOutputFile); // Use a Transformer for output TransformerFactory transformerFactory = TransformerFactory.newInstance(); transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(fos); // transform source into result will do save transformer.setOutputProperty("encoding", "iso-8859-2"); transformer.setOutputProperty("indent", "yes"); transformer.transform(source, result); }
/** * Transforms the given XML file using the specified XSL file. * * @param origXmlFile The file containg the XML to transform * @param xslString The XML Stylesheet conntaining the transform instructions * @return String representation of the transformation */ public static String transform(File origXmlFile, String xslString) { if (!origXmlFile.exists()) { GuiUtils.showErrorMessage( logger, "Warning, XML file: " + origXmlFile + " doesn't exist", null, null); return null; } try { TransformerFactory tFactory = TransformerFactory.newInstance(); StreamSource xslFileSource = new StreamSource(new StringReader(xslString)); Transformer transformer = tFactory.newTransformer(xslFileSource); StringWriter writer = new StringWriter(); transformer.transform(new StreamSource(origXmlFile), new StreamResult(writer)); return writer.toString(); } catch (Exception e) { GuiUtils.showErrorMessage(logger, "Error when loading the XML file: " + origXmlFile, e, null); return null; } }
@Override public ContentHandler getSAXHandler() throws IOException, ServletException { this.handlerUsed = true; // Set the content-type for the output assignContentType(this.getTransformCtx()); TransformerHandler tHandler; try { SAXTransformerFactory saxTFact = (SAXTransformerFactory) TransformerFactory.newInstance(); tHandler = saxTFact.newTransformerHandler(this.getCompiled()); } catch (TransformerConfigurationException ex) { throw new ServletException(ex); } // Populate any params which might have been set if (this.getTransformCtx().getTransformParams() != null) populateParams(tHandler.getTransformer(), this.getTransformCtx().getTransformParams()); if (this.getNext().isLast()) tHandler.setResult(new StreamResult(this.getNext().getResponse().getOutputStream())); else tHandler.setResult(new SAXResult(this.getNext().getSAXHandler())); return tHandler; }
/** * Loads nested schema type definitions from wsdl. * * @throws IOException * @throws WSDLException * @throws TransformerFactoryConfigurationError * @throws TransformerException * @throws TransformerConfigurationException */ private void loadSchemas() throws WSDLException, IOException, TransformerConfigurationException, TransformerException, TransformerFactoryConfigurationError { Definition definition = WSDLFactory.newInstance().newWSDLReader().readWSDL(wsdl.getFile().getAbsolutePath()); Types types = definition.getTypes(); List<?> schemaTypes = types.getExtensibilityElements(); for (Object schemaObject : schemaTypes) { if (schemaObject instanceof SchemaImpl) { SchemaImpl schema = (SchemaImpl) schemaObject; inheritNamespaces(schema, definition); ByteArrayOutputStream bos = new ByteArrayOutputStream(); Source source = new DOMSource(schema.getElement()); Result result = new StreamResult(bos); TransformerFactory.newInstance().newTransformer().transform(source, result); Resource schemaResource = new ByteArrayResource(bos.toByteArray()); schemas.add(schemaResource); if (definition .getTargetNamespace() .equals(schema.getElement().getAttribute("targetNamespace"))) { setXsd(schemaResource); } } else { log.warn("Found unsupported schema type implementation " + schemaObject.getClass()); } } }
static { System.setProperty( "javax.xml.transform.TransformerFactory", "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl"); transformerFactory = TransformerFactory.newInstance(); }
/** Check for required facilities. If not available, an exception will be thrown. */ public TemplatesPool(boolean templateCaching) throws Exception { final TransformerFactory tFactory = TransformerFactory.newInstance(); final String processorClass = tFactory.getClass().getName(); /* * Only report XSLT processor class once. */ if (!reportedProcessors.contains(processorClass)) { logger.info("XSLT transformer factory: " + processorClass); reportedProcessors.add(processorClass); } if (!tFactory.getFeature(SAXSource.FEATURE) || !tFactory.getFeature(SAXResult.FEATURE)) { throw new Exception("Required source types not supported by the transformer factory."); } if (!tFactory.getFeature(SAXResult.FEATURE) || !tFactory.getFeature(StreamResult.FEATURE)) { throw new Exception("Required result types not supported by the transformer factory."); } if (!(tFactory instanceof SAXTransformerFactory)) { throw new Exception( "TransformerFactory not an instance of SAXTransformerFactory: " + tFactory.getClass().getName()); } this.tFactory = ((SAXTransformerFactory) tFactory); this.tFactory.setErrorListener(new StylesheetErrorListener()); this.templateCaching = templateCaching; }
private static Transformer getTransformer() throws TransformerException { if (_transformer == null) { TransformerFactory factory = TransformerFactory.newInstance(); _transformer = factory.newTransformer(); } return _transformer; }
/** * Transforms a DOM Document into a file on disk * * @param fromDocument the Document to use as the source * @param toPath the destination file path represented as a String * @throws java.io.IOException * @throws javax.xml.transform.TransformerException */ public static void transform(Document fromDocument, File toPath) throws TransformerException, IOException { Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); DOMSource source = new DOMSource(fromDocument); StreamResult result = new StreamResult(new BufferedWriter(new FileWriter(toPath))); transformer.transform(source, result); }
private DOMSource toDOMSource(Source source) throws Exception { if (source instanceof DOMSource) { return (DOMSource) source; } Transformer trans = TransformerFactory.newInstance().newTransformer(); DOMResult result = new DOMResult(); trans.transform(source, result); return new DOMSource(result.getNode()); }
/** * Transforms a DOM Document into a String * * @param fromDocument the Document to use as the source * @return the XML as a String * @throws java.io.IOException * @throws javax.xml.transform.TransformerException */ public static String transform(Document fromDocument) throws TransformerException, IOException { Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); StringWriter sw = new StringWriter(); StreamResult result = new StreamResult(sw); DOMSource source = new DOMSource(fromDocument); transformer.transform(source, result); return sw.toString(); }
/** * Transforms a streamed XML representation into a DOM Document * * @param reader the XML fragment as an input stream to use as the source * @param toDocument the destination Document * @throws javax.xml.transform.TransformerException */ public static void transform(UnicodeReader reader, Document toDocument) throws TransformerException { try { TransformerFactory.newInstance() .newTransformer() .transform(new StreamSource(reader), new DOMResult(toDocument)); } catch (Exception e) { throw new TransformerException("Cannot remove byte-order-mark from XML file"); } }
public static String transform(File fromPath) throws TransformerException, IOException { Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); Reader reader = bomCheck(fromPath); StringWriter sw = new StringWriter(); transformer.transform(new StreamSource(reader), new StreamResult(sw)); return sw.toString(); }
/** * Transforms a DOM Document into a String * * @param fromDocument the Document to use as the source * @param omitXmlDeclaration will not write the XML header if true * @return the XML as a String * @throws java.io.IOException * @throws javax.xml.transform.TransformerException */ public static String transform(Document fromDocument, boolean omitXmlDeclaration) throws TransformerException, IOException { Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); if (omitXmlDeclaration) transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); StringWriter sw = new StringWriter(); transformer.transform(new DOMSource(fromDocument), new StreamResult(sw)); return sw.toString(); }
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { try { DateFormat df = DateFormat.getDateTimeInstance(); String titleStr = "C3P0 Status - " + df.format(new Date()); DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance(); DocumentBuilder db = fact.newDocumentBuilder(); Document doc = db.newDocument(); Element htmlElem = doc.createElement("html"); Element headElem = doc.createElement("head"); Element titleElem = doc.createElement("title"); titleElem.appendChild(doc.createTextNode(titleStr)); Element bodyElem = doc.createElement("body"); Element h1Elem = doc.createElement("h1"); h1Elem.appendChild(doc.createTextNode(titleStr)); Element h3Elem = doc.createElement("h3"); h3Elem.appendChild(doc.createTextNode("PooledDataSources")); Element pdsDlElem = doc.createElement("dl"); pdsDlElem.setAttribute("class", "PooledDataSources"); for (Iterator ii = C3P0Registry.getPooledDataSources().iterator(); ii.hasNext(); ) { PooledDataSource pds = (PooledDataSource) ii.next(); StatusReporter sr = findStatusReporter(pds, doc); pdsDlElem.appendChild(sr.reportDtElem()); pdsDlElem.appendChild(sr.reportDdElem()); } headElem.appendChild(titleElem); htmlElem.appendChild(headElem); bodyElem.appendChild(h1Elem); bodyElem.appendChild(h3Elem); bodyElem.appendChild(pdsDlElem); htmlElem.appendChild(bodyElem); res.setContentType("application/xhtml+xml"); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); Source src = new DOMSource(doc); Result result = new StreamResult(res.getOutputStream()); transformer.transform(src, result); } catch (IOException e) { throw e; } catch (Exception e) { throw new ServletException(e); } }
public static void saveTodoListToXml(TodoList todoList, String file) throws TransformerConfigurationException, ParserConfigurationException, FileNotFoundException, TransformerException { Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); transformer.transform( new DOMSource(_createXmlFromTodoList(todoList)), new StreamResult(new FileOutputStream(file))); }
/** * Transforms a streamed XML representation into a DOM Document * * @param in the XML fragment as an input stream to use as the source * @param toDocument the destination Document * @throws javax.xml.transform.TransformerException */ public static void transform(InputStream in, Document toDocument) throws TransformerException { // Reader reader = new BufferedReader(new InputStreamReader(in)); try { // removeBOM(reader); Reader reader = bomCheck(in); TransformerFactory.newInstance() .newTransformer() .transform(new StreamSource(reader), new DOMResult(toDocument)); } catch (Exception e) { throw new TransformerException("Cannot remove byte-order-mark from XML file"); } }
public static String getXMLasString(Document document) throws TransformerException { Source source = new DOMSource(document); Transformer xformer = TransformerFactory.newInstance().newTransformer(); xformer.setParameter(OutputKeys.INDENT, "yes"); xformer.setOutputProperty(OutputKeys.INDENT, "yes"); xformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); Writer outputWriter = new StringWriter(); Result stringOut = new StreamResult(outputWriter); xformer.transform(source, stringOut); return outputWriter.toString(); }
void outputDocument(Writer out) throws Exception { // Set up the output transformer TransformerFactory transfac = TransformerFactory.newInstance(); Transformer trans = transfac.newTransformer(); // trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); trans.setOutputProperty(OutputKeys.INDENT, "yes"); trans.setOutputProperty(OutputKeys.METHOD, "html"); // Print the DOM node StreamResult result = new StreamResult(out); DOMSource source = new DOMSource(this.document); trans.transform(source, result); }
public void write(SecureItemTable tbl, char[] password) throws IOException { OutputStream os = new FileOutputStream(file); OutputStream xmlout; if (password.length == 0) { xmlout = os; os = null; } else { PBEKeySpec keyspec = new PBEKeySpec(password); Cipher c; try { SecretKeyFactory fac = SecretKeyFactory.getInstance("PBEWithMD5AndDES"); SecretKey key = fac.generateSecret(keyspec); c = Cipher.getInstance("PBEWithMD5AndDES"); c.init(Cipher.ENCRYPT_MODE, key, pbeSpec); } catch (java.security.GeneralSecurityException exc) { os.close(); IOException ioe = new IOException("Security exception during write"); ioe.initCause(exc); throw ioe; } CipherOutputStream out = new CipherOutputStream(os, c); xmlout = out; } try { TransformerFactory tf = TransformerFactory.newInstance(); Transformer t = tf.newTransformer(); DOMSource src = new DOMSource(tbl.getDocument()); StringWriter writer = new StringWriter(); StreamResult sr = new StreamResult(writer); t.transform(src, sr); OutputStreamWriter osw = new OutputStreamWriter(xmlout, StandardCharsets.UTF_8); osw.write(writer.toString()); osw.close(); } catch (Exception exc) { IOException ioe = new IOException("Unable to serialize XML"); ioe.initCause(exc); throw ioe; } finally { xmlout.close(); if (os != null) os.close(); } tbl.setDirty(false); return; }
/** * http://www.atmarkit.co.jp/fxml/rensai2/xmltool04/02.html * * @return */ private static Transformer getTransformer() { if (s_transformer == null) { TransformerFactory transFactory = TransformerFactory.newInstance(); try { s_transformer = transFactory.newTransformer(); } catch (TransformerConfigurationException e) { } s_transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); s_transformer.setOutputProperty(OutputKeys.INDENT, "yes"); } // if return s_transformer; }
// This method writes a DOM document to a file public static void writeXmlFile(Document doc, File file) { try { // Prepare the DOM document for writing Source source = new DOMSource(doc); // Prepare the output file Result result = new StreamResult(file); // Write the DOM document to the file Transformer xformer = TransformerFactory.newInstance().newTransformer(); xformer.transform(source, result); } catch (TransformerException ignored) { } }