Java Code Examples for javax.xml.transform.Transformer#setErrorListener()

The following examples show how to use javax.xml.transform.Transformer#setErrorListener() . 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: OaiCatalog.java    From proarc with GNU General Public License v3.0 6 votes vote down vote up
/**
 * @return the result metadata or {@code null} for empty result.
 */
<T extends Result> T transformOaiResponse(Source src, T dst) throws TransformerException {
    Transformer t = getOai2MarcXslt().newTransformer();
    XslErrorListener errorListener = new XslErrorListener();
    t.setErrorListener(errorListener);
    try {
        t.transform(src, dst);
        return dst;
    } catch (TransformerException ex) {
        // ignore ID not found
        if (errorListener.containError(XslErrorListener.ERR_ID_DOESNOT_EXIST)) {
            return null;
        } else if (!errorListener.getMessages().isEmpty()) {
            throw new TransformerException(errorListener.getMessages().toString(), ex);
        }
        throw ex;
    }
}
 
Example 2
Source File: SummerXSLTView.java    From GreenSummer with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
@Measured("xsltTransform")
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
    Transformer transformer = getTransformer(model, request);
    if (transformer != null) {
        configureTransformer(model, response, transformer);
        configureResponse(model, response, transformer);
        transformer.setErrorListener(this);
        Source source = null;
        try {
            source = locateSource(model);
            if (source == null) {
                throw new IllegalArgumentException("Unable to locate Source object in model: " + model);
            }
            addXSLTParameters(request, transformer);
            transformer.transform(source, createResult(response));
        } finally {
            customCloseSourceIfNecessary(source);
        }
    } else {
        superRenderMergedOutputModel(model, request, response);
    }
}
 
Example 3
Source File: XSLTResponseWriter.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
/** Get Transformer from request context, or from TransformerProvider.
 *  This allows either getContentType(...) or write(...) to instantiate the Transformer,
 *  depending on which one is called first, then the other one reuses the same Transformer
 */
protected Transformer getTransformer(SolrQueryRequest request) throws IOException {
  final String xslt = request.getParams().get(CommonParams.TR,null);
  if(xslt==null) {
    throw new IOException("'" + CommonParams.TR + "' request parameter is required to use the XSLTResponseWriter");
  }
  // not the cleanest way to achieve this
  SolrConfig solrConfig = request.getCore().getSolrConfig();
  // no need to synchronize access to context, right? 
  // Nothing else happens with it at the same time
  final Map<Object,Object> ctx = request.getContext();
  Transformer result = (Transformer)ctx.get(CONTEXT_TRANSFORMER_KEY);
  if(result==null) {
    result = TransformerProvider.instance.getTransformer(solrConfig, xslt,xsltCacheLifetimeSeconds.intValue());
    result.setErrorListener(xmllog);
    ctx.put(CONTEXT_TRANSFORMER_KEY,result);
  }
  return result;
}
 
Example 4
Source File: TransformerPool.java    From iaf with Apache License 2.0 5 votes vote down vote up
protected synchronized Transformer createTransformer() throws TransformerConfigurationException {
	Transformer t = templates.newTransformer();
	if (t==null) {
		throw new TransformerConfigurationException("cannot instantiate transformer");
	}
	t.setErrorListener(new TransformerErrorListener());
	// Set URIResolver on transformer for Xalan. Setting it on the factory
	// doesn't work for Xalan. See
	// https://www.oxygenxml.com/archives/xsl-list/200306/msg00021.html
	t.setURIResolver(classLoaderURIResolver);
	return t;
}
 
Example 5
Source File: SCHTransformerCustomizer.java    From ph-schematron with Apache License 2.0 5 votes vote down vote up
public void customize (@Nonnull final EStep eStep, @Nonnull final Transformer aTransformer)
{
  // 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 (eStep == EStep.SCH2XSLT_3)
  {
    // On the last step, set the respective Schematron parameters as the
    // last action to avoid they are overwritten by a custom parameter.
    if (m_sPhase != null)
      aTransformer.setParameter ("phase", m_sPhase);

    if (m_sLanguageCode != null)
      aTransformer.setParameter ("langCode", m_sLanguageCode);
  }
}
 
Example 6
Source File: DomUtils.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * This method returns a new instance of Transformer with secured features enabled
 * 
 * @return an instance of Transformer with enabled secure features
 */
