List of usage examples for java.net URLConnection setReadTimeout
public void setReadTimeout(int timeout)
From source file:org.wattdepot.client.http.api.collector.EGaugeCollector.java
@Override public void run() { Measurement meas = null;/*from www. j av a 2s . c o m*/ DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); domFactory.setNamespaceAware(true); try { DocumentBuilder builder = domFactory.newDocumentBuilder(); // Have to make HTTP connection manually so we can set proper timeouts URL url = new URL(eGaugeUri); URLConnection httpConnection; httpConnection = url.openConnection(); // Set both connect and read timeouts to 15 seconds. No point in long // timeouts since the // sensor will retry before too long anyway. httpConnection.setConnectTimeout(15 * 1000); httpConnection.setReadTimeout(15 * 1000); httpConnection.connect(); // Record current time as close approximation to time for reading we are // about to make Date timestamp = new Date(); Document doc = builder.parse(httpConnection.getInputStream()); XPathFactory factory = XPathFactory.newInstance(); XPath powerXpath = factory.newXPath(); XPath energyXpath = factory.newXPath(); // Path to get the current power consumed measured by the meter in watts String exprPowerString = "//r[@rt='total' and @t='P' and @n='" + this.registerName + "']/i/text()"; XPathExpression exprPower = powerXpath.compile(exprPowerString); // Path to get the energy consumed month to date in watt seconds String exprEnergyString = "//r[@rt='total' and @t='P' and @n='" + this.registerName + "']/v/text()"; XPathExpression exprEnergy = energyXpath.compile(exprEnergyString); Object powerResult = exprPower.evaluate(doc, XPathConstants.NUMBER); Object energyResult = exprEnergy.evaluate(doc, XPathConstants.NUMBER); Double value = null; // power is given in W Amount<?> power = Amount.valueOf((Double) powerResult, SI.WATT); // energy given in Ws Amount<?> energy = Amount.valueOf((Double) energyResult, SI.WATT.times(SI.SECOND)); if (isPower()) { value = power.to(measUnit).getEstimatedValue(); } else { value = energy.to(measUnit).getEstimatedValue(); } meas = new Measurement(definition.getSensorId(), timestamp, value, measUnit); } catch (MalformedURLException e) { System.err.format("URI %s was invalid leading to malformed URL%n", eGaugeUri); } catch (XPathExpressionException e) { System.err.println("Bad XPath expression, this should never happen."); } catch (ParserConfigurationException e) { System.err.println("Unable to configure XML parser, this is weird."); } catch (SAXException e) { System.err.format("%s: Got bad XML from eGauge sensor %s (%s), hopefully this is temporary.%n", Tstamp.makeTimestamp(), sensor.getName(), e); } catch (IOException e) { System.err.format( "%s: Unable to retrieve data from eGauge sensor %s (%s), hopefully this is temporary.%n", Tstamp.makeTimestamp(), sensor.getName(), e); } if (meas != null) { try { this.client.putMeasurement(depository, meas); } catch (MeasurementTypeException e) { System.err.format("%s does not store %s measurements%n", depository.getName(), meas.getMeasurementType()); } if (debug) { System.out.println(meas); } } }
From source file:org.wso2.emm.system.service.api.OTADownload.java
public void onStateChecked(int error, final BuildPropParser parser) { final String operation = Preference.getBoolean(context, context.getResources().getString(R.string.firmware_status_check_in_progress)) ? Constants.Operation.GET_FIRMWARE_UPGRADE_PACKAGE_STATUS : Constants.Operation.UPGRADE_FIRMWARE; if (error == 0) { if (!otaServerManager.compareLocalVersionToServer(parser)) { Log.i(TAG, "Software is up to date:" + Build.VERSION.RELEASE + ", " + Build.ID); JSONObject result = new JSONObject(); try { result.put(UPGRADE_AVAILABLE, false); if (parser != null) { result.put(UPGRADE_DESCRIPTION, parser.getProp("Software is up to date")); }/*w w w. j av a 2s . c om*/ CommonUtils.sendBroadcast(context, operation, Constants.Code.SUCCESS, Constants.Status.NO_UPGRADE_FOUND, result.toString()); } catch (JSONException e) { String message = "Result payload build failed."; CommonUtils.sendBroadcast(context, operation, Constants.Code.FAILURE, Constants.Status.UPDATE_INFO_NOT_READABLE, message); Log.e(TAG, message + e); } } else if (checkNetworkOnline()) { new AsyncTask<Void, Void, Long>() { protected Long doInBackground(Void... param) { URL url = otaServerManager.getServerConfig().getPackageURL(); URLConnection con; try { con = url.openConnection(); con.setConnectTimeout(Constants.FIRMWARE_UPGRADE_CONNECTIVITY_TIMEOUT); con.setReadTimeout(Constants.FIRMWARE_UPGRADE_READ_TIMEOUT); return (long) con.getContentLength(); } catch (SocketTimeoutException e) { String message = "Connection failure (Socket timeout) when retrieving update package size."; Log.e(TAG, message + e); CommonUtils.sendBroadcast(context, operation, Constants.Code.FAILURE, Constants.Status.CONNECTION_FAILED, message); CommonUtils.callAgentApp(context, Constants.Operation.FAILED_FIRMWARE_UPGRADE_NOTIFICATION, 0, null); return (long) -1; } catch (IOException e) { String message = "Connection failure when retrieving update package size."; Log.e(TAG, message + e); CommonUtils.sendBroadcast(context, operation, Constants.Code.FAILURE, Constants.Status.CONNECTION_FAILED, message); CommonUtils.callAgentApp(context, Constants.Operation.FAILED_FIRMWARE_UPGRADE_NOTIFICATION, 0, null); return (long) -1; } } protected void onPostExecute(Long bytes) { Log.i(TAG, "New release found " + Build.VERSION.RELEASE + ", " + Build.ID); String length = "Unknown"; if (bytes > 0) { length = byteCountToDisplaySize(bytes, false); } Log.i(TAG, "version :" + parser.getProp("ro.build.id") + "\n" + "full_version :" + parser.getProp("ro.build.description") + "\n" + "size : " + length); //Downloading the new update package if a new version is available. if (Preference.getBoolean(context, context.getResources().getString(R.string.firmware_status_check_in_progress))) { JSONObject result = new JSONObject(); try { result.put(UPGRADE_AVAILABLE, true); result.put(UPGRADE_SIZE, length); result.put(UPGRADE_RELEASE, parser.getNumRelease()); result.put(UPGRADE_VERSION, parser.getProp("ro.build.id")); result.put(UPGRADE_DESCRIPTION, parser.getProp("ro.build.description")); CommonUtils.sendBroadcast(context, Constants.Operation.GET_FIRMWARE_UPGRADE_PACKAGE_STATUS, Constants.Code.SUCCESS, Constants.Status.SUCCESSFUL, result.toString()); } catch (JSONException e) { String message = "Result payload build failed."; CommonUtils.sendBroadcast(context, Constants.Operation.GET_FIRMWARE_UPGRADE_PACKAGE_STATUS, Constants.Code.FAILURE, Constants.Status.OTA_IMAGE_VERIFICATION_FAILED, message); Log.e(TAG, message + e); } } else { if (checkNetworkOnline()) { Boolean isAutomaticRetry = (Preference.hasPreferenceKey(context, context.getResources().getString(R.string.firmware_upgrade_automatic_retry)) && Preference.getBoolean(context, context.getResources() .getString(R.string.firmware_upgrade_automatic_retry))) || !Preference.hasPreferenceKey(context, context.getResources() .getString(R.string.firmware_upgrade_automatic_retry)); if (getBatteryLevel( context) >= Constants.REQUIRED_BATTERY_LEVEL_TO_FIRMWARE_UPGRADE) { otaServerManager.startDownloadUpgradePackage(otaServerManager); } else if (isAutomaticRetry) { String message = "Upgrade download has been differed due to insufficient battery level."; Log.w(TAG, message); Preference.putString(context, context.getResources().getString(R.string.upgrade_download_status), Constants.Status.BATTERY_LEVEL_INSUFFICIENT_TO_DOWNLOAD); CommonUtils.sendBroadcast(context, Constants.Operation.UPGRADE_FIRMWARE, Constants.Code.PENDING, Constants.Status.BATTERY_LEVEL_INSUFFICIENT_TO_DOWNLOAD, message); } else { String message = "Upgrade download has been failed due to insufficient battery level."; Preference.putString(context, context.getResources().getString(R.string.upgrade_download_status), Constants.Status.BATTERY_LEVEL_INSUFFICIENT_TO_DOWNLOAD); Log.e(TAG, message); CommonUtils.sendBroadcast(context, Constants.Operation.UPGRADE_FIRMWARE, Constants.Code.FAILURE, Constants.Status.BATTERY_LEVEL_INSUFFICIENT_TO_DOWNLOAD, message); CommonUtils.callAgentApp(context, Constants.Operation.FIRMWARE_UPGRADE_FAILURE, 0, message); } } else { String message = "Connection failure when starting upgrade download."; Log.e(TAG, message); CommonUtils.sendBroadcast(context, Constants.Operation.UPGRADE_FIRMWARE, Constants.Code.FAILURE, Constants.Status.NETWORK_UNREACHABLE, message); CommonUtils.callAgentApp(context, Constants.Operation.FAILED_FIRMWARE_UPGRADE_NOTIFICATION, 0, message); } } } }.execute(); } else { String message = "Connection failure when starting build prop download."; Log.e(TAG, message); CommonUtils.sendBroadcast(context, operation, Constants.Code.FAILURE, Constants.Status.CONNECTION_FAILED, message); CommonUtils.callAgentApp(context, Constants.Operation.FAILED_FIRMWARE_UPGRADE_NOTIFICATION, 0, null); } } else if (error == ERROR_WIFI_NOT_AVAILABLE) { Preference.putString(context, context.getResources().getString(R.string.upgrade_download_status), Constants.Status.WIFI_OFF); Log.e(TAG, "OTA failed due to WIFI connection failure."); } else if (error == ERROR_CANNOT_FIND_SERVER) { String message = "OTA failed due to OTA server not accessible."; Log.e(TAG, message); } else if (error == ERROR_WRITE_FILE_ERROR) { String message = "OTA failed due to file write error."; Log.e(TAG, message); } }
From source file:com.varaneckas.hawkscope.plugin.PluginManager.java
/** * Tells to check for plugin updates//ww w .j a v a2 s . c o m * * @param pluginVersionCheckUrl * @param proxy can be null */ public void checkPluginUpdates(final String pluginVersionCheckUrl, final Proxy proxy) { try { final URL pluginCheckUrl = new URL(Version.PLUGIN_VERSION_CHECK_URL); final URLConnection conn; if (proxy == null) { conn = pluginCheckUrl.openConnection(); } else { conn = pluginCheckUrl.openConnection(proxy); } conn.setConnectTimeout(Constants.CONNECTION_TIMOUT); conn.setReadTimeout(Constants.CONNECTION_TIMOUT); final InputStream io = conn.getInputStream(); int c = 0; final StringBuilder version = new StringBuilder(); while ((c = io.read()) != -1) { version.append((char) c); } final String[] plugs = version.toString().split("\n"); final Map<String, String> currentVersions = new HashMap<String, String>(); for (final Plugin p : getActivePlugins()) { currentVersions.put(p.getName(), p.getVersion()); } for (final String plug : plugs) { final String[] plugData = plug.split(":"); if (currentVersions.containsKey(plugData[0])) { if (currentVersions.get(plugData[0]).compareTo(plugData[1]) < 0) { availableUpdates.put(plugData[0], plugData[1]); } } } if (availableUpdates.size() > 0) { log.info("Plugin updates available: " + availableUpdates); } } catch (final Exception e) { log.error("Failed getting plugin updates"); } }
From source file:net.sourceforge.atunes.kernel.modules.network.NetworkHandler.java
/** * Returns a HttpURLConnection specified by a given URL * /*from w ww . ja va 2 s .co m*/ * @param urlString * A URL as String * * @return A HttpURLConnection * * @throws IOException * If an IO exception occurs */ @Override public URLConnection getConnection(final String urlString) throws IOException { Logger.debug("Opening Connection With: ", urlString); URL url = new URL(urlString); URLConnection connection; ExtendedProxy proxy = ExtendedProxy.getProxy(stateCore.getProxy()); if (proxy == null) { connection = url.openConnection(); } else { connection = url.openConnection(proxy); } connection.setRequestProperty("User-agent", Constants.APP_NAME); connection.setConnectTimeout(connectTimeoutInSeconds * 1000); connection.setReadTimeout(readTimeoutInSeconds * 1000); return connection; }
From source file:xyz.lebalex.lockscreen.MainActivity.java
private static Bitmap getBitMapFromUrl(String urls, int timeout) { try {/* ww w . ja va2s . com*/ originalUrlTemp = urls; /*URL url = new URL(urls); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setConnectTimeout(10000); urlConnection.setReadTimeout(10000); urlConnection.setRequestMethod("GET"); urlConnection.connect(); InputStream imageStream = urlConnection.getInputStream();*/ URL url = new URL(urls); URLConnection dc = url.openConnection(); dc.setConnectTimeout(timeout * 1000); dc.setReadTimeout(timeout * 1000); InputStream imageStream = dc.getInputStream(); return BitmapFactory.decodeStream(imageStream); } catch (Exception e) { return null; } }
From source file:org.wso2.iot.system.service.api.OTADownload.java
public void onStateChecked(int error, final BuildPropParser parser) { final String operation = Preference.getBoolean(context, context.getResources().getString(R.string.firmware_status_check_in_progress)) ? Constants.Operation.GET_FIRMWARE_UPGRADE_PACKAGE_STATUS : Constants.Operation.UPGRADE_FIRMWARE; if (error == 0) { if (!otaServerManager.compareLocalVersionToServer(parser)) { JSONObject result = new JSONObject(); try { result.put(UPGRADE_AVAILABLE, false); if (parser != null) { result.put(UPGRADE_DESCRIPTION, parser.getProp("Software is up to date")); }/*from w w w . j a v a2 s. c o m*/ CommonUtils.sendBroadcast(context, operation, Constants.Code.SUCCESS, Constants.Status.NO_UPGRADE_FOUND, result.toString()); } catch (JSONException e) { String message = "Result payload build failed."; CommonUtils.sendBroadcast(context, operation, Constants.Code.FAILURE, Constants.Status.UPDATE_INFO_NOT_READABLE, message); Log.e(TAG, message + e); } String message = "Software is up to date:" + Build.VERSION.RELEASE + ", " + Build.ID; Log.i(TAG, message); CommonUtils.callAgentApp(context, Constants.Operation.FIRMWARE_UPGRADE_COMPLETE, Preference.getInt(context, context.getResources().getString(R.string.operation_id)), "No upgrades available. " + message); } else if (checkNetworkOnline()) { new AsyncTask<Void, Void, Long>() { protected Long doInBackground(Void... param) { URL url = otaServerManager.getServerConfig().getPackageURL(); URLConnection con; try { con = url.openConnection(); con.setConnectTimeout(Constants.FIRMWARE_UPGRADE_CONNECTIVITY_TIMEOUT); con.setReadTimeout(Constants.FIRMWARE_UPGRADE_READ_TIMEOUT); return (long) con.getContentLength(); } catch (SocketTimeoutException e) { String message = "Connection failure (Socket timeout) when retrieving update package size."; Log.e(TAG, message + e); CommonUtils.sendBroadcast(context, operation, Constants.Code.FAILURE, Constants.Status.CONNECTION_FAILED, message); CommonUtils .callAgentApp(context, Constants.Operation.FAILED_FIRMWARE_UPGRADE_NOTIFICATION, Preference.getInt(context, context.getResources().getString(R.string.operation_id)), message); return (long) -1; } catch (IOException e) { String message = "Connection failure when retrieving update package size."; Log.e(TAG, message + e); CommonUtils.sendBroadcast(context, operation, Constants.Code.FAILURE, Constants.Status.CONNECTION_FAILED, message); CommonUtils .callAgentApp(context, Constants.Operation.FAILED_FIRMWARE_UPGRADE_NOTIFICATION, Preference.getInt(context, context.getResources().getString(R.string.operation_id)), message); return (long) -1; } } protected void onPostExecute(Long bytes) { Log.i(TAG, "New release found " + Build.VERSION.RELEASE + ", " + Build.ID); String length = "Unknown"; if (bytes > 0) { length = byteCountToDisplaySize(bytes, false); } Log.i(TAG, "version :" + parser.getProp("ro.build.id") + "\n" + "full_version :" + parser.getProp("ro.build.description") + "\n" + "size : " + length); //Downloading the new update package if a new version is available. if (Preference.getBoolean(context, context.getResources().getString(R.string.firmware_status_check_in_progress))) { JSONObject result = new JSONObject(); try { result.put(UPGRADE_AVAILABLE, true); result.put(UPGRADE_SIZE, length); result.put(UPGRADE_RELEASE, parser.getNumRelease()); result.put(UPGRADE_VERSION, parser.getProp("ro.build.id")); result.put(UPGRADE_DESCRIPTION, parser.getProp("ro.build.description")); CommonUtils.sendBroadcast(context, Constants.Operation.GET_FIRMWARE_UPGRADE_PACKAGE_STATUS, Constants.Code.SUCCESS, Constants.Status.SUCCESSFUL, result.toString()); } catch (JSONException e) { String message = "Result payload build failed."; CommonUtils.sendBroadcast(context, Constants.Operation.GET_FIRMWARE_UPGRADE_PACKAGE_STATUS, Constants.Code.FAILURE, Constants.Status.OTA_IMAGE_VERIFICATION_FAILED, message); Log.e(TAG, message + e); } } else { Boolean isAutomaticRetry = !Preference.hasPreferenceKey(context, context.getResources().getString(R.string.firmware_upgrade_automatic_retry)) || Preference.getBoolean(context, context.getResources() .getString(R.string.firmware_upgrade_automatic_retry)); if (checkNetworkOnline()) { if (getBatteryLevel( context) >= Constants.REQUIRED_BATTERY_LEVEL_TO_FIRMWARE_UPGRADE) { otaServerManager.startDownloadUpgradePackage(otaServerManager); } else if (isAutomaticRetry) { String message = "Upgrade download has been differed due to insufficient battery level."; Log.w(TAG, message); Preference.putString(context, context.getResources().getString(R.string.upgrade_download_status), Constants.Status.BATTERY_LEVEL_INSUFFICIENT_TO_DOWNLOAD); CommonUtils.sendBroadcast(context, Constants.Operation.UPGRADE_FIRMWARE, Constants.Code.PENDING, Constants.Status.BATTERY_LEVEL_INSUFFICIENT_TO_DOWNLOAD, message); } else { String message = "Upgrade download has been failed due to insufficient battery level."; Preference.putString(context, context.getResources().getString(R.string.upgrade_download_status), Constants.Status.BATTERY_LEVEL_INSUFFICIENT_TO_DOWNLOAD); Log.e(TAG, message); CommonUtils.sendBroadcast(context, Constants.Operation.UPGRADE_FIRMWARE, Constants.Code.FAILURE, Constants.Status.BATTERY_LEVEL_INSUFFICIENT_TO_DOWNLOAD, message); CommonUtils.callAgentApp(context, Constants.Operation.FIRMWARE_UPGRADE_FAILURE, Preference.getInt(context, context.getResources().getString(R.string.operation_id)), message); } } else { String message = "Connection failure when starting upgrade download."; Log.e(TAG, message); if (isAutomaticRetry) { Preference.putString(context, context.getResources().getString(R.string.upgrade_download_status), Constants.Status.NETWORK_UNREACHABLE); CommonUtils.sendBroadcast(context, Constants.Operation.UPGRADE_FIRMWARE, Constants.Code.PENDING, Constants.Status.NETWORK_UNREACHABLE, message); CommonUtils.callAgentApp(context, Constants.Operation.FAILED_FIRMWARE_UPGRADE_NOTIFICATION, Preference.getInt(context, context.getResources().getString(R.string.operation_id)), message); } else { CommonUtils.sendBroadcast(context, Constants.Operation.UPGRADE_FIRMWARE, Constants.Code.FAILURE, Constants.Status.NETWORK_UNREACHABLE, message); CommonUtils.callAgentApp(context, Constants.Operation.FIRMWARE_UPGRADE_FAILURE, Preference.getInt(context, context.getResources().getString(R.string.operation_id)), message); } } } } }.execute(); } else { String message = "Connection failure when starting build prop download."; Log.e(TAG, message); CommonUtils.sendBroadcast(context, operation, Constants.Code.FAILURE, Constants.Status.CONNECTION_FAILED, message); CommonUtils.callAgentApp(context, Constants.Operation.FAILED_FIRMWARE_UPGRADE_NOTIFICATION, Preference.getInt(context, context.getResources().getString(R.string.operation_id)), null); } } else if (error == ERROR_WIFI_NOT_AVAILABLE) { Preference.putString(context, context.getResources().getString(R.string.upgrade_download_status), Constants.Status.WIFI_OFF); Log.e(TAG, "OTA failed due to WIFI connection failure."); } else if (error == ERROR_CANNOT_FIND_SERVER) { String message = "OTA failed due to OTA server not accessible."; Log.e(TAG, message); } else if (error == ERROR_WRITE_FILE_ERROR) { String message = "OTA failed due to file write error."; Log.e(TAG, message); } }
From source file:net.sf.eclipsecs.core.config.configtypes.RemoteConfigurationType.java
@Override protected byte[] getBytesFromURLConnection(URLConnection connection) throws IOException { byte[] configurationFileData = null; InputStream in = null;/*from w w w . j av a 2s . c o m*/ try { // set timeouts - bug 2941010 connection.setConnectTimeout(10000); connection.setReadTimeout(10000); if (connection instanceof HttpURLConnection) { if (!sFailedWith401URLs.contains(connection.getURL().toString())) { HttpURLConnection httpConn = (HttpURLConnection) connection; httpConn.setInstanceFollowRedirects(true); httpConn.connect(); if (httpConn.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) { try { RemoteConfigAuthenticator.removeCachedAuthInfo(connection.getURL()); } catch (CheckstylePluginException e) { CheckstyleLog.log(e); } // add to 401ed URLs sFailedWith401URLs.add(connection.getURL().toString()); throw new IOException(Messages.RemoteConfigurationType_msgUnAuthorized); } } else { // don't retry since we just get another 401 throw new IOException(Messages.RemoteConfigurationType_msgUnAuthorized); } } in = connection.getInputStream(); configurationFileData = IOUtils.toByteArray(in); } finally { IOUtils.closeQuietly(in); } return configurationFileData; }
From source file:com.example.mahmoud.asynctask_and_network.NetWork.java
public String callURL(String myStringURL) { StringBuilder sb = new StringBuilder(); // String sb=""; // to convert String to URL URL url = null;/* w w w .j a v a 2 s . c om*/ //to open Connection with URL URLConnection urlConn = null; //to get InputStrem From Connection InputStreamReader in = null; // to connect inputStrem with bufferedReader BufferedReader bufferedReader = null; try { //1 convert String to URL url = new URL(myStringURL); //2 Open Connection urlConn = url.openConnection(); //3 check if there are newtork found or not if (urlConn != null && urlConn.getInputStream() != null) { // 4 if there are connectio found make connection opent for just 1 minute urlConn.setReadTimeout(60 * 1000); // 5 get inputStrem from connection with the default charset for URL in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset()); // 6 connect inputStrem with bufferedReader bufferedReader = new BufferedReader(in); // 7 Read Data from bufferReader while that we not arrived to final char (-1) String cp; /* while ((cp = bufferedReader.readLine()) != null) { sb.append( cp); // sb.a //sb+=""+((char) cp); }*/ int x; while ((x = in.read()) != -1) { sb.append((char) x); } bufferedReader.close(); } in.close(); } catch (Exception e) { } return sb.toString(); }
From source file:org.syncany.operations.plugin.PluginOperation.java
/** * Downloads the plugin JAR from the given URL to a temporary * local location./* w w w . ja v a 2s .c om*/ */ private File downloadPluginJar(String pluginJarUrl) throws Exception { URL pluginJarFile = new URL(pluginJarUrl); logger.log(Level.INFO, "Querying " + pluginJarFile + " ..."); URLConnection urlConnection = pluginJarFile.openConnection(); urlConnection.setConnectTimeout(2000); urlConnection.setReadTimeout(2000); File tempPluginFile = File.createTempFile("syncany-plugin", "tmp"); tempPluginFile.deleteOnExit(); logger.log(Level.INFO, "Downloading to " + tempPluginFile + " ..."); FileOutputStream tempPluginFileOutputStream = new FileOutputStream(tempPluginFile); InputStream remoteJarFileInputStream = urlConnection.getInputStream(); IOUtils.copy(remoteJarFileInputStream, tempPluginFileOutputStream); remoteJarFileInputStream.close(); tempPluginFileOutputStream.close(); if (!tempPluginFile.exists() || tempPluginFile.length() == 0) { throw new Exception("Downloading plugin file failed, URL was " + pluginJarUrl); } return tempPluginFile; }
From source file:com.miz.apis.thetvdb.TheTVDbService.java
private ArrayList<TvShow> getListFromUrl(String serviceUrl) { ArrayList<TvShow> results = new ArrayList<TvShow>(); // Fail early if (TextUtils.isEmpty(serviceUrl)) return results; try {// w w w . ja v a 2 s. co m DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); URL url = new URL(serviceUrl); URLConnection con = url.openConnection(); con.setReadTimeout(60000); con.setConnectTimeout(60000); Document doc = db.parse(con.getInputStream()); doc.getDocumentElement().normalize(); // Check if there's an element with the "id" tag NodeList nodeList = doc.getElementsByTagName("Series"); for (int i = 0; i < nodeList.getLength(); i++) { if (nodeList.item(i).getNodeType() == Node.ELEMENT_NODE) { TvShow show = new TvShow(); Element firstElement = (Element) nodeList.item(i); NodeList list; Element element; NodeList tag; try { list = firstElement.getElementsByTagName("SeriesName"); element = (Element) list.item(0); tag = element.getChildNodes(); show.setTitle(tag.item(0).getNodeValue()); } catch (Exception e) { show.setTitle(mContext.getString(R.string.stringNA)); } try { list = firstElement.getElementsByTagName("Overview"); element = (Element) list.item(0); tag = element.getChildNodes(); show.setDescription(tag.item(0).getNodeValue()); } catch (Exception e) { show.setDescription(mContext.getString(R.string.stringNA)); } try { list = firstElement.getElementsByTagName("id"); element = (Element) list.item(0); tag = element.getChildNodes(); show.setId(tag.item(0).getNodeValue()); } catch (Exception e) { show.setId(DbAdapterTvShows.UNIDENTIFIED_ID); } try { list = firstElement.getElementsByTagName("id"); element = (Element) list.item(0); tag = element.getChildNodes(); show.setCoverUrl( "http://thetvdb.com/banners/posters/" + tag.item(0).getNodeValue() + "-1.jpg"); } catch (Exception e) { show.setCoverUrl(""); } try { list = firstElement.getElementsByTagName("FirstAired"); element = (Element) list.item(0); tag = element.getChildNodes(); show.setFirstAired(tag.item(0).getNodeValue()); } catch (Exception e) { show.setFirstAired(mContext.getString(R.string.stringNA)); } results.add(show); } } } catch (Exception e) { } return results; }