List of usage examples for org.xml.sax.helpers XMLReaderFactory createXMLReader
public static XMLReader createXMLReader(String className) throws SAXException
From source file:Main.java
public static void main(String[] args) throws Exception { String parserClass = "org.apache.xerces.parsers.SAXParser"; String validationFeature = "http://xml.org/sax/features/validation"; String schemaFeature = "http://apache.org/xml/features/validation/schema"; String x = args[0];/* ww w.j a v a 2 s.c o m*/ XMLReader r = XMLReaderFactory.createXMLReader(parserClass); r.setFeature(validationFeature, true); r.setFeature(schemaFeature, true); r.setErrorHandler(new MyErrorHandler()); r.parse(x); }
From source file:com.semsaas.jsonxml.tools.JsonXpath.java
public static void main(String[] args) { /*/*from w w w . j a va 2 s . c o m*/ * Process options */ LinkedList<String> files = new LinkedList<String>(); LinkedList<String> expr = new LinkedList<String>(); boolean help = false; String activeOption = null; String error = null; for (int i = 0; i < args.length && error == null && !help; i++) { if (activeOption != null) { if (activeOption.equals("-e")) { expr.push(args[i]); } else if (activeOption.equals("-h")) { help = true; } else { error = "Unknown option " + activeOption; } activeOption = null; } else { if (args[i].startsWith("-")) { activeOption = args[i]; } else { files.push(args[i]); } } } if (error != null) { System.err.println(error); showHelp(); } else if (help) { showHelp(); } else { try { TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); for (String f : files) { System.out.println("*** " + f + " ***"); try { // Create a JSON XML reader XMLReader reader = XMLReaderFactory.createXMLReader("com.semsaas.jsonxml.JsonXMLReader"); // Prepare a reader with the JSON file as input InputStreamReader stringReader = new InputStreamReader(new FileInputStream(f)); SAXSource saxSource = new SAXSource(reader, new InputSource(stringReader)); // Prepare a DOMResult which will hold the DOM of the xjson DOMResult domResult = new DOMResult(); // Run SAX processing through a transformer // (This could be done more simply, but we have here the opportunity to pass our xjson through // an XSLT and get a legacy XML output ;) ) transformer.transform(saxSource, domResult); Node dom = domResult.getNode(); XPathFactory xpathFactory = XPathFactory.newInstance(); for (String x : expr) { try { XPath xpath = xpathFactory.newXPath(); xpath.setNamespaceContext(new NamespaceContext() { public Iterator getPrefixes(String namespaceURI) { return null; } public String getPrefix(String namespaceURI) { return null; } public String getNamespaceURI(String prefix) { if (prefix == null) { return XJSON.XMLNS; } else if ("j".equals(prefix)) { return XJSON.XMLNS; } else { return null; } } }); NodeList nl = (NodeList) xpath.evaluate(x, dom, XPathConstants.NODESET); System.out.println("-- Found " + nl.getLength() + " nodes for xpath '" + x + "' in file '" + f + "'"); for (int i = 0; i < nl.getLength(); i++) { System.out.println(" +(" + i + ")+ "); XMLJsonGenerator handler = new XMLJsonGenerator(); StringWriter buffer = new StringWriter(); handler.setOutputWriter(buffer); SAXResult result = new SAXResult(handler); transformer.transform(new DOMSource(nl.item(i)), result); System.out.println(buffer.toString()); } } catch (XPathExpressionException e) { System.err.println("-- Error evaluating '" + x + "' on file '" + f + "'"); e.printStackTrace(); } catch (TransformerException e) { System.err.println("-- Error evaluating '" + x + "' on file '" + f + "'"); e.printStackTrace(); } } } catch (FileNotFoundException e) { System.err.println("File '" + f + "' was not found"); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } } } catch (TransformerConfigurationException e) { e.printStackTrace(); } } }
From source file:Main.java
/** This will create an XML read that will set the parser parameters that * are necessary for parsing an email XML. It will also set which schema * to validate against./*from w w w.j a va 2 s. co m*/ */ public static XMLReader createXmlReader() throws SAXException { final XMLReader xmlReader = XMLReaderFactory.createXMLReader(DEFAULT_PARSER_NAME); return xmlReader; }
From source file:com.adamrosenfield.wordswithcrosses.net.derstandard.DerStandardParser.java
private void parse(InputSource input, ContentHandler handler) throws SAXException, IOException { XMLReader xmlReader = XMLReaderFactory.createXMLReader("org.ccil.cowan.tagsoup.Parser"); xmlReader.setContentHandler(handler); xmlReader.parse(input);/* w w w . jav a2s .c o m*/ }
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();/* ww w . ja va 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:info.magnolia.importexport.DataTransporterTest.java
@Test public void testParseAndFormat() throws Exception { File inputFile = new File(getClass().getResource("/test-formatted-input.xml").getFile()); File outputFile = File.createTempFile("export-test-", ".xml"); OutputStream outputStream = new FileOutputStream(outputFile); XMLReader reader = XMLReaderFactory.createXMLReader(org.apache.xerces.parsers.SAXParser.class.getName()); DataTransporter.readFormatted(reader, inputFile, outputStream); IOUtils.closeQuietly(outputStream);//from w ww .j ava2 s.com Reader expectedReader = new InputStreamReader( getClass().getResourceAsStream("/test-formatted-expected.xml")); Reader actualReader = new FileReader(outputFile); DetailedDiff xmlDiff = new DetailedDiff(new Diff(expectedReader, actualReader)); IOUtils.closeQuietly(expectedReader); IOUtils.closeQuietly(actualReader); outputFile.delete(); final StringBuilder diffLog = new StringBuilder(); for (Iterator iter = xmlDiff.getAllDifferences().iterator(); iter.hasNext();) { Difference difference = (Difference) iter.next(); diffLog.append("expected> ").append(difference.getControlNodeDetail().getValue()).append("\n"); diffLog.append("actual > ").append(difference.getTestNodeDetail().getValue()).append("\n"); } assertTrue("Document is not formatted as expected:\n" + diffLog.toString(), xmlDiff.identical()); }
From source file:info.magnolia.importexport.filters.MagnoliaV2FilterTest.java
/** * Test bogus sv:value creation while replacing MetaData jcr:primary block See * http://jira.magnolia-cms.com/browse/MAGNOLIA-2653 for details. * @throws Exception/*from w w w.ja v a 2 s. c om*/ */ @Test public void testBogusMetaElement() throws Exception { final String inputResourcePath = "/test-v2-filter.xml"; final InputStream input = getClass().getResourceAsStream(inputResourcePath); assertNotNull("Can't open stream to resource " + inputResourcePath, input); File outputFile = File.createTempFile("v2filter-out-", ".xml"); OutputStream os = new FileOutputStream(outputFile); // simulate DataTransporter Formatting OutputFormat outputFormat = new OutputFormat(); outputFormat.setPreserveSpace(false); // this is ok, doesn't affect text nodes?? outputFormat.setIndenting(true); outputFormat.setIndent(2 /* INDENT_VALUE */); outputFormat.setLineWidth(120); // need to be set after setIndenting()! XMLSerializer xmlSerializer = new XMLSerializer(os, outputFormat); // XMLReader inputXmlReader = // XMLReaderFactory.createXMLReader(org.apache.xerces.parsers.SAXParser.class.getName()); XMLReader v2Reader = XMLReaderFactory.createXMLReader(org.apache.xerces.parsers.SAXParser.class.getName()); MagnoliaV2Filter v2Filter = new MagnoliaV2Filter(v2Reader); v2Filter.setContentHandler(xmlSerializer); v2Filter.parse(new InputSource(input)); IOUtils.closeQuietly(input); IOUtils.closeQuietly(os); // XXX: Fixme - UTF-8! final InputStream expected = getClass().getResourceAsStream(inputResourcePath); assertNotNull("Can't open stream to resource " + inputResourcePath, expected); Reader expectedReader = new InputStreamReader(expected); Reader actualReader = new FileReader(outputFile); DetailedDiff xmlDiff = new DetailedDiff(new Diff(expectedReader, actualReader)); IOUtils.closeQuietly(expectedReader); IOUtils.closeQuietly(actualReader); for (Iterator iter = xmlDiff.getAllDifferences().iterator(); iter.hasNext();) { Difference d = (Difference) iter.next(); log.warn(d.getControlNodeDetail().getXpathLocation() + " expected: '" + d.getControlNodeDetail().getValue() + "'"); log.warn(d.getTestNodeDetail().getXpathLocation() + " actual: '" + d.getTestNodeDetail().getValue() + "'"); } assertTrue("Document " + outputFile.getAbsolutePath() + " is not formatted as expected", xmlDiff.identical()); outputFile.delete(); // Delete working file on success (keep for diagnostics on error ) }
From source file:Counter.java
/** Main program entry point. */ public static void main(String argv[]) { // is there anything to do? if (argv.length == 0) { printUsage();/*from w ww.ja v a 2 s .co m*/ System.exit(1); } // variables Counter counter = new Counter(); PrintWriter out = new PrintWriter(System.out); XMLReader parser = null; int repetition = DEFAULT_REPETITION; boolean namespaces = DEFAULT_NAMESPACES; boolean namespacePrefixes = DEFAULT_NAMESPACE_PREFIXES; boolean validation = DEFAULT_VALIDATION; 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; boolean memoryUsage = DEFAULT_MEMORY_USAGE; boolean tagginess = DEFAULT_TAGGINESS; // 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."); 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 + ")"); } } continue; } if (option.equals("x")) { if (++i == argv.length) { System.err.println("error: Missing argument to -x option."); continue; } String number = argv[i]; try { int value = Integer.parseInt(number); if (value < 1) { System.err.println("error: Repetition must be at least 1."); continue; } repetition = value; } catch (NumberFormatException e) { System.err.println("error: invalid number (" + number + ")."); } 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("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.equalsIgnoreCase("m")) { memoryUsage = option.equals("m"); continue; } if (option.equalsIgnoreCase("t")) { tagginess = option.equals("t"); continue; } if (option.equals("-rem")) { if (++i == argv.length) { System.err.println("error: Missing argument to -# option."); continue; } System.out.print("# "); System.out.println(argv[i]); 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 + ")"); 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(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 + ")"); } // parse file parser.setContentHandler(counter); parser.setErrorHandler(counter); try { long timeBefore = System.currentTimeMillis(); long memoryBefore = Runtime.getRuntime().freeMemory(); for (int j = 0; j < repetition; j++) { parser.parse(arg); } long memoryAfter = Runtime.getRuntime().freeMemory(); long timeAfter = System.currentTimeMillis(); long time = timeAfter - timeBefore; long memory = memoryUsage ? memoryBefore - memoryAfter : Long.MIN_VALUE; counter.printResults(out, arg, time, memory, tagginess, repetition); } catch (SAXParseException e) { // ignore } catch (Exception e) { System.err.println("error: Parse error occurred - " + e.getMessage()); Exception se = e; if (e instanceof SAXException) { se = ((SAXException) e).getException(); } if (se != null) se.printStackTrace(System.err); else e.printStackTrace(System.err); } } }
From source file:edu.wisc.my.portlets.dmp.tools.XmlMenuPublisher.java
/** * Publishes all the menus in the XML specified by the URL. * /*from w ww . j a va2s . c om*/ * @param xmlSourceUrl URL to the menu XML. */ public void publishMenus(URL xmlSourceUrl) { LOG.info("Publishing menus from: " + xmlSourceUrl); try { //The XMLReader will read in the XML document final XMLReader reader = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser"); try { reader.setFeature("http://apache.org/xml/features/validation/dynamic", true); reader.setFeature("http://apache.org/xml/features/validation/schema", true); final URL menuSchema = this.getClass().getResource("/menu.xsd"); if (menuSchema == null) { throw new MissingResourceException("Could not load menu schema. '/menu.xsd'", this.getClass().getName(), "/menu.xsd"); } reader.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation", menuSchema.toString()); } catch (SAXNotRecognizedException snre) { LOG.warn("Could not enable XSD validation", snre); } catch (SAXNotSupportedException xnse) { LOG.warn("Could not enable XSD validation", xnse); } final MenuItemGeneratingHandler handler = new MenuItemGeneratingHandler(); reader.setContentHandler(handler); reader.parse(new InputSource(xmlSourceUrl.openStream())); final Map menus = handler.getMenus(); final BeanFactory factory = this.getFactory(); final MenuDao dao = (MenuDao) factory.getBean("menuDao", MenuDao.class); for (final Iterator nameItr = menus.entrySet().iterator(); nameItr.hasNext();) { final Map.Entry entry = (Map.Entry) nameItr.next(); final String menuName = (String) entry.getKey(); final MenuItem rootItem = (MenuItem) entry.getValue(); LOG.info("Publishing menu='" + menuName + "' item='" + rootItem + "'"); dao.storeMenu(menuName, rootItem); } LOG.info("Published menus from: " + xmlSourceUrl); } catch (IOException ioe) { LOG.error("Error publishing menus", ioe); } catch (SAXException saxe) { LOG.error("Error publishing menus", saxe); } }
From source file:SAXTreeViewer.java
/** * <p>This handles building the Swing UI tree.</p> * * @param treeModel Swing component to build upon. * @param base tree node to build on.//ww w . j a va2 s .co m * @param xmlURI URI to build XML document from. * @throws <code>IOException</code> - when reading the XML URI fails. * @throws <code>SAXException</code> - when errors in parsing occur. */ public void buildTree(DefaultTreeModel treeModel, DefaultMutableTreeNode base, String xmlURI) throws IOException, SAXException { // Create instances needed for parsing XMLReader reader = XMLReaderFactory.createXMLReader(vendorParserClass); ContentHandler jTreeContentHandler = new JTreeContentHandler(treeModel, base); ErrorHandler jTreeErrorHandler = new JTreeErrorHandler(); // Register content handler reader.setContentHandler(jTreeContentHandler); // Register error handler reader.setErrorHandler(jTreeErrorHandler); // Parse InputSource inputSource = new InputSource(xmlURI); reader.parse(inputSource); }