public static Transformer getSecureTransformer() {
	TransformerFactory transformerFactory = getSecureTransformerFactory();
	Transformer transformer = null;
	try {
		transformer = transformerFactory.newTransformer();
		transformer.setOutputProperty(OutputKeys.METHOD, TRANSFORMER_METHOD_VALUE);
	} catch (TransformerConfigurationException e) {
		throw new DSSException(e);
	}
	transformer.setErrorListener(new DSSXmlErrorListener());
	return transformer;
}
 
Example 7
Source File: XMLLoader.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/** Get Transformer from request context, or from TransformerProvider.
 *  This allows either getContentType(...) or write(...) to instantiate the Transformer,
 *  depending on which one is called first, then the other one reuses the same Transformer
 */
Transformer getTransformer(String xslt, SolrQueryRequest request) throws IOException {
  // not the cleanest way to achieve this
  // no need to synchronize access to context, right? 
  // Nothing else happens with it at the same time
  final Map<Object,Object> ctx = request.getContext();
  Transformer result = (Transformer)ctx.get(CONTEXT_TRANSFORMER_KEY);
  if(result==null) {
    SolrConfig solrConfig = request.getCore().getSolrConfig();
    result = TransformerProvider.instance.getTransformer(solrConfig, xslt, xsltCacheLifetimeSeconds);
    result.setErrorListener(xmllog);
    ctx.put(CONTEXT_TRANSFORMER_KEY,result);
  }
  return result;
}
 
Example 8
Source File: TransformerTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * This tests set/get ErrorListener methods of Transformer.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void transformer04() throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document document = db.parse(new File(TEST_XSL));
    DOMSource domSource = new DOMSource(document);

    Transformer transformer = TransformerFactory.newInstance()
            .newTransformer(domSource);
    transformer.setErrorListener(new MyErrorListener());
    assertNotNull(transformer.getErrorListener());
    assertTrue(transformer.getErrorListener() instanceof MyErrorListener);
}
 
Example 9
Source File: DomLoader.java    From metafacture-core with Apache License 2.0 5 votes vote down vote up
private static Transformer createTransformer() {
    try {
        final Transformer transformer = TransformerFactory.newInstance()
                .newTransformer();
        transformer.setErrorListener(TRANSFORMER_ERROR_HANDLER);
        return transformer;
    } catch (TransformerConfigurationException e) {
        throw new MetafactureException(e);
    }
}
 
Example 10
Source File: XSLTFunctionsTest.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * bug 8062518
 * Verifies that a reference to the DTM created by XSLT document function is
 * actually read from the DTM by an extension function.
 * @param xml Content of xml file to process
 * @param xsl stylesheet content that loads external document {@code externalDoc}
 *        with XSLT 'document' function and then reads it with
 *        DocumentExtFunc.test() function
 * @param externalDoc Content of the external xml document
 * @param expectedResult Expected transformation result
 **/
@Test(dataProvider = "document")
public void testDocument(final String xml, final String xsl,
                         final String externalDoc, final String expectedResult) throws Exception {
    // Prepare sources for transormation
    Source src = new StreamSource(new StringReader(xml));
    Source xslsrc = new StreamSource(new StringReader(xsl));

    // Create factory and transformer
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer t = tf.newTransformer( xslsrc );
    t.setErrorListener(tf.getErrorListener());

    // Set URI Resolver to return the newly constructed xml
    // stream source object from xml test string
    t.setURIResolver(new URIResolver() {
        @Override
        public Source resolve(String href, String base)
                throws TransformerException {
            if (href.contains("externalDoc")) {
                return new StreamSource(new StringReader(externalDoc));
            } else {
                return new StreamSource(new StringReader(xml));
            }
        }
    });

    // Prepare output stream
    StringWriter xmlResultString = new StringWriter();
    StreamResult xmlResultStream = new StreamResult(xmlResultString);

    //Transform the xml
    t.transform(src, xmlResultStream);

    // If the document can't be accessed and the bug is in place then
    // reported exception will be thrown during transformation
    System.out.println("Transformation result:"+xmlResultString.toString().trim());

    // Check the result - it should contain two (node name, node values) entries -
    // one for original document, another for a document created with
    // call to 'document' function
    assertEquals(xmlResultString.toString().trim(), expectedResult);
}
 
