Пример #1
2
  public static void writeXmlFile(Document doc, File saveFile, boolean systemOut) {
    try {

      Source source = new DOMSource(doc);
      Transformer xformer = TransformerFactory.newInstance().newTransformer();
      xformer.setParameter(OutputKeys.INDENT, "yes");
      xformer.setOutputProperty(OutputKeys.INDENT, "yes");
      xformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

      if (saveFile != null) {
        Result result = new StreamResult(saveFile);
        xformer.transform(source, result);
      }

      Writer outputWriter = new StringWriter();
      Result stringOut = new StreamResult(outputWriter);
      xformer.transform(source, stringOut);

      //            new SinglePanelPopup(new TextAreaPane(outputWriter.toString()));

      if (systemOut) {
        Result system = new StreamResult(System.out);
        xformer.transform(source, system);
      }

    } catch (TransformerConfigurationException e) {
    } catch (TransformerException e) {
    }
  }
Пример #2
0
  private static String getXHTMLfromGameXML(String gameXML, String XSL) {
    XSL = XSL.replace("<!DOCTYPE stylesheet [<!ENTITY ROOT \"http://games.ggp.org/base\">]>", "");
    XSL = XSL.replace("&ROOT;", "http://games.ggp.org/base").trim();

    IOString game = new IOString(gameXML);
    IOString xslIOString = new IOString(XSL);
    IOString content = new IOString("");
    try {
      TransformerFactory tFactory = TransformerFactory.newInstance();
      Transformer transformer =
          tFactory.newTransformer(new StreamSource(xslIOString.getInputStream()));
      transformer.setParameter("width", defaultSize.getWidth() - 40);
      transformer.setParameter("height", defaultSize.getHeight() - 40);
      transformer.transform(
          new StreamSource(game.getInputStream()), new StreamResult(content.getOutputStream()));
    } catch (Exception ex) {
      ex.printStackTrace();
    }

    Tidy tidy = new Tidy();
    tidy.setXHTML(true);
    tidy.setShowWarnings(false);
    tidy.setQuiet(true);
    tidy.setDropEmptyParas(false);

    IOString tidied = new IOString("");
    tidy.parse(content.getInputStream(), tidied.getOutputStream());
    return tidied.getString();
  }
  private void doXslTransform(
      ServiceBinding binding,
      XSLTServiceBindingValueSourceConfig config,
      Reader reader,
      Writer writer) {
    Source xmlSource = new StreamSource(reader);
    Result xmlResult = new StreamResult(writer);
    Source xslSource = new StreamSource(new StringReader(config.getXslt()));

    TransformerFactory factory = TransformerFactory.newInstance();
    try {
      Transformer transformer = factory.newTransformer(xslSource);

      transformer.setParameter("port", new Integer(binding.getPort()));
      String host = binding.getHostName();
      if (host != null) {
        transformer.setParameter("host", host);
      }

      // Check for any arbitrary attributes
      Map<String, String> attributes = config.getAdditionalAttributes();
      for (Map.Entry<String, String> entry : attributes.entrySet()) {
        String attrValue = StringPropertyReplacer.replaceProperties(entry.getValue());
        transformer.setParameter(entry.getKey(), attrValue);
      }

      transformer.transform(xmlSource, xmlResult);
    } catch (TransformerException e) {
      throw new RuntimeException("Caught TransformerException during transformation", e);
    }
  }
 protected Transformer buildTransformer(Message<?> message) throws TransformerException {
   // process  individual mappings
   Transformer transformer = this.templates.newTransformer();
   context.setRootObject(message);
   context.addPropertyAccessor(new MapAccessor());
   if (xslParameterMappings != null) {
     for (String parameterName : xslParameterMappings.keySet()) {
       Expression expression = xslParameterMappings.get(parameterName);
       Object value = null;
       try {
         value = expression.getValue(context);
         transformer.setParameter(parameterName, value);
       } catch (Exception e) {
         logger.warn(
             "Header expression '"
                 + expression.getExpressionString()
                 + "' can not resolve within current message and will not be mapped to XSLT parameter");
       }
     }
   }
   // process xslt-parameter-headers
   MessageHeaders headers = message.getHeaders();
   if (xsltParamHeaders != null) {
     for (String headerName : headers.keySet()) {
       if (PatternMatchUtils.simpleMatch(xsltParamHeaders, headerName)) {
         transformer.setParameter(headerName, headers.get(headerName));
       }
     }
   }
   return transformer;
 }
  public void generateEngineOutputManager(
      File servicePath, Document describeDocument, String processingName) throws Exception {
    File stylesheet = new File(servicePath, SHELL_OUTPUT_MANAGER_XLST_PATH);
    Document xslDocument;
    File shellScriptFolder = new File(servicePath, SHELL_SCRIPT_PATH);
    shellScriptFolder.mkdirs();

    if (stylesheet.exists()) {
      xslDocument = domUtil.fileToDocument(stylesheet);
      transformer =
          TransformerFactory.newInstance()
              .newTemplates(new DOMSource(xslDocument))
              .newTransformer();
      transformer.setParameter("processingName", processingName);
      transformer.setParameter(
          "complexDataFolderPath", new File(servicePath, COMPLEX_DATA_PATH).getAbsolutePath());
      transformer.transform(
          new StreamSource(DOMUtil.getDocumentAsInputStream(describeDocument)),
          new StreamResult(
              new FileOutputStream(
                  new File(
                      shellScriptFolder,
                      SHELL_SCRIPT_FILE_PREFIX + processingName + "_outputManager.tmp"))));
    }
  }
