List of usage examples for javax.xml.parsers SAXParser getXMLReader
public abstract org.xml.sax.XMLReader getXMLReader() throws SAXException;
From source file:eionet.cr.util.xml.XmlAnalysis.java
/** * * @param inputStream//from w ww. j a v a 2 s. c o m * @return * @throws SAXException * @throws ParserConfigurationException * @throws GDEMException * @throws SAXException * @throws IOException */ public void parse(InputStream inputStream) throws ParserConfigurationException, SAXException, IOException { // set up the parser and reader SAXParserFactory parserFactory = SAXParserFactory.newInstance(); SAXParser parser = parserFactory.newSAXParser(); XMLReader reader = parser.getXMLReader(); // turn off validation against schema or dtd (we only need the document to be well-formed XML) parserFactory.setValidating(false); reader.setFeature("http://xml.org/sax/features/validation", false); reader.setFeature("http://apache.org/xml/features/validation/schema", false); reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); reader.setFeature("http://xml.org/sax/features/namespaces", true); // turn on dtd handling doctypeReader = new SAXDoctypeReader(); try { parser.setProperty("http://xml.org/sax/properties/lexical-handler", doctypeReader); } catch (SAXNotRecognizedException e) { logger.warn("Installed XML parser does not provide lexical events", e); } catch (SAXNotSupportedException e) { logger.warn("Cannot turn on comment processing here", e); } // set the handler and do the parsing handler = new Handler(); reader.setContentHandler(handler); try { reader.parse(new InputSource(inputStream)); } catch (SAXException e) { Exception ee = e.getException(); if (ee == null || !(ee instanceof CRException)) throw e; } }
From source file:de.betterform.connector.SchemaValidator.java
/** * validate the instance according to the schema specified on the model * * @return false if the instance is not valid *///from w w w. j a va 2 s . co m public boolean validateSchema(Model model, Node instance) throws XFormsException { boolean valid = true; String message; if (LOGGER.isDebugEnabled()) LOGGER.debug("SchemaValidator.validateSchema: validating instance"); //needed if we want to load schemas from Model + set it as "schemaLocation" attribute String schemas = model.getElement().getAttributeNS(NamespaceConstants.XFORMS_NS, "schema"); if (schemas != null && !schemas.equals("")) { // valid=false; //add schemas to element //shouldn't it be done on a copy of the doc ? Element el = null; if (instance.getNodeType() == Node.ELEMENT_NODE) el = (Element) instance; else if (instance.getNodeType() == Node.DOCUMENT_NODE) el = ((Document) instance).getDocumentElement(); else { if (LOGGER.isDebugEnabled()) LOGGER.debug("instance node type is: " + instance.getNodeType()); } String prefix = NamespaceResolver.getPrefix(el, NamespaceConstants.XMLSCHEMA_INSTANCE_NS); //test if with targetNamespace or not //if more than one schema : namespaces are mandatory ! (optional only for 1) StringTokenizer tokenizer = new StringTokenizer(schemas, " ", false); String schemaLocations = null; String noNamespaceSchemaLocation = null; while (tokenizer.hasMoreElements()) { String token = (String) tokenizer.nextElement(); //check that it is an URL URI uri = null; try { uri = new java.net.URI(token); } catch (java.net.URISyntaxException ex) { if (LOGGER.isDebugEnabled()) LOGGER.debug(token + " is not an URI"); } if (uri != null) { String ns; try { ns = this.getSchemaNamespace(uri); if (ns != null && !ns.equals("")) { if (schemaLocations == null) schemaLocations = ns + " " + token; else schemaLocations = schemaLocations + " " + ns + " " + token; ///add the namespace declaration if it is not on the instance? //TODO: how to know with which prefix ? String nsPrefix = NamespaceResolver.getPrefix(el, ns); if (nsPrefix == null) { //namespace not declared ! LOGGER.warn("SchemaValidator: targetNamespace " + ns + " of schema " + token + " is not declared in instance: declaring it as default..."); el.setAttributeNS(NamespaceConstants.XMLNS_NS, NamespaceConstants.XMLNS_PREFIX, ns); } } else if (noNamespaceSchemaLocation == null) noNamespaceSchemaLocation = token; else { //we have more than one schema without namespace LOGGER.warn("SchemaValidator: There is more than one schema without namespace !"); } } catch (Exception ex) { LOGGER.warn( "Exception while trying to load schema: " + uri.toString() + ": " + ex.getMessage(), ex); //in case there was an exception: do nothing, do not set the schema } } } //write schemaLocations found if (schemaLocations != null && !schemaLocations.equals("")) el.setAttributeNS(NamespaceConstants.XMLSCHEMA_INSTANCE_NS, prefix + ":schemaLocation", schemaLocations); if (noNamespaceSchemaLocation != null) el.setAttributeNS(NamespaceConstants.XMLSCHEMA_INSTANCE_NS, prefix + ":noNamespaceSchemaLocation", noNamespaceSchemaLocation); //save and parse the doc ValidationErrorHandler handler = null; File f; try { //save document f = File.createTempFile("instance", ".xml"); f.deleteOnExit(); TransformerFactory trFact = TransformerFactory.newInstance(); Transformer trans = trFact.newTransformer(); DOMSource source = new DOMSource(el); StreamResult result = new StreamResult(f); trans.transform(source, result); if (LOGGER.isDebugEnabled()) LOGGER.debug("Validator.validateSchema: file temporarily saved in " + f.getAbsolutePath()); //parse it with error handler to validate it handler = new ValidationErrorHandler(); SAXParserFactory parserFact = SAXParserFactory.newInstance(); parserFact.setValidating(true); parserFact.setNamespaceAware(true); SAXParser parser = parserFact.newSAXParser(); XMLReader reader = parser.getXMLReader(); //validation activated reader.setFeature("http://xml.org/sax/features/validation", true); //schema validation activated reader.setFeature("http://apache.org/xml/features/validation/schema", true); //used only to validate the schema, not the instance //reader.setFeature( "http://apache.org/xml/features/validation/schema-full-checking", true); //validate only if there is a grammar reader.setFeature("http://apache.org/xml/features/validation/dynamic", true); parser.parse(f, handler); } catch (Exception ex) { LOGGER.warn("Validator.validateSchema: Exception in XMLSchema validation: " + ex.getMessage(), ex); //throw new XFormsException("XMLSchema validation failed. "+message); } //if no exception if (handler != null && handler.isValid()) valid = true; else { message = handler.getMessage(); //TODO: find a way to get the error message displayed throw new XFormsException("XMLSchema validation failed. " + message); } if (LOGGER.isDebugEnabled()) LOGGER.debug("Validator.validateSchema: result=" + valid); } return valid; }
From source file:com.typhoon.newsreader.engine.ChannelRefresh.java
public long syncDB(Handler h, long id, String rssurl) throws Exception { mHandler = h;/*from ww w .j a v a 2s .com*/ mID = id; mRSSURL = rssurl; SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); xr.setContentHandler(this); xr.setErrorHandler(this); URL url = new URL(mRSSURL); URLConnection c = url.openConnection(); c.setRequestProperty("User-Agent", "Android/m3-rc37a"); xr.parse(new InputSource(c.getInputStream())); return mID; }
From source file:com.trailmagic.image.util.ImagesParserImpl.java
@Transactional(propagation = Propagation.REQUIRED, readOnly = false) public void parse(InputStream inputStream) { try {// w w w .j av a2 s .c o m SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setValidating(true); SAXParser parser = factory.newSAXParser(); XMLReader reader = parser.getXMLReader(); // CatalogManager cm = new CatalogManager(); // Catalog catalog = cm.getCatalog(); // catalog.parseCatalog(getClass().getClassLoader().getResource("CatalogManager.properties")); // reader.setEntityResolver(new CatalogResolver(cm)); s_logger.info("Parsing input stream..."); parser.parse(inputStream, this); s_logger.info("done"); } catch (Throwable t) { t.printStackTrace(); System.exit(1); } }
From source file:se.lu.nateko.edca.svc.DescribeFeatureType.java
/** * Parses an XML response from a DescribeFeatureType request and stores the layer * attribute names and their data types in a GeographyLayer object. * @param xmlResponse A reader wrapped around an InputStream containing the XML response from a DescribeFeatureType request. *///from w w w .j av a 2s . c o m protected boolean parseXMLResponse(Reader xmlResponse) { // Log.d(TAG, "parseXMLResponse(Reader) called."); try { SAXParserFactory spfactory = SAXParserFactory.newInstance(); // Make a SAXParser factory. spfactory.setValidating(false); // Tell the factory not to make validating parsers. SAXParser saxParser = spfactory.newSAXParser(); // Use the factory to make a SAXParser. XMLReader xmlReader = saxParser.getXMLReader(); // Get an XML reader from the parser, which will send event calls to its specified event handler. XMLEventHandler xmlEventHandler = new XMLEventHandler(); xmlReader.setContentHandler(xmlEventHandler); // Set which event handler to use. xmlReader.setErrorHandler(xmlEventHandler); // Also set where to send error calls. InputSource source = new InputSource(xmlResponse); // Make an InputSource from the XML input to give to the reader. xmlReader.parse(source); // Start parsing the XML. } catch (Exception e) { Log.e(TAG, e.toString()); return false; } return true; }
From source file:com.determinato.feeddroid.parser.RssParser.java
/** * Persists RSS item to the database.//from w w w . j ava 2 s . co m * @param id item ID * @param folderId ID of containing folder * @param rssurl URL of RSS feed * @return long containing ID of inserted item * @throws Exception */ public long syncDb(long id, long folderId, String rssurl) throws Exception { mId = id; mFolderId = folderId; mRssUrl = rssurl; SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser = factory.newSAXParser(); XMLReader reader = parser.getXMLReader(); reader.setContentHandler(this); reader.setErrorHandler(this); URL url = new URL(mRssUrl); URLConnection c = url.openConnection(); // TODO: Is this a known user agent, or do I need to come up with my own? c.setRequestProperty("User-Agent", "Android/m3-rc37a"); try { BufferedReader bufReader = new BufferedReader(new InputStreamReader(c.getInputStream()), 65535); reader.parse(new InputSource(bufReader)); } catch (NullPointerException e) { Log.e(TAG, Log.getStackTraceString(e)); Log.e(TAG, "Failed to load URL" + url.toString()); } return mId; }
From source file:com.netspective.commons.xml.ParseContext.java
public void init(InputSource inputSource) throws ParserConfigurationException, SAXException { this.inputSource = inputSource; this.errors = new ArrayList(); this.warnings = new ArrayList(); if (inputSource.getSystemId() == null) throw new ParserConfigurationException("Please set the system id."); SAXParser saxParser = getParserFactory().newSAXParser(); parser = saxParser.getXMLReader(); }
From source file:com.typhoon.newsreader.engine.ChannelRefresh.java
public List<FeedsListItem> parser(String link) { if (link.contains("www.24h.com.vn")) { try {/*from w w w . j a va 2 s. co m*/ URL url = new URL(link); URLConnection connection = url.openConnection(); connection.addRequestProperty("http.agent", USER_AGENT); InputSource input = new InputSource(url.openStream()); SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(false); SAXParser parser = factory.newSAXParser(); XMLReader reader = parser.getXMLReader(); reader.setContentHandler(this); reader.parse(input); return getFeedsList(); } catch (Exception e) { e.printStackTrace(); return null; } } else { try { // URL url= new URL(link); DefaultHttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(link); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(false); SAXParser parser = factory.newSAXParser(); XMLReader reader = parser.getXMLReader(); reader.setContentHandler(this); InputSource inStream = new InputSource(); inStream.setCharacterStream(new StringReader(EntityUtils.toString(entity))); reader.parse(inStream); return getFeedsList(); } catch (MalformedURLException e) { e.printStackTrace(); return null; } catch (ParserConfigurationException e) { e.printStackTrace(); return null; } catch (SAXException e) { e.printStackTrace(); return null; } catch (IOException e) { e.printStackTrace(); return null; } } }
From source file:org.semantictools.frame.api.OntologyManager.java
private void loadXsd(File file) throws SchemaParseException { try {/*from www .ja v a 2 s. com*/ SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser = factory.newSAXParser(); XMLReader reader = parser.getXMLReader(); reader.setFeature("http://xml.org/sax/features/namespaces", true); NamespaceReader handler = new NamespaceReader(); reader.setContentHandler(handler); parser.parse(file, handler); String namespace = handler.getTargetNamespace(); if (namespace == null) { logger.warn("Ignoring schema since targetNamespace is not declared: " + file.getPath()); } else { OntologyEntity entity = new OntologyEntity(XML_FORMAT, file, namespace); uri2OntologyEntity.put(namespace, entity); } } catch (Throwable oops) { throw new SchemaParseException(oops); } }