Example 11
Source File: XSLTFunctionsTest.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
/**
 * bug 8062518
 * Verifies that a reference to the DTM created by XSLT document function is
 * actually read from the DTM by an extension function.
 * @param xml Content of xml file to process
 * @param xsl stylesheet content that loads external document {@code externalDoc}
 *        with XSLT 'document' function and then reads it with
 *        DocumentExtFunc.test() function
 * @param externalDoc Content of the external xml document
 * @param expectedResult Expected transformation result
 **/
@Test(dataProvider = "document")
public void testDocument(final String xml, final String xsl,
                         final String externalDoc, final String expectedResult) throws Exception {
    // Prepare sources for transormation
    Source src = new StreamSource(new StringReader(xml));
    Source xslsrc = new StreamSource(new StringReader(xsl));

    // Create factory and transformer
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer t = tf.newTransformer( xslsrc );
    t.setErrorListener(tf.getErrorListener());

    // Set URI Resolver to return the newly constructed xml
    // stream source object from xml test string
    t.setURIResolver(new URIResolver() {
        @Override
        public Source resolve(String href, String base)
                throws TransformerException {
            if (href.contains("externalDoc")) {
                return new StreamSource(new StringReader(externalDoc));
            } else {
                return new StreamSource(new StringReader(xml));
            }
        }
    });

    // Prepare output stream
    StringWriter xmlResultString = new StringWriter();
    StreamResult xmlResultStream = new StreamResult(xmlResultString);

    //Transform the xml
    t.transform(src, xmlResultStream);

    // If the document can't be accessed and the bug is in place then
    // reported exception will be thrown during transformation
    System.out.println("Transformation result:"+xmlResultString.toString().trim());

    // Check the result - it should contain two (node name, node values) entries -
    // one for original document, another for a document created with
    // call to 'document' function
    assertEquals(xmlResultString.toString().trim(), expectedResult);
}
 
Example 12
Source File: XSLTFunctionsTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * @bug 8062518 8153082
 * Verifies that a reference to the DTM created by XSLT document function is
 * actually read from the DTM by an extension function.
 * @param xml Content of xml file to process
 * @param xsl stylesheet content that loads external document {@code externalDoc}
 *        with XSLT 'document' function and then reads it with
 *        DocumentExtFunc.test() function
 * @param externalDoc Content of the external xml document
 * @param expectedResult Expected transformation result
 **/
@Test(dataProvider = "document")
public void testDocument(final String xml, final String xsl,
                         final String externalDoc, final String expectedResult) throws Exception {
    // Prepare sources for transormation
    Source src = new StreamSource(new StringReader(xml));
    Source xslsrc = new StreamSource(new StringReader(xsl));

    // Create factory and transformer
    TransformerFactory tf = TransformerFactory.newInstance();
    tf.setFeature(ORACLE_ENABLE_EXTENSION_FUNCTION, true);
    tf.setAttribute(EXTENSION_CLASS_LOADER,
            runWithAllPerm(() -> Thread.currentThread().getContextClassLoader()));
    Transformer t = tf.newTransformer( xslsrc );
    t.setErrorListener(tf.getErrorListener());

    // Set URI Resolver to return the newly constructed xml
    // stream source object from xml test string
    t.setURIResolver(new URIResolver() {
        @Override
        public Source resolve(String href, String base)
                throws TransformerException {
            if (href.contains("externalDoc")) {
                return new StreamSource(new StringReader(externalDoc));
            } else {
                return new StreamSource(new StringReader(xml));
            }
        }
    });

    // Prepare output stream
    StringWriter xmlResultString = new StringWriter();
    StreamResult xmlResultStream = new StreamResult(xmlResultString);

    //Transform the xml
    t.transform(src, xmlResultStream);

    // If the document can't be accessed and the bug is in place then
    // reported exception will be thrown during transformation
    System.out.println("Transformation result:"+xmlResultString.toString().trim());

    // Check the result - it should contain two (node name, node values) entries -
    // one for original document, another for a document created with
    // call to 'document' function
    assertEquals(xmlResultString.toString().trim(), expectedResult);
}
 
Example 13
Source File: XSLTFunctionsTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
/**
 * bug 8062518
 * Verifies that a reference to the DTM created by XSLT document function is
 * actually read from the DTM by an extension function.
 * @param xml Content of xml file to process
 * @param xsl stylesheet content that loads external document {@code externalDoc}
 *        with XSLT 'document' function and then reads it with
 *        DocumentExtFunc.test() function
 * @param externalDoc Content of the external xml document
 * @param expectedResult Expected transformation result
 **/