Пример #6
0
  private String transformContent(
      ServerRequestContext context, String xsltId, String xmlNotif, String action, String user)
      throws RegistryException {
    try {
      RepositoryItem repositoryItem =
          RepositoryManagerFactory.getInstance().getRepositoryManager().getRepositoryItem(xsltId);
      StreamSource xsltIn = new StreamSource(repositoryItem.getDataHandler().getInputStream());

      TransformerFactory tFactory = TransformerFactory.newInstance();
      Transformer transformer = tFactory.newTransformer(xsltIn);

      // transformer.setURIResolver(rm.getURIResolver());
      transformer.setErrorListener(
          new ErrorListener() {
            public void error(TransformerException exception) throws TransformerException {
              log.info(ServerResourceBundle.getInstance().getString("xsltError"), exception);
            }

            public void fatalError(TransformerException exception) throws TransformerException {
              log.error(ServerResourceBundle.getInstance().getString("xsltFatalError"), exception);
              throw exception;
            }

            public void warning(TransformerException exception) throws TransformerException {
              log.info(ServerResourceBundle.getInstance().getString("xsltWarning"), exception);
            }
          });

      // Set parameters
      transformer.setParameter("action", action);
      transformer.setParameter("user", user);
      transformer.setParameter(
          "registryBaseURL", RegistryProperties.getInstance().getProperty("omar.registry.baseurl"));

      ByteArrayInputStream bais = new ByteArrayInputStream(xmlNotif.getBytes("utf-8"));
      StreamSource inputSrc = new StreamSource(bais);

      // TODO: use file in case we have a large amount of data to transform?
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      StreamResult streamResult = new StreamResult(baos);

      transformer.transform(inputSrc, streamResult);

      return baos.toString("utf-8");
    } catch (Exception e) {
      log.error(
          ServerResourceBundle.getInstance().getString("message.prettyPrintNotificationFailure"),
          e);
      throw new RegistryException(e);
    }
  }
