下面列出了怎么用javax.xml.transform.sax.TransformerHandler的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* 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);
}
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);
}
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);
}
/**
* 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;
}
@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);
}
/**
* 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;
}
/**
* 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;
}
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);
}
}
}
/**
* 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;
}
@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");
}
}
/**
* 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));
}
/**
* 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));
}
/**
* 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));
}
/**
* 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);
}
private void writeAsXML(Attributes attrs, OutputStream out) throws Exception {
TransformerHandler th = getTransformerHandler();
th.getTransformer().setOutputProperty(OutputKeys.INDENT, xmlIndent ? "yes" : "no");
th.setResult(new StreamResult(out));
SAXWriter saxWriter = new SAXWriter(th);
saxWriter.setIncludeKeyword(xmlIncludeKeyword);
saxWriter.setIncludeNamespaceDeclaration(xmlIncludeNamespaceDeclaration);
saxWriter.write(attrs);
}
/**
* 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);
}
private void savePreferences(Preferences node, TransformerHandler handler) throws BackingStoreException, SAXException {
AttributesImpl attrs = new AttributesImpl();
startElement(node.name(), attrs, handler);
String[] keys = node.keys();
for (int i = 0; i < keys.length; i++) {
addAttribute("name", keys[i], attrs);
addAttribute("value", node.get(keys[i], ""), attrs);
emptyElement("option", attrs, handler);
}
String[] children = node.childrenNames();
for (int i = 0; i < children.length; i++) {
savePreferences(node.node(children[i]), handler);
}
endElement(node.name(), handler);
}
/**
* Writes tasks explicitly shown in the timeline as comma-separated list of task identifiers in CDATA section
* of <timeline> element.
*/
private void writeTimelineTasks(UIFacade facade, TransformerHandler handler) throws SAXException {
AttributesImpl attrs = new AttributesImpl();
Set<Task> timelineTasks = facade.getCurrentTaskView().getTimelineTasks();
if (timelineTasks.isEmpty()) {
return;
}
Function<Task, String> getId = new Function<Task, String>() {
@Override
public String apply(Task t) {
return String.valueOf(t.getTaskID());
}
};
cdataElement("timeline", Joiner.on(',').join(Collections2.transform(timelineTasks, getId)), attrs, handler);
}
@Override
protected void marshalToOutputStream(Marshaller ms, Object obj, OutputStream os,
Annotation[] anns, MediaType mt)
throws Exception {
Templates t = createTemplates(getOutTemplates(anns, mt), outParamsMap, outProperties);
if (t == null && supportJaxbOnly) {
super.marshalToOutputStream(ms, obj, os, anns, mt);
return;
}
org.apache.cxf.common.jaxb.JAXBUtils.setMinimumEscapeHandler(ms);
TransformerHandler th = null;
try {
th = factory.newTransformerHandler(t);
} catch (TransformerConfigurationException ex) {
TemplatesImpl ti = (TemplatesImpl)t;
th = factory.newTransformerHandler(ti.getTemplates());
this.trySettingProperties(th, ti);
}
Result result = getStreamResult(os, anns, mt);
if (systemId != null) {
result.setSystemId(systemId);
}
th.setResult(result);
if (getContext() == null) {
th.startDocument();
}
ms.marshal(obj, th);
if (getContext() == null) {
th.endDocument();
}
}
public final ContentHandler createContentHandler() {
try {
TransformerHandler handler = saxtf.newTransformerHandler(templates);
handler.setResult(new SAXResult(outputHandler));
return handler;
} catch (TransformerConfigurationException ex) {
throw new RuntimeException(ex.toString());
}
}
public final ContentHandler createContentHandler() {
try {
TransformerHandler handler = saxtf
.newTransformerHandler(templates);
handler.setResult(new SAXResult(outputHandler));
return handler;
} catch (TransformerConfigurationException ex) {
throw new RuntimeException(ex.toString());
}
}
/**
* Method transform. Transforms a JDOM-Document to the given OutputStream
*
*/
public void transform(Document in, TransformerHandler handler, OutputStream out) {
handler.setResult(new StreamResult(out));
try {
new SAXOutputter(handler).output(in);
} catch (JDOMException ex) {
LOGGER.error("Error while transforming an XML document with an XSL stylesheet.");
}
}
public void test() throws Exception {
ClassReader cr = new ClassReader(is);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
SAXTransformerFactory saxtf = (SAXTransformerFactory) TransformerFactory.newInstance();
TransformerHandler handler = saxtf.newTransformerHandler();
handler.setResult(new SAXResult(new ASMContentHandler(bos, false)));
handler.startDocument();
cr.accept(new SAXClassAdapter(handler, false), false);
handler.endDocument();
assertEquals(cr, new ClassReader(bos.toByteArray()));
}
/**
* 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();
}
/**
* 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);
}
@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);
}
/**
* 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);
}
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;
}
/**
* 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);
}
/**
* 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
}
}