List of usage examples for javax.xml.parsers SAXParser getXMLReader
public abstract org.xml.sax.XMLReader getXMLReader() throws SAXException;
From source file:com.zyz.mobile.book.UserBookData.java
/** * open the info xml file. create one if it cannot be found *//*from w w w .jav a2s.c o m*/ public boolean parse() { try { SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader reader = sp.getXMLReader(); reader.setContentHandler(this); reader.parse(new InputSource(new FileReader(mInfoFile))); } catch (Exception e) { // constructor doesn't check for validity of the file // catch all exceptions here Log.e(TAG, "Failed to parse xml file?"); return false; } return true; }
From source file:eionet.gdem.validation.ValidationService.java
/** /**/*w w w .ja v a2 s .com*/ * Validate XML. If schema is null, then read the schema or DTD from the header of XML. If schema or DTD is defined, then ignore * the defined schema or DTD. * * @param srcStream XML file as InputStream to be validated. * @param schema XML Schema URL. * @return Validation result as HTML snippet. * @throws DCMException in case of unknnown system error. */ public String validateSchema(InputStream srcStream, String schema) throws DCMException { String result = ""; boolean isDTD = false; boolean isBlocker = false; if (Utils.isNullStr(schema)) { schema = null; } try { SAXParserFactory spfact = SAXParserFactory.newInstance(); SAXParser parser = spfact.newSAXParser(); XMLReader reader = parser.getXMLReader(); reader.setErrorHandler(errHandler); XmlconvCatalogResolver catalogResolver = new XmlconvCatalogResolver(); reader.setEntityResolver(catalogResolver); // make parser to validate reader.setFeature("http://xml.org/sax/features/validation", true); reader.setFeature("http://apache.org/xml/features/validation/schema", true); reader.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true); reader.setFeature("http://xml.org/sax/features/namespaces", true); reader.setFeature("http://xml.org/sax/features/namespace-prefixes", true); reader.setFeature("http://apache.org/xml/features/continue-after-fatal-error", false); InputAnalyser inputAnalyser = new InputAnalyser(); inputAnalyser.parseXML(uriXml); String namespace = inputAnalyser.getSchemaNamespace(); // if schema is not in the parameter, then sniff it from the header of xml if (schema == null) { schema = inputAnalyser.getSchemaOrDTD(); isDTD = inputAnalyser.isDTD(); } else { // if the given schema ends with dtd, then don't do schema validation isDTD = schema.endsWith("dtd"); } // schema is already given as a parameter. Read the default namespace from XML file and set external schema. if (schema != null) { if (!isDTD) { if (Utils.isNullStr(namespace)) { // XML file does not have default namespace setNoNamespaceSchemaProperty(reader, schema); } else { setNamespaceSchemaProperty(reader, namespace, schema); } } else { // validate against DTD setLocalSchemaUrl(schema); LocalEntityResolver localResolver = new LocalEntityResolver(schema, getValidatedSchema()); reader.setEntityResolver(localResolver); } } else { return validationFeedback.formatFeedbackText( "Could not validate XML file. Unable to locate XML Schema reference.", QAFeedbackType.WARNING, isBlocker); } // if schema is not available, then do not parse the XML and throw error if (!Utils.resourceExists(getValidatedSchema())) { return validationFeedback.formatFeedbackText( "Failed to read schema document from the following URL: " + getValidatedSchema(), QAFeedbackType.ERROR, isBlocker); } Schema schemaObj = schemaManager.getSchema(getOriginalSchema()); if (schemaObj != null) { isBlocker = schemaObj.isBlocker(); } validationFeedback.setSchema(getOriginalSchema()); InputSource is = new InputSource(srcStream); reader.parse(is); } catch (SAXParseException se) { return validationFeedback.formatFeedbackText("Document is not well-formed. Column: " + se.getColumnNumber() + "; line:" + se.getLineNumber() + "; " + se.getMessage(), QAFeedbackType.ERROR, isBlocker); } catch (IOException ioe) { return validationFeedback.formatFeedbackText( "Due to an IOException, the parser could not check the document. " + ioe.getMessage(), QAFeedbackType.ERROR, isBlocker); } catch (Exception e) { Exception se = e; if (e instanceof SAXException) { se = ((SAXException) e).getException(); } if (se != null) { se.printStackTrace(System.err); } else { e.printStackTrace(System.err); } return validationFeedback.formatFeedbackText( "The parser could not check the document. " + e.getMessage(), QAFeedbackType.ERROR, isBlocker); } validationFeedback.setValidationErrors(getErrorList()); result = validationFeedback.formatFeedbackText(isBlocker); // validation post-processor QAResultPostProcessor postProcessor = new QAResultPostProcessor(); result = postProcessor.processQAResult(result, schema); warningMessage = postProcessor.getWarningMessage(schema); return result; }
From source file:cm.aptoide.pt.RemoteInTab.java
private void xmlPass(String srv, boolean type) { SAXParserFactory spf = SAXParserFactory.newInstance(); try {//from w ww. j a va 2s . com File xml_file = null; SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); if (type) { RssHandler handler = new RssHandler(this, srv); xr.setContentHandler(handler); xml_file = new File(XML_PATH); } else { ExtrasRssHandler handler = new ExtrasRssHandler(this, srv); xr.setContentHandler(handler); xml_file = new File(EXTRAS_XML_PATH); } InputStreamReader isr = new FileReader(xml_file); InputSource is = new InputSource(isr); xr.parse(is); xml_file.delete(); } catch (IOException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } }
From source file:org.apache.uima.ruta.resource.TreeWordList.java
public void readXML(InputStream stream, String encoding) throws IOException { try {// ww w . j a va2 s . c o m InputStream is = new BufferedInputStream(stream); // adds mark/reset support boolean isXml = MultiTreeWordListPersistence.isSniffedXmlContentType(is); if (!isXml) { // MTWL is encoded is = new ZipInputStream(is); ((ZipInputStream) is).getNextEntry(); // zip must contain a single entry } InputStreamReader streamReader = new InputStreamReader(is, encoding); this.root = new TextNode(); XMLEventHandler handler = new XMLEventHandler(root); SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser = factory.newSAXParser(); XMLReader reader = parser.getXMLReader(); // XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setContentHandler(handler); reader.setErrorHandler(handler); reader.parse(new InputSource(streamReader)); } catch (SAXParseException spe) { StringBuffer sb = new StringBuffer(spe.toString()); sb.append("\n Line number: " + spe.getLineNumber()); sb.append("\n Column number: " + spe.getColumnNumber()); sb.append("\n Public ID: " + spe.getPublicId()); sb.append("\n System ID: " + spe.getSystemId() + "\n"); System.out.println(sb.toString()); } catch (SAXException se) { System.out.println("loadDOM threw " + se); se.printStackTrace(System.out); } catch (ParserConfigurationException e) { e.printStackTrace(); } }
From source file:se.lu.nateko.edca.svc.GetCapabilities.java
/** * Parses an XML response from a GetCapabilities request and stores available Layers * and options in the local SQLite database. * @param xmlResponse A reader wrapped around an InputStream containing the XML response from a GetCapabilities request. */// w w w . j a va 2s .c o m protected boolean parseXMLResponse(BufferedReader 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, "XML parsing error: " + e.toString() + " - " + e.getMessage()); return false; } return true; }
From source file:cm.aptoide.pt.ManageRepo.java
private Vector<String> getRemoteServLst(String file) { SAXParserFactory spf = SAXParserFactory.newInstance(); Vector<String> out = new Vector<String>(); try {//from w w w . ja v a 2 s .co m SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); NewServerRssHandler handler = new NewServerRssHandler(this); xr.setContentHandler(handler); InputStreamReader isr = new FileReader(new File(file)); InputSource is = new InputSource(isr); xr.parse(is); File xml_file = new File(file); xml_file.delete(); out = handler.getNewSrvs(); } catch (IOException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } return out; }
From source file:eionet.gdem.conversion.spreadsheet.DDXMLConverter.java
/** * Converts XML file/* w w w . jav a 2 s .co m*/ * @param xmlSchema XML schema * @param outStream OutputStream * @throws Exception If an error occurs. */ protected void doConversion(String xmlSchema, OutputStream outStream) throws Exception { String instanceUrl = DataDictUtil.getInstanceUrl(xmlSchema); DD_XMLInstance instance = new DD_XMLInstance(instanceUrl); DD_XMLInstanceHandler handler = new DD_XMLInstanceHandler(instance); SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser = factory.newSAXParser(); XMLReader reader = parser.getXMLReader(); factory.setValidating(false); factory.setNamespaceAware(true); 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); reader.setContentHandler(handler); reader.parse(instanceUrl); if (Utils.isNullStr(instance.getEncoding())) { String enc_url = Utils.getEncodingFromStream(instanceUrl); if (!Utils.isNullStr(enc_url)) { instance.setEncoding(enc_url); } } importSheetSchemas(sourcefile, instance, xmlSchema); instance.startWritingXml(outStream); sourcefile.writeContentToInstance(instance); instance.flushXml(); }
From source file:com.commonsware.android.EMusicDownloader.SingleAlbum.java
private void getInfoFromXML() { //Show a progress dialog while reading XML final ProgressDialog dialog = ProgressDialog.show(this, "", getString(R.string.loading), true, true); setProgressBarIndeterminateVisibility(true); Thread t3 = new Thread() { public void run() { waiting(200);/* w ww .ja v a 2s. co m*/ try { //Log.d("EMD - ","About to parse"); URL url = new URL(urlAddress); SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); XMLHandlerSingleAlbum myXMLHandler = new XMLHandlerSingleAlbum(); xr.setContentHandler(myXMLHandler); xr.parse(new InputSource(url.openStream())); //Log.d("EMD - ","Done Parsing"); statuscode = myXMLHandler.statuscode; if (statuscode != 200 && statuscode != 206) { throw new Exception(); } genre = myXMLHandler.genre; genreId = myXMLHandler.genreId; labelId = myXMLHandler.labelId; label = myXMLHandler.label; date = myXMLHandler.releaseDate; rating = myXMLHandler.rating; imageURL = myXMLHandler.imageURL; artist = myXMLHandler.artist; artistId = myXMLHandler.artistId; //Log.d("EMD - ","Set genre etc.."); numberOfTracks = myXMLHandler.nItems; trackNames = myXMLHandler.tracks; //sampleAddresses = myXMLHandler.sampleAddress; //sampleExists = myXMLHandler.sampleExists; //vSamplesExist = myXMLHandler.samplesExist; handlerSetContent.sendEmptyMessage(0); dialog.dismiss(); updateImage(); } catch (Exception e) { final Exception ef = e; nameTextView.post(new Runnable() { public void run() { nameTextView.setText(R.string.couldnt_get_album_info); } }); } //Remove Progress Dialog if (dialog.isShowing()) { dialog.dismiss(); } handlerDoneLoading.sendEmptyMessage(0); } }; t3.start(); }
From source file:cm.aptoide.pt.Aptoide.java
private void parseXmlString(String file) { SAXParserFactory spf = SAXParserFactory.newInstance(); try {//from w ww . j a v a 2 s. c om keepScreenOn.acquire(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); NewServerRssHandler handler = new NewServerRssHandler(this); xr.setContentHandler(handler); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(file)); xr.parse(is); server_lst = handler.getNewSrvs(); get_apks = handler.getNewApks(); keepScreenOn.release(); } catch (IOException e) { } catch (SAXException e) { } catch (ParserConfigurationException e) { } }