javax.xml.transform.sax.TransformerHandler Java Examples

The following examples show how to use javax.xml.transform.sax.TransformerHandler. 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: XmlUtil.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Performs identity transformation.
 */
public static <T extends Result>
T identityTransform(Source src, T result) throws TransformerException, SAXException, ParserConfigurationException, IOException {
    if (src instanceof StreamSource) {
        // work around a bug in JAXP in JDK6u4 and earlier where the namespace processing
        // is not turned on by default
        StreamSource ssrc = (StreamSource) src;
        TransformerHandler th = ((SAXTransformerFactory) transformerFactory.get()).newTransformerHandler();
        th.setResult(result);
        XMLReader reader = saxParserFactory.get().newSAXParser().getXMLReader();
        reader.setContentHandler(th);
        reader.setProperty(LEXICAL_HANDLER_PROPERTY, th);
        reader.parse(toInputSource(ssrc));
    } else {
        newTransformer().transform(src, result);
    }
    return result;
}
 
Example #2
Source File: TestBeansFilter.java    From JVoiceXML with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Test method for the filter.
 *
 * @exception Exception
 *                test failed
 */
@Test
public void testFilter() throws Exception {
    final TransformerFactory tf = TransformerFactory.newInstance();
    final TransformerHandler th = ((SAXTransformerFactory) tf)
            .newTransformerHandler();
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    final Result result = new StreamResult(out);
    th.setResult(result);
    final SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setValidating(false);
    spf.setNamespaceAware(true);
    spf.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
    final SAXParser parser = spf.newSAXParser();
    final XMLFilterImpl filter = new BeansFilter(parser.getXMLReader());
    filter.setContentHandler(th);
    final InputStream in =
        new FileInputStream("../org.jvoicexml.config/src/test/resources/config/test-implementation.xml");
    final InputSource input = new InputSource(in);
    filter.parse(input);
    final String str = out.toString();
    Assert.assertTrue("classpath should be removed",
            str.indexOf("classpath") < 0);
    Assert.assertTrue("repository should be removed",
            str.indexOf("repository") < 0);
}
 
Example #3
Source File: SAXTFactoryTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Test newTransformerHandler with a Template Handler.
 *
 * @throws Exception If any errors occur.
 */
public void testcase08() throws Exception {
    String outputFile = USER_DIR + "saxtf008.out";
    String goldFile = GOLDEN_DIR + "saxtf008GF.out";

    try (FileOutputStream fos = new FileOutputStream(outputFile)) {
        XMLReader reader = XMLReaderFactory.createXMLReader();
        SAXTransformerFactory saxTFactory
                = (SAXTransformerFactory)TransformerFactory.newInstance();

        TemplatesHandler thandler = saxTFactory.newTemplatesHandler();
        reader.setContentHandler(thandler);
        reader.parse(XSLT_FILE);
        TransformerHandler tfhandler
                = saxTFactory.newTransformerHandler(thandler.getTemplates());

        Result result = new StreamResult(fos);
        tfhandler.setResult(result);

        reader.setContentHandler(tfhandler);
        reader.parse(XML_FILE);
    }
    assertTrue(compareWithGold(goldFile, outputFile));
}
 
Example #4
Source File: VacationSaver.java    From ganttproject with GNU General Public License v3.0 6 votes vote down vote up
void save(IGanttProject project, TransformerHandler handler) throws SAXException {
  AttributesImpl attrs = new AttributesImpl();
  startElement("vacations", handler);
  HumanResource[] resources = project.getHumanResourceManager().getResourcesArray();
  for (int i = 0; i < resources.length; i++) {
    HumanResource p = resources[i];
    if (p.getDaysOff() != null)
      for (int j = 0; j < p.getDaysOff().size(); j++) {
        GanttDaysOff gdo = (GanttDaysOff) p.getDaysOff().getElementAt(j);
        addAttribute("start", gdo.getStart().toXMLString(), attrs);
        addAttribute("end", gdo.getFinish().toXMLString(), attrs);
        addAttribute("resourceid", p.getId(), attrs);
        emptyElement("vacation", attrs, handler);
      }
  }
  endElement("vacations", handler);
}
 