Пример #7
0
 private SAXSource createTransformingSource(
     SAXSource in, String phase, boolean diagnose, String systemId, CountingErrorHandler ceh)
     throws SAXException {
   try {
     Transformer transformer = schematron.newTransformer();
     transformer.setErrorListener(new DraconianErrorListener());
     if (phase != null) transformer.setParameter("phase", phase);
     if (diagnose) transformer.setParameter("diagnose", Boolean.TRUE);
     return new SAXSource(
         new TransformStage(transformer, in, systemId, ceh, localizer), new InputSource(systemId));
   } catch (TransformerConfigurationException e) {
     throw new SAXException(e);
   }
 }
  /**
   * Method updates existing Spring bean definitions in a XML application context file. Bean
   * definition is identified by its type defining class.
   *
   * @param project
   * @param type
   * @param jaxbElement
   */
  public void updateBeanDefinitions(
      File configFile, Project project, Class<?> type, Object jaxbElement) {
    Source xsltSource;
    Source xmlSource;
    try {
      xsltSource =
          new StreamSource(
              new ClassPathResource("transform/update-bean-type.xsl").getInputStream());
      xsltSource.setSystemId("update-bean");

      List<File> configFiles = new ArrayList<>();
      configFiles.add(configFile);
      configFiles.addAll(getConfigImports(configFile, project));

      LSParser parser = XMLUtils.createLSParser();
      GetSpringBeansFilter getBeanFilter = new GetSpringBeansFilter(type, null);
      parser.setFilter(getBeanFilter);

      for (File file : configFiles) {
        parser.parseURI(file.toURI().toString());
        if (!CollectionUtils.isEmpty(getBeanFilter.getBeanDefinitions())) {
          xmlSource = new StringSource(FileUtils.readToString(new FileInputStream(file)));

          String beanElement = type.getAnnotation(XmlRootElement.class).name();
          String beanNamespace = type.getPackage().getAnnotation(XmlSchema.class).namespace();

          // create transformer
          Transformer transformer = transformerFactory.newTransformer(xsltSource);
          transformer.setParameter("bean_element", beanElement);
          transformer.setParameter("bean_namespace", beanNamespace);
          transformer.setParameter(
              "bean_content",
              getXmlContent(jaxbElement)
                  .replaceAll("(?m)^(\\s<)", getTabs(1, project.getSettings().getTabSize()) + "$1")
                  .replaceAll("(?m)^(</)", getTabs(1, project.getSettings().getTabSize()) + "$1"));

          // transform
          StringResult result = new StringResult();
          transformer.transform(xmlSource, result);
          FileUtils.writeToFile(
              format(result.toString(), project.getSettings().getTabSize()), file);
          return;
        }
      }
    } catch (IOException e) {
      throw new ApplicationRuntimeException(UNABLE_TO_READ_TRANSFORMATION_SOURCE, e);
    } catch (TransformerException e) {
      throw new ApplicationRuntimeException(FAILED_TO_UPDATE_BEAN_DEFINITION, e);
    }
  }
Пример #9
0
  /**
   * Transforms the specifed input file to the specifed output file using the specified stylehseet.
   * The entries of the map <code>params</code> are passed as parameters to the stylesheet. The keys
   * of the map must be strings, the values may be arbitrary objects. <code>outputFilename</code>
   * may also be <code>null</code>, in which case the output is sent stdout.
   *
   * @param stylesheetFilename filename of the XSL stylesheet
   * @param inputFilename filename of the input
   * @param outputFilename filename of the output, or <code>null</code> if the output shout go to
   *     stdout
   * @param params parameters to pass to the stylesheet
   * @throws Exception if something goes wrong
   */
  public static void transform(
      String stylesheetFilename, String inputFilename, String outputFilename, Map params)
      throws Exception {
    // Get the stylesheet source object:
    Source stylesheet = new StreamSource(new File(stylesheetFilename));

    // Get the input source object:
    Source input = new StreamSource(new File(inputFilename));

    // Get the output result object:
    Result output =
        (outputFilename != null
            ? new StreamResult(new File(outputFilename))
            : new StreamResult(System.out));

    // Get the transformer:
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    transformerFactory.setErrorListener(new XSLErrorListener());
    Transformer transformer = transformerFactory.newTransformer(stylesheet);
    transformer.setErrorListener(new XSLErrorListener());

    // Pass parameters to the transformer:
    if (params != null) {
      Iterator iterator = params.entrySet().iterator();
      while (iterator.hasNext()) {
        Map.Entry entry = (Map.Entry) iterator.next();
        transformer.setParameter((String) entry.getKey(), entry.getValue());
      }
    }

    // Transform:
    transformer.transform(input, output);
  }
