protected Templates getTemplates(String filename) { File file = new File(filename); // check timestamp if we have it already long lastModified = file.lastModified(); TemplatesCache cache = (TemplatesCache) xslCache.get(file); if (cache != null && cache.timestamp == lastModified) return cache.templates; cache = new TemplatesCache(); cache.timestamp = lastModified; // get a new try { TransformerFactory factory = TransformerFactory.newInstance(); cache.templates = factory.newTemplates(new StreamSource(file)); } catch (TransformerConfigurationException e) { throw new RuntimeException( "Exception reading templates from " + filename + ": " + e.getMessage()); } // keep it xslCache.put(file, cache); // done return cache.templates; }
// taken from // http://www.exampledepot.com/egs/javax.xml.transform/BasicXsl.html // This method applies the xslFilename to inFilename and writes // the output to outFilename. public static void xsl(File inFile, File outFile, InputStream xslStream) throws Exception { try { // Create transformer factory TransformerFactory factory = TransformerFactory.newInstance(); // Use the factory to create a template containing the xsl file Templates template = factory.newTemplates(new StreamSource(xslStream)); // Use the template to create a transformer Transformer xformer = template.newTransformer(); // Prepare the input and output files Source source = new StreamSource(new FileInputStream(inFile)); Result result = new StreamResult(new FileOutputStream(outFile)); // Apply the xsl file to the source file and write the result to the // output file xformer.transform(source, result); } catch (TransformerException e) { // An error occurred while applying the XSL file // Get location of error in input file SourceLocator locator = e.getLocator(); int col = locator.getColumnNumber(); int line = locator.getLineNumber(); throw new Exception( String.format("XSL exception line %d col %d message: %s", line, col, e.getMessage())); } }
/** * Sets the XSLT transformer from a Source * * @param source the source * @throws TransformerConfigurationException is thrown if creating a XSLT transformer failed. */ public void setTransformerSource(Source source) throws TransformerConfigurationException { TransformerFactory factory = converter.getTransformerFactory(); if (errorListener != null) { factory.setErrorListener(errorListener); } else { // use a logger error listener so users can see from the logs what the error may be factory.setErrorListener(new XsltErrorListener()); } if (getUriResolver() != null) { factory.setURIResolver(getUriResolver()); } // Check that the call to newTemplates() returns a valid template instance. // In case of an xslt parse error, it will return null and we should stop the // deployment and raise an exception as the route will not be setup properly. Templates templates = factory.newTemplates(source); if (templates != null) { setTemplate(templates); } else { throw new TransformerConfigurationException( "Error creating XSLT template. " + "This is most likely be caused by a XML parse error. " + "Please verify your XSLT file configured."); } }
private String importXMI(File sourceFile) throws FileNotFoundException, TransformerConfigurationException, TransformerException { BufferedReader styledata; StreamSource sourcedata; Templates stylesheet; Transformer trans; // Get the stylesheet file stream styledata = new BufferedReader( new FileReader( new File( getClass().getClassLoader().getResource("verifier/xmi2lem.xsl").getFile()))); sourcedata = new StreamSource(new FileReader(sourceFile)); // Initialize Saxon TransformerFactory factory = TransformerFactoryImpl.newInstance(); stylesheet = factory.newTemplates(new StreamSource(styledata)); // Apply the transformation trans = stylesheet.newTransformer(); StringWriter sw = new StringWriter(); trans.transform(sourcedata, new StreamResult(sw)); // return sw.toString(); return sw.getBuffer().substring(sw.getBuffer().indexOf("model")); }
public Schema createSchema(InputSource in, PropertyMap properties) throws IOException, SAXException, IncorrectSchemaException { ErrorHandler eh = ValidateProperty.ERROR_HANDLER.get(properties); SAXErrorListener errorListener = new SAXErrorListener(eh, in.getSystemId()); UserWrapErrorHandler ueh1 = new UserWrapErrorHandler(eh); UserWrapErrorHandler ueh2 = new UserWrapErrorHandler(eh); try { PropertyMapBuilder builder = new PropertyMapBuilder(properties); ValidateProperty.ERROR_HANDLER.put(builder, ueh1); SAXSource source = createValidatingSource(in, builder.toPropertyMap(), ueh1); source = createTransformingSource( source, SchematronProperty.PHASE.get(properties), properties.contains(SchematronProperty.DIAGNOSE), in.getSystemId(), ueh2); TransformerFactory transformerFactory = (TransformerFactory) transformerFactoryClass.newInstance(); initTransformerFactory(transformerFactory); transformerFactory.setErrorListener(errorListener); Templates templates = transformerFactory.newTemplates(source); return new SchemaImpl(templates, properties, supportedPropertyIds); } catch (TransformerConfigurationException e) { throw toSAXException( e, errorListener.getHadError() || ueh1.getHadErrorOrFatalError() || ueh2.getHadErrorOrFatalError()); } catch (InstantiationException e) { throw new SAXException(e); } catch (IllegalAccessException e) { throw new SAXException(e); } }
/** Gets an XSLT template from the given resource location. */ public static Templates getStylesheet(String resourcePath, Class<?> sourceClass) { InputStream xsltStream; if (sourceClass == null) { try { xsltStream = new FileInputStream(resourcePath); } catch (IOException exc) { LOGGER.debug("Could not open file", exc); return null; } } else { xsltStream = sourceClass.getResourceAsStream(resourcePath); } try { StreamSource xsltSource = new StreamSource(xsltStream); // Java XML factories are not declared to be thread safe TransformerFactory transformerFactory = TransformerFactory.newInstance(); transformerFactory.setErrorListener(new XMLListener()); return transformerFactory.newTemplates(xsltSource); } catch (TransformerConfigurationException exc) { LOGGER.debug("Could not construct template", exc); } finally { try { if (xsltStream != null) xsltStream.close(); } catch (IOException e) { LOGGER.debug("Could not close file", e); } } return null; }
private void showResults(HttpSession session, HttpServletResponse response) { Document xmlDocument = null; try { PrintWriter writer = response.getWriter(); xmlDocument = (Document) session.getAttribute("queryResults"); String xslPath = ContextUtil.getRealPath(session.getServletContext(), XSL_TBLTEXT_RELATIVE_PATH); StreamSource s = new StreamSource( new InputStreamReader(new BufferedInputStream(new FileInputStream(xslPath)))); Templates cachedXSLT = factory.newTemplates(s); Transformer transformer = cachedXSLT.newTransformer(); DocumentSource source = new DocumentSource(xmlDocument); StreamResult result = new StreamResult(writer); transformer.transform(source, result); } catch (Exception ex) { } }
public synchronized Transformer getTransformer(String framework, String filename) { if (filename == null || filename.length() == 0) { throw new IllegalArgumentException("filename cannot be null or empty"); } String key = framework + "-" + filename; Templates t = (Templates) pool.getTemplates().get(key); String s = null; if (t == null) { try { WOApplication app = WOApplication.application(); WOResourceManager rm = app.resourceManager(); TransformerFactory fac = TransformerFactory.newInstance(); log.debug("creating template for file " + filename + " in framework " + framework); InputStream is = rm.inputStreamForResourceNamed(filename, framework, null); if (is == null) { log.debug("trying with framework = null"); is = rm.inputStreamForResourceNamed(filename, null, null); if (is == null) { throw new IllegalArgumentException("inputStream is null"); } } if (is.available() == 0) { throw new IllegalArgumentException( "InputStream has 0 bytes available, cannot read xsl file!"); } s = ERXFileUtilities.stringFromInputStream(is); s = templateParser.parseTemplateWithObject(s, "@@", app); t = fac.newTemplates(new StreamSource(new ByteArrayInputStream(s.getBytes()))); if (app.isCachingEnabled()) { templates.put(key, t); } } catch (IOException e1) { throw NSForwardException._runtimeExceptionForThrowable(e1); } catch (TransformerConfigurationException tce) { log.error("could not create template " + tce.getLocationAsString(), tce); log.error(" cause", tce.getCause()); if (tce.getCause() != null && tce.getCause() instanceof org.xml.sax.SAXParseException) { org.xml.sax.SAXParseException e = (org.xml.sax.SAXParseException) tce.getCause(); log.error( "SAXParseException: line " + e.getLineNumber() + ", column " + e.getColumnNumber()); } log.error("this is the incorrect xsl:>>>" + s + "<<<"); return null; } } try { return t.newTransformer(); } catch (TransformerConfigurationException tce) { log.error("could not create template " + tce.getLocationAsString(), tce); log.error(" cause", tce.getCause()); return null; } }
private void transform(StreamSource xmlStream, StreamSource xslStream, StreamResult result) { try { TransformerFactory factory = TransformerFactory.newInstance(); Templates template = factory.newTemplates(xslStream); Transformer transformer = template.newTransformer(); transformer.transform(xmlStream, result); } catch (TransformerException e) { e.printStackTrace(); } }
protected static void initTransformers() throws Exception { transformers = new HashMap<String, Transformer>(); TransformerFactory xformFactory = new org.apache.xalan.processor.TransformerFactoryImpl(); transformers.put( "WADL", xformFactory .newTemplates( new StreamSource( SoapUI.class.getResourceAsStream( "/com/eviware/soapui/resources/doc/wadl_documentation.xsl"))) .newTransformer()); }
/** Maintain prepared stylesheets in memory for reuse */ public static Templates tryTemplCache(String path) throws TransformerException, FileNotFoundException, CitationStyleManagerException { Utils.checkName(path, "Empty XSLT name."); InputStream is = ResourceUtil.getResourceAsStream(path, XmlHelper.class.getClassLoader()); Templates x = templCache.get(path); if (x == null) { x = tf.newTemplates(new StreamSource(is)); templCache.put(path, x); } return x; }
protected static void prettify(OMElement wsdlElement, OutputStream out) throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); wsdlElement.serialize(baos); Source stylesheetSource = new StreamSource(new ByteArrayInputStream(prettyPrintStylesheet.getBytes())); Source xmlSource = new StreamSource(new ByteArrayInputStream(baos.toByteArray())); TransformerFactory tf = TransformerFactory.newInstance(); Templates templates = tf.newTemplates(stylesheetSource); Transformer transformer = templates.newTransformer(); transformer.transform(xmlSource, new StreamResult(out)); }
@Test public void testTransformInitialDoc() throws Exception { TransformerFactory factory = TransformerFactory.newInstance(); Source styleSheet = new StreamSource(this.getClass().getClassLoader().getResourceAsStream(STYLESHEET_RESOURCE)); Templates templates = templates = factory.newTemplates(styleSheet); Transformer transformer = templates.newTransformer(); transformer.setOutputProperty("indent", "yes"); transformer.setParameter("readOnly", "false"); // transformer.setParameter("docType", docType); // transformer.setParameter("schema", schema); Source input = new StreamSource(this.getClass().getResourceAsStream(INITIAL_EDOC_XML)); transformer.transform(input, new StreamResult(System.out)); }
public static void xslt(Document data, Document xsl, Result result, boolean outHead) throws TransformerException { TransformerFactory factory = TransformerFactory.newInstance(); Templates templates = factory.newTemplates(new DOMSource(xsl)); Transformer transformer = templates.newTransformer(); if (!outHead) { transformer.setOutputProperty("omit-xml-declaration", "yes"); } else { transformer.setOutputProperty("omit-xml-declaration", "no"); } transformer.setOutputProperty("encoding", encoding); transformer.transform(new DOMSource(data), result); }
@Override protected Object read(InputStream in) throws IOException { // store in a string so that we can perform validation String xslt = IOUtils.toString(in); try { Source xslSource = new StreamSource(new StringReader(xslt)); TransformerFactory tf = TransformerFactory.newInstance(); tf.newTemplates(xslSource); } catch (Exception e) { throw new RestletException( "Invalid XSLT : " + e.getMessage(), Status.CLIENT_ERROR_BAD_REQUEST); } return xslt; }
private Transform() { try { ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); Resource[] resources = resolver.getResources(TEMPLATES_PATH); for (Resource resource : resources) { templates.put( getName(resource), transformerFactory.newTemplates(new StreamSource(resource.getURL().openStream()))); } } catch (IOException e) { throw new RuntimeException( "Failed to discover XSLT resources in '" + TEMPLATES_PATH + "'", e); } catch (TransformerConfigurationException e) { throw new RuntimeException("Error loading XSLT stylesheets", e); } if (log.isDebugEnabled()) { log.debug("templates=" + new TreeSet<String>(templates.keySet())); } }
SchemaReaderImpl(TransformerFactory transformerFactory) throws TransformerConfigurationException, IncorrectSchemaException { this.transformerFactoryClass = transformerFactory.getClass(); String resourceName = fullResourceName(SCHEMATRON_STYLESHEET); StreamSource source = new StreamSource(getResourceAsStream(resourceName)); initTransformerFactory(transformerFactory); schematron = transformerFactory.newTemplates(source); InputSource schemaSource = new InputSource(getResourceAsStream(fullResourceName(SCHEMATRON_SCHEMA))); PropertyMapBuilder builder = new PropertyMapBuilder(); ValidateProperty.ERROR_HANDLER.put(builder, new DraconianErrorHandler()); RngProperty.CHECK_ID_IDREF.add(builder); try { schematronSchema = CompactSchemaReader.getInstance().createSchema(schemaSource, builder.toPropertyMap()); } catch (SAXException e) { throw new IncorrectSchemaException(); } catch (IOException e) { throw new IncorrectSchemaException(); } }
// 使用XSLT模板对Document进行转化 public static Document getStyleDocument(Document document, String xsltfile) throws Exception { InputStream in = null; if (CommonPath.path == null || CommonPath.path.equals("")) { in = ClassLoader.getSystemResourceAsStream(xsltfile); } else { String[] ss = xsltfile.split("/"); String filename = ss[ss.length - 1]; File file = new File(CommonPath.path + filename); in = new FileInputStream(file); } DocumentSource docSource = new DocumentSource(document); DocumentResult docResult = new DocumentResult(); TransformerFactory factory = TransformerFactory.newInstance(); Templates cachedXSLT = factory.newTemplates(new StreamSource(in)); Transformer transformer = cachedXSLT.newTransformer(); if (transformer != null) { transformer.transform(docSource, docResult); } Document resultDoc = docResult.getDocument(); return resultDoc; }
private Transformer getTransformer() throws TransformerConfigurationException, FileNotFoundException { if (this.cachedXslt == null) { TransformerFactory factory = TransformerFactory.newInstance(); // Get Filter InputStream is = null; Source xslt = null; if (StringUtil.isNotEmpty(customFilterPath)) { File file = new File(customFilterPath); if (!file.exists()) { throw new FileNotFoundException("Could not Find Swiper XSLT Filter"); } xslt = new StreamSource(file); } else { is = getClass().getResourceAsStream(DEFAULT_FILTER); xslt = new StreamSource(is); } this.cachedXslt = factory.newTemplates(xslt); try { if (is != null) { is.close(); } } catch (IOException e) { } } return cachedXslt.newTransformer(); }
/** * Constructs a new object. * * @param source the source URL of this endpoint * @exception IOException error creating the receiver */ public MmiReceiver(final String source) throws IOException { listeners = new java.util.ArrayList<MMIEventListener>(); sourceUrl = source; final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); // Configure the factory to ignore comments factory.setIgnoringComments(true); try { builder = factory.newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new IOException(e.getMessage(), e); } TransformerFactory transFact = TransformerFactory.newInstance(); try { final URL xsltURL = UmundoETLProtocolAdapter.class.getResource("VoiceXmlTemplate.xsl"); final String xsltSystemID = xsltURL.toExternalForm(); template = transFact.newTemplates(new StreamSource(xsltSystemID)); } catch (TransformerConfigurationException tce) { throw new IOException("Unable to compile stylesheet", tce); } }
private void doWork(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setDateHeader("Expires", 0); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Pragma", "no-cache"); response.setContentType("text/html; charset=UTF-8"); // identificador de archivo de usuario. Integer archiveId = RequestUtils.parseRequestParameterAsInteger(request, "ArchiveId"); // Identificador de carpeta. Integer folderId = RequestUtils.parseRequestParameterAsInteger(request, "FolderId"); // Obtenemos la sesión asociada al usuario. HttpSession session = request.getSession(); // Texto del idioma. Ej: EU_ String idioma = (String) session.getAttribute(Keys.J_IDIOMA); // Número del idioma. Ej: 10 Long numIdioma = (Long) session.getAttribute(Keys.J_NUM_IDIOMA); // Formulario o no. Boolean form = (Boolean) session.getAttribute(Keys.J_OPENFOLDER_FORM); // Obtenemos el objeto de configuración del servidor de aplicaciones y el identificador // de sesión para este usuario en el servidor de aplicaciones. UseCaseConf useCaseConf = (UseCaseConf) session.getAttribute(J_USECASECONF); // response.getWriter().write(ACTIVATE_TREE_1); // response.getWriter().write("LISTA DE DISTRIBUCION"); PrintWriter writer = response.getWriter(); try { Document xmlDocument = bookUseCase.getDtrFdrResults(useCaseConf, archiveId, folderId.intValue()); String xslPath = ContextUtil.getRealPath(session.getServletContext(), XSL_DTRLISTFDR_RELATIVE_PATH); StreamSource s = new StreamSource( new InputStreamReader(new BufferedInputStream(new FileInputStream(xslPath)))); Templates cachedXSLT = factory.newTemplates(s); Transformer transformer = cachedXSLT.newTransformer(); DocumentSource source = new DocumentSource(xmlDocument); StreamResult result = new StreamResult(writer); transformer.transform(source, result); } catch (ValidationException e) { _logger.fatal("Error de validacion", e); writer.write(ACTIVATE_TREE_1); ResponseUtils.generateJavaScriptLog( writer, RBUtil.getInstance(useCaseConf.getLocale()) .getProperty(Keys.I18N_EXCEPTION_VALIDATIONEXCEPTION)); } catch (BookException e) { _logger.fatal("Error en el libro", e); writer.write(ACTIVATE_TREE_1); ResponseUtils.generateJavaScriptError(writer, e); } catch (SessionException e) { _logger.fatal("Error en la sesion", e); ResponseUtils.generateJavaScriptLogSessionExpiredDtrfdr( writer, e.getMessage(), idioma, numIdioma); // ResponseUtils.generateJavaScriptError(response, e); } catch (TransformerConfigurationException e) { _logger.fatal("Error en la distribucion", e); writer.write(ACTIVATE_TREE_1); ResponseUtils.generateJavaScriptLog( writer, RBUtil.getInstance(useCaseConf.getLocale()) .getProperty(Keys.I18N_ISICRESSRV_ERR_CREATING_DTR_OBJ)); } catch (TransformerFactoryConfigurationError e) { _logger.fatal("Error en la distribucion", e); writer.write(ACTIVATE_TREE_1); ResponseUtils.generateJavaScriptLog( writer, RBUtil.getInstance(useCaseConf.getLocale()) .getProperty(Keys.I18N_ISICRESSRV_ERR_CREATING_DTR_OBJ)); } catch (TransformerException e) { _logger.fatal("Error en la distribucion", e); writer.write(ACTIVATE_TREE_1); ResponseUtils.generateJavaScriptLog( writer, RBUtil.getInstance(useCaseConf.getLocale()) .getProperty(Keys.I18N_ISICRESSRV_ERR_CREATING_DTR_OBJ)); } catch (Exception e) { _logger.fatal("Error en la distribucion", e); writer.write(ACTIVATE_TREE_1); ResponseUtils.generateJavaScriptLog( writer, RBUtil.getInstance(useCaseConf.getLocale()) .getProperty(Keys.I18N_ISICRESSRV_ERR_CREATING_DTR_OBJ)); } }
// 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"); } }
/** * @param path Path, starting with /, relative to context root, of xsl * @return The jaxp object for the specified path. * @exception ConfigException */ protected Templates loadTemplate(String path, ServletContext servletCtx) throws ConfigException { boolean pathIsFileUrl = false; boolean pathIsOtherUrl = false; java.net.URL resURL = null; if (this.isMonitoredFile && this.monitoredFile != null) { // This happens if the file is monitored and it has changed on the filesystem try { resURL = this.monitoredFile.toURI().toURL(); this.monitoredFileLastModified = this.monitoredFile.lastModified(); } catch (MalformedURLException me) { log.error("Eror parsing monitored template URL " + path + ": " + me.toString()); throw new ConfigException(me); } catch (SecurityException se) { log.error("Unable to access monitored template " + path + ": " + se.toString()); throw new ConfigException(se); } } else { // Check to see if the path is a URL and what type, otherwise make sure // it's a proper servlet resource path if (path.toLowerCase().startsWith("file:")) pathIsFileUrl = true; else if (path.toLowerCase().startsWith("http:") || path.toLowerCase().startsWith("https:") || path.toLowerCase().startsWith("ftp:")) pathIsOtherUrl = true; else if (!path.startsWith("/")) path = "/" + path; try { if (pathIsFileUrl && this.isMonitoredFile) { resURL = new java.net.URL(path); this.monitoredFile = new File(resURL.getFile()); if (this.monitoredFile == null || !this.monitoredFile.canRead()) { this.monitoredFile = null; log.error("Resource not found or unable to read file: " + path); throw new ConfigException("Resource not found or unable to read file: " + path); } this.monitoredFileLastModified = this.monitoredFile.lastModified(); } else if (pathIsFileUrl || pathIsOtherUrl) resURL = new java.net.URL(path); else resURL = servletCtx.getResource(path); if (resURL == null) { log.error("Resource not found: " + path); throw new ConfigException("Resource not found: " + path); } } catch (MalformedURLException me) { log.error("Eror parsing template URL " + path + ": " + me.toString()); throw new ConfigException(me); } } try { TransformerFactory tFactory = TransformerFactory.newInstance(); if (this.uriResolver != null) tFactory.setURIResolver(this.uriResolver); return tFactory.newTemplates(new StreamSource(resURL.openStream(), resURL.toString())); } catch (TransformerException ex) { log.error("Error loading template " + path + ": " + ex.toString()); throw new ConfigException(ex); } catch (IOException ex) { log.error("Eror loading template " + path + ": " + ex.toString()); throw new ConfigException(ex); } }
private void createTemplate(Source xslSource) throws TransformerException { if (m_template == null) { m_template = m_tFactory.newTemplates(xslSource); } }
private boolean processOneXMLFile( String xmlfilename, String xslfilename, String outputfilename, Result result, Job parentJob) { boolean retval = false; FileObject xmlfile = null; FileObject xslfile = null; FileObject outputfile = null; try { xmlfile = KettleVFS.getFileObject(xmlfilename, this); xslfile = KettleVFS.getFileObject(xslfilename, this); outputfile = KettleVFS.getFileObject(outputfilename, this); if (xmlfile.exists() && xslfile.exists()) { if (outputfile.exists() && iffileexists == 2) { // Output file exists // User want to fail logError( BaseMessages.getString(PKG, "JobEntryXSLT.OuputFileExists1.Label") + outputfilename + BaseMessages.getString(PKG, "JobEntryXSLT.OuputFileExists2.Label")); return retval; } else if (outputfile.exists() && iffileexists == 1) { // Do nothing if (log.isDebug()) { logDebug( BaseMessages.getString(PKG, "JobEntryXSLT.OuputFileExists1.Label") + outputfilename + BaseMessages.getString(PKG, "JobEntryXSLT.OuputFileExists2.Label")); } retval = true; return retval; } else { if (outputfile.exists() && iffileexists == 0) { // the output file exists and user want to create new one with unique name // Format Date // Try to clean filename (without wildcard) String wildcard = outputfilename.substring(outputfilename.length() - 4, outputfilename.length()); if (wildcard.substring(0, 1).equals(".")) { // Find wildcard outputfilename = outputfilename.substring(0, outputfilename.length() - 4) + "_" + StringUtil.getFormattedDateTimeNow(true) + wildcard; } else { // did not find wildcard outputfilename = outputfilename + "_" + StringUtil.getFormattedDateTimeNow(true); } if (log.isDebug()) { logDebug( BaseMessages.getString(PKG, "JobEntryXSLT.OuputFileExists1.Label") + outputfilename + BaseMessages.getString(PKG, "JobEntryXSLT.OuputFileExists2.Label")); logDebug( BaseMessages.getString(PKG, "JobEntryXSLT.OuputFileNameChange1.Label") + outputfilename + BaseMessages.getString(PKG, "JobEntryXSLT.OuputFileNameChange2.Label")); } } // Create transformer factory TransformerFactory factory = TransformerFactory.newInstance(); if (xsltfactory.equals(FACTORY_SAXON)) { // Set the TransformerFactory to the SAXON implementation. factory = new net.sf.saxon.TransformerFactoryImpl(); } if (log.isDetailed()) { log.logDetailed( BaseMessages.getString(PKG, "JobEntryXSL.Log.TransformerFactoryInfos"), BaseMessages.getString( PKG, "JobEntryXSL.Log.TransformerFactory", factory.getClass().getName())); } InputStream xslInputStream = KettleVFS.getInputStream(xslfile); InputStream xmlInputStream = KettleVFS.getInputStream(xmlfile); OutputStream os = null; try { // Use the factory to create a template containing the xsl file Templates template = factory.newTemplates(new StreamSource(xslInputStream)); // Use the template to create a transformer Transformer xformer = template.newTransformer(); if (log.isDetailed()) { log.logDetailed( BaseMessages.getString(PKG, "JobEntryXSL.Log.TransformerClassInfos"), BaseMessages.getString( PKG, "JobEntryXSL.Log.TransformerClass", xformer.getClass().getName())); } // Do we need to set output properties? if (setOutputProperties) { xformer.setOutputProperties(outputProperties); } // Do we need to pass parameters? if (useParameters) { for (int i = 0; i < nrParams; i++) { xformer.setParameter(nameOfParams[i], valueOfParams[i]); } } // Prepare the input and output files Source source = new StreamSource(xmlInputStream); os = KettleVFS.getOutputStream(outputfile, false); StreamResult resultat = new StreamResult(os); // Apply the xsl file to the source file and write the result to the output file xformer.transform(source, resultat); if (isAddFileToResult()) { // Add output filename to output files ResultFile resultFile = new ResultFile( ResultFile.FILE_TYPE_GENERAL, KettleVFS.getFileObject(outputfilename, this), parentJob.getJobname(), toString()); result.getResultFiles().put(resultFile.getFile().toString(), resultFile); } // Everything is OK retval = true; } finally { try { xslInputStream.close(); } catch (IOException ignored) { // ignore IO Exception on close } try { xmlInputStream.close(); } catch (IOException ignored) { // ignore IO Exception on close } try { if (os != null) { os.close(); } } catch (IOException ignored) { // ignore IO Exception on close } } } } else { if (!xmlfile.exists()) { logError( BaseMessages.getString(PKG, "JobEntryXSLT.FileDoesNotExist1.Label") + xmlfilename + BaseMessages.getString(PKG, "JobEntryXSLT.FileDoesNotExist2.Label")); } if (!xslfile.exists()) { logError( BaseMessages.getString(PKG, "JobEntryXSLT.FileDoesNotExist1.Label") + xmlfilename + BaseMessages.getString(PKG, "JobEntryXSLT.FileDoesNotExist2.Label")); } } } catch (Exception e) { logError( BaseMessages.getString(PKG, "JobEntryXSLT.ErrorXLST.Label") + BaseMessages.getString(PKG, "JobEntryXSLT.ErrorXLSTXML1.Label") + xmlfilename + BaseMessages.getString(PKG, "JobEntryXSLT.ErrorXLSTXML2.Label") + BaseMessages.getString(PKG, "JobEntryXSLT.ErrorXLSTXSL1.Label") + xslfilename + BaseMessages.getString(PKG, "JobEntryXSLT.ErrorXLSTXSL2.Label") + e.getMessage()); } finally { try { if (xmlfile != null) { xmlfile.close(); } if (xslfile != null) { xslfile.close(); } if (outputfile != null) { outputfile.close(); } } catch (IOException e) { logError("Unable to close file", e); } } return retval; }