Example #5
Source File: SAXTFactoryTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Test newTransformerHandler with a Template Handler along with a relative
 * URI in the style-sheet file.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testcase09() throws Exception {
    String outputFile = USER_DIR + "saxtf009.out";
    String goldFile = GOLDEN_DIR + "saxtf009GF.out";

    try (FileOutputStream fos = new FileOutputStream(outputFile)) {
        XMLReader reader = XMLReaderFactory.createXMLReader();
        SAXTransformerFactory saxTFactory
                = (SAXTransformerFactory)TransformerFactory.newInstance();

        TemplatesHandler thandler = saxTFactory.newTemplatesHandler();
        thandler.setSystemId("file:///" + XML_DIR);
        reader.setContentHandler(thandler);
        reader.parse(XSLT_INCL_FILE);
        TransformerHandler tfhandler=
            saxTFactory.newTransformerHandler(thandler.getTemplates());
        Result result = new StreamResult(fos);
        tfhandler.setResult(result);
        reader.setContentHandler(tfhandler);
        reader.parse(XML_FILE);
    }
    assertTrue(compareWithGold(goldFile, outputFile));
}
 
Example #6
Source File: AstroProcessor.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public TransformerHandler getRADECFilter(double rmin, double rmax, double dmin, double dmax) throws TransformerConfigurationException, SAXException,
        ParserConfigurationException, IOException {
    double raMin = RA_MIN; // hours
    double raMax = RA_MAX; // hours
    double decMin = DEC_MIN; // degrees
    double decMax = DEC_MAX; // degrees
    if (rmin < rmax && dmin < dmax) {
        if ((rmin >= RA_MIN && rmin <= RA_MAX) && (rmax >= RA_MIN && rmax <= RA_MAX)) {
            raMin = rmin; // set value of query
            raMax = rmax; // set value of query
        }
        if ((dmin >= DEC_MIN && dmin <= DEC_MAX) && (dmax >= DEC_MIN && dmax <= DEC_MAX)) {
            decMin = dmin; // set value of query
            decMax = dmax; // set value of query
        }

    } else {
        throw new IllegalArgumentException("min must be less than max.\n" + "rmin=" + rmin + ", rmax=" + rmax + ", dmin=" + dmin + ", dmax=" + dmax);
    }

    return ffact.newRADECFilter(raMin, raMax, decMin, decMax);
}
 
Example #7
Source File: SAXTFactoryTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * SAXTFactory.newTransformerhandler() method which takes SAXSource as
 * argument can be set to XMLReader. SAXSource has input XML file as its
 * input source. XMLReader has a content handler which write out the result
 * to output file. Test verifies output file is same as golden file.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testcase02() throws Exception {
    String outputFile = USER_DIR + "saxtf002.out";
    String goldFile = GOLDEN_DIR + "saxtf002GF.out";

    try (FileOutputStream fos = new FileOutputStream(outputFile);
            FileInputStream fis = new FileInputStream(XSLT_FILE)) {
        XMLReader reader = XMLReaderFactory.createXMLReader();
        SAXTransformerFactory saxTFactory
                = (SAXTransformerFactory) TransformerFactory.newInstance();
        SAXSource ss = new SAXSource();
        ss.setInputSource(new InputSource(fis));

        TransformerHandler handler = saxTFactory.newTransformerHandler(ss);
        Result result = new StreamResult(fos);
        handler.setResult(result);
        reader.setContentHandler(handler);
        reader.parse(XML_FILE);
    }
    assertTrue(compareWithGold(goldFile, outputFile));
}
 
Example #8
Source File: XmlUtil.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Performs identity transformation.
 */
public static <T extends Result>
T identityTransform(Source src, T result) throws TransformerException, SAXException, ParserConfigurationException, IOException {
    if (src instanceof StreamSource) {
        // work around a bug in JAXP in JDK6u4 and earlier where the namespace processing
        // is not turned on by default
        StreamSource ssrc = (StreamSource) src;
        TransformerHandler th = ((SAXTransformerFactory) transformerFactory.get()).newTransformerHandler();
        th.setResult(result);
        XMLReader reader = saxParserFactory.get().newSAXParser().getXMLReader();
        reader.setContentHandler(th);
        reader.setProperty(LEXICAL_HANDLER_PROPERTY, th);
        reader.parse(toInputSource(ssrc));
    } else {
        newTransformer().transform(src, result);
    }
    return result;
}
 