@Test(dataProvider = "document")
public void testDocument(final String xml, final String xsl,
                         final String externalDoc, final String expectedResult) throws Exception {
    // Prepare sources for transormation
    Source src = new StreamSource(new StringReader(xml));
    Source xslsrc = new StreamSource(new StringReader(xsl));

    // Create factory and transformer
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer t = tf.newTransformer( xslsrc );
    t.setErrorListener(tf.getErrorListener());

    // Set URI Resolver to return the newly constructed xml
    // stream source object from xml test string
    t.setURIResolver(new URIResolver() {
        @Override
        public Source resolve(String href, String base)
                throws TransformerException {
            if (href.contains("externalDoc")) {
                return new StreamSource(new StringReader(externalDoc));
            } else {
                return new StreamSource(new StringReader(xml));
            }
        }
    });

    // Prepare output stream
    StringWriter xmlResultString = new StringWriter();
    StreamResult xmlResultStream = new StreamResult(xmlResultString);

    //Transform the xml
    t.transform(src, xmlResultStream);

    // If the document can't be accessed and the bug is in place then
    // reported exception will be thrown during transformation
    System.out.println("Transformation result:"+xmlResultString.toString().trim());

    // Check the result - it should contain two (node name, node values) entries -
    // one for original document, another for a document created with
    // call to 'document' function
    assertEquals(xmlResultString.toString().trim(), expectedResult);
}
 
Example 14
Source File: XSLTFunctionsTest.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * bug 8062518
 * Verifies that a reference to the DTM created by XSLT document function is
 * actually read from the DTM by an extension function.
 * @param xml Content of xml file to process
 * @param xsl stylesheet content that loads external document {@code externalDoc}
 *        with XSLT 'document' function and then reads it with
 *        DocumentExtFunc.test() function
 * @param externalDoc Content of the external xml document
 * @param expectedResult Expected transformation result
 **/
@Test(dataProvider = "document")
public void testDocument(final String xml, final String xsl,
                         final String externalDoc, final String expectedResult) throws Exception {
    // Prepare sources for transormation
    Source src = new StreamSource(new StringReader(xml));
    Source xslsrc = new StreamSource(new StringReader(xsl));

    // Create factory and transformer
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer t = tf.newTransformer( xslsrc );
    t.setErrorListener(tf.getErrorListener());

    // Set URI Resolver to return the newly constructed xml
    // stream source object from xml test string
    t.setURIResolver(new URIResolver() {
        @Override
        public Source resolve(String href, String base)
                throws TransformerException {
            if (href.contains("externalDoc")) {
                return new StreamSource(new StringReader(externalDoc));
            } else {
                return new StreamSource(new StringReader(xml));
            }
        }
    });

    // Prepare output stream
    StringWriter xmlResultString = new StringWriter();
    StreamResult xmlResultStream = new StreamResult(xmlResultString);

    //Transform the xml
    t.transform(src, xmlResultStream);

    // If the document can't be accessed and the bug is in place then
    // reported exception will be thrown during transformation
    System.out.println("Transformation result:"+xmlResultString.toString().trim());

    // Check the result - it should contain two (node name, node values) entries -
    // one for original document, another for a document created with
    // call to 'document' function
    assertEquals(xmlResultString.toString().trim(), expectedResult);
}
 
Example 15
Source File: XSLTFunctionsTest.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
/**
 * bug 8062518
 * Verifies that a reference to the DTM created by XSLT document function is
 * actually read from the DTM by an extension function.
 * @param xml Content of xml file to process
 * @param xsl stylesheet content that loads external document {@code externalDoc}
 *        with XSLT 'document' function and then reads it with
 *        DocumentExtFunc.test() function
 * @param externalDoc Content of the external xml document
 * @param expectedResult Expected transformation result
 **/
