List of usage examples for javax.xml.transform TransformerFactory setAttribute
public abstract void setAttribute(String name, Object value);
From source file:org.automagic.deps.doctor.Utils.java
public static Node prettyFormat(Node node, int indentSize, boolean indentWithTabs) { if (indentSize < 1) { throw new IllegalArgumentException("Indentation size must be greater or equal to 1"); }/*from w w w. j av a2 s.co m*/ try { Source xmlInput = new DOMSource(node); StringWriter stringWriter = new StringWriter(); StreamResult xmlOutput = new StreamResult(stringWriter); TransformerFactory transformerFactory = TransformerFactory.newInstance(); transformerFactory.setAttribute("indent-number", indentSize); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.transform(xmlInput, xmlOutput); String result = xmlOutput.getWriter().toString(); if (indentWithTabs) { StringBuilder sb = new StringBuilder(result); Matcher matcher = INDENT_PATTERN.matcher(result); while (matcher.find()) { sb.setCharAt(matcher.start(), '\t'); } result = sb.toString(); } Document parse = DOC_BUILDER.get().parse(new ByteArrayInputStream(result.getBytes())); Node importNode = node.getOwnerDocument().importNode(parse.getDocumentElement(), true); return importNode; } catch (TransformerException | SAXException | IOException e) { throw new RuntimeException(e); } }
From source file:org.carewebframework.common.XMLUtil.java
/** * Converts an XML document to a formatted XML string. * * @param doc The document to format./*from w w w . ja va2 s . c om*/ * @param indent Number of characters to indent. * @return Formatted XML document. */ public static String toString(Document doc, int indent) { if (doc == null) { return ""; } try { DOMSource domSource = new DOMSource(doc); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); TransformerFactory tf = TransformerFactory.newInstance(); try { tf.setAttribute("indent-number", indent); } catch (IllegalArgumentException e) { // Ignore if not supported. } Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", Integer.toString(indent)); transformer.transform(domSource, result); return writer.toString(); } catch (Exception e) { throw MiscUtil.toUnchecked(e); } }
From source file:org.eclim.plugin.core.command.xml.FormatCommand.java
/** * {@inheritDoc}// ww w. j a v a 2 s .co m */ public String execute(CommandLine commandLine) throws Exception { String restoreNewline = null; FileInputStream in = null; try { String file = commandLine.getValue(Options.FILE_OPTION); //int lineWidth = commandLine.getIntValue(Options.LINE_WIDTH_OPTION); int indent = commandLine.getIntValue(Options.INDENT_OPTION); String format = commandLine.getValue("m"); // set the line separator if necessary String newline = System.getProperty("line.separator"); if (newline.equals("\r\n") && format.equals("unix")) { restoreNewline = newline; System.setProperty("line.separator", "\n"); } else if (newline.equals("\n") && format.equals("dos")) { restoreNewline = newline; System.setProperty("line.separator", "\r\n"); } // javax.xml.transform (indentation issues) TransformerFactory factory = TransformerFactory.newInstance(); factory.setAttribute("indent-number", Integer.valueOf(indent)); Transformer serializer = factory.newTransformer(); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); // broken in 1.5 /*serializer.setOutputProperty( "{http://xml.apache.org/xslt}indent-amount", String.valueOf(indent)); in = new FileInputStream(file); serializer.transform(new SAXSource(new InputSource(in)), new StreamResult(getContext().out));*/ in = new FileInputStream(file); serializer.transform(new SAXSource(new InputSource(in)), new StreamResult(new OutputStreamWriter(getContext().out, "utf-8"))); return StringUtils.EMPTY; } finally { IOUtils.closeQuietly(in); if (restoreNewline != null) { System.setProperty("line.separator", restoreNewline); } } }
From source file:org.geoserver.test.GeoServerAbstractTestSupport.java
/** * Utility method to print out a dom./*from ww w . ja v a 2s . c om*/ */ protected void print(Document dom) throws Exception { TransformerFactory txFactory = TransformerFactory.newInstance(); try { txFactory.setAttribute("{http://xml.apache.org/xalan}indent-number", new Integer(2)); } catch (Exception e) { // some } Transformer tx = txFactory.newTransformer(); tx.setOutputProperty(OutputKeys.METHOD, "xml"); tx.setOutputProperty(OutputKeys.INDENT, "yes"); tx.transform(new DOMSource(dom), new StreamResult(new OutputStreamWriter(System.out, "utf-8"))); }
From source file:org.giavacms.base.common.util.HtmlUtils.java
public static String prettyXml(String code) { if (code == null) { code = ""; }// w w w .j a v a 2 s . co m try { TransformerFactory transformerFactory = TransformerFactory.newInstance(); transformerFactory.setAttribute("indent-number", 4); Transformer transformer; transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); StreamResult result = new StreamResult(new StringWriter()); StreamSource source = new StreamSource(new StringReader(code)); transformer.transform(source, result); return result.getWriter().toString(); } catch (TransformerConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TransformerException e) { // TODO Auto-generated catch block e.printStackTrace(); } return ""; }
From source file:org.ikasan.filetransfer.xml.transform.DefaultXSLTransformer.java
/** * Creates a new <code>TransformerFactory</code> instance, * sets the default error listener, sets debugging flag on if necessary * and finally returns the instance.//from ww w . ja v a 2 s .co m * * @return new TransformerFactory instance */ private TransformerFactory newTransformerFactory() { // Get a new TransformerFactory instance TransformerFactory tFactory = TransformerFactory.newInstance(); //logger.debug("Setting auto-translet to true..."); //tFactory.setAttribute("auto-translet", Boolean.TRUE); if (System.getProperty(XSLT_DEBUG, "false").equalsIgnoreCase("true")) tFactory.setAttribute("debug", Boolean.TRUE); logger.debug("Setting error event listener to ErrorListener..."); tFactory.setErrorListener(new DefaultErrorListener()); return tFactory; }
From source file:org.kalypso.kalypsosimulationmodel.utils.SLDHelper.java
private static void exportSLD(final IFile sldFile, final StyledLayerDescriptor descriptor, final IProgressMonitor progressMonitor) throws IOException, SAXException, CoreException { // FIXME: ugly! The bug is elsewhere! if (!sldFile.isSynchronized(IResource.DEPTH_ZERO)) sldFile.refreshLocal(IResource.DEPTH_ZERO, new NullProgressMonitor()); final ByteArrayInputStream stream = new ByteArrayInputStream(descriptor.exportAsXML().getBytes("UTF-8")); //$NON-NLS-1$ final Document doc = XMLTools.parse(stream); final Source source = new DOMSource(doc); final SetContentHelper helper = new SetContentHelper() { @Override/*from w ww . j a va2 s . co m*/ protected void write(final OutputStreamWriter writer) throws Throwable { try { final StreamResult result = new StreamResult(writer); final TransformerFactory factory = TransformerFactory.newInstance(); // Comment from Dejan: this works only with Java 1.5, in 1.4 it throws IllegalArgumentException // also, indentation doesn't works with OutputStream, only with OutputStreamWriter :) try { factory.setAttribute("indent-number", new Integer(4)); //$NON-NLS-1$ } catch (final IllegalArgumentException e) { } final Transformer transformer = factory.newTransformer(); transformer.setOutputProperty(OutputKeys.ENCODING, writer.getEncoding()); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$ // transformer.setOutputProperty( "{http://xml.apache.org/xslt}indent-amount", "2" ); // //$NON-NLS-1$ // //$NON-NLS-2$ // transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$ // transformer.setOutputProperty(OutputKeys.MEDIA_TYPE, "text/xml"); //$NON-NLS-1$ //$NON-NLS-2$ transformer.transform(source, result); } finally { IOUtils.closeQuietly(writer); } } }; if (progressMonitor.isCanceled()) throw new CoreException(Status.CANCEL_STATUS); helper.setFileContents(sldFile, false, false, progressMonitor); }
From source file:org.openbravo.erpCommon.ad_forms.TranslationManager.java
/** * Exports a single trl table in a xml file * /* w w w.j a v a 2 s . c om*/ * @param AD_Language * Language to export * @param exportReferenceData * Defines whether exporting reference data * @param exportAll * In case it is reference data if it should be exported all data or just imported * @param table * Base table * @param tableID * Base table id * @param rootDirectory * Root directory to the the exportation * @param moduleId * Id for the module to export to * @param moduleLanguage * Base language for the module * @param javaPackage * Java package for the module */ private static void exportTable(ConnectionProvider cp, String AD_Language, boolean exportReferenceData, boolean exportAll, String table, String tableID, String rootDirectory, String moduleId, String moduleLanguage, String javaPackage, boolean trl) { Statement st = null; StringBuffer sql = null; try { String trlTable = table; if (trl && !table.endsWith("_TRL")) trlTable = table + "_TRL"; final TranslationData[] trlColumns = getTrlColumns(cp, table); final String keyColumn = table + "_ID"; boolean m_IsCentrallyMaintained = false; try { m_IsCentrallyMaintained = !(TranslationData.centrallyMaintained(cp, table).equals("0")); if (m_IsCentrallyMaintained) log4j.debug("table:" + table + " IS centrally maintained"); else log4j.debug("table:" + table + " is NOT centrally maintained"); } catch (final Exception e) { log4j.error("getTrlColumns (IsCentrallyMaintained)", e); } // Prepare query to retrieve translated rows sql = new StringBuffer("SELECT "); if (trl) sql.append("t.IsTranslated,"); else sql.append("'N', "); sql.append("t.").append(keyColumn); for (int i = 0; i < trlColumns.length; i++) { sql.append(", t.").append(trlColumns[i].c).append(",o.").append(trlColumns[i].c).append(" AS ") .append(trlColumns[i].c).append("O"); } sql.append(" FROM ").append(trlTable).append(" t").append(", ").append(table).append(" o"); if (exportReferenceData && !exportAll) { sql.append(", AD_REF_DATA_LOADED DL"); } sql.append(" WHERE "); if (trl) sql.append("t.AD_Language='" + AD_Language + "'").append(" AND "); sql.append("o.").append(keyColumn).append("= t.").append(keyColumn); if (m_IsCentrallyMaintained) { sql.append(" AND ").append("o.IsCentrallyMaintained='N'"); } // AdClient !=0 not supported sql.append(" AND o.AD_Client_ID='0' "); if (!exportReferenceData) { String tempTrlTableName = trlTable; if (!tempTrlTableName.toLowerCase().endsWith("_trl")) { tempTrlTableName = tempTrlTableName + "_Trl"; } final TranslationData[] parentTable = TranslationData.parentTable(cp, tempTrlTableName); if (parentTable.length == 0) { sql.append(" AND ").append(" o.ad_module_id='").append(moduleId).append("'"); } else { /** Search for ad_module_id in the parent table */ if (StringUtils.isEmpty(parentTable[0].grandparent)) { String strParentTable = parentTable[0].tablename; sql.append(" AND "); sql.append(" exists ( select 1 from ").append(strParentTable).append(" p "); sql.append(" where p.").append(strParentTable + "_ID").append("=") .append("o." + strParentTable + "_ID"); sql.append(" and p.ad_module_id='").append(moduleId).append("')"); } else { String strParentTable = parentTable[0].tablename; String strGandParentTable = parentTable[0].grandparent; sql.append(" AND "); sql.append(" exists ( select 1 from ").append(strGandParentTable).append(" gp, ") .append(strParentTable).append(" p"); sql.append(" where p.").append(strParentTable + "_ID").append("=") .append("o." + strParentTable + "_ID"); sql.append(" and p." + strGandParentTable + "_ID = gp." + strGandParentTable + "_ID"); sql.append(" and gp.ad_module_id='").append(moduleId).append("')"); } } } if (exportReferenceData && !exportAll) { sql.append(" AND DL.GENERIC_ID = o.").append(keyColumn).append(" AND DL.AD_TABLE_ID = '") .append(tableID).append("'").append(" AND DL.AD_MODULE_ID = '").append(moduleId) .append("'"); } sql.append(" ORDER BY t.").append(keyColumn); // if (log4j.isDebugEnabled()) log4j.debug("SQL:" + sql.toString()); st = cp.getStatement(); if (log4j.isDebugEnabled()) log4j.debug("st"); final ResultSet rs = st.executeQuery(sql.toString()); if (log4j.isDebugEnabled()) log4j.debug("rs"); int rows = 0; boolean hasRows = false; DocumentBuilderFactory factory = null; DocumentBuilder builder = null; Document document = null; Element root = null; File out = null; // Create xml file String directory = ""; factory = DocumentBuilderFactory.newInstance(); builder = factory.newDocumentBuilder(); document = builder.newDocument(); // Root root = document.createElement(XML_TAG); root.setAttribute(XML_ATTRIBUTE_LANGUAGE, AD_Language); root.setAttribute(XML_ATTRIBUTE_TABLE, table); root.setAttribute(XML_ATTRIBUTE_BASE_LANGUAGE, moduleLanguage); root.setAttribute(XML_ATTRIBUTE_VERSION, TranslationData.version(cp)); document.appendChild(root); if (moduleId.equals("0")) directory = rootDirectory + AD_Language + "/"; else directory = rootDirectory + AD_Language + "/" + javaPackage + "/"; if (!new File(directory).exists()) (new File(directory)).mkdir(); String fileName = directory + trlTable + "_" + AD_Language + ".xml"; log4j.info("exportTrl - " + fileName); out = new File(fileName); while (rs.next()) { if (!hasRows && !exportReferenceData) { // Create file only in // case it has contents // or it is not rd hasRows = true; factory = DocumentBuilderFactory.newInstance(); builder = factory.newDocumentBuilder(); document = builder.newDocument(); // Root root = document.createElement(XML_TAG); root.setAttribute(XML_ATTRIBUTE_LANGUAGE, AD_Language); root.setAttribute(XML_ATTRIBUTE_TABLE, table); root.setAttribute(XML_ATTRIBUTE_BASE_LANGUAGE, moduleLanguage); root.setAttribute(XML_ATTRIBUTE_VERSION, TranslationData.version(cp)); document.appendChild(root); if (moduleId.equals("0")) directory = rootDirectory + AD_Language + "/"; else directory = rootDirectory + AD_Language + "/" + javaPackage + "/"; if (!new File(directory).exists()) (new File(directory)).mkdir(); fileName = directory + trlTable + "_" + AD_Language + ".xml"; log4j.info("exportTrl - " + fileName); out = new File(fileName); } final Element row = document.createElement(XML_ROW_TAG); row.setAttribute(XML_ROW_ATTRIBUTE_ID, String.valueOf(rs.getString(2))); // KeyColumn row.setAttribute(XML_ROW_ATTRIBUTE_TRANSLATED, rs.getString(1)); // IsTranslated for (int i = 0; i < trlColumns.length; i++) { final Element value = document.createElement(XML_VALUE_TAG); value.setAttribute(XML_VALUE_ATTRIBUTE_COLUMN, trlColumns[i].c); String origString = rs.getString(trlColumns[i].c + "O"); // Original String isTrlString = "Y"; // Value if (origString == null) { origString = ""; isTrlString = "N"; } String valueString = rs.getString(trlColumns[i].c); // Value if (valueString == null) { valueString = ""; isTrlString = "N"; } if (origString.equals(valueString)) isTrlString = "N"; value.setAttribute(XML_VALUE_ATTRIBUTE_ISTRL, isTrlString); value.setAttribute(XML_VALUE_ATTRIBUTE_ORIGINAL, origString); value.appendChild(document.createTextNode(valueString)); row.appendChild(value); } root.appendChild(row); rows++; } rs.close(); log4j.info("exportTrl - Records=" + rows + ", DTD=" + document.getDoctype()); final DOMSource source = new DOMSource(document); final TransformerFactory tFactory = TransformerFactory.newInstance(); tFactory.setAttribute("indent-number", new Integer(2)); final Transformer transformer = tFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // Output out.createNewFile(); // Transform final OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(out), "UTF-8"); transformer.transform(source, new StreamResult(osw)); osw.close(); } catch (final Exception e) { log4j.error("Error exporting translation for table " + table + "\n" + sql, e); } finally { try { if (st != null) cp.releaseStatement(st); } catch (final Exception ignored) { } } }
From source file:org.pepstock.jem.ant.validator.transformer.TransformerValidator.java
/** * Inits the transformer, load the xslt and validate it, load jem properties * During the transformation, the transformer onbject is locked, so the file * listner is inhibited to do a refresh. * /*w w w . ja v a2 s.co m*/ * @param xsltvalidatorFile the xslt file * @return the transformer * @throws ValidationException the validation exception */ private Transformer createTransformer(String xsltvalidatorFile) throws ValidationException { Transformer t = null; // Instantiate a TransformerFactory TransformerFactory tFactory = TransformerFactory.newInstance(); // add error listner to capture validation error. ErrorListener tfel = new TransformerFactoryErrorListener(); tFactory.setErrorListener(tfel); // check the transformer compliant if (!tFactory.getFeature(SAXTransformerFactory.FEATURE)) { throw new ValidationException(AntMessage.JEMA050E.toMessage().getFormattedMessage()); } // activate xalan extension NodeInfo to map source xml code position tFactory.setAttribute(TransformerFactoryImpl.FEATURE_SOURCE_LOCATION, Boolean.TRUE); StreamSource ss = new StreamSource(xsltvalidatorFile); try { // A Transformer may be used multiple times. // Parameters and output properties are preserved across // transformations. t = tFactory.newTransformer(ss); } catch (TransformerConfigurationException e) { throw new ValidationException(AntMessage.JEMA047E.toMessage().getFormattedMessage(e.getMessage()), e); } // add custom error listener, necessary to avoid internal catch // of exception throwed by xslt ErrorListener el = new TransformerErrorListener(); t.setErrorListener(el); // pass the parameter list to the xslt for (Object key : System.getProperties().keySet()) { String keyString = key.toString(); String value = System.getProperty(keyString); t.setParameter(keyString, value); } for (String key : System.getenv().keySet()) { String value = System.getenv().get(key); t.setParameter(key, value); } return t; }
From source file:org.toobsframework.transformpipeline.domain.BaseXMLTransformer.java
public void init() { if (uriResolver == null) { throw new RuntimeException("uriResolver property must be set"); }//from w w w . j a v a 2 s .c o m TransformerFactory tFactory = TransformerFactory.newInstance(); setFactoryResolver(tFactory); tFactory.setAttribute("http://xml.apache.org/xalan/features/incremental", java.lang.Boolean.TRUE); if (tFactory.getFeature(SAXSource.FEATURE) && tFactory.getFeature(SAXResult.FEATURE)) { // Cast the TransformerFactory to SAXTransformerFactory. saxTFactory = ((SAXTransformerFactory) tFactory); } if (outputProperties == null) { outputProperties = OutputPropertiesFactory.getDefaultMethodProperties("html"); } templateCache = new ConcurrentHashMap<String, Templates>(); }