List of usage examples for org.xml.sax XMLReader setContentHandler
public void setContentHandler(ContentHandler handler);
From source file:hu.sztaki.lpds.pgportal.services.dspace.LNIclient.java
/** * Completes the two-part operation started by startPut(), by * collecting status of the PUT operation and converting the * WebDAV URI of the newly-created resource back to a Handle, * which it returns.//from w w w .j av a 2s . co m * <p> * Any failure results in an exception. * * @return Handle of the newly-created DSpace resource. */ public String finishPut() throws InterruptedException, IOException, SAXException, SAXNotRecognizedException, ParserConfigurationException { if (lastPutThread != null) { lastPutThread.join(); lastPutThread = null; } Header loc = lastPut.getResponseHeader("Location"); lastStatus = lastPut.getStatusCode(); if (lastStatus < 100 || lastStatus >= 400) throw new IOException("PUT returned status = " + lastStatus + "; text=" + lastPut.getStatusText()); lastPut = null; if (loc != null) { String newURL = loc.getValue(); // do a quick PROPFIND to get the handle PropfindMethod pf = new PropfindMethod(newURL, propfindBody); pf.setDoAuthentication(true); client.executeMethod(pf); int pfStatus = pf.getStatusCode(); if (pfStatus < 200 || pfStatus >= 300) throw new IOException( "finishPut.propfind got status = " + pfStatus + "; text=" + pf.getStatusText()); // Maybe move all this crap to within Propfind class?? // so it can get the inputstream directly? SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); PropfindHandler handler = new PropfindHandler(); // XXX FIXME: should turn off validation here explicitly, but // it seems to be off by default. xr.setFeature("http://xml.org/sax/features/namespaces", true); xr.setContentHandler(handler); xr.setErrorHandler(handler); xr.parse(new InputSource(pf.getResponseBodyAsStream())); return handler.handle; } else throw new IOException("PUT response was missing a Location: header."); }
From source file:org.gege.caldavsyncadapter.caldav.CaldavFacade.java
private void parseXML(HttpResponse response, ContentHandler contentHandler) throws IOException, CaldavProtocolException { InputStream is = response.getEntity().getContent(); /*BufferedReader bReader = new BufferedReader(new InputStreamReader(is, "UTF-8")); String Content = "";/*ww w .j a va 2 s . c o m*/ String Line = bReader.readLine(); while (Line != null) { Content += Line; Line = bReader.readLine(); }*/ SAXParserFactory factory = SAXParserFactory.newInstance(); try { SAXParser parser = factory.newSAXParser(); XMLReader reader = parser.getXMLReader(); reader.setContentHandler(contentHandler); reader.parse(new InputSource(is)); } catch (ParserConfigurationException e) { throw new AssertionError("ParserConfigurationException " + e.getMessage()); } catch (IllegalStateException e) { throw new CaldavProtocolException(e.getMessage()); } catch (SAXException e) { throw new CaldavProtocolException(e.getMessage()); } }
From source file:org.castor.jaxb.CastorUnmarshallerTest.java
/** * Tests the {@link CastorUnmarshaller#getUnmarshallerHandler()} method. * * @throws Exception if any error occurs during test *///ww w . j av a 2 s . c o m @Test public void testGetUnmarshallHandler() throws Exception { UnmarshallerHandler unmarshallerHandler = unmarshaller.getUnmarshallerHandler(); SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setNamespaceAware(true); XMLReader xmlReader = spf.newSAXParser().getXMLReader(); xmlReader.setContentHandler(unmarshallerHandler); xmlReader.parse(new InputSource(new StringReader(INPUT_XML))); Entity entity = (Entity) unmarshallerHandler.getResult(); testEntity(entity); }
From source file:com.entertailion.java.caster.RampClient.java
private void parseXml(Reader reader) { try {//from w w w. ja v a 2 s. c om InputSource inStream = new org.xml.sax.InputSource(); inStream.setCharacterStream(reader); SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); AppHandler appHandler = new AppHandler(); xr.setContentHandler(appHandler); xr.parse(inStream); connectionServiceUrl = appHandler.getConnectionServiceUrl(); state = appHandler.getState(); protocol = appHandler.getProtocol(); } catch (Exception e) { Log.e(LOG_TAG, "parse device description", e); } }
From source file:Counter.java
/** Main program entry point. */ public static void main(String argv[]) { // is there anything to do? if (argv.length == 0) { printUsage();//from ww w .jav a2 s.com System.exit(1); } // variables Counter counter = new Counter(); PrintWriter out = new PrintWriter(System.out); XMLReader parser = null; int repetition = DEFAULT_REPETITION; boolean namespaces = DEFAULT_NAMESPACES; boolean namespacePrefixes = DEFAULT_NAMESPACE_PREFIXES; boolean validation = DEFAULT_VALIDATION; boolean schemaValidation = DEFAULT_SCHEMA_VALIDATION; boolean schemaFullChecking = DEFAULT_SCHEMA_FULL_CHECKING; boolean honourAllSchemaLocations = DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS; boolean validateAnnotations = DEFAULT_VALIDATE_ANNOTATIONS; boolean dynamicValidation = DEFAULT_DYNAMIC_VALIDATION; boolean xincludeProcessing = DEFAULT_XINCLUDE; boolean xincludeFixupBaseURIs = DEFAULT_XINCLUDE_FIXUP_BASE_URIS; boolean xincludeFixupLanguage = DEFAULT_XINCLUDE_FIXUP_LANGUAGE; boolean memoryUsage = DEFAULT_MEMORY_USAGE; boolean tagginess = DEFAULT_TAGGINESS; // process arguments for (int i = 0; i < argv.length; i++) { String arg = argv[i]; if (arg.startsWith("-")) { String option = arg.substring(1); if (option.equals("p")) { // get parser name if (++i == argv.length) { System.err.println("error: Missing argument to -p option."); continue; } String parserName = argv[i]; // create parser try { parser = XMLReaderFactory.createXMLReader(parserName); } catch (Exception e) { try { Parser sax1Parser = ParserFactory.makeParser(parserName); parser = new ParserAdapter(sax1Parser); System.err.println("warning: Features and properties not supported on SAX1 parsers."); } catch (Exception ex) { parser = null; System.err.println("error: Unable to instantiate parser (" + parserName + ")"); } } continue; } if (option.equals("x")) { if (++i == argv.length) { System.err.println("error: Missing argument to -x option."); continue; } String number = argv[i]; try { int value = Integer.parseInt(number); if (value < 1) { System.err.println("error: Repetition must be at least 1."); continue; } repetition = value; } catch (NumberFormatException e) { System.err.println("error: invalid number (" + number + ")."); } continue; } if (option.equalsIgnoreCase("n")) { namespaces = option.equals("n"); continue; } if (option.equalsIgnoreCase("np")) { namespacePrefixes = option.equals("np"); continue; } if (option.equalsIgnoreCase("v")) { validation = option.equals("v"); continue; } if (option.equalsIgnoreCase("s")) { schemaValidation = option.equals("s"); continue; } if (option.equalsIgnoreCase("f")) { schemaFullChecking = option.equals("f"); continue; } if (option.equalsIgnoreCase("hs")) { honourAllSchemaLocations = option.equals("hs"); continue; } if (option.equalsIgnoreCase("va")) { validateAnnotations = option.equals("va"); continue; } if (option.equalsIgnoreCase("dv")) { dynamicValidation = option.equals("dv"); continue; } if (option.equalsIgnoreCase("xi")) { xincludeProcessing = option.equals("xi"); continue; } if (option.equalsIgnoreCase("xb")) { xincludeFixupBaseURIs = option.equals("xb"); continue; } if (option.equalsIgnoreCase("xl")) { xincludeFixupLanguage = option.equals("xl"); continue; } if (option.equalsIgnoreCase("m")) { memoryUsage = option.equals("m"); continue; } if (option.equalsIgnoreCase("t")) { tagginess = option.equals("t"); continue; } if (option.equals("-rem")) { if (++i == argv.length) { System.err.println("error: Missing argument to -# option."); continue; } System.out.print("# "); System.out.println(argv[i]); continue; } if (option.equals("h")) { printUsage(); continue; } System.err.println("error: unknown option (" + option + ")."); continue; } // use default parser? if (parser == null) { // create parser try { parser = XMLReaderFactory.createXMLReader(DEFAULT_PARSER_NAME); } catch (Exception e) { System.err.println("error: Unable to instantiate parser (" + DEFAULT_PARSER_NAME + ")"); continue; } } // set parser features try { parser.setFeature(NAMESPACES_FEATURE_ID, namespaces); } catch (SAXException e) { System.err.println("warning: Parser does not support feature (" + NAMESPACES_FEATURE_ID + ")"); } try { parser.setFeature(NAMESPACE_PREFIXES_FEATURE_ID, namespacePrefixes); } catch (SAXException e) { System.err.println( "warning: Parser does not support feature (" + NAMESPACE_PREFIXES_FEATURE_ID + ")"); } try { parser.setFeature(VALIDATION_FEATURE_ID, validation); } catch (SAXException e) { System.err.println("warning: Parser does not support feature (" + VALIDATION_FEATURE_ID + ")"); } try { parser.setFeature(SCHEMA_VALIDATION_FEATURE_ID, schemaValidation); } catch (SAXNotRecognizedException e) { System.err.println( "warning: Parser does not recognize feature (" + SCHEMA_VALIDATION_FEATURE_ID + ")"); } catch (SAXNotSupportedException e) { System.err .println("warning: Parser does not support feature (" + SCHEMA_VALIDATION_FEATURE_ID + ")"); } try { parser.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking); } catch (SAXNotRecognizedException e) { System.err.println( "warning: Parser does not recognize feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println( "warning: Parser does not support feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")"); } try { parser.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations); } catch (SAXNotRecognizedException e) { System.err.println( "warning: Parser does not recognize feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println( "warning: Parser does not support feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")"); } try { parser.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations); } catch (SAXNotRecognizedException e) { System.err.println("warning: Parser does not recognize feature (" + VALIDATE_ANNOTATIONS_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println("warning: Parser does not support feature (" + VALIDATE_ANNOTATIONS_ID + ")"); } try { parser.setFeature(DYNAMIC_VALIDATION_FEATURE_ID, dynamicValidation); } catch (SAXNotRecognizedException e) { System.err.println( "warning: Parser does not recognize feature (" + DYNAMIC_VALIDATION_FEATURE_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println( "warning: Parser does not support feature (" + DYNAMIC_VALIDATION_FEATURE_ID + ")"); } try { parser.setFeature(XINCLUDE_FEATURE_ID, xincludeProcessing); } catch (SAXNotRecognizedException e) { System.err.println("warning: Parser does not recognize feature (" + XINCLUDE_FEATURE_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println("warning: Parser does not support feature (" + XINCLUDE_FEATURE_ID + ")"); } try { parser.setFeature(XINCLUDE_FIXUP_BASE_URIS_FEATURE_ID, xincludeFixupBaseURIs); } catch (SAXNotRecognizedException e) { System.err.println( "warning: Parser does not recognize feature (" + XINCLUDE_FIXUP_BASE_URIS_FEATURE_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println( "warning: Parser does not support feature (" + XINCLUDE_FIXUP_BASE_URIS_FEATURE_ID + ")"); } try { parser.setFeature(XINCLUDE_FIXUP_LANGUAGE_FEATURE_ID, xincludeFixupLanguage); } catch (SAXNotRecognizedException e) { System.err.println( "warning: Parser does not recognize feature (" + XINCLUDE_FIXUP_LANGUAGE_FEATURE_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println( "warning: Parser does not support feature (" + XINCLUDE_FIXUP_LANGUAGE_FEATURE_ID + ")"); } // parse file parser.setContentHandler(counter); parser.setErrorHandler(counter); try { long timeBefore = System.currentTimeMillis(); long memoryBefore = Runtime.getRuntime().freeMemory(); for (int j = 0; j < repetition; j++) { parser.parse(arg); } long memoryAfter = Runtime.getRuntime().freeMemory(); long timeAfter = System.currentTimeMillis(); long time = timeAfter - timeBefore; long memory = memoryUsage ? memoryBefore - memoryAfter : Long.MIN_VALUE; counter.printResults(out, arg, time, memory, tagginess, repetition); } catch (SAXParseException e) { // ignore } catch (Exception e) { System.err.println("error: Parse error occurred - " + e.getMessage()); Exception se = e; if (e instanceof SAXException) { se = ((SAXException) e).getException(); } if (se != null) se.printStackTrace(System.err); else e.printStackTrace(System.err); } } }
From source file:com.commonsware.android.EMusicDownloader.SingleBook.java
private void getInfoFromXML() { final ProgressDialog dialog = ProgressDialog.show(this, "", getString(R.string.loading), true, true); setProgressBarIndeterminateVisibility(true); Thread t3 = new Thread() { public void run() { waiting(200);/*from w w w . ja v a 2 s . c om*/ try { URL url = new URL(urlAddress); SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); XMLHandlerSingleBook myXMLHandler = new XMLHandlerSingleBook(); xr.setContentHandler(myXMLHandler); xr.parse(new InputSource(url.openStream())); genre = myXMLHandler.genre; publisher = myXMLHandler.publisher; narrator = myXMLHandler.narrator; edition = myXMLHandler.edition; artist = myXMLHandler.author; authorId = myXMLHandler.authorId; if (edition == null) { edition = ""; } date = myXMLHandler.releaseDate; rating = myXMLHandler.rating; sampleURL = myXMLHandler.sampleURL; imageURL = myXMLHandler.imageURL; statuscode = myXMLHandler.statuscode; if (statuscode != 200 && statuscode != 206) { throw new Exception(); } blurb = myXMLHandler.blurb; blurb = blurb.replace("<br> ", "<br>"); blurbSource = myXMLHandler.blurbSource; 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_book_info); } }); dialog.dismiss(); } handlerDoneLoading.sendEmptyMessage(0); } }; t3.start(); }
From source file:org.esco.grouper.parsing.SGSParsingUtil.java
/** * Starts the parsing process./*from w w w .j ava 2 s . c o m*/ * @throws SAXException If there is an error during the parsing (invalid group defintion for instance). * @throws IOException If there is an IO error. */ public void parse() throws IOException, SAXException { XMLReader saxReader = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser"); saxReader.setFeature("http://xml.org/sax/features/validation", true); saxReader.setContentHandler(this); saxReader.setErrorHandler(this); saxReader.setEntityResolver(this); if (LOGGER.isInfoEnabled()) { LOGGER.info("---------------------------------"); LOGGER.info("Parsing definition file: "); LOGGER.info(definitionsFileURI); LOGGER.info("---------------------------------"); } InputStream iStream = getClass().getClassLoader().getResourceAsStream(definitionsFileURI); if (iStream == null) { LOGGER.fatal("Unable to load (from classpath) file: " + definitionsFileURI + "."); } //final InputSource is = saxReader.parse(new InputSource(iStream)); if (LOGGER.isInfoEnabled()) { LOGGER.info("---------------------------------"); LOGGER.info("Definition file parsed."); LOGGER.info("---------------------------------"); } }
From source file:eionet.gdem.conversion.spreadsheet.DDXMLConverter.java
/** * Converts XML file/*from ww w . ja v a 2 s.c o 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.daphne.es.showcase.excel.service.ExcelDataService.java
@Async public void importExcel2007(final User user, final InputStream is) { ExcelDataService proxy = ((ExcelDataService) AopContext.currentProxy()); BufferedInputStream bis = null; try {// w w w.ja va 2 s .c o m long beginTime = System.currentTimeMillis(); List<ExcelData> dataList = Lists.newArrayList(); bis = new BufferedInputStream(is); OPCPackage pkg = OPCPackage.open(bis); XSSFReader r = new XSSFReader(pkg); XMLReader parser = XMLReaderFactory.createXMLReader(); ContentHandler handler = new Excel2007ImportSheetHandler(proxy, dataList, batchSize); parser.setContentHandler(handler); Iterator<InputStream> sheets = r.getSheetsData(); while (sheets.hasNext()) { InputStream sheet = null; try { sheet = sheets.next(); InputSource sheetSource = new InputSource(sheet); parser.parse(sheetSource); } catch (Exception e) { throw e; } finally { IOUtils.closeQuietly(sheet); } } //??batchSize? if (dataList.size() > 0) { proxy.doBatchSave(dataList); } long endTime = System.currentTimeMillis(); Map<String, Object> context = Maps.newHashMap(); context.put("seconds", (endTime - beginTime) / 1000); notificationApi.notify(user.getId(), "excelImportSuccess", context); } catch (Exception e) { log.error("excel import error", e); Map<String, Object> context = Maps.newHashMap(); context.put("error", e.getMessage()); notificationApi.notify(user.getId(), "excelImportError", context); } finally { IOUtils.closeQuietly(bis); } }