public void marshal(Object obj, Result result) throws JAXBException { // XMLSerializable so = Util.toXMLSerializable(obj); XMLSerializable so = context.getGrammarInfo().castToXMLSerializable(obj); if (so == null) throw new MarshalException(Messages.format(Messages.NOT_MARSHALLABLE)); if (result instanceof SAXResult) { write(so, ((SAXResult) result).getHandler()); return; } if (result instanceof DOMResult) { Node node = ((DOMResult) result).getNode(); if (node == null) { try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.newDocument(); ((DOMResult) result).setNode(doc); write(so, new SAX2DOMEx(doc)); } catch (ParserConfigurationException pce) { throw new JAXBAssertionError(pce); } } else { write(so, new SAX2DOMEx(node)); } return; } if (result instanceof StreamResult) { StreamResult sr = (StreamResult) result; XMLWriter w = null; if (sr.getWriter() != null) w = createWriter(sr.getWriter()); else if (sr.getOutputStream() != null) w = createWriter(sr.getOutputStream()); else if (sr.getSystemId() != null) { String fileURL = sr.getSystemId(); if (fileURL.startsWith("file:///")) { if (fileURL.substring(8).indexOf(":") > 0) fileURL = fileURL.substring(8); else fileURL = fileURL.substring(7); } // otherwise assume that it's a file name try { w = createWriter(new FileOutputStream(fileURL)); } catch (IOException e) { throw new MarshalException(e); } } if (w == null) throw new IllegalArgumentException(); write(so, w); return; } // unsupported parameter type throw new MarshalException(Messages.format(Messages.UNSUPPORTED_RESULT)); }
@Override public void close() { if (result.getOutputStream() != null) { try { result.getOutputStream().close(); } catch (IOException e) { } } }
protected static void createXslFile(String fileName, MappingScript script) throws IOException { File xsltDir = ConfigSingleton.getRepoxContextUtil() .getRepoxManager() .getMetadataTransformationManager() .getXsltDir(); if (!xsltDir.exists()) xsltDir.mkdirs(); File xslFile = new File(xsltDir, fileName.toLowerCase() + XSL_END); StreamResult tmpResult = new StreamResult(new FileOutputStream(xslFile)); XsltStylesheet xslt = new XSLTCompiler(new ToolsetManagerImpl<XsltFunction>(XsltToolsetLibrary.getToolsets())) .compile(script); new XsltWriter().write(xslt, tmpResult); tmpResult.getOutputStream().close(); /* DUMMY FILE CREATION CODE File xsltDir = ConfigSingleton.getRepoxContextUtil().getRepoxManager().getMetadataTransformationManager().getXsltDir(); if(!xsltDir.exists()) xsltDir.mkdirs(); tmpFile = new File(xsltDir, fileName.toLowerCase()+XSL_END); FileWriter fstream = new FileWriter(tmpFile); BufferedWriter outFile = new BufferedWriter(fstream); outFile.write("<This is a dummy xslt>"); outFile.close();*/ // System.out.println("SERVER - XSL created"); }
protected XSLProcessorImpl init(Result result) throws TransformerException { XSLProcessorImpl processor = (XSLProcessorImpl) _processor.clone(); if (result instanceof StreamResult) { StreamResult sr = (StreamResult) result; OutputMethodHandlerImpl outputMethodHandler = new OutputMethodHandlerImpl(); processor.setOutputMethodHandler(outputMethodHandler); Destination dest; OutputStream ostream = sr.getOutputStream(); if (ostream != null) { dest = new OutputStreamDestination(ostream); } else { // FIXME: we need to handle a characterWriter throw new TransformerException("cannot use Writer result"); } outputMethodHandler.setDestination(dest); } else if (result instanceof SAXResult) { SAXResult sr = (SAXResult) result; processor.setContentHandler(sr.getHandler()); // FIXME: set lexical handler? } else { throw new TransformerException("unrecognized Result class: " + result.getClass().getName()); } return processor; }
/** Generate schema. */ public void doSchema(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { setHeaders(rsp); rsp.setContentType("application/xml"); StreamResult r = new StreamResult(rsp.getOutputStream()); new SchemaGenerator(new ModelBuilder().get(bean.getClass())).generateSchema(r); r.getOutputStream().close(); }
public void save(XMLDocument xmlDocument, Result result, Object options) throws IOException { if (xmlDocument == null) { throw new IllegalArgumentException( SDOException.cannotPerformOperationWithNullInputParameter("save", "xmlDocument")); } if (result instanceof StreamResult) { StreamResult streamResult = (StreamResult) result; Writer writer = streamResult.getWriter(); if (null == writer) { save(xmlDocument, streamResult.getOutputStream(), options); } else { save(xmlDocument, writer, options); } } else { // get XMLMarshaller once - as we may create a new instance if this helper isDirty=true XMLMarshaller anXMLMarshaller = getXmlMarshaller(options); // Ask the SDOXMLDocument if we should include the XML declaration in the resulting XML anXMLMarshaller.setFragment(!xmlDocument.isXMLDeclaration()); anXMLMarshaller.setEncoding(xmlDocument.getEncoding()); anXMLMarshaller.setSchemaLocation(xmlDocument.getSchemaLocation()); anXMLMarshaller.setNoNamespaceSchemaLocation(xmlDocument.getNoNamespaceSchemaLocation()); ((SDOMarshalListener) anXMLMarshaller.getMarshalListener()) .setMarshalledObject(xmlDocument.getRootObject()); ((SDOMarshalListener) anXMLMarshaller.getMarshalListener()) .setMarshalledObjectRootQName( new QName(xmlDocument.getRootElementURI(), xmlDocument.getRootElementName())); if (result instanceof SAXResult) { ContentHandlerRecord marshalRecord = new ContentHandlerRecord(); marshalRecord.setContentHandler(((SAXResult) result).getHandler()); marshalRecord.setMarshaller(anXMLMarshaller); ((SDOMarshalListener) anXMLMarshaller.getMarshalListener()) .setRootMarshalRecord(marshalRecord); anXMLMarshaller.marshal(xmlDocument, marshalRecord); } else if (result instanceof DOMResult) { NodeRecord marshalRecord = new NodeRecord(); marshalRecord.setDOM(((DOMResult) result).getNode()); marshalRecord.setMarshaller(anXMLMarshaller); ((SDOMarshalListener) anXMLMarshaller.getMarshalListener()) .setRootMarshalRecord(marshalRecord); anXMLMarshaller.marshal(xmlDocument, marshalRecord); } else { StringWriter writer = new StringWriter(); this.save(xmlDocument, writer, options); String xml = writer.toString(); StreamSource source = new StreamSource(new java.io.StringReader(xml)); anXMLMarshaller.getTransformer().transform(source, result); } } }
public static String formatXml(String xml) { try { Transformer serializer = SAXTransformerFactory.newInstance().newTransformer(); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); Source xmlSource = new SAXSource(new InputSource(new ByteArrayInputStream(xml.getBytes()))); StreamResult res = new StreamResult(new ByteArrayOutputStream()); serializer.transform(xmlSource, res); return new String(((ByteArrayOutputStream) res.getOutputStream()).toByteArray()); } catch (Exception e) { return xml; } }
/** * Reformats XML text for pretty-printing. * * @param xml The XML text. * @return The formatted XML text. */ public static String format(String xml) { try { Transformer serializer = SAXTransformerFactory.newInstance().newTransformer(); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); Source xmlSource = new SAXSource(new InputSource(new ByteArrayInputStream(xml.getBytes()))); StreamResult res = new StreamResult(new ByteArrayOutputStream()); serializer.transform(xmlSource, res); return new String(((ByteArrayOutputStream) res.getOutputStream()).toByteArray()); } catch (IllegalArgumentException | TransformerException | TransformerFactoryConfigurationError ex) { throw new RuntimeException("Failed to format XML", ex); } }
public void writeDoc() throws Exception { if (!isReadOnly && !getValue("readOnly").equalsIgnoreCase("true")) { final InputStream stylesheet = this.getClass().getResourceAsStream("/org/jpedal/examples/viewer/res/xmlstyle.xslt"); final StreamResult str = new StreamResult(configFile); final StreamSource ss = new StreamSource(stylesheet); final DOMSource dom = new DOMSource(doc); final TransformerFactory transformerFactory = TransformerFactory.newInstance(); final Transformer transformer = transformerFactory.newTransformer(ss); transformer.transform(dom, str); stylesheet.close(); if (ss != null) { ss.getInputStream().close(); } // Prevents exception when viewer is closing. if (str != null && str.getOutputStream() != null) { str.getOutputStream().close(); } } }
protected static void createXmapFile(String fileName, MappingScript script) throws IOException { File xmapDir = ConfigSingleton.getRepoxContextUtil() .getRepoxManager() .getMetadataTransformationManager() .getXmapDir(); if (!xmapDir.exists()) xmapDir.mkdirs(); File xmapFile = new File(xmapDir, fileName.toLowerCase() + XMAP_END); StreamResult tmpResult = new StreamResult(new FileOutputStream(xmapFile)); new XMLMappingWriter().write(script, tmpResult); tmpResult.getOutputStream().close(); // System.out.println("SERVER - XMAP created"); }
public static String domToString(org.w3c.dom.Document document) { try { Source xmlSource = new DOMSource(document); StreamResult result = new StreamResult(new ByteArrayOutputStream()); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty("indent", "yes"); // Java XML Indent transformer.transform(xmlSource, result); return result.getOutputStream().toString(); } catch (TransformerFactoryConfigurationError factoryError) { LOG.error("Error creating TransformerFactory", factoryError); } catch (TransformerException transformerError) { LOG.error("Error transforming document", transformerError); } return null; }
public void save(File file) throws TransformerException, IOException { OutputStream os = new FileOutputStream(file); StreamResult streamResult; if (gzipOutput) { streamResult = new StreamResult(new GZIPOutputStream(os)); } else { streamResult = new StreamResult(os); } TransformerFactory tf = TransformerFactory.newInstance(); Transformer serializer = tf.newTransformer(); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); serializer.setOutputProperty(OutputKeys.STANDALONE, "yes"); serializer.setOutputProperty(OutputKeys.METHOD, "xml"); serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); serializer.setOutputProperty(OutputKeys.MEDIA_TYPE, "text/xml"); serializer.transform(new DOMSource(doc), streamResult); streamResult.getOutputStream().close(); }
private static String formatXml(String xml) { try { Transformer serializer = SAXTransformerFactory.newInstance().newTransformer(); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); // serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, // "yes"); serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); // serializer.setOutputProperty("{http://xml.customer.org/xslt}indent-amount", // "2"); Source xmlSource = new SAXSource(new InputSource(new ByteArrayInputStream(xml.getBytes()))); StreamResult res = new StreamResult(new ByteArrayOutputStream()); serializer.transform(xmlSource, res); return new String(((ByteArrayOutputStream) res.getOutputStream()).toByteArray()); } catch (Exception e) { // TODO log error return xml; } }
/** * 格式化xml * * @param xml * @return String */ public static String formatXml(String xml) { ByteArrayInputStream bis = null; try { Transformer serializer = SAXTransformerFactory.newInstance().newTransformer(); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); bis = new ByteArrayInputStream(xml.getBytes()); Source xmlSource = new SAXSource(new InputSource(bis)); StreamResult res = new StreamResult(new ByteArrayOutputStream()); serializer.transform(xmlSource, res); return new String(((ByteArrayOutputStream) res.getOutputStream()).toByteArray()); } catch (IllegalArgumentException | TransformerException e) { return xml; } finally { try { bis.close(); } catch (IOException e) { e.printStackTrace(); } } }
public void validate(Source source, Result result) throws SAXException, IOException { if (result instanceof StreamResult || result == null) { final StreamSource streamSource = (StreamSource) source; final StreamResult streamResult = (StreamResult) result; XMLInputSource input = new XMLInputSource(streamSource.getPublicId(), streamSource.getSystemId(), null); input.setByteStream(streamSource.getInputStream()); input.setCharacterStream(streamSource.getReader()); // Gets the parser configuration. We'll create and initialize a new one, if we // haven't created one before or if the previous one was garbage collected. boolean newConfig = false; XMLParserConfiguration config = (XMLParserConfiguration) fConfiguration.get(); if (config == null) { config = initialize(); newConfig = true; } // If settings have changed on the component manager, refresh the error handler and entity // resolver. else if (fComponentManager.getFeature(PARSER_SETTINGS)) { config.setProperty(ENTITY_RESOLVER, fComponentManager.getProperty(ENTITY_RESOLVER)); config.setProperty(ERROR_HANDLER, fComponentManager.getProperty(ERROR_HANDLER)); config.setProperty(SECURITY_MANAGER, fComponentManager.getProperty(SECURITY_MANAGER)); } // prepare for parse fComponentManager.reset(); if (streamResult != null) { if (fSerializerFactory == null) { fSerializerFactory = SerializerFactory.getSerializerFactory(Method.XML); } // there doesn't seem to be a way to reset a serializer, so we need to make // a new one each time. Serializer ser; if (streamResult.getWriter() != null) { ser = fSerializerFactory.makeSerializer(streamResult.getWriter(), new OutputFormat()); } else if (streamResult.getOutputStream() != null) { ser = fSerializerFactory.makeSerializer(streamResult.getOutputStream(), new OutputFormat()); } else if (streamResult.getSystemId() != null) { String uri = streamResult.getSystemId(); OutputStream out = XMLEntityManager.createOutputStream(uri); ser = fSerializerFactory.makeSerializer(out, new OutputFormat()); } else { throw new IllegalArgumentException( JAXPValidationMessageFormatter.formatMessage( fComponentManager.getLocale(), "StreamResultNotInitialized", null)); } // we're using the parser only as an XNI-to-SAX converter, // so that we can use the SAX-based serializer SAXParser parser = (SAXParser) fParser.get(); if (newConfig || parser == null) { parser = new SAXParser(config); fParser = new SoftReference(parser); } else { parser.reset(); } config.setDocumentHandler(fSchemaValidator); fSchemaValidator.setDocumentHandler(parser); parser.setContentHandler(ser.asContentHandler()); } else { fSchemaValidator.setDocumentHandler(null); } try { config.parse(input); } catch (XMLParseException e) { throw Util.toSAXParseException(e); } catch (XNIException e) { throw Util.toSAXException(e); } finally { // release the references to the SAXParser and Serializer fSchemaValidator.setDocumentHandler(null); } return; } throw new IllegalArgumentException( JAXPValidationMessageFormatter.formatMessage( fComponentManager.getLocale(), "SourceResultMismatch", new Object[] {source.getClass().getName(), result.getClass().getName()})); }
// 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"); } }