List of usage examples for javax.xml.transform TransformerFactory setAttribute
public abstract void setAttribute(String name, Object value);
From source file:com.sangupta.clitools.file.Format.java
private void formatXML(File file) { try {/*from w w w. jav a 2 s. c o m*/ Source xmlInput = new StreamSource(file); StringWriter stringWriter = new StringWriter(); StreamResult xmlOutput = new StreamResult(stringWriter); TransformerFactory transformerFactory = TransformerFactory.newInstance(); transformerFactory.setAttribute("indent-number", 4); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.transform(xmlInput, xmlOutput); String out = xmlOutput.getWriter().toString(); // add a new line after "?>< for next tag starting int index = out.indexOf("\"?><"); if (index > 0) { out = out.substring(0, index + 3) + "\n" + out.substring(index + 3); } if (!this.overwrite) { System.out.println(out); return; } org.apache.commons.io.FileUtils.writeStringToFile(file, out); } catch (Exception e) { System.out.println("Unable to format file!"); e.printStackTrace(); } }
From source file:TransformServlet.java
/** * Main servlet entry point/*from w w w . j av a 2s . c o m*/ */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // Initialise the output writer response.setContentType("text/html"); PrintWriter out = response.getWriter(); // Get the two paramters "class" and "source". String transletName = request.getParameter("class"); String documentURI = request.getParameter("source"); try { if ((transletName == null) || (documentURI == null)) { out.println("<h1>XSL transformation error</h1>"); out.println( "The parameters <b><tt>class</tt></b> and " + "<b><tt>source</tt></b> must be specified"); } else { TransformerFactory tf = TransformerFactory.newInstance(); try { tf.setAttribute("use-classpath", Boolean.TRUE); } catch (IllegalArgumentException iae) { System.err.println("Could not set XSLTC-specific TransformerFactory " + "attributes. Transformation failed."); } Transformer t = tf.newTransformer(new StreamSource(transletName)); // Start the transformation final long start = System.currentTimeMillis(); t.transform(new StreamSource(documentURI), new StreamResult(out)); final long done = System.currentTimeMillis() - start; out.println("<!-- transformed by XSLTC in " + done + "msecs -->"); } } catch (Exception e) { out.println("<h1>Error</h1>"); out.println(e.toString()); } }
From source file:it.unibas.spicy.persistence.xml.DAOXmlUtility.java
public void saveDOM(org.w3c.dom.Document document, String filename) throws DAOException { try {// www .j av a2s .c o m File file = new java.io.File(filename); TransformerFactory transformerFactory = TransformerFactory.newInstance(); transformerFactory.setAttribute("indent-number", new Integer(2)); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xalan}indent-amount", "2"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); DOMSource source = new DOMSource(document); StreamResult result = new StreamResult(file); transformer.transform(source, result); } catch (Exception ex) { logger.error("- Exception in saveDOM: \n" + ex); throw new DAOException(ex.getMessage()); } }
From source file:TransformBean.java
/** * Main bean entry point/*w w w. ja v a 2s. c om*/ */ public String transform(String document, String transletName) { // Initialise the output stream final StringWriter sout = new StringWriter(); final PrintWriter out = new PrintWriter(sout); try { if ((document == null) || (transletName == null)) { out.println(nullErrorMsg); } else { TransformerFactory tf = TransformerFactory.newInstance(); try { tf.setAttribute("use-classpath", Boolean.TRUE); } catch (IllegalArgumentException iae) { System.err.println("Could not set XSLTC-specific TransformerFactory " + "attributes. Transformation failed."); } Transformer t = tf.newTransformer(new StreamSource(transletName)); // Do the actual transformation final long start = System.currentTimeMillis(); t.transform(new StreamSource(document), new StreamResult(out)); final long done = System.currentTimeMillis() - start; out.println("<!-- transformed by XSLTC in " + done + "msecs -->"); } } catch (Exception e) { errorMsg(out, e, "Impossible state reached."); } // Now close up the sink, and return the HTML output in the // StringWrite object as a string. out.close(); return sout.toString(); }
From source file:com.adaptris.util.text.xml.XmlTransformerFactoryImpl.java
TransformerFactory configure(TransformerFactory tf) throws TransformerConfigurationException { for (KeyValuePair kp : getTransformerFactoryAttributes()) { tf.setAttribute(kp.getKey(), kp.getValue()); }/*from ww w. j a v a 2 s. c om*/ for (KeyValuePair kp : getTransformerFactoryFeatures()) { tf.setFeature(kp.getKey(), BooleanUtils.toBoolean(kp.getValue())); } tf.setErrorListener(new DefaultErrorListener(failOnRecoverableError())); return tf; }
From source file:datascript.backend.xml.XmlExtension.java
public void generate(DataScriptEmitter emitter, TokenAST rootNode) throws Exception { if (params == null) throw new DataScriptException("No parameters set for XmlBackend!"); if (!params.argumentExists("-xml")) { System.out.println("emitting XML file is disabled."); return;// w w w . j av a 2s . c o m } System.out.println("emitting xml"); String fileName = params.getCommandlineArg("-xml"); if (fileName == null) { fileName = "datascript.xml"; } File outputFile = new File(params.getOutPathName(), fileName); this.rootNode = rootNode; FileOutputStream os = new FileOutputStream(outputFile); TransformerFactory tf = TransformerFactory.newInstance(); tf.setAttribute("indent-number", new Integer(2)); Transformer t = tf.newTransformer(); t.setOutputProperty(OutputKeys.INDENT, "yes"); t.setOutputProperty(OutputKeys.METHOD, "xml"); Source source = new SAXSource(this, new InputSource()); Result result = new StreamResult(new OutputStreamWriter(os)); t.transform(source, result); }
From source file:fedora.server.rest.BaseRestResource.java
protected void transform(String xml, String xslt, Writer out) throws TransformerFactoryConfigurationError, TransformerConfigurationException, TransformerException { File xslFile = new File(fedoraServer.getHomeDir(), xslt); TransformerFactory factory = TransformerFactory.newInstance(); if (factory.getClass().getName().equals("net.sf.saxon.TransformerFactoryImpl")) { factory.setAttribute(FeatureKeys.VERSION_WARNING, Boolean.FALSE); }//w w w . ja va 2 s .c o m Templates template = factory.newTemplates(new StreamSource(xslFile)); Transformer transformer = template.newTransformer(); String appContext = getContext().getEnvironmentValue(Constants.FEDORA_APP_CONTEXT_NAME); transformer.setParameter("fedora", appContext); transformer.transform(new StreamSource(new StringReader(xml)), new StreamResult(out)); }
From source file:datascript.emit.xml.XmlExtension.java
public void generate(DataScriptEmitter emitter, TokenAST root) { if (parameters == null) throw new DataScriptException("No parameters set for XmlBackend!"); if (!parameters.argumentExists("-xml")) { System.out.println("emitting XML file is disabled."); return;// w w w . j a va 2 s . c o m } System.out.println("emitting xml"); String fileName = parameters.getCommandLineArg("-xml"); if (fileName == null) { fileName = "datascript.xml"; } File outputFile = new File(parameters.getOutPathName(), fileName); this.rootNode = root; FileOutputStream os; try { os = new FileOutputStream(outputFile); TransformerFactory tf = TransformerFactory.newInstance(); tf.setAttribute("indent-number", new Integer(2)); Transformer t = tf.newTransformer(); t.setOutputProperty(OutputKeys.INDENT, "yes"); t.setOutputProperty(OutputKeys.METHOD, "xml"); Source source = new SAXSource(this, new InputSource()); Result result = new StreamResult(new OutputStreamWriter(os)); t.transform(source, result); } catch (FileNotFoundException exc) { throw new DataScriptException(exc); } catch (TransformerConfigurationException exc) { throw new DataScriptException(exc); } catch (TransformerException exc) { throw new DataScriptException(exc); } }
From source file:jeeves.utils.Xml.java
/** * Transforms an xml tree putting the result to a stream with optional parameters. * * @param xml//from w w w. ja va 2s . c o m * @param styleSheetPath * @param result * @param params * @throws Exception */ public static void transform(Element xml, String styleSheetPath, Result result, Map<String, String> params) throws Exception { File styleSheet = new File(styleSheetPath); Source srcXml = new JDOMSource(new Document((Element) xml.detach())); Source srcSheet = new StreamSource(styleSheet); // Dear old saxon likes to yell loudly about each and every XSLT 1.0 // stylesheet so switch it off but trap any exceptions because this // code is run on transformers other than saxon TransformerFactory transFact = TransformerFactoryFactory.getTransformerFactory(); transFact.setURIResolver(new JeevesURIResolver()); try { transFact.setAttribute(FeatureKeys.VERSION_WARNING, false); transFact.setAttribute(FeatureKeys.LINE_NUMBERING, true); transFact.setAttribute(FeatureKeys.PRE_EVALUATE_DOC_FUNCTION, false); transFact.setAttribute(FeatureKeys.RECOVERY_POLICY, Configuration.RECOVER_SILENTLY); // Add the following to get timing info on xslt transformations //transFact.setAttribute(FeatureKeys.TIMING,true); } catch (IllegalArgumentException e) { Log.warning(Log.ENGINE, "WARNING: transformerfactory doesnt like saxon attributes!"); //e.printStackTrace(); } finally { Transformer t = transFact.newTransformer(srcSheet); if (params != null) { for (Map.Entry<String, String> param : params.entrySet()) { t.setParameter(param.getKey(), param.getValue()); } } t.transform(srcXml, result); } }
From source file:net.sourceforge.fullsync.fs.connection.SyncFileBufferedConnection.java
public void saveToBuffer() throws IOException { File fsRoot = fs.getRoot();//from ww w .ja va 2 s . co m File node = fsRoot.getChild(BUFFER_FILENAME); if ((null == node) || !node.exists()) { node = root.createChild(BUFFER_FILENAME, false); } try { DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = docBuilder.newDocument(); Element e = doc.createElement(ELEMENT_SYNC_FILES); e.appendChild(serializeFile(root, doc)); doc.appendChild(e); TransformerFactory fac = TransformerFactory.newInstance(); fac.setAttribute("indent-number", 2); //$NON-NLS-1$ Transformer tf = fac.newTransformer(); tf.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$ tf.setOutputProperty(OutputKeys.VERSION, "1.0"); //$NON-NLS-1$ tf.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$ tf.setOutputProperty(OutputKeys.STANDALONE, "no"); //$NON-NLS-1$ DOMSource source = new DOMSource(doc); try (OutputStreamWriter osw = new OutputStreamWriter(new GZIPOutputStream(node.getOutputStream()), StandardCharsets.UTF_8)) { tf.transform(source, new StreamResult(osw)); osw.flush(); } } catch (IOException | ParserConfigurationException | FactoryConfigurationError | TransformerException e) { ExceptionHandler.reportException(e); } }