List of usage examples for javax.xml.transform TransformerFactory setAttribute
public abstract void setAttribute(String name, Object value);
From source file:jef.tools.XMLUtils.java
private static void output(Node node, StreamResult sr, String encoding, int indent, Boolean XmlDeclarion) throws IOException { if (node.getNodeType() == Node.ATTRIBUTE_NODE) { sr.getWriter().write(node.getNodeValue()); sr.getWriter().flush();//from w w w. j a v a 2 s . c o m return; } TransformerFactory tf = TransformerFactory.newInstance(); Transformer t = null; try { if (indent > 0) { try { tf.setAttribute("indent-number", indent); t = tf.newTransformer(); // ?XML??XML? t.setOutputProperty(OutputKeys.INDENT, "yes"); } catch (Exception e) { } } else { t = tf.newTransformer(); } t.setOutputProperty(OutputKeys.METHOD, "xml"); if (encoding != null) { t.setOutputProperty(OutputKeys.ENCODING, encoding); } if (XmlDeclarion == null) { XmlDeclarion = (node instanceof Document); } if (node instanceof Document) { Document doc = (Document) node; if (doc.getDoctype() != null) { t.setOutputProperty(javax.xml.transform.OutputKeys.DOCTYPE_PUBLIC, doc.getDoctype().getPublicId()); t.setOutputProperty(javax.xml.transform.OutputKeys.DOCTYPE_SYSTEM, doc.getDoctype().getSystemId()); } } if (XmlDeclarion) { t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); } else { t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); } } catch (Exception tce) { throw new IOException(tce); } DOMSource doms = new DOMSource(node); try { t.transform(doms, sr); } catch (TransformerException te) { IOException ioe = new IOException(); ioe.initCause(te); throw ioe; } }
From source file:com.cloud.network.resource.PaloAltoResource.java
private String prettyFormat(String input) { int indent = 4; try {/*from w ww .j a va 2 s .co m*/ Source xmlInput = new StreamSource(new StringReader(input)); StringWriter stringWriter = new StringWriter(); StreamResult xmlOutput = new StreamResult(stringWriter); TransformerFactory transformerFactory = TransformerFactory.newInstance(); transformerFactory.setAttribute("indent-number", indent); 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 e) { try { Source xmlInput = new StreamSource(new StringReader(input)); StringWriter stringWriter = new StringWriter(); StreamResult xmlOutput = new StreamResult(stringWriter); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", String.valueOf(indent)); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.transform(xmlInput, xmlOutput); return xmlOutput.getWriter().toString(); } catch (Throwable t) { return input; } } }
From source file:net.sourceforge.eclipsetrader.core.internal.XMLRepository.java
void saveDocument(Document document, String path, String name) { try {/*from w ww. j ava 2s . c om*/ 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, "UTF-8"); //$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(), 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:net.sourceforge.pmd.RuleSetWriter.java
public void write(RuleSet ruleSet) { try {//w ww .j av a 2 s . c o m DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); document = documentBuilder.newDocument(); ruleSetFileNames = new HashSet<>(); Element ruleSetElement = createRuleSetElement(ruleSet); document.appendChild(ruleSetElement); TransformerFactory transformerFactory = TransformerFactory.newInstance(); try { transformerFactory.setAttribute("indent-number", 3); } catch (IllegalArgumentException iae) { // ignore it, specific to one parser LOG.log(Level.FINE, "Couldn't set indentation", iae); } Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); // This is as close to pretty printing as we'll get using standard // Java APIs. transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.transform(new DOMSource(document), new StreamResult(outputStream)); } catch (DOMException e) { throw new RuntimeException(e); } catch (FactoryConfigurationError e) { throw new RuntimeException(e); } catch (ParserConfigurationException e) { throw new RuntimeException(e); } catch (TransformerException e) { throw new RuntimeException(e); } }
From source file:org.apache.hadoop.corona.ConfigManager.java
/** * Generate the new pools configuration using the configuration generator. * The generated configuration is written to a temporary file and then * atomically renamed to the specified destination file. * This function may be called concurrently and it is safe to do so because * of the atomic rename to the destination file. * * @return Md5 of the generated file or null if generation failed. *//*w w w. ja va 2 s.c o m*/ public String generatePoolsConfigIfClassSet() { if (poolsConfigDocumentGenerator == null) { return null; } Document document = poolsConfigDocumentGenerator.generatePoolsDocument(); if (document == null) { LOG.warn("generatePoolsConfig: Did not generate a valid pools xml file"); return null; } // Write the content into a temporary xml file and rename to the // expected file. File tempXmlFile; try { TransformerFactory transformerFactory = TransformerFactory.newInstance(); transformerFactory.setAttribute("indent-number", new Integer(2)); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); DOMSource source = new DOMSource(document); tempXmlFile = File.createTempFile("tmpPoolsConfig", "xml"); if (LOG.isDebugEnabled()) { StreamResult stdoutResult = new StreamResult(System.out); transformer.transform(source, stdoutResult); } StreamResult result = new StreamResult(tempXmlFile); transformer.transform(source, result); String md5 = org.apache.commons.codec.digest.DigestUtils.md5Hex(new FileInputStream(tempXmlFile)); File destXmlFile = new File(conf.getPoolsConfigFile()); boolean success = tempXmlFile.renameTo(destXmlFile); LOG.info("generatePoolConfig: Renamed generated file " + tempXmlFile.getAbsolutePath() + " to " + destXmlFile.getAbsolutePath() + " returned " + success + " with md5sum " + md5); return md5; } catch (TransformerConfigurationException e) { LOG.warn("generatePoolConfig: Failed to write file", e); } catch (IOException e) { LOG.warn("generatePoolConfig: Failed to write file", e); } catch (TransformerException e) { LOG.warn("generatePoolConfig: Failed to write file", e); } return null; }
From source file:org.apache.hadoop.gateway.filter.rewrite.impl.xml.XmlUrlRewriteRulesExporter.java
@Override public void store(UrlRewriteRulesDescriptor descriptor, Writer writer) throws IOException { try {// w w w . j av a2s . c om DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = builderFactory.newDocumentBuilder(); Document document = builder.newDocument(); document.setXmlStandalone(true); Element root = document.createElement(ROOT); document.appendChild(root); if (!descriptor.getFunctions().isEmpty()) { Element functionsElement = document.createElement(FUNCTIONS); root.appendChild(functionsElement); for (UrlRewriteFunctionDescriptor function : descriptor.getFunctions()) { Element functionElement = createElement(document, function.name(), function); functionsElement.appendChild(functionElement); } } if (!descriptor.getRules().isEmpty()) { for (UrlRewriteRuleDescriptor rule : descriptor.getRules()) { Element ruleElement = createRule(document, rule); root.appendChild(ruleElement); } } if (!descriptor.getFilters().isEmpty()) { for (UrlRewriteFilterDescriptor filter : descriptor.getFilters()) { Element filterElement = createFilter(document, filter); root.appendChild(filterElement); } } TransformerFactory transformerFactory = TransformerFactory.newInstance(); transformerFactory.setAttribute("indent-number", 2); Transformer transformer = transformerFactory.newTransformer(); //transformer.setOutputProperty( OutputKeys.OMIT_XML_DECLARATION, "yes" ); transformer.setOutputProperty(OutputKeys.STANDALONE, "yes"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); StreamResult result = new StreamResult(writer); DOMSource source = new DOMSource(document); transformer.transform(source, result); } catch (ParserConfigurationException e) { throw new IOException(e); } catch (TransformerException e) { throw new IOException(e); } catch (InvocationTargetException e) { LOG.failedToWriteRulesDescriptor(e); } catch (NoSuchMethodException e) { LOG.failedToWriteRulesDescriptor(e); } catch (IntrospectionException e) { LOG.failedToWriteRulesDescriptor(e); } catch (IllegalAccessException e) { LOG.failedToWriteRulesDescriptor(e); } }
From source file:org.apache.openaz.xacml.std.dom.DOMUtil.java
public static String toString(Document document) throws DOMStructureException { try {//from w w w . j av a 2s .c om TransformerFactory transformerFactory = TransformerFactory.newInstance(); transformerFactory.setAttribute("indent-number", new Integer(4)); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); Source source = new DOMSource(document); StringWriter stringOut = new StringWriter(); Result result = new StreamResult(stringOut); transformer.transform(source, result); return stringOut.toString(); } catch (Exception ex) { throw new DOMStructureException(document, "Exception converting Document to a String", ex); } }
From source file:org.apache.solr.common.cloud.SolrZkClient.java
public static String prettyPrint(String input, int indent) { try {//from w w w . j a v a 2 s .co m Source xmlInput = new StreamSource(new StringReader(input)); StringWriter stringWriter = new StringWriter(); StreamResult xmlOutput = new StreamResult(stringWriter); TransformerFactory transformerFactory = TransformerFactory.newInstance(); transformerFactory.setAttribute("indent-number", indent); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.transform(xmlInput, xmlOutput); return xmlOutput.getWriter().toString(); } catch (Exception e) { throw new RuntimeException("Problem pretty printing XML", e); } }
From source file:org.apache.usergrid.tools.ApiDoc.java
public void output(ApiListing listing, String section) throws IOException, TransformerException { Document doc = listing.createWADLApplication(); TransformerFactory transformerFactory = TransformerFactory.newInstance(); transformerFactory.setAttribute("indent-number", 4); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File(section + ".wadl")); transformer.transform(source, result); File file = new File(section + ".json"); listing.setBasePath("${basePath}"); FileUtils.write(file, JsonUtils.mapToFormattedJsonString(listing)); }
From source file:org.apereo.portal.utils.cache.resource.TemplatesBuilder.java
@Override public LoadedResource<Templates> loadResource(Resource resource) throws IOException { final TransformerFactory transformerFactory = TransformerFactory.newInstance(); if (this.transformerAttributes != null) { for (final Map.Entry<String, Object> attributeEntry : this.transformerAttributes.entrySet()) { transformerFactory.setAttribute(attributeEntry.getKey(), attributeEntry.getValue()); }// w w w . ja v a 2s . com } final ResourceTrackingURIResolver uriResolver = new ResourceTrackingURIResolver(this.resourceLoader); transformerFactory.setURIResolver(uriResolver); final URI uri = resource.getURI(); final String systemId = uri.toString(); final InputStream stream = resource.getInputStream(); final Templates templates; try { final StreamSource source = new StreamSource(stream, systemId); templates = transformerFactory.newTemplates(source); } catch (TransformerConfigurationException e) { throw new IOException("Failed to parse stream into Templates", e); } finally { IOUtils.closeQuietly(stream); } final Map<Resource, Long> resolvedResources = uriResolver.getResolvedResources(); return new LoadedResourceImpl<Templates>(templates, resolvedResources); }