Example #9
Source File: OpenJDK100017Test.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Test
public final void testXMLStackOverflowBug() throws TransformerConfigurationException, IOException, SAXException {
    try {
        SAXTransformerFactory stf = (SAXTransformerFactory) TransformerFactory.newInstance();
        TransformerHandler ser = stf.newTransformerHandler();
        ser.setResult(new StreamResult(System.out));

        StringBuilder sb = new StringBuilder(4096);
        for (int x = 4096; x > 0; x--) {
            sb.append((char) x);
        }
        ser.characters(sb.toString().toCharArray(), 0, sb.toString().toCharArray().length);
        ser.endDocument();
    } catch (StackOverflowError se) {
        se.printStackTrace();
        Assert.fail("StackOverflow");
    }
}
 
Example #10
Source File: BundleRepoTest.java    From ant-ivy with Apache License 2.0 6 votes vote down vote up
@Test
public void testXMLSerialisation() throws SAXException, IOException {
    FSManifestIterable it = new FSManifestIterable(bundlerepo);
    BundleRepoDescriptor repo = new BundleRepoDescriptor(bundlerepo.toURI(),
            ExecutionEnvironmentProfileProvider.getInstance());
    repo.populate(it.iterator());

    SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
    TransformerHandler hd;
    try {
        hd = tf.newTransformerHandler();
    } catch (TransformerConfigurationException e) {
        throw new BuildException("Sax configuration error: " + e.getMessage(), e);
    }

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    StreamResult stream = new StreamResult(out);
    hd.setResult(stream);

    OBRXMLWriter.writeManifests(it, hd, false);

    ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
    BundleRepoDescriptor repo2 = OBRXMLParser.parse(bundlerepo.toURI(), in);

    assertEquals(repo, repo2);
}
 
Example #11
Source File: XmlUtil.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Performs identity transformation.
 */
public static <T extends Result>
T identityTransform(Source src, T result) throws TransformerException, SAXException, ParserConfigurationException, IOException {
    if (src instanceof StreamSource) {
        // work around a bug in JAXP in JDK6u4 and earlier where the namespace processing
        // is not turned on by default
        StreamSource ssrc = (StreamSource) src;
        TransformerHandler th = ((SAXTransformerFactory) transformerFactory.get()).newTransformerHandler();
        th.setResult(result);
        XMLReader reader = saxParserFactory.get().newSAXParser().getXMLReader();
        reader.setContentHandler(th);
        reader.setProperty(LEXICAL_HANDLER_PROPERTY, th);
        reader.parse(toInputSource(ssrc));
    } else {
        newTransformer().transform(src, result);
    }
    return result;
}
 
Example #12
Source File: XmlUtil.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Performs identity transformation.
 */
public static <T extends Result>
T identityTransform(Source src, T result) throws TransformerException, SAXException, ParserConfigurationException, IOException {
    if (src instanceof StreamSource) {
        // work around a bug in JAXP in JDK6u4 and earlier where the namespace processing
        // is not turned on by default
        StreamSource ssrc = (StreamSource) src;
        TransformerHandler th = ((SAXTransformerFactory) transformerFactory.get()).newTransformerHandler();
        th.setResult(result);
        XMLReader reader = saxParserFactory.get().newSAXParser().getXMLReader();
        reader.setContentHandler(th);
        reader.setProperty(LEXICAL_HANDLER_PROPERTY, th);
        reader.parse(toInputSource(ssrc));
    } else {
        newTransformer().transform(src, result);
    }
    return result;
}
 
