List of usage examples for javax.xml.parsers SAXParserFactory newSAXParser
public abstract SAXParser newSAXParser() throws ParserConfigurationException, SAXException;
From source file:jproxy.DefaultSamplerCreator.java
/** * Tries parsing to see if content is xml * @param postData String/*from w w w . j av a2s. c o m*/ * @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:Main.java
/** * Creates a SAX parser./*from w w w .ja v a2s . c om*/ * * <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:Main.java
/** * Constructs a validating secure SAX Parser. * * @param schemaStream the schema to validate the XML against * @return a SAX Parser/*from w w w .j av a2 s . c o m*/ * @throws ParserConfigurationException is thrown if there is a parser * configuration exception * @throws SAXNotRecognizedException thrown if there is an unrecognized * feature * @throws SAXNotSupportedException thrown if there is a non-supported * feature * @throws SAXException is thrown if there is a SAXException */ public static SAXParser buildSecureSaxParser(InputStream schemaStream) throws ParserConfigurationException, SAXNotRecognizedException, SAXNotSupportedException, SAXException { final SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(true); factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); factory.setFeature("http://xml.org/sax/features/external-general-entities", false); //setting the following unfortunately breaks reading the old suppression files (version 1). //factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); final SAXParser saxParser = factory.newSAXParser(); saxParser.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA); saxParser.setProperty(JAXP_SCHEMA_SOURCE, schemaStream); return saxParser; }
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 w w w . j a v a 2s . c o 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:net.sf.jasperreports.renderers.util.XmlDataSniffer.java
public static XmlSniffResult sniffXml(byte[] data) { SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setValidating(false);/* w w w . j ava2s . co m*/ factory.setNamespaceAware(false); factory.setXIncludeAware(false); setParserFeature(factory, FEATURE_EXTERNAL_GENERAL_ENTITIES, false); setParserFeature(factory, FEATURE_EXTERNAL_PARAMETER_ENTITIES, false); setParserFeature(factory, FEATURE_LOAD_EXTERNAL_DTD, false); SaxHandler handler = new SaxHandler(); ByteArrayInputStream bais = new ByteArrayInputStream(data); try { SAXParser saxParser = factory.newSAXParser(); saxParser.parse(bais, handler); return new XmlSniffResult(handler.rootElementName); } catch (ValidXmlSAXException e) { return new XmlSniffResult(handler.rootElementName); } catch (SAXException | ParserConfigurationException | IOException e) { return null; } }
From source file:eu.annocultor.utils.XmlUtils.java
/** * //w w w . j av a 2 s . co 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.connectsdk.core.upnp.Device.java
public static Device createInstanceFromXML(String url, String searchTarget) { Device newDevice = null;// ww w . j a v a 2 s . c om try { newDevice = new Device(url, searchTarget); } catch (IOException e) { return null; } final Device device = newDevice; DefaultHandler dh = new DefaultHandler() { String currentValue = null; Icon currentIcon; Service currentService; @Override public void characters(char[] ch, int start, int length) throws SAXException { currentValue = new String(ch, start, length); } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (Icon.TAG.equals(qName)) { currentIcon = new Icon(); } else if (Service.TAG.equals(qName)) { currentService = new Service(); currentService.baseURL = device.baseURL; } } @Override public void endElement(String uri, String localName, String qName) throws SAXException { // System.out.println("[DEBUG] qName: " + qName + ", currentValue: " + currentValue); /* Parse device-specific information */ if (TAG_DEVICE_TYPE.equals(qName)) { device.deviceType = currentValue; } else if (TAG_FRIENDLY_NAME.equals(qName)) { device.friendlyName = currentValue; } else if (TAG_MANUFACTURER.equals(qName)) { device.manufacturer = currentValue; } else if (TAG_MANUFACTURER_URL.equals(qName)) { device.manufacturerURL = currentValue; } else if (TAG_MODEL_DESCRIPTION.equals(qName)) { device.modelDescription = currentValue; } else if (TAG_MODEL_NAME.equals(qName)) { device.modelName = currentValue; } else if (TAG_MODEL_NUMBER.equals(qName)) { device.modelNumber = currentValue; } else if (TAG_MODEL_URL.equals(qName)) { device.modelURL = currentValue; } else if (TAG_SERIAL_NUMBER.equals(qName)) { device.serialNumber = currentValue; } else if (TAG_UDN.equals(qName)) { device.UDN = currentValue; // device.UUID = Device.parseUUID(currentValue); } else if (TAG_UPC.equals(qName)) { device.UPC = currentValue; } /* Parse icon-list information */ else if (Icon.TAG_MIME_TYPE.equals(qName)) { currentIcon.mimetype = currentValue; } else if (Icon.TAG_WIDTH.equals(qName)) { currentIcon.width = currentValue; } else if (Icon.TAG_HEIGHT.equals(qName)) { currentIcon.height = currentValue; } else if (Icon.TAG_DEPTH.equals(qName)) { currentIcon.depth = currentValue; } else if (Icon.TAG_URL.equals(qName)) { currentIcon.url = currentValue; } else if (Icon.TAG.equals(qName)) { device.iconList.add(currentIcon); } /* Parse service-list information */ else if (Service.TAG_SERVICE_TYPE.equals(qName)) { currentService.serviceType = currentValue; } else if (Service.TAG_SERVICE_ID.equals(qName)) { currentService.serviceId = currentValue; } else if (Service.TAG_SCPD_URL.equals(qName)) { currentService.SCPDURL = currentValue; } else if (Service.TAG_CONTROL_URL.equals(qName)) { currentService.controlURL = currentValue; } else if (Service.TAG_EVENTSUB_URL.equals(qName)) { currentService.eventSubURL = currentValue; } else if (Service.TAG.equals(qName)) { device.serviceList.add(currentService); } } }; SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser; try { URL mURL = new URL(url); URLConnection urlConnection = mURL.openConnection(); InputStream in = new BufferedInputStream(urlConnection.getInputStream()); try { parser = factory.newSAXParser(); parser.parse(in, dh); } finally { in.close(); } device.headers = urlConnection.getHeaderFields(); return device; } catch (MalformedURLException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }
From source file:com.vinexs.tool.XML.java
/** * Parse standard XML to element structure, allow access with css selector. * * @param inputStream InputStream point to a XML document. * @return JSONObject/* www .j a v a 2 s . com*/ */ public static Element toElement(InputStream inputStream) throws ParserConfigurationException, SAXException, IOException { SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); SAXParser parser = saxParserFactory.newSAXParser(); parseHandler handler = new parseHandler(); parser.parse(inputStream, handler); return handler.datas; }
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. j a v a 2 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. */// w w w. j a va2 s.co 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)); }