List of usage examples for java.net URLConnection setConnectTimeout
public void setConnectTimeout(int timeout)
From source file:org.sensorhub.impl.sensor.axis.AxisCameraDriver.java
@Override public boolean isConnected() { try {//from ww w .ja v a2 s . c om // try to open stream and check for AXIS Brand URL optionsURL = new URL( "http://" + ipAddress + "/axis-cgi/view/param.cgi?action=list&group=root.Brand.Brand"); URLConnection conn = optionsURL.openConnection(); conn.setConnectTimeout(500); conn.connect(); InputStream is = conn.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); // note: should return one line with root.Brand.Brand=AXIS String line = reader.readLine(); if (line != null) { String[] tokens = line.split("="); if ((tokens[0].trim().equalsIgnoreCase("root.Brand.Brand")) && (tokens[1].trim().equalsIgnoreCase("AXIS"))) return true; } return false; } catch (Exception e) { return false; } }
From source file:com.google.bazel.example.android.activities.MainActivity.java
@Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_ping) { new AsyncTask<String, Void, String>() { public static final int READ_TIMEOUT_MS = 5000; public static final int CONNECTION_TIMEOUT_MS = 2000; private String inputStreamToString(InputStream stream) throws IOException { StringBuilder result = new StringBuilder(); try { BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8")); String line;/*from w w w . j a v a 2s .c o m*/ while ((line = reader.readLine()) != null) { result.append(line); } } finally { stream.close(); } return result.toString(); } private HttpURLConnection getConnection(String url) throws IOException { URLConnection urlConnection = new URL(url).openConnection(); urlConnection.setConnectTimeout(CONNECTION_TIMEOUT_MS); urlConnection.setReadTimeout(READ_TIMEOUT_MS); return (HttpURLConnection) urlConnection; } @Override protected String doInBackground(String... params) { String url = params[0]; HttpURLConnection connection = null; try { connection = getConnection(url); return new JSONObject(inputStreamToString(connection.getInputStream())) .getString("requested"); } catch (IOException e) { Log.e("background", "IOException", e); return null; } catch (JSONException e) { Log.e("background", "JSONException", e); return null; } finally { if (connection != null) { connection.disconnect(); } } } @Override protected void onPostExecute(String result) { TextView textView = (TextView) findViewById(R.id.text_view); if (result == null) { Toast.makeText(MainActivity.this, getString(R.string.error_sending_request), Toast.LENGTH_LONG).show(); textView.setText("???"); return; } textView.setText(result); } }.execute("http://10.0.2.2:8080/boop"); return true; } return super.onOptionsItemSelected(item); }
From source file:org.jesterj.ingest.processors.FetchUrl.java
@Override public Document[] processDocument(Document document) { URL url = null;//from w w w . j av a 2 s. co m try { url = new URL(document.getFirstValue(linkField)); String protocol = url.getProtocol(); String server = url.getHost(); Long lastAccess = visitedSiteCache.getIfPresent(server); long now = System.currentTimeMillis(); if (lastAccess == null) { visitedSiteCache.put(server, now); } else { long elapsed = now - lastAccess; if (elapsed < throttleMs) { try { Thread.sleep(throttleMs - elapsed); } catch (InterruptedException e) { // ignore, not really important. } } } URLConnection conn = url.openConnection(); conn.setConnectTimeout(5000); conn.setReadTimeout(5000); conn.connect(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); if (protocol != null && ("http".equals(protocol) || "https".equals(protocol))) { HttpURLConnection httpConnection = (HttpURLConnection) conn; int responseCode = httpConnection.getResponseCode(); if (httpStatusField != null) { document.put(httpStatusField, String.valueOf(responseCode)); } if (responseCode >= 400) { String message = "HTTP server responded " + responseCode + " " + httpConnection.getResponseMessage(); if (errorField != null) { document.put(errorField, message); } throw new IOException(message); } } IOUtils.copy(conn.getInputStream(), baos); document.setRawData(baos.toByteArray()); } catch (IOException e) { if (failOnIOError) { if (errorField != null) { document.put(errorField, e.getMessage()); } document.setStatus(Status.ERROR); } else { log.warn("Could not fetch " + url + " for " + document.getId(), e); } } return new Document[] { document }; }
From source file:org.ambraproject.solr.SolrHttpServiceImpl.java
@Override public Document makeSolrRequest(Map<String, String> params) throws SolrException { if (solrUrl == null || solrUrl.isEmpty()) { setSolrUrl(config.getString(URL_CONFIG_PARAM)); }//from www .j av a 2s . co m //make sure the return type is xml if (!params.keySet().contains(RETURN_TYPE_PARAM) || !params.get(RETURN_TYPE_PARAM).equals(XML)) { params.put(RETURN_TYPE_PARAM, XML); } //make sure that we include a 'q' parameter if (!params.keySet().contains(Q_PARAM)) { params.put(Q_PARAM, NO_FILTER); } String queryString = "?"; for (String param : params.keySet()) { String value = params.get(param); if (queryString.length() > 1) { queryString += "&"; } queryString += (cleanInput(param) + "=" + cleanInput(value)); } URL url; String urlString = solrUrl + queryString; log.debug("Making Solr http request to " + urlString); try { url = new URL(urlString); } catch (MalformedURLException e) { throw new SolrException("Bad Solr Url: " + urlString, e); } InputStream urlStream = null; Document doc = null; try { URLConnection connection = url.openConnection(); connection.setConnectTimeout(CONNECTION_TIMEOUT); connection.connect(); urlStream = connection.getInputStream(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); doc = builder.parse(urlStream); } catch (IOException e) { throw new SolrException("Error connecting to the Solr server at " + solrUrl, e); } catch (ParserConfigurationException e) { throw new SolrException("Error configuring parser xml parser for solr response", e); } catch (SAXException e) { throw new SolrException("Solr Returned bad XML for url: " + urlString, e); } finally { //Close the input stream if (urlStream != null) { try { urlStream.close(); } catch (IOException e) { log.error("Error closing url stream to Solr", e); } } } return doc; }
From source file:org.dlut.mycloudserver.service.performancemonitor.PerformanceListener.java
private void monitorForOne(PerformanceMonitorDTO performanceMonitorDTO) { String url = "http://" + performanceMonitorDTO.getIp() + ":8001"; InputStream is = null;/* w w w . j a v a 2s . c om*/ BufferedReader br = null; try { URLConnection conn = new URL(url).openConnection(); conn.setConnectTimeout(CONN_TIME_OUT); conn.setReadTimeout(READ_TIME_OUT); is = conn.getInputStream(); br = new BufferedReader(new InputStreamReader(is)); String res = br.readLine(); br.close(); is.close(); JSONObject jsonRes = JSON.parseObject(res); int cores = jsonRes.getIntValue("cores"); int totalMem = jsonRes.getIntValue("totalMem"); int usedMem = jsonRes.getIntValue("usedMem"); double loadAverage = jsonRes.getDoubleValue("loadAverage"); double sendRate = jsonRes.getDoubleValue("sendRate"); double receiveRate = jsonRes.getDoubleValue("receiveRate"); performanceMonitorDTO.setPerformanceMonitorStatus(PerformanceMonitorStatusEnum.RUNNING); performanceMonitorDTO.setCores(cores); performanceMonitorDTO.setTotalMem(totalMem); performanceMonitorDTO.setUsedMem(usedMem); performanceMonitorDTO.setLoadAverage(loadAverage); performanceMonitorDTO.setSendRate(sendRate); performanceMonitorDTO.setReceiveRate(receiveRate); } catch (IOException e) { log.warn("" + performanceMonitorDTO.getIp() + " "); performanceMonitorDTO.setPerformanceMonitorStatus(PerformanceMonitorStatusEnum.CLOSED); } finally { if (br != null) { try { br.close(); } catch (IOException e) { log.error("error message", e); } } if (is != null) { try { is.close(); } catch (IOException e) { log.error("error message", e); } } } // ?? MyCloudResult<Boolean> res = performanceMonitorService.updatePerformanceMonitor(performanceMonitorDTO); if (!res.isSuccess()) { log.error("?" + res.getMsgInfo()); } }
From source file:de.ingrid.iplug.dscmapclient.utils.CapabilitiesUtils.java
public Document requestCaps() { Document doc = null;// w ww. ja v a 2 s . c o m try { URL url; url = new URL(urlStr); URLConnection conn; conn = url.openConnection(); conn.setConnectTimeout(5000); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); doc = dBuilder.parse(conn.getInputStream()); doc.getDocumentElement().normalize(); // insert the dom into the hashmap // in case of exception null entry is written } catch (ConnectTimeoutException e) { log.error("Url timed out: " + urlStr); log.error("Error creating record ids.", e); // e.printStackTrace(); return null; } catch (MalformedURLException e) { log.error("Error creating record ids.", e); // e.printStackTrace(); return null; } catch (IOException e) { log.error("Error creating record ids.", e); // e.printStackTrace(); return null; } catch (ParserConfigurationException e) { log.error("Error creating record ids.", e); // e.printStackTrace(); return null; } catch (SAXException e) { log.error("Error creating record ids.", e); // e.printStackTrace(); return null; } catch (Exception e) { log.error("Error creating record ids.", e); // e.printStackTrace(); return null; } return doc; }
From source file:com.tc.server.UpdateCheckAction.java
private Properties getUpdateProperties(URL updateUrl) throws IOException { URLConnection connection = updateUrl.openConnection(); connection.setConnectTimeout(CONNECT_TIMEOUT); InputStream in = connection.getInputStream(); try {// w w w . ja v a 2s . c om Properties props = new Properties(); props.load(connection.getInputStream()); return props; } finally { if (in != null) { in.close(); } } }
From source file:com.fluidops.iwb.provider.RDFProvider.java
@Override public void gather(final List<Statement> res) throws Exception { InputStream rdfStream = null; RDFFormat rdfFormat;// w w w. j a v a2s . c o m String baseUri; try { // use either DataSource or legacy initialization if (config.dataSource != null) { RDFDataSource ds = config.lookupAndRefreshDataSource(RDFDataSource.class); rdfFormat = ds.getRDFFormat(); if (rdfFormat == null) throw new IllegalStateException(String .format("Data source '%s' does not provide a valid RDF Format", ds.getIdentifier())); rdfStream = ds.getRDFStream(); baseUri = providerID.stringValue(); } else { // legacy support URL url = new URL(config.url); URLConnection conn = url.openConnection(); conn.setConnectTimeout(1000); String contentType = conn.getContentType(); rdfFormat = getRDFFormat(url, contentType); if (rdfFormat == null) throw new IllegalStateException(String.format( "Cannot determine RDF format for URL '%s'. Please specify a format manually.", config.url)); rdfStream = conn.getInputStream(); baseUri = config.url; } // load the RDF data from the rdf stream ParserConfig parserConfig = new ParserConfig(); RDFLoader loader = new RDFLoader(parserConfig, ValueFactoryImpl.getInstance()); loader.load(rdfStream, baseUri, rdfFormat, new RDFHandlerBase() { @Override public void handleStatement(Statement st) throws RDFHandlerException { res.add(st); } }); } finally { IOUtils.closeQuietly(rdfStream); } }
From source file:com.p000ison.dev.simpleclans2.updater.bamboo.BambooBuild.java
private Reader connect(String file) throws IOException { URL buildAPIURL = new URL("http", BAMBOO_HOST, 80, file); URLConnection connection = buildAPIURL.openConnection(); connection.setReadTimeout(1000);/*from www . j av a 2 s . co m*/ connection.setConnectTimeout(1000); return new InputStreamReader(connection.getInputStream(), Charset.forName("UTF-8")); }
From source file:org.shredzone.commons.gravatar.impl.GravatarServiceImpl.java
/** * Fetches a Gravatar icon from the server and stores it in the given {@link File}. * * @param url//from w w w . ja va2 s. c o m * Gravatar URL to fetch * @param file * {@link File} to store the icon to */ private void fetchGravatar(URL url, File file) throws IOException { limitUpstreamRequests(); URLConnection conn = url.openConnection(); conn.setConnectTimeout(TIMEOUT); conn.setReadTimeout(TIMEOUT); if (file.exists()) { conn.setIfModifiedSince(file.lastModified()); } conn.connect(); long lastModified = conn.getLastModified(); if (lastModified > 0L && lastModified <= file.lastModified()) { // Cache file exists and is unchanged if (log.isDebugEnabled()) { log.debug("Cached Gravatar is still good: {}", url); } file.setLastModified(System.currentTimeMillis()); // touch return; } try (InputStream in = conn.getInputStream(); OutputStream out = new FileOutputStream(file)) { byte[] buffer = new byte[8192]; int total = 0; int len; while ((len = in.read(buffer)) >= 0) { out.write(buffer, 0, len); total += len; if (total > MAX_GRAVATAR_SIZE) { log.warn("Gravatar exceeded maximum size: {}", url); break; } } out.flush(); if (log.isDebugEnabled()) { log.debug("Downloaded Gravatar: {}", url); } } }