List of usage examples for java.net URLConnection setConnectTimeout
public void setConnectTimeout(int timeout)
From source file:jp.classmethod.aws.InstanceMetadataFactoryBean.java
private Reader createUserDataReader() throws IOException, MalformedURLException { URLConnection conn = new URL(USER_DATA_URL).openConnection(); conn.setReadTimeout(TIMEOUT); conn.setConnectTimeout(TIMEOUT); conn.connect();//from w w w . j a v a 2 s . c o m return new BufferedReader(new InputStreamReader(conn.getInputStream())); }
From source file:org.n52.geolabel.server.resources.PNGResourceV1.java
@GET @Produces(MEDIA_TYPE)//from w w w. j a va 2 s . c om @ApiOperation(value = "Returns a GEO label", notes = "Requires metadata/feedback documents as url") @ApiResponses({ @ApiResponse(code = 400, message = "Error in feedback/metadata document") }) public Response getLabelSVGByURL(@ApiParam("Url to LML document") @QueryParam(Constants.PARAM_LML) URL lmlURL, @ApiParam("Url to metadata document") @QueryParam(Constants.PARAM_METADATA) URL metadataURL, @ApiParam("Url to feedback document") @QueryParam(Constants.PARAM_FEEDBACK) URL feedbackURL, @ApiParam("Desired size of returned PNG") @QueryParam(Constants.PARAM_SIZE) Integer size, @ApiParam("use cached labels") @QueryParam(Constants.PARAM_USECACHE) @DefaultValue(Constants.PARAM_USECACHE_DEFAULT) boolean useCache) throws IOException { Label label = null; if (lmlURL != null) { URLConnection con = lmlURL.openConnection(); con.setConnectTimeout(GeoLabelConfig.CONNECT_TIMEOUT); con.setReadTimeout(GeoLabelConfig.READ_TIMEOUT); label = Label.fromXML(con.getInputStream()); } else { LMLResourceV1 lmlR = this.lmlResource.get(); label = lmlR.getLabelByURL(metadataURL, feedbackURL, useCache); } return createLabelPNGResponse(size != null ? size.intValue() : DEFAULT_PNG_SIZE, label); }
From source file:org.kuali.mobility.itnotices.service.ITNoticesServiceImpl.java
private List<ITNotice> getITNoticesFromFeed() { List<ITNotice> notices = new ArrayList<ITNotice>(); SAXBuilder builder = new SAXBuilder(); Document doc = null;/*from w w w .j a v a 2s .c o m*/ URL urlObj; try { urlObj = new URL("http://itnotices.iu.edu/rss.aspx"); URLConnection urlConnection = urlObj.openConnection(); urlConnection.setConnectTimeout(5000); urlConnection.setReadTimeout(5000); urlConnection.connect(); doc = builder.build(urlConnection.getInputStream()); if (doc != null) { Element root = doc.getRootElement(); List items = root.getChild("channel").getChildren("item"); for (Iterator iterator = items.iterator(); iterator.hasNext();) { Element item = (Element) iterator.next(); String services = ""; List service = item.getChildren("service"); for (Iterator iterator2 = service.iterator(); iterator2.hasNext();) { Element s = (Element) iterator2.next(); services += s.getContent(0).getValue() + ", "; } if (services.endsWith(", ")) { services = services.substring(0, services.length() - 2); } ITNotice notice = new ITNotice(item.getChildTextTrim("lastUpdated"), item.getChildTextTrim("noticeType"), item.getChildTextTrim("title"), services, item.getChildTextTrim("message")); determineImage(notice); notices.add(notice); } } } catch (Exception e) { LOG.error(e.getMessage(), e); } return notices; }
From source file:no.get.cms.plugin.resourcecompressor.ContentLoader.java
public String load(String srcUrl) { try {/*from ww w . ja v a2 s . c o m*/ URL url = new URL(srcUrl); URLConnection connection = url.openConnection(); connection.setRequestProperty("Accept-Charset", "UTF-8"); connection.setConnectTimeout(2000); connection.setReadTimeout(10000); connection.connect(); InputStream inputStream = connection.getInputStream(); String charset = extractCharsetFromContentType(connection.getContentType()); String body = IOUtils.toString(inputStream, charset); IOUtils.close(connection); return body; } catch (MalformedURLException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } }
From source file:org.geoserver.web.wicket.FileExistsValidator.java
@Override protected void onValidate(IValidatable validatable) { String uriSpec = Converters.convert(validatable.getValue(), String.class); // Make sure we are dealing with a local path try {/* w w w. j a va 2 s. c o m*/ URI uri = new URI(uriSpec); if (uri.getScheme() != null && !"file".equals(uri.getScheme())) { if (delegate != null) { delegate.validate(validatable); InputStream is = null; try { URLConnection connection = uri.toURL().openConnection(); connection.setConnectTimeout(10000); is = connection.getInputStream(); } catch (Exception e) { error(validatable, "FileExistsValidator.unreachable", Collections.singletonMap("file", uriSpec)); } finally { IOUtils.closeQuietly(is); } } return; } else { // ok, strip away the scheme and just get to the path String path = uri.getPath(); if (path != null && new File(path).exists()) { return; } } } catch (URISyntaxException e) { // may be a windows path, move on } // local to data dir? File relFile = GeoserverDataDirectory.findDataFile(uriSpec); if (relFile == null || !relFile.exists()) { error(validatable, "FileExistsValidator.fileNotFoundError", Collections.singletonMap("file", uriSpec)); } }
From source file:com.bah.applefox.main.plugins.fulltextindex.FTLoader.java
/** This method is used to get the page source from the given URL * @param url - the url from which to get the contents * @return - the page contents/*from w ww . j a v a 2 s .c o m*/ */ private static String getPageContents(URL url) { String pageContents = ""; try { // Open the URL Connection URLConnection con = url.openConnection(); // Get the file path, and eliminate unreadable documents String filePath = url.toString(); // Reads content only if it is a valid format if (!(filePath.endsWith(".pdf") || filePath.endsWith(".doc") || filePath.endsWith(".jsp") || filePath.endsWith("rss") || filePath.endsWith(".css"))) { // Sets the connection timeout (in milliseconds) con.setConnectTimeout(1000); // Tries to match the character set of the Web Page String charset = "utf-8"; try { Matcher m = Pattern.compile("\\s+charset=([^\\s]+)\\s*").matcher(con.getContentType()); charset = m.matches() ? m.group(1) : "utf-8"; } catch (Exception e) { log.error("Page had no specified charset"); } // Reader derived from the URL Connection's input stream, with // the // given character set Reader r = new InputStreamReader(con.getInputStream(), charset); // String Buffer used to append each chunk of Web Page data StringBuffer buf = new StringBuffer(); // Tries to get an estimate of bytes available int BUFFER_SIZE = con.getInputStream().available(); // If BUFFER_SIZE is too small, increases the size if (BUFFER_SIZE <= 1000) { BUFFER_SIZE = 1000; } // Character array to hold each chunk of Web Page data char[] ch = new char[BUFFER_SIZE]; // Read the first chunk of Web Page data int len = r.read(ch); // Loops until end of the Web Page is reached while (len != -1) { // Appends the data chunk to the string buffer and gets the // next chunk buf.append(ch, 0, len); len = r.read(ch, 0, BUFFER_SIZE); } // Sets the pageContents to the newly created string pageContents = buf.toString(); } } catch (UnsupportedEncodingException e) { if (e.getMessage() != null) { log.error(e.getMessage()); } else { log.error(e.getStackTrace()); } // Assume the body contents are blank if the character encoding is // not supported pageContents = ""; } catch (IOException e) { if (e.getMessage() != null) { log.error(e.getMessage()); } else { log.error(e.getStackTrace()); } // Assume the body contents are blank if the Web Page could not be // accessed pageContents = ""; } return pageContents; }
From source file:com.ijuru.kumva.app.site.FetchSuggestionsTask.java
@Override protected List<Suggestion> fetch(String term) { URL url = dictionary.createSuggestionsURL(term); URLConnection connection; try {//from w w w .j a va2 s. c om connection = url.openConnection(); connection.setConnectTimeout(timeout); connection.setReadTimeout(timeout); StringBuilder sb = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; while ((line = reader.readLine()) != null) sb.append(line); JSONArray jsonArray = new JSONArray(sb.toString()); List<Suggestion> suggestions = new ArrayList<Suggestion>(); for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); String text = jsonObject.getString("value"); String lang = jsonObject.getString("lang"); suggestions.add(new Suggestion(text, lang)); } return suggestions; } catch (Exception e) { return null; } }
From source file:tritop.android.naturalselectionnews.StatsWorker.java
private String downloadJSON() { try {// w w w . j av a 2s . c o m StringBuilder sBuilder = new StringBuilder(); String line = null; URLConnection con = url.openConnection(); con.setConnectTimeout(CON_TIMEOUT); BufferedReader bReader = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8")); while ((line = bReader.readLine()) != null) { sBuilder.append(line); } return sBuilder.toString(); } catch (IOException e) { e.printStackTrace(); return null; } }
From source file:HttpConnections.DiffURIBuilder.java
public URL getFinalURIString() { URL endpoint = null;// w w w . j a va2 s. co 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:dlauncher.dialogs.Login.java
private void login_write(String UserName, String Password) { Logger.getGlobal().info("Started login process"); Logger.getGlobal().info("Writing login data.."); try {//from w w w. j a v a 2s. c o m url = new URL("http://authserver.mojang.com/authenticate"); final URLConnection con = url.openConnection(); con.setConnectTimeout(5000); con.setReadTimeout(5000); con.setDoOutput(true); con.setDoInput(true); con.setRequestProperty("Content-Type", "application/json"); try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(con.getOutputStream()))) { writer.write("{\n" + " \"agent\": {" + " \"name\": \"Minecraft\"," + " \"version\": 1" + "\n" + " },\n" + " \"username\": \"" + UserName + "\",\n" + "\n" + " \"password\": \"" + Password + "\",\n" + "}"); writer.close(); } Logger.getGlobal().info("Succesful written login data"); } catch (MalformedURLException ex) { Logger.getGlobal().warning("Failed Writing login data,"); Logger.getLogger(Login.class.getName()).log(Level.SEVERE, "", ex); } catch (IOException ex) { Logger.getGlobal().warning("Failed Writing login data,"); Logger.getLogger(Login.class.getName()).log(Level.SEVERE, "", ex); } }