List of usage examples for javax.xml.parsers SAXParserFactory setNamespaceAware
public void setNamespaceAware(boolean awareness)
From source file:org.apache.clerezza.commons.rdf.impl.sparql.SparqlResultParser.java
static Object parse(InputStream in) throws IOException { try {// w ww. j av a 2 s . com 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:eu.annocultor.utils.XmlUtils.java
/** * //from ww w. j a v a 2 s .c o m * @param fileStream * @param handler * @param validating * @return <code>true</code> on success. * @throws Exception */ public static int parseXmlFileSAX(File sourceFile, ConverterHandler handler, boolean validating) throws Exception { // Create a builder factory SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setValidating(validating); factory.setNamespaceAware(true); InputStream fileStream = new BufferedInputStream(new FileInputStream(sourceFile), 1024 * 1024); if (fileStream == null) { throw new Exception("Null input XML file stream"); } if (handler == null) { throw new Exception("Null XML handler"); } try { // Create the builder and parse the file SAXParser newSAXParser = factory.newSAXParser(); if (newSAXParser == null) { throw new Exception("null SAX parser"); } newSAXParser.parse(fileStream, handler); } catch (Exception e) { System.err.println("\n" + "*****************************************************\n" + "EXCEPTION OCCURRED in file " + sourceFile.getCanonicalPath() + "\n" + "at line " + handler.getDocumentLocator().getLineNumber() + ", column " + handler.getDocumentLocator().getColumnNumber()); e.printStackTrace(); System.err.println("\n" + "TRYING TO CLOSE FILES GRACEFULLY \n" + "*****************************************************\n"); return -1; } return 0; }
From source file:com.haulmont.bali.util.Dom4j.java
public static SAXParser getParser() { SAXParser parser = saxParserHolder.get(); if (parser == null) { SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setValidating(false);/* ww w .ja v a 2s . co m*/ factory.setNamespaceAware(false); try { parser = factory.newSAXParser(); } catch (ParserConfigurationException | SAXException e) { throw new RuntimeException("Unable to create SAX parser", e); } saxParserHolder.set(parser); } return parser; }
From source file:gov.nih.nci.ncicb.tcga.dcc.common.jaxb.JAXBUtil.java
private static SAXSource applyMetaDataNamespaceFilter(final Unmarshaller unmarshaller, final Reader xmlFileReader) throws SAXException, ParserConfigurationException, FileNotFoundException { final SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); // this should not be changed! final XMLReader reader = factory.newSAXParser().getXMLReader(); final XMLFilterImpl xmlFilter = new MetaDataXMLNamespaceFilter(reader); reader.setContentHandler(unmarshaller.getUnmarshallerHandler()); return new SAXSource(xmlFilter, new InputSource(xmlFileReader)); }
From source file:architecture.common.model.factory.ModelTypeFactory.java
private static List<ModelList> parseLegacyXmlFile(List<ModelList> list) throws Exception { ClassLoader cl = Thread.currentThread().getContextClassLoader(); Enumeration<URL> enumeration = cl.getResources(IF_PLUGIN_PATH); SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); XMLReader xmlreader = factory.newSAXParser().getXMLReader(); ImplFactoryParsingHandler handler = new ImplFactoryParsingHandler(); xmlreader.setContentHandler(handler); xmlreader.setDTDHandler(handler);//from w w w . java 2 s .c o m xmlreader.setEntityResolver(handler); xmlreader.setErrorHandler(handler); System.out.println("Model Enum:"); do { if (!enumeration.hasMoreElements()) break; URL url = (URL) enumeration.nextElement(); System.out.println(" - " + url); try { xmlreader.parse(new InputSource(url.openStream())); ModelList factorylist = new ModelList(); factorylist.rank = handler.rank; factorylist.modelTypes.addAll(handler.getModels()); list.add(factorylist); } catch (Exception exception) { } } while (true); return list; }
From source file:Main.java
/** * Creates a SAX parser.// w w w . ja va 2 s . c o m * * <p> * See {@link #parse} for hints on setting an entity resolver. * * @param validate if true, a validating parser is returned * @param namespaceAware if true, a namespace aware parser is returned * * @throws FactoryConfigurationError Application developers should never * need to directly catch errors of this * type. * @throws SAXException if a parser fulfilling given parameters * can not be created * * @return XMLReader configured according to passed parameters */ public static synchronized XMLReader createXMLReader(boolean validate, boolean namespaceAware) throws SAXException { SAXParserFactory factory = saxes[validate ? 0 : 1][namespaceAware ? 0 : 1]; if (factory == null) { try { factory = SAXParserFactory.newInstance(); } catch (FactoryConfigurationError err) { throw err; } factory.setValidating(validate); factory.setNamespaceAware(namespaceAware); saxes[validate ? 0 : 1][namespaceAware ? 0 : 1] = factory; } try { return factory.newSAXParser().getXMLReader(); } catch (ParserConfigurationException ex) { throw new SAXException("Cannot create parser satisfying configuration parameters", ex); // NOI18N } }
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. *//*from w ww . j a va2 s . co m*/ 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. *///from ww w. j a v a 2 s . c o m 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 w w w . j ava2s. 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 .j a va 2 s .c o m*/ 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"); } }