List of usage examples for java.net URLConnection setConnectTimeout
public void setConnectTimeout(int timeout)
From source file:com.pa165.ddtroops.console.client.Application.java
/** * Update role in database/* ww w . j av a2 s. co m*/ * @param id role id * @param name role name * @param description role desc * @param energy role energy * @param attack role attack * @param defense role defense */ private static void updateRole(String id, String name, String description, String energy, String attack, String defense) { try { RoleDTO r = new RoleDTO(); r.setId(Long.parseLong(id)); r.setName(name); r.setDescription(description); r.setEnergy(Integer.parseInt(energy)); r.setAttack(Integer.parseInt(attack)); r.setDefense(Integer.parseInt(defense)); JSONObject jsonObject = new JSONObject(r); URL url = new URL("http://localhost:8080/pa165/rest-jersey-server/role/put"); URLConnection connection = url.openConnection(); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "application/json"); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); out.write(jsonObject.toString()); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); while (in.readLine() != null) { } System.out.println("Updated role with id: " + r.getId()); System.out.println(); in.close(); } catch (Exception e) { System.out.println("\nError when updating role"); System.out.println(e); } }
From source file:org.y20k.transistor.helpers.MetadataHelper.java
public static void prepareMetadata(final String mStreamUri, final Station mStation, final Context mContext) throws IOException { metaDataThread = new Thread(new Runnable() { @Override/*from w w w .j av a2 s .c o m*/ public void run() { try { URLConnection connection = new URL(mStreamUri).openConnection(); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); connection.setRequestProperty("Icy-MetaData", "1"); connection.connect(); InputStream in = connection.getInputStream(); byte buf[] = new byte[16384]; // one second of 128kbit stream int count = 0; int total = 0; int metadataSize = 0; final int metadataOffset = connection.getHeaderFieldInt("icy-metaint", 0); int bitRate = Math.max(connection.getHeaderFieldInt("icy-br", 128), 32); LogHelper.v(LOG_TAG, "createProxyConnection: connected, icy-metaint " + metadataOffset + " icy-br " + bitRate); Thread thisThread = Thread.currentThread(); int thisThreadCounter = 0; while (true && metaDataThread == thisThread) { if (thisThreadCounter > 20) { //only try 20 times and terminate thread to be sure getting metadata LogHelper.v(LOG_TAG, "thisThreadCounter: Upper Break at thisThreadCounter=" + thisThreadCounter); break; } thisThreadCounter++; count = Math.min(in.available(), buf.length); if (count <= 0) { count = Math.min(bitRate * 64, buf.length); // buffer half-second of stream data } if (metadataOffset > 0) { count = Math.min(count, metadataOffset - total); } count = in.read(buf, 0, count); if (count == 0) { continue; } if (count < 0) { LogHelper.v(LOG_TAG, "thisThreadCounter: Break at -count < 0- thisThreadCounter=" + thisThreadCounter); break; } total += count; if (metadataOffset > 0 && total >= metadataOffset) { // read metadata total = 0; count = in.read(); if (count < 0) { LogHelper.v(LOG_TAG, "thisThreadCounter: Break2 at -count < 0- thisThreadCounter=" + thisThreadCounter); break; } count *= 16; metadataSize = count; if (metadataSize == 0) { continue; } // maximum metadata length is 4080 bytes total = 0; while (total < metadataSize) { count = in.read(buf, total, count); if (count < 0) { LogHelper.v(LOG_TAG, "thisThreadCounter: Break3 at -count < 0- thisThreadCounter=" + thisThreadCounter); break; } if (count == 0) { continue; } total += count; count = metadataSize - total; } total = 0; String[] metadata = new String(buf, 0, metadataSize, StandardCharsets.UTF_8).split(";"); for (String s : metadata) { if (s.indexOf(TransistorKeys.SHOUTCAST_STREAM_TITLE_HEADER) == 0 && s .length() >= TransistorKeys.SHOUTCAST_STREAM_TITLE_HEADER.length() + 1) { //handleMetadataString(s.substring(TransistorKeys.SHOUTCAST_STREAM_TITLE_HEADER.length(), s.length() - 1)); String metadata2 = s.substring( TransistorKeys.SHOUTCAST_STREAM_TITLE_HEADER.length(), s.length() - 1); if (metadata2 != null && metadata2.length() > 0) { // send local broadcast Intent i = new Intent(); i.setAction(TransistorKeys.ACTION_METADATA_CHANGED); i.putExtra(TransistorKeys.EXTRA_METADATA, metadata2); i.putExtra(TransistorKeys.EXTRA_STATION, mStation); LocalBroadcastManager.getInstance(mContext).sendBroadcast(i); // save metadata to shared preferences SharedPreferences settings = PreferenceManager .getDefaultSharedPreferences(mContext); SharedPreferences.Editor editor = settings.edit(); editor.putString(TransistorKeys.PREF_STATION_METADATA, metadata2); editor.apply(); //done getting the metadata LogHelper.v(LOG_TAG, "thisThreadCounter: Lower Break at thisThreadCounter=" + thisThreadCounter); break; } // break; } } } } } catch (IOException e) { e.printStackTrace(); LogHelper.e(LOG_TAG, e.getMessage()); } } }); metaDataThread.start(); }
From source file:io.bitsquare.common.util.Utilities.java
public static String readTextFileFromServer(String url, String userAgent) throws IOException { URLConnection connection = URI.create(url).toURL().openConnection(); connection.setDoOutput(true);//from w ww . j av a2 s . co m connection.setUseCaches(false); connection.setConnectTimeout((int) TimeUnit.SECONDS.toMillis(10)); connection.addRequestProperty("User-Agent", userAgent); connection.connect(); try (InputStream inputStream = connection.getInputStream()) { return CharStreams.toString(new InputStreamReader(inputStream, Charsets.UTF_8)); } catch (IOException e) { e.printStackTrace(); throw e; } }
From source file:net.pms.configuration.DownloadPlugins.java
public static ArrayList<DownloadPlugins> downloadList() { ArrayList<DownloadPlugins> res = new ArrayList<>(); if (!configuration.getExternalNetwork()) { // Do not try to get the plugin list if there is no // external network. return res; }//w w w. j av a2 s .com try { URL u = new URL(PLUGIN_LIST_URL); URLConnection connection = u.openConnection(); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); parse_list(res, in, false); File test = new File(configuration.getPluginDirectory() + File.separator + PLUGIN_TEST_FILE); if (test.exists()) { in = new BufferedReader(new InputStreamReader(new FileInputStream(test))); parse_list(res, in, true); } } catch (IOException e) { } return res; }
From source file:org.lobid.lodmill.PipeLobidOrganisationEnrichment.java
private static BufferedReader getUrlContent(final URL url) throws IOException { URLConnection urlConnection = url.openConnection(); urlConnection.setConnectTimeout(URL_CONNECTION_TIMEOUT); LOG.debug("Lookup url:" + url); return new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); }
From source file:org.openhab.binding.fems.FEMSCore.java
/** * Initialize FEMS/FEMSmonitor system//from w w w . j a va 2s . c om */ private static void init() { int returnCode = 0; try { log.info("FEMS Initialization"); // start IO Agent Constants.IO_AGENT.start(); // init LCD display Constants.IO_AGENT.setLcdText(true, "FEMS Selbsttest"); // Init runtime variables Runtime rt = Runtime.getRuntime(); Process proc; InitStatus initStatus = new InitStatus(); try { // check for valid ip address InetAddress ip = Tools.getIPaddress(); if (ip == null) { try { proc = rt.exec("/sbin/dhclient eth0"); proc.waitFor(); ip = Tools.getIPaddress(); /* try again */ if (ip == null) { /* still no IP */ throw new IPException(); } } catch (IOException | InterruptedException e) { throw new IPException(e.getMessage()); } } log.info("IP: " + ip.getHostAddress()); initStatus.setIp(true); Constants.IO_AGENT.setLcdText(initStatus + " IP ok "); Constants.IO_AGENT.handleCommand(Constants.UserLED_1, OnOffType.ON); // check time if (Tools.isDateValid()) { /* date is valid, so we check internet access only */ log.info("Date ok: " + Constants.LONG_DATE_FORMAT.format(new Date())); try { URL url = new URL("https://fenecon.de"); URLConnection con = url.openConnection(); con.setConnectTimeout(5000); con.getContent(); } catch (IOException e) { throw new InternetException(e.getMessage()); } } else { log.info("Date not ok: " + Constants.LONG_DATE_FORMAT.format(new Date())); try { proc = rt.exec( "/usr/sbin/ntpdate -b -u fenecon.de 0.pool.ntp.org 1.pool.ntp.org 2.pool.ntp.org 3.pool.ntp.org"); proc.waitFor(); if (!Tools.isDateValid()) { // try one more time proc = rt.exec( "/usr/sbin/ntpdate -b -u fenecon.de 0.pool.ntp.org 1.pool.ntp.org 2.pool.ntp.org 3.pool.ntp.org"); proc.waitFor(); if (!Tools.isDateValid()) { throw new InternetException( "Wrong Date: " + Constants.LONG_DATE_FORMAT.format(new Date())); } } log.info("Date now ok: " + Constants.LONG_DATE_FORMAT.format(new Date())); } catch (IOException | InterruptedException e) { throw new InternetException(e.getMessage()); } } log.info("Internet access is available"); initStatus.setInternet(true); Constants.IO_AGENT.setLcdText(initStatus + " Internet ok"); Constants.IO_AGENT.handleCommand(Constants.UserLED_2, OnOffType.ON); // test modbus if (isModbusWorking(log, ess)) { log.info("Modbus is ok"); initStatus.setModbus(true); Constants.IO_AGENT.setLcdText(initStatus + " RS485 ok "); Constants.IO_AGENT.handleCommand(Constants.UserLED_3, OnOffType.ON); } else { if (debug) { // if we are in debug mode: ignore RS485-errors log.info("Ignore RS485-Error"); } else { throw new RS485Exception(); } } // Exit message log.info("Finished without error"); Constants.IO_AGENT.setLcdText(initStatus + " erfolgreich"); // announce systemd finished log.info("Announce systemd: ready"); try { proc = rt.exec("/bin/systemd-notify --ready"); proc.waitFor(); } catch (IOException | InterruptedException e) { log.error(e.getMessage()); } } catch (FEMSException e) { log.error(e.getMessage()); log.error("Finished with error"); Constants.IO_AGENT.setLcdText(initStatus + " " + e.getMessage()); returnCode = 1; } // Check if Yaler is active if (FEMSYaler.getFEMSYaler().isActive()) { log.info("Yaler is activated"); } else { log.info("Yaler is deactivated"); } // Send message if (apikey == null) { log.error("Apikey is not available"); } else { // start Agents Constants.ONLINE_MONITORING_AGENT.setApikey(apikey); Constants.ONLINE_MONITORING_AGENT.start(); Constants.ONLINE_MONITORING_CACHE_AGENT.setApikey(apikey); Constants.ONLINE_MONITORING_CACHE_AGENT.start(); Constants.ONLINE_MONITORING_AGENT.sendSystemMessage(log.getLog()); } // start system update log.info("Start system update"); try { proc = rt.exec("/usr/bin/fems-autoupdate"); proc.waitFor(); } catch (IOException | InterruptedException e) { log.error(e.getMessage()); } Constants.IO_AGENT.handleCommand(Constants.UserLED_4, OnOffType.ON); } catch (Throwable e) { // Catch everything else returnCode = 2; StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); log.error("Critical error: " + sw.toString()); e.printStackTrace(); Constants.ONLINE_MONITORING_AGENT.sendSystemMessage(log.getLog()); // try to send log } try { Thread.sleep(2000); // give the agents some time to try sending } catch (InterruptedException e) { e.printStackTrace(); } // Stop agents Constants.ONLINE_MONITORING_AGENT.interrupt(); try { Constants.ONLINE_MONITORING_AGENT.join(); } catch (InterruptedException e) { e.printStackTrace(); } Constants.ONLINE_MONITORING_CACHE_AGENT.interrupt(); try { Constants.ONLINE_MONITORING_CACHE_AGENT.join(); } catch (InterruptedException e) { e.printStackTrace(); } Constants.IO_AGENT.interrupt(); try { Constants.IO_AGENT.join(); } catch (InterruptedException e) { e.printStackTrace(); } // Exit System.exit(returnCode); }
From source file:com.ibuildapp.romanblack.CataloguePlugin.utils.Utils.java
/** * download file url and save it/*from w ww . j a v a2s . c om*/ * * @param url */ public static String downloadFile(String url) { int BYTE_ARRAY_SIZE = 1024; int CONNECTION_TIMEOUT = 30000; int READ_TIMEOUT = 30000; // downloading cover image and saving it into file try { URL imageUrl = new URL(URLDecoder.decode(url)); URLConnection conn = imageUrl.openConnection(); conn.setConnectTimeout(CONNECTION_TIMEOUT); conn.setReadTimeout(READ_TIMEOUT); BufferedInputStream bis = new BufferedInputStream(conn.getInputStream()); File resFile = new File( Statics.moduleCachePath + File.separator + com.appbuilder.sdk.android.Utils.md5(url)); if (!resFile.exists()) { resFile.createNewFile(); } FileOutputStream fos = new FileOutputStream(resFile); int current = 0; byte[] buf = new byte[BYTE_ARRAY_SIZE]; Arrays.fill(buf, (byte) 0); while ((current = bis.read(buf, 0, BYTE_ARRAY_SIZE)) != -1) { fos.write(buf, 0, current); Arrays.fill(buf, (byte) 0); } bis.close(); fos.flush(); fos.close(); Log.d("", ""); return resFile.getAbsolutePath(); } catch (SocketTimeoutException e) { return null; } catch (IllegalArgumentException e) { return null; } catch (Exception e) { return null; } }
From source file:jeeves.xlink.Processor.java
/** * Resolves an xlink//ww w . ja v a 2 s . co m */ public static synchronized Element resolveXLink(String uri, String idSearch, ServiceContext srvContext) throws IOException, JDOMException, CacheException { cleanFailures(); if (failures.size() > MAX_FAILURES) { throw new RuntimeException("There have been " + failures.size() + " timeouts resolving xlinks in the last " + ELAPSE_TIME + " ms"); } Element remoteFragment = null; try { // TODO-API: Support local protocol on /api/registries/ if (uri.startsWith(XLink.LOCAL_PROTOCOL)) { SpringLocalServiceInvoker springLocalServiceInvoker = srvContext .getBean(SpringLocalServiceInvoker.class); remoteFragment = (Element) springLocalServiceInvoker.invoke(uri); } else { // Avoid references to filesystem if (uri.toLowerCase().startsWith("file://")) { return null; } uri = uri.replaceAll("&+", "&"); String mappedURI = mapURI(uri); JeevesJCS xlinkCache = JeevesJCS.getInstance(XLINK_JCS); remoteFragment = (Element) xlinkCache.getFromGroup(uri.toLowerCase(), mappedURI); if (remoteFragment == null) { Log.info(Log.XLINK_PROCESSOR, "cache MISS on " + uri.toLowerCase()); URL url = new URL(uri.replaceAll("&", "&")); URLConnection conn = url.openConnection(); conn.setConnectTimeout(1000); BufferedInputStream in = new BufferedInputStream(conn.getInputStream()); try { remoteFragment = Xml.loadStream(in); if (Log.isDebugEnabled(Log.XLINK_PROCESSOR)) Log.debug(Log.XLINK_PROCESSOR, "Read:\n" + Xml.getString(remoteFragment)); } finally { in.close(); } } else { Log.debug(Log.XLINK_PROCESSOR, "cache HIT on " + uri.toLowerCase()); } if (remoteFragment != null && !remoteFragment.getName().equalsIgnoreCase("error")) { xlinkCache.putInGroup(uri.toLowerCase(), mappedURI, remoteFragment); if (Log.isDebugEnabled(Log.XLINK_PROCESSOR)) Log.debug(Log.XLINK_PROCESSOR, "cache miss for " + uri); } else { return null; } } } catch (Exception e) { // MalformedURLException, IOException synchronized (Processor.class) { failures.add(System.currentTimeMillis()); } Log.error(Log.XLINK_PROCESSOR, "Failed on " + uri, e); } // search for and return only the xml fragment that has @id=idSearch Element res = null; if (idSearch != null) { String xpath = "*//*[@id='" + idSearch + "']"; try { res = Xml.selectElement(remoteFragment, xpath); if (res != null) { res = (Element) res.clone(); res.removeAttribute("id"); } } catch (Exception e) { Log.warning(Log.XLINK_PROCESSOR, "Failed to search for remote fragment using " + xpath + ", error" + e.getMessage()); return null; } } else { if (remoteFragment == null) { return null; } else { res = (Element) remoteFragment.clone(); } } if (Log.isDebugEnabled(Log.XLINK_PROCESSOR)) Log.debug(Log.XLINK_PROCESSOR, "Read:" + Xml.getString(res)); return res; }
From source file:com.viettel.dms.download.DownloadFile.java
/** * Download file with urlConnection//w w w . j ava 2s. c om * @author : BangHN * since : 1.0 */ public static void downloadWithURLConnection(String url, File output, File tmpDir) { BufferedOutputStream os = null; BufferedInputStream is = null; File tmp = null; try { VTLog.i("Download ZIPFile", "Downloading url :" + url); tmp = File.createTempFile("download", ".tmp", tmpDir); URL urlDownload = new URL(url); URLConnection cn = urlDownload.openConnection(); cn.addRequestProperty("session", HTTPClient.sessionID); cn.setConnectTimeout(CONNECT_TIMEOUT); cn.setReadTimeout(READ_TIMEOUT); cn.connect(); is = new BufferedInputStream(cn.getInputStream()); os = new BufferedOutputStream(new FileOutputStream(tmp)); //cp nht dung lng tp tin request fileSize = cn.getContentLength(); //vn c tr?ng hp khng c ContentLength if (fileSize < 0) { //mc nh = 4 MB fileSize = 4 * 1024 * 1024; } copyStream(is, os); tmp.renameTo(output); tmp = null; } catch (IOException e) { ServerLogger.sendLog("Download ZIPFile", e.getMessage() + "\n" + e.toString() + "\n" + url, false, TabletActionLogDTO.LOG_EXCEPTION); VTLog.e("UnexceptionLog", VNMTraceUnexceptionLog.getReportFromThrowable(e)); throw new RuntimeException(e); } catch (Exception e) { VTLog.e("UnexceptionLog", VNMTraceUnexceptionLog.getReportFromThrowable(e)); ServerLogger.sendLog("Download ZIPFile", e.getMessage() + "\n" + e.toString() + "\n" + url, false, TabletActionLogDTO.LOG_EXCEPTION); throw new RuntimeException(e); } finally { if (tmp != null) { try { tmp.delete(); tmp = null; } catch (Exception ignore) { ; } } if (is != null) { try { is.close(); is = null; } catch (Exception ignore) { ; } } if (os != null) { try { os.close(); os = null; } catch (Exception ignore) { ; } } } }
From source file:org.spoutcraft.launcher.rest.RestAPI.java
public static <T extends RestObject> T getRestObject(Class<T> restObject, String url) throws RestfulAPIException { InputStream stream = null;//from w ww.jav a2 s. co m try { URLConnection conn = new URL(url).openConnection(); conn.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"); conn.setConnectTimeout(15000); conn.setReadTimeout(15000); stream = conn.getInputStream(); T result = mapper.readValue(stream, restObject); if (result.hasError()) { throw new RestfulAPIException("Error in json response: " + result.getError()); } return result; } catch (SocketTimeoutException e) { throw new RestfulAPIException("Timed out accessing URL [" + url + "]", e); } catch (IOException e) { throw new RestfulAPIException("Error accessing URL [" + url + "]", e); } finally { IOUtils.closeQuietly(stream); } }