List of usage examples for java.net URLConnection setConnectTimeout
public void setConnectTimeout(int timeout)
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 a va2 s.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.intellij.util.net.HttpConfigurable.java
/** * todo [all] It is NOT nessesary to call anything if you obey common IDEA proxy settings; * todo if you want to define your own behaviour, refer to {@link com.intellij.util.proxy.CommonProxy} * * also, this method is useful in a way that it test connection to the host [through proxy] * * @param url URL for HTTP connection/*from www . j a va 2 s . co m*/ * @throws IOException */ public void prepareURL(String url) throws IOException { //setAuthenticator(); CommonProxy.isInstalledAssertion(); final URLConnection connection = openConnection(url); try { connection.setConnectTimeout(3 * 1000); connection.setReadTimeout(3 * 1000); connection.connect(); connection.getInputStream(); } catch (Throwable e) { if (e instanceof IOException) { throw (IOException) e; } } finally { if (connection instanceof HttpURLConnection) { ((HttpURLConnection) connection).disconnect(); } } }
From source file:org.botlibre.util.Utils.java
public static InputStream openStream(URL url, int timeout) throws IOException { URLConnection connection = url.openConnection(); connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2"); connection.setConnectTimeout(timeout); connection.setReadTimeout(timeout);// w ww . j a v a 2 s.c om return connection.getInputStream(); }
From source file:com.openshift.internal.restclient.http.UrlConnectionHttpClient.java
private void setConnectTimeout(int timeout, URLConnection connection) { if (getTimeout(timeout) != NO_TIMEOUT) { connection.setConnectTimeout(getTimeout(timeout)); }// ww w . j a v a 2 s . c o m }
From source file:com.wavemaker.runtime.ws.SyndFeedService.java
/** * Reads from the InputStream of the specified URL and builds the feed object from the returned XML. * /*w w w . ja v a2 s .c o m*/ * @param feedURL The URL to read feed from. * @param httpBasicAuthUsername The username for HTTP Basic Authentication. * @param httpBasicAuthPassword The password for HTTP Basic Authentication. * @param connectionTimeout HTTP connection timeout. * @return A feed object. */ @ExposeToClient public Feed getFeedWithHttpConfig(String feedURL, String httpBasicAuthUsername, String httpBasicAuthPassword, int connectionTimeout) { URL url = null; try { url = new URL(feedURL); } catch (MalformedURLException e) { throw new WebServiceInvocationException(e); } SyndFeedInput input = new SyndFeedInput(); try { URLConnection urlConn = url.openConnection(); if (urlConn instanceof HttpURLConnection) { urlConn.setAllowUserInteraction(false); urlConn.setDoInput(true); urlConn.setDoOutput(false); ((HttpURLConnection) urlConn).setInstanceFollowRedirects(true); urlConn.setUseCaches(false); urlConn.setRequestProperty(USER_AGENT_KEY, USER_AGENT_VALUE); urlConn.setConnectTimeout(connectionTimeout); if (httpBasicAuthUsername != null && httpBasicAuthUsername.length() > 0) { String auth = httpBasicAuthPassword == null ? httpBasicAuthUsername : httpBasicAuthUsername + ":" + httpBasicAuthPassword; urlConn.setRequestProperty(BASIC_AUTH_KEY, BASIC_AUTH_VALUE_PREFIX + Base64.encodeBase64URLSafeString(auth.getBytes())); } } SyndFeed feed = input.build(new XmlReader(urlConn)); return FeedBuilder.getFeed(feed); } catch (IllegalArgumentException e) { throw new WebServiceInvocationException(e); } catch (FeedException e) { throw new WebServiceInvocationException(e); } catch (IOException e) { throw new WebServiceInvocationException(e); } }
From source file:edu.ucuenca.authorsdisambiguation.nwd.NWD.java
public synchronized String Http(String s, String prefix) throws SQLException, IOException { String get = Cache.getInstance().get(prefix + s); String resp = ""; if (get != null) { //System.out.print("."); resp = get;// ww w . ja va 2s . c o m } else { final URL url = new URL(s); final URLConnection connection = url.openConnection(); connection.setConnectTimeout(60000); connection.setReadTimeout(60000); connection.addRequestProperty("User-Agent", "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:44.0) Gecko/20100101 Firefox/44.0"); connection.addRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); final Scanner reader = new Scanner(connection.getInputStream(), "UTF-8"); while (reader.hasNextLine()) { final String line = reader.nextLine(); resp += line + "\n"; } reader.close(); Cache.getInstance().put(prefix + s, resp); } return resp; }
From source file:com.enonic.vertical.engine.PresentationEngine.java
private Document getURL(String address, String encoding, int timeoutMs) { InputStream in = null;// www.j ava 2s . com BufferedReader reader = null; Document result; try { URL url = new URL(address); URLConnection urlConn = url.openConnection(); urlConn.setConnectTimeout(timeoutMs > 0 ? timeoutMs : DEFAULT_CONNECTION_TIMEOUT); urlConn.setRequestProperty("User-Agent", VerticalProperties.getVerticalProperties().getDataSourceUserAgent()); String userInfo = url.getUserInfo(); if (StringUtils.isNotBlank(userInfo)) { String userInfoBase64Encoded = new String(Base64.encodeBase64(userInfo.getBytes())); urlConn.setRequestProperty("Authorization", "Basic " + userInfoBase64Encoded); } in = urlConn.getInputStream(); // encoding == null: XML file if (encoding == null) { result = XMLTool.domparse(in); } else { StringBuffer sb = new StringBuffer(1024); reader = new BufferedReader(new InputStreamReader(in, encoding)); char[] line = new char[1024]; int charCount = reader.read(line); while (charCount > 0) { sb.append(line, 0, charCount); charCount = reader.read(line); } result = XMLTool.createDocument("urlresult"); Element root = result.getDocumentElement(); XMLTool.createCDATASection(result, root, sb.toString()); } } catch (SocketTimeoutException ste) { String message = "Socket timeout when trying to get url: " + address; VerticalEngineLogger.warn(this.getClass(), 0, message, null); result = null; } catch (IOException ioe) { String message = "Failed to get URL: %t"; VerticalEngineLogger.warn(this.getClass(), 0, message, ioe); result = null; } catch (RuntimeException re) { String message = "Failed to get URL: %t"; VerticalEngineLogger.warn(this.getClass(), 0, message, re); result = null; } finally { try { if (reader != null) { reader.close(); } else if (in != null) { in.close(); } } catch (IOException ioe) { String message = "Failed to close URL connection: %t"; VerticalEngineLogger.warn(this.getClass(), 0, message, ioe); } } if (result == null) { result = XMLTool.createDocument("noresult"); } return result; }
From source file:org.wattdepot.client.http.api.collector.NOAAWeatherCollector.java
@Override public void run() { Measurement meas = null;/*from www. j a v a 2 s . 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(noaaWeatherUri); 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 xPath = factory.newXPath(); // path to the data String valString = "/current_observation/" + this.registerName + "/text()"; XPathExpression exprValue = xPath.compile(valString); Object result = new Double(0); if (this.registerName.equals("weather")) { Object cloudCoverage = exprValue.evaluate(doc, XPathConstants.STRING); String cloudStr = cloudCoverage.toString(); if (cloudStr.equalsIgnoreCase("sunny") || cloudStr.equalsIgnoreCase("clear")) { // 0 to 1/8 cloud coverage result = new Double(6.25); } else if (cloudStr.equalsIgnoreCase("mostly sunny") || cloudStr.equalsIgnoreCase("mostly clear")) { // 1/8 to 2/8 cloud coverage result = new Double(18.75); } else if (cloudStr.equalsIgnoreCase("partly sunny") || cloudStr.equalsIgnoreCase("partly cloudy")) { // 3/8 to 5/8 cloud coverage result = new Double(50.0); } else if (cloudStr.equalsIgnoreCase("mostly cloudy")) { // 6/8 to 7/8 cloud coverage result = new Double(81.25); } else if (cloudStr.equalsIgnoreCase("cloudy")) { // 7/8 to 100% cloud coverage result = new Double(93.75); } } else { result = exprValue.evaluate(doc, XPathConstants.NUMBER); } Double value = (Double) result; meas = new Measurement(definition.getSensorId(), timestamp, value, measUnit); } catch (MalformedURLException e) { System.err.format("URI %s was invalid leading to malformed URL%n", noaaWeatherUri); } 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:net.sourceforge.atunes.kernel.modules.network.NetworkHandler.java
/** * Returns a HttpURLConnection specified by a given URL * /*from ww w. ja v a 2 s. c o 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:com.dsh105.commodus.data.Updater.java
private boolean read() { try {/*from w w w . ja v a 2 s . c o m*/ final URLConnection conn = this.url.openConnection(); conn.setConnectTimeout(5000); if (this.apiKey != null) { conn.addRequestProperty("X-API-Key", this.apiKey); } conn.addRequestProperty("User-Agent", "Updater (by Gravity)"); conn.setDoOutput(true); final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); final String response = reader.readLine(); final JSONArray array = (JSONArray) JSONValue.parse(response); if (array.size() == 0) { this.plugin.getLogger() .warning("The updater could not find any files for the project id " + this.id); this.result = UpdateResult.FAIL_BADID; return false; } this.versionName = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.TITLE_VALUE); this.versionLink = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.LINK_VALUE); this.versionType = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.TYPE_VALUE); this.versionGameVersion = (String) ((JSONObject) array.get(array.size() - 1)) .get(Updater.VERSION_VALUE); return true; } catch (final IOException e) { if (e.getMessage().contains("HTTP response code: 403")) { this.plugin.getLogger() .warning("dev.bukkit.org rejected the API key provided in plugins/Updater/config.yml"); this.plugin.getLogger().warning("Please double-check your configuration to ensure it is correct."); this.result = UpdateResult.FAIL_APIKEY; } else { this.plugin.getLogger().warning("The updater could not contact dev.bukkit.org for updating."); this.plugin.getLogger().warning( "If you have not recently modified your configuration and this is the first time you are seeing this message, the site may be experiencing temporary downtime."); this.result = UpdateResult.FAIL_DBO; } e.printStackTrace(); return false; } }