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) { } }
/** * 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; }
@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"); } }
private String importXMI(File sourceFile) throws FileNotFoundException, TransformerConfigurationException, TransformerException { BufferedReader styledata; StreamSource sourcedata; Templates stylesheet; Transformer trans; // Get the stylesheet file stream styledata = new BufferedReader( new FileReader( new File( getClass().getClassLoader().getResource("verifier/xmi2lem.xsl").getFile()))); sourcedata = new StreamSource(new FileReader(sourceFile)); // Initialize Saxon TransformerFactory factory = TransformerFactoryImpl.newInstance(); stylesheet = factory.newTemplates(new StreamSource(styledata)); // Apply the transformation trans = stylesheet.newTransformer(); StringWriter sw = new StringWriter(); trans.transform(sourcedata, new StreamResult(sw)); // return sw.toString(); return sw.getBuffer().substring(sw.getBuffer().indexOf("model")); }
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 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; } }
/** * 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; } }
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); }
static { DocumentBuilderFactory factory = new org.apache.xerces.jaxp.DocumentBuilderFactoryImpl(); try { builder = factory.newDocumentBuilder(); } catch (Exception e) { e.printStackTrace(); } try { // Create an instance of our own transformer factory impl TransformerFactory transFactory = new com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl(); // create Transformer transformer = transFactory.newTransformer(); } catch (TransformerConfigurationException tce) { // Error generated by the parser System.out.println("* Transformer Factory error"); System.out.println(" " + tce.getMessage()); // Use the contained exception, if any Throwable x = tce; if (tce.getException() != null) x = tce.getException(); x.printStackTrace(); } }
private static Transformer getTransformer() throws TransformerException { if (_transformer == null) { TransformerFactory factory = TransformerFactory.newInstance(); _transformer = factory.newTransformer(); } return _transformer; }
public final void testCreateFromAlgorithmName() throws XMLTransformNotFoundException { assertNotNull(TransformerFactory.make("uri:neuclear-test-clear-transform")); assertNotNull(TransformerFactory.make("uri:neuclear-test-opaque-transform")); try { TransformerFactory.make("uri:neuclear-test-non-existent"); assertTrue("TransformerFactory incorrectly did not throw an exception", true); } catch (XMLTransformNotFoundException e) { assertTrue("TransformerFactory correctly throw an exception", true); } }
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); } }
/** * Create a Collection of {@link Transformer} instances from the supplied {@link TransformModel} * instance. * * @param transformModel The TransformModel instance. * @return The Transformer instance. */ public Collection<Transformer<?, ?>> newTransformers(TransformModel transformModel) { Collection<Transformer<?, ?>> transformers = null; if (transformModel instanceof JavaTransformModel) { JavaTransformModel javaTransformModel = JavaTransformModel.class.cast(transformModel); String bean = javaTransformModel.getBean(); if (bean != null) { BeanManager beanManager = CDIUtil.lookupBeanManager(); if (beanManager == null) { throw TransformMessages.MESSAGES.cdiBeanManagerNotFound(); } Object transformer = null; Set<Bean<?>> beans = beanManager.getBeans(bean); if (beans != null && !beans.isEmpty()) { Bean<?> target = beans.iterator().next(); CreationalContext<?> context = beanManager.createCreationalContext(target); transformer = beanManager.getReference(target, Object.class, context); _cdiCreationalContexts.add(context); } if (transformer == null) { throw TransformMessages.MESSAGES.beanNotFoundInCDIRegistry(bean); } transformers = TransformerUtil.newTransformers( transformer, transformModel.getFrom(), transformModel.getTo()); } else { String className = ((JavaTransformModel) transformModel).getClazz(); if (className == null) { throw TransformMessages.MESSAGES.beanOrClassMustBeSpecified(); } Class<?> transformClass = getClass(className); if (transformClass == null) { throw TransformMessages.MESSAGES.unableToLoadTransformerClass(className); } transformers = TransformerUtil.newTransformers( transformClass, transformModel.getFrom(), transformModel.getTo()); } } else { TransformerFactory factory = getTransformerFactory(transformModel); transformers = new ArrayList<Transformer<?, ?>>(); transformers.add(factory.newTransformer(_serviceDomain, transformModel)); } if (transformers == null || transformers.isEmpty()) { throw TransformMessages.MESSAGES.unknownTransformModel(transformModel.getClass().getName()); } return transformers; }
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; }
public static void main(String[] args) { try { // Find the implementation DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); DOMImplementation impl = builder.getDOMImplementation(); // Create the document DocumentType svgDOCTYPE = impl.createDocumentType( "svg", "-//W3C//DTD SVG 1.0//EN", "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd"); Document doc = impl.createDocument("http://www.w3.org/2000/svg", "svg", svgDOCTYPE); // Fill the document Node rootElement = doc.getDocumentElement(); ProcessingInstruction xmlstylesheet = doc.createProcessingInstruction( "xml-stylesheet", "type=\"text/css\" href=\"standard.css\""); Comment comment = doc.createComment("An example from Chapter 10 of Processing XML with Java"); doc.insertBefore(comment, rootElement); doc.insertBefore(xmlstylesheet, rootElement); Node desc = doc.createElementNS("http://www.w3.org/2000/svg", "desc"); rootElement.appendChild(desc); Text descText = doc.createTextNode("An example from Processing XML with Java"); desc.appendChild(descText); // Serialize the document onto System.out TransformerFactory xformFactory = TransformerFactory.newInstance(); Transformer idTransform = xformFactory.newTransformer(); Source input = new DOMSource(doc); Result output = new StreamResult(System.out); idTransform.transform(input, output); } catch (FactoryConfigurationError e) { System.out.println("Could not locate a JAXP factory class"); } catch (ParserConfigurationException e) { System.out.println("Could not locate a JAXP DocumentBuilder class"); } catch (DOMException e) { System.err.println(e); } catch (TransformerConfigurationException e) { System.err.println(e); } catch (TransformerException e) { System.err.println(e); } }
/** * 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; }
/** 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; }
/** * Converts an XML document to a string. From Zaz Gmy on this StackOverflow post: * http://stackoverflow.com/questions/10356258/how-do-i-convert-a-org-w3c-dom-document-object-to-a-string * * @param doc The document to convert to a String. */ private static String getStringFromDocument(Document doc) { try { DOMSource domSource = new DOMSource(doc); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.transform(domSource, result); return writer.toString(); } catch (TransformerException ex) { ex.printStackTrace(); return null; } }
public SchematronTransformer() throws TransformerConfigurationException { step1 = transformerFactory.newTransformer( new StreamSource( getClass().getResourceAsStream("/iso-schematron-xslt2/iso_dsdl_include.xsl"))); step2 = transformerFactory.newTransformer( new StreamSource( getClass().getResourceAsStream("/iso-schematron-xslt2/iso_abstract_expand.xsl"))); step3 = transformerFactory.newTransformer( new StreamSource( getClass().getResourceAsStream("/iso-schematron-xslt2/iso_svrl_for_xslt2.xsl"))); }
public static String toString(org.w3c.dom.Element doc) { try { DOMSource domSource = new DOMSource(doc); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.transform(domSource, result); writer.flush(); return writer.toString(); } catch (TransformerException ex) { ex.printStackTrace(); return null; } }
/** * 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)); }
@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; }
/** * Marshal jaxb element and try to perform basic formatting like namespace clean up and attribute * formatting with xsl transformation. * * @param jaxbElement * @return */ private String getXmlContent(Object jaxbElement) { StringResult jaxbContent = new StringResult(); springBeanMarshaller.marshal(jaxbElement, jaxbContent); Source xsltSource; try { xsltSource = new StreamSource(new ClassPathResource("transform/format-bean.xsl").getInputStream()); Transformer transformer = transformerFactory.newTransformer(xsltSource); // transform StringResult result = new StringResult(); transformer.transform(new StringSource(jaxbContent.toString()), result); if (log.isDebugEnabled()) { log.debug("Created bean definition:\n" + result.toString()); } return result.toString(); } catch (IOException e) { throw new ApplicationRuntimeException(UNABLE_TO_READ_TRANSFORMATION_SOURCE, e); } catch (TransformerException e) { throw new ApplicationRuntimeException(FAILED_TO_UPDATE_BEAN_DEFINITION, e); } }
/** * Method removes a Spring bean definition from the XML application context file. Bean definition * is identified by its id or bean name. * * @param project * @param id */ public void removeBeanDefinition(File configFile, Project project, String id) { Source xsltSource; Source xmlSource; try { xsltSource = new StreamSource(new ClassPathResource("transform/delete-bean.xsl").getInputStream()); xsltSource.setSystemId("delete-bean"); List<File> configFiles = new ArrayList<>(); configFiles.add(configFile); configFiles.addAll(getConfigImports(configFile, project)); for (File file : configFiles) { xmlSource = new StringSource(FileUtils.readToString(new FileInputStream(configFile))); // create transformer Transformer transformer = transformerFactory.newTransformer(xsltSource); transformer.setParameter("bean_id", id); // transform StringResult result = new StringResult(); transformer.transform(xmlSource, result); FileUtils.writeToFile(format(result.toString(), project.getSettings().getTabSize()), file); return; } } catch (IOException e) { throw new ApplicationRuntimeException(UNABLE_TO_READ_TRANSFORMATION_SOURCE, e); } catch (TransformerException e) { throw new ApplicationRuntimeException(FAILED_TO_UPDATE_BEAN_DEFINITION, e); } }
/** * Method adds a new Spring bean definition to the XML application context file. * * @param project * @param jaxbElement */ public void addBeanDefinition(File configFile, Project project, Object jaxbElement) { Source xsltSource; Source xmlSource; try { xsltSource = new StreamSource(new ClassPathResource("transform/add-bean.xsl").getInputStream()); xsltSource.setSystemId("add-bean"); xmlSource = new StringSource(FileUtils.readToString(new FileInputStream(configFile))); // create transformer Transformer transformer = transformerFactory.newTransformer(xsltSource); transformer.setParameter( "bean_content", getXmlContent(jaxbElement) .replaceAll("(?m)^(.)", getTabs(1, project.getSettings().getTabSize()) + "$1")); // transform StringResult result = new StringResult(); transformer.transform(xmlSource, result); FileUtils.writeToFile( format(result.toString(), project.getSettings().getTabSize()), configFile); return; } catch (IOException e) { throw new ApplicationRuntimeException(UNABLE_TO_READ_TRANSFORMATION_SOURCE, e); } catch (TransformerException e) { throw new ApplicationRuntimeException(FAILED_TO_UPDATE_BEAN_DEFINITION, e); } }
public void testAbortMultiRecordFileRead() { Transformer spec = TransformerFactory.getTransformer(FixedColBean.class); spec.parseFlatFile( FixedColumnWithRecordListenerTestCase.class.getResourceAsStream( "abortread-multi-record-fixedcol-file.txt"), new AbortListener()); }
public void save(String filename) { try { Document document = element.getOwnerDocument(); document.getDocumentElement().normalize(); TransformerFactory tFactory = TransformerFactory.newInstance(); tFactory.setAttribute("indent-number", new Integer(4)); Transformer transformer = tFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); DOMSource source = new DOMSource(document); File file = new File(filename); StreamResult result = new StreamResult(file); transformer.transform(source, result); } catch (Exception e) { severe("Could not save XML file: " + e.getMessage()); } }
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 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(); }