Example #13
Source File: ResourceSaver.java    From ganttproject with GNU General Public License v3.0 6 votes vote down vote up
private void saveCustomProperties(IGanttProject project, HumanResource resource, TransformerHandler handler)
    throws SAXException {
  // CustomPropertyManager customPropsManager =
  // project.getHumanResourceManager().getCustomPropertyManager();
  AttributesImpl attrs = new AttributesImpl();
  List<CustomProperty> properties = resource.getCustomProperties();
  for (int i = 0; i < properties.size(); i++) {
    CustomProperty nextProperty = properties.get(i);
    CustomPropertyDefinition nextDefinition = nextProperty.getDefinition();
    assert nextProperty != null : "WTF? null property in properties=" + properties;
    assert nextDefinition != null : "WTF? null property definition for property=" + i + "(value="
        + nextProperty.getValueAsString() + ")";
    if (nextProperty.getValue() != null && !nextProperty.getValue().equals(nextDefinition.getDefaultValue())) {
      addAttribute("definition-id", nextDefinition.getID(), attrs);
      addAttribute("value", nextProperty.getValueAsString(), attrs);
      emptyElement("custom-property", attrs, handler);
    }
  }
}
 
Example #14
Source File: SmartTransformerFactoryImpl.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Get a TransformerHandler object that can process SAX ContentHandler
 * events based on a copy transformer.
 * Uses com.sun.org.apache.xalan.internal.processor.TransformerFactory.
 */
public TransformerHandler newTransformerHandler()
    throws TransformerConfigurationException
{
    if (_xalanFactory == null) {
        createXalanTransformerFactory();
    }
    if (_errorlistener != null) {
        _xalanFactory.setErrorListener(_errorlistener);
    }
    if (_uriresolver != null) {
        _xalanFactory.setURIResolver(_uriresolver);
    }
    return _xalanFactory.newTransformerHandler();
}
 
Example #15
Source File: TikaPoweredContentTransformer.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Returns an appropriate Tika ContentHandler for the
 *  requested content type. Normally you'll let this
 *  work as default, but if you need fine-grained
 *  control of how the Tika events become text then
 *  override and supply your own.
 */
protected ContentHandler getContentHandler(String targetMimeType, Writer output) 
               throws TransformerConfigurationException
{
   if(MimetypeMap.MIMETYPE_TEXT_PLAIN.equals(targetMimeType)) 
   {
      return new BodyContentHandler(output);
   }
   
   SAXTransformerFactory factory = (SAXTransformerFactory)
         SAXTransformerFactory.newInstance();
   TransformerHandler handler = factory.newTransformerHandler();
   handler.getTransformer().setOutputProperty(OutputKeys.INDENT, "yes");
   handler.setResult(new StreamResult(output));
   
   if(MimetypeMap.MIMETYPE_HTML.equals(targetMimeType))
   {
      handler.getTransformer().setOutputProperty(OutputKeys.METHOD, "html");
      return new ExpandedTitleContentHandler(handler);
   }
   else if(MimetypeMap.MIMETYPE_XHTML.equals(targetMimeType) ||
           MimetypeMap.MIMETYPE_XML.equals(targetMimeType))
   {
      handler.getTransformer().setOutputProperty(OutputKeys.METHOD, "xml");
   }
   else
   {
      throw new TransformerInfoException(
            WRONG_FORMAT_MESSAGE_ID,
            new IllegalArgumentException("Requested target type " + targetMimeType + " not supported")
      );
   }
   return handler;
}
 
Example #16
Source File: TransformerFactoryImpl.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/**
 * javax.xml.transform.sax.SAXTransformerFactory implementation.
 * Get a TransformerHandler object that can process SAX ContentHandler
 * events into a Result, based on the transformation instructions
 * specified by the argument.
 *
 * @param src The source of the transformation instructions.
 * @return A TransformerHandler object that can handle SAX events
 * @throws TransformerConfigurationException
 */
@Override
public TransformerHandler newTransformerHandler(Source src)
    throws TransformerConfigurationException
{
    final Transformer transformer = newTransformer(src);
    if (_uriResolver != null) {
        transformer.setURIResolver(_uriResolver);
    }
    return new TransformerHandlerImpl((TransformerImpl) transformer);
}
 
Example #17
Source File: JAXBContextImpl.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates a new identity transformer.
 */
public static TransformerHandler createTransformerHandler(boolean disableSecureProcessing) {
    try {
        SAXTransformerFactory tf = (SAXTransformerFactory)XmlFactory.createTransformerFactory(disableSecureProcessing);
        return tf.newTransformerHandler();
    } catch (TransformerConfigurationException e) {
        throw new Error(e); // impossible
    }
}
 
