net.sf.saxon.s9api.XsltTransformer Java Examples

The following examples show how to use net.sf.saxon.s9api.XsltTransformer. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: XSLTBuilder.java    From kite with Apache License 2.0 6 votes vote down vote up
@Override
protected boolean doProcess2(Record inputRecord, InputStream stream) throws SaxonApiException, XMLStreamException {
  incrementNumRecords();      
  for (Fragment fragment : fragments) {
    Record outputRecord = inputRecord.copy();
    removeAttachments(outputRecord);   
    XdmNode document = parseXmlDocument(stream);
    LOG.trace("XSLT input document: {}", document);
    XsltTransformer evaluator = fragment.transformer;
    evaluator.setInitialContextNode(document);
    XMLStreamWriter morphlineWriter = new MorphlineXMLStreamWriter(getChild(), outputRecord);
    evaluator.setDestination(new XMLStreamWriterDestination(morphlineWriter));
    evaluator.transform(); //  run the query and push into child via RecordXMLStreamWriter
  }      
  return true;
}
 
Example #2
Source File: SchematronValidationActionTest.java    From validator with Apache License 2.0 5 votes vote down vote up
@Test
public void testProcessingError() throws IOException, SaxonApiException {
    final CheckAction.Bag bag = createBag(InputFactory.read(Simple.SIMPLE_VALID.toURL()), true);

    final Scenario scenario = bag.getScenarioSelectionResult().getObject();
    final XsltExecutable exec = mock(XsltExecutable.class);
    final XsltTransformer transformer = mock(XsltTransformer.class);
    doThrow(new SaxonApiException("invalid")).when(transformer).transform();
    when(exec.load()).thenReturn(transformer);
    final ResourceType resourceType = new ResourceType();
    resourceType.setName("invalid internal");
    scenario.setSchematronValidations(Collections.singletonList(new Transformation(exec, resourceType)));
    this.action.check(bag);
    assertThat(bag.getReportInput().getProcessingError().getError()).isNotEmpty();
}
 
Example #3
Source File: SaxonSecurityTest.java    From validator with Apache License 2.0 5 votes vote down vote up
@Test
public void testEvilStylesheets() throws IOException {
    final Processor p = TestObjectFactory.createProcessor();
    for (int i = 1; i <= 5; i++) {
        try {
            final URL resource = SaxonSecurityTest.class.getResource(String.format("/evil/evil%s.xsl", i));
            final XsltCompiler compiler = p.newXsltCompiler();
            final RelativeUriResolver resolver = new RelativeUriResolver(Simple.REPOSITORY_URI);
            compiler.setURIResolver(resolver);
            final XsltExecutable executable = compiler.compile(new StreamSource(resource.openStream()));
            final XsltTransformer transformer = executable.load();
            final Source document = InputFactory.read("<root/>".getBytes(), "dummy").getSource();
            // transformer.getUnderlyingController().setUnparsedTextURIResolver(resolver);
            transformer.setURIResolver(resolver);
            transformer.setSource(document);
            final XdmDestination result = new XdmDestination();
            transformer.setDestination(result);
            transformer.transform();

            // wenn der Punkt erreicht wird, sollte wenigstens, das Element evil nicht mit 'bösen' Inhalten gefüllt sein!
            if (StringUtils.isNotBlank(result.getXdmNode().getStringValue())) {
                fail(String.format("Saxon configuration should prevent expansion within %s", resource));
            }

        } catch (final SaxonApiException | RuntimeException e) {
            log.info("Expected exception detected {}", e.getMessage(), e);
        }
    }
}
 
Example #4
Source File: TECore.java    From teamengine with Apache License 2.0 5 votes vote down vote up
public XdmNode executeTemplate(TemplateEntry template, XdmNode params,
        XPathContext context) throws Exception {
  if (stop) {
    throw new Exception("Execution was stopped by the user.");
  }
  XsltExecutable executable = engine.loadExecutable(template,
          opts.getSourcesName());
  XsltTransformer xt = executable.load();
  XdmDestination dest = new XdmDestination();
  xt.setDestination(dest);
  if (template.usesContext() && context != null) {
    xt.setSource((NodeInfo) context.getContextItem());
  } else {
    xt.setSource(new StreamSource(new StringReader("<nil/>")));
  }
      xt.setParameter(TECORE_QNAME, new ObjValue(this));
  if (params != null) {
          xt.setParameter(TEPARAMS_QNAME, params);
  }
  // test may set global verdict, e.g. by calling ctl:fail
  if (LOGR.isLoggable( FINE)) {
    LOGR.log( FINE,
            "Executing TemplateEntry {0}" + template.getQName());
  }
  xt.transform();
  XdmNode ret = dest.getXdmNode();
      if (ret != null && LOGR.isLoggable( FINE)) {
          LOGR.log( FINE, "Output:\n" + ret.toString());
      }
  return ret;
}
 
