Example #1
0
  /** Check for required facilities. If not available, an exception will be thrown. */
  public TemplatesPool(boolean templateCaching) throws Exception {
    final TransformerFactory tFactory = TransformerFactory.newInstance();
    final String processorClass = tFactory.getClass().getName();

    /*
     * Only report XSLT processor class once.
     */
    if (!reportedProcessors.contains(processorClass)) {
      logger.info("XSLT transformer factory: " + processorClass);
      reportedProcessors.add(processorClass);
    }

    if (!tFactory.getFeature(SAXSource.FEATURE) || !tFactory.getFeature(SAXResult.FEATURE)) {
      throw new Exception("Required source types not supported by the transformer factory.");
    }

    if (!tFactory.getFeature(SAXResult.FEATURE) || !tFactory.getFeature(StreamResult.FEATURE)) {
      throw new Exception("Required result types not supported by the transformer factory.");
    }

    if (!(tFactory instanceof SAXTransformerFactory)) {
      throw new Exception(
          "TransformerFactory not an instance of SAXTransformerFactory: "
              + tFactory.getClass().getName());
    }

    this.tFactory = ((SAXTransformerFactory) tFactory);
    this.tFactory.setErrorListener(new StylesheetErrorListener());
    this.templateCaching = templateCaching;
  }
Example #2
0
 /**
  * Clears the cache used in the stylesheet transformer factory. This will only work for the
  * GeoNetwork Caching stylesheet transformer factory. This is a no-op for other transformer
  * factories.
  */
 public static void clearTransformerFactoryStylesheetCache() {
   TransformerFactory transFact = TransformerFactory.newInstance();
   try {
     Class<?> class1 = transFact.getClass();
     Method cacheMethod = class1.getDeclaredMethod("clearCache");
     cacheMethod.invoke(transFact, new Object[0]);
   } catch (Exception e) {
     Log.error(
         Log.ENGINE,
         "Failed to find/invoke clearCache method - continuing (" + e.getMessage() + ")");
   }
 }
Example #3
0
 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) {
   }
 }
