/** * Transforms an xml tree putting the result to a stream with optional parameters. * * @param xml * @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); } }
/** * Transform an xml tree to PDF using XSL-FOP * putting the result to a stream (uses a * stylesheet on disk) */ 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; }
public void write(Document doc, OutputStream outputStream) throws IOException { // OutputFormat format = new OutputFormat(doc); // format.setIndenting(true); // format.setEncoding("UTF-8"); // XMLSerializer serializer = new XMLSerializer(outputStream, format); // serializer.asDOMSerializer(); // serializer.serialize(doc); try { TransformerFactory factory = TransformerFactory.newInstance(); try { factory.setAttribute("indent-number", 4); } catch (Exception e) {; // guess we can't set it, that's ok } Transformer transformer = factory.newTransformer(); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); // need to nest outputStreamWriter to get around JDK 5 bug. See // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6296446 transformer.transform( new DOMSource(doc), new StreamResult(new OutputStreamWriter(outputStream, "utf-8"))); } catch (TransformerException e) { throw new IOException(e.getMessage()); } }
/** * @param out * @param document * @param xsltStream * @throws TransformerFactoryConfigurationError * @throws TransformerException */ public static void parse( OutputStream out, Document document, InputStream xsltStream, URIResolver customResolver, boolean pretty) throws TransformerFactoryConfigurationError, TransformerException { Source xsltSource = new StreamSource(xsltStream); TransformerFactory transformerFactory = TransformerFactory.newInstance(); if (pretty) { try { transformerFactory.setAttribute("indent-number", new Integer(2)); } catch (Exception e) { } } if (customResolver != null) { transformerFactory.setURIResolver(customResolver); } Transformer transformer = transformerFactory.newTransformer(xsltSource); if (pretty) { try { transformer.setOutputProperty("{http://xml.apache.org/xalan}indent-amount", "2"); } catch (Exception e) { } } parse(out, document, transformer); }
private void initTransformerFactory(TransformerFactory factory) { String name = factory.getClass().getName(); try { if (name.equals("com.icl.saxon.TransformerFactoryImpl")) factory.setAttribute("http://icl.com/saxon/feature/linenumbering", Boolean.TRUE); else if (name.equals("org.apache.xalan.processor.TransformerFactoryImpl")) { // Try both the documented URI and the URI that the code expects. try { // This is the URI that the code expects. factory.setAttribute( "http://xml.apache.org/xalan/properties/source-location", Boolean.TRUE); } catch (IllegalArgumentException e) { // This is the URI that's documented. factory.setAttribute("http://apache.org/xalan/features/source_location", Boolean.TRUE); } } } catch (IllegalArgumentException e) { } }
static { _docBuilderFactory = DocumentBuilderFactory.newInstance(); _docBuilderFactory.setNamespaceAware(true); try { _transformerFactory.setAttribute("indent-number", Integer.valueOf(4)); } catch (Exception e) { // Ignore... Xalan may throw on this!! // We handle Xalan indentation separately (see serialize method). Logger.getLogger(AbstractDOMTransformer.class) .debug("Failed to set indent on transformer.", e); } }
public String toString(SOAPMessage message, int indent) throws IOException, SOAPException, TransformerException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); message.writeTo(baos); TransformerFactory tf = TransformerFactory.newInstance(); tf.setAttribute("indent-number", indent); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); StreamResult result = new StreamResult(new StringWriter()); StreamSource streamSource = new StreamSource(new ByteArrayInputStream(baos.toByteArray())); transformer.transform(streamSource, result); return result.getWriter().toString(); }
private boolean writeHostFile(Document doc, File spec) { try { final TransformerFactory tfac = TransformerFactory.newInstance(); tfac.setAttribute("indent-number", "3"); final Transformer t = tfac.newTransformer(); t.setOutputProperty(OutputKeys.INDENT, "yes"); t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); t.transform(new DOMSource(doc), new StreamResult(new BufferedWriter(new FileWriter(spec)))); return true; } catch (final Exception e) { setErrorMessage("Could not write file " + e.getMessage()); return false; } }
/** * This method is used to format response xml * * @param input * @param indent * @return */ public static String prettyFormat(String input, int indent) { try { 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(e); } }
public static boolean writeStaticHostFile(Document doc, File spec) { try { final TransformerFactory tfac = TransformerFactory.newInstance(); tfac.setAttribute("indent-number", "3"); final Transformer t = tfac.newTransformer(); t.setOutputProperty(OutputKeys.INDENT, "yes"); t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); t.transform(new DOMSource(doc), new StreamResult(new BufferedWriter(new FileWriter(spec)))); return true; } catch (final TransformerException e) { return false; } catch (IOException e) { return false; } }
public static String prettyPrint(String inString) { try { TransformerFactory factory = TransformerFactory.newInstance(); factory.setAttribute("indent-number", new Integer(4)); Transformer transformer = factory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); StreamResult result = new StreamResult(new StringWriter()); StreamSource source = new StreamSource(new StringReader(inString)); transformer.transform(source, result); String xmlString = result.getWriter().toString(); return xmlString; } catch (TransformerException ex) { ex.printStackTrace(); } return null; }
public void save(String filename) { try { Document document = element.getOwnerDocument(); document.getDocumentElement().normalize(); TransformerFactory tFactory = TransformerFactory.newInstance(); tFactory.setAttribute("indent-number", new Integer(4)); Transformer transformer = tFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); DOMSource source = new DOMSource(document); File file = new File(filename); StreamResult result = new StreamResult(file); transformer.transform(source, result); } catch (Exception e) { severe("Could not save XML file: " + e.getMessage()); } }
private String formatXML(String str) { try { // Use a Transformer for output TransformerFactory tFactory = TransformerFactory.newInstance(); // Surround this setting in a try/catch for compatibility with Java 1.4. This setting is // required // for Java 1.5 try { tFactory.setAttribute("indent-number", 2); } catch (IllegalArgumentException e) { // Ignore } Transformer transformer = tFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); // Transform the requested string into a nice formatted XML string StreamSource source = new StreamSource(new StringReader(str)); StringWriter sw = new StringWriter(); StreamResult result = new StreamResult(sw); transformer.transform(source, result); return sw.toString(); } catch (TransformerConfigurationException tce) { // Error generated by the parser System.out.println("\n** Transformer Factory error"); System.out.println(" " + tce.getMessage()); // Use the contained exception, if any Throwable x = tce; if (tce.getException() != null) x = tce.getException(); x.printStackTrace(); } catch (TransformerException te) { // Error generated by the parser System.out.println("\n** Transformation error"); System.out.println(" " + te.getMessage()); // Use the contained exception, if any Throwable x = te; if (te.getException() != null) x = te.getException(); x.printStackTrace(); } return str; }
/** * Returns a toString of indented XML file from doc. * * @param doc * @param indent * @return String XML file */ public static String documentToString(Node doc, boolean indent) { StringWriter sw = new StringWriter(); try { TransformerFactory tFactory = TransformerFactory.newInstance(); if (indent) { tFactory.setAttribute("indent-number", 2); } Transformer transformer = tFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, indent ? "yes" : "no"); transformer.transform(new DOMSource(doc), new StreamResult(sw)); } catch (TransformerConfigurationException e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } catch (TransformerFactoryConfigurationError e) { e.printStackTrace(); } return sw.toString(); }
public static void saveDocument(Document document, String path) throws TransformerConfigurationException, TransformerFactoryConfigurationError, TransformerFactoryConfigurationError, TransformerException, IOException { StringWriter sw = new StringWriter(); StreamResult sr = new StreamResult(sw); DOMSource dom = new DOMSource(document); TransformerFactory transformerFactory = TransformerFactory.newInstance(); transformerFactory.setAttribute("indent-number", 4); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.transform(dom, sr); String string = sw.toString(); FileWriter fw = new FileWriter(new File(path)); fw.write(string); fw.close(); }
public static String formatMetadata(String input, int indent) { input = input.replace("> <", "><"); try { Source xmlInput = new StreamSource(new StringReader(input)); StringWriter stringWriter = new StringWriter(); StreamResult xmlOutput = new StreamResult(stringWriter); StringWriter sw = new StringWriter(); xmlOutput.setWriter(sw); 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.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "" + indent); transformer.transform(xmlInput, xmlOutput); return xmlOutput.getWriter().toString(); } catch (IllegalArgumentException | TransformerException e) { return input; } }
/** * 格式化XML格式的字符串 * * @see 格式化失败时返回的Map中,isPrettySuccess=no,prettyResultStr=堆栈信息 * @see 格式化成功时返回的Map中,isPrettySuccess=yes,prettyResultStr=格式化后的字符串 * @param xmlString 待格式化的XML字符串 * @return 返回的Map中有两个字符串的key-value,分别为isPrettySuccess和prettyResultStr */ public static Map<String, String> formatXMLString(String xmlString) { Map<String, String> resultMap = new HashMap<String, String>(); TransformerFactory transformerFactory = TransformerFactory.newInstance(); transformerFactory.setAttribute("indent-number", new Integer(2)); StringWriter writer = new StringWriter(); Transformer transformer = null; try { transformer = transformerFactory.newTransformer(); transformer.setOutputProperty("{http://xml.apache.org/xalan}indent-amount", "2"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.transform( new StreamSource(new StringReader(xmlString)), new StreamResult(writer)); } catch (TransformerException e) { resultMap.put("isPrettySuccess", "no"); resultMap.put("prettyResultStr", extractStackTrace(e)); return resultMap; } resultMap.put("isPrettySuccess", "yes"); resultMap.put("prettyResultStr", writer.toString()); return resultMap; }
public static void generate(String directory) { try { PrintWriter writer = new PrintWriter(new File(directory + File.separator + "radargun-1.1.xsd")); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.newDocument(); doc.setXmlVersion("1.0"); doc.setXmlStandalone(true); generate(doc); TransformerFactory tf = TransformerFactory.newInstance(); tf.setAttribute("indent-number", 3); Transformer trans = tf.newTransformer(); trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); trans.setOutputProperty(OutputKeys.INDENT, "yes"); StreamResult result = new StreamResult(writer); DOMSource source = new DOMSource(doc); trans.transform(source, result); writer.flush(); } catch (FileNotFoundException e) { e .printStackTrace(); // To change body of catch statement use File | Settings | File // Templates. } catch (ParserConfigurationException e) { e .printStackTrace(); // To change body of catch statement use File | Settings | File // Templates. } catch (TransformerConfigurationException e) { e .printStackTrace(); // To change body of catch statement use File | Settings | File // Templates. } catch (TransformerException e) { e .printStackTrace(); // To change body of catch statement use File | Settings | File // Templates. } }
/** * Format this XML data as a String. * * @webref xml:method * @brief Formats XML data as a String * @param indent -1 for a single line (and no declaration), >= 0 for indents and newlines * @return the content * @see XML#toString() */ public String format(int indent) { try { // entities = doctype.getEntities() boolean useIndentAmount = false; TransformerFactory factory = TransformerFactory.newInstance(); if (indent != -1) { try { factory.setAttribute("indent-number", indent); } catch (IllegalArgumentException e) { useIndentAmount = true; } } Transformer transformer = factory.newTransformer(); // Add the XML declaration at the top if this node is the root and we're // not writing to a single line (indent = -1 means single line). if (indent == -1 || parent == null) { transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); } else { transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); } // transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "sample.dtd"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); // transformer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, "yes"); // huh? // transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, // "-//W3C//DTD XHTML 1.0 Transitional//EN"); // transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, // "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"); // For Android, because (at least 2.3.3) doesn't like indent-number if (useIndentAmount) { transformer.setOutputProperty( "{http://xml.apache.org/xslt}indent-amount", String.valueOf(indent)); } // transformer.setOutputProperty(OutputKeys.ENCODING,"ISO-8859-1"); // transformer.setOutputProperty(OutputKeys.ENCODING,"UTF8"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); // transformer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS // Always indent, otherwise the XML declaration will just be jammed // onto the first line with the XML code as well. transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // Properties p = transformer.getOutputProperties(); // for (Object key : p.keySet()) { // System.out.println(key + " -> " + p.get(key)); // } // If you smell something, that's because this code stinks. No matter // the settings of the Transformer object, if the XML document already // has whitespace elements, it won't bother re-indenting/re-formatting. // So instead, transform the data once into a single line string. // If indent is -1, then we're done. Otherwise re-run and the settings // of the factory will kick in. If you know a better way to do this, // please contribute. I've wasted too much of my Sunday on it. But at // least the Giants are getting blown out by the Falcons. final String decl = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; final String sep = System.getProperty("line.separator"); StringWriter tempWriter = new StringWriter(); StreamResult tempResult = new StreamResult(tempWriter); transformer.transform(new DOMSource(node), tempResult); String[] tempLines = PApplet.split(tempWriter.toString(), sep); // PApplet.println(tempLines); if (tempLines[0].startsWith("<?xml")) { // Remove XML declaration from the top before slamming into one line int declEnd = tempLines[0].indexOf("?>") + 2; // if (tempLines[0].length() == decl.length()) { if (tempLines[0].length() == declEnd) { // If it's all the XML declaration, remove it // PApplet.println("removing first line"); tempLines = PApplet.subset(tempLines, 1); } else { // PApplet.println("removing part of first line"); // If the first node has been moved to this line, be more careful // tempLines[0] = tempLines[0].substring(decl.length()); tempLines[0] = tempLines[0].substring(declEnd); } } String singleLine = PApplet.join(PApplet.trim(tempLines), ""); if (indent == -1) { return singleLine; } // Might just be whitespace, which won't be valid XML for parsing below. // https://github.com/processing/processing/issues/1796 // Since indent is not -1, that means they want valid XML, // so we'll give them the single line plus the decl... Lame? sure. if (singleLine.trim().length() == 0) { // You want whitespace? I've got your whitespace right here. return decl + sep + singleLine; } // Since the indent is not -1, bring back the XML declaration // transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); StringWriter stringWriter = new StringWriter(); StreamResult xmlOutput = new StreamResult(stringWriter); // DOMSource source = new DOMSource(node); Source source = new StreamSource(new StringReader(singleLine)); transformer.transform(source, xmlOutput); String outgoing = stringWriter.toString(); // Add the XML declaration to the top if it's not there already if (outgoing.startsWith(decl)) { int declen = decl.length(); int seplen = sep.length(); if (outgoing.length() > declen + seplen && !outgoing.substring(declen, declen + seplen).equals(sep)) { // make sure there's a line break between the XML decl and the code return outgoing.substring(0, decl.length()) + sep + outgoing.substring(decl.length()); } return outgoing; } else { return decl + sep + outgoing; } } catch (Exception e) { e.printStackTrace(); } return null; }
// J2SE does not support Xalan interpretive // main -> _main public static void _main(String argv[]) { // Runtime.getRuntime().traceMethodCalls(false); // turns Java tracing off boolean doStackDumpOnError = false; boolean setQuietMode = false; boolean doDiag = false; String msg = null; boolean isSecureProcessing = false; // Runtime.getRuntime().traceMethodCalls(false); // Runtime.getRuntime().traceInstructions(false); /** The default diagnostic writer... */ java.io.PrintWriter diagnosticsWriter = new PrintWriter(System.err, true); java.io.PrintWriter dumpWriter = diagnosticsWriter; ResourceBundle resbundle = (SecuritySupport.getResourceBundle( com.sun.org.apache.xml.internal.utils.res.XResourceBundle.ERROR_RESOURCES)); String flavor = "s2s"; if (argv.length < 1) { printArgOptions(resbundle); } else { // J2SE does not support Xalan interpretive // false -> true boolean useXSLTC = true; for (int i = 0; i < argv.length; i++) { if ("-XSLTC".equalsIgnoreCase(argv[i])) { useXSLTC = true; } } TransformerFactory tfactory; if (useXSLTC) { String key = "javax.xml.transform.TransformerFactory"; String value = "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl"; Properties props = System.getProperties(); props.put(key, value); System.setProperties(props); } try { tfactory = TransformerFactory.newInstance(); tfactory.setErrorListener(new DefaultErrorHandler()); } catch (TransformerFactoryConfigurationError pfe) { pfe.printStackTrace(dumpWriter); // "XSL Process was not successful."); msg = XSLMessages.createMessage(XSLTErrorResources.ER_NOT_SUCCESSFUL, null); diagnosticsWriter.println(msg); tfactory = null; // shut up compiler doExit(msg); } boolean formatOutput = false; boolean useSourceLocation = false; String inFileName = null; String outFileName = null; String dumpFileName = null; String xslFileName = null; String treedumpFileName = null; // J2SE does not support Xalan interpretive /* PrintTraceListener tracer = null; */ String outputType = null; String media = null; Vector params = new Vector(); boolean quietConflictWarnings = false; URIResolver uriResolver = null; EntityResolver entityResolver = null; ContentHandler contentHandler = null; int recursionLimit = -1; for (int i = 0; i < argv.length; i++) { if ("-XSLTC".equalsIgnoreCase(argv[i])) { // The -XSLTC option has been processed. } // J2SE does not support Xalan interpretive /* else if ("-TT".equalsIgnoreCase(argv[i])) { if (!useXSLTC) { if (null == tracer) tracer = new PrintTraceListener(diagnosticsWriter); tracer.m_traceTemplates = true; } else printInvalidXSLTCOption("-TT"); // tfactory.setTraceTemplates(true); } else if ("-TG".equalsIgnoreCase(argv[i])) { if (!useXSLTC) { if (null == tracer) tracer = new PrintTraceListener(diagnosticsWriter); tracer.m_traceGeneration = true; } else printInvalidXSLTCOption("-TG"); // tfactory.setTraceSelect(true); } else if ("-TS".equalsIgnoreCase(argv[i])) { if (!useXSLTC) { if (null == tracer) tracer = new PrintTraceListener(diagnosticsWriter); tracer.m_traceSelection = true; } else printInvalidXSLTCOption("-TS"); // tfactory.setTraceTemplates(true); } else if ("-TTC".equalsIgnoreCase(argv[i])) { if (!useXSLTC) { if (null == tracer) tracer = new PrintTraceListener(diagnosticsWriter); tracer.m_traceElements = true; } else printInvalidXSLTCOption("-TTC"); // tfactory.setTraceTemplateChildren(true); } */ else if ("-INDENT".equalsIgnoreCase(argv[i])) { int indentAmount; if (((i + 1) < argv.length) && (argv[i + 1].charAt(0) != '-')) { indentAmount = Integer.parseInt(argv[++i]); } else { indentAmount = 0; } // TBD: // xmlProcessorLiaison.setIndent(indentAmount); } else if ("-IN".equalsIgnoreCase(argv[i])) { if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-') inFileName = argv[++i]; else System.err.println( XSLMessages.createMessage( XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, new Object[] {"-IN"})); // "Missing argument for); } else if ("-MEDIA".equalsIgnoreCase(argv[i])) { if (i + 1 < argv.length) media = argv[++i]; else System.err.println( XSLMessages.createMessage( XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, new Object[] {"-MEDIA"})); // "Missing argument for); } else if ("-OUT".equalsIgnoreCase(argv[i])) { if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-') outFileName = argv[++i]; else System.err.println( XSLMessages.createMessage( XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, new Object[] {"-OUT"})); // "Missing argument for); } else if ("-XSL".equalsIgnoreCase(argv[i])) { if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-') xslFileName = argv[++i]; else System.err.println( XSLMessages.createMessage( XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, new Object[] {"-XSL"})); // "Missing argument for); } else if ("-FLAVOR".equalsIgnoreCase(argv[i])) { if (i + 1 < argv.length) { flavor = argv[++i]; } else System.err.println( XSLMessages.createMessage( XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, new Object[] {"-FLAVOR"})); // "Missing argument for); } else if ("-PARAM".equalsIgnoreCase(argv[i])) { if (i + 2 < argv.length) { String name = argv[++i]; params.addElement(name); String expression = argv[++i]; params.addElement(expression); } else System.err.println( XSLMessages.createMessage( XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, new Object[] {"-PARAM"})); // "Missing argument for); } else if ("-E".equalsIgnoreCase(argv[i])) { // TBD: // xmlProcessorLiaison.setShouldExpandEntityRefs(false); } else if ("-V".equalsIgnoreCase(argv[i])) { diagnosticsWriter.println( resbundle.getString("version") // ">>>>>>> Xalan Version " + Version.getVersion() + ", " + /* xmlProcessorLiaison.getParserDescription()+ */ resbundle.getString("version2")); // "<<<<<<<"); } // J2SE does not support Xalan interpretive /* else if ("-QC".equalsIgnoreCase(argv[i])) { if (!useXSLTC) quietConflictWarnings = true; else printInvalidXSLTCOption("-QC"); } */ else if ("-Q".equalsIgnoreCase(argv[i])) { setQuietMode = true; } else if ("-DIAG".equalsIgnoreCase(argv[i])) { doDiag = true; } else if ("-XML".equalsIgnoreCase(argv[i])) { outputType = "xml"; } else if ("-TEXT".equalsIgnoreCase(argv[i])) { outputType = "text"; } else if ("-HTML".equalsIgnoreCase(argv[i])) { outputType = "html"; } else if ("-EDUMP".equalsIgnoreCase(argv[i])) { doStackDumpOnError = true; if (((i + 1) < argv.length) && (argv[i + 1].charAt(0) != '-')) { dumpFileName = argv[++i]; } } else if ("-URIRESOLVER".equalsIgnoreCase(argv[i])) { if (i + 1 < argv.length) { try { uriResolver = (URIResolver) ObjectFactory.newInstance(argv[++i], true); tfactory.setURIResolver(uriResolver); } catch (ConfigurationError cnfe) { msg = XSLMessages.createMessage( XSLTErrorResources.ER_CLASS_NOT_FOUND_FOR_OPTION, new Object[] {"-URIResolver"}); System.err.println(msg); doExit(msg); } } else { msg = XSLMessages.createMessage( XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, new Object[] {"-URIResolver"}); // "Missing argument for); System.err.println(msg); doExit(msg); } } else if ("-ENTITYRESOLVER".equalsIgnoreCase(argv[i])) { if (i + 1 < argv.length) { try { entityResolver = (EntityResolver) ObjectFactory.newInstance(argv[++i], true); } catch (ConfigurationError cnfe) { msg = XSLMessages.createMessage( XSLTErrorResources.ER_CLASS_NOT_FOUND_FOR_OPTION, new Object[] {"-EntityResolver"}); System.err.println(msg); doExit(msg); } } else { // "Missing argument for); msg = XSLMessages.createMessage( XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, new Object[] {"-EntityResolver"}); System.err.println(msg); doExit(msg); } } else if ("-CONTENTHANDLER".equalsIgnoreCase(argv[i])) { if (i + 1 < argv.length) { try { contentHandler = (ContentHandler) ObjectFactory.newInstance(argv[++i], true); } catch (ConfigurationError cnfe) { msg = XSLMessages.createMessage( XSLTErrorResources.ER_CLASS_NOT_FOUND_FOR_OPTION, new Object[] {"-ContentHandler"}); System.err.println(msg); doExit(msg); } } else { // "Missing argument for); msg = XSLMessages.createMessage( XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, new Object[] {"-ContentHandler"}); System.err.println(msg); doExit(msg); } } // J2SE does not support Xalan interpretive /* else if ("-L".equalsIgnoreCase(argv[i])) { if (!useXSLTC) tfactory.setAttribute(XalanProperties.SOURCE_LOCATION, Boolean.TRUE); else printInvalidXSLTCOption("-L"); } else if ("-INCREMENTAL".equalsIgnoreCase(argv[i])) { if (!useXSLTC) tfactory.setAttribute ("http://xml.apache.org/xalan/features/incremental", java.lang.Boolean.TRUE); else printInvalidXSLTCOption("-INCREMENTAL"); } else if ("-NOOPTIMIZE".equalsIgnoreCase(argv[i])) { // Default is true. // // %REVIEW% We should have a generalized syntax for negative // switches... and probably should accept the inverse even // if it is the default. if (!useXSLTC) tfactory.setAttribute ("http://xml.apache.org/xalan/features/optimize", java.lang.Boolean.FALSE); else printInvalidXSLTCOption("-NOOPTIMIZE"); } else if ("-RL".equalsIgnoreCase(argv[i])) { if (!useXSLTC) { if (i + 1 < argv.length) recursionLimit = Integer.parseInt(argv[++i]); else System.err.println( XSLMessages.createMessage( XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, new Object[]{ "-rl" })); //"Missing argument for); } else { if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-') i++; printInvalidXSLTCOption("-RL"); } } */ // Generate the translet class and optionally specify the name // of the translet class. else if ("-XO".equalsIgnoreCase(argv[i])) { if (useXSLTC) { if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-') { tfactory.setAttribute("generate-translet", "true"); tfactory.setAttribute("translet-name", argv[++i]); } else tfactory.setAttribute("generate-translet", "true"); } else { if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-') i++; printInvalidXalanOption("-XO"); } } // Specify the destination directory for the translet classes. else if ("-XD".equalsIgnoreCase(argv[i])) { if (useXSLTC) { if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-') tfactory.setAttribute("destination-directory", argv[++i]); else System.err.println( XSLMessages.createMessage( XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, new Object[] {"-XD"})); // "Missing argument for); } else { if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-') i++; printInvalidXalanOption("-XD"); } } // Specify the jar file name which the translet classes are packaged into. else if ("-XJ".equalsIgnoreCase(argv[i])) { if (useXSLTC) { if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-') { tfactory.setAttribute("generate-translet", "true"); tfactory.setAttribute("jar-name", argv[++i]); } else System.err.println( XSLMessages.createMessage( XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, new Object[] {"-XJ"})); // "Missing argument for); } else { if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-') i++; printInvalidXalanOption("-XJ"); } } // Specify the package name prefix for the generated translet classes. else if ("-XP".equalsIgnoreCase(argv[i])) { if (useXSLTC) { if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-') tfactory.setAttribute("package-name", argv[++i]); else System.err.println( XSLMessages.createMessage( XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, new Object[] {"-XP"})); // "Missing argument for); } else { if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-') i++; printInvalidXalanOption("-XP"); } } // Enable template inlining. else if ("-XN".equalsIgnoreCase(argv[i])) { if (useXSLTC) { tfactory.setAttribute("enable-inlining", "true"); } else printInvalidXalanOption("-XN"); } // Turns on additional debugging message output else if ("-XX".equalsIgnoreCase(argv[i])) { if (useXSLTC) { tfactory.setAttribute("debug", "true"); } else printInvalidXalanOption("-XX"); } // Create the Transformer from the translet if the translet class is newer // than the stylesheet. else if ("-XT".equalsIgnoreCase(argv[i])) { if (useXSLTC) { tfactory.setAttribute("auto-translet", "true"); } else printInvalidXalanOption("-XT"); } else if ("-SECURE".equalsIgnoreCase(argv[i])) { isSecureProcessing = true; try { tfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); } catch (TransformerConfigurationException e) { } } else System.err.println( XSLMessages.createMessage( XSLTErrorResources.ER_INVALID_OPTION, new Object[] {argv[i]})); // "Invalid argument:); } // Print usage instructions if no xml and xsl file is specified in the command line if (inFileName == null && xslFileName == null) { msg = resbundle.getString("xslProc_no_input"); System.err.println(msg); doExit(msg); } // Note that there are usage cases for calling us without a -IN arg // The main XSL transformation occurs here! try { long start = System.currentTimeMillis(); if (null != dumpFileName) { dumpWriter = new PrintWriter(new FileWriter(dumpFileName)); } Templates stylesheet = null; if (null != xslFileName) { if (flavor.equals("d2d")) { // Parse in the xml data into a DOM DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); dfactory.setNamespaceAware(true); if (isSecureProcessing) { try { dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); } catch (ParserConfigurationException pce) { } } DocumentBuilder docBuilder = dfactory.newDocumentBuilder(); Node xslDOM = docBuilder.parse(new InputSource(xslFileName)); stylesheet = tfactory.newTemplates(new DOMSource(xslDOM, xslFileName)); } else { // System.out.println("Calling newTemplates: "+xslFileName); stylesheet = tfactory.newTemplates(new StreamSource(xslFileName)); // System.out.println("Done calling newTemplates: "+xslFileName); } } PrintWriter resultWriter; StreamResult strResult; if (null != outFileName) { strResult = new StreamResult(new FileOutputStream(outFileName)); // One possible improvement might be to ensure this is // a valid URI before setting the systemId, but that // might have subtle changes that pre-existing users // might notice; we can think about that later -sc r1.46 strResult.setSystemId(outFileName); } else { strResult = new StreamResult(System.out); // We used to default to incremental mode in this case. // We've since decided that since the -INCREMENTAL switch is // available, that default is probably not necessary nor // necessarily a good idea. } SAXTransformerFactory stf = (SAXTransformerFactory) tfactory; // J2SE does not support Xalan interpretive /* // This is currently controlled via TransformerFactoryImpl. if (!useXSLTC && useSourceLocation) stf.setAttribute(XalanProperties.SOURCE_LOCATION, Boolean.TRUE); */ // Did they pass in a stylesheet, or should we get it from the // document? if (null == stylesheet) { Source source = stf.getAssociatedStylesheet(new StreamSource(inFileName), media, null, null); if (null != source) stylesheet = tfactory.newTemplates(source); else { if (null != media) throw new TransformerException( XSLMessages.createMessage( XSLTErrorResources.ER_NO_STYLESHEET_IN_MEDIA, new Object[] {inFileName, media})); // "No stylesheet found in: " // + inFileName + ", media=" // + media); else throw new TransformerException( XSLMessages.createMessage( XSLTErrorResources.ER_NO_STYLESHEET_PI, new Object[] {inFileName})); // "No xml-stylesheet PI found in: " // + inFileName); } } if (null != stylesheet) { Transformer transformer = flavor.equals("th") ? null : stylesheet.newTransformer(); transformer.setErrorListener(new DefaultErrorHandler()); // Override the output format? if (null != outputType) { transformer.setOutputProperty(OutputKeys.METHOD, outputType); } // J2SE does not support Xalan interpretive /* if (transformer instanceof com.sun.org.apache.xalan.internal.transformer.TransformerImpl) { com.sun.org.apache.xalan.internal.transformer.TransformerImpl impl = (com.sun.org.apache.xalan.internal.transformer.TransformerImpl)transformer; TraceManager tm = impl.getTraceManager(); if (null != tracer) tm.addTraceListener(tracer); impl.setQuietConflictWarnings(quietConflictWarnings); // This is currently controlled via TransformerFactoryImpl. if (useSourceLocation) impl.setProperty(XalanProperties.SOURCE_LOCATION, Boolean.TRUE); if(recursionLimit>0) impl.setRecursionLimit(recursionLimit); // sc 28-Feb-01 if we re-implement this, please uncomment helpmsg in printArgOptions // impl.setDiagnosticsOutput( setQuietMode ? null : diagnosticsWriter ); } */ int nParams = params.size(); for (int i = 0; i < nParams; i += 2) { transformer.setParameter( (String) params.elementAt(i), (String) params.elementAt(i + 1)); } if (uriResolver != null) transformer.setURIResolver(uriResolver); if (null != inFileName) { if (flavor.equals("d2d")) { // Parse in the xml data into a DOM DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); dfactory.setCoalescing(true); dfactory.setNamespaceAware(true); if (isSecureProcessing) { try { dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); } catch (ParserConfigurationException pce) { } } DocumentBuilder docBuilder = dfactory.newDocumentBuilder(); if (entityResolver != null) docBuilder.setEntityResolver(entityResolver); Node xmlDoc = docBuilder.parse(new InputSource(inFileName)); Document doc = docBuilder.newDocument(); org.w3c.dom.DocumentFragment outNode = doc.createDocumentFragment(); transformer.transform(new DOMSource(xmlDoc, inFileName), new DOMResult(outNode)); // Now serialize output to disk with identity transformer Transformer serializer = stf.newTransformer(); serializer.setErrorListener(new DefaultErrorHandler()); Properties serializationProps = stylesheet.getOutputProperties(); serializer.setOutputProperties(serializationProps); if (contentHandler != null) { SAXResult result = new SAXResult(contentHandler); serializer.transform(new DOMSource(outNode), result); } else serializer.transform(new DOMSource(outNode), strResult); } else if (flavor.equals("th")) { for (int i = 0; i < 1; i++) // Loop for diagnosing bugs with inconsistent behavior { // System.out.println("Testing the TransformerHandler..."); XMLReader reader = null; // Use JAXP1.1 ( if possible ) try { javax.xml.parsers.SAXParserFactory factory = javax.xml.parsers.SAXParserFactory.newInstance(); factory.setNamespaceAware(true); if (isSecureProcessing) { try { factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); } catch (org.xml.sax.SAXException se) { } } javax.xml.parsers.SAXParser jaxpParser = factory.newSAXParser(); reader = jaxpParser.getXMLReader(); } catch (javax.xml.parsers.ParserConfigurationException ex) { throw new org.xml.sax.SAXException(ex); } catch (javax.xml.parsers.FactoryConfigurationError ex1) { throw new org.xml.sax.SAXException(ex1.toString()); } catch (NoSuchMethodError ex2) { } catch (AbstractMethodError ame) { } if (null == reader) { reader = XMLReaderFactory.createXMLReader(); } // J2SE does not support Xalan interpretive /* if (!useXSLTC) stf.setAttribute(com.sun.org.apache.xalan.internal.processor.TransformerFactoryImpl.FEATURE_INCREMENTAL, Boolean.TRUE); */ TransformerHandler th = stf.newTransformerHandler(stylesheet); reader.setContentHandler(th); reader.setDTDHandler(th); if (th instanceof org.xml.sax.ErrorHandler) reader.setErrorHandler((org.xml.sax.ErrorHandler) th); try { reader.setProperty("http://xml.org/sax/properties/lexical-handler", th); } catch (org.xml.sax.SAXNotRecognizedException e) { } catch (org.xml.sax.SAXNotSupportedException e) { } try { reader.setFeature("http://xml.org/sax/features/namespace-prefixes", true); } catch (org.xml.sax.SAXException se) { } th.setResult(strResult); reader.parse(new InputSource(inFileName)); } } else { if (entityResolver != null) { XMLReader reader = null; // Use JAXP1.1 ( if possible ) try { javax.xml.parsers.SAXParserFactory factory = javax.xml.parsers.SAXParserFactory.newInstance(); factory.setNamespaceAware(true); if (isSecureProcessing) { try { factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); } catch (org.xml.sax.SAXException se) { } } javax.xml.parsers.SAXParser jaxpParser = factory.newSAXParser(); reader = jaxpParser.getXMLReader(); } catch (javax.xml.parsers.ParserConfigurationException ex) { throw new org.xml.sax.SAXException(ex); } catch (javax.xml.parsers.FactoryConfigurationError ex1) { throw new org.xml.sax.SAXException(ex1.toString()); } catch (NoSuchMethodError ex2) { } catch (AbstractMethodError ame) { } if (null == reader) { reader = XMLReaderFactory.createXMLReader(); } reader.setEntityResolver(entityResolver); if (contentHandler != null) { SAXResult result = new SAXResult(contentHandler); transformer.transform(new SAXSource(reader, new InputSource(inFileName)), result); } else { transformer.transform( new SAXSource(reader, new InputSource(inFileName)), strResult); } } else if (contentHandler != null) { SAXResult result = new SAXResult(contentHandler); transformer.transform(new StreamSource(inFileName), result); } else { // System.out.println("Starting transform"); transformer.transform(new StreamSource(inFileName), strResult); // System.out.println("Done with transform"); } } } else { StringReader reader = new StringReader("<?xml version=\"1.0\"?> <doc/>"); transformer.transform(new StreamSource(reader), strResult); } } else { // "XSL Process was not successful."); msg = XSLMessages.createMessage(XSLTErrorResources.ER_NOT_SUCCESSFUL, null); diagnosticsWriter.println(msg); doExit(msg); } // close output streams if (null != outFileName && strResult != null) { java.io.OutputStream out = strResult.getOutputStream(); java.io.Writer writer = strResult.getWriter(); try { if (out != null) out.close(); if (writer != null) writer.close(); } catch (java.io.IOException ie) { } } long stop = System.currentTimeMillis(); long millisecondsDuration = stop - start; if (doDiag) { Object[] msgArgs = new Object[] {inFileName, xslFileName, new Long(millisecondsDuration)}; msg = XSLMessages.createMessage("diagTiming", msgArgs); diagnosticsWriter.println('\n'); diagnosticsWriter.println(msg); } } catch (Throwable throwable) { while (throwable instanceof com.sun.org.apache.xml.internal.utils.WrappedRuntimeException) { throwable = ((com.sun.org.apache.xml.internal.utils.WrappedRuntimeException) throwable) .getException(); } if ((throwable instanceof NullPointerException) || (throwable instanceof ClassCastException)) doStackDumpOnError = true; diagnosticsWriter.println(); if (doStackDumpOnError) throwable.printStackTrace(dumpWriter); else { DefaultErrorHandler.printLocation(diagnosticsWriter, throwable); diagnosticsWriter.println( XSLMessages.createMessage(XSLTErrorResources.ER_XSLT_ERROR, null) + " (" + throwable.getClass().getName() + "): " + throwable.getMessage()); } // diagnosticsWriter.println(XSLMessages.createMessage(XSLTErrorResources.ER_NOT_SUCCESSFUL, // null)); //"XSL Process was not successful."); if (null != dumpFileName) { dumpWriter.close(); } doExit(throwable.getMessage()); } if (null != dumpFileName) { dumpWriter.close(); } if (null != diagnosticsWriter) { // diagnosticsWriter.close(); } // if(!setQuietMode) // diagnosticsWriter.println(resbundle.getString("xsldone")); //"Xalan: done"); // else // diagnosticsWriter.println(""); //"Xalan: done"); } }