Example #18
Source File: ParseDOM.java    From jlibs with Apache License 2.0 5 votes vote down vote up
@Override
protected void parsingCompleted(Exchange exchange, Message msg, AsyncXMLReader xmlReader){
    TransformerHandler handler = (TransformerHandler)xmlReader.getContentHandler();
    DOMResult result = (DOMResult)handler.getTransformer().getParameter(DOMResult.class.getName());
    MediaType mt = msg.getPayload().getMediaType();
    String contentType = mt.withCharset(IOUtil.UTF_8.name()).toString();
    try{
        msg.setPayload(new DOMPayload(contentType, result.getNode(), false, -1));
    }catch(Throwable thr){
        exchange.resume(thr);
        return;
    }
    super.parsingCompleted(exchange, msg, xmlReader);
}
 
Example #19
Source File: XSLTTransformer.java    From syncope with Apache License 2.0 5 votes vote down vote up
@Override
protected void setSAXConsumer(final SAXConsumer consumer) {
    TransformerHandler transformerHandler;
    try {
        transformerHandler = TRAX_FACTORY.newTransformerHandler(this.templates);
    } catch (Exception e) {
        throw new SetupException("Could not initialize transformer handler.", e);
    }

    if (this.parameters != null) {
        final Transformer transformer = transformerHandler.getTransformer();

        this.parameters.forEach((name, values) -> {
            // is valid XSLT parameter name
            if (XSLT_PARAMETER_NAME_PATTERN.matcher(name).matches()) {
                transformer.setParameter(name, values);
            }
        });
    }

    final SAXResult result = new SAXResult();
    result.setHandler(consumer);
    // According to TrAX specs, all TransformerHandlers are LexicalHandlers
    result.setLexicalHandler(consumer);
    transformerHandler.setResult(result);

    final SAXConsumerAdapter saxConsumerAdapter = new SAXConsumerAdapter();
    saxConsumerAdapter.setContentHandler(transformerHandler);
    super.setSAXConsumer(saxConsumerAdapter);
}
 
Example #20
Source File: MessageOutputStreamTest.java    From iaf with Apache License 2.0 5 votes vote down vote up
@Test
@Ignore("No contract to call endDocument() in case of an Exception")
public void testX31ContentHandlerAsStreamError() throws Exception {
	
	CloseObservableOutputStream cos = new CloseObservableOutputStream() {

		@Override
		public void write(byte[] arg0, int arg1, int arg2) {
			throw new RuntimeException("fakeFailure");
		}
		
	};
	Result result = new StreamResult(cos);
	SAXTransformerFactory tf = (SAXTransformerFactory) TransformerFactory.newInstance();
	TransformerHandler transformerHandler = tf.newTransformerHandler();
	transformerHandler.setResult(result);

	try (MessageOutputStream stream = new MessageOutputStream(null, transformerHandler, (IForwardTarget)null, null, null)) {

		try {
			try (Writer writer = stream.asWriter()) {
				writer.write(testString);
			}
			fail("exception should be thrown");
		} catch (Exception e) {
			assertThat(e.getMessage(),StringContains.containsString("fakeFailure"));
		}

	}
	assertTrue(cos.isCloseCalled());
}
 
Example #21
Source File: JAXBContextImpl.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates a new identity transformer.
 */
public static TransformerHandler createTransformerHandler(boolean disableSecureProcessing) {
    try {
        SAXTransformerFactory tf = (SAXTransformerFactory)XmlFactory.createTransformerFactory(disableSecureProcessing);
        return tf.newTransformerHandler();
    } catch (TransformerConfigurationException e) {
        throw new Error(e); // impossible
    }
}
 
Example #22
Source File: TransformerFactoryImpl.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * javax.xml.transform.sax.SAXTransformerFactory implementation.
 * Get a TransformerHandler object that can process SAX ContentHandler
 * events into a Result, based on the transformation instructions
 * specified by the argument.
 *
 * @param src The source of the transformation instructions.
 * @return A TransformerHandler object that can handle SAX events
 * @throws TransformerConfigurationException
 */