Пример #10
0
  public void xlstCompiledTransformation() throws Exception {

    String xsltFile = "D:\\JZarzuela\\D_S_Escritorio\\xml\\Sat-cfg.xsl";
    String xmlFile = "D:\\JZarzuela\\D_S_Escritorio\\xml\\VariableCFG.xml";
    Source xsltSrc = new StreamSource(xsltFile);
    Source inXML = new StreamSource(new FileInputStream(xmlFile));
    StringWriter sw = new StringWriter();
    Result outXML = new StreamResult(sw);

    // Set the TransformerFactory system property to generate and use a translet.
    // Note: To make this sample more flexible, load properties from a properties file.
    // The setting for the Xalan Transformer is "org.apache.xalan.processor.TransformerFactoryImpl"
    // String key = "javax.xml.transform.TransformerFactory";
    // String value = "org.apache.xalan.xsltc.trax.TransformerFactoryImpl";
    // Properties props = System.getProperties();
    // props.put(key, value);
    // System.setProperties(props);

    org.apache.xalan.xsltc.trax.TransformerFactoryImpl tFactory =
        new org.apache.xalan.xsltc.trax.TransformerFactoryImpl();
    tFactory.setAttribute(TransformerFactoryImpl.USE_CLASSPATH, Boolean.TRUE);
    tFactory.setAttribute(TransformerFactoryImpl.PACKAGE_NAME, "com.jzb.xslt.comp");
    tFactory.setAttribute(TransformerFactoryImpl.GENERATE_TRANSLET, Boolean.FALSE);
    Transformer transformer = tFactory.newTransformer(xsltSrc);

    transformer.setParameter("PARAM_WHICH_CODE", "0001");

    // Perform the transformation from a StreamSource to a StreamResult;
    transformer.transform(inXML, outXML);

    System.out.println(sw.getBuffer());
  }
  private static String transform(
      RestService target, final String reportDirAbsolutePath, String filename) throws Exception {
    if (transformers == null) {
      initTransformers();
    }

    Transformer transformer = transformers.get("WADL");
    if (transformer == null) {
      throw new Exception("Missing transformer for format [" + target + "]");
    }

    transformer.setParameter("output.dir", reportDirAbsolutePath);

    String reportFile = reportDirAbsolutePath + File.separatorChar + "wadl-report.html";
    StreamResult result = new StreamResult(new FileWriter(reportFile));

    WadlDefinitionExporter exporter = new WadlDefinitionExporter(target);
    String infile = exporter.export(reportDirAbsolutePath);

    transformer.setURIResolver(new FileUriResolver(reportDirAbsolutePath));
    transformer.transform(new StreamSource(new FileReader(infile)), result);

    String reportUrl = new File(reportFile).toURI().toURL().toString();
    return reportUrl;
  }
Пример #12
0
  /**
   * Transforms an xml tree putting the result to a stream with optional parameters.
   *
   * @param xml
   * @param styleSheetPath
   * @param result
   * @param params
   * @throws Exception
   */
  public static void transform(
      Element xml, String styleSheetPath, Result result, Map<String, String> params)
      throws Exception {
    File styleSheet = new File(styleSheetPath);
    Source srcXml = new JDOMSource(new Document((Element) xml.detach()));
    Source srcSheet = new StreamSource(styleSheet);

    // Dear old saxon likes to yell loudly about each and every XSLT 1.0
    // stylesheet so switch it off but trap any exceptions because this
    // code is run on transformers other than saxon
    TransformerFactory transFact = TransformerFactoryFactory.getTransformerFactory();
    transFact.setURIResolver(new JeevesURIResolver());
    try {
      transFact.setAttribute(FeatureKeys.VERSION_WARNING, false);
      transFact.setAttribute(FeatureKeys.LINE_NUMBERING, true);
      transFact.setAttribute(FeatureKeys.PRE_EVALUATE_DOC_FUNCTION, false);
      transFact.setAttribute(FeatureKeys.RECOVERY_POLICY, Configuration.RECOVER_SILENTLY);
      // Add the following to get timing info on xslt transformations
      // transFact.setAttribute(FeatureKeys.TIMING,true);
    } catch (IllegalArgumentException e) {
      Log.warning(Log.ENGINE, "WARNING: transformerfactory doesnt like saxon attributes!");
      // e.printStackTrace();
    } finally {
      Transformer t = transFact.newTransformer(srcSheet);
      if (params != null) {
        for (Map.Entry<String, String> param : params.entrySet()) {
          t.setParameter(param.getKey(), param.getValue());
        }
      }
      t.transform(srcXml, result);
    }
  }