Example #5
Source File: AbstractSchematronXSLTBasedResource.java    From ph-schematron with Apache License 2.0 4 votes vote down vote up
@Nullable
public final Document applySchematronValidation (@Nonnull final Node aXMLNode,
                                                 @Nullable final String sBaseURI) throws TransformerException
{
  ValueEnforcer.notNull (aXMLNode, "XMLNode");

  final ISchematronXSLTBasedProvider aXSLTProvider = getXSLTProvider ();
  if (aXSLTProvider == null || !aXSLTProvider.isValidSchematron ())
  {
    // We cannot progress because of invalid Schematron
    return null;
  }

  // Debug print the created XSLT document
  if (SchematronDebug.isShowCreatedXSLT ())
    LOGGER.info ("Created XSLT document: " + XMLWriter.getNodeAsString (aXSLTProvider.getXSLTDocument ()));

  // Create result document
  final Document ret = XMLFactory.newDocument ();

  // Create the transformer object from the templates specified in the
  // constructor
  final Transformer aTransformer = aXSLTProvider.getXSLTTransformer ();

  // Apply customizations
  // Ensure an error listener is present
  if (m_aCustomErrorListener != null)
    aTransformer.setErrorListener (m_aCustomErrorListener);
  else
    aTransformer.setErrorListener (new LoggingTransformErrorListener (Locale.US));

  // Set the optional URI Resolver
  if (m_aCustomURIResolver != null)
    aTransformer.setURIResolver (m_aCustomURIResolver);

  // Set all custom parameters
  if (m_aCustomParameters != null)
    for (final Map.Entry <String, ?> aEntry : m_aCustomParameters.entrySet ())
      aTransformer.setParameter (aEntry.getKey (), aEntry.getValue ());

  if (LOGGER.isDebugEnabled ())
    LOGGER.debug ("Applying Schematron XSLT on XML [start]");

  // Enable this for hardcore Saxon debugging only
  if (false)
    if (aTransformer.getClass ().getName ().equals ("net.sf.saxon.jaxp.TransformerImpl"))
    {
      final XsltTransformer aXT = ((TransformerImpl) aTransformer).getUnderlyingXsltTransformer ();

      aXT.setMessageListener ( (a,
                                b,
                                c,
                                d) -> LOGGER.info ("MessageListener2: " + a + ", " + b + ", " + c + ", " + d));
      aXT.setTraceFunctionDestination (new StandardLogger (System.err));
      if (false)
        aXT.getUnderlyingController ().setTraceListener (new XSLTTraceListener ());
      if (false)
      {
        final XSLTTraceListener aTL = new XSLTTraceListener ();
        aTL.setOutputDestination (new StandardLogger (System.err));
        aXT.getUnderlyingController ().setTraceListener (TraceEventMulticaster.add (aTL, null));
      }

      if (false)
        System.out.println ("mode=" + aXT.getInitialMode ());
      if (false)
        System.out.println ("temp=" + aXT.getInitialTemplate ());
      if (false)
        System.out.println (aTransformer.getOutputProperties ());
    }

  // Do the main transformation
  {
    final DOMSource aSource = new DOMSource (aXMLNode);
    aSource.setSystemId (sBaseURI);
    aTransformer.transform (aSource, new DOMResult (ret));
  }

  if (LOGGER.isDebugEnabled ())
    LOGGER.debug ("Applying Schematron XSLT on XML [end]");

  // Debug print the created SVRL document
  if (SchematronDebug.isShowCreatedSVRL ())
    LOGGER.info ("Created SVRL:\n" + XMLWriter.getNodeAsString (ret));

  return ret;
}
 
Example #6
Source File: XSLTBuilder.java    From kite with Apache License 2.0 4 votes vote down vote up
public Fragment(String fragmentPath, XsltTransformer transformer) {
  this.fragmentPath = fragmentPath;
  this.transformer = transformer;
}