Java Code Examples for org.xml.sax.XMLFilter#setParent()

The following examples show how to use org.xml.sax.XMLFilter#setParent() . 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: SAXTFactoryTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Unit test for contentHandler setter/getter along reader as handler's
 * parent.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testcase10() throws Exception {
    String outputFile = USER_DIR + "saxtf010.out";
    String goldFile = GOLDEN_DIR + "saxtf010GF.out";
    // The transformer will use a SAX parser as it's reader.
    XMLReader reader = XMLReaderFactory.createXMLReader();
    SAXTransformerFactory saxTFactory
            = (SAXTransformerFactory)TransformerFactory.newInstance();
    XMLFilter filter =
        saxTFactory.newXMLFilter(new StreamSource(XSLT_FILE));
    filter.setParent(reader);
    filter.setContentHandler(new MyContentHandler(outputFile));

    // Now, when you call transformer.parse, it will set itself as
    // the content handler for the parser object (it's "parent"), and
    // will then call the parse method on the parser.
    filter.parse(new InputSource(XML_FILE));
    assertTrue(compareWithGold(goldFile, outputFile));
}
 
Example 2
Source File: SAXTFactoryTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Unit test for contentHandler setter/getter.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testcase12() throws Exception {
    String outputFile = USER_DIR + "saxtf012.out";
    String goldFile = GOLDEN_DIR + "saxtf012GF.out";
    // The transformer will use a SAX parser as it's reader.
    XMLReader reader = XMLReaderFactory.createXMLReader();

    InputSource is = new InputSource(new FileInputStream(XSLT_FILE));
    SAXSource saxSource = new SAXSource();
    saxSource.setInputSource(is);

    SAXTransformerFactory saxTFactory = (SAXTransformerFactory)TransformerFactory.newInstance();
    XMLFilter filter = saxTFactory.newXMLFilter(saxSource);

    filter.setParent(reader);
    filter.setContentHandler(new MyContentHandler(outputFile));

    // Now, when you call transformer.parse, it will set itself as
    // the content handler for the parser object (it's "parent"), and
    // will then call the parse method on the parser.
    filter.parse(new InputSource(XML_FILE));
    assertTrue(compareWithGold(goldFile, outputFile));
}
 
Example 3
Source File: SAXTFactoryTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Unit test for TemplatesHandler setter/getter.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testcase13() throws Exception {
    String outputFile = USER_DIR + "saxtf013.out";
    String goldFile = GOLDEN_DIR + "saxtf013GF.out";
    try(FileInputStream fis = new FileInputStream(XML_FILE)) {
        // The transformer will use a SAX parser as it's reader.
        XMLReader reader = XMLReaderFactory.createXMLReader();

        SAXTransformerFactory saxTFactory
                = (SAXTransformerFactory) TransformerFactory.newInstance();
        TemplatesHandler thandler = saxTFactory.newTemplatesHandler();
        // I have put this as it was complaining about systemid
        thandler.setSystemId("file:///" + USER_DIR);

        reader.setContentHandler(thandler);
        reader.parse(XSLT_FILE);
        XMLFilter filter
                = saxTFactory.newXMLFilter(thandler.getTemplates());
        filter.setParent(reader);

        filter.setContentHandler(new MyContentHandler(outputFile));
        filter.parse(new InputSource(fis));
    }
    assertTrue(compareWithGold(goldFile, outputFile));
}
 
Example 4
Source File: JAXBConfigImpl.java    From rice with Educational Community License v2.0 6 votes vote down vote up
protected org.kuali.rice.core.impl.config.property.Config unmarshal(Unmarshaller unmarshaller, InputStream in)
        throws SAXException, ParserConfigurationException, IOException,
        IllegalStateException, JAXBException {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setNamespaceAware(true);

    XMLFilter filter = new ConfigNamespaceURIFilter();
    filter.setParent(spf.newSAXParser().getXMLReader());

    UnmarshallerHandler handler = unmarshaller.getUnmarshallerHandler();
    filter.setContentHandler(handler);

    filter.parse(new InputSource(in));

    return (org.kuali.rice.core.impl.config.property.Config) handler.getResult();
}
 
Example 5
Source File: ModelLoader.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Parses a RELAX NG grammar into an annotated grammar.
 */
