List of usage examples for org.xml.sax XMLReader setContentHandler
public void setContentHandler(ContentHandler handler);
From source file:net.sf.vfsjfilechooser.accessories.bookmarks.BookmarksReader.java
public BookmarksReader(File bookmarksFile) { entries = new ArrayList<TitledURLEntry>(); Reader reader = null;// w w w .ja v a 2s .c om try { XMLReader xmlReader = XMLReaderFactory.createXMLReader(); xmlReader.setContentHandler(new BookmarksHandler()); reader = new BufferedReader(new InputStreamReader(new FileInputStream(bookmarksFile), "UTF-8")); // read 1st 2 bytes to support multiple encryptions char[] code = new char[2]; reader.read(code, 0, 2); LOGGER.debug("code=" + String.valueOf(code) + "="); if ((code[0] == 'b') && (code[1] == '1')) { LOGGER.debug("in encrypted code section"); // read the encrypted file InputStream is = new FileInputStream(bookmarksFile); int the_length = (int) bookmarksFile.length() - 2; LOGGER.debug("raw_length=" + (the_length + 2)); if (the_length <= 0) the_length = 1; LOGGER.debug("fixed_length=" + the_length); byte[] code2 = new byte[2]; byte[] outhex = new byte[the_length]; try { is.read(code2); is.read(outhex); // is.read(outhex,2,the_length); is.close(); } catch (Exception e) { LOGGER.info("exception reading encrypted file" + e); } finally { IOUtils.closeQuietly(is); } byte[] out = Util.hexByteArrayToByteArray(outhex); // do the decryption byte[] raw = new byte[16]; raw[0] = (byte) 1; raw[2] = (byte) 23; raw[3] = (byte) 24; raw[4] = (byte) 2; raw[5] = (byte) 99; raw[6] = (byte) 200; raw[7] = (byte) 202; raw[8] = (byte) 209; raw[9] = (byte) 199; raw[10] = (byte) 181; raw[11] = (byte) 255; raw[12] = (byte) 33; raw[13] = (byte) 210; raw[14] = (byte) 214; raw[15] = (byte) 216; SecretKeySpec skeyspec = new SecretKeySpec(raw, "Blowfish"); Cipher cipher = Cipher.getInstance("Blowfish"); cipher.init(Cipher.DECRYPT_MODE, skeyspec); byte[] decrypted = cipher.doFinal(out); // convert decrypted into a bytestream and parse it ByteArrayInputStream bstream = new ByteArrayInputStream(decrypted); InputSource inputSource = new InputSource(bstream); xmlReader.parse(inputSource); LOGGER.debug("leaving encrypted code section"); } else { LOGGER.debug("in decrypted code section"); reader = new BufferedReader(new InputStreamReader(new FileInputStream(bookmarksFile), "UTF-8")); InputSource inputSource = new InputSource(reader); xmlReader.parse(inputSource); LOGGER.debug("leaving decrypted code section"); } } catch (SAXParseException e) { StringBuilder sb = new StringBuilder(); sb.append("Error parsing xml bookmarks file").append("\n").append(e.getLineNumber()).append(":") .append(e.getColumnNumber()).append("\n").append(e.getMessage()); throw new RuntimeException(sb.toString(), e); } catch (FileNotFoundException e) { throw new RuntimeException("Bookmarks file doesn't exist!", e); } catch (Exception e) { throw new RuntimeException(e); } finally { if (reader != null) { try { reader.close(); } catch (IOException ioe) { LOGGER.error("Unable to close bookmarks stream", ioe); } } } }
From source file:com.badugi.game.logic.model.utils.common.XmlUtils.java
/** * Retrieve the text for a group of elements. Each text element is an entry * in a list.//www .jav a 2s. c o m * <p>This method is currently optimized for the use case of two elements in a list. * * @param xmlAsString the xml response * @param element the element to look for * @return the list of text from the elements. */ public static List<String> getTextForElements(final String xmlAsString, final String element) { final List<String> elements = new ArrayList<String>(2); final XMLReader reader = getXmlReader(); final DefaultHandler handler = new DefaultHandler() { private boolean foundElement = false; private StringBuilder buffer = new StringBuilder(); public void startElement(final String uri, final String localName, final String qName, final Attributes attributes) throws SAXException { if (localName.equals(element)) { this.foundElement = true; } } public void endElement(final String uri, final String localName, final String qName) throws SAXException { if (localName.equals(element)) { this.foundElement = false; elements.add(this.buffer.toString()); this.buffer = new StringBuilder(); } } public void characters(char[] ch, int start, int length) throws SAXException { if (this.foundElement) { this.buffer.append(ch, start, length); } } }; reader.setContentHandler(handler); reader.setErrorHandler(handler); try { reader.parse(new InputSource(new StringReader(xmlAsString))); } catch (final Exception e) { LOG.error(e, e); return null; } return elements; }
From source file:com.entertailion.android.overlaynews.rss.RssHandler.java
public RssFeed getFeed(String data) { feed = null;/*from w w w . j a v a 2 s . c o m*/ try { SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); InputSource inStream = new org.xml.sax.InputSource(); inStream.setCharacterStream(new StringReader(data)); xr.setContentHandler(this); feed = new RssFeed(); xr.parse(inStream); xr = null; sp = null; spf = null; } catch (Exception e) { Log.e(LOG_CAT, "getFeed", e); } return feed; }
From source file:org.energyos.espi.datacustodian.integration.utils.ATOMContentHandlerTests.java
@Test @Ignore//from w ww.j av a2s .com public void processEnty() throws Exception { JAXBContext context = marshaller.getJaxbContext(); SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); XMLReader reader = factory.newSAXParser().getXMLReader(); // EntryProcessorServiceImpl procssor = // mock(EntryProcessorServiceImpl.class); ATOMContentHandler atomContentHandler = new ATOMContentHandler(context, entryProcessorService); reader.setContentHandler(atomContentHandler); reader.parse(new InputSource(FixtureFactory.newUsagePointInputStream(UUID.randomUUID()))); // verify(procssor).process(any(EntryType.class)); }
From source file:com.travelguide.GuideActivity.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); final String TAG = "Activity2"; String ln = getIntent().getExtras().getString("tag"); if ((ln.equals("Espaol")) || (ln.equals("Spanish"))) { TextView t1 = (TextView) findViewById(R.id.thanks); t1.setText("Gracias por usar mi aplicacin."); TextView t2 = (TextView) findViewById(R.id.link); t2.setText("Las ubicaciones de visitantes en el interior " + getIntent().getExtras().getString("com.travelguide.radius") + " millas para " + getIntent().getExtras().getString("com.travelguide.location")); } else {//w w w . j av a 2s . c om TextView t1 = (TextView) findViewById(R.id.thanks); t1.setText("Thanks for using my App."); TextView t2 = (TextView) findViewById(R.id.link); t2.setText( "Visitor locations found within " + getIntent().getExtras().getString("com.travelguide.radius") + " miles for " + getIntent().getExtras().getString("com.travelguide.location")); } String url = getIntent().getExtras().getString("com.travelguide.link"); Log.i(TAG, url); try { //***** Parsing the xml file***** SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); tgparse myXML_parser = new tgparse(); xr.setContentHandler(myXML_parser); HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(url.replace(" ", "%20")); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = httpclient.execute(httpget, responseHandler); Log.i(TAG, "responseBody: " + responseBody); ByteArrayInputStream is = new ByteArrayInputStream(responseBody.getBytes()); xr.parse(new InputSource(is)); Log.i(TAG, "parse complete"); TextView placename[]; TextView placeaddress[]; TextView placerating[]; tgxml data; data = tgparse.getXMLData(); placename = new TextView[data.getName().size()]; placeaddress = new TextView[data.getName().size()]; placerating = new TextView[data.getName().size()]; webview = (WebView) findViewById(R.id.myWebView); // webview.setBackgroundColor(0); // webview.setBackgroundResource(R.drawable.openbook); String stg1 = new String(); stg1 = "<html>"; for (int i = 1; i < (data.getName().size()); i++) { Log.i(TAG, " " + i); Log.i(TAG, "Name= " + data.getName().get(i)); Log.i(TAG, "Address= " + data.getAddress().get(i)); Log.i(TAG, "Rating= " + data.getRating().get(i)); placename[i] = new TextView(this); placename[i].setText("Name= " + data.getName().get(i)); placeaddress[i] = new TextView(this); placeaddress[i].setText("Address= " + data.getAddress().get(i)); placerating[i] = new TextView(this); placerating[i].setText("Rating= " + data.getRating().get(i)); if ((ln.equals("Espaol")) || (ln.equals("Spanish"))) { stg1 = stg1 + "Nombre: " + data.getName().get(i) + "<br>" + " Direccin: " + data.getAddress().get(i) + "<br>" + " clasificacin= " + data.getRating().get(i) + "<br>" + "<br>"; } else { stg1 = stg1 + "Name: " + data.getName().get(i) + "<br>" + " Address: " + data.getAddress().get(i) + "<br>" + " Rating= " + data.getRating().get(i) + "<br>" + "<br>"; } } stg1 = stg1 + "</html>"; webview.loadDataWithBaseURL(null, stg1, "text/html", "utf-8", "about:blank"); } catch (Exception e) { Log.i(TAG, "Exception caught", e); } }
From source file:DocumentTracer.java
/** Main. */ public static void main(String[] argv) throws Exception { // is there anything to do? if (argv.length == 0) { printUsage();//from w w w .j a va2 s . com System.exit(1); } // variables DocumentTracer tracer = new DocumentTracer(); PrintWriter out = new PrintWriter(System.out); XMLReader parser = null; boolean namespaces = DEFAULT_NAMESPACES; boolean namespacePrefixes = DEFAULT_NAMESPACE_PREFIXES; boolean validation = DEFAULT_VALIDATION; boolean externalDTD = DEFAULT_LOAD_EXTERNAL_DTD; 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; // 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."); } 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.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("xd")) { externalDTD = option.equals("xd"); 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.equals("h")) { printUsage(); 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(LOAD_EXTERNAL_DTD_FEATURE_ID, externalDTD); } catch (SAXNotRecognizedException e) { System.err.println( "warning: Parser does not recognize feature (" + LOAD_EXTERNAL_DTD_FEATURE_ID + ")"); } catch (SAXNotSupportedException e) { System.err .println("warning: Parser does not support feature (" + LOAD_EXTERNAL_DTD_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 + ")"); } // set handlers parser.setDTDHandler(tracer); parser.setErrorHandler(tracer); if (parser instanceof XMLReader) { parser.setContentHandler(tracer); try { parser.setProperty("http://xml.org/sax/properties/declaration-handler", tracer); } catch (SAXException e) { e.printStackTrace(System.err); } try { parser.setProperty("http://xml.org/sax/properties/lexical-handler", tracer); } catch (SAXException e) { e.printStackTrace(System.err); } } else { ((Parser) parser).setDocumentHandler(tracer); } // parse file try { parser.parse(arg); } catch (SAXParseException e) { // ignore } catch (Exception e) { System.err.println("error: Parse error occurred - " + e.getMessage()); if (e instanceof SAXException) { Exception nested = ((SAXException) e).getException(); if (nested != null) { e = nested; } } e.printStackTrace(System.err); } } }
From source file:fr.eyal.lib.data.parser.GenericParser.java
public void parseSheet(final Object content, final int parseType) throws ParseException { //Sax method used for XML if (parseType == PARSE_TYPE_SAX) { //we convert the content to String String xml = new String((byte[]) content); final SAXParserFactory factory = SAXParserFactory.newInstance(); try {/*from w w w . j a v a2s. c om*/ final SAXParser sp = factory.newSAXParser(); final XMLReader xr = sp.getXMLReader(); final InputSource is = new InputSource(); is.setCharacterStream(new StringReader(xml)); //we set the SAX DefaultHandler xr.setContentHandler((DefaultHandler) mHandler); Out.v(TAG, "start parsing SAX"); xr.parse(is); Out.v(TAG, "end parsing SAX"); } catch (final Exception e) { e.printStackTrace(); throw new ParseException("Parsing error"); } } else if (parseType == PARSE_TYPE_JSON) { mHandler.parse(content); } else if (parseType == PARSE_TYPE_IMAGE) { mHandler.parse(content); } }
From source file:io.milton.http.webdav.DefaultPropFindRequestFieldParser.java
@Override public PropertiesRequest getRequestedFields(InputStream in) { final Set<QName> set = new LinkedHashSet<QName>(); try {//from ww w. j av a 2s . com ByteArrayOutputStream bout = new ByteArrayOutputStream(); StreamUtils.readTo(in, bout, false, true); byte[] arr = bout.toByteArray(); if (arr.length > 1) { ByteArrayInputStream bin = new ByteArrayInputStream(arr); XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setFeature("http://xml.org/sax/features/external-parameter-entities", false); PropFindSaxHandler handler = new PropFindSaxHandler(); reader.setContentHandler(handler); try { reader.parse(new InputSource(bin)); if (handler.isAllProp()) { return new PropertiesRequest(); } else { set.addAll(handler.getAttributes().keySet()); } } catch (IOException e) { log.warn("exception parsing request body", e); // ignore } catch (SAXException e) { log.warn("exception parsing request body", e); // ignore } } } catch (Exception ex) { // There's a report of an exception being thrown here by IT Hit Webdav client // Perhaps we can just log the error and return an empty set. Usually this // class is wrapped by the MsPropFindRequestFieldParser which will use a default // set of properties if this returns an empty set log.warn("Exception parsing PROPFIND request fields. Returning empty property set", ex); //throw new RuntimeException( ex ); } return PropertiesRequest.toProperties(set); }
From source file:cauchy.android.tracker.PicasaWSUtils.java
public Map<String, String> getAlbumsIdsByAlbumTitles() { String url_string = "http://picasaweb.google.com/data/feed/api/user/" + userID; try {/*from ww w . j ava2 s . c o m*/ URL url = new URL(url_string); SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); xr.setContentHandler(this); InputStream openStream = url.openStream(); xr.parse(new InputSource(openStream)); openStream.close(); return albumsIdsByAlbumTitles; } catch (Exception e) { e.printStackTrace(); return null; } }