下面列出了javax.xml.transform.TransformerFactory#getFeature ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void test03() {
String xsl = "<?xml version='1.0'?>\n" + "<xsl:stylesheet" + " xmlns:xsl='http://www.w3.org/1999/XSL/Transform'" + " version='1.0'>\n"
+ " <xsl:template match='/'>Hello World!</xsl:template>\n" + "</xsl:stylesheet>\n";
ReaderStub.used = false;
setSystemProperty("org.xml.sax.driver", ReaderStub.class.getName());
try {
TransformerFactory transFactory = TransformerFactory.newInstance();
if (transFactory.getFeature(SAXTransformerFactory.FEATURE) == false) {
System.out.println("SAXTransformerFactory not supported");
}
InputSource in = new InputSource(new StringReader(xsl));
SAXSource source = new SAXSource(in);
transFactory.newTransformer(source);
Assert.assertTrue(printWasReaderStubCreated());
} catch (TransformerException e) {
Assert.fail(e.getMessage());
}
}
@Test(enabled=false) //skipped due to bug JDK-8080097
public void testTransform_DOM_withSM() {
System.out.println("Transform using DOM Source; Security Manager is set:");
setSystemProperty(DOM_FACTORY_ID, "MyDOMFactoryImpl");
try {
TransformerFactory factory = TransformerFactory.newInstance("com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl",
TransformerFactory.class.getClassLoader());
factory.setFeature(ORACLE_FEATURE_SERVICE_MECHANISM, true);
if ((boolean) factory.getFeature(ORACLE_FEATURE_SERVICE_MECHANISM)) {
Assert.fail("should not override in secure mode");
}
} catch (Exception e) {
Assert.fail(e.getMessage());
} finally {
clearSystemProperty(DOM_FACTORY_ID);
}
}
/**
* @bug 8161454
* Verifies that the new / correct name is supported, as is the old / incorrect
* one for compatibility
*/
@Test
public void testNameChange() {
boolean feature;
TransformerFactory tf = TransformerFactory.newInstance();
feature = tf.getFeature(ORACLE_ENABLE_EXTENSION_FUNCTION);
System.out.println("Default setting: " + feature);
// The default: true if no SecurityManager, false otherwise
Assert.assertTrue(feature == getDefault());
setSystemProperty(SP_ENABLE_EXTENSION_FUNCTION, getDefaultOpposite());
tf = TransformerFactory.newInstance();
feature = tf.getFeature(ORACLE_ENABLE_EXTENSION_FUNCTION);
System.out.println("After setting " + SP_ENABLE_EXTENSION_FUNCTION + ": " + feature);
clearSystemProperty(SP_ENABLE_EXTENSION_FUNCTION);
// old/incorrect name is still supported
Assert.assertTrue(feature != getDefault());
setSystemProperty(SP_ENABLE_EXTENSION_FUNCTION_SPEC, getDefaultOpposite());
tf = TransformerFactory.newInstance();
feature = tf.getFeature(ORACLE_ENABLE_EXTENSION_FUNCTION);
System.out.println("After setting " + SP_ENABLE_EXTENSION_FUNCTION_SPEC + ": " + feature);
clearSystemProperty(SP_ENABLE_EXTENSION_FUNCTION_SPEC);
// new/correct name is effective
Assert.assertTrue(feature != getDefault());
}
private static TransformerFactory transformerFactory() throws TransformerConfigurationException {
TransformerFactory factory = TransformerFactory.newInstance();
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
if (factory.getFeature(XMLConstants.ACCESS_EXTERNAL_DTD)) {
factory.setFeature(XMLConstants.ACCESS_EXTERNAL_DTD, false);
}
return factory;
}
/**
* @param template the content or url of the xsl template
* @param data the content or url of the xml data file
* @throws TransformerException
*/
public static String renderTemplate(String template, String data)
throws TransformerException {
String result = null;
TransformerFactory tfactory = TransformerFactory.newInstance();
if (tfactory.getFeature(SAXSource.FEATURE)) {
// setup for xml data file preprocessing to be able to xinclude
SAXParserFactory pfactory= SAXParserFactory.newInstance();
pfactory.setNamespaceAware(true);
pfactory.setValidating(false);
pfactory.setXIncludeAware(true);
XMLReader reader = null;
try {
reader = pfactory.newSAXParser().getXMLReader();
} catch (Exception e) {
throw new TransformerException("Error creating SAX parser/reader", e);
}
// do the actual preprocessing
SAXSource source = new SAXSource(reader, new InputSource(data));
// compile the xsl template
Transformer transformer = tfactory.newTransformer(new StreamSource(template));
// and apply the xsl template to the source document and save in a result string
StringWriter sw = new StringWriter();
StreamResult sr = new StreamResult(sw);
transformer.transform(source, sr);
result = sw.toString();
} else {
Debug.logError("tfactory does not support SAX features!", module);
}
return result;
}
public synchronized void setTransformerFactory(String factoryClass) throws TransformerFactoryConfigurationError {
TransformerFactory transformerFactory = Optional.ofNullable(factoryClass)
.map(c -> TransformerFactory.newInstance(c, MCRClassTools.getClassLoader()))
.orElseGet(TransformerFactory::newInstance);
LOGGER.debug("Transformerfactory: {}", transformerFactory.getClass().getName());
transformerFactory.setURIResolver(URI_RESOLVER);
transformerFactory.setErrorListener(MCRErrorListener.getInstance());
if (transformerFactory.getFeature(SAXSource.FEATURE) && transformerFactory.getFeature(SAXResult.FEATURE)) {
this.tFactory = (SAXTransformerFactory) transformerFactory;
} else {
throw new MCRConfigurationException("Transformer Factory " + transformerFactory.getClass().getName()
+ " does not implement SAXTransformerFactory");
}
}
/**
* 转换文件
* @param strSourcePath
* 源文件路径
* @param strXSLPath
* XSL 文件路径
* @param strTargetPath
* 转变文件路径
* @throws Exception
* ;
*/
private void transform(String strSourcePath, String strXSLPath, String strTargetPath) throws Exception {
TransformerFactory tfactory = TransformerFactory.newInstance();
String catalogPath = PluginUtil.getCataloguePath();
if (tfactory.getFeature(SAXSource.FEATURE)) {
// Standard way of creating an XMLReader in JAXP 1.1.
SAXParserFactory pfactory = SAXParserFactory.newInstance();
pfactory.setNamespaceAware(true); // Very important!
// Turn on validation.
// pfactory.setValidating(true);
// Get an XMLReader.
XMLReader reader = pfactory.newSAXParser().getXMLReader();
reader.setEntityResolver(new Catalogue(catalogPath));
// Instantiate an error handler (see the Handler inner class below)
// that will report any
// errors or warnings that occur as the XMLReader is parsing the XML
// input.
reader.setErrorHandler(new HSErrorHandler());
// Standard way of creating a transformer from a URL.
Transformer t = tfactory.newTransformer(new StreamSource(strXSLPath));
// Specify a SAXSource that takes both an XMLReader and a URL.
SAXSource source = new SAXSource(reader, new InputSource(strSourcePath));
// Transform to a file.
t.transform(source, new StreamResult(strTargetPath));
} else {
throw new Exception(Messages.getString("dialog.XSLTransformationDialog.msg6")); //$NON-NLS-1$
}
}
@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")));
}
}
/**
* 转换文件
* @param strSourcePath
* 源文件路径
* @param strXSLPath
* XSL 文件路径
* @param strTargetPath
* 转变文件路径
* @throws Exception
* ;
*/
private void transform(String strSourcePath, String strXSLPath, String strTargetPath) throws Exception {
TransformerFactory tfactory = TransformerFactory.newInstance();
String catalogPath = PluginUtil.getCataloguePath();
if (tfactory.getFeature(SAXSource.FEATURE)) {
// Standard way of creating an XMLReader in JAXP 1.1.
SAXParserFactory pfactory = SAXParserFactory.newInstance();
pfactory.setNamespaceAware(true); // Very important!
// Turn on validation.
// pfactory.setValidating(true);
// Get an XMLReader.
XMLReader reader = pfactory.newSAXParser().getXMLReader();
reader.setEntityResolver(new Catalogue(catalogPath));
// Instantiate an error handler (see the Handler inner class below)
// that will report any
// errors or warnings that occur as the XMLReader is parsing the XML
// input.
reader.setErrorHandler(new HSErrorHandler());
// Standard way of creating a transformer from a URL.
Transformer t = tfactory.newTransformer(new StreamSource(strXSLPath));
// Specify a SAXSource that takes both an XMLReader and a URL.
SAXSource source = new SAXSource(reader, new InputSource(strSourcePath));
// Transform to a file.
t.transform(source, new StreamResult(strTargetPath));
} else {
throw new Exception(Messages.getString("dialog.XSLTransformationDialog.msg6")); //$NON-NLS-1$
}
}
public static void requireFeature(final TransformerFactory transformerFactory, final String feature) {
if (!transformerFactory.getFeature(feature)) {
throw new SnuggleRuntimeException("TransformerFactory "
+ transformerFactory.getClass().getName()
+ " needs to support feature "
+ feature
+ " in order to be used with SnuggleTeX");
}
}
public int process() throws TransformerException, IOException, SAXException {
ZipInputStream zis = new ZipInputStream(input);
final ZipOutputStream zos = new ZipOutputStream(output);
final OutputStreamWriter osw = new OutputStreamWriter(zos);
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
TransformerFactory tf = TransformerFactory.newInstance();
if (!tf.getFeature(SAXSource.FEATURE) || !tf.getFeature(SAXResult.FEATURE)) {
return 0;
}
SAXTransformerFactory saxtf = (SAXTransformerFactory) tf;
Templates templates = null;
if (xslt != null) {
templates = saxtf.newTemplates(xslt);
}
// configuring outHandlerFactory
// ///////////////////////////////////////////////////////
EntryElement entryElement = getEntryElement(zos);
ContentHandler outDocHandler = null;
switch (outRepresentation) {
case BYTECODE:
outDocHandler = new OutputSlicingHandler(new ASMContentHandlerFactory(zos), entryElement, false);
break;
case MULTI_XML:
outDocHandler = new OutputSlicingHandler(new SAXWriterFactory(osw, true), entryElement, true);
break;
case SINGLE_XML:
ZipEntry outputEntry = new ZipEntry(SINGLE_XML_NAME);
zos.putNextEntry(outputEntry);
outDocHandler = new SAXWriter(osw, false);
break;
}
// configuring inputDocHandlerFactory
// /////////////////////////////////////////////////
ContentHandler inDocHandler;
if (templates == null) {
inDocHandler = outDocHandler;
} else {
inDocHandler = new InputSlicingHandler("class", outDocHandler, new TransformerHandlerFactory(saxtf, templates, outDocHandler));
}
ContentHandlerFactory inDocHandlerFactory = new SubdocumentHandlerFactory(inDocHandler);
if (inDocHandler != null && inRepresentation != SINGLE_XML) {
inDocHandler.startDocument();
inDocHandler.startElement("", "classes", "classes", new AttributesImpl());
}
int i = 0;
ZipEntry ze;
while ((ze = zis.getNextEntry()) != null) {
update(ze.getName(), n++);
if (isClassEntry(ze)) {
processEntry(zis, ze, inDocHandlerFactory);
} else {
OutputStream os = entryElement.openEntry(getName(ze));
copyEntry(zis, os);
entryElement.closeEntry();
}
i++;
}
if (inDocHandler != null && inRepresentation != SINGLE_XML) {
inDocHandler.endElement("", "classes", "classes");
inDocHandler.endDocument();
}
if (outRepresentation == SINGLE_XML) {
zos.closeEntry();
}
zos.flush();
zos.close();
return i;
}
public int process() throws TransformerException, IOException, SAXException {
ZipInputStream zis = new ZipInputStream(input);
final ZipOutputStream zos = new ZipOutputStream(output);
final OutputStreamWriter osw = new OutputStreamWriter(zos);
Thread.currentThread().setContextClassLoader(
getClass().getClassLoader());
TransformerFactory tf = TransformerFactory.newInstance();
if (!tf.getFeature(SAXSource.FEATURE)
|| !tf.getFeature(SAXResult.FEATURE)) {
return 0;
}
SAXTransformerFactory saxtf = (SAXTransformerFactory) tf;
Templates templates = null;
if (xslt != null) {
templates = saxtf.newTemplates(xslt);
}
// configuring outHandlerFactory
// ///////////////////////////////////////////////////////
EntryElement entryElement = getEntryElement(zos);
ContentHandler outDocHandler = null;
switch (outRepresentation) {
case BYTECODE:
outDocHandler = new OutputSlicingHandler(
new ASMContentHandlerFactory(zos), entryElement, false);
break;
case MULTI_XML:
outDocHandler = new OutputSlicingHandler(new SAXWriterFactory(osw,
true), entryElement, true);
break;
case SINGLE_XML:
ZipEntry outputEntry = new ZipEntry(SINGLE_XML_NAME);
zos.putNextEntry(outputEntry);
outDocHandler = new SAXWriter(osw, false);
break;
}
// configuring inputDocHandlerFactory
// /////////////////////////////////////////////////
ContentHandler inDocHandler;
if (templates == null) {
inDocHandler = outDocHandler;
} else {
inDocHandler = new InputSlicingHandler("class", outDocHandler,
new TransformerHandlerFactory(saxtf, templates,
outDocHandler));
}
ContentHandlerFactory inDocHandlerFactory = new SubdocumentHandlerFactory(
inDocHandler);
if (inDocHandler != null && inRepresentation != SINGLE_XML) {
inDocHandler.startDocument();
inDocHandler.startElement("", "classes", "classes",
new AttributesImpl());
}
int i = 0;
ZipEntry ze;
while ((ze = zis.getNextEntry()) != null) {
update(ze.getName(), n++);
if (isClassEntry(ze)) {
processEntry(zis, ze, inDocHandlerFactory);
} else {
OutputStream os = entryElement.openEntry(getName(ze));
copyEntry(zis, os);
entryElement.closeEntry();
}
i++;
}
if (inDocHandler != null && inRepresentation != SINGLE_XML) {
inDocHandler.endElement("", "classes", "classes");
inDocHandler.endDocument();
}
if (outRepresentation == SINGLE_XML) {
zos.closeEntry();
}
zos.flush();
zos.close();
return i;
}
public int process() throws TransformerException, IOException, SAXException {
ZipInputStream zis = new ZipInputStream(input);
final ZipOutputStream zos = new ZipOutputStream(output);
final OutputStreamWriter osw = new OutputStreamWriter(zos);
Thread.currentThread().setContextClassLoader(
getClass().getClassLoader());
TransformerFactory tf = TransformerFactory.newInstance();
if (!tf.getFeature(SAXSource.FEATURE)
|| !tf.getFeature(SAXResult.FEATURE)) {
return 0;
}
SAXTransformerFactory saxtf = (SAXTransformerFactory) tf;
Templates templates = null;
if (xslt != null) {
templates = saxtf.newTemplates(xslt);
}
// configuring outHandlerFactory
// ///////////////////////////////////////////////////////
EntryElement entryElement = getEntryElement(zos);
ContentHandler outDocHandler = null;
switch (outRepresentation) {
case BYTECODE:
outDocHandler = new OutputSlicingHandler(
new ASMContentHandlerFactory(zos), entryElement, false);
break;
case MULTI_XML:
outDocHandler = new OutputSlicingHandler(new SAXWriterFactory(osw,
true), entryElement, true);
break;
case SINGLE_XML:
ZipEntry outputEntry = new ZipEntry(SINGLE_XML_NAME);
zos.putNextEntry(outputEntry);
outDocHandler = new SAXWriter(osw, false);
break;
}
// configuring inputDocHandlerFactory
// /////////////////////////////////////////////////
ContentHandler inDocHandler;
if (templates == null) {
inDocHandler = outDocHandler;
} else {
inDocHandler = new InputSlicingHandler("class", outDocHandler,
new TransformerHandlerFactory(saxtf, templates,
outDocHandler));
}
ContentHandlerFactory inDocHandlerFactory = new SubdocumentHandlerFactory(
inDocHandler);
if (inDocHandler != null && inRepresentation != SINGLE_XML) {
inDocHandler.startDocument();
inDocHandler.startElement("", "classes", "classes",
new AttributesImpl());
}
int i = 0;
ZipEntry ze;
while ((ze = zis.getNextEntry()) != null) {
update(ze.getName(), n++);
if (isClassEntry(ze)) {
processEntry(zis, ze, inDocHandlerFactory);
} else {
OutputStream os = entryElement.openEntry(getName(ze));
copyEntry(zis, os);
entryElement.closeEntry();
}
i++;
}
if (inDocHandler != null && inRepresentation != SINGLE_XML) {
inDocHandler.endElement("", "classes", "classes");
inDocHandler.endDocument();
}
if (outRepresentation == SINGLE_XML) {
zos.closeEntry();
}
zos.flush();
zos.close();
return i;
}
public int process() throws TransformerException, IOException, SAXException
{
ZipInputStream zis = new ZipInputStream(input);
final ZipOutputStream zos = new ZipOutputStream(output);
final OutputStreamWriter osw = new OutputStreamWriter(zos);
Thread.currentThread()
.setContextClassLoader(getClass().getClassLoader());
TransformerFactory tf = TransformerFactory.newInstance();
if (!tf.getFeature(SAXSource.FEATURE)
|| !tf.getFeature(SAXResult.FEATURE))
return 0;
SAXTransformerFactory saxtf = (SAXTransformerFactory) tf;
Templates templates = null;
if (xslt != null) {
templates = saxtf.newTemplates(xslt);
}
// configuring outHandlerFactory
// ///////////////////////////////////////////////////////
EntryElement entryElement = getEntryElement(zos);
ContentHandler outDocHandler = null;
switch (outRepresentation) {
case BYTECODE:
outDocHandler = new OutputSlicingHandler(new ASMContentHandlerFactory(zos,
computeMax),
entryElement,
false);
break;
case MULTI_XML:
outDocHandler = new OutputSlicingHandler(new SAXWriterFactory(osw,
true),
entryElement,
true);
break;
case SINGLE_XML:
ZipEntry outputEntry = new ZipEntry(SINGLE_XML_NAME);
zos.putNextEntry(outputEntry);
outDocHandler = new SAXWriter(osw, false);
break;
}
// configuring inputDocHandlerFactory
// /////////////////////////////////////////////////
ContentHandler inDocHandler = null;
if (templates == null) {
inDocHandler = outDocHandler;
} else {
inDocHandler = new InputSlicingHandler("class",
outDocHandler,
new TransformerHandlerFactory(saxtf,
templates,
outDocHandler));
}
ContentHandlerFactory inDocHandlerFactory = new SubdocumentHandlerFactory(inDocHandler);
if (inDocHandler != null && inRepresentation != SINGLE_XML) {
inDocHandler.startDocument();
inDocHandler.startElement("",
"classes",
"classes",
new AttributesImpl());
}
int i = 0;
ZipEntry ze = null;
while ((ze = zis.getNextEntry()) != null) {
update(ze.getName(), n++);
if (isClassEntry(ze)) {
processEntry(zis, ze, inDocHandlerFactory);
} else {
OutputStream os = entryElement.openEntry(getName(ze));
copyEntry(zis, os);
entryElement.closeEntry();
}
i++;
}
if (inDocHandler != null && inRepresentation != SINGLE_XML) {
inDocHandler.endElement("", "classes", "classes");
inDocHandler.endDocument();
}
if (outRepresentation == SINGLE_XML) {
zos.closeEntry();
}
zos.flush();
zos.close();
return i;
}
public int process() throws TransformerException, IOException, SAXException {
ZipInputStream zis = new ZipInputStream(input);
final ZipOutputStream zos = new ZipOutputStream(output);
final OutputStreamWriter osw = new OutputStreamWriter(zos);
Thread.currentThread().setContextClassLoader(
getClass().getClassLoader());
TransformerFactory tf = TransformerFactory.newInstance();
if (!tf.getFeature(SAXSource.FEATURE)
|| !tf.getFeature(SAXResult.FEATURE)) {
return 0;
}
SAXTransformerFactory saxtf = (SAXTransformerFactory) tf;
Templates templates = null;
if (xslt != null) {
templates = saxtf.newTemplates(xslt);
}
// configuring outHandlerFactory
// ///////////////////////////////////////////////////////
EntryElement entryElement = getEntryElement(zos);
ContentHandler outDocHandler = null;
switch (outRepresentation) {
case BYTECODE:
outDocHandler = new OutputSlicingHandler(
new ASMContentHandlerFactory(zos), entryElement, false);
break;
case MULTI_XML:
outDocHandler = new OutputSlicingHandler(new SAXWriterFactory(osw,
true), entryElement, true);
break;
case SINGLE_XML:
ZipEntry outputEntry = new ZipEntry(SINGLE_XML_NAME);
zos.putNextEntry(outputEntry);
outDocHandler = new SAXWriter(osw, false);
break;
}
// configuring inputDocHandlerFactory
// /////////////////////////////////////////////////
ContentHandler inDocHandler;
if (templates == null) {
inDocHandler = outDocHandler;
} else {
inDocHandler = new InputSlicingHandler("class", outDocHandler,
new TransformerHandlerFactory(saxtf, templates,
outDocHandler));
}
ContentHandlerFactory inDocHandlerFactory = new SubdocumentHandlerFactory(
inDocHandler);
if (inDocHandler != null && inRepresentation != SINGLE_XML) {
inDocHandler.startDocument();
inDocHandler.startElement("", "classes", "classes",
new AttributesImpl());
}
int i = 0;
ZipEntry ze;
while ((ze = zis.getNextEntry()) != null) {
update(ze.getName(), n++);
if (isClassEntry(ze)) {
processEntry(zis, ze, inDocHandlerFactory);
} else {
OutputStream os = entryElement.openEntry(getName(ze));
copyEntry(zis, os);
entryElement.closeEntry();
}
i++;
}
if (inDocHandler != null && inRepresentation != SINGLE_XML) {
inDocHandler.endElement("", "classes", "classes");
inDocHandler.endDocument();
}
if (outRepresentation == SINGLE_XML) {
zos.closeEntry();
}
zos.flush();
zos.close();
return i;
}
@Test public void testPipeUsingTemplate(){
try{
// 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);
// Get Relevant StyleSheets
URIResolver resolver = new WidgetURITestResolver();
saxTFactory.setURIResolver(resolver);
/*
Document edlStyle,templateStyle;
edlStyle=XMLUtil.parseInputStream(PipeTransformationTest.class.getResourceAsStream("StudentInitiatedDrop_Style_pipeTest.xml"));
// Get Template Name
XPathFactory xPathFactory=XPathFactory.newInstance();
XPath xPath=xPathFactory.newXPath();
Node node=(Node)xPath.evaluate("//use[0]",edlStyle,XPathConstants.NODE);
//Node node=nodes.item(0);
if(node!=null){
if(node.hasAttributes()){
Node testAttri=node.getAttributes().getNamedItem("name");
if(testAttri!=null){
templateName=testAttri.getNodeValue();
}else{
//set default template as widgets
templateName="widgets";
}
}
}
System.out.println(templateName);
*/
//templateStyle=XMLUtil.parseInputStream(PipeTransformationTest.class.getResourceAsStream("widgets_pipeTest.xml"));
// Create a TransformerHandler for each stylesheet.
TransformerHandler tHandler1 = saxTFactory.newTransformerHandler(new StreamSource(PipeTransformationTest.class.getResourceAsStream("StudentInitiatedDrop_Style_pipeTest.xml")));
// TransformerHandler tHandler2 = saxTFactory.newTransformerHandler(new StreamSource(PipeTransformationTest.class.getResourceAsStream("trans.xml")));
//TransformerHandler tHandler3 = saxTFactory.newTransformerHandler(new StreamSource("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);
FileOutputStream transformedXML=new FileOutputStream("c://file.xml");
serializer.setOutputStream(transformedXML);
tHandler1.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(PipeTransformationTest.class.getResourceAsStream("StudentInitiatedDrop.xml")));
}
}catch(Exception ex){
ex.printStackTrace();
}
}
public static void extractMorph(ExtractionProperties extractProps)
throws TransformerException, TransformerConfigurationException,
SAXException, IOException, JDOMException {
System.out.println("Extracting morph:");
System.out.println("Generating morph.xml");
TransformerFactory tFactory = TransformerFactory.newInstance();
File morphFile = new File(new File(extractProps.destDir), "morph.xml");
File tempFile = new File(new File(extractProps.tempDir), "temp.xml");
if (tFactory.getFeature(SAXSource.FEATURE)
&& tFactory.getFeature(SAXResult.FEATURE)) {
SAXTransformerFactory saxTFactory = ((SAXTransformerFactory) tFactory);
ArrayList<XMLFilter> filterChain = new ArrayList<XMLFilter>();
ArrayList<String> xslChain = new ArrayList<String>();
if (extractProps.macroSpecs.length() > 0) {
}
addTransforms(xslChain, extractProps.macroSpecs);
for (String xslFile : xslChain)
filterChain.add(saxTFactory.newXMLFilter(ExtractGrammar
.getSource(xslFile)));
// Create an XMLReader and set first xsl transform to that.
XMLReader reader = XMLReaderFactory.createXMLReader();
XMLFilter xmlFilter0 = filterChain.get(0);
xmlFilter0.setParent(reader);
//Create chain of xsl transforms
// Create an XMLFilter for each stylesheet.
for (int i = 1; i < filterChain.size(); i++) {
XMLFilter xmlFilterPrev = filterChain.get(i - 1);
XMLFilter xmlFilterCurr = filterChain.get(i);
xmlFilterCurr.setParent(xmlFilterPrev);
}
XMLFilter xmlFilter = filterChain.get(filterChain.size() - 1);
java.util.Properties xmlProps = OutputPropertiesFactory
.getDefaultMethodProperties("xml");
xmlProps.setProperty("indent", "yes");
xmlProps.setProperty("standalone", "no");
xmlProps.setProperty("{http://xml.apache.org/xalan}indent-amount",
"2");
Serializer serializer = SerializerFactory.getSerializer(xmlProps);
serializer.setOutputStream(new FileOutputStream(morphFile));
//XMLFilter xmlFilter = xmlFilter2;
//XMLFilter xmlFilter = xmlFilter3;
xmlFilter.setContentHandler(serializer.asContentHandler());
xmlFilter.parse(new InputSource(tempFile.getPath()));
}
//Deleting the temporary lex file
//tempFile.delete();
}
public static void extractRules(ExtractionProperties extractProps) throws TransformerException, TransformerConfigurationException,SAXException, IOException,JDOMException{
System.out.println("Extracting rule info:");
File rulesFile = new File(new File(extractProps.destDir), "rules.xml");
File tempFile = new File(new File(extractProps.tempDir), "temp-rules.xml");
PrintWriter tempOut=new PrintWriter(new FileOutputStream(tempFile),true);
File ccgbankDir = new File(extractProps.srcDir);
File[] ccgbankSections=ccgbankDir.listFiles();
Arrays.sort(ccgbankSections);
RulesTally.RULE_FREQ_CUTOFF = extractProps.ruleFreqCutoff;
RulesTally.KEEP_UNMATCHED = !extractProps.skipUnmatched;
// add root
tempOut.println("<rules>");
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer(ExtractGrammar.getSource("opennlp.ccgbank/transform/rulesExtr.xsl"));
for (int i=extractProps.startSection; i<=extractProps.endSection; i++){
File[] files=ccgbankSections[i].listFiles();
Arrays.sort(files);
int fileStart = 0; int fileLimit = files.length;
if (extractProps.fileNum >= 0) {
fileStart = extractProps.fileNum;
fileLimit = extractProps.fileNum + 1;
}
for (int j=fileStart; j<fileLimit; j++){
String inputFile=files[j].getAbsolutePath();
if (j == fileStart) System.out.print(files[j].getName() + " ");
else if (j == (fileLimit-1)) System.out.println(" " + files[j].getName());
else System.out.print(".");
if (fileStart == fileLimit-1) System.out.println();
try {
transformer.transform(new StreamSource(inputFile),new StreamResult(tempOut));
}
catch (Exception exc) {
System.out.println("Skipping: " + inputFile);
System.out.println(exc.toString());
}
tempOut.flush();
}
}
tempOut.flush();
tempOut.println("</rules>");
tempOut.close();
RulesTally.printTally(extractProps);
System.out.println("Generating rules.xml");
if (tFactory.getFeature(SAXSource.FEATURE) && tFactory.getFeature(SAXResult.FEATURE)){
SAXTransformerFactory saxTFactory = ((SAXTransformerFactory) tFactory);
// Create an XMLFilter for each stylesheet.
XMLFilter xmlFilter1 = saxTFactory.newXMLFilter(ExtractGrammar.getSource("opennlp.ccgbank/transform/ccgRules.xsl"));
//XMLFilter xmlFilter3 = saxTFactory.newXMLFilter(new StreamSource("foo3.xsl"));
// Create an XMLReader.
XMLReader reader = XMLReaderFactory.createXMLReader();
// xmlFilter1 uses the XMLReader as its reader.
xmlFilter1.setParent(reader);
java.util.Properties xmlProps = OutputPropertiesFactory.getDefaultMethodProperties("xml");
xmlProps.setProperty("indent", "yes");
xmlProps.setProperty("standalone", "no");
xmlProps.setProperty("{http://xml.apache.org/xalan}indent-amount", "2");
Serializer serializer = SerializerFactory.getSerializer(xmlProps);
serializer.setOutputStream(new FileOutputStream(rulesFile));
XMLFilter xmlFilter = xmlFilter1;
xmlFilter.setContentHandler(serializer.asContentHandler());
xmlFilter.parse(new InputSource(tempFile.getPath()));
}
//Deleting the temporory lex file
//lexiconTempFile.delete();
}