private Model loadRELAXNG() throws SAXException {

    // build DOM forest
    final DOMForest forest = buildDOMForest( new RELAXNGInternalizationLogic() );

    // use JAXP masquerading to validate the input document.
    // DOMForest -> ExtensionBindingChecker -> RNGOM

    XMLReaderCreator xrc = new XMLReaderCreator() {
        public XMLReader createXMLReader() {

            // foreset parser cannot change the receivers while it's working,
            // so we need to have one XMLFilter that works as a buffer
            XMLFilter buffer = new XMLFilterImpl() {
                @Override
                public void parse(InputSource source) throws IOException, SAXException {
                    forest.createParser().parse( source, this, this, this );
                }
            };

            XMLFilter f = new ExtensionBindingChecker(Const.RELAXNG_URI,opt,errorReceiver);
            f.setParent(buffer);

            f.setEntityResolver(opt.entityResolver);

            return f;
        }
    };

    Parseable p = new SAXParseable( opt.getGrammars()[0], errorReceiver, xrc );

    return loadRELAXNG(p);

}
 
Example 6
Source File: ModelLoader.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Parses a RELAX NG grammar into an annotated grammar.
 */
private Model loadRELAXNG() throws SAXException {

    // build DOM forest
    final DOMForest forest = buildDOMForest( new RELAXNGInternalizationLogic() );

    // use JAXP masquerading to validate the input document.
    // DOMForest -> ExtensionBindingChecker -> RNGOM

    XMLReaderCreator xrc = new XMLReaderCreator() {
        public XMLReader createXMLReader() {

            // foreset parser cannot change the receivers while it's working,
            // so we need to have one XMLFilter that works as a buffer
            XMLFilter buffer = new XMLFilterImpl() {
                @Override
                public void parse(InputSource source) throws IOException, SAXException {
                    forest.createParser().parse( source, this, this, this );
                }
            };

            XMLFilter f = new ExtensionBindingChecker(Const.RELAXNG_URI,opt,errorReceiver);
            f.setParent(buffer);

            f.setEntityResolver(opt.entityResolver);

            return f;
        }
    };

    Parseable p = new SAXParseable( opt.getGrammars()[0], errorReceiver, xrc );

    return loadRELAXNG(p);

}
 
Example 7
Source File: ModelLoader.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Parses a RELAX NG grammar into an annotated grammar.
 */
private Model loadRELAXNG() throws SAXException {

    // build DOM forest
    final DOMForest forest = buildDOMForest( new RELAXNGInternalizationLogic() );

    // use JAXP masquerading to validate the input document.
    // DOMForest -> ExtensionBindingChecker -> RNGOM

    XMLReaderCreator xrc = new XMLReaderCreator() {
        public XMLReader createXMLReader() {

            // foreset parser cannot change the receivers while it's working,
            // so we need to have one XMLFilter that works as a buffer
            XMLFilter buffer = new XMLFilterImpl() {
                @Override
                public void parse(InputSource source) throws IOException, SAXException {
                    forest.createParser().parse( source, this, this, this );
                }
            };

            XMLFilter f = new ExtensionBindingChecker(Const.RELAXNG_URI,opt,errorReceiver);
            f.setParent(buffer);

            f.setEntityResolver(opt.entityResolver);

            return f;
        }
    };

    Parseable p = new SAXParseable( opt.getGrammars()[0], errorReceiver, xrc );

    return loadRELAXNG(p);

}
 
Example 8
Source File: ModelLoader.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Parses a RELAX NG grammar into an annotated grammar.
 */
private Model loadRELAXNG() throws SAXException {

    // build DOM forest
    final DOMForest forest = buildDOMForest( new RELAXNGInternalizationLogic() );

    // use JAXP masquerading to validate the input document.
    // DOMForest -> ExtensionBindingChecker -> RNGOM

    XMLReaderCreator xrc = new XMLReaderCreator() {
        public XMLReader createXMLReader() {

            // foreset parser cannot change the receivers while it's working,
            // so we need to have one XMLFilter that works as a buffer
            XMLFilter buffer = new XMLFilterImpl() {
                @Override
                public void parse(InputSource source) throws IOException, SAXException {
                    forest.createParser().parse( source, this, this, this );
                }
            };

            XMLFilter f = new ExtensionBindingChecker(Const.RELAXNG_URI,opt,errorReceiver);
            f.setParent(buffer);

            f.setEntityResolver(opt.entityResolver);

            return f;
        }
    };

    Parseable p = new SAXParseable( opt.getGrammars()[0], errorReceiver, xrc );

    return loadRELAXNG(p);

}
 