Пример #13
0
  private void eatMemory(int callIndex, File foFile, int replicatorRepeats) throws Exception {
    Source src = new StreamSource(foFile);

    Transformer transformer = replicatorTemplates.newTransformer();
    transformer.setParameter("repeats", new Integer(replicatorRepeats));

    OutputStream out = new NullOutputStream(); // write to /dev/nul
    try {
      FOUserAgent userAgent = fopFactory.newFOUserAgent();
      userAgent.setBaseURL(foFile.getParentFile().toURL().toExternalForm());
      Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, userAgent, out);
      Result res = new SAXResult(fop.getDefaultHandler());

      transformer.transform(src, res);

      stats.notifyPagesProduced(fop.getResults().getPageCount());
      if (callIndex == 0) {
        System.out.println(
            foFile.getName() + " generates " + fop.getResults().getPageCount() + " pages.");
      }
      stats.checkStats();
    } finally {
      IOUtils.closeQuietly(out);
    }
  }
Пример #14
0
 public String transform(String type, String input, Map<String, String> transformModel)
     throws TransformException {
   if (log.isDebugEnabled()) {
     log.debug("transform(input=" + input + ")");
   }
   try {
     Templates template = templates.get(type);
     if (log.isDebugEnabled()) {
       log.debug("template=" + template);
     }
     if (template != null) {
       Transformer transformer = template.newTransformer();
       StringWriter writer = new StringWriter(INITIAL_BUFFER_SIZE);
       transformer.setErrorListener(new DefaultErrorListener());
       if (transformModel != null) {
         for (Map.Entry<String, String> entry : transformModel.entrySet()) {
           transformer.setParameter(entry.getKey(), entry.getValue());
         }
       }
       transformer.transform(new StreamSource(new StringReader(input)), new StreamResult(writer));
       String result = writer.toString().trim();
       if (log.isDebugEnabled()) {
         log.debug("result=" + result);
       }
       return result;
     } else {
       String errMsg = "Transformation '" + type + "' not available";
       log.error(errMsg);
       throw new RuntimeException(errMsg);
     }
   } catch (Exception e) {
     log.error("Error during transform", e);
     throw new TransformException(e);
   }
 }
Пример #15
0
  /**
   * Method adds a new Spring bean definition to the XML application context file.
   *
   * @param project
   * @param jaxbElement
   */
  public void addBeanDefinition(File configFile, Project project, Object jaxbElement) {
    Source xsltSource;
    Source xmlSource;
    try {
      xsltSource =
          new StreamSource(new ClassPathResource("transform/add-bean.xsl").getInputStream());
      xsltSource.setSystemId("add-bean");
      xmlSource = new StringSource(FileUtils.readToString(new FileInputStream(configFile)));

      // create transformer
      Transformer transformer = transformerFactory.newTransformer(xsltSource);
      transformer.setParameter(
          "bean_content",
          getXmlContent(jaxbElement)
              .replaceAll("(?m)^(.)", getTabs(1, project.getSettings().getTabSize()) + "$1"));

      // transform
      StringResult result = new StringResult();
      transformer.transform(xmlSource, result);
      FileUtils.writeToFile(
          format(result.toString(), project.getSettings().getTabSize()), configFile);
      return;
    } catch (IOException e) {
      throw new ApplicationRuntimeException(UNABLE_TO_READ_TRANSFORMATION_SOURCE, e);
    } catch (TransformerException e) {
      throw new ApplicationRuntimeException(FAILED_TO_UPDATE_BEAN_DEFINITION, e);
    }
  }
