List of usage examples for java.net URLConnection setReadTimeout
public void setReadTimeout(int timeout)
From source file:org.infoglue.common.util.RemoteCacheUpdater.java
/** * This method post information to an URL and returns a string.It throws * an exception if anything goes wrong.// w ww . j a va 2 s. co m * (Works like most 'doPost' methods) * * @param urlAddress The address of the URL you would like to post to. * @param inHash The parameters you would like to post to the URL. * @return The result of the postToUrl method as a string. * @exception java.lang.Exception */ private String postToUrl(String urlAddress, Hashtable inHash) throws Exception { URL url = new URL(urlAddress); URLConnection urlConn = url.openConnection(); urlConn.setConnectTimeout(3000); urlConn.setReadTimeout(3000); urlConn.setAllowUserInteraction(false); urlConn.setDoOutput(true); urlConn.setDoInput(true); urlConn.setUseCaches(false); urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); PrintWriter printout = new PrintWriter(urlConn.getOutputStream(), true); String argString = ""; if (inHash != null) { argString = toEncodedString(inHash); } printout.print(argString); printout.flush(); printout.close(); InputStream inStream = null; inStream = urlConn.getInputStream(); InputStreamReader inStreamReader = new InputStreamReader(inStream); BufferedReader buffer = new BufferedReader(inStreamReader); StringBuffer strbuf = new StringBuffer(); String line; while ((line = buffer.readLine()) != null) { strbuf.append(line); } String readData = strbuf.toString(); buffer.close(); return readData; }
From source file:org.tinymediamanager.thirdparty.UpnpDevice.java
/** * Retrieves the properties and description of the UpnpDevice. * <p/>/*w ww .j a v a2 s.c o m*/ * Connects to the device's {@link #location} and parses the response to populate the fields of this class * * @throws SAXException * if an error occurs while parsing the request * @throws IOException * on communication errors * @see org.bitlet.weupnp.GatewayDeviceHandler */ public void loadDescription() throws SAXException, IOException { URLConnection urlConn = new URL(getLocation()).openConnection(); urlConn.setReadTimeout(HTTP_RECEIVE_TIMEOUT); XMLReader parser = XMLReaderFactory.createXMLReader(); parser.setContentHandler(new UpnpDeviceHandler(this)); parser.parse(new InputSource(urlConn.getInputStream())); /* fix urls */ String ipConDescURL; if (urlBase != null && urlBase.trim().length() > 0) { ipConDescURL = urlBase; } else { ipConDescURL = location; } int lastSlashIndex = ipConDescURL.indexOf('/', 7); if (lastSlashIndex > 0) { ipConDescURL = ipConDescURL.substring(0, lastSlashIndex); } sCPDURL = copyOrCatUrl(ipConDescURL, sCPDURL); controlURL = copyOrCatUrl(ipConDescURL, controlURL); controlURLCIF = copyOrCatUrl(ipConDescURL, controlURLCIF); presentationURL = copyOrCatUrl(ipConDescURL, presentationURL); }
From source file:ome.system.UpgradeCheck.java
/** * If the {@link #url} has been set to null or the empty string, then no * upgrade check will be performed (silently). If however the string is an * invalid URL, a warning will be printed. * // w w w. jav a 2s. co m * This method should <em>never</em> throw an exception. */ public void run() { // If null or empty, the upgrade check is disabled. if (url == null || url.length() == 0) { return; // EARLY EXIT! } StringBuilder query = new StringBuilder(); try { query.append(url); query.append("?version="); query.append(URLEncoder.encode(version, "UTF-8")); query.append(";os.name="); query.append(URLEncoder.encode(System.getProperty("os.name"), "UTF-8")); query.append(";os.arch="); query.append(URLEncoder.encode(System.getProperty("os.arch"), "UTF-8")); query.append(";os.version="); query.append(URLEncoder.encode(System.getProperty("os.version"), "UTF-8")); query.append(";java.runtime.version="); query.append(URLEncoder.encode(System.getProperty("java.runtime.version"), "UTF-8")); query.append(";java.vm.vendor="); query.append(URLEncoder.encode(System.getProperty("java.vm.vendor"), "UTF-8")); } catch (UnsupportedEncodingException uee) { // Internal issue set(null, uee); return; } URL _url; try { _url = new URL(query.toString()); } catch (Exception e) { set(null, e); log.error("Invalid URL: " + query.toString()); return; } BufferedInputStream bufIn = null; try { URLConnection conn = _url.openConnection(); conn.setUseCaches(false); conn.addRequestProperty("User-Agent", agent); conn.setConnectTimeout(timeout); conn.setReadTimeout(timeout); conn.connect(); log.debug("Attempting to connect to " + query); InputStream in = conn.getInputStream(); bufIn = new BufferedInputStream(in); StringBuilder sb = new StringBuilder(); while (true) { int data = bufIn.read(); if (data == -1) { break; } else { sb.append((char) data); } } String result = sb.toString(); if (result.length() == 0) { log.info("no update needed"); set(null, null); } else { log.warn("UPGRADE AVAILABLE:" + result); set(result, null); } } catch (UnknownHostException uhe) { log.error("Unknown host:" + url); set(null, uhe); } catch (IOException ioe) { log.error(String.format("Error reading from url: %s \"%s\"", query, ioe.getMessage())); set(null, ioe); } catch (Exception ex) { log.error("Unknown exception thrown on UpgradeCheck", ex); set(null, ex); } finally { Utils.closeQuietly(bufIn); } }
From source file:org.onebusaway.transit_data_federation.util.RestApiLibrary.java
public String getContentsOfUrlAsString(URL requestUrl) throws IOException { BufferedReader br = null;/*from ww w . ja v a2 s. co m*/ InputStream inStream = null; URLConnection conn = null; try { conn = requestUrl.openConnection(); conn.setConnectTimeout(connectionTimeout); conn.setReadTimeout(readTimeout); inStream = conn.getInputStream(); br = new BufferedReader(new InputStreamReader(inStream)); StringBuilder output = new StringBuilder(); int cp; while ((cp = br.read()) != -1) { output.append((char) cp); } return output.toString(); } catch (IOException ioe) { String url = requestUrl != null ? requestUrl.toExternalForm() : "url unavailable"; log.error("Error getting contents of url: " + url); throw ioe; } finally { try { if (br != null) br.close(); if (inStream != null) inStream.close(); } catch (IOException ioe2) { log.error("Error closing connection"); } } }
From source file:jp.go.nict.langrid.serviceexecutor.google.GoogleTranslation.java
@SuppressWarnings("unchecked") private String invokeTranslation(Language sourceLang, Language targetLang, String source) throws InvalidParameterException, ProcessFailedException { InputStream is = null;/*from www .j a v a 2 s .c om*/ try { URLConnection con = new URL(TRANSLATE_URL).openConnection(); con.setDoOutput(true); con.setReadTimeout(timeoutMillis); con.addRequestProperty("Referer", referer); writeParameters(con, sourceLang, targetLang, source); is = con.getInputStream(); String json = StreamUtil.readAsString(is, CharsetUtil.newUTF8Decoder()); try { TranslationResult result = JSON.decode(json, TranslationResult.class); ResponseData responseData = result.responseData; int status = result.responseStatus; String key = sourceLang.getCode() + ":" + targetLang.getCode(); if (status == 200) { langPairCache.putInCache(key, true); return StringEscapeUtils.unescapeHtml(responseData.translatedText.replaceAll("'", "'")); } else { String details = result.responseDetails; if (details.equals("invalid translation language pair")) { langPairCache.putInCache(key, false); languagePairValidator.get().getUniqueLanguagePair(Collections.EMPTY_LIST); } throw new ProcessFailedException(result.responseStatus + ": " + details); } } catch (JSONException e) { String message = "failed to read translated text: " + json; logger.log(Level.WARNING, message, e); throw new ProcessFailedException(message); } } catch (IOException e) { logger.log(Level.SEVERE, "failed to execute service.", e); throw new ProcessFailedException(e); } finally { if (is != null) { try { is.close(); } catch (IOException e) { } } } }
From source file:com.util.httpRecargas.java
public List<Recarga> getRecargas(String idAccount, String page, String max, String startDate, String endDate) { // System.out.println("OBTENER SOLO UN ARRAY DE CADENA JSON"); String myURL = "http://192.168.5.44/app_dev.php/cus/recharges/history/" + idAccount + ".json"; // System.out.println("Requested URL:" + myURL); StringBuilder sb = new StringBuilder(); URLConnection urlConn = null; InputStreamReader in = null;//from w w w . j a va 2 s .c o m try { URL url = new URL(myURL); urlConn = url.openConnection(); if (urlConn != null) { urlConn.setReadTimeout(60 * 1000); urlConn.setDoOutput(true); String data = URLEncoder.encode("page", "UTF-8") + "=" + URLEncoder.encode(page, "UTF-8"); data += "&" + URLEncoder.encode("max", "UTF-8") + "=" + URLEncoder.encode(max, "UTF-8"); data += "&" + URLEncoder.encode("startDate", "UTF-8") + "=" + URLEncoder.encode(startDate, "UTF-8"); data += "&" + URLEncoder.encode("endDate", "UTF-8") + "=" + URLEncoder.encode(endDate, "UTF-8"); System.out.println("los Datos a enviar por POST son " + data); try ( //obtenemos el flujo de escritura OutputStreamWriter wr = new OutputStreamWriter(urlConn.getOutputStream())) { //escribimos wr.write(data); wr.flush(); //cerramos la conexin } } if (urlConn != null && urlConn.getInputStream() != null) { in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset()); BufferedReader bufferedReader = new BufferedReader(in); if (bufferedReader != null) { int cp; while ((cp = bufferedReader.read()) != -1) { sb.append((char) cp); } bufferedReader.close(); } } in.close(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("Exception while calling URL:" + myURL, e); } String jsonResult = sb.toString(); System.out.println("DATOS ENVIADOS DEL SERVIDOR " + sb.toString()); // System.out.println("\n\n--------------------OBTENEMOS OBJETO JSON NATIVO DE LA PAGINA, USAMOS EL ARRAY DATA---------------------------\n\n"); JSONObject objJason = new JSONObject(jsonResult); // JSONArray dataJson = new JSONArray(); // dataJson = objJason.getJSONArray("data"); String jdata = objJason.optString("data"); String mensaje = objJason.optString("message"); System.out.println("\n MENSAJE DEL SERVIDOR " + mensaje); // System.out.println(" el objeto jdata es " + jdata); objJason = new JSONObject(jdata); // System.out.println("objeto normal 1 " + objJason.toString()); // jdata = objJason.optString("items"); // System.out.println("\n\n el objeto jdata es " + jdata); JSONArray jsonArray = new JSONArray(); Gson gson = new Gson(); //objJason = gson.t jsonArray = objJason.getJSONArray("items"); // System.out.println("\n\nEL ARRAY FINAL ES " + jsonArray.toString()); /* List<String> list = new ArrayList<String>(); for (int i = 0; i < jsonArray.length(); i++) { list.add(String.valueOf(i)); list.add(jsonArray.getJSONObject(i).getString("created_date")); list.add(jsonArray.getJSONObject(i).getString("description")); list.add(String.valueOf(jsonArray.getJSONObject(i).getInt("credit"))); list.add(jsonArray.getJSONObject(i).getString("before_balance")); list.add(jsonArray.getJSONObject(i).getString("after_balance")); } System.out.println("\n\nel array java contiene "+ list.toString()); */ List<Recarga> recargas = new ArrayList<Recarga>(); for (int i = 0; i < jsonArray.length(); i++) { Recarga recarga = new Recarga(); recarga.setNo(i); recarga.setFecha(jsonArray.getJSONObject(i).getString("created_date")); recarga.setDescripcion(jsonArray.getJSONObject(i).getString("description")); recarga.setMonto(String.valueOf(jsonArray.getJSONObject(i).getInt("credit"))); recarga.setSaldoAnterior(jsonArray.getJSONObject(i).getString("before_balance")); recarga.setSaldoPosterior(jsonArray.getJSONObject(i).getString("after_balance")); recargas.add(recarga); } for (int i = 0; i < recargas.size(); i++) { System.out.print("\n\nNo" + recargas.get(i).getNo()); System.out.print("\nFecna " + recargas.get(i).getFecha()); System.out.print("\nDescripcion " + recargas.get(i).getDescripcion()); System.out.print("\nMonto " + recargas.get(i).getMonto()); System.out.print("\nSaldo Anterior " + recargas.get(i).getSaldoAnterior()); System.out.print("\nSaldo Posterior" + recargas.get(i).getSaldoPosterior()); } return recargas; }
From source file:com.alfaariss.oa.authentication.remote.aselect.idp.storage.config.IDPConfigStorage.java
/** * @see com.alfaariss.oa.engine.idp.storage.configuration.AbstractConfigurationStorage#createIDP(com.alfaariss.oa.api.configuration.IConfigurationManager, org.w3c.dom.Element) *//* w ww .j a v a 2 s . co m*/ @Override protected IIDP createIDP(IConfigurationManager configManager, Element config) throws OAException { ASelectIDP oASelectIDP = null; try { String sServerID = configManager.getParam(config, "server_id"); if (sServerID == null) { _logger.error("No 'server_id' parameter found in configuration"); throw new OAException(SystemErrors.ERROR_CONFIG_READ); } String sOrganizationID = configManager.getParam(config, "id"); if (sOrganizationID == null) { _logger.error("No 'id' parameter found in configuration"); throw new OAException(SystemErrors.ERROR_CONFIG_READ); } String sFriendlyname = configManager.getParam(config, "friendlyname"); if (sFriendlyname == null) { _logger.error("No 'friendlyname' parameter found in configuration"); throw new OAException(SystemErrors.ERROR_CONFIG_READ); } String sURL = configManager.getParam(config, "url"); if (sURL == null) { _logger.error("No 'url' parameter found in configuration"); throw new OAException(SystemErrors.ERROR_CONFIG_READ); } URL urlTarget = null; try { urlTarget = new URL(sURL); } catch (MalformedURLException e) { _logger.error("Invalid 'url' parameter found in configuration: " + sURL); throw new OAException(SystemErrors.ERROR_CONFIG_READ); } try { URLConnection urlConnection = urlTarget.openConnection(); urlConnection.setConnectTimeout(3000); urlConnection.setReadTimeout(3000); urlConnection.connect(); } catch (IOException e) { _logger.warn("Could not connect to 'url' parameter found in configuration: " + sURL); } String sLevel = configManager.getParam(config, "level"); if (sLevel == null) { _logger.error("No 'level' parameter found in configuration"); throw new OAException(SystemErrors.ERROR_CONFIG_READ); } int iLevel; try { iLevel = Integer.parseInt(sLevel); } catch (NumberFormatException e) { _logger.error("Invalid 'level' parameter found in configuration, not a number: " + sLevel); throw new OAException(SystemErrors.ERROR_INIT); } String sCountry = configManager.getParam(config, "country"); if (sCountry == null) _logger.info("No optional 'country' parameter found in configuration"); String sLanguage = configManager.getParam(config, "language"); if (sLanguage == null) _logger.info("No optional 'language' parameter found in configuration"); boolean bDoSigning = false; String sSigning = configManager.getParam(config, "signing"); if (sSigning != null) { if (sSigning.equalsIgnoreCase("TRUE")) bDoSigning = true; else if (!sSigning.equalsIgnoreCase("FALSE")) { _logger.error("Invalid 'signing' parameter found in configuration, must be 'true' or 'false': " + sSigning); throw new OAException(SystemErrors.ERROR_INIT); } } boolean bASynchronousLogout = false; String sASynchronousLogout = configManager.getParam(config, "asynchronouslogout"); if (sASynchronousLogout != null) { if (sASynchronousLogout.equalsIgnoreCase("TRUE")) bASynchronousLogout = true; else if (!sASynchronousLogout.equalsIgnoreCase("FALSE")) { _logger.error( "Invalid 'asynchronouslogout' parameter found in configuration, must be 'true' or 'false': " + sASynchronousLogout); throw new OAException(SystemErrors.ERROR_INIT); } } boolean bSynchronousLogout = false; String sSynchronousLogout = configManager.getParam(config, "synchronouslogout"); if (sSynchronousLogout != null) { if (sSynchronousLogout.equalsIgnoreCase("TRUE")) bSynchronousLogout = true; else if (!sSynchronousLogout.equalsIgnoreCase("FALSE")) { _logger.error( "Invalid 'synchronouslogout' parameter found in configuration, must be 'true' or 'false': " + sSynchronousLogout); throw new OAException(SystemErrors.ERROR_INIT); } } boolean bSendArpTarget = false; String sSendArpTarget = configManager.getParam(config, "send_arp_target"); if (sSendArpTarget != null) { if (sSendArpTarget.equalsIgnoreCase("TRUE")) bSendArpTarget = true; else if (!sSendArpTarget.equalsIgnoreCase("FALSE")) { _logger.error( "Invalid 'send_arp_target' parameter found in configuration, must be 'true' or 'false': " + sSigning); throw new OAException(SystemErrors.ERROR_INIT); } } oASelectIDP = new ASelectIDP(sOrganizationID, sFriendlyname, sServerID, sURL, iLevel, bDoSigning, sCountry, sLanguage, bASynchronousLogout, bSynchronousLogout, bSendArpTarget); } catch (OAException e) { throw e; } catch (Exception e) { _logger.fatal("Internal error during create", e); throw new OAException(SystemErrors.ERROR_INTERNAL, e); } return oASelectIDP; }
From source file:org.voyanttools.trombone.input.source.UriInputSource.java
private URLConnection getURLConnection(URI uri, int readTimeoutMilliseconds, int connectTimeoutMilliseconds) throws IOException { URLConnection c; try {/*from w w w . j av a 2s . c o m*/ c = uri.toURL().openConnection(); } catch (MalformedURLException e) { throw new IllegalArgumentException("Attempt to use a malformed URL: " + uri, e); } c.addRequestProperty("User-Agent", "Mozilla/4.0 (compatible; Trombone)"); c.setReadTimeout(readTimeoutMilliseconds); c.setConnectTimeout(connectTimeoutMilliseconds); return c; }
From source file:fr.inria.atlanmod.neo4emf.neo4jresolver.runtimes.internal.Neo4jZippedInstaller.java
@Override public void performInstall(IProgressMonitor monitor, IPath dirPath) throws IOException { if (monitor == null) { monitor = new NullProgressMonitor(); }// ww w . j ava2s. c om InputStream urlStream = null; try { URL url = getUrl(); URLConnection connection = url.openConnection(); connection.setConnectTimeout(TIMEOUT); connection.setReadTimeout(TIMEOUT); int length = connection.getContentLength(); monitor.beginTask(NLS.bind("Reading from {1}", getVersion(), getUrl().toString()), length >= 0 ? length : IProgressMonitor.UNKNOWN); urlStream = connection.getInputStream(); ZipInputStream zipStream = new ZipInputStream(urlStream); byte[] buffer = new byte[1024 * 8]; long start = System.currentTimeMillis(); int total = length; int totalRead = 0; ZipEntry entry; float kBps = -1; while ((entry = zipStream.getNextEntry()) != null) { if (monitor.isCanceled()) break; String fullFilename = entry.getName(); IPath fullFilenamePath = new Path(fullFilename); int secsRemaining = (int) ((total - totalRead) / 1024 / kBps); String textRemaining = secsToText(secsRemaining); monitor.subTask(NLS.bind("{0} remaining. Reading {1}", textRemaining.length() > 0 ? textRemaining : "unknown time", StringUtils .abbreviateMiddle(fullFilenamePath.removeFirstSegments(1).toString(), "...", 45))); int entrySize = (int) entry.getCompressedSize(); OutputStream output = null; try { int len = 0; int read = 0; String action = null; if (jarFiles.contains(fullFilename)) { action = "Copying"; String filename = FilenameUtils.getName(fullFilename); output = new FileOutputStream(dirPath.append(filename).toOSString()); } else { action = "Skipping"; output = new NullOutputStream(); } int secs = (int) ((System.currentTimeMillis() - start) / 1000); kBps = (float) totalRead / 1024 / secs; while ((len = zipStream.read(buffer)) > 0) { if (monitor.isCanceled()) break; read += len; monitor.subTask(NLS.bind("{0} remaining. {1} {2} at {3}KB/s ({4}KB / {5}KB)", new Object[] { String.format("%s", textRemaining.length() > 0 ? textRemaining : "unknown time"), action, StringUtils.abbreviateMiddle( fullFilenamePath.removeFirstSegments(1).toString(), "...", 45), String.format("%,.1f", kBps), String.format("%,.1f", (float) read / 1024), String.format("%,.1f", (float) entry.getSize() / 1024) })); output.write(buffer, 0, len); } totalRead += entrySize; monitor.worked(entrySize); } finally { IOUtils.closeQuietly(output); } } } finally { IOUtils.closeQuietly(urlStream); monitor.done(); } }
From source file:jp.go.nict.langrid.serviceexecutor.google.GoogleTranslation.java
@SuppressWarnings("unchecked") private ArrayList<String> invokeBatchTranslation(Language sourceLang, Language targetLang, String[] sources) throws InvalidParameterException, ProcessFailedException { InputStream is = null;//ww w.ja v a 2s . c o m try { URLConnection con = new URL(TRANSLATE_URL).openConnection(); con.setDoOutput(true); con.setReadTimeout(timeoutMillis); con.addRequestProperty("Referer", referer); writeParameters(con, sourceLang, targetLang, sources); is = con.getInputStream(); String json = StreamUtil.readAsString(is, CharsetUtil.newUTF8Decoder()); try { BatchTranslationResult result = JSON.decode(json, BatchTranslationResult.class); int status = result.responseStatus; String key = sourceLang.getCode() + ":" + targetLang.getCode(); if (status == 200) { langPairCache.putInCache(key, true); ArrayList<String> resultArray = new ArrayList<String>(); for (TranslationResult r : result.responseData) { resultArray.add(StringEscapeUtils .unescapeHtml(r.responseData.translatedText.replaceAll("'", "'"))); } return resultArray; } else { String details = result.responseDetails; if (details.equals("invalid translation language pair")) { langPairCache.putInCache(key, false); languagePairValidator.get().getUniqueLanguagePair(Collections.EMPTY_LIST); } throw new ProcessFailedException(result.responseStatus + ": " + details); } } catch (JSONException e) { String message = "failed to read translated text: " + json; logger.log(Level.WARNING, message, e); throw new ProcessFailedException(message); } } catch (IOException e) { logger.log(Level.SEVERE, "failed to execute service.", e); throw new ProcessFailedException(e); } finally { if (is != null) { try { is.close(); } catch (IOException e) { } } } }