List of usage examples for java.net URLConnection setReadTimeout
public void setReadTimeout(int timeout)
From source file:org.niord.core.mail.CachedUrlDataSource.java
/** * Checks if the data is cached. Otherwise the URL data is loaded and cached * @return the URL data/* ww w . j a v a2 s. c om*/ */ protected synchronized CachedUrlData loadData() { // Check if the attachment has been loaded already if (data != null) { return data; } // Check if the attachment is stored in the global attachment cache if (cache != null && cache.containsKey(url)) { data = cache.get(url); return data; } data = new CachedUrlData(); data.setUrl(url); try { // Resolve the name from the URL path String name = url.getPath(); if (name.contains("/")) { name = name.substring(name.lastIndexOf("/") + 1); } data.setName(name); URLConnection urlc = url.openConnection(); // give it 15 seconds to respond urlc.setReadTimeout(15 * 1000); // Fetch the content type from the header data.setContentType(urlc.getHeaderField("Content-Type")); // Load the content try (InputStream in = urlc.getInputStream()) { data.setContent(IOUtils.toByteArray(in)); } } catch (Exception ex) { // We don't really want to fail the mail if an attachment fails... log.warn("Silently failed loading mail attachment from " + url); } // Cache the result if (cache != null) { cache.put(url, data); } return data; }
From source file:org.apache.cayenne.rop.http.HttpROPConnector.java
protected InputStream doRequest(Map<String, String> params) throws IOException { URLConnection connection = new URL(url).openConnection(); if (readTimeout != null) { connection.setReadTimeout(readTimeout.intValue()); }/* ww w. ja va 2 s. c om*/ addAuthHeader(connection); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("charset", "utf-8"); try (OutputStream output = connection.getOutputStream()) { output.write(ROPUtil.getParamsAsString(params).getBytes(StandardCharsets.UTF_8)); output.flush(); } return connection.getInputStream(); }
From source file:org.apache.cayenne.rop.http.HttpROPConnector.java
protected InputStream doRequest(byte[] data) throws IOException { URLConnection connection = new URL(url).openConnection(); if (readTimeout != null) { connection.setReadTimeout(readTimeout.intValue()); }//w w w. j a v a 2 s . c o m addAuthHeader(connection); addSessionCookie(connection); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "application/octet-stream"); if (data != null) { try (OutputStream output = connection.getOutputStream()) { output.write(data); output.flush(); } } return connection.getInputStream(); }
From source file:util.io.IOUtilities.java
/** * Originally copied from javax.swing.JEditorPane. * <p>/*from w w w . ja v a2s . c o m*/ * Fetches a stream for the given URL, which is about to * be loaded by the <code>setPage</code> method. By * default, this simply opens the URL and returns the * stream. This can be reimplemented to do useful things * like fetch the stream from a cache, monitor the progress * of the stream, etc. * <p> * This method is expected to have the the side effect of * establishing the content type, and therefore setting the * appropriate <code>EditorKit</code> to use for loading the stream. * <p> * If this the stream was an http connection, redirects * will be followed and the resulting URL will be set as * the <code>Document.StreamDescriptionProperty</code> so that relative * URL's can be properly resolved. * * @param page the URL of the page * @param followRedirects Follow redirects. * @param timeout The read timeout. * @param userName The user name to use for the connection. * @param userPassword The password to use for the connection. * @throws IOException if something went wrong. * @return a stream reading data from the specified URL. */ public static InputStream getStream(URL page, boolean followRedirects, int timeout, String userName, String userPassword) throws IOException { URLConnection conn = page.openConnection(); if (userName != null && userPassword != null) { String password = userName + ":" + userPassword; String encodedPassword = new String(Base64.encodeBase64(password.getBytes())); conn.setRequestProperty("Authorization", "Basic " + encodedPassword); } if (timeout > 0) { conn.setReadTimeout(timeout); } if (followRedirects && (conn instanceof HttpURLConnection)) { HttpURLConnection hconn = (HttpURLConnection) conn; hconn.setInstanceFollowRedirects(false); int response = hconn.getResponseCode(); boolean redirect = (response >= 300 && response <= 399); // In the case of a redirect, we want to actually change the URL // that was input to the new, redirected URL if (redirect) { String loc = conn.getHeaderField("Location"); if (loc == null) { throw new FileNotFoundException( "URL points to a redirect without " + "target location: " + page); } if (loc.startsWith("http")) { page = new URL(loc); } else { page = new URL(page, loc); } return getStream(page, followRedirects, timeout, userName, userPassword); } } InputStream in = conn.getInputStream(); return in; }
From source file:HttpConnections.DiffURIBuilder.java
public URL getFinalURIString() { URL endpoint = null;//from w w w . j a v a 2 s .c o m try { endpoint = new URL(new URL(getFinalURI().build().toString()), "", new URLStreamHandler() { @Override protected URLConnection openConnection(URL url) throws IOException { URL target = new URL(url.toString()); URLConnection connection = target.openConnection(); // Connection settings connection.setConnectTimeout(30000); // 20 sec connection.setReadTimeout(60000); // 30 sec return (connection); } }); } catch (MalformedURLException ex) { Logger.getLogger(DiffURIBuilder.class.getName()).log(Level.SEVERE, null, ex); } catch (URISyntaxException ex) { Logger.getLogger(DiffURIBuilder.class.getName()).log(Level.SEVERE, null, ex); } //System.out.println("Soap URL:"+endpoint); return endpoint; }
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 a 2 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.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);/*w w w . ja v a 2s .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 w w w. j a v a2s . c om connection.setDoOutput(true); connection.setUseCaches(false); return (HttpURLConnection) connection; }
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. */// w w w .j ava 2s . c o 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()); } }
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 w w w. j ava2 s. 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()); }