List of usage examples for javax.xml.parsers SAXParserFactory newInstance
public static SAXParserFactory newInstance()
From source file:edwardawebb.queueman.classes.NetFlix.java
/** * //from w w w. ja v a 2 s .co m * @param queueType * @param maxResults * @return HttpStatusCOde or NF_ERROR_BAD_DEFAULT for exceptions */ public int getQueue(int queueType, String maxResults) { Log.d("NetFlix", "getQueue()>>>"); URL QueueUrl = null; QueueHandler myQueueHandler = null; int result = NF_ERROR_BAD_DEFAULT; if (maxResults.equals(QueueMan.ALL_TITLES_STRING)) { maxResults = "500"; } // addtional info to return String expanders = "?expand=synopsis,formats&max_results=" + maxResults; InputStream xml = null; try { switch (queueType) { case NetFlixQueue.QUEUE_TYPE_INSTANT: if (!NetFlix.instantQueue.isEmpty() && instantQueue.isDownloaded()) return SUCCESS_FROM_CACHE; QueueUrl = new URL( "http://api.netflix.com/users/" + user.getUserId() + "/queues/instant" + expanders); myQueueHandler = new InstantQueueHandler(); break; case NetFlixQueue.QUEUE_TYPE_DISC: if (!NetFlix.discQueue.isEmpty() && discQueue.isDownloaded()) return SUCCESS_FROM_CACHE; QueueUrl = new URL( "http://api.netflix.com/users/" + user.getUserId() + "/queues/disc/available" + expanders); myQueueHandler = new DiscQueueHandler(); break; } //Log.d("NetFlix", "" + QueueUrl.toString()); setSignPost(user.getAccessToken(), user.getAccessTokenSecret()); HttpURLConnection request = (HttpURLConnection) QueueUrl.openConnection(); Log.d("NetFlix", "getQueue() | ready"); NetFlix.oaconsumer.sign(request); Log.d("NetFlix", "getQueue() | signed"); request.connect(); Log.d("NetFlix", "getQueue() | response"); lastResponseMessage = request.getResponseCode() + ": " + request.getResponseMessage(); result = request.getResponseCode(); xml = request.getInputStream(); /* BufferedReader in = new BufferedReader(new InputStreamReader(xml)); String linein = null; while ((linein = in.readLine()) != null) { Log.d("NetFlix", "GetQueue: " + linein); }*/ SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp; sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); xr.setContentHandler(myQueueHandler); Log.d("NetFlix", "getQueue() | parse ready"); xr.parse(new InputSource(xml)); Log.d("NetFlix", "getQueue() | parse complete"); result = myQueueHandler.getSubCode(result); if (myQueueHandler.getMessage() != null) { //we may have an error from netflix, check it lastResponseMessage += " NF:" + result + ", " + myQueueHandler.getMessage(); lastNFResponseMessage = myQueueHandler.getMessage(); } else { lastNFResponseMessage = "No Message"; } if (result == 200) { switch (queueType) { case NetFlixQueue.QUEUE_TYPE_INSTANT: instantQueue.setDownloaded(true); break; case NetFlixQueue.QUEUE_TYPE_DISC: discQueue.setDownloaded(true); break; } } else if (result == 502) { HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put("Queue Type:", "" + NetFlixQueue.queueTypeText[queueType]); parameters.put("HTTP Result:", "" + lastResponseMessage); parameters.put("User ID:", "" + user.getUserId()); parameters.put("NF Message:", "" + myQueueHandler.getMessage()); FlurryAgent.onEvent("getQueue502", parameters); } } catch (ParserConfigurationException e) { reportError(e, lastResponseMessage); } catch (SAXException e) { reportError(e, lastResponseMessage); } catch (IOException e) { reportError(e, lastResponseMessage); // Log.i("NetFlix", "IO Error connecting to NetFlix queue") } catch (OAuthMessageSignerException e) { reportError(e, lastResponseMessage); // Log.i("NetFlix", "Unable to Sign request - token invalid") } catch (OAuthExpectationFailedException e) { reportError(e, lastResponseMessage); // Log.i("NetFlix", "Expectation failed") } Log.d("NetFlix", "getQueue()<<<"); return result; }
From source file:crawlercommons.sitemaps.SiteMapParserSAX.java
/** * Parse the given XML content.// w w w. j av a2s . com * * @param sitemapUrl * a sitemap {@link java.net.URL} * @param is * an {@link org.xml.sax.InputSource} backing the sitemap * @return the site map * @throws UnknownFormatException * if there is an error parsing the * {@link org.xml.sax.InputSource} */ protected AbstractSiteMap processXml(URL sitemapUrl, InputSource is) throws UnknownFormatException { SAXParserFactory factory = SAXParserFactory.newInstance(); DelegatorHandler handler = new DelegatorHandler(sitemapUrl, strict); try { SAXParser saxParser = factory.newSAXParser(); saxParser.parse(is, handler); AbstractSiteMap sitemap = handler.getSiteMap(); if (sitemap == null) { throw new UnknownFormatException("Unknown XML format for: " + sitemapUrl); } return sitemap; } catch (IOException e) { LOG.warn("Error parsing sitemap {}: {}", sitemapUrl, e.getMessage()); UnknownFormatException ufe = new UnknownFormatException("Failed to parse " + sitemapUrl); ufe.initCause(e); throw ufe; } catch (SAXException e) { LOG.warn("Error parsing sitemap {}: {}", sitemapUrl, e.getMessage()); AbstractSiteMap sitemap = handler.getSiteMap(); if (allowPartial && sitemap != null) { LOG.warn("Processed broken/partial sitemap for '" + sitemapUrl + "'"); sitemap.setProcessed(true); return sitemap; } else { UnknownFormatException ufe = new UnknownFormatException("Failed to parse " + sitemapUrl); ufe.initCause(e); throw ufe; } } catch (ParserConfigurationException e) { throw new IllegalStateException(e); } }
From source file:self.philbrown.javaQuery.AjaxTask.java
@Override protected TaskResponse doInBackground(Void... arg0) { //handle cached responses CachedResponse cachedResponse = URLresponses .get(String.format(Locale.US, "%s_?=%s", options.url(), options.dataType())); //handle ajax caching option if (cachedResponse != null) { if (options.cache()) { if (new Date().getTime() - cachedResponse.timestamp.getTime() < options.cacheTimeout()) { //return cached response Success s = new Success(); s.obj = cachedResponse.response; s.reason = "cached response"; s.headers = null;//from w ww. j av a 2 s.c o m return s; } } } if (request == null) { String type = options.type(); if (type == null) type = "GET"; if (type.equalsIgnoreCase("DELETE")) { request = new HttpDelete(options.url()); } else if (type.equalsIgnoreCase("GET")) { request = new HttpGet(options.url()); } else if (type.equalsIgnoreCase("HEAD")) { request = new HttpHead(options.url()); } else if (type.equalsIgnoreCase("OPTIONS")) { request = new HttpOptions(options.url()); } else if (type.equalsIgnoreCase("POST")) { request = new HttpPost(options.url()); } else if (type.equalsIgnoreCase("PUT")) { request = new HttpPut(options.url()); } else if (type.equalsIgnoreCase("TRACE")) { request = new HttpTrace(options.url()); } else if (type.equalsIgnoreCase("CUSTOM")) { try { request = options.customRequest(); } catch (Exception e) { request = null; } if (request == null) { Log.w("javaQuery.ajax", "CUSTOM type set, but AjaxOptions.customRequest is invalid. Defaulting to GET."); request = new HttpGet(); } } else { //default to GET request = new HttpGet(); } } Map<String, Object> args = new HashMap<String, Object>(); args.put("options", options); args.put("request", request); EventCenter.trigger("ajaxPrefilter", args, null); if (options.headers() != null) { if (options.headers().authorization() != null) { options.headers() .authorization(options.headers().authorization() + " " + options.getEncodedCredentials()); } else if (options.username() != null) { //guessing that authentication is basic options.headers().authorization("Basic " + options.getEncodedCredentials()); } for (Entry<String, String> entry : options.headers().map().entrySet()) { request.addHeader(entry.getKey(), entry.getValue()); } } if (options.data() != null) { try { Method setEntity = request.getClass().getMethod("setEntity", new Class<?>[] { HttpEntity.class }); if (options.processData() == null) { setEntity.invoke(request, new StringEntity(options.data().toString())); } else { Class<?> dataProcessor = Class.forName(options.processData()); Constructor<?> constructor = dataProcessor.getConstructor(new Class<?>[] { Object.class }); setEntity.invoke(request, constructor.newInstance(options.data())); } } catch (Throwable t) { Log.w("Ajax", "Could not post data"); } } HttpParams params = new BasicHttpParams(); if (options.timeout() != 0) { HttpConnectionParams.setConnectionTimeout(params, options.timeout()); HttpConnectionParams.setSoTimeout(params, options.timeout()); } HttpClient client = new DefaultHttpClient(params); HttpResponse response = null; try { if (options.cookies() != null) { CookieStore cookies = new BasicCookieStore(); for (Entry<String, String> entry : options.cookies().entrySet()) { cookies.addCookie(new BasicClientCookie(entry.getKey(), entry.getValue())); } HttpContext httpContext = new BasicHttpContext(); httpContext.setAttribute(ClientContext.COOKIE_STORE, cookies); response = client.execute(request, httpContext); } else { response = client.execute(request); } if (options.dataFilter() != null) { if (options.context() != null) options.dataFilter().invoke(new $(options.context()), response, options.dataType()); else options.dataFilter().invoke(null, response, options.dataType()); } StatusLine statusLine = response.getStatusLine(); Function function = options.statusCode().get(statusLine); if (function != null) { if (options.context() != null) function.invoke(new $(options.context())); else function.invoke(null); } if (statusLine.getStatusCode() >= 300) { //an error occurred Error e = new Error(); AjaxError error = new AjaxError(); error.request = request; error.options = options; e.status = statusLine.getStatusCode(); e.reason = statusLine.getReasonPhrase(); error.status = e.status; error.reason = e.reason; e.headers = response.getAllHeaders(); e.error = error; return e; } else { //handle dataType String dataType = options.dataType(); if (dataType == null) dataType = "text"; Object parsedResponse = null; boolean success = true; try { if (dataType.equalsIgnoreCase("text") || dataType.equalsIgnoreCase("html")) { parsedResponse = parseText(response); } else if (dataType.equalsIgnoreCase("xml")) { if (options.customXMLParser() != null) { InputStream is = response.getEntity().getContent(); if (options.SAXContentHandler() != null) options.customXMLParser().parse(is, options.SAXContentHandler()); else options.customXMLParser().parse(is, new DefaultHandler()); parsedResponse = "Response handled by custom SAX parser"; } else if (options.SAXContentHandler() != null) { InputStream is = response.getEntity().getContent(); SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setFeature("http://xml.org/sax/features/namespaces", false); factory.setFeature("http://xml.org/sax/features/namespace-prefixes", true); SAXParser parser = factory.newSAXParser(); XMLReader reader = parser.getXMLReader(); reader.setContentHandler(options.SAXContentHandler()); reader.parse(new InputSource(is)); parsedResponse = "Response handled by custom SAX content handler"; } else { parsedResponse = parseXML(response); } } else if (dataType.equalsIgnoreCase("json")) { parsedResponse = parseJSON(response); } else if (dataType.equalsIgnoreCase("script")) { parsedResponse = parseScript(response); } else if (dataType.equalsIgnoreCase("image")) { parsedResponse = parseImage(response); } } catch (ClientProtocolException cpe) { if (options.debug()) cpe.printStackTrace(); success = false; Error e = new Error(); AjaxError error = new AjaxError(); error.request = request; error.options = options; e.status = statusLine.getStatusCode(); e.reason = statusLine.getReasonPhrase(); error.status = e.status; error.reason = e.reason; e.headers = response.getAllHeaders(); e.error = error; return e; } catch (Exception ioe) { if (options.debug()) ioe.printStackTrace(); success = false; Error e = new Error(); AjaxError error = new AjaxError(); error.request = request; error.options = options; e.status = statusLine.getStatusCode(); e.reason = statusLine.getReasonPhrase(); error.status = e.status; error.reason = e.reason; e.headers = response.getAllHeaders(); e.error = error; return e; } if (success) { //Handle cases where successful requests still return errors (these include //configurations in AjaxOptions and HTTP Headers String key = String.format(Locale.US, "%s_?=%s", options.url(), options.dataType()); CachedResponse cache = URLresponses.get(key); Date now = new Date(); //handle ajax caching option if (cache != null) { if (options.cache()) { if (now.getTime() - cache.timestamp.getTime() < options.cacheTimeout()) { parsedResponse = cache; } else { cache.response = parsedResponse; cache.timestamp = now; synchronized (URLresponses) { URLresponses.put(key, cache); } } } } //handle ajax ifModified option Header[] lastModifiedHeaders = response.getHeaders("last-modified"); if (lastModifiedHeaders.length >= 1) { try { Header h = lastModifiedHeaders[0]; SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz"); Date lastModified = format.parse(h.getValue()); if (options.ifModified() && lastModified != null) { if (cache.lastModified != null && cache.lastModified.compareTo(lastModified) == 0) { //request response has not been modified. //Causes an error instead of a success. Error e = new Error(); AjaxError error = new AjaxError(); error.request = request; error.options = options; e.status = statusLine.getStatusCode(); e.reason = statusLine.getReasonPhrase(); error.status = e.status; error.reason = e.reason; e.headers = response.getAllHeaders(); e.error = error; Function func = options.statusCode().get(304); if (func != null) { if (options.context() != null) func.invoke(new $(options.context())); else func.invoke(null); } return e; } else { cache.lastModified = lastModified; synchronized (URLresponses) { URLresponses.put(key, cache); } } } } catch (Throwable t) { Log.e("Ajax", "Could not parse Last-Modified Header"); } } //Now handle a successful request Success s = new Success(); s.obj = parsedResponse; s.reason = statusLine.getReasonPhrase(); s.headers = response.getAllHeaders(); return s; } //success Success s = new Success(); s.obj = parsedResponse; s.reason = statusLine.getReasonPhrase(); s.headers = response.getAllHeaders(); return s; } } catch (Throwable t) { if (options.debug()) t.printStackTrace(); if (t instanceof java.net.SocketTimeoutException) { Error e = new Error(); AjaxError error = new AjaxError(); error.request = request; error.options = options; e.status = 0; String reason = t.getMessage(); if (reason == null) reason = "Socket Timeout"; e.reason = reason; error.status = e.status; error.reason = e.reason; if (response != null) e.headers = response.getAllHeaders(); else e.headers = new Header[0]; e.error = error; return e; } return null; } }
From source file:com.trailmagic.image.util.ImagesParserImpl.java
@Transactional(propagation = Propagation.REQUIRED, readOnly = false) public void parseFile(File metadataFile) { try {//from w ww .j ava 2 s . c o m SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setValidating(true); SAXParser parser = factory.newSAXParser(); s_logger.info("Parsing " + metadataFile.getPath() + "..."); parser.parse(metadataFile, this); s_logger.info("done"); } catch (Throwable t) { t.printStackTrace(); System.exit(1); } }
From source file:es.rczone.tutoriales.gmaps.MainActivity.java
private void cargarKML(String ruta) { try {/* ww w . ja v a2 s .c o m*/ InputStream is_kml = getResources().getAssets().open(ruta); // create the factory SAXParserFactory factory = SAXParserFactory.newInstance(); // create a parser SAXParser parser; parser = factory.newSAXParser(); // create the reader (scanner) XMLReader xmlreader = parser.getXMLReader(); // instantiate our handler NavigationSaxHandler navSaxHandler = new NavigationSaxHandler(); // assign our handler xmlreader.setContentHandler(navSaxHandler); // get our data via the url class InputSource is = new InputSource(is_kml); // perform the synchronous parse xmlreader.parse(is); // get the results - should be a fully populated RSSFeed instance, or null on error NavigationDataSet ds = navSaxHandler.getParsedData(); Placemark place = ds.getPlacemarks().get(0); ArrayList<String> lista_coordenadas = place.getCoordinates(); LatLng locationToCamera = null; for (String coordenadas : lista_coordenadas) { locationToCamera = draw(coordenadas); } CameraPosition camPos = new CameraPosition.Builder().target(locationToCamera) //Centramos el mapa en Madrid .zoom(9) //Establecemos el zoom en 19 .build(); CameraUpdate camUpd3 = CameraUpdateFactory.newCameraPosition(camPos); map.animateCamera(camUpd3); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:immf.AppNotifications.java
private boolean auth() { boolean httpOk = false; while (!httpOk) { try {//ww w . ja v a2 s. c o m SAXParserFactory spfactory = SAXParserFactory.newInstance(); SAXParser parser = spfactory.newSAXParser(); byte[] xml = this.getCredentials(); InputStream is = new ByteArrayInputStream(xml); parser.parse(is, this); httpOk = true; } catch (Exception e) { log.warn("5????", e); try { Thread.sleep(ReconnectInterval * ReconnectCount); } catch (Exception ee) { } } } if (!ok.equals("OK")) { ok = ""; return false; } this.setCredentials(); return true; }
From source file:org.apache.uima.ruta.resource.TreeWordList.java
public void readXML(InputStream stream, String encoding) throws IOException { try {/*w w w .ja v a2 s .c om*/ 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:com.trailmagic.image.util.ImagesParserImpl.java
@Transactional(propagation = Propagation.REQUIRED, readOnly = false) public void parse(InputStream inputStream) { try {//from w w w. j ava 2s .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:org.metawatch.manager.Monitors.java
private static synchronized void updateWeatherDataGoogle(Context context) { try {//from w ww . j a v a 2 s. c o m if (WeatherData.updating) return; // Prevent weather updating more frequently than every 5 mins if (WeatherData.timeStamp != 0 && WeatherData.received) { long currentTime = System.currentTimeMillis(); long diff = currentTime - WeatherData.timeStamp; if (diff < 5 * 60 * 1000) { if (Preferences.logging) Log.d(MetaWatch.TAG, "Skipping weather update - updated less than 5m ago"); //IdleScreenWidgetRenderer.sendIdleScreenWidgetUpdate(context); return; } } WeatherData.updating = true; if (Preferences.logging) Log.d(MetaWatch.TAG, "Monitors.updateWeatherDataGoogle(): start"); String queryString; List<Address> addresses; if (Preferences.weatherGeolocation && LocationData.received) { Geocoder geocoder; String locality = ""; String PostalCode = ""; try { geocoder = new Geocoder(context, Locale.getDefault()); addresses = geocoder.getFromLocation(LocationData.latitude, LocationData.longitude, 1); for (Address address : addresses) { if (!address.getPostalCode().equalsIgnoreCase("")) { PostalCode = address.getPostalCode(); locality = address.getLocality(); if (locality.equals("")) { locality = PostalCode; } else { PostalCode = locality + ", " + PostalCode; } } } } catch (IOException e) { if (Preferences.logging) Log.e(MetaWatch.TAG, "Exception while retreiving postalcode", e); } if (PostalCode.equals("")) { PostalCode = Preferences.weatherCity; } if (locality.equals("")) { WeatherData.locationName = PostalCode; } else { WeatherData.locationName = locality; } queryString = "http://www.google.com/ig/api?weather=" + PostalCode; } else { queryString = "http://www.google.com/ig/api?weather=" + Preferences.weatherCity; WeatherData.locationName = Preferences.weatherCity; } URL url = new URL(queryString.replace(" ", "%20")); SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); GoogleWeatherHandler gwh = new GoogleWeatherHandler(); xr.setContentHandler(gwh); xr.parse(new InputSource(url.openStream())); WeatherSet ws = gwh.getWeatherSet(); WeatherCurrentCondition wcc = ws.getWeatherCurrentCondition(); ArrayList<WeatherForecastCondition> conditions = ws.getWeatherForecastConditions(); int days = conditions.size(); WeatherData.forecast = new Forecast[days]; for (int i = 0; i < days; ++i) { WeatherForecastCondition wfc = conditions.get(i); WeatherData.forecast[i] = m.new Forecast(); WeatherData.forecast[i].day = null; WeatherData.forecast[i].icon = getIconGoogleWeather(wfc.getCondition()); WeatherData.forecast[i].day = wfc.getDayofWeek(); if (Preferences.weatherCelsius) { WeatherData.forecast[i].tempHigh = wfc.getTempMaxCelsius().toString(); WeatherData.forecast[i].tempLow = wfc.getTempMinCelsius().toString(); } else { WeatherData.forecast[i].tempHigh = Integer .toString(WeatherUtils.celsiusToFahrenheit(wfc.getTempMaxCelsius())); WeatherData.forecast[i].tempLow = Integer .toString(WeatherUtils.celsiusToFahrenheit(wfc.getTempMinCelsius())); } } WeatherData.celsius = Preferences.weatherCelsius; String cond = wcc.getCondition(); WeatherData.condition = cond; if (Preferences.weatherCelsius) { WeatherData.temp = Integer.toString(wcc.getTempCelcius()); } else { WeatherData.temp = Integer.toString(wcc.getTempFahrenheit()); } cond = cond.toLowerCase(); WeatherData.icon = getIconGoogleWeather(cond); WeatherData.received = true; WeatherData.timeStamp = System.currentTimeMillis(); Idle.updateIdle(context, true); MetaWatchService.notifyClients(); } catch (Exception e) { if (Preferences.logging) Log.e(MetaWatch.TAG, "Exception while retreiving weather", e); } finally { if (Preferences.logging) Log.d(MetaWatch.TAG, "Monitors.updateWeatherData(): finish"); } }
From source file:com.netspective.commons.xml.ParseContext.java
private static SAXParserFactory getParserFactory() { if (parserFactory == null) parserFactory = SAXParserFactory.newInstance(); return parserFactory; }