Example #4
0
 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();
   }
 }
  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;
  }
  public void apply(File xmlSourceDirectory, File targetDirectory, DocErrorReporter reporter)
      throws DocTransletException {

    PrintStream err = System.err;

    try {
      URL mainResourceURL =
          classLoader == null
              ? ClassLoader.getSystemResource(mainResourceFilename)
              : classLoader.getResource(mainResourceFilename);

      if (null == mainResourceURL) {
        throw new DocTransletException("Cannot find resource '" + mainResourceFilename + "'");
      }

      Map parameters = new HashMap();
      parameters.put("gjdoc.xmldoclet.version", Driver.XMLDOCLET_VERSION);

      parameters.put("gjdoc.option.nonavbar", xsltBoolean(options.nonavbar));
      parameters.put("gjdoc.option.noindex", xsltBoolean(options.noindex));
      parameters.put("gjdoc.option.notree", xsltBoolean(options.notree));
      parameters.put("gjdoc.option.nocomment", xsltBoolean(options.nocomment));
      parameters.put("gjdoc.option.nohelp", xsltBoolean(options.nohelp));
      parameters.put("gjdoc.option.splitindex", xsltBoolean(options.splitindex));
      parameters.put("gjdoc.option.linksource", xsltBoolean(options.linksource));
      parameters.put("gjdoc.option.nodeprecatedlist", xsltBoolean(options.nodeprecatedlist));
      parameters.put("gjdoc.option.uses", xsltBoolean(options.uses));
      parameters.put("gjdoc.option.windowtitle", options.windowtitle);
      parameters.put("gjdoc.option.helpfile", options.helpfile);
      parameters.put("gjdoc.option.stylesheetfile", options.stylesheetfile);
      parameters.put("gjdoc.option.header", options.header);
      parameters.put("gjdoc.option.footer", options.footer);
      parameters.put("gjdoc.option.bottom", options.bottom);
      parameters.put("gjdoc.option.doctitle", options.doctitle);

      List outputFileList = getOutputFileList(mainResourceURL, xmlSourceDirectory, parameters);

      reporter.printNotice("Running DocTranslet...");

      TransformerFactory transformerFactory = TransformerFactory.newInstance();

      transformerFactory.setErrorListener(this);

      boolean isLibxmlJ =
          transformerFactory
              .getClass()
              .getName()
              .equals("gnu.xml.libxmlj.transform.TransformerFactoryImpl");

      for (Iterator it = outputFileList.iterator(); it.hasNext(); ) {

        if (isLibxmlJ) {
          System.gc();
          Runtime.getRuntime().runFinalization();
        }

        OutputFileInfo fileInfo = (OutputFileInfo) it.next();

        File targetFile = new File(targetDirectory, fileInfo.getName());
        File packageTargetDir = getParentFile(targetFile);

        if (!packageTargetDir.exists() && !packageTargetDir.mkdirs()) {
          throw new DocTransletException(
              "Target directory " + packageTargetDir + " does not exist and cannot be created.");
        }

        if (options.linksource) {
          File sourceTargetDirectory = new File(targetDirectory, "src-html");
          File sourceTargetFile = new File(sourceTargetDirectory, fileInfo.getName());
          File sourcePackageTargetDir = getParentFile(sourceTargetFile);

          if (!sourcePackageTargetDir.exists() && !sourcePackageTargetDir.mkdirs()) {
            throw new DocTransletException(
                "Target directory " + packageTargetDir + " does not exist and cannot be created.");
          }
        }

        if (options.uses) {
          File usesTargetDirectory = new File(targetDirectory, "class-use");
          File usesTargetFile = new File(usesTargetDirectory, fileInfo.getName());
          File usesPackageTargetDir = getParentFile(usesTargetFile);

          if (!usesPackageTargetDir.exists() && !usesPackageTargetDir.mkdirs()) {
            throw new DocTransletException(
                "Target directory " + packageTargetDir + " does not exist and cannot be created.");
          }
        }

        if (null != fileInfo.getSource()) {

          reporter.printNotice("Copying " + fileInfo.getComment() + "...");
          InputStream in = new URL(mainResourceURL, fileInfo.getSource()).openStream();
          FileOutputStream out = new FileOutputStream(targetFile.getAbsolutePath());
          IOToolkit.copyStream(in, out);
          in.close();
          out.close();
        } else {

          reporter.printNotice("Generating " + fileInfo.getComment() + "...");

          String pathToRoot = "";
          for (File file = getParentFile(targetFile);
              !equalsFile(file, targetDirectory);
              file = getParentFile(file)) {
            pathToRoot += "../";
          }

          StreamResult out = new StreamResult(targetFile.getAbsolutePath());

          StreamSource in =
              new StreamSource(new File(xmlSourceDirectory, "index.xml").getAbsolutePath());
          URL resource = new URL(mainResourceURL, fileInfo.getSheet());

          StreamSource xsltSource = new StreamSource(resource.toExternalForm());

          if (null != fileInfo.getInfo()) {
            parameters.put("gjdoc.outputfile.info", fileInfo.getInfo());
          }
          parameters.put("gjdoc.pathtoroot", pathToRoot);

          Transformer transformer;
          transformer = (Transformer) transformerMap.get(xsltSource.getSystemId());
          if (null == transformer) {
            transformer = transformerFactory.newTransformer(xsltSource);
            if (cacheXSLTSheets) {
              transformerMap.put(xsltSource.getSystemId(), transformer);
            }
          }

          transformer.clearParameters();
          for (Iterator pit = parameters.keySet().iterator(); pit.hasNext(); ) {
            String key = (String) pit.next();
            String value = (String) parameters.get(key);
            transformer.setParameter(key, value);
          }

          transformer.setErrorListener(this);
          DocErrorReporterOutputStream errorReporterOut =
              new DocErrorReporterOutputStream(reporter);
          System.setErr(new PrintStream(errorReporterOut));

          transformer.transform(in, out);
          errorReporterOut.flush();
        }
      }
    } catch (MalformedURLException e) {
      throw new DocTransletException(e);
    } catch (TransformerFactoryConfigurationError e) {
      throw new DocTransletException(e);
    } catch (TransformerException e) {
      throw new DocTransletException(e.getMessageAndLocation(), e);
    } catch (IOException e) {
      throw new DocTransletException(e);
    } finally {
      System.setErr(err);
    }
  }