List of usage examples for javax.xml.transform TransformerFactory setAttribute
public abstract void setAttribute(String name, Object value);
From source file:jeeves.utils.Xml.java
/** * Transform an xml tree to PDF using XSL-FOP * putting the result to a stream (uses a stylesheet * on disk)//from www .j a v a 2s. c o m */ public static String transformFOP(String uploadDir, Element xml, String styleSheetPath) throws Exception { String file = uploadDir + UUID.randomUUID().toString() + ".pdf"; // Step 1: Construct a FopFactory // (reuse if you plan to render multiple documents!) FopFactory fopFactory = FopFactory.newInstance(); // Step 2: Set up output stream. // Note: Using BufferedOutputStream for performance reasons (helpful // with FileOutputStreams). OutputStream out = new BufferedOutputStream(new FileOutputStream(new File(file))); try { // Step 3: Construct fop with desired output format Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, out); // Step 4: Setup JAXP using identity transformer TransformerFactory factory = TransformerFactoryFactory.getTransformerFactory(); factory.setURIResolver(new JeevesURIResolver()); Source xslt = new StreamSource(new File(styleSheetPath)); try { factory.setAttribute(FeatureKeys.VERSION_WARNING, false); factory.setAttribute(FeatureKeys.LINE_NUMBERING, true); factory.setAttribute(FeatureKeys.RECOVERY_POLICY, Configuration.RECOVER_SILENTLY); } catch (IllegalArgumentException e) { Log.warning(Log.ENGINE, "WARNING: transformerfactory doesnt like saxon attributes!"); //e.printStackTrace(); } finally { Transformer transformer = factory.newTransformer(xslt); // Step 5: Setup input and output for XSLT transformation // Setup input stream Source src = new JDOMSource(new Document((Element) xml.detach())); // Resulting SAX events (the generated FO) must be piped through to // FOP Result res = new SAXResult(fop.getDefaultHandler()); // Step 6: Start XSLT transformation and FOP processing transformer.transform(src, res); } } finally { // Clean-up out.close(); } return file; }
From source file:org.fcrepo.localservices.saxon.SaxonServlet.java
/** * Maintain prepared stylesheets in memory for reuse *//*from w w w .j av a 2s .co m*/ private Templates tryCache(String url) throws Exception { Templates x = (Templates) m_cache.get(url); if (x == null) { synchronized (m_cache) { if (!m_cache.containsKey(url)) { TransformerFactory factory = TransformerFactory.newInstance(); if (factory.getClass().getName().equals("net.sf.saxon.TransformerFactoryImpl")) { factory.setAttribute(FeatureKeys.VERSION_WARNING, Boolean.FALSE); } StreamSource ss = new StreamSource(getInputStream(url)); ss.setSystemId(url); x = factory.newTemplates(ss); m_cache.put(url, x); } } } return x; }
From source file:net.sourceforge.eclipsetrader.ats.Repository.java
protected void saveDocument(Document document, String path, String name) { try {//from ww w . j a v a 2 s . c o m TransformerFactory factory = TransformerFactory.newInstance(); try { factory.setAttribute("indent-number", new Integer(4)); } catch (Exception e) { } Transformer transformer = factory.newTransformer(); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http\u003a//xml.apache.org/xslt}indent-amount", "4"); DOMSource source = new DOMSource(document); File file = new File(Platform.getLocation().toFile(), path); file.mkdirs(); file = new File(file, name); BufferedWriter out = new BufferedWriter(new FileWriter(file)); StreamResult result = new StreamResult(out); transformer.transform(source, result); out.flush(); out.close(); } catch (Exception e) { log.error(e.toString(), e); } }
From source file:com.messagehub.samples.servlet.KafkaServlet.java
public String toPrettyString(String xml, int indent) { try {/* w ww .ja v a2s.c o m*/ // Turn xml string into a document Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder() .parse(new InputSource(new ByteArrayInputStream(xml.getBytes("utf-8")))); // Remove whitespaces outside tags XPath xPath = XPathFactory.newInstance().newXPath(); NodeList nodeList = (NodeList) xPath.evaluate("//text()[normalize-space()='']", document, XPathConstants.NODESET); for (int i = 0; i < nodeList.getLength(); ++i) { Node node = nodeList.item(i); node.getParentNode().removeChild(node); } // Setup pretty print options TransformerFactory transformerFactory = TransformerFactory.newInstance(); transformerFactory.setAttribute("indent-number", indent); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // Return pretty print xml string StringWriter stringWriter = new StringWriter(); transformer.transform(new DOMSource(document), new StreamResult(stringWriter)); return stringWriter.toString(); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:net.sourceforge.eclipsetrader.core.CurrencyConverter.java
private void save() { try {/*from w ww. j ava 2 s .c om*/ DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document document = builder.getDOMImplementation().createDocument(null, "data", null); //$NON-NLS-1$ Element root = document.getDocumentElement(); for (Iterator iter = currencies.iterator(); iter.hasNext();) { Element node = document.createElement("currency"); //$NON-NLS-1$ node.appendChild(document.createTextNode((String) iter.next())); root.appendChild(node); } for (Iterator iter = map.keySet().iterator(); iter.hasNext();) { String symbol = (String) iter.next(); Element node = document.createElement("conversion"); //$NON-NLS-1$ node.setAttribute("symbol", symbol); //$NON-NLS-1$ node.setAttribute("ratio", String.valueOf(map.get(symbol))); //$NON-NLS-1$ saveHistory(node, symbol); root.appendChild(node); } TransformerFactory factory = TransformerFactory.newInstance(); try { factory.setAttribute("indent-number", new Integer(4)); //$NON-NLS-1$ } catch (Exception e) { } Transformer transformer = factory.newTransformer(); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$ transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1"); //$NON-NLS-1$ transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$ transformer.setOutputProperty("{http\u003a//xml.apache.org/xslt}indent-amount", "4"); //$NON-NLS-1$ //$NON-NLS-2$ DOMSource source = new DOMSource(document); File file = new File(Platform.getLocation().toFile(), "currencies.xml"); //$NON-NLS-1$ BufferedWriter out = new BufferedWriter(new FileWriter(file)); StreamResult result = new StreamResult(out); transformer.transform(source, result); out.flush(); out.close(); } catch (Exception e) { logger.error(e, e); } }
From source file:com.legstar.cob2xsd.Cob2Xsd.java
/** * Serialize the XML Schema to a string. * <p/>//from w w w . ja va 2 s . c o m * If we are provided with an XSLT customization file then we transform the * XMLSchema. * * @param xsd the XML Schema before customization * @return a string serialization of the customized XML Schema * @throws XsdGenerationException if customization fails */ public String xsdToString(final XmlSchema xsd) throws XsdGenerationException { if (_log.isDebugEnabled()) { StringWriter writer = new StringWriter(); xsd.write(writer); debug("6. Writing XML Schema: ", writer.toString()); } String errorMessage = "Customizing XML Schema failed."; try { TransformerFactory tFactory = TransformerFactory.newInstance(); try { tFactory.setAttribute("indent-number", "4"); } catch (IllegalArgumentException e) { _log.debug("Unable to set indent-number on transfomer factory", e); } StringWriter writer = new StringWriter(); Source source = new DOMSource(xsd.getAllSchemas()[0]); Result result = new StreamResult(writer); Transformer transformer; String xsltFileName = getModel().getCustomXsltFileName(); if (xsltFileName == null || xsltFileName.trim().length() == 0) { transformer = tFactory.newTransformer(); } else { Source xsltSource = new StreamSource(new File(xsltFileName)); transformer = tFactory.newTransformer(xsltSource); } transformer.setOutputProperty(OutputKeys.ENCODING, getModel().getXsdEncoding()); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); transformer.setOutputProperty(OutputKeys.STANDALONE, "no"); transformer.transform(source, result); writer.flush(); return writer.toString(); } catch (TransformerConfigurationException e) { _log.error(errorMessage, e); throw new XsdGenerationException(e); } catch (TransformerFactoryConfigurationError e) { _log.error(errorMessage, e); throw new XsdGenerationException(e); } catch (TransformerException e) { _log.error(errorMessage, e); throw new XsdGenerationException(e); } }
From source file:es.upm.fi.dia.oeg.sitemap4rdf.Generator.java
/** * Save as zip file the given XML Document using a given file name * @param fileName the name of the generated zip file * @param doc the XML document to store in the zip file *//*from w ww . ja v a 2 s . c o m*/ protected void saveZipFile(String fileName, Document doc) { String outfileName = fileName + zipFileExtension; if (outputDir != null && !outputDir.isEmpty()) outfileName = outputDir + outfileName; try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); Source xmlSource = new DOMSource(doc); Result outputTarget = new StreamResult(new OutputStreamWriter(outputStream, DEFAULT_ENCODING)); TransformerFactory tf = TransformerFactory.newInstance(); tf.setAttribute(xmlAttributeIdentNumber, new Integer(4)); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, DEFAULT_ENCODING); transformer.setOutputProperty("{http://xml. customer .org/xslt}indent-amount", "4"); transformer.transform(xmlSource, outputTarget); InputStream in = new ByteArrayInputStream(outputStream.toString(DEFAULT_ENCODING).getBytes()); byte[] buf = new byte[1024]; //create the zip file GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(outfileName)); //Transfer bytes from the inputstream to the ZIP int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } //Complete the entry in.close(); //complete the zip file out.finish(); out.close(); } catch (FileNotFoundException e) { logger.debug("FileNotFoundException ", e); System.err.println(e.getMessage()); System.exit(3); } catch (IOException e) { logger.debug("IOException ", e); System.err.println(e.getMessage()); System.exit(3); } catch (TransformerConfigurationException e) { logger.debug("TransformerConfigurationException ", e); System.err.println(e.getMessage()); System.exit(3); } catch (TransformerException e) { logger.debug("TransformerException ", e); System.err.println(e.getMessage()); System.exit(3); } catch (TransformerFactoryConfigurationError e) { logger.debug("TransformerFactoryConfigurationError ", e); System.err.println(e.getMessage()); System.exit(3); } }
From source file:XMLConfig.java
/** Saves configuration to an output stream * @param os output stream//from ww w.java 2 s . c o m */ public void save(OutputStream os) { if (isDelegated()) { _parent.save(os); return; } // Prepare the DOM document for writing Source source = new DOMSource(_document); /* // Prepare the output file Result result = new StreamResult(os); */ // Write the DOM document to the file try { TransformerFactory tf = TransformerFactory.newInstance(); tf.setAttribute("indent-number", Integer.valueOf(2)); Transformer t = tf.newTransformer(); t.setOutputProperty(OutputKeys.INDENT, "yes"); t.transform(source, new StreamResult(new OutputStreamWriter(os, "utf-8"))); /* Transformer xformer = TransformerFactory.newInstance().newTransformer(); xformer.setOutputProperty(OutputKeys.INDENT, "yes"); xformer.transform(source, result); */ } catch (TransformerException e) { throw new XMLConfigException("Error in save", e); } catch (UnsupportedEncodingException e) { throw new XMLConfigException("Error in save", e); } }
From source file:io.kahu.hawaii.util.logger.DefaultLogManager.java
@Override public String prettyPrintXml(final String s) { try {//w w w . ja v a 2 s . c o m if (s == null) { return null; } if (!looksLikeXml(s)) { return s; } Source xmlInput = new StreamSource(new StringReader(s)); StringWriter stringWriter = new StringWriter(); StreamResult xmlOutput = new StreamResult(stringWriter); TransformerFactory transformerFactory = TransformerFactory.newInstance(); transformerFactory.setAttribute("indent-number", 2); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.transform(xmlInput, xmlOutput); return xmlOutput.getWriter().toString(); } catch (Throwable t) { return s; } }
From source file:com.amalto.core.plugin.base.xslt.XSLTTransformerPluginBean.java
/** * @throws XtentisException// w w w .j a va2 s . c om * * @ejb.interface-method view-type = "local" * @ejb.facade-method */ public void init(TransformerPluginContext context, String compiledParameters) throws XtentisException { try { if (!configurationLoaded) { loadConfiguration(); } // fetech the parameters CompiledParameters parameters = CompiledParameters.deserialize(compiledParameters); // get the xslt compiled style sheet and the Transformer /** * Unfortunately this does not work for the moment PreparedStylesheet preparedStyleSheet * =parameters.getPreparedStyleSheet(); Transformer transformer = preparedStyleSheet.newTransformer(); **/ // As a replacement in the meantime setCompilationErrors(""); //$NON-NLS-1$ // USE SAXON for XSLT 2.0 Support TransformerFactory transFactory = new net.sf.saxon.TransformerFactoryImpl(); transFactory.setErrorListener(new ErrorListener() { public void error(TransformerException exception) throws TransformerException { add2CompilationErrors(exception.getLocalizedMessage()); } public void fatalError(TransformerException exception) throws TransformerException { add2CompilationErrors(exception.getLocalizedMessage()); } public void warning(TransformerException exception) throws TransformerException { String err = "XSLT Plugin: Warning during the compilation of the XSLT"; //$NON-NLS-1$ LOG.warn(err, exception); } }); transFactory.setAttribute(FeatureKeys.VERSION_WARNING, Boolean.valueOf(false)); if (!"".equals(getCompilationErrors())) { //$NON-NLS-1$ String err = "XSLT Plugin: Errors occurred during the compilation of the XSLT:" //$NON-NLS-1$ + getCompilationErrors(); LOG.error(err); throw new XtentisException(err); } Transformer transformer = transFactory .newTransformer(new StreamSource(new StringReader(parameters.getXslt()))); // Pass Parameters to the XSLT processor String username = LocalUser.getLocalUser().getUsername(); transformer.setParameter("USERNAME", username); //$NON-NLS-1$ transformer.setErrorListener(new ErrorListener() { public void error(TransformerException exception) throws TransformerException { String err = "XSLT Plugin: An error occured during the XSLT transformation"; //$NON-NLS-1$ LOG.error(err, exception); throw new TransformerException(err); } public void fatalError(TransformerException exception) throws TransformerException { String err = "XSLT Plugin: A fatal error occured during the XSLT transformation"; //$NON-NLS-1$ LOG.error(err, exception); throw new TransformerException(err); } public void warning(TransformerException exception) throws TransformerException { String err = "XSLT Plugin: Warning during the XSLT transformation"; //$NON-NLS-1$ LOG.warn(err, exception); } }); // Insert all this in the context context.put(TRANSFORMER, transformer); context.put(OUTPUT_METHOD, parameters.getOutputMethod()); } catch (Exception e) { String err = compilationErrors; if (err == null || err.length() == 0) { err = "Could not init the XSLT Plugin"; //$NON-NLS-1$ } LOG.error(err, e); throw new XtentisException(err); } }