@Override
public TransformerHandler newTransformerHandler(Source src)
    throws TransformerConfigurationException
{
    final Transformer transformer = newTransformer(src);
    if (_uriResolver != null) {
        transformer.setURIResolver(_uriResolver);
    }
    return new TransformerHandlerImpl((TransformerImpl) transformer);
}
 
Example #23
Source File: SmartTransformerFactoryImpl.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Get a TransformerHandler object that can process SAX ContentHandler
 * events based on a transformer specified by the stylesheet Source.
 * Uses com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactory.
 */
public TransformerHandler newTransformerHandler(Templates templates)
    throws TransformerConfigurationException
{
    if (_xsltcFactory == null) {
        createXSLTCTransformerFactory();
    }
    if (_errorlistener != null) {
        _xsltcFactory.setErrorListener(_errorlistener);
    }
    if (_uriresolver != null) {
        _xsltcFactory.setURIResolver(_uriresolver);
    }
    return _xsltcFactory.newTransformerHandler(templates);
}
 
Example #24
Source File: ParseDOM.java    From jlibs with Apache License 2.0 5 votes vote down vote up
@Override
protected void addHandlers(AsyncXMLReader xmlReader) throws Exception{
    TransformerHandler handler = TransformerUtil.newTransformerHandler(null, false, -1, null);
    SAXUtil.setHandler(xmlReader, handler);
    DOMResult result = createDOMResult();
    handler.setResult(result);
    handler.getTransformer().setParameter(DOMResult.class.getName(), result);
}
 
Example #25
Source File: JAXBContextImpl.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates a new identity transformer.
 */
public static TransformerHandler createTransformerHandler(boolean disableSecureProcessing) {
    try {
        SAXTransformerFactory tf = (SAXTransformerFactory)XmlFactory.createTransformerFactory(disableSecureProcessing);
        return tf.newTransformerHandler();
    } catch (TransformerConfigurationException e) {
        throw new Error(e); // impossible
    }
}
 
Example #26
Source File: SmartTransformerFactoryImpl.java    From JDKSourceCode1.8 with MIT License 5 votes vote down vote up
/**
 * Get a TransformerHandler object that can process SAX ContentHandler
 * events based on a transformer specified by the stylesheet Source.
 * Uses com.sun.org.apache.xalan.internal.processor.TransformerFactory.
 */
public TransformerHandler newTransformerHandler(Source src)
    throws TransformerConfigurationException
{
    if (_xalanFactory == null) {
        createXalanTransformerFactory();
    }
    if (_errorlistener != null) {
        _xalanFactory.setErrorListener(_errorlistener);
    }
    if (_uriresolver != null) {
        _xalanFactory.setURIResolver(_uriresolver);
    }
    return _xalanFactory.newTransformerHandler(src);
}
 
Example #27
Source File: MCRXSLTransformer.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
protected LinkedList<TransformerHandler> getTransformHandlerList(MCRParameterCollector parameterCollector)
    throws TransformerConfigurationException, SAXException, ParserConfigurationException {
    checkTemplateUptodate();
    LinkedList<TransformerHandler> xslSteps = new LinkedList<>();
    //every transformhandler shares the same ErrorListener instance
    MCRErrorListener errorListener = MCRErrorListener.getInstance();
    for (Templates template : templates) {
        TransformerHandler handler = tFactory.newTransformerHandler(template);
        parameterCollector.setParametersTo(handler.getTransformer());
        handler.getTransformer().setErrorListener(errorListener);
        if (TRACE_LISTENER_ENABLED) {
            TransformerImpl transformer = (TransformerImpl) handler.getTransformer();
            TraceManager traceManager = transformer.getTraceManager();
            try {
                traceManager.addTraceListener(TRACE_LISTENER);
            } catch (TooManyListenersException e) {
                LOGGER.warn("Could not add MCRTraceListener.", e);
            }
        }
        if (!xslSteps.isEmpty()) {
            Result result = new SAXResult(handler);
            xslSteps.getLast().setResult(result);
        }
        xslSteps.add(handler);
    }
    return xslSteps;
}
 