Пример #16
0
  /**
   * Transform the passed XML string with the stated stylesheet.
   *
   * <p>Enables passing any amount of <code>parameters</code> into the stylesheet using a <code>
   * Hashtable</code> to store them as name:value pairs where the key is the name of the parameter
   * and the value is the value.<br>
   * The parameter can be matched in the XSL as follows:<br>
   * &lt;xsl:value-of select=&quot;$parameter_name&quot;&gt;.
   *
   * @return String The transformed XML
   * @param xmlString String XML input string
   * @param xslFileName String XSL stylesheet filename
   * @param parameters the list of parameters to pass to the XSL stylesheet.
   * @exception TransformerException Any exception thrown during the transform process
   */
  public static String transform(String xmlString, String xslFileName, HashMap parameters)
      throws TransformerException {
    try {
      StringWriter stringWriter = new StringWriter();
      Source xmlSource = new StreamSource(new StringReader(xmlString));
      Templates template = (Templates) xslcache.getTemplate(xslFileName);
      Transformer trans = template.newTransformer();

      if (parameters != null) {
        Set keys = parameters.keySet();
        Iterator it = keys.iterator();
        while (it.hasNext()) {
          String name = (String) it.next();
          String value = (String) parameters.get(name);
          trans.setParameter(name, value);
        }
      }
      trans.transform(xmlSource, new StreamResult(stringWriter));
      return stringWriter.toString();

    } catch (TransformerConfigurationException e) {
      throw new TransformerException(
          "Transformer could not be created: " + e.getClass().getName() + " - " + e.getMessage());
    } catch (TransformerException e) {
      throw new TransformerException(
          "Error during transformation: " + e.getClass().getName() + " - " + e.getMessage());
    } catch (Exception e) {
      throw new TransformerException(
          "Unknown error during transformation: "
              + e.getClass().getName()
              + " - "
              + e.getMessage());
    }
  }
Пример #17
0
  protected void doTransform(
      MuleMessage message, String outputEncoding, Source sourceDoc, Result result)
      throws Exception {
    DefaultErrorListener errorListener = new DefaultErrorListener(this);
    javax.xml.transform.Transformer transformer = null;

    try {
      transformer = (javax.xml.transform.Transformer) transformerPool.borrowObject();

      transformer.setErrorListener(errorListener);
      transformer.setOutputProperty(OutputKeys.ENCODING, outputEncoding);

      // set transformation parameters
      if (contextProperties != null) {
        for (Entry<String, Object> parameter : contextProperties.entrySet()) {
          String key = parameter.getKey();
          transformer.setParameter(
              key, evaluateTransformParameter(key, parameter.getValue(), message));
        }
      }

      transformer.transform(sourceDoc, result);

      if (errorListener.isError()) {
        throw errorListener.getException();
      }
    } finally {
      if (transformer != null) {
        transformerPool.returnObject(transformer);
      }
    }
  }
Пример #18
0
 /**
  * Set parameters on a transformer
  *
  * @param t
  * @param params
  */
 protected void populateParams(Transformer t, Map<String, Object> params) {
   Iterator<Entry<String, Object>> entriesIt = params.entrySet().iterator();
   while (entriesIt.hasNext()) {
     Entry<String, Object> entry = entriesIt.next();
     t.setParameter(entry.getKey(), entry.getValue());
   }
 }
Пример #19
0
  /**
   * Method removes a Spring bean definition from the XML application context file. Bean definition
   * is identified by its id or bean name.
   *
   * @param project
   * @param id
   */
  public void removeBeanDefinition(File configFile, Project project, String id) {
    Source xsltSource;
    Source xmlSource;
    try {
      xsltSource =
          new StreamSource(new ClassPathResource("transform/delete-bean.xsl").getInputStream());
      xsltSource.setSystemId("delete-bean");

      List<File> configFiles = new ArrayList<>();
      configFiles.add(configFile);
      configFiles.addAll(getConfigImports(configFile, project));

      for (File file : configFiles) {
        xmlSource = new StringSource(FileUtils.readToString(new FileInputStream(configFile)));

        // create transformer
        Transformer transformer = transformerFactory.newTransformer(xsltSource);
        transformer.setParameter("bean_id", id);

        // transform
        StringResult result = new StringResult();
        transformer.transform(xmlSource, result);
        FileUtils.writeToFile(format(result.toString(), project.getSettings().getTabSize()), file);
        return;
      }
    } catch (IOException e) {
      throw new ApplicationRuntimeException(UNABLE_TO_READ_TRANSFORMATION_SOURCE, e);
    } catch (TransformerException e) {
      throw new ApplicationRuntimeException(FAILED_TO_UPDATE_BEAN_DEFINITION, e);
    }
  }
 /**
  * Adds properties to the specified {@code transformer} for the current Git commit hash. The
  * following properties are added to {@code transformer}:
  *
  * <ul>
  *   <li>{@code repository.commit}: The full commit hash, in lowercase hexadecimal form.
  *   <li>{@code repository.commit.short}: The abbreviated commit hash, which is the first {@code
  *       abbrevLen} hexadecimal characters of the full commit hash.
  * </ul>
  *
  * <p>If {@code baseDir} is not currently stored in a Git repository, or if the current Git commit
  * hash could not be determined, this method logs a warning and returns {@code false}.
  *
  * @param transformer The transformer.
  * @param baseDir The base directory where versioned files are contained.
  * @param abbrevLen The length of the abbreviated commit hash to create, in number of hexadecimal
  *     characters.
  * @param log The Maven log instance.
  * @return {@code true} if the commit hash was identified and the properties added to the {@code
  *     transformer}; otherwise, {@code false}.
  */
 public static boolean addCommitProperties(
     Transformer transformer, File baseDir, int abbrevLen, Log log) {
   try {
     RepositoryBuilder builder = new RepositoryBuilder();
     Repository repository = builder.findGitDir(baseDir).readEnvironment().build();
     ObjectId objectId = repository.resolve(Constants.HEAD);
     if (objectId != null) {
       transformer.setParameter("repository.commit", objectId.getName());
       transformer.setParameter("repository.commit.short", objectId.abbreviate(abbrevLen).name());
       return true;
     } else {
       log.warn("Could not determine current repository commit hash.");
       return false;
     }
   } catch (IOException ex) {
     log.warn("Could not determine current repository commit hash.", ex);
     return false;
   }
 }
