List of usage examples for org.xml.sax XMLReader setErrorHandler
public void setErrorHandler(ErrorHandler handler);
From source file:MyContentHandler.java
static public void main(String[] arg) { SAXParserFactory spf = SAXParserFactory.newInstance(); XMLReader reader = null; try {//from www . j a va2 s. c o m SAXParser parser = spf.newSAXParser(); reader = parser.getXMLReader(); } catch (Exception e) { System.err.println(e); System.exit(1); } reader.setErrorHandler(new MyErrorHandler()); reader.setContentHandler(new MyContentHandler()); try { InputSource is = new InputSource(new StringReader(getXMLData())); reader.parse(is); } catch (SAXException e) { System.exit(1); } catch (IOException e) { System.err.println(e); System.exit(1); } }
From source file:MyContentHandler.java
static public void main(String[] arg) { SAXParserFactory spf = SAXParserFactory.newInstance(); XMLReader reader = null; try {// ww w. j a v a2 s . co m SAXParser parser = spf.newSAXParser(); reader = parser.getXMLReader(); } catch (Exception e) { System.err.println(e); System.exit(1); } reader.setErrorHandler(new MyErrorHandler()); reader.setContentHandler(new MyContentHandler()); try { InputSource is = new InputSource("test.xml"); reader.parse(is); } catch (SAXException e) { System.exit(1); } catch (IOException e) { System.err.println(e); System.exit(1); } }
From source file:SAXCheck.java
static public void main(String[] arg) { String filename = null;/*from w w w. j ava2 s. c om*/ boolean validate = false; if (arg.length == 1) { filename = arg[0]; } else if (arg.length == 2) { if (!arg[0].equals("-v")) usage(); validate = true; filename = arg[1]; } else { usage(); } // Create a new factory to create parsers that will // validate or not, according to the flag setting. SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setValidating(validate); // Create the XMLReader to be used to check for errors. XMLReader reader = null; try { SAXParser parser = spf.newSAXParser(); reader = parser.getXMLReader(); } catch (Exception e) { System.err.println(e); System.exit(1); } // Install an error handler in the reader. reader.setErrorHandler(new MyErrorHandler()); // Use the XMLReader to parse the entire file. try { InputSource is = new InputSource(filename); reader.parse(is); } catch (SAXException e) { System.exit(1); } catch (IOException e) { System.err.println(e); System.exit(1); } }
From source file:TypeInfoWriter.java
/** Main program entry point. */ public static void main(String[] argv) { // is there anything to do? if (argv.length == 0) { printUsage();/*from w w w. j a v a 2 s . c o m*/ System.exit(1); } // variables XMLReader parser = null; Vector schemas = null; Vector instances = null; String schemaLanguage = DEFAULT_SCHEMA_LANGUAGE; boolean schemaFullChecking = DEFAULT_SCHEMA_FULL_CHECKING; boolean honourAllSchemaLocations = DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS; boolean validateAnnotations = DEFAULT_VALIDATE_ANNOTATIONS; boolean generateSyntheticAnnotations = DEFAULT_GENERATE_SYNTHETIC_ANNOTATIONS; // 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("l")) { // get schema language name if (++i == argv.length) { System.err.println("error: Missing argument to -l option."); } else { schemaLanguage = argv[i]; } continue; } if (option.equals("p")) { // get parser name if (++i == argv.length) { System.err.println("error: Missing argument to -p option."); continue; } 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 + ")"); e.printStackTrace(System.err); System.exit(1); } } continue; } if (arg.equals("-a")) { // process -a: schema documents if (schemas == null) { schemas = new Vector(); } while (i + 1 < argv.length && !(arg = argv[i + 1]).startsWith("-")) { schemas.add(arg); ++i; } continue; } if (arg.equals("-i")) { // process -i: instance documents if (instances == null) { instances = new Vector(); } while (i + 1 < argv.length && !(arg = argv[i + 1]).startsWith("-")) { instances.add(arg); ++i; } 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("ga")) { generateSyntheticAnnotations = option.equals("ga"); continue; } if (option.equals("h")) { printUsage(); continue; } System.err.println("error: unknown option (" + option + ")."); 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 + ")"); e.printStackTrace(System.err); System.exit(1); } } try { // Create writer TypeInfoWriter writer = new TypeInfoWriter(); writer.setOutput(System.out, "UTF8"); // Create SchemaFactory and configure SchemaFactory factory = SchemaFactory.newInstance(schemaLanguage); factory.setErrorHandler(writer); try { factory.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking); } catch (SAXNotRecognizedException e) { System.err.println("warning: SchemaFactory does not recognize feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println("warning: SchemaFactory does not support feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")"); } try { factory.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations); } catch (SAXNotRecognizedException e) { System.err.println("warning: SchemaFactory does not recognize feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println( "warning: SchemaFactory does not support feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")"); } try { factory.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations); } catch (SAXNotRecognizedException e) { System.err.println( "warning: SchemaFactory does not recognize feature (" + VALIDATE_ANNOTATIONS_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println( "warning: SchemaFactory does not support feature (" + VALIDATE_ANNOTATIONS_ID + ")"); } try { factory.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations); } catch (SAXNotRecognizedException e) { System.err.println("warning: SchemaFactory does not recognize feature (" + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println("warning: SchemaFactory does not support feature (" + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")"); } // Build Schema from sources Schema schema; if (schemas != null && schemas.size() > 0) { final int length = schemas.size(); StreamSource[] sources = new StreamSource[length]; for (int j = 0; j < length; ++j) { sources[j] = new StreamSource((String) schemas.elementAt(j)); } schema = factory.newSchema(sources); } else { schema = factory.newSchema(); } // Setup validator and parser ValidatorHandler validator = schema.newValidatorHandler(); parser.setContentHandler(validator); if (validator instanceof DTDHandler) { parser.setDTDHandler((DTDHandler) validator); } parser.setErrorHandler(writer); validator.setContentHandler(writer); validator.setErrorHandler(writer); writer.setTypeInfoProvider(validator.getTypeInfoProvider()); try { validator.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking); } catch (SAXNotRecognizedException e) { System.err.println( "warning: Validator does not recognize feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println( "warning: Validator does not support feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")"); } try { validator.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations); } catch (SAXNotRecognizedException e) { System.err.println( "warning: Validator does not recognize feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println( "warning: Validator does not support feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")"); } try { validator.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations); } catch (SAXNotRecognizedException e) { System.err .println("warning: Validator does not recognize feature (" + VALIDATE_ANNOTATIONS_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println("warning: Validator does not support feature (" + VALIDATE_ANNOTATIONS_ID + ")"); } try { validator.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations); } catch (SAXNotRecognizedException e) { System.err.println("warning: Validator does not recognize feature (" + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println( "warning: Validator does not support feature (" + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")"); } // Validate instance documents and print type information if (instances != null && instances.size() > 0) { final int length = instances.size(); for (int j = 0; j < length; ++j) { parser.parse((String) instances.elementAt(j)); } } } 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:Main.java
public static boolean validateWithDTDUsingSAX(String xml) throws Exception { SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setValidating(true);// w ww . ja v a2s . c o m factory.setNamespaceAware(true); SAXParser parser = factory.newSAXParser(); XMLReader reader = parser.getXMLReader(); reader.setErrorHandler(new ErrorHandler() { public void warning(SAXParseException e) throws SAXException { System.out.println("WARNING : " + e.getMessage()); // do nothing } public void error(SAXParseException e) throws SAXException { System.out.println("ERROR : " + e.getMessage()); throw e; } public void fatalError(SAXParseException e) throws SAXException { System.out.println("FATAL : " + e.getMessage()); throw e; } }); reader.parse(new InputSource(xml)); return true; }
From source file:Main.java
/** * Parse the XML data in the given input stream, using the * specified handler object as both the content and error handler. * * @param handler the SAX event handler//from w w w . j ava 2 s.c o m * @param in the input stream containing the XML to be parsed */ public static void parse(DefaultHandler handler, InputStream in) throws IOException, ParserConfigurationException, SAXException { XMLReader xr = _pfactory.newSAXParser().getXMLReader(); xr.setContentHandler(handler); xr.setErrorHandler(handler); xr.parse(new InputSource(in)); }
From source file:com.surveypanel.form.xml.ParserHelper.java
/** * Return a reader to parse content/* w w w .j ava2s . co m*/ * @param path * @return */ protected static FormValuesHandler getReader(InputStream is) { FormValuesHandler formValuesHandler = new FormValuesHandler(); XMLReader parser = null; try { InputStreamReader inputStreamReader = new InputStreamReader(is, "UTF-8"); parser = XMLReaderFactory.createXMLReader(); parser.setContentHandler(formValuesHandler); parser.setErrorHandler(formValuesHandler); InputSource inputSource = new InputSource(inputStreamReader); parser.parse(inputSource); } catch (Exception e) { e.printStackTrace(); } return formValuesHandler; }
From source file:com.mindquarry.desktop.I18N.java
protected static Map<String, String> initTranslationMap(String fileBase, String fileSuffix) { try {//w w w .j a va 2 s. co m SAXParserFactory parserFactory = SAXParserFactory.newInstance(); parserFactory.setValidating(false); SAXParser parser = parserFactory.newSAXParser(); XMLReader reader = parser.getXMLReader(); TranslationMessageParser translationParser = new TranslationMessageParser(); reader.setContentHandler(translationParser); reader.setErrorHandler(translationParser); // TODO: use "xx_YY" if available, use "xx" otherwise: String transFile = fileBase + Locale.getDefault().getLanguage() + fileSuffix; InputStream is = I18N.class.getResourceAsStream(transFile); if (is == null) { // no translation available for this language log.debug("No translation file available for language: " + Locale.getDefault().getLanguage()); return new HashMap<String, String>(); } log.debug("Loading translation file " + transFile + " from JAR"); reader.parse(new InputSource(is)); return translationParser.getMap(); } catch (Exception e) { throw new RuntimeException(e.toString(), e); } }
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();/* w ww. j av a2 s. c om*/ 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 www .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(); }