List of usage examples for javax.xml.parsers SAXParserFactory newInstance
public static SAXParserFactory newInstance()
From source file:com.panet.imeta.job.entries.xmlwellformed.JobEntryXMLWellFormed.java
private boolean CheckWellFormed(FileObject file, LogWriter log) { boolean retval = false; try {/*from w ww . j a v a 2 s . c om*/ SAXParserFactory factory = SAXParserFactory.newInstance(); XMLTreeHandler handler = new XMLTreeHandler(); // Parse the input. SAXParser saxParser = factory.newSAXParser(); saxParser.parse(new File(KettleVFS.getFilename(file)), handler); retval = true; } catch (Exception e) { log.logError(toString(), Messages.getString("JobXMLWellFormed.Log.ErrorCheckingFile", file.toString(), e.getMessage())); } return retval; }
From source file:com.esri.geoportal.commons.csw.client.impl.Client.java
/** * Reads capabilities from the stream./*from w w w .j ava 2 s . co m*/ * * @param stream input stream with capabilities response * @return capabilities * @throws ParserConfigurationException if unable to create XML parser * @throws SAXException if invalid XML response * @throws IOException if unable to read response */ private Capabilities readCapabilities(InputStream stream) throws ParserConfigurationException, SAXException, IOException { Capabilities capabilities = new Capabilities(); SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); CapabilitiesParse cParse = new CapabilitiesParse(capabilities); factory.newSAXParser().parse(new InputSource(stream), cParse); return capabilities; }
From source file:cm.aptoide.pt.MainActivity.java
private void loadFeatured() { new Thread(new Runnable() { public void run() { loadUIEditorsApps();//from w w w . j a v a 2s .c om File f = null; try { SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); NetworkUtils utils = new NetworkUtils(); String url; f = File.createTempFile("tempFile", ""); String countryCode = Geolocation.getCountryCode(mContext); Log.d("Aptoide-Geolocation", "Using countrycode: " + countryCode); if (ApplicationAptoide.CUSTOMEDITORSCHOICE) { url = getEditorsChoiceURL(ApplicationAptoide.DEFAULTSTORENAME, countryCode); if (((HttpURLConnection) new URL(url).openConnection()).getResponseCode() != 200) { url = getEditorsChoiceURL("apps", countryCode); } } else { url = getEditorsChoiceURL("apps", countryCode); } long date = utils.getLastModified(new URL(url)); long cachedDate = db.getEditorsChoiceHash(); Log.d("Getting", "Date is " + date); Log.d("Getting", "CachedDate is " + cachedDate); if (cachedDate < date) { BufferedInputStream bis = new BufferedInputStream( utils.getInputStream(url, null, null, mContext), 8 * 1024); OutputStream out = new FileOutputStream(f); byte buf[] = new byte[1024]; int len; while ((len = bis.read(buf)) > 0) out.write(buf, 0, len); out.close(); bis.close(); Server server = new Server(); // Database.database.beginTransaction(); db.deleteEditorsChoice(); sp.parse(f, new HandlerEditorsChoice(server)); db.insertEditorsChoiceHash(date); // Database.database.setTransactionSuccessful(); // Database.database.endTransaction(); loadUIEditorsApps(); } } catch (SAXException e) { // Database.database.setTransactionSuccessful(); // Database.database.endTransaction(); } catch (Exception e) { e.printStackTrace(); } if (f != null) f.delete(); } private String getEditorsChoiceURL(String store, String countryCode) { if (countryCode.length() > 0) { return "http://" + store + ".store.aptoide.com/editors.xml?country=" + countryCode; } return "http://" + store + ".store.aptoide.com/editors.xml"; } }).start(); new Thread(new Runnable() { public void run() { loadUItopapps(); File f = null; try { SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); Server server = new Server(); server.id = 1; NetworkUtils utils = new NetworkUtils(); String url; if (ApplicationAptoide.CUSTOMEDITORSCHOICE) { url = "http://" + ApplicationAptoide.DEFAULTSTORENAME + ".store.aptoide.com/top.xml"; if (((HttpURLConnection) new URL(url).openConnection()).getResponseCode() != 200) { url = "http://apps.store.aptoide.com/top.xml"; } } else { url = "http://apps.store.aptoide.com/top.xml"; } long date = utils.getLastModified(new URL(url)); long cachedDate; try { cachedDate = Long.parseLong(db.getRepoHash(server.id, Category.TOPFEATURED)); } catch (Exception e) { cachedDate = 0; } if (cachedDate < date) { BufferedInputStream bis = new BufferedInputStream( utils.getInputStream(url, null, null, mContext), 8 * 1024); f = File.createTempFile("tempFile", ""); OutputStream out = new FileOutputStream(f); byte buf[] = new byte[1024]; int len; while ((len = bis.read(buf)) > 0) out.write(buf, 0, len); out.close(); bis.close(); // Database.database.beginTransaction(); db.deleteFeaturedTopApps(); sp.parse(f, new HandlerFeaturedTop(server)); db.insertFeaturedTopHash(date); loadUItopapps(); f.delete(); } } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { } catch (IOException e) { e.printStackTrace(); } if (f != null) f.delete(); } }).start(); }
From source file:com.centurylink.mdw.util.HttpHelper.java
/** * Use SAX for fastest parsing./*from w w w . j av a 2 s .c o m*/ */ private URL parseResponseForHtmlMetaEquiv(String response) throws IOException, SAXException, ParserConfigurationException { final StringBuffer urlBuf = new StringBuffer(); InputStream xmlStream = new ByteArrayInputStream(response.getBytes()); InputSource src = new InputSource(xmlStream); SAXParserFactory parserFactory = SAXParserFactory.newInstance(); SAXParser parser = parserFactory.newSAXParser(); parser.parse(src, new DefaultHandler() { boolean inHtml; boolean inHead; boolean inMeta; public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException { if (qName.equals("html")) inHtml = true; else if (qName.equals("head")) inHead = true; else if (qName.equals("meta")) inMeta = true; if (inHtml && inHead && inMeta) { if ("refresh".equals(attrs.getValue("http-equiv"))) { String cAttr = attrs.getValue("content"); if (cAttr != null) { int urlIdx = cAttr.indexOf("url="); if (urlIdx >= 0) urlBuf.append(cAttr.substring(urlIdx + 4)); } } } } public void endElement(String uri, String localName, String qName) throws SAXException { if (qName.equals("html")) inHtml = false; else if (qName.equals("head")) inHead = false; else if (qName.equals("meta")) inMeta = false; } }); String str = urlBuf.toString().trim(); if (str.isEmpty()) return null; else return new URL(str); }
From source file:edwardawebb.queueman.classes.NetFlix.java
/** * //ww w . j a v a 2s.c o m * @param queueType * @param maxResults * @return HttpStatusCOde or NF_ERROR_BAD_DEFAULT for exceptions */ public int getRecommendations(int startIndex, String maxResults) { times[0] = System.currentTimeMillis(); URL QueueUrl = null; int result = NF_ERROR_BAD_DEFAULT; if (maxResults.equals(QueueMan.ALL_TITLES_STRING)) { maxResults = "500"; } String expanders = "?expand=synopsis,formats&start_index=" + startIndex + "&max_results=" + maxResults; InputStream xml = null; try { // we're either rotating/task jumping OR we're starting/paging /*if (!NetFlix.recomemendedQueue.isEmpty() && startIndex == recomemendedQueue.getStartIndex()){ return 200; }else if(recomemendedQueue.getTotalTitles() < startIndex){ return NF_ERROR_NO_MORE; }else{ recomemendedQueue.purge(); }*/ QueueUrl = new URL("http://api.netflix.com/users/" + user.getUserId() + "/recommendations" + expanders); RecommendationsHandler myHandler = new RecommendationsHandler(this); Log.d("NetFlix", "" + QueueUrl.toString()); setSignPost(user.getAccessToken(), user.getAccessTokenSecret()); HttpURLConnection request = (HttpURLConnection) QueueUrl.openConnection(); NetFlix.oaconsumer.sign(request); request.connect(); 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("NetFlixQueue", "" + linein); }*/ SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp; sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); xr.setContentHandler(myHandler); xr.parse(new InputSource(xml)); } 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") } times[1] = System.currentTimeMillis(); return result; }
From source file:de.uzk.hki.da.sb.Cli.java
/** * Copies the files listed in a SIP list to a single directory * /*w w w .ja v a 2 s . c o m*/ * @param fileListFile The SIP list file * @return The path to the directory containing the files */ private String copySipListContentToFolder(File sipListFile) { CliProgressManager progressManager = new CliProgressManager(); String tempFolderName = getTempFolderName(); XMLReader xmlReader = null; SAXParserFactory spf = SAXParserFactory.newInstance(); try { xmlReader = spf.newSAXParser().getXMLReader(); } catch (Exception e) { logger.log("ERROR: Failed to create SAX parser", e); System.out.println("Fehler beim Einlesen der SIP-Liste: SAX-Parser konnte nicht erstellt werden."); return ""; } xmlReader.setErrorHandler(new ErrorHandler() { @Override public void error(SAXParseException e) throws SAXException { throw new SAXException("Beim Einlesen der SIP-Liste ist ein Fehler aufgetreten.", e); } @Override public void fatalError(SAXParseException e) throws SAXException { throw new SAXException("Beim Einlesen der SIP-Liste ist ein schwerer Fehler aufgetreten.", e); } @Override public void warning(SAXParseException e) throws SAXException { logger.log("WARNING: Warning while parsing siplist", e); System.out.println("\nWarnung:\n" + e.getMessage()); } }); InputStream inputStream; try { inputStream = new FileInputStream(sipListFile); Reader reader = new InputStreamReader(inputStream, "UTF-8"); Builder parser = new Builder(xmlReader); Document doc = parser.build(reader); reader.close(); Element root = doc.getRootElement(); Elements sipElements = root.getChildElements("sip"); long files = 0; for (int i = 0; i < sipElements.size(); i++) { Elements fileElements = sipElements.get(i).getChildElements("file"); if (fileElements != null) files += fileElements.size(); } progressManager.setTotalSize(files); for (int i = 0; i < sipElements.size(); i++) { Element sipElement = sipElements.get(i); String sipName = sipElement.getAttributeValue("name"); File tempDirectory = new File(tempFolderName + File.separator + sipName); if (tempDirectory.exists()) { FileUtils.deleteQuietly(new File(tempFolderName)); System.out.println("\nDie SIP-Liste enthlt mehrere SIPs mit dem Namen " + sipName + ". " + "Bitte vergeben Sie fr jedes SIP einen eigenen Namen."); return ""; } tempDirectory.mkdirs(); Elements fileElements = sipElement.getChildElements("file"); for (int j = 0; j < fileElements.size(); j++) { Element fileElement = fileElements.get(j); String filepath = fileElement.getValue(); File file = new File(filepath); if (!file.exists()) { logger.log("ERROR: File " + file.getAbsolutePath() + " is referenced in siplist, " + "but does not exist"); System.out.println("\nDie in der SIP-Liste angegebene Datei " + file.getAbsolutePath() + " existiert nicht."); FileUtils.deleteQuietly(new File(tempFolderName)); return ""; } try { if (file.isDirectory()) FileUtils.copyDirectoryToDirectory(file, tempDirectory); else FileUtils.copyFileToDirectory(file, tempDirectory); progressManager.copyFilesFromListProgress(); } catch (IOException e) { logger.log("ERROR: Failed to copy file " + file.getAbsolutePath() + " to folder " + tempDirectory.getAbsolutePath(), e); System.out.println("\nDie in der SIP-Liste angegebene Datei " + file.getAbsolutePath() + " konnte nicht kopiert werden."); FileUtils.deleteQuietly(new File(tempFolderName)); return ""; } } } } catch (Exception e) { logger.log("ERROR: Failed to read siplist " + sipListFile.getAbsolutePath(), e); System.out.println("\nBeim Lesen der SIP-Liste ist ein Fehler aufgetreten. "); return ""; } return (new File(tempFolderName).getAbsolutePath()); }
From source file:com.flipzu.flipzu.FlipInterface.java
public FlipUser getUser(String username, String token) throws IOException { String data = "username=" + username + "&access_token=" + token; String url = WSServer + "/api/get_user.xml"; debug.logV(TAG, "getUser for username " + username); DefaultHttpClient hc = new DefaultHttpClient(); ResponseHandler<String> res = new ResponseHandler<String>() { public String handleResponse(final HttpResponse response) throws HttpResponseException, IOException { StatusLine statusLine = response.getStatusLine(); if (statusLine.getStatusCode() >= 300) { throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase()); }/*w w w.j av a2 s . c o m*/ HttpEntity entity = response.getEntity(); return entity == null ? null : EntityUtils.toString(entity, "UTF-8"); } }; HttpPost postMethod = new HttpPost(url); postMethod.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE); if (data != null) { StringEntity tmp = null; try { tmp = new StringEntity(data, "UTF-8"); } catch (UnsupportedEncodingException e) { debug.logE(TAG, "getUser ERROR", e.getCause()); return null; } postMethod.setEntity(tmp); } String response = hc.execute(postMethod, res); SAXParserFactory spf = SAXParserFactory.newInstance(); try { SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); UserHandler myUserHandler = new UserHandler(); xr.setContentHandler(myUserHandler); InputSource inputSource = new InputSource(); inputSource.setEncoding("UTF-8"); inputSource.setCharacterStream(new StringReader(response)); xr.parse(inputSource); FlipUser parsedData = myUserHandler.getParsedData(); return parsedData; } catch (ParserConfigurationException e) { return null; } catch (SAXException e) { return null; } }
From source file:com.entertailion.java.fling.FlingFrame.java
public void onBroadcastFound(final BroadcastAdvertisement advert) { if (advert.getLocation() != null) { new Thread(new Runnable() { public void run() { Log.d(LOG_TAG, "location=" + advert.getLocation()); HttpResponse response = new HttpRequestHelper().sendHttpGet(advert.getLocation()); if (response != null) { String appsUrl = null; Header header = response.getLastHeader(HEADER_APPLICATION_URL); if (header != null) { appsUrl = header.getValue(); if (!appsUrl.endsWith("/")) { appsUrl = appsUrl + "/"; }/*from www . j a v a 2 s . c o m*/ Log.d(LOG_TAG, "appsUrl=" + appsUrl); } try { InputStream inputStream = response.getEntity().getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); InputSource inStream = new org.xml.sax.InputSource(); inStream.setCharacterStream(reader); SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); BroadcastHandler broadcastHandler = new BroadcastHandler(); xr.setContentHandler(broadcastHandler); xr.parse(inStream); Log.d(LOG_TAG, "modelName=" + broadcastHandler.getDialServer().getModelName()); // Only handle ChromeCast devices; not other DIAL // devices like ChromeCast devices if (broadcastHandler.getDialServer().getModelName().equals(CHROME_CAST_MODEL_NAME)) { Log.d(LOG_TAG, "ChromeCast device found: " + advert.getIpAddress().getHostAddress()); DialServer dialServer = new DialServer(advert.getLocation(), advert.getIpAddress(), advert.getPort(), appsUrl, broadcastHandler.getDialServer().getFriendlyName(), broadcastHandler.getDialServer().getUuid(), broadcastHandler.getDialServer().getManufacturer(), broadcastHandler.getDialServer().getModelName()); trackedServers.add(dialServer); } } catch (Exception e) { Log.e(LOG_TAG, "parse device description", e); } } } }).start(); } }
From source file:self.philbrown.droidQuery.Ajax.java
protected TaskResponse doInBackground(Void... arg0) { if (this.isCancelled) return null; //if synchronous, block on the background thread until ready. Then call beforeSend, etc, before resuming. if (!beforeSendIsAsync) { try {// w ww . ja va 2s . c o m mutex.acquire(); } catch (InterruptedException e) { Log.w("AjaxTask", "Synchronization Error. Running Task Async"); } final Thread asyncThread = Thread.currentThread(); isLocked = true; mHandler.post(new Runnable() { @Override public void run() { if (options.beforeSend() != null) { if (options.context() != null) options.beforeSend().invoke($.with(options.context()), options); else options.beforeSend().invoke(null, options); } if (options.isAborted()) { cancel(true); return; } if (options.global()) { synchronized (globalTasks) { if (globalTasks.isEmpty()) { $.ajaxStart(); } globalTasks.add(Ajax.this); } $.ajaxSend(); } else { synchronized (localTasks) { localTasks.add(Ajax.this); } } isLocked = false; LockSupport.unpark(asyncThread); } }); if (isLocked) LockSupport.park(); } //here is where to use the mutex //handle cached responses Object cachedResponse = AjaxCache.sharedCache().getCachedResponse(options); //handle ajax caching option if (cachedResponse != null && options.cache()) { Success s = new Success(cachedResponse); s.reason = "cached response"; s.allHeaders = null; return s; } if (connection == null) { try { String type = options.type(); URL url = new URL(options.url()); if (type == null) { type = "GET"; } if (type.equalsIgnoreCase("CUSTOM")) { try { connection = options.customConnection(); } catch (Exception e) { connection = null; } if (connection == null) { Log.w("droidQuery.ajax", "CUSTOM type set, but AjaxOptions.customRequest is invalid. Defaulting to GET."); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); } } else { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(type); if (type.equalsIgnoreCase("POST") || type.equalsIgnoreCase("PUT")) { connection.setDoOutput(true); } } } catch (Throwable t) { if (options.debug()) t.printStackTrace(); Error e = new Error(null); AjaxError error = new AjaxError(); error.connection = connection; error.options = options; e.status = 0; e.reason = "Bad Configuration"; error.status = e.status; error.reason = e.reason; error.response = e.response; e.allHeaders = new Headers(); e.error = error; return e; } } Map<String, Object> args = new HashMap<String, Object>(); args.put("options", options); args.put("request", null); args.put("connection", connection); 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()) { connection.setRequestProperty(entry.getKey(), entry.getValue()); } } if (options.data() != null) { try { OutputStream os = connection.getOutputStream(); os.write(options.data().toString().getBytes()); os.close(); } catch (Throwable t) { Log.w("Ajax", "Could not post data"); } } if (options.timeout() != 0) { connection.setConnectTimeout(options.timeout()); connection.setReadTimeout(options.timeout()); } if (options.trustedCertificate() != null) { Certificate ca = options.trustedCertificate(); String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = null; try { keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("ca", ca); } catch (KeyStoreException e) { if (options.debug()) e.printStackTrace(); } catch (NoSuchAlgorithmException e) { if (options.debug()) e.printStackTrace(); } catch (CertificateException e) { if (options.debug()) e.printStackTrace(); } catch (IOException e) { if (options.debug()) e.printStackTrace(); } if (keyStore == null) { Log.w("Ajax", "Could not configure trusted certificate"); } else { try { //Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); //Create an SSLContext that uses our TrustManager SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, tmf.getTrustManagers(), null); ((HttpsURLConnection) connection).setSSLSocketFactory(sslContext.getSocketFactory()); } catch (KeyManagementException e) { if (options.debug()) e.printStackTrace(); } catch (NoSuchAlgorithmException e) { if (options.debug()) e.printStackTrace(); } catch (KeyStoreException e) { if (options.debug()) e.printStackTrace(); } } } try { if (options.cookies() != null) { CookieManager cm = new CookieManager(); CookieStore cookies = cm.getCookieStore(); URI uri = URI.create(options.url()); for (Entry<String, String> entry : options.cookies().entrySet()) { HttpCookie cookie = new HttpCookie(entry.getKey(), entry.getValue()); cookies.add(uri, cookie); } connection.setRequestProperty("Cookie", TextUtils.join(",", cookies.getCookies())); } connection.connect(); final int statusCode = connection.getResponseCode(); final String message = connection.getResponseMessage(); if (options.dataFilter() != null) { if (options.context() != null) options.dataFilter().invoke($.with(options.context()), connection, options.dataType()); else options.dataFilter().invoke(null, connection, options.dataType()); } final Function function = options.statusCode().get(statusCode); if (function != null) { mHandler.post(new Runnable() { @Override public void run() { if (options.context() != null) function.invoke($.with(options.context()), statusCode, options.clone()); else function.invoke(null, statusCode, options.clone()); } }); } //handle dataType String dataType = options.dataType(); if (dataType == null) dataType = "text"; if (options.debug()) Log.i("Ajax", "dataType = " + dataType); Object parsedResponse = null; InputStream stream = null; try { if (dataType.equalsIgnoreCase("text") || dataType.equalsIgnoreCase("html")) { if (options.debug()) Log.i("Ajax", "parsing text"); stream = AjaxUtil.getInputStream(connection); parsedResponse = parseText(stream); } else if (dataType.equalsIgnoreCase("xml")) { if (options.debug()) Log.i("Ajax", "parsing xml"); if (options.customXMLParser() != null) { stream = AjaxUtil.getInputStream(connection); if (options.SAXContentHandler() != null) options.customXMLParser().parse(stream, options.SAXContentHandler()); else options.customXMLParser().parse(stream, new DefaultHandler()); parsedResponse = "Response handled by custom SAX parser"; } else if (options.SAXContentHandler() != null) { stream = AjaxUtil.getInputStream(connection); 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(stream)); parsedResponse = "Response handled by custom SAX content handler"; } else { parsedResponse = parseXML(connection); } } else if (dataType.equalsIgnoreCase("json")) { if (options.debug()) Log.i("Ajax", "parsing json"); parsedResponse = parseJSON(connection); } else if (dataType.equalsIgnoreCase("script")) { if (options.debug()) Log.i("Ajax", "parsing script"); parsedResponse = parseScript(connection); } else if (dataType.equalsIgnoreCase("image")) { if (options.debug()) Log.i("Ajax", "parsing image"); stream = AjaxUtil.getInputStream(connection); parsedResponse = parseImage(stream); } else if (dataType.equalsIgnoreCase("raw")) { if (options.debug()) Log.i("Ajax", "parsing raw data"); parsedResponse = parseRawContent(connection); } } catch (ClientProtocolException cpe) { if (options.debug()) cpe.printStackTrace(); Error e = new Error(parsedResponse); AjaxError error = new AjaxError(); error.connection = connection; error.options = options; e.status = statusCode; e.reason = message; error.status = e.status; error.reason = e.reason; error.response = e.response; e.allHeaders = Headers.createHeaders(connection.getHeaderFields()); e.error = error; return e; } catch (Exception ioe) { if (options.debug()) ioe.printStackTrace(); Error e = new Error(parsedResponse); AjaxError error = new AjaxError(); error.connection = connection; error.options = options; e.status = statusCode; e.reason = message; error.status = e.status; error.reason = e.reason; error.response = e.response; e.allHeaders = Headers.createHeaders(connection.getHeaderFields()); e.error = error; return e; } finally { connection.disconnect(); try { if (stream != null) { stream.close(); } } catch (IOException e) { } } if (statusCode >= 300) { //an error occurred Error e = new Error(parsedResponse); Log.e("Ajax Test", parsedResponse.toString()); //AjaxError error = new AjaxError(); //error.request = request; //error.options = options; e.status = e.status; e.reason = e.reason; //error.status = e.status; //error.reason = e.reason; //error.response = e.response; e.allHeaders = Headers.createHeaders(connection.getHeaderFields()); //e.error = error; if (options.debug()) Log.i("Ajax", "Error " + e.status + ": " + e.reason); return e; } else { //handle ajax ifModified option List<String> lastModifiedHeaders = connection.getHeaderFields().get("last-modified"); if (lastModifiedHeaders.size() >= 1) { try { String h = lastModifiedHeaders.get(0); SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US); Date lastModified = format.parse(h); if (options.ifModified() && lastModified != null) { Date lastModifiedDate; synchronized (lastModifiedUrls) { lastModifiedDate = lastModifiedUrls.get(options.url()); } if (lastModifiedDate != null && lastModifiedDate.compareTo(lastModified) == 0) { //request response has not been modified. //Causes an error instead of a success. Error e = new Error(parsedResponse); AjaxError error = new AjaxError(); error.connection = connection; error.options = options; e.status = e.status; e.reason = e.reason; error.status = e.status; error.reason = e.reason; error.response = e.response; e.allHeaders = Headers.createHeaders(connection.getHeaderFields()); e.error = error; Function func = options.statusCode().get(304); if (func != null) { if (options.context() != null) func.invoke($.with(options.context())); else func.invoke(null); } return e; } else { synchronized (lastModifiedUrls) { lastModifiedUrls.put(options.url(), lastModified); } } } } catch (Throwable t) { Log.e("Ajax", "Could not parse Last-Modified Header", t); } } //Now handle a successful request Success s = new Success(parsedResponse); s.reason = message; s.allHeaders = Headers.createHeaders(connection.getHeaderFields()); return s; } } catch (Throwable t) { if (options.debug()) t.printStackTrace(); if (t instanceof java.net.SocketTimeoutException) { Error e = new Error(null); AjaxError error = new AjaxError(); error.connection = connection; error.options = options; error.response = e.response; 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 (connection != null) e.allHeaders = Headers.createHeaders(connection.getHeaderFields()); else e.allHeaders = new Headers(); e.error = error; return e; } return null; } }
From source file:edwardawebb.queueman.classes.NetFlix.java
/** * /*w w w .j a v a 2s . com*/ * @param queueType * @param maxResults * @return HttpStatusCOde or NF_ERROR_BAD_DEFAULT for exceptions */ public int getHomeTitles() { URL QueueUrl = null; int result = NF_ERROR_BAD_DEFAULT; String expanders = "?expand=synopsis,formats"; InputStream xml = null; try { if (!NetFlix.homeQueue.isEmpty()) return 200; QueueUrl = new URL("http://api.netflix.com/users/" + user.getUserId() + "/at_home" + expanders); HomeQueueHandler myHandler = new HomeQueueHandler(); Log.d("NetFlix", "" + QueueUrl.toString()); setSignPost(user.getAccessToken(), user.getAccessTokenSecret()); HttpURLConnection request = (HttpURLConnection) QueueUrl.openConnection(); NetFlix.oaconsumer.sign(request); request.connect(); 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("NetFlixQueue", "" + linein); }*/ SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp; sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); xr.setContentHandler(myHandler); xr.parse(new InputSource(xml)); } 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") } return result; }