Пример #21
0
  private String applyXSLTTransformation(String source, String ontologyUrl, String lang)
      throws TransformerException {
    TransformerFactory tfactory = new net.sf.saxon.TransformerFactoryImpl();

    ByteArrayOutputStream output = new ByteArrayOutputStream();

    Transformer transformer = tfactory.newTransformer(new StreamSource(xsltURL));

    transformer.setParameter("css-location", cssLocation);
    transformer.setParameter("lang", lang);
    transformer.setParameter("ontology-url", ontologyUrl);
    transformer.setParameter("source", cssLocation + "source");

    StreamSource inputSource = new StreamSource(new StringReader(source));

    transformer.transform(inputSource, new StreamResult(output));

    return output.toString();
  }
Пример #22
0
 public Transformer newTransformer() throws TransformerConfigurationException {
   Transformer tr = templates.newTransformer();
   tr.setURIResolver(resolver);
   for (Map.Entry<String, Object> entry : transformParameters.entrySet()) {
     tr.setParameter(entry.getKey(), entry.getValue());
   }
   for (Map.Entry<String, String> entry : outProps.entrySet()) {
     tr.setOutputProperty(entry.getKey(), entry.getValue());
   }
   return tr;
 }
Пример #23
0
 protected void addParameters(Transformer transformer, Map<String, Object> map) {
   Set<Map.Entry<String, Object>> propertyEntries = map.entrySet();
   for (Map.Entry<String, Object> entry : propertyEntries) {
     String key = entry.getKey();
     Object value = entry.getValue();
     if (value != null) {
       LOG.trace("Transformer set parameter {} -> {}", key, value);
       transformer.setParameter(key, value);
     }
   }
 }
Пример #24
0
  private void assignParameters(javax.xml.transform.Transformer transformer, Map params) {

    if (params != null) {
      for (Iterator it = params.entrySet().iterator(); it.hasNext(); ) {

        Map.Entry entry = (Map.Entry) it.next();

        transformer.setParameter(entry.getKey().toString(), entry.getValue().toString());
      }
    }
  }
Пример #25
0
  /** Configures the transformer with exchange specific parameters */
  protected void configureTransformer(Transformer transformer, Exchange exchange) throws Exception {
    if (uriResolver == null) {
      uriResolver = new XsltUriResolver(exchange.getContext().getClassResolver(), null);
    }
    transformer.setURIResolver(uriResolver);
    if (errorListener == null) {
      // set our error listener so we can capture errors and report them back on the exchange
      transformer.setErrorListener(new DefaultTransformErrorHandler(exchange));
    } else {
      // use custom error listener
      transformer.setErrorListener(errorListener);
    }

    transformer.clearParameters();
    addParameters(transformer, exchange.getProperties());
    addParameters(transformer, exchange.getIn().getHeaders());
    addParameters(transformer, getParameters());
    transformer.setParameter("exchange", exchange);
    transformer.setParameter("in", exchange.getIn());
    transformer.setParameter("out", exchange.getOut());
  }