Example 9
Source File: SAXTFactoryTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Unit test for contentHandler setter/getter with parent.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testcase11() throws Exception {
    String outputFile = USER_DIR + "saxtf011.out";
    String goldFile = GOLDEN_DIR + "saxtf011GF.out";
    // The transformer will use a SAX parser as it's reader.
    XMLReader reader = XMLReaderFactory.createXMLReader();
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    DocumentBuilder docBuilder = dbf.newDocumentBuilder();
    Document document = docBuilder.parse(new File(XSLT_FILE));
    Node node = (Node)document;
    DOMSource domSource= new DOMSource(node);

    SAXTransformerFactory saxTFactory
            = (SAXTransformerFactory)TransformerFactory.newInstance();
    XMLFilter filter = saxTFactory.newXMLFilter(domSource);

    filter.setParent(reader);
    filter.setContentHandler(new MyContentHandler(outputFile));

    // Now, when you call transformer.parse, it will set itself as
    // the content handler for the parser object (it's "parent"), and
    // will then call the parse method on the parser.
    filter.parse(new InputSource(XML_FILE));
    assertTrue(compareWithGold(goldFile, outputFile));
}
 
Example 10
Source File: ModelLoader.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Parses a RELAX NG grammar into an annotated grammar.
 */
private Model loadRELAXNG() throws SAXException {

    // build DOM forest
    final DOMForest forest = buildDOMForest( new RELAXNGInternalizationLogic() );

    // use JAXP masquerading to validate the input document.
    // DOMForest -> ExtensionBindingChecker -> RNGOM

    XMLReaderCreator xrc = new XMLReaderCreator() {
        public XMLReader createXMLReader() {

            // foreset parser cannot change the receivers while it's working,
            // so we need to have one XMLFilter that works as a buffer
            XMLFilter buffer = new XMLFilterImpl() {
                @Override
                public void parse(InputSource source) throws IOException, SAXException {
                    forest.createParser().parse( source, this, this, this );
                }
            };

            XMLFilter f = new ExtensionBindingChecker(Const.RELAXNG_URI,opt,errorReceiver);
            f.setParent(buffer);

            f.setEntityResolver(opt.entityResolver);

            return f;
        }
    };

    Parseable p = new SAXParseable( opt.getGrammars()[0], errorReceiver, xrc );

    return loadRELAXNG(p);

}
 
Example 11
Source File: ModelLoader.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Parses a RELAX NG grammar into an annotated grammar.
 */
private Model loadRELAXNG() throws SAXException {

    // build DOM forest
    final DOMForest forest = buildDOMForest( new RELAXNGInternalizationLogic() );

    // use JAXP masquerading to validate the input document.
    // DOMForest -> ExtensionBindingChecker -> RNGOM

    XMLReaderCreator xrc = new XMLReaderCreator() {
        public XMLReader createXMLReader() {

            // foreset parser cannot change the receivers while it's working,
            // so we need to have one XMLFilter that works as a buffer
            XMLFilter buffer = new XMLFilterImpl() {
                @Override
                public void parse(InputSource source) throws IOException, SAXException {
                    forest.createParser().parse( source, this, this, this );
                }
            };

            XMLFilter f = new ExtensionBindingChecker(Const.RELAXNG_URI,opt,errorReceiver);
            f.setParent(buffer);

            f.setEntityResolver(opt.entityResolver);

            return f;
        }
    };

    Parseable p = new SAXParseable( opt.getGrammars()[0], errorReceiver, xrc );

    return loadRELAXNG(p);

}
 
Example 12
Source File: ModelLoader.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Parses a RELAX NG grammar into an annotated grammar.
 */
private Model loadRELAXNG() throws SAXException {

    // build DOM forest
    final DOMForest forest = buildDOMForest( new RELAXNGInternalizationLogic() );

    // use JAXP masquerading to validate the input document.
    // DOMForest -> ExtensionBindingChecker -> RNGOM

    XMLReaderCreator xrc = new XMLReaderCreator() {
        public XMLReader createXMLReader() {

            // foreset parser cannot change the receivers while it's working,
            // so we need to have one XMLFilter that works as a buffer
            XMLFilter buffer = new XMLFilterImpl() {
                @Override
                public void parse(InputSource source) throws IOException, SAXException {
                    forest.createParser().parse( source, this, this, this );
                }
            };

            XMLFilter f = new ExtensionBindingChecker(Const.RELAXNG_URI,opt,errorReceiver);
            f.setParent(buffer);

            f.setEntityResolver(opt.entityResolver);

            return f;
        }
    };

    Parseable p = new SAXParseable( opt.getGrammars()[0], errorReceiver, xrc );

    return loadRELAXNG(p);

}
 
Example 13
Source File: SAXUtil.java    From jpmml-model with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
static
public XMLReader createFilteredReader(XMLReader reader, XMLFilter... filters){
	XMLReader result = reader;

	for(XMLFilter filter : filters){
		filter.setParent(result);

		result = filter;
	}

	return result;
}
 
Example 14
Source File: MorphExtract.java    From openccg with GNU Lesser General Public License v2.1 4 votes vote down vote up
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();
}
 
Example 15
Source File: RulesExtract.java    From openccg with GNU Lesser General Public License v2.1 4 votes vote down vote up
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();
}