@Test(dataProvider = "document")
public void testDocument(final String xml, final String xsl,
                         final String externalDoc, final String expectedResult) throws Exception {
    // Prepare sources for transormation
    Source src = new StreamSource(new StringReader(xml));
    Source xslsrc = new StreamSource(new StringReader(xsl));

    // Create factory and transformer
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer t = tf.newTransformer( xslsrc );
    t.setErrorListener(tf.getErrorListener());

    // Set URI Resolver to return the newly constructed xml
    // stream source object from xml test string
    t.setURIResolver(new URIResolver() {
        @Override
        public Source resolve(String href, String base)
                throws TransformerException {
            if (href.contains("externalDoc")) {
                return new StreamSource(new StringReader(externalDoc));
            } else {
                return new StreamSource(new StringReader(xml));
            }
        }
    });

    // Prepare output stream
    StringWriter xmlResultString = new StringWriter();
    StreamResult xmlResultStream = new StreamResult(xmlResultString);

    //Transform the xml
    t.transform(src, xmlResultStream);

    // If the document can't be accessed and the bug is in place then
    // reported exception will be thrown during transformation
    System.out.println("Transformation result:"+xmlResultString.toString().trim());

    // Check the result - it should contain two (node name, node values) entries -
    // one for original document, another for a document created with
    // call to 'document' function
    assertEquals(xmlResultString.toString().trim(), expectedResult);
}
 
Example 16
Source File: FopTask.java    From pcgen with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Run the FO to PDF/AWT conversion. This automatically closes any provided OutputStream for
 * this FopTask.
 */
@Override
public void run()
{
	try (OutputStream out = outputStream)
	{
		userAgent.setProducer("PC Gen Character Generator");
		userAgent.setAuthor(System.getProperty("user.name"));
		userAgent.setCreationDate(Date.from(LocalDateTime.now().toInstant(ZoneOffset.ofHours(0))));

		userAgent.getEventBroadcaster().addEventListener(new FOPEventListener());

		String mimeType;
		if (renderer != null)
		{
			userAgent.setKeywords("PCGEN FOP PREVIEW");
			mimeType = MimeConstants.MIME_FOP_AWT_PREVIEW;
		}
		else
		{
			userAgent.setKeywords("PCGEN FOP PDF");
			mimeType = org.apache.xmlgraphics.util.MimeConstants.MIME_PDF;
		}
		Fop fop;
		if (out != null)
		{
			fop = FOP_FACTORY.newFop(mimeType, userAgent, out);
		}
		else
		{
			fop = FOP_FACTORY.newFop(mimeType, userAgent);
		}

		Transformer transformer;
		if (xsltSource != null)
		{
			transformer = TRANS_FACTORY.newTransformer(xsltSource);
		}
		else
		{
			transformer = TRANS_FACTORY.newTransformer(); // identity transformer		
		}
		transformer.setErrorListener(new FOPErrorListener());
		transformer.transform(inputSource, new SAXResult(fop.getDefaultHandler()));
	}
	catch (TransformerException | FOPException | IOException e)
	{
		errorBuilder.append(e.getMessage()).append(Constants.LINE_SEPARATOR);
		Logging.errorPrint("Exception in FopTask:run", e);
	}
	catch (RuntimeException ex)
	{
		errorBuilder.append(ex.getMessage()).append(Constants.LINE_SEPARATOR);
		Logging.errorPrint("Unexpected exception in FopTask:run: ", ex);
	}
}
 
Example 17
Source File: FopTask.java    From pcgen with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Run the FO to PDF/AWT conversion. This automatically closes any provided OutputStream for
 * this FopTask.
 */
@Override
public void run()
{
	try (OutputStream out = outputStream)
	{
		userAgent.setProducer("PC Gen Character Generator");
		userAgent.setAuthor(System.getProperty("user.name"));
		userAgent.setCreationDate(Date.from(LocalDateTime.now().toInstant(ZoneOffset.ofHours(0))));

		userAgent.getEventBroadcaster().addEventListener(new FOPEventListener());

		String mimeType;
		if (renderer != null)
		{
			userAgent.setKeywords("PCGEN FOP PREVIEW");
			mimeType = MimeConstants.MIME_FOP_AWT_PREVIEW;
		}
		else
		{
			userAgent.setKeywords("PCGEN FOP PDF");
			mimeType = org.apache.xmlgraphics.util.MimeConstants.MIME_PDF;
		}
		Fop fop;
		if (out != null)
		{
			fop = FOP_FACTORY.newFop(mimeType, userAgent, out);
		}
		else
		{
			fop = FOP_FACTORY.newFop(mimeType, userAgent);
		}

		Transformer transformer;
		if (xsltSource != null)
		{
			transformer = TRANS_FACTORY.newTransformer(xsltSource);
		}
		else
		{
			transformer = TRANS_FACTORY.newTransformer(); // identity transformer		
		}
		transformer.setErrorListener(new FOPErrorListener());
		transformer.transform(inputSource, new SAXResult(fop.getDefaultHandler()));
	}
	catch (TransformerException | FOPException | IOException e)
	{
		errorBuilder.append(e.getMessage()).append(Constants.LINE_SEPARATOR);
		Logging.errorPrint("Exception in FopTask:run", e);
	}
	catch (RuntimeException ex)
	{
		errorBuilder.append(ex.getMessage()).append(Constants.LINE_SEPARATOR);
		Logging.errorPrint("Unexpected exception in FopTask:run: ", ex);
	}
}
 
