List of usage examples for javax.xml.transform TransformerFactory setAttribute
public abstract void setAttribute(String name, Object value);
From source file:Main.java
/** * Configures a {@link TransformerFactory} to protect it against XML * External Entity attacks.//from w w w. j a v a 2 s. c o m * @param factory the factory * @see <a href= * "https://www.owasp.org/index.php/XML_External_Entity_%28XXE%29_Prevention_Cheat_Sheet#Java"> * XXE Cheat Sheet</a> */ public static void applyXXEProtection(TransformerFactory factory) { //@formatter:off String[] attributes = { //XMLConstants.ACCESS_EXTERNAL_DTD (Java 7 only) "http://javax.xml.XMLConstants/property/accessExternalDTD", //XMLConstants.ACCESS_EXTERNAL_STYLESHEET (Java 7 only) "http://javax.xml.XMLConstants/property/accessExternalStylesheet" }; //@formatter:on for (String attribute : attributes) { try { factory.setAttribute(attribute, ""); } catch (IllegalArgumentException e) { //attribute is not supported by the local XML engine, skip it } } }
From source file:com.hangum.tadpole.engine.sql.util.QueryUtils.java
/** * execute DML/*w w w. jav a2 s .c o m*/ * * @param userDB * @param strQuery * @param listParam * @param resultType * @throws Exception */ public static String executeDML(final UserDBDAO userDB, final String strQuery, final List<Object> listParam, final String resultType) throws Exception { SqlMapClient client = TadpoleSQLManager.getInstance(userDB); Object effectObject = runSQLOther(userDB, strQuery, listParam); String strReturn = ""; if (resultType.equals(RESULT_TYPE.CSV.name())) { final StringWriter stWriter = new StringWriter(); CSVWriter csvWriter = new CSVWriter(stWriter, ','); String[] arryString = new String[2]; arryString[0] = "effectrow"; arryString[1] = String.valueOf(effectObject); csvWriter.writeNext(arryString); strReturn = stWriter.toString(); } else if (resultType.equals(RESULT_TYPE.JSON.name())) { final JsonArray jsonArry = new JsonArray(); JsonObject jsonObj = new JsonObject(); jsonObj.addProperty("effectrow", String.valueOf(effectObject)); jsonArry.add(jsonObj); strReturn = JSONUtil.getPretty(jsonArry.toString()); } else {//if(resultType.equals(RESULT_TYPE.XML.name())) { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); final Document doc = builder.newDocument(); final Element results = doc.createElement("Results"); doc.appendChild(results); Element row = doc.createElement("Row"); results.appendChild(row); Element node = doc.createElement("effectrow"); node.appendChild(doc.createTextNode(String.valueOf(effectObject))); row.appendChild(node); DOMSource domSource = new DOMSource(doc); TransformerFactory tf = TransformerFactory.newInstance(); tf.setAttribute("indent-number", 4); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); final StringWriter stWriter = new StringWriter(); StreamResult sr = new StreamResult(stWriter); transformer.transform(domSource, sr); strReturn = stWriter.toString(); } return strReturn; }
From source file:com.azaptree.services.command.http.handler.CommandServiceHandlerTest.java
public static String prettyFormat(final String input, final int indent) { try {//from www . ja v a 2 s .co m final Source xmlInput = new StreamSource(new StringReader(input)); final StringWriter stringWriter = new StringWriter(); final StreamResult xmlOutput = new StreamResult(stringWriter); final TransformerFactory transformerFactory = TransformerFactory.newInstance(); transformerFactory.setAttribute("indent-number", indent); final Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.transform(xmlInput, xmlOutput); return xmlOutput.getWriter().toString(); } catch (final Exception e) { throw new RuntimeException(e); // simple exception handling, please review it } }
From source file:Main.java
public static String getFormattedXml(String xmlString) { // /////////////////////////////////////////////////////////////// // Declarations // /////////////////////////////////////////////////////////////// Source xmlInput = null;/*from ww w .j a va 2 s .c om*/ StringWriter stringWriter = null; StreamResult xmlOutput = null; TransformerFactory transformerFactory = null; Transformer transformer = null; String formattedXml = null; // /////////////////////////////////////////////////////////////// // Code // /////////////////////////////////////////////////////////////// try { xmlInput = new StreamSource(new StringReader(xmlString)); stringWriter = new StringWriter(); xmlOutput = new StreamResult(stringWriter); transformerFactory = TransformerFactory.newInstance(); transformerFactory.setAttribute("indent-number", 4); transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.transform(xmlInput, xmlOutput); formattedXml = xmlOutput.getWriter().toString(); } catch (Exception e) { // To Do: Handle Exception.. } return formattedXml; }
From source file:net.sourceforge.eclipsetrader.charts.ChartsPlugin.java
public static void saveDefaultChart(Chart chart) { Log logger = LogFactory.getLog(ChartsPlugin.class); SimpleDateFormat dateTimeFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); //$NON-NLS-1$ try {//from w w w. j a va 2 s .com DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document document = builder.getDOMImplementation().createDocument(null, "chart", null); //$NON-NLS-1$ Element root = document.getDocumentElement(); Element node = document.createElement("title"); //$NON-NLS-1$ node.appendChild(document.createTextNode(chart.getTitle())); root.appendChild(node); node = document.createElement("compression"); //$NON-NLS-1$ node.appendChild(document.createTextNode(String.valueOf(chart.getCompression()))); root.appendChild(node); node = document.createElement("period"); //$NON-NLS-1$ node.appendChild(document.createTextNode(String.valueOf(chart.getPeriod()))); root.appendChild(node); node = document.createElement("autoScale"); //$NON-NLS-1$ node.appendChild(document.createTextNode(String.valueOf(chart.isAutoScale()))); root.appendChild(node); if (chart.getBeginDate() != null) { node = document.createElement("begin"); //$NON-NLS-1$ node.appendChild(document.createTextNode(dateTimeFormat.format(chart.getBeginDate()))); root.appendChild(node); } if (chart.getEndDate() != null) { node = document.createElement("end"); //$NON-NLS-1$ node.appendChild(document.createTextNode(dateTimeFormat.format(chart.getEndDate()))); root.appendChild(node); } for (int r = 0; r < chart.getRows().size(); r++) { ChartRow row = (ChartRow) chart.getRows().get(r); row.setId(new Integer(r)); Element rowNode = document.createElement("row"); //$NON-NLS-1$ root.appendChild(rowNode); for (int t = 0; t < row.getTabs().size(); t++) { ChartTab tab = (ChartTab) row.getTabs().get(t); tab.setId(new Integer(t)); Element tabNode = document.createElement("tab"); //$NON-NLS-1$ tabNode.setAttribute("label", tab.getLabel()); //$NON-NLS-1$ rowNode.appendChild(tabNode); for (int i = 0; i < tab.getIndicators().size(); i++) { ChartIndicator indicator = (ChartIndicator) tab.getIndicators().get(i); indicator.setId(new Integer(i)); Element indicatorNode = document.createElement("indicator"); //$NON-NLS-1$ indicatorNode.setAttribute("pluginId", indicator.getPluginId()); //$NON-NLS-1$ tabNode.appendChild(indicatorNode); for (Iterator iter = indicator.getParameters().keySet().iterator(); iter.hasNext();) { String key = (String) iter.next(); node = document.createElement("param"); //$NON-NLS-1$ node.setAttribute("key", key); //$NON-NLS-1$ node.setAttribute("value", (String) indicator.getParameters().get(key)); //$NON-NLS-1$ indicatorNode.appendChild(node); } } for (int i = 0; i < tab.getObjects().size(); i++) { ChartObject object = (ChartObject) tab.getObjects().get(i); object.setId(new Integer(i)); Element indicatorNode = document.createElement("object"); //$NON-NLS-1$ indicatorNode.setAttribute("pluginId", object.getPluginId()); //$NON-NLS-1$ tabNode.appendChild(indicatorNode); for (Iterator iter = object.getParameters().keySet().iterator(); iter.hasNext();) { String key = (String) iter.next(); node = document.createElement("param"); //$NON-NLS-1$ node.setAttribute("key", key); //$NON-NLS-1$ node.setAttribute("value", (String) object.getParameters().get(key)); //$NON-NLS-1$ indicatorNode.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 = ChartsPlugin.getDefault().getStateLocation().append("defaultChart.xml").toFile(); //$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.toString(), e); } }
From source file:org.apache.falcon.regression.core.util.Util.java
/** * Prints xml in readable form./* w ww. j a va 2s . c om*/ * @param xmlString xmlString * @return formatted xmlString */ public static String prettyPrintXml(final String xmlString) { if (xmlString == null) { return null; } try { Source xmlInput = new StreamSource(new StringReader(xmlString)); 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.transform(xmlInput, xmlOutput); return xmlOutput.getWriter().toString(); } catch (TransformerConfigurationException e) { return xmlString; } catch (TransformerException e) { return xmlString; } }
From source file:cross.applicationContext.ReflectionApplicationContextGenerator.java
/** * Write the given xml document to the outputFile. * * @param document the xml document/* w ww . ja v a 2 s. c om*/ * @param outputFile the output file */ public static void writeToFile(Document document, File outputFile) { try { TransformerFactory transfac = TransformerFactory.newInstance(); transfac.setAttribute("indent-number", 2); Transformer trans = transfac.newTransformer(); trans.setOutputProperty(OutputKeys.INDENT, "yes"); DOMSource domSource = new DOMSource(document); BufferedOutputStream bw = null; try { outputFile.getParentFile().mkdirs(); log.info("Writing to file {}", outputFile.getAbsolutePath()); bw = new BufferedOutputStream(new FileOutputStream(outputFile)); trans.transform(domSource, new StreamResult(new OutputStreamWriter(bw, "utf-8"))); bw.close(); } catch (IOException ex) { Logger.getLogger(ReflectionApplicationContextGenerator.class.getName()).log(Level.SEVERE, null, ex); } finally { if (bw != null) { try { bw.close(); } catch (IOException ex) { Logger.getLogger(ReflectionApplicationContextGenerator.class.getName()).log(Level.SEVERE, null, ex); } } } //System.out.println(xmlString); } catch (TransformerException ex) { Logger.getLogger(ReflectionApplicationContextGenerator.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:Compile.java
/** * Compiles an XSL stylesheet into a translet, wraps the translet * inside a Templates object and dumps it to a file. *//*w ww .j a v a 2 s . com*/ public void run(String xsl) { try { // Set XSLTC's TransformerFactory implementation as the default System.setProperty("javax.xml.transform.TransformerFactory", "org.apache.xalan.xsltc.trax.TransformerFactoryImpl"); // Get an input stream for the XSL stylesheet StreamSource stylesheet = new StreamSource(xsl); // The TransformerFactory will compile the stylesheet and // put the translet classes inside the Templates object TransformerFactory factory = TransformerFactory.newInstance(); factory.setAttribute("generate-translet", Boolean.TRUE); Templates templates = factory.newTemplates(stylesheet); } catch (Exception e) { System.err.println("Exception: " + e); e.printStackTrace(); } System.exit(0); }
From source file:Transform.java
/** * Asks the TransformerFactory to try to load a precompiled version of * the translet from the class path to construct a Transformer object. * The translet performs the transformation on behalf of the * Transformer.transform() method.//from w w w.ja v a 2 s. c o m */ public void run(String[] args) { String xml = args[0]; String transletURI = args[1]; try { // Set XSLTC's TransformerFactory implementation as the default System.setProperty("javax.xml.transform.TransformerFactory", "org.apache.xalan.xsltc.trax.TransformerFactoryImpl"); TransformerFactory tf = TransformerFactory.newInstance(); tf.setAttribute("use-classpath", Boolean.TRUE); Transformer transformer = tf.newTransformer(new StreamSource(transletURI)); StreamSource document = new StreamSource(xml); StreamResult result = new StreamResult(new OutputStreamWriter(System.out)); transformer.transform(document, result); } catch (Exception e) { System.err.println("Exception: " + e); e.printStackTrace(); } System.exit(0); }
From source file:com.pactera.edg.am.metamanager.extractor.util.ExtractorContext.java
/** * ????XSLT//www . ja va 2s .com * * @return the xsltTemplate throws Exception ?XLST */ public Templates getXsltTemplate(String xslt) throws IOException, TransformerConfigurationException { // if (!this.templates.containsKey(xslt)) { InputStream in = new DefaultResourceLoader().getResource(xslt).getInputStream(); Source xsltSource = new SAXSource(new InputSource(in)); TransformerFactory factory = TransformerFactory.newInstance(); factory.setAttribute(FeatureKeys.DTD_VALIDATION, Boolean.FALSE); //TODO DTD? factory.setAttribute(FeatureKeys.SCHEMA_VALIDATION, 4); Templates xsltTemplate = factory.newTemplates(xsltSource); // this.templates.put(xslt, xsltTemplate); if (in != null) in.close(); // } return xsltTemplate; }