Пример #26
0
  public static String getXMLasString(Document document) throws TransformerException {
    Source source = new DOMSource(document);
    Transformer xformer = TransformerFactory.newInstance().newTransformer();
    xformer.setParameter(OutputKeys.INDENT, "yes");
    xformer.setOutputProperty(OutputKeys.INDENT, "yes");
    xformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

    Writer outputWriter = new StringWriter();
    Result stringOut = new StreamResult(outputWriter);
    xformer.transform(source, stringOut);

    return outputWriter.toString();
  }
Пример #27
0
  public String feed(String sensorId) {
    String nt = "";
    try {
      Sensor sensor = sensorManager.getSpecifiedSensorWithSensorId(sensorId);
      if (sensor == null) return null;
      String xml = WebServiceURLRetriever.RetrieveFromURL(sensor.getSource());

      System.setProperty(
          "javax.xml.transform.TransformerFactory", "net.sf.saxon.TransformerFactoryImpl");
      TransformerFactory tFactory = TransformerFactory.newInstance();
      String xsltPath =
          XSLTMapFile.sensordata2xslt.get(SourceType.getSourceType(sensor.getSourceType()));
      xsltPath = MyServlet.realPath + xsltPath;
      try {
        Transformer transformer = tFactory.newTransformer(new StreamSource(new File(xsltPath)));
        String id = sensor.getId().substring(sensor.getId().lastIndexOf("/") + 1);
        String foi =
            Double.toString(sensor.getPlace().getLat()).replace(".", "").replace("-", "")
                + Double.toString(sensor.getPlace().getLng()).replace(".", "").replace("-", "");
        transformer.setParameter("sensorId", id);
        transformer.setParameter("sourceType", sensor.getSourceType());
        transformer.setParameter("sensorType", sensor.getSensorType());
        transformer.setParameter("sourceURL", sensor.getSource());
        transformer.setParameter("foi", foi);
        InputStream inputStream = new ByteArrayInputStream(xml.getBytes("UTF-8"));
        Writer outWriter = new StringWriter();
        StreamResult result = new StreamResult(outWriter);
        transformer.transform(new StreamSource(inputStream), result);
        nt = outWriter.toString().trim();
        //				System.out.println(nt);
        sensorManager.insertTriplesToGraph(VirtuosoConstantUtil.sensormasherDataGraphURI, nt);
      } catch (Exception e) {
        e.printStackTrace();
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return nt;
  }
Пример #28
0
 private void setTransformParameters(Transformer transformer, Hashtable paramHash) {
   for (Enumeration e = paramHash.keys(); e.hasMoreElements(); ) {
     String parameter = (String) e.nextElement();
     String value = (String) paramHash.get((Object) parameter);
     log.debug(
         this.working_for
             + " : Accepting XSLT transform parameter : '"
             + parameter
             + "' with value : '"
             + value
             + "'");
     transformer.setParameter(parameter, value);
   }
 }
Пример #29
0
  /**
   * Creates html validation report
   *
   * @param htmlReportPath path with name of the resulting html report
   * @param xmlReport xml validation report file
   * @param validationProfile validation profile file
   * @throws TransformerException if an unrecoverable error occurs during the course of the
   *     transformation or
   * @throws IOException file system exceptions
   */
  public static void writeHTMLReport(String htmlReportPath, File xmlReport, File validationProfile)
      throws TransformerException, IOException {

    TransformerFactory factory = TransformerFactory.newInstance();

    Transformer transformer =
        factory.newTransformer(
            new StreamSource(
                HTMLReport.class.getClassLoader().getResourceAsStream("HTMLReportStylesheet.xsl")));
    transformer.setParameter("profilePath", validationProfile.getAbsolutePath());

    transformer.transform(
        new StreamSource(xmlReport), new StreamResult(new FileOutputStream(htmlReportPath)));
  }
Пример #30
0
  @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));
  }