List of usage examples for java.net URLConnection setConnectTimeout
public void setConnectTimeout(int timeout)
From source file:org.opennms.netmgt.provision.detector.simple.client.DominoIIOPClient.java
/** * @param hostAddress/*from w w w . j av a 2s. c o m*/ * @param port * @return */ private boolean retrieveIORText(final String hostAddress, final int port, final int timeout) throws IOException { String IOR = ""; final URL u = new URL("http://" + hostAddress + ":" + port + "/diiop_ior.txt"); try { final URLConnection conn = u.openConnection(); conn.setConnectTimeout(timeout); conn.setReadTimeout(timeout); InputStreamReader isr = null; BufferedReader br = null; try { isr = new InputStreamReader(conn.getInputStream()); br = new BufferedReader(isr); boolean done = false; while (!done) { final String line = br.readLine(); if (line == null) { // end of stream done = true; } else { IOR += line; if (IOR.startsWith("IOR:")) { // the IOR does not span a line, so we're done done = true; } } } } finally { IOUtils.closeQuietly(br); IOUtils.closeQuietly(isr); } } catch (final SocketException e) { LOG.warn("Unable to connect to {}", u, e); } if (!IOR.startsWith("IOR:")) return false; return true; }
From source file:com.adito.rss.Feed.java
void load() throws IOException, FeedException { if (log.isInfoEnabled()) { log.info("Retrieving RSS feeds from " + url); }/*from w w w. j a v a2 s . c o m*/ URLConnection conx = url.openConnection(); conx.setConnectTimeout(Feed.CONNECT_TIMEOUT); conx.setReadTimeout(Feed.READ_TIMEOUT); InputStream inputStream = null; try { inputStream = conx.getInputStream(); status = STATUS_LOADING; feed = input.build(new XmlReader(inputStream)); if (log.isInfoEnabled()) log.info("Retrieved feed " + url); status = STATUS_LOADED; } catch (IOException e) { status = STATUS_FAILED_TO_LOAD; throw e; } catch (FeedException e) { status = STATUS_FAILED_TO_LOAD; throw e; } finally { Util.closeStream(inputStream); } }
From source file:com.netflix.iep.dynprop.RemoteConfigurationSource.java
private Properties getProperties() throws IOException { AbstractConfiguration config = ConfigurationManager.getConfigInstance(); String vip = config.getString(VIP, "atlas_archaius-main:7001"); List<String> hosts = getHostsForVip(vip, config.getBoolean(USE_IP, false)); int numAttempts = config.getInt(NUM_RETRIES, 2) + 1; for (int i = 1; i <= numAttempts; ++i) { String host = hosts.get(i % hosts.size()); String url = "http://" + host + "/api/v1/property" + "?asg=" + getAsgName() + "&instanceId=" + getInstanceId() + "&zone=" + getZone(); logger.debug("attempt {} of {}, requesting properties from: {}", i, numAttempts, url); try {/* w w w .j a v a 2s . c om*/ URLConnection con = new URL(url).openConnection(); con.setConnectTimeout(config.getInt(CONNECT_TIMEOUT, 1000)); con.setReadTimeout(config.getInt(READ_TIMEOUT, 5000)); Properties props = new Properties(); try (InputStream in = con.getInputStream()) { props.load(in); } logger.debug("fetched {} properties from: {}", props.size(), url); return props; } catch (IOException e) { String msg = String.format("attempt %d of %d failed, url: %s", i, numAttempts, url); if (i == numAttempts) { logger.error(msg, e); throw e; } else { logger.warn(msg, e); } } } // Shouldn't get here throw new IllegalStateException("failed to get properties"); }
From source file:org.intermine.api.mines.HttpRequester.java
@Override public BufferedReader requestURL(final String urlString, final ContentType contentType) { BufferedReader reader = null; OutputStreamWriter writer = null; // TODO: when all friendly mines support mimetype formats then we can remove this. String suffix = "?format=" + contentType.getFormat(); try {//from w ww .ja v a2 s. c om URL url = new URL(StringUtils.substringBefore(urlString, "?") + suffix); URLConnection conn = url.openConnection(); conn.addRequestProperty("Accept", contentType.getMimeType()); conn.setConnectTimeout(timeout * 1000); // conn accepts millisecond timeout. if (urlString.contains("?")) { // POST String queryString = StringUtils.substringAfter(urlString, "?"); conn.setDoOutput(true); writer = new OutputStreamWriter(conn.getOutputStream()); writer.write(queryString); writer.flush(); LOG.info("FriendlyMine URL (POST) " + urlString); } reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); } catch (Exception e) { throw new RuntimeException("Unable to access " + urlString + " exception: " + e.getMessage()); } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { LOG.error("Error sending POST request", e); } } } return reader; }
From source file:com.gmail.tracebachi.DeltaSkins.Shared.MojangApi.java
private HttpURLConnection openSkinConnection(String uuid) throws IOException { URL url = new URL(SKIN_ADDR + uuid + "?unsigned=false"); URLConnection connection = url.openConnection(); connection.setConnectTimeout(CONNECT_TIMEOUT); connection.setReadTimeout(READ_TIMEOUT); connection.setDoInput(true);//from ww w . j a va2 s.c o m connection.setUseCaches(false); return (HttpURLConnection) connection; }
From source file:com.gmail.tracebachi.DeltaSkins.Shared.MojangApi.java
private HttpURLConnection openNameToIdConnection() throws IOException { URL url = new URL(NAMES_TO_IDS_ADDR); URLConnection connection = url.openConnection(); connection.setConnectTimeout(CONNECT_TIMEOUT); connection.setReadTimeout(READ_TIMEOUT); connection.setDoInput(true);//from www . j av a2 s .co m connection.setDoOutput(true); connection.setUseCaches(false); return (HttpURLConnection) connection; }
From source file:org.orekit.data.NetworkCrawler.java
/** Get the stream to read from the remote URL. * @param url url to read from// ww w .j ava 2s . c o m * @return stream to read the content of the URL * @throws IOException if the URL cannot be opened for reading */ private InputStream getStream(final URL url) throws IOException { final URLConnection connection = url.openConnection(); connection.setConnectTimeout(timeout); return connection.getInputStream(); }
From source file:dk.dma.vessel.track.store.AisStoreClient.java
public List<PastTrackPos> getPastTrack(int mmsi, Integer minDist, Duration age) { // Determine URL age = age != null ? age : Duration.parse(pastTrackTtl); minDist = minDist == null ? Integer.valueOf(pastTrackMinDist) : minDist; ZonedDateTime now = ZonedDateTime.now(); String from = now.format(DateTimeFormatter.ISO_INSTANT); ZonedDateTime end = now.minus(age); String to = end.format(DateTimeFormatter.ISO_INSTANT); String interval = String.format("%s/%s", to, from); String url = String.format("%s?mmsi=%d&interval=%s", aisViewUrl, mmsi, interval); final List<PastTrackPos> track = new ArrayList<>(); try {/*from ww w .ja v a 2s .c o m*/ long t0 = System.currentTimeMillis(); // TEST url = url + "&filter=" + URLEncoder.encode("(s.country not in (GBR)) & (s.region!=808)", "UTF-8"); // Set up a few timeouts and fetch the attachment URLConnection con = new URL(url).openConnection(); con.setConnectTimeout(10 * 1000); // 10 seconds con.setReadTimeout(60 * 1000); // 1 minute if (!StringUtils.isEmpty(aisAuthHeader)) { con.setRequestProperty("Authorization", aisAuthHeader); } try (InputStream in = con.getInputStream(); BufferedInputStream bin = new BufferedInputStream(in)) { AisReader aisReader = AisReaders.createReaderFromInputStream(bin); aisReader.registerPacketHandler(new Consumer<AisPacket>() { @Override public void accept(AisPacket p) { AisMessage message = p.tryGetAisMessage(); if (message == null || !(message instanceof IVesselPositionMessage)) { return; } VesselTarget target = new VesselTarget(); target.merge(p, message); if (!target.checkValidPos()) { return; } track.add(new PastTrackPos(target.getLat(), target.getLon(), target.getCog(), target.getSog(), target.getLastPosReport())); } }); aisReader.start(); try { aisReader.join(); } catch (InterruptedException e) { return null; } } LOG.info(String.format("Read %d past track positions in %d ms", track.size(), System.currentTimeMillis() - t0)); } catch (IOException e) { LOG.error("Failed to make REST query: " + url); throw new InternalError("REST endpoint failed"); } LOG.info("AisStore returned track with " + track.size() + " points"); return PastTrack.downSample(track, minDist, age.toMillis()); }
From source file:com.example.chengcheng.network.httpstacks.HttpUrlConnStack.java
private HttpURLConnection createUrlConnection(String url) throws IOException { URL newURL = new URL(url); URLConnection urlConnection = newURL.openConnection(); urlConnection.setConnectTimeout(mConfig.connTimeOut); urlConnection.setReadTimeout(mConfig.soTimeOut); urlConnection.setDoInput(true);/*from w w w . java 2 s . co m*/ urlConnection.setUseCaches(false); return (HttpURLConnection) urlConnection; }
From source file:com.mstiles92.plugins.stileslib.updates.UpdateChecker.java
/** * The task to be run by the Bukkit scheduler that finds the latest published version on BukkitDev. *//*from ww w .ja v a 2s .co m*/ @Override public void run() { try { URL url = new URL("https://api.curseforge.com/servermods/files?projectIds=" + curseProjectId); URLConnection connection = url.openConnection(); connection.setConnectTimeout(5000); connection.setReadTimeout(10000); connection.addRequestProperty("User-Agent", plugin.getName() + " (by mstiles92)"); InputStream stream = connection.getInputStream(); JSONParser parser = new JSONParser(); Object o = parser.parse(new InputStreamReader(stream)); stream.close(); JSONArray array = (JSONArray) o; if (array.size() > 0) { JSONObject latest = (JSONObject) array.get(array.size() - 1); latestVersion = (String) latest.get("name"); latestVersion = latestVersion.substring(1, latestVersion.length()); updateAvailable = isNewerVersion(latestVersion); if (updateAvailable) { plugin.getLogger().info("Update available! New version: " + latestVersion); plugin.getLogger() .info("More information available at http://dev.bukkit.org/bukkit-plugins/" + slug); } } } catch (IOException | ParseException | ClassCastException e) { plugin.getLogger() .info("Unable to check for updates. Will try again later. Error message: " + e.getMessage()); } }