Example 18
Source File: XSLTFunctionsTest.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * bug 8062518
 * Verifies that a reference to the DTM created by XSLT document function is
 * actually read from the DTM by an extension function.
 * @param xml Content of xml file to process
 * @param xsl stylesheet content that loads external document {@code externalDoc}
 *        with XSLT 'document' function and then reads it with
 *        DocumentExtFunc.test() function
 * @param externalDoc Content of the external xml document
 * @param expectedResult Expected transformation result
 **/
@Test(dataProvider = "document")
public void testDocument(final String xml, final String xsl,
                         final String externalDoc, final String expectedResult) throws Exception {
    // Prepare sources for transormation
    Source src = new StreamSource(new StringReader(xml));
    Source xslsrc = new StreamSource(new StringReader(xsl));

    // Create factory and transformer
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer t = tf.newTransformer( xslsrc );
    t.setErrorListener(tf.getErrorListener());

    // Set URI Resolver to return the newly constructed xml
    // stream source object from xml test string
    t.setURIResolver(new URIResolver() {
        @Override
        public Source resolve(String href, String base)
                throws TransformerException {
            if (href.contains("externalDoc")) {
                return new StreamSource(new StringReader(externalDoc));
            } else {
                return new StreamSource(new StringReader(xml));
            }
        }
    });

    // Prepare output stream
    StringWriter xmlResultString = new StringWriter();
    StreamResult xmlResultStream = new StreamResult(xmlResultString);

    //Transform the xml
    t.transform(src, xmlResultStream);

    // If the document can't be accessed and the bug is in place then
    // reported exception will be thrown during transformation
    System.out.println("Transformation result:"+xmlResultString.toString().trim());

    // Check the result - it should contain two (node name, node values) entries -
    // one for original document, another for a document created with
    // call to 'document' function
    assertEquals(xmlResultString.toString().trim(), expectedResult);
}
 
Example 19
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 20
Source File: XSLTransformationParser.java    From teamengine with Apache License 2.0 4 votes vote down vote up
public Document parse(URLConnection uc, Element instruction,
        PrintWriter logger) throws Exception {
    HashMap<String, String> properties = new HashMap<String, String>();
    properties.putAll(defaultProperties);
    HashMap<String, String> params = new HashMap<String, String>();
    params.putAll(defaultParams);
    Boolean ignoreErrors = defaultIgnoreErrors;
    Boolean ignoreWarnings = defaultIgnoreWarnings;
    Templates templates = parseInstruction(instruction, properties, params,
            ignoreErrors, ignoreWarnings);
    Transformer t = null;
    if (templates != null) {
        t = templates.newTransformer();
    } else if (defaultTemplates != null) {
        t = defaultTemplates.newTransformer();
    } else {
        t = tf.newTransformer();
    }
    for (Entry<String, String> prop : properties.entrySet()) {
        t.setOutputProperty(prop.getKey(), prop.getValue());
    }
    for (Entry<String, String> param : params.entrySet()) {
        t.setParameter(param.getKey(), param.getValue());
    }
    XSLTransformationErrorHandler el = new XSLTransformationErrorHandler(
            logger, ignoreErrors, ignoreWarnings);
    t.setErrorListener(el);
    Document doc = db.newDocument();
    InputStream is = null;
    try {
        if (LOGR.isLoggable(Level.FINER)) {
            String msg = String
                    .format("Attempting to transform source from %s using instruction set:%n %s",
                            uc.getURL(),
                            DomUtils.serializeNode(instruction));
            LOGR.finer(msg);
        }
        // may return error stream
        is = URLConnectionUtils.getInputStream(uc);
        t.transform(new StreamSource(is), new DOMResult(doc));
    } catch (TransformerException e) {
        el.error(e);
    } finally {
        if (null != is)
            is.close();
    }
    if (el.getErrorCount() > 0 && !ignoreErrors) {
        return null;
    }
    if (el.getWarningCount() > 0 && !ignoreWarnings) {
        return null;
    }
    return doc;
}