List of usage examples for org.xml.sax XMLReader setProperty
public void setProperty(String name, Object value) throws SAXNotRecognizedException, SAXNotSupportedException;
From source file:Pipe.java
public static void main(String[] args) 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("foo1.xsl")); TransformerHandler tHandler2 = saxTFactory.newTransformerHandler(new StreamSource("foo2.xsl")); 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); 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("foo.xml"); }//from w w w . ja v a 2s . c o m }
From source file:SAX2SAX.java
public static void main(String[] args) throws TransformerException, TransformerConfigurationException, SAXException, IOException { // Instantiate a TransformerFactory. TransformerFactory tFactory = TransformerFactory.newInstance(); // Determine whether the TransformerFactory supports The use of SAXSource // and SAXResult if (tFactory.getFeature(SAXSource.FEATURE) && tFactory.getFeature(SAXResult.FEATURE)) { // Cast the TransformerFactory. SAXTransformerFactory saxTFactory = ((SAXTransformerFactory) tFactory); // Create a ContentHandler to handle parsing of the stylesheet. TemplatesHandler templatesHandler = saxTFactory.newTemplatesHandler(); // Create an XMLReader and set its ContentHandler. XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setContentHandler(templatesHandler); // Parse the stylesheet. reader.parse("birds.xsl"); //Get the Templates object from the ContentHandler. Templates templates = templatesHandler.getTemplates(); // Create a ContentHandler to handle parsing of the XML source. TransformerHandler handler = saxTFactory.newTransformerHandler(templates); // Reset the XMLReader's ContentHandler. reader.setContentHandler(handler); // Set the ContentHandler to also function as a LexicalHandler, which // includes "lexical" events (e.g., comments and CDATA). reader.setProperty("http://xml.org/sax/properties/lexical-handler", handler); FileOutputStream fos = new FileOutputStream("birds.out"); java.util.Properties xmlProps = OutputPropertiesFactory.getDefaultMethodProperties("xml"); xmlProps.setProperty("indent", "yes"); xmlProps.setProperty("standalone", "no"); Serializer serializer = SerializerFactory.getSerializer(xmlProps); serializer.setOutputStream(fos); // Set the result handling to be a serialization to the file output stream. Result result = new SAXResult(serializer.asContentHandler()); handler.setResult(result);// ww w . ja va 2s .c o m // Parse the XML input document. reader.parse("birds.xml"); System.out.println("************* The result is in birds.out *************"); } else System.out.println("The TransformerFactory does not support SAX input and SAX output"); }
From source file:Main.java
public static synchronized SAXParser getSAXParser() { if (!stack.empty()) return (SAXParser) stack.pop(); try {/*from w w w . java2 s . c o m*/ SAXParser parser = factory.newSAXParser(); XMLReader reader = parser.getXMLReader(); reader.setProperty("http://apache.org/xml/properties/input-buffer-size", new Integer(8192)); return parser; } catch (Exception exc) { System.err.println("Error attempting to initialize SAXParserFactory: " + exc); exc.printStackTrace(); return null; } }
From source file:Main.java
public static void setDefaultNamespaceSchemaLocation(final XMLReader xmlReader, final URL urlToSchema) throws SAXException { xmlReader.setProperty(NO_NAMESPACE_SCHEMA_LOCATION_ID, urlToSchema.toExternalForm()); }
From source file:com.mirth.connect.plugins.datatypes.ncpdp.test.NCPDPTest.java
private static long runTest(String testMessage) throws MessageSerializerException, SAXException, IOException { Stopwatch stopwatch = new Stopwatch(); // Properties properties = new Properties(); String SchemaUrl = "/ncpdp51.xsd"; // properties.put("useStrictParser", "true"); // properties.put("http://java.sun.com/xml/jaxp/properties/schemaSource",SchemaUrl); stopwatch.start();/*from w w w . j a v a 2s . co m*/ NCPDPSerializer serializer = new NCPDPSerializer(null); String xmloutput = serializer.toXML(testMessage); //System.out.println(xmloutput); DocumentSerializer docser = new DocumentSerializer(); Document doc = docser.fromXML(xmloutput); XMLReader xr = XMLReaderFactory.createXMLReader(); NCPDPXMLHandler handler = new NCPDPXMLHandler("\u001E", "\u001D", "\u001C", "51"); xr.setContentHandler(handler); xr.setErrorHandler(handler); xr.setFeature("http://xml.org/sax/features/validation", true); xr.setFeature("http://apache.org/xml/features/validation/schema", true); xr.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true); xr.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema"); xr.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation", SchemaUrl); xr.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", "/ncpdp51.xsd"); xr.parse(new InputSource(new StringReader(xmloutput))); stopwatch.stop(); //System.out.println(docser.serialize(doc)); //handler.getOutput()); //System.out.println(handler.getOutput()); //System.out.println(xmloutput); if (handler.getOutput().toString().replace('\n', '\r').trim() .equals(testMessage.replaceAll("\\r\\n", "\r").trim())) { System.out.println("Test Successful!"); } else { String original = testMessage.replaceAll("\\r\\n", "\r").trim(); String newm = handler.getOutput().toString().replace('\n', '\r').trim(); for (int i = 0; i < original.length(); i++) { if (original.charAt(i) == newm.charAt(i)) { System.out.print(newm.charAt(i)); } else { System.out.println(""); System.out.print("Saw: "); System.out.println(newm.charAt(i)); System.out.print("Expected: "); System.out.print(original.charAt(i)); break; } } System.out.println("Test Failed!"); } return stopwatch.toValue(); }
From source file:com.mirth.connect.model.converters.tests.NCPDPTest.java
private static long runTest(String testMessage) throws SerializerException, SAXException, IOException { Stopwatch stopwatch = new Stopwatch(); Properties properties = new Properties(); String SchemaUrl = "/ncpdp51.xsd"; properties.put("useStrictParser", "true"); properties.put("http://java.sun.com/xml/jaxp/properties/schemaSource", SchemaUrl); stopwatch.start();/*from ww w. j a v a 2s .co m*/ NCPDPSerializer serializer = new NCPDPSerializer(properties); String xmloutput = serializer.toXML(testMessage); //System.out.println(xmloutput); DocumentSerializer docser = new DocumentSerializer(); Document doc = docser.fromXML(xmloutput); XMLReader xr = XMLReaderFactory.createXMLReader(); NCPDPXMLHandler handler = new NCPDPXMLHandler("\u001E", "\u001D", "\u001C", "51"); xr.setContentHandler(handler); xr.setErrorHandler(handler); xr.setFeature("http://xml.org/sax/features/validation", true); xr.setFeature("http://apache.org/xml/features/validation/schema", true); xr.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true); xr.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema"); xr.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation", SchemaUrl); xr.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", "/ncpdp51.xsd"); xr.parse(new InputSource(new StringReader(xmloutput))); stopwatch.stop(); //System.out.println(docser.toXML(doc)); //handler.getOutput()); //System.out.println(handler.getOutput()); //System.out.println(xmloutput); if (handler.getOutput().toString().replace('\n', '\r').trim() .equals(testMessage.replaceAll("\\r\\n", "\r").trim())) { System.out.println("Test Successful!"); } else { String original = testMessage.replaceAll("\\r\\n", "\r").trim(); String newm = handler.getOutput().toString().replace('\n', '\r').trim(); for (int i = 0; i < original.length(); i++) { if (original.charAt(i) == newm.charAt(i)) { System.out.print(newm.charAt(i)); } else { System.out.println(""); System.out.print("Saw: "); System.out.println(newm.charAt(i)); System.out.print("Expected: "); System.out.print(original.charAt(i)); break; } } System.out.println("Test Failed!"); } return stopwatch.toValue(); }
From source file:Validate.java
void parse(String dir, String filename) throws FileNotFoundException, IOException, ParserConfigurationException, SAXException { try {//from w ww. j a v a 2 s.c o m File f = new File(dir, filename); StringBuffer errorBuff = new StringBuffer(); InputSource input = new InputSource(new FileInputStream(f)); // Set systemID so parser can find the dtd with a relative URL in the source document. input.setSystemId(f.toString()); SAXParserFactory spfact = SAXParserFactory.newInstance(); spfact.setValidating(true); spfact.setNamespaceAware(true); SAXParser parser = spfact.newSAXParser(); XMLReader reader = parser.getXMLReader(); //Instantiate inner-class error and lexical handler. Handler handler = new Handler(filename, errorBuff); reader.setProperty("http://xml.org/sax/properties/lexical-handler", handler); parser.parse(input, handler); if (handler.containsDTD && !handler.errorOrWarning) // valid { buff.append("VALID " + filename + "\n"); numValidFiles++; } else if (handler.containsDTD) // not valid { buff.append("NOT VALID " + filename + "\n"); buff.append(errorBuff.toString()); numInvalidFiles++; } else // no DOCTYPE to use for validation { buff.append("NO DOCTYPE DECLARATION " + filename + "\n"); numFilesMissingDoctype++; } } catch (Exception e) // Serious problem! { buff.append("NOT WELL-FORMED " + filename + ". " + e.getMessage() + "\n"); numMalformedFiles++; } finally { numXMLFiles++; } }
From source file:DocumentTracer.java
/** Main. */ public static void main(String[] argv) throws Exception { // is there anything to do? if (argv.length == 0) { printUsage();//from www . j av a 2 s . c o m System.exit(1); } // variables DocumentTracer tracer = new DocumentTracer(); PrintWriter out = new PrintWriter(System.out); XMLReader parser = null; boolean namespaces = DEFAULT_NAMESPACES; boolean namespacePrefixes = DEFAULT_NAMESPACE_PREFIXES; boolean validation = DEFAULT_VALIDATION; boolean externalDTD = DEFAULT_LOAD_EXTERNAL_DTD; boolean schemaValidation = DEFAULT_SCHEMA_VALIDATION; boolean schemaFullChecking = DEFAULT_SCHEMA_FULL_CHECKING; boolean honourAllSchemaLocations = DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS; boolean validateAnnotations = DEFAULT_VALIDATE_ANNOTATIONS; boolean dynamicValidation = DEFAULT_DYNAMIC_VALIDATION; boolean xincludeProcessing = DEFAULT_XINCLUDE; boolean xincludeFixupBaseURIs = DEFAULT_XINCLUDE_FIXUP_BASE_URIS; boolean xincludeFixupLanguage = DEFAULT_XINCLUDE_FIXUP_LANGUAGE; // process arguments for (int i = 0; i < argv.length; i++) { String arg = argv[i]; if (arg.startsWith("-")) { String option = arg.substring(1); if (option.equals("p")) { // get parser name if (++i == argv.length) { System.err.println("error: Missing argument to -p option."); } String parserName = argv[i]; // create parser try { parser = XMLReaderFactory.createXMLReader(parserName); } catch (Exception e) { try { Parser sax1Parser = ParserFactory.makeParser(parserName); parser = new ParserAdapter(sax1Parser); System.err.println("warning: Features and properties not supported on SAX1 parsers."); } catch (Exception ex) { parser = null; System.err.println("error: Unable to instantiate parser (" + parserName + ")"); } } continue; } if (option.equalsIgnoreCase("n")) { namespaces = option.equals("n"); continue; } if (option.equalsIgnoreCase("np")) { namespacePrefixes = option.equals("np"); continue; } if (option.equalsIgnoreCase("v")) { validation = option.equals("v"); continue; } if (option.equalsIgnoreCase("xd")) { externalDTD = option.equals("xd"); continue; } if (option.equalsIgnoreCase("s")) { schemaValidation = option.equals("s"); continue; } if (option.equalsIgnoreCase("f")) { schemaFullChecking = option.equals("f"); continue; } if (option.equalsIgnoreCase("hs")) { honourAllSchemaLocations = option.equals("hs"); continue; } if (option.equalsIgnoreCase("va")) { validateAnnotations = option.equals("va"); continue; } if (option.equalsIgnoreCase("dv")) { dynamicValidation = option.equals("dv"); continue; } if (option.equalsIgnoreCase("xi")) { xincludeProcessing = option.equals("xi"); continue; } if (option.equalsIgnoreCase("xb")) { xincludeFixupBaseURIs = option.equals("xb"); continue; } if (option.equalsIgnoreCase("xl")) { xincludeFixupLanguage = option.equals("xl"); continue; } if (option.equals("h")) { printUsage(); continue; } } // use default parser? if (parser == null) { // create parser try { parser = XMLReaderFactory.createXMLReader(DEFAULT_PARSER_NAME); } catch (Exception e) { System.err.println("error: Unable to instantiate parser (" + DEFAULT_PARSER_NAME + ")"); continue; } } // set parser features try { parser.setFeature(NAMESPACES_FEATURE_ID, namespaces); } catch (SAXException e) { System.err.println("warning: Parser does not support feature (" + NAMESPACES_FEATURE_ID + ")"); } try { parser.setFeature(NAMESPACE_PREFIXES_FEATURE_ID, namespacePrefixes); } catch (SAXException e) { System.err.println( "warning: Parser does not support feature (" + NAMESPACE_PREFIXES_FEATURE_ID + ")"); } try { parser.setFeature(VALIDATION_FEATURE_ID, validation); } catch (SAXException e) { System.err.println("warning: Parser does not support feature (" + VALIDATION_FEATURE_ID + ")"); } try { parser.setFeature(LOAD_EXTERNAL_DTD_FEATURE_ID, externalDTD); } catch (SAXNotRecognizedException e) { System.err.println( "warning: Parser does not recognize feature (" + LOAD_EXTERNAL_DTD_FEATURE_ID + ")"); } catch (SAXNotSupportedException e) { System.err .println("warning: Parser does not support feature (" + LOAD_EXTERNAL_DTD_FEATURE_ID + ")"); } try { parser.setFeature(SCHEMA_VALIDATION_FEATURE_ID, schemaValidation); } catch (SAXNotRecognizedException e) { System.err.println( "warning: Parser does not recognize feature (" + SCHEMA_VALIDATION_FEATURE_ID + ")"); } catch (SAXNotSupportedException e) { System.err .println("warning: Parser does not support feature (" + SCHEMA_VALIDATION_FEATURE_ID + ")"); } try { parser.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking); } catch (SAXNotRecognizedException e) { System.err.println( "warning: Parser does not recognize feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println( "warning: Parser does not support feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")"); } try { parser.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations); } catch (SAXNotRecognizedException e) { System.err.println( "warning: Parser does not recognize feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println( "warning: Parser does not support feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")"); } try { parser.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations); } catch (SAXNotRecognizedException e) { System.err.println("warning: Parser does not recognize feature (" + VALIDATE_ANNOTATIONS_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println("warning: Parser does not support feature (" + VALIDATE_ANNOTATIONS_ID + ")"); } try { parser.setFeature(DYNAMIC_VALIDATION_FEATURE_ID, dynamicValidation); } catch (SAXNotRecognizedException e) { System.err.println( "warning: Parser does not recognize feature (" + DYNAMIC_VALIDATION_FEATURE_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println( "warning: Parser does not support feature (" + DYNAMIC_VALIDATION_FEATURE_ID + ")"); } try { parser.setFeature(XINCLUDE_FEATURE_ID, xincludeProcessing); } catch (SAXNotRecognizedException e) { System.err.println("warning: Parser does not recognize feature (" + XINCLUDE_FEATURE_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println("warning: Parser does not support feature (" + XINCLUDE_FEATURE_ID + ")"); } try { parser.setFeature(XINCLUDE_FIXUP_BASE_URIS_FEATURE_ID, xincludeFixupBaseURIs); } catch (SAXNotRecognizedException e) { System.err.println( "warning: Parser does not recognize feature (" + XINCLUDE_FIXUP_BASE_URIS_FEATURE_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println( "warning: Parser does not support feature (" + XINCLUDE_FIXUP_BASE_URIS_FEATURE_ID + ")"); } try { parser.setFeature(XINCLUDE_FIXUP_LANGUAGE_FEATURE_ID, xincludeFixupLanguage); } catch (SAXNotRecognizedException e) { System.err.println( "warning: Parser does not recognize feature (" + XINCLUDE_FIXUP_LANGUAGE_FEATURE_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println( "warning: Parser does not support feature (" + XINCLUDE_FIXUP_LANGUAGE_FEATURE_ID + ")"); } // set handlers parser.setDTDHandler(tracer); parser.setErrorHandler(tracer); if (parser instanceof XMLReader) { parser.setContentHandler(tracer); try { parser.setProperty("http://xml.org/sax/properties/declaration-handler", tracer); } catch (SAXException e) { e.printStackTrace(System.err); } try { parser.setProperty("http://xml.org/sax/properties/lexical-handler", tracer); } catch (SAXException e) { e.printStackTrace(System.err); } } else { ((Parser) parser).setDocumentHandler(tracer); } // parse file try { parser.parse(arg); } catch (SAXParseException e) { // ignore } catch (Exception e) { System.err.println("error: Parse error occurred - " + e.getMessage()); if (e instanceof SAXException) { Exception nested = ((SAXException) e).getException(); if (nested != null) { e = nested; } } e.printStackTrace(System.err); } } }
From source file:eionet.gdem.validation.ValidationService.java
/** * Set the noNamespaceSchemaLocation property. * * @param reader XMLReader./*from ww w. ja v a2 s . c om*/ * @param schema XML Schema URL. * @throws SAXNotRecognizedException * @throws SAXNotSupportedException */ private void setNoNamespaceSchemaProperty(XMLReader reader, String schema) throws SAXNotRecognizedException, SAXNotSupportedException { setLocalSchemaUrl(schema); reader.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation", getValidatedSchema()); }
From source file:ee.ria.xroad.proxy.serverproxy.MetadataServiceHandlerImpl.java
/** * reads a WSDL from input stream, modifies it and returns input stream to the result * @param wsdl//from w w w. j av a 2 s . co m * @return */ private InputStream modifyWsdl(InputStream wsdl) { try { TransformerHandler serializer = TRANSFORMER_FACTORY.newTransformerHandler(); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); serializer.setResult(result); OverwriteAttributeFilter filter = getModifyWsdlFilter(); filter.setContentHandler(serializer); XMLReader xmlreader = XMLReaderFactory.createXMLReader(); xmlreader.setFeature("http://xml.org/sax/features/namespace-prefixes", true); xmlreader.setProperty("http://xml.org/sax/properties/lexical-handler", new CommentsHandler(serializer)); xmlreader.setContentHandler(filter); // parse XML, filter it, put end result to a String xmlreader.parse(new InputSource(wsdl)); String resultString = writer.toString(); log.debug("result of WSDL cleanup: {}", resultString); // offer InputStream into processed String return new ByteArrayInputStream(resultString.getBytes(StandardCharsets.UTF_8)); } catch (IOException | SAXException | TransformerConfigurationException e) { throw new RuntimeException(e); } }