List of usage examples for javax.xml.parsers SAXParser getXMLReader
public abstract org.xml.sax.XMLReader getXMLReader() throws SAXException;
From source file:Util.java
/** * Creates an XMLReader with default feature set. Note that all Cayenne internal XML * parsers should probably use XMLReader obtained via this method for consistency * sake, and can customize feature sets as needed. *//*from ww w . ja v a2s .c o m*/ public static XMLReader createXmlReader() throws SAXException, ParserConfigurationException { SAXParserFactory spf = SAXParserFactory.newInstance(); // Create a JAXP SAXParser SAXParser saxParser = spf.newSAXParser(); // Get the encapsulated SAX XMLReader XMLReader reader = saxParser.getXMLReader(); // set default features reader.setFeature("http://xml.org/sax/features/namespaces", true); return reader; }
From source file:eu.project.ttc.test.unit.TestUtil.java
public static String getTeiTxt(String filename) throws ParserConfigurationException, SAXException, IOException, FileNotFoundException { SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setNamespaceAware(true);//from www . j a v a 2 s . co m spf.setValidating(false); spf.setFeature("http://xml.org/sax/features/namespaces", true); spf.setFeature("http://xml.org/sax/features/validation", false); spf.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false); spf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); SAXParser saxParser = spf.newSAXParser(); XMLReader xmlReader = saxParser.getXMLReader(); TeiToTxtSaxHandler handler = new TeiToTxtSaxHandler(); xmlReader.setContentHandler(handler); xmlReader.parse(new InputSource(TestUtil.getInputStream(filename))); String text = handler.getText(); return text; }
From source file:org.apache.clerezza.commons.rdf.impl.sparql.SparqlResultParser.java
static Object parse(InputStream in) throws IOException { try {/*from ww w .j ava 2 s . c o m*/ SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setNamespaceAware(true); SAXParser saxParser = spf.newSAXParser(); XMLReader xmlReader = saxParser.getXMLReader(); final SparqlsResultsHandler sparqlsResultsHandler = new SparqlsResultsHandler(); xmlReader.setContentHandler(sparqlsResultsHandler); xmlReader.parse(new InputSource(in)); return sparqlsResultsHandler.getResults(); } catch (ParserConfigurationException | SAXException ex) { throw new RuntimeException(ex); } }
From source file:info.unyttig.helladroid.newzbin.NewzBinController.java
/** * Fetches a report from Newzbin based on a given id. * However if the report is already cached, its just fetched from the hashmap. * @param id// ww w .j a v a 2 s .c o m */ public static NewzBinReport getReportInfo(int id) { if (detailedReports.containsKey(id)) return detailedReports.get(id); String url = NBAPIURL + "reportinfo/"; HashMap<String, String> searchOptions = new HashMap<String, String>(); searchOptions.put("id", "" + id); try { HttpResponse response = doPost(url, searchOptions); checkReturnCode(response.getStatusLine().getStatusCode(), false); InputStream is = response.getEntity().getContent(); SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); NewzBinDRHandler handler = new NewzBinDRHandler(); if (reports.containsKey(id)) handler.nbdr = reports.get(id); xr.setContentHandler(handler); xr.parse(new InputSource(is)); detailedReports.put(id, handler.getParsedData()); // Temp ArrayList<NewzBinReportComment> comments = handler.nbdr.getComments(); Log.i(LOG_NAME, "Comments size: " + comments.size()); Iterator<NewzBinReportComment> sd = comments.iterator(); while (sd.hasNext()) { NewzBinReportComment nrc = sd.next(); Log.i(LOG_NAME, nrc.toString()); } return handler.getParsedData(); } catch (ClientProtocolException e) { Log.e(LOG_NAME, "ClientProtocol thrown: ", e); } catch (IOException e) { Log.e(LOG_NAME, "IOException thrown: ", e); } catch (NewzBinPostReturnCodeException e) { Log.e(LOG_NAME, "POST ReturnCode error: " + e.toString()); } catch (ParserConfigurationException e) { Log.e(LOG_NAME, "ParserError thrown: ", e); } catch (SAXException e) { Log.e(LOG_NAME, "SAXError thrown: ", e); } return null; }
From source file:Main.java
public static XMLReader createXmlReader() throws SAXException { try {/*from w ww. ja v a 2 s.c om*/ // use Xerces to ensure XML 1.1 is handled correctly Class<?> clazz = Class.forName("org.apache.xerces.parsers.SAXParser"); //$NON-NLS-1$ return (XMLReader) clazz.newInstance(); } catch (Throwable e) { SAXParser saxParser; try { SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); saxParserFactory.setNamespaceAware(true); saxParser = saxParserFactory.newSAXParser(); } catch (ParserConfigurationException e2) { throw new SAXException(e2); } return saxParser.getXMLReader(); } }
From source file:jproxy.DefaultSamplerCreator.java
/** * Tries parsing to see if content is xml * @param postData String//from ww w. j a v a2 s.c om * @return boolean */ private static boolean isPotentialXml(String postData) { try { SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser saxParser = spf.newSAXParser(); XMLReader xmlReader = saxParser.getXMLReader(); ErrorDetectionHandler detectionHandler = new ErrorDetectionHandler(); xmlReader.setContentHandler(detectionHandler); xmlReader.setErrorHandler(detectionHandler); xmlReader.parse(new InputSource(new StringReader(postData))); return !detectionHandler.isErrorDetected(); } catch (ParserConfigurationException e) { return false; } catch (SAXException e) { return false; } catch (IOException e) { return false; } }
From source file:com.granule.json.utils.XML.java
/** * Method to do the transform from an XML input stream to a JSON stream. * Neither input nor output streams are closed. Closure is left up to the caller. * * @param XMLStream The XML stream to convert to JSON * @param JSONStream The stream to write out JSON to. The contents written to this stream are always in UTF-8 format. * @param verbose Flag to denote whether or not to render the JSON text in verbose (indented easy to read), or compact (not so easy to read, but smaller), format. * * @throws SAXException Thrown if a parse error occurs. * @throws IOException Thrown if an IO error occurs. */// w w w . java2 s .c om public static void toJson(InputStream XMLStream, OutputStream JSONStream, boolean verbose) throws SAXException, IOException { if (logger.isLoggable(Level.FINER)) { logger.entering(className, "toJson(InputStream, OutputStream)"); } if (XMLStream == null) { throw new NullPointerException("XMLStream cannot be null"); } else if (JSONStream == null) { throw new NullPointerException("JSONStream cannot be null"); } else { if (logger.isLoggable(Level.FINEST)) { logger.logp(Level.FINEST, className, "transform", "Fetching a SAX parser for use with JSONSAXHandler"); } try { /** * Get a parser. */ SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); SAXParser sParser = factory.newSAXParser(); XMLReader parser = sParser.getXMLReader(); JSONSAXHandler jsonHandler = new JSONSAXHandler(JSONStream, verbose); parser.setContentHandler(jsonHandler); parser.setErrorHandler(jsonHandler); InputSource source = new InputSource(new BufferedInputStream(XMLStream)); if (logger.isLoggable(Level.FINEST)) { logger.logp(Level.FINEST, className, "transform", "Parsing the XML content to JSON"); } /** * Parse it. */ source.setEncoding("UTF-8"); parser.parse(source); jsonHandler.flushBuffer(); } catch (javax.xml.parsers.ParserConfigurationException pce) { throw new SAXException("Could not get a parser: " + pce.toString()); } } if (logger.isLoggable(Level.FINER)) { logger.exiting(className, "toJson(InputStream, OutputStream)"); } }
From source file:Examples.java
/** * Show the Transformer as a simple XMLFilter. This is pretty similar * to exampleXMLReader, except that here the parent XMLReader is created * by the caller, instead of automatically within the XMLFilter. This * gives the caller more direct control over the parent reader. */// ww w .ja v a2s .com public static void exampleXMLFilter(String sourceID, String xslID) throws TransformerException, TransformerConfigurationException, SAXException, IOException // , ParserConfigurationException { TransformerFactory tfactory = TransformerFactory.newInstance(); XMLReader reader = null; // Use JAXP1.1 ( if possible ) try { javax.xml.parsers.SAXParserFactory factory = javax.xml.parsers.SAXParserFactory.newInstance(); factory.setNamespaceAware(true); javax.xml.parsers.SAXParser jaxpParser = factory.newSAXParser(); reader = jaxpParser.getXMLReader(); } catch (javax.xml.parsers.ParserConfigurationException ex) { throw new org.xml.sax.SAXException(ex); } catch (javax.xml.parsers.FactoryConfigurationError ex1) { throw new org.xml.sax.SAXException(ex1.toString()); } catch (NoSuchMethodError ex2) { } if (reader == null) reader = XMLReaderFactory.createXMLReader(); // The transformer will use a SAX parser as it's reader. reader.setContentHandler(new ExampleContentHandler()); try { reader.setFeature("http://xml.org/sax/features/namespace-prefixes", true); reader.setFeature("http://apache.org/xml/features/validation/dynamic", true); } catch (SAXException se) { // What can we do? // TODO: User diagnostics. } XMLFilter filter = ((SAXTransformerFactory) tfactory).newXMLFilter(new StreamSource(xslID)); filter.setParent(reader); // 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(sourceID)); }
From source file:Examples.java
/** * Show the Transformer using SAX events in and SAX events out. *///from ww w . ja v a2 s .co m public static void exampleContentHandlerToContentHandler(String sourceID, String xslID) throws TransformerException, TransformerConfigurationException, SAXException, IOException { TransformerFactory tfactory = TransformerFactory.newInstance(); // Does this factory support SAX features? if (tfactory.getFeature(SAXSource.FEATURE)) { // If so, we can safely cast. SAXTransformerFactory stfactory = ((SAXTransformerFactory) tfactory); // A TransformerHandler is a ContentHandler that will listen for // SAX events, and transform them to the result. TransformerHandler handler = stfactory.newTransformerHandler(new StreamSource(xslID)); // Set the result handling to be a serialization to System.out. Result result = new SAXResult(new ExampleContentHandler()); handler.setResult(result); // Create a reader, and set it's content handler to be the TransformerHandler. XMLReader reader = null; // Use JAXP1.1 ( if possible ) try { javax.xml.parsers.SAXParserFactory factory = javax.xml.parsers.SAXParserFactory.newInstance(); factory.setNamespaceAware(true); javax.xml.parsers.SAXParser jaxpParser = factory.newSAXParser(); reader = jaxpParser.getXMLReader(); } catch (javax.xml.parsers.ParserConfigurationException ex) { throw new org.xml.sax.SAXException(ex); } catch (javax.xml.parsers.FactoryConfigurationError ex1) { throw new org.xml.sax.SAXException(ex1.toString()); } catch (NoSuchMethodError ex2) { } if (reader == null) reader = XMLReaderFactory.createXMLReader(); reader.setContentHandler(handler); // It's a good idea for the parser to send lexical events. // The TransformerHandler is also a LexicalHandler. reader.setProperty("http://xml.org/sax/properties/lexical-handler", handler); // Parse the source XML, and send the parse events to the TransformerHandler. reader.parse(sourceID); } else { System.out.println( "Can't do exampleContentHandlerToContentHandler because tfactory is not a SAXTransformerFactory"); } }
From source file:Examples.java
/** * Show the Transformer using SAX events in and DOM nodes out. *//*from w w w .jav a 2 s . c om*/ public static void exampleContentHandler2DOM(String sourceID, String xslID) throws TransformerException, TransformerConfigurationException, SAXException, IOException, ParserConfigurationException { TransformerFactory tfactory = TransformerFactory.newInstance(); // Make sure the transformer factory we obtained supports both // DOM and SAX. if (tfactory.getFeature(SAXSource.FEATURE) && tfactory.getFeature(DOMSource.FEATURE)) { // We can now safely cast to a SAXTransformerFactory. SAXTransformerFactory sfactory = (SAXTransformerFactory) tfactory; // Create an Document node as the root for the output. DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = dfactory.newDocumentBuilder(); org.w3c.dom.Document outNode = docBuilder.newDocument(); // Create a ContentHandler that can liston to SAX events // and transform the output to DOM nodes. TransformerHandler handler = sfactory.newTransformerHandler(new StreamSource(xslID)); handler.setResult(new DOMResult(outNode)); // Create a reader and set it's ContentHandler to be the // transformer. XMLReader reader = null; // Use JAXP1.1 ( if possible ) try { javax.xml.parsers.SAXParserFactory factory = javax.xml.parsers.SAXParserFactory.newInstance(); factory.setNamespaceAware(true); javax.xml.parsers.SAXParser jaxpParser = factory.newSAXParser(); reader = jaxpParser.getXMLReader(); } catch (javax.xml.parsers.ParserConfigurationException ex) { throw new org.xml.sax.SAXException(ex); } catch (javax.xml.parsers.FactoryConfigurationError ex1) { throw new org.xml.sax.SAXException(ex1.toString()); } catch (NoSuchMethodError ex2) { } if (reader == null) reader = XMLReaderFactory.createXMLReader(); reader.setContentHandler(handler); reader.setProperty("http://xml.org/sax/properties/lexical-handler", handler); // Send the SAX events from the parser to the transformer, // and thus to the DOM tree. reader.parse(sourceID); // Serialize the node for diagnosis. exampleSerializeNode(outNode); } else { System.out.println( "Can't do exampleContentHandlerToContentHandler because tfactory is not a SAXTransformerFactory"); } }