Example #28
Source File: SAXTFactoryTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Unit test newTransformerHandler with a DOMSource.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testcase06() throws Exception {
    String outputFile = USER_DIR + "saxtf006.out";
    String goldFile = GOLDEN_DIR + "saxtf006GF.out";

    try (FileOutputStream fos = new FileOutputStream(outputFile)) {
        XMLReader reader = XMLReaderFactory.createXMLReader();
        SAXTransformerFactory saxTFactory
                = (SAXTransformerFactory)TransformerFactory.newInstance();

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder docBuilder = dbf.newDocumentBuilder();
        Node node = (Node)docBuilder.parse(new File(XSLT_INCL_FILE));

        DOMSource domSource = new DOMSource(node, "file:///" + XML_DIR);
        TransformerHandler handler =
                    saxTFactory.newTransformerHandler(domSource);

        Result result = new StreamResult(fos);
        handler.setResult(result);
        reader.setContentHandler(handler);
        reader.parse(XML_FILE);
    }
    assertTrue(compareWithGold(goldFile, outputFile));
}
 
Example #29
Source File: TransformerFactoryImpl.java    From JDKSourceCode1.8 with MIT License 5 votes vote down vote up
/**
 * javax.xml.transform.sax.SAXTransformerFactory implementation.
 * Get a TransformerHandler object that can process SAX ContentHandler
 * events into a Result. This method will return a pure copy transformer.
 *
 * @return A TransformerHandler object that can handle SAX events
 * @throws TransformerConfigurationException
 */
@Override
public TransformerHandler newTransformerHandler()
    throws TransformerConfigurationException
{
    final Transformer transformer = newTransformer();
    if (_uriResolver != null) {
        transformer.setURIResolver(_uriResolver);
    }
    return new TransformerHandlerImpl((TransformerImpl) transformer);
}
 
Example #30
Source File: PipeTest.java    From rice with Educational Community License v2.0 5 votes vote down vote up
@Test
public void testPipe()
throws TransformerException, TransformerConfigurationException, 
        SAXException, IOException	   
{
   // Instantiate  a TransformerFactory.
 	TransformerFactory tFactory = TransformerFactory.newInstance();
   // Determine whether the TransformerFactory supports The use uf SAXSource 
   // and SAXResult
   if (tFactory.getFeature(SAXSource.FEATURE) && tFactory.getFeature(SAXResult.FEATURE))
   { 
     // Cast the TransformerFactory to SAXTransformerFactory.
     SAXTransformerFactory saxTFactory = ((SAXTransformerFactory) tFactory);	  
     // Create a TransformerHandler for each stylesheet.
     TransformerHandler tHandler1 = saxTFactory.newTransformerHandler(new StreamSource(PipeTest.class.getResourceAsStream("foo1.xsl")));
     TransformerHandler tHandler2 = saxTFactory.newTransformerHandler(new StreamSource(PipeTest.class.getResourceAsStream("foo2.xsl")));
     TransformerHandler tHandler3 = saxTFactory.newTransformerHandler(new StreamSource(PipeTest.class.getResourceAsStream("foo3.xsl")));
   
     // Create an XMLReader.
    XMLReader reader = XMLReaderFactory.createXMLReader();
     reader.setContentHandler(tHandler1);
     reader.setProperty("http://xml.org/sax/properties/lexical-handler", tHandler1);

     tHandler1.setResult(new SAXResult(tHandler2));
     tHandler2.setResult(new SAXResult(tHandler3));

     // transformer3 outputs SAX events to the serializer.
     java.util.Properties xmlProps = OutputPropertiesFactory.getDefaultMethodProperties("xml");
     xmlProps.setProperty("indent", "yes");
     xmlProps.setProperty("standalone", "no");
     Serializer serializer = SerializerFactory.getSerializer(xmlProps);
     serializer.setOutputStream(System.out);
     tHandler3.setResult(new SAXResult(serializer.asContentHandler()));

    // Parse the XML input document. The input ContentHandler and output ContentHandler
     // work in separate threads to optimize performance.   
     reader.parse(new InputSource(PipeTest.class.getResourceAsStream("foo.xml")));
   }
 }