List of usage examples for java.net URLConnection setReadTimeout
public void setReadTimeout(int timeout)
From source file:com.miz.apis.thetvdb.TheTVDbService.java
@Override public TvShow get(String id, String language) { TvShow show = new TvShow(); show.setId(id);/*w w w.ja va 2 s . co m*/ // Show details try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); URL url = new URL( "http://thetvdb.com/api/" + mTvdbApiKey + "/series/" + show.getId() + "/" + language + ".xml"); URLConnection con = url.openConnection(); con.setReadTimeout(60000); con.setConnectTimeout(60000); Document doc = db.parse(con.getInputStream()); doc.getDocumentElement().normalize(); NodeList nodeList = doc.getElementsByTagName("Series"); if (nodeList.getLength() > 0) { Node firstNode = nodeList.item(0); if (firstNode.getNodeType() == Node.ELEMENT_NODE) { Element firstElement = (Element) firstNode; NodeList list; Element element; NodeList tag; try { list = firstElement.getElementsByTagName("SeriesName"); element = (Element) list.item(0); tag = element.getChildNodes(); show.setTitle((tag.item(0)).getNodeValue()); } catch (Exception e) { } try { list = firstElement.getElementsByTagName("Overview"); element = (Element) list.item(0); tag = element.getChildNodes(); show.setDescription((tag.item(0)).getNodeValue()); } catch (Exception e) { } try { list = firstElement.getElementsByTagName("Actors"); element = (Element) list.item(0); tag = element.getChildNodes(); show.setActors((tag.item(0)).getNodeValue()); } catch (Exception e) { } try { list = firstElement.getElementsByTagName("Genre"); element = (Element) list.item(0); tag = element.getChildNodes(); show.setGenres((tag.item(0)).getNodeValue()); } catch (Exception e) { } try { list = firstElement.getElementsByTagName("Rating"); element = (Element) list.item(0); tag = element.getChildNodes(); show.setRating((tag.item(0)).getNodeValue()); } catch (Exception e) { show.setRating("0"); } try { list = firstElement.getElementsByTagName("poster"); element = (Element) list.item(0); tag = element.getChildNodes(); show.setCoverUrl("http://thetvdb.com/banners/" + tag.item(0).getNodeValue()); } catch (Exception e) { } try { list = firstElement.getElementsByTagName("fanart"); element = (Element) list.item(0); tag = element.getChildNodes(); show.setBackdropUrl("http://thetvdb.com/banners/" + tag.item(0).getNodeValue()); } catch (Exception e) { } try { list = firstElement.getElementsByTagName("ContentRating"); element = (Element) list.item(0); tag = element.getChildNodes(); show.setCertification(tag.item(0).getNodeValue()); } catch (Exception e) { } try { list = firstElement.getElementsByTagName("Runtime"); element = (Element) list.item(0); tag = element.getChildNodes(); show.setRuntime(tag.item(0).getNodeValue()); } catch (Exception e) { } try { list = firstElement.getElementsByTagName("FirstAired"); element = (Element) list.item(0); tag = element.getChildNodes(); show.setFirstAired(tag.item(0).getNodeValue()); } catch (Exception e) { } try { list = firstElement.getElementsByTagName("IMDB_ID"); element = (Element) list.item(0); tag = element.getChildNodes(); show.setIMDbId(tag.item(0).getNodeValue()); } catch (Exception e) { } } } // Trakt.tv if (getRatingsProvider().equals(mContext.getString(R.string.ratings_option_2))) { try { Show showSummary = Trakt.getShowSummary(mContext, id); double rating = Double.valueOf(showSummary.getRating() / 10); if (rating > 0 || show.getRating().equals("0.0")) show.setRating(String.valueOf(rating)); } catch (Exception e) { } } // OMDb API / IMDb if (getRatingsProvider().equals(mContext.getString(R.string.ratings_option_3))) { try { JSONObject jObject = MizLib.getJSONObject(mContext, "http://www.omdbapi.com/?i=" + show.getImdbId()); double rating = Double.valueOf(MizLib.getStringFromJSONObject(jObject, "imdbRating", "0")); if (rating > 0 || show.getRating().equals("0.0")) show.setRating(String.valueOf(rating)); } catch (Exception e) { } } } catch (Exception e) { } // Episode details try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); URL url = new URL("http://thetvdb.com/api/" + mTvdbApiKey + "/series/" + show.getId() + "/all/" + language + ".xml"); URLConnection con = url.openConnection(); con.setReadTimeout(60000); con.setConnectTimeout(60000); Document doc = db.parse(con.getInputStream()); doc.getDocumentElement().normalize(); NodeList nodeList = doc.getElementsByTagName("Episode"); for (int i = 0; i < nodeList.getLength(); i++) { Node firstNode = nodeList.item(i); if (firstNode.getNodeType() == Node.ELEMENT_NODE) { Element firstElement = (Element) firstNode; NodeList list; Element element; NodeList tag; Episode episode = new Episode(); if (useDvdOrder()) { try { list = firstElement.getElementsByTagName("DVD_episodenumber"); element = (Element) list.item(0); tag = element.getChildNodes(); episode.setEpisode(MizLib.getInteger(Double.valueOf(tag.item(0).getNodeValue()))); } catch (Exception e) { } } if (episode.getEpisode() == -1) { try { list = firstElement.getElementsByTagName("EpisodeNumber"); element = (Element) list.item(0); tag = element.getChildNodes(); episode.setEpisode(MizLib.getInteger(tag.item(0).getNodeValue())); } catch (Exception e) { episode.setEpisode(0); } } if (useDvdOrder()) { try { list = firstElement.getElementsByTagName("DVD_season"); element = (Element) list.item(0); tag = element.getChildNodes(); episode.setSeason(MizLib.getInteger(tag.item(0).getNodeValue())); } catch (Exception e) { } } if (episode.getSeason() == -1) { try { list = firstElement.getElementsByTagName("SeasonNumber"); element = (Element) list.item(0); tag = element.getChildNodes(); episode.setSeason(MizLib.getInteger(tag.item(0).getNodeValue())); } catch (Exception e) { episode.setSeason(0); } } try { list = firstElement.getElementsByTagName("EpisodeName"); element = (Element) list.item(0); tag = element.getChildNodes(); episode.setTitle(tag.item(0).getNodeValue()); } catch (Exception e) { } try { list = firstElement.getElementsByTagName("FirstAired"); element = (Element) list.item(0); tag = element.getChildNodes(); episode.setAirdate(tag.item(0).getNodeValue()); } catch (Exception e) { } try { list = firstElement.getElementsByTagName("Overview"); element = (Element) list.item(0); tag = element.getChildNodes(); episode.setDescription(tag.item(0).getNodeValue()); } catch (Exception e) { } try { list = firstElement.getElementsByTagName("filename"); element = (Element) list.item(0); tag = element.getChildNodes(); episode.setScreenshotUrl("http://thetvdb.com/banners/" + tag.item(0).getNodeValue()); } catch (Exception e) { } try { list = firstElement.getElementsByTagName("Rating"); element = (Element) list.item(0); tag = element.getChildNodes(); episode.setRating(tag.item(0).getNodeValue()); } catch (Exception e) { episode.setRating("0"); } try { list = firstElement.getElementsByTagName("Director"); element = (Element) list.item(0); tag = element.getChildNodes(); episode.setDirector(tag.item(0).getNodeValue()); } catch (Exception e) { } try { list = firstElement.getElementsByTagName("Writer"); element = (Element) list.item(0); tag = element.getChildNodes(); episode.setWriter(tag.item(0).getNodeValue()); } catch (Exception e) { } try { list = firstElement.getElementsByTagName("GuestStars"); element = (Element) list.item(0); tag = element.getChildNodes(); episode.setGueststars(tag.item(0).getNodeValue()); } catch (Exception e) { } show.addEpisode(episode); } } } catch (Exception e) { } // Season covers try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); URL url = new URL("http://thetvdb.com/api/" + mTvdbApiKey + "/series/" + show.getId() + "/banners.xml"); URLConnection con = url.openConnection(); con.setReadTimeout(60000); con.setConnectTimeout(60000); Document doc = db.parse(con.getInputStream()); doc.getDocumentElement().normalize(); NodeList nodeList = doc.getElementsByTagName("Banner"); for (int i = 0; i < nodeList.getLength(); i++) { Node firstNode = nodeList.item(i); if (firstNode.getNodeType() == Node.ELEMENT_NODE) { Element firstElement = (Element) firstNode; NodeList list; Element element; NodeList tag; Season season = new Season(); String bannerType = ""; int seasonNumber = -1; try { list = firstElement.getElementsByTagName("BannerType"); element = (Element) list.item(0); tag = element.getChildNodes(); bannerType = tag.item(0).getNodeValue(); } catch (Exception e) { } if (!bannerType.equals("season")) continue; try { list = firstElement.getElementsByTagName("Season"); element = (Element) list.item(0); tag = element.getChildNodes(); seasonNumber = Integer.valueOf(tag.item(0).getNodeValue()); } catch (Exception e) { } if (seasonNumber >= 0 && !show.hasSeason(seasonNumber)) { season.setSeason(seasonNumber); try { list = firstElement.getElementsByTagName("BannerPath"); element = (Element) list.item(0); tag = element.getChildNodes(); season.setCoverPath("http://thetvdb.com/banners/" + tag.item(0).getNodeValue()); } catch (Exception e) { season.setCoverPath(""); } show.addSeason(season); } } } } catch (Exception e) { } return show; }
From source file:edu.ucuenca.authorsdisambiguation.Distance.java
public synchronized String Http(String s) throws SQLException, IOException { Statement stmt = conn.createStatement(); String sql;// w w w . j a va2 s. c o m sql = "SELECT * FROM cache where cache.key='" + getMD5(s) + "'"; java.sql.ResultSet rs = stmt.executeQuery(sql); String resp = ""; if (rs.next()) { resp = rs.getString("value"); rs.close(); stmt.close(); } else { rs.close(); stmt.close(); final URL url = new URL(s); final URLConnection connection = url.openConnection(); connection.setConnectTimeout(60000); connection.setReadTimeout(60000); connection.addRequestProperty("User-Agent", "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:44.0) Gecko/20100101 Firefox/44.0"); connection.addRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); final Scanner reader = new Scanner(connection.getInputStream(), "UTF-8"); while (reader.hasNextLine()) { final String line = reader.nextLine(); resp += line + "\n"; } reader.close(); try { JsonParser parser = new JsonParser(); parser.parse(resp); PreparedStatement stmt2 = conn.prepareStatement("INSERT INTO cache (key, value) values (?, ?)"); stmt2.setString(1, getMD5(s)); stmt2.setString(2, resp); stmt2.executeUpdate(); stmt2.close(); } catch (Exception e) { System.out.printf("Error al insertar en la DB: " + e); } } return resp; }
From source file:org.infoglue.calendar.actions.ViewEventListAction.java
public List getExternalFeedEntries(String externalRSSUrl) throws Exception { try {/*from w ww . j a v a 2 s . c o m*/ URL url = new URL(externalRSSUrl); URLConnection urlConn = url.openConnection(); urlConn.setConnectTimeout(5000); urlConn.setReadTimeout(10000); SyndFeedInput input = new SyndFeedInput(); SyndFeed inputFeed = input.build(new XmlReader(urlConn)); List entries = inputFeed.getEntries(); Iterator entriesIterator = entries.iterator(); while (entriesIterator.hasNext()) { SyndEntry entry = (SyndEntry) entriesIterator.next(); Iterator contentIterator = entry.getContents().iterator(); while (contentIterator.hasNext()) { SyndContent content = (SyndContent) contentIterator.next(); log.info("content:" + content.getValue()); if (content.getType().equalsIgnoreCase("text/xml")) content.setValue("<![CDATA[" + content.getValue() + "]]>"); } } return entries; } catch (Exception e) { throw new Exception( getParameterizedLabel("labels.internal.event.error.couldNotConnectToRSS", externalRSSUrl)); } }
From source file:org.wso2.emm.system.service.api.OTAServerManager.java
/** * Downloads the property list from remote site, and parse it to property list. * The caller can parse this list and get information. *///from w ww . j a va 2 s. c o m public void getTargetPackagePropertyList(final URL url) { final String operation = Preference.getBoolean(context, context.getResources().getString(R.string.firmware_status_check_in_progress)) ? Constants.Operation.GET_FIRMWARE_UPGRADE_PACKAGE_STATUS : Constants.Operation.UPGRADE_FIRMWARE; if (asyncTask != null) { asyncTask.cancel(true); } asyncTask = new AsyncTask<Void, Void, Void>() { protected Void doInBackground(Void... param) { InputStream reader = null; ByteArrayOutputStream writer = null; BuildPropParser parser = null; final int bufSize = 1024; // First, trying to download the property list file. the build.prop of target image. try { URLConnection urlConnection; /* Use the URL configuration to open a connection to the OTA server */ urlConnection = url.openConnection(); urlConnection.setConnectTimeout(Constants.FIRMWARE_UPGRADE_CONNECTIVITY_TIMEOUT); urlConnection.setReadTimeout(Constants.FIRMWARE_UPGRADE_READ_TIMEOUT); /* Since you get a URLConnection, use it to get the InputStream */ reader = urlConnection.getInputStream(); /* Now that the InputStream is open, get the content length */ final int contentLength = urlConnection.getContentLength(); byte[] buffer = new byte[bufSize]; if (contentLength != -1) { writer = new ByteArrayOutputStream(contentLength); } else { writer = new ByteArrayOutputStream(DEFAULT_STREAM_LENGTH); } int totalBufRead = 0; int bytesRead; Timer timer = new Timer(); Log.d(TAG, "Start download: " + url.toString() + " to buffer"); while ((bytesRead = reader.read(buffer)) > 0) { // Write current segment into byte output stream writer.write(buffer, 0, bytesRead); Log.d(TAG, "wrote " + bytesRead + " into byte output stream"); totalBufRead += bytesRead; buffer = new byte[bufSize]; timer.cancel(); timer = new Timer(); timer.schedule(new Timeout(this), Constants.FIRMWARE_UPGRADE_READ_TIMEOUT); } Log.d(TAG, "Download finished: " + (Integer.toString(totalBufRead)) + " bytes downloaded"); parser = new BuildPropParser(writer, context); timer.cancel(); } catch (SocketTimeoutException e) { String message = "Connection failure (Socket timeout) when retrieving update package size."; Log.e(TAG, message + e); CommonUtils.sendBroadcast(context, operation, Constants.Code.FAILURE, Constants.Status.CONNECTION_FAILED, message); CommonUtils.callAgentApp(context, Constants.Operation.FAILED_FIRMWARE_UPGRADE_NOTIFICATION, 0, null); } catch (IOException e) { String message = "Property list (build.prop) not found in the server."; Log.e(TAG, message + e); CommonUtils.sendBroadcast(context, operation, Constants.Code.FAILURE, Constants.Status.FILE_NOT_FOUND, message); CommonUtils.callAgentApp(context, Constants.Operation.FAILED_FIRMWARE_UPGRADE_NOTIFICATION, 0, null); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { Log.e(TAG, "Failed to close buffer reader." + e); } } if (writer != null) { try { writer.close(); } catch (IOException e) { Log.e(TAG, "Failed to close buffer writer." + e); } } if (parser != null) { if (stateChangeListener != null) { stateChangeListener.onStateOrProgress(OTAStateChangeListener.STATE_IN_CHECKED, OTAStateChangeListener.NO_ERROR, parser, DEFAULT_STATE_INFO_CODE); } } else { reportCheckingError(OTAStateChangeListener.ERROR_CANNOT_FIND_SERVER); } } return null; } }.executeOnExecutor(threadPoolExecutor); }
From source file:org.hw.parlance.ParlanceActivity.java
/** * Method to parse XML response from Yahoo URL and add markers of restaurants on the map *//* w ww .j av a2 s . co m*/ private synchronized void xmlParsing(String XMLResponse) { try { URLConnection conn = new URL(XMLResponse).openConnection(); conn.setConnectTimeout(50000); conn.setReadTimeout(50000); SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); ItemHandler itemHandler = new ItemHandler(); xr.setContentHandler(itemHandler); xr.parse(new InputSource(conn.getInputStream())); _itemAdapter.arr = itemHandler.getList(); for (int index = 0; index < _itemAdapter.arr.size(); index++) { Marker temp_marker = mMap.addMarker(new MarkerOptions() .position(new LatLng(Double.parseDouble(_itemAdapter.arr.get(index).getLat()), Double.parseDouble(_itemAdapter.arr.get(index).getLon()))) .title(_itemAdapter.arr.get(index).getName()) .icon(BitmapDescriptorFactory.fromResource(numMarkerIcon[index]))); this._markList.add(temp_marker); } _itemAdapter.notifyDataSetChanged(); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:ch.cyberduck.core.gdocs.GDSession.java
protected HttpURLConnection getConnection(URL url) throws IOException { URLConnection c = null; if (Preferences.instance().getBoolean("connection.proxy.enable")) { final Proxy proxy = ProxyFactory.instance(); if (proxy.isHTTPSProxyEnabled(new Host(Protocol.GDOCS_SSL, url.getHost(), url.getPort()))) { c = url.openConnection(new java.net.Proxy(java.net.Proxy.Type.HTTP, new InetSocketAddress(proxy.getHTTPSProxyHost(host), proxy.getHTTPSProxyPort(host)))); }//ww w.ja va 2 s. c om } if (null == c) { log.debug("Direct connection"); c = url.openConnection(); } c.setConnectTimeout(timeout()); c.setReadTimeout(timeout()); if (c instanceof HttpsURLConnection) { ((HttpsURLConnection) c).setSSLSocketFactory( new CustomTrustSSLProtocolSocketFactory(this.getTrustManager(url.getHost()))); ((HttpsURLConnection) c).setHostnameVerifier(new HostnameVerifier() { public boolean verify(String s, javax.net.ssl.SSLSession sslSession) { return true; } }); } if (c instanceof HttpURLConnection) { return (HttpURLConnection) c; } throw new ConnectionCanceledException("Invalid URL connection:" + c); }
From source file:org.wso2.iot.system.service.api.OTAServerManager.java
/** * Downloads the property list from remote site, and parse it to property list. * The caller can parse this list and get information. *///from w w w . j ava 2s . c om public void getTargetPackagePropertyList(final URL url) { final String operation = Preference.getBoolean(context, context.getResources().getString(R.string.firmware_status_check_in_progress)) ? Constants.Operation.GET_FIRMWARE_UPGRADE_PACKAGE_STATUS : Constants.Operation.UPGRADE_FIRMWARE; if (asyncTask != null) { asyncTask.cancel(true); } asyncTask = new AsyncTask<Void, Void, Void>() { protected Void doInBackground(Void... param) { InputStream reader = null; ByteArrayOutputStream writer = null; BuildPropParser parser = null; final int bufSize = 1024; // First, trying to download the property list file. the build.prop of target image. try { URLConnection urlConnection; /* Use the URL configuration to open a connection to the OTA server */ urlConnection = url.openConnection(); urlConnection.setConnectTimeout(Constants.FIRMWARE_UPGRADE_CONNECTIVITY_TIMEOUT); urlConnection.setReadTimeout(Constants.FIRMWARE_UPGRADE_READ_TIMEOUT); /* Since you get a URLConnection, use it to get the InputStream */ reader = urlConnection.getInputStream(); /* Now that the InputStream is open, get the content length */ final int contentLength = urlConnection.getContentLength(); byte[] buffer = new byte[bufSize]; if (contentLength != -1) { writer = new ByteArrayOutputStream(contentLength); } else { writer = new ByteArrayOutputStream(DEFAULT_STREAM_LENGTH); } int totalBufRead = 0; int bytesRead; Timer timer = new Timer(); Log.d(TAG, "Start download: " + url.toString() + " to buffer"); while ((bytesRead = reader.read(buffer)) > 0) { // Write current segment into byte output stream writer.write(buffer, 0, bytesRead); Log.d(TAG, "wrote " + bytesRead + " into byte output stream"); totalBufRead += bytesRead; buffer = new byte[bufSize]; timer.cancel(); timer = new Timer(); timer.schedule(new Timeout(this), Constants.FIRMWARE_UPGRADE_READ_TIMEOUT); } Log.d(TAG, "Download finished: " + (Integer.toString(totalBufRead)) + " bytes downloaded"); parser = new BuildPropParser(writer, context); timer.cancel(); } catch (SocketTimeoutException e) { String message = "Connection failure (Socket timeout) when retrieving update package size."; Log.e(TAG, message + e); CommonUtils.sendBroadcast(context, operation, Constants.Code.FAILURE, Constants.Status.CONNECTION_FAILED, message); CommonUtils.callAgentApp(context, Constants.Operation.FAILED_FIRMWARE_UPGRADE_NOTIFICATION, Preference.getInt(context, context.getResources().getString(R.string.operation_id)), message); } catch (IOException e) { String message = "Property list (build.prop) not found in the server."; Log.e(TAG, message + e); CommonUtils.sendBroadcast(context, operation, Constants.Code.FAILURE, Constants.Status.FILE_NOT_FOUND, message); CommonUtils.callAgentApp(context, Constants.Operation.FAILED_FIRMWARE_UPGRADE_NOTIFICATION, Preference.getInt(context, context.getResources().getString(R.string.operation_id)), message); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { Log.e(TAG, "Failed to close buffer reader." + e); } } if (writer != null) { try { writer.close(); } catch (IOException e) { Log.e(TAG, "Failed to close buffer writer." + e); } } if (parser != null) { if (stateChangeListener != null) { stateChangeListener.onStateOrProgress(OTAStateChangeListener.STATE_IN_CHECKED, OTAStateChangeListener.NO_ERROR, parser, DEFAULT_STATE_INFO_CODE); } } else { reportCheckingError(OTAStateChangeListener.ERROR_CANNOT_FIND_SERVER); } } return null; } }.executeOnExecutor(threadPoolExecutor); }
From source file:org.eclipse.kapua.app.console.server.GwtDeviceManagementServiceImpl.java
/** * Checks the source of the icon.//from ww w. j av a2 s. co m * The component config icon can be one of the well known icon (i.e. MqttDataTransport icon) * as well as an icon loaded from external source with an HTTP link. * * We need to filter HTTP link to protect the console page and also to have content always served from * EC console. Otherwise browsers can alert the user that content is served from domain different from * *.everyware-cloud.com and over insicure connection. * * To avoid this we will download the image locally on the server temporary directory and give back the page * a token URL to get the file. * * @param icon * The icon from the OCD of the component configuration. * @throws IOException * @throws NoSuchAlgorithmException * @throws ImageReadException */ private void checkIconResource(KapuaTicon icon) { ConsoleSetting config = ConsoleSetting.getInstance(); String iconResource = icon.getResource(); // // Check if the resource is an HTTP URL or not if (iconResource != null && (iconResource.toLowerCase().startsWith("http://") || iconResource.toLowerCase().startsWith("https://"))) { File tmpFile = null; try { logger.info("Got configuration component icon from URL: {}", iconResource); // // Tmp file name creation String systemTmpDir = System.getProperty("java.io.tmpdir"); String iconResourcesTmpDir = config.getString(ConsoleSettingKeys.DEVICE_CONFIGURATION_ICON_FOLDER); String tmpFileName = Base64.encodeBase64String( MessageDigest.getInstance("MD5").digest(iconResource.getBytes("UTF-8"))); // Conversions needed got security reasons! // On the file servlet we use the regex [0-9A-Za-z]{1,} to validate the given file id. // This validation prevents the caller of the file servlet to try to move out of the directory where the icons are stored. tmpFileName = tmpFileName.replaceAll("/", "a"); tmpFileName = tmpFileName.replaceAll("\\+", "m"); tmpFileName = tmpFileName.replaceAll("=", "z"); // // Tmp dir check and creation StringBuilder tmpDirPathSb = new StringBuilder().append(systemTmpDir); if (!systemTmpDir.endsWith("/")) { tmpDirPathSb.append("/"); } tmpDirPathSb.append(iconResourcesTmpDir); File tmpDir = new File(tmpDirPathSb.toString()); if (!tmpDir.exists()) { logger.info("Creating tmp dir on path: {}", tmpDir.toString()); tmpDir.mkdir(); } // // Tmp file check and creation tmpDirPathSb.append("/").append(tmpFileName); tmpFile = new File(tmpDirPathSb.toString()); // Check date of modification to avoid caching forever if (tmpFile.exists()) { long lastModifiedDate = tmpFile.lastModified(); long maxCacheTime = config.getLong(ConsoleSettingKeys.DEVICE_CONFIGURATION_ICON_CACHE_TIME); if (System.currentTimeMillis() - lastModifiedDate > maxCacheTime) { logger.info("Deleting old cached file: {}", tmpFile.toString()); tmpFile.delete(); } } // If file is not cached, download it. if (!tmpFile.exists()) { // Url connection URL iconUrl = new URL(iconResource); URLConnection urlConnection = iconUrl.openConnection(); urlConnection.setConnectTimeout(2000); urlConnection.setReadTimeout(2000); // Length check String contentLengthString = urlConnection.getHeaderField("Content-Length"); long maxLength = config.getLong(ConsoleSettingKeys.DEVICE_CONFIGURATION_ICON_SIZE_MAX); try { Long contentLength = Long.parseLong(contentLengthString); if (contentLength > maxLength) { logger.warn("Content lenght exceeded ({}/{}) for URL: {}", new Object[] { contentLength, maxLength, iconResource }); throw new IOException("Content-Length reported a length of " + contentLength + " which exceeds the maximum allowed size of " + maxLength); } } catch (NumberFormatException nfe) { logger.warn("Cannot get Content-Length header!"); } logger.info("Creating file: {}", tmpFile.toString()); tmpFile.createNewFile(); // Icon download InputStream is = urlConnection.getInputStream(); OutputStream os = new FileOutputStream(tmpFile); byte[] buffer = new byte[4096]; try { int len; while ((len = is.read(buffer)) > 0) { os.write(buffer, 0, len); maxLength -= len; if (maxLength < 0) { logger.warn("Maximum content lenght exceeded ({}) for URL: {}", new Object[] { maxLength, iconResource }); throw new IOException("Maximum content lenght exceeded (" + maxLength + ") for URL: " + iconResource); } } } finally { os.close(); } logger.info("Downloaded file: {}", tmpFile.toString()); // Image metadata content checks ImageFormat imgFormat = Sanselan.guessFormat(tmpFile); if (imgFormat.equals(ImageFormat.IMAGE_FORMAT_BMP) || imgFormat.equals(ImageFormat.IMAGE_FORMAT_GIF) || imgFormat.equals(ImageFormat.IMAGE_FORMAT_JPEG) || imgFormat.equals(ImageFormat.IMAGE_FORMAT_PNG)) { logger.info("Detected image format: {}", imgFormat.name); } else if (imgFormat.equals(ImageFormat.IMAGE_FORMAT_UNKNOWN)) { logger.error("Unknown file format for URL: {}", iconResource); throw new IOException("Unknown file format for URL: " + iconResource); } else { logger.error("Usupported file format ({}) for URL: {}", imgFormat, iconResource); throw new IOException("Unknown file format for URL: {}" + iconResource); } logger.info("Image validation passed for URL: {}", iconResource); } else { logger.info("Using cached file: {}", tmpFile.toString()); } // // Injecting new URL for the icon resource String newResourceURL = new StringBuilder().append("img://console/file/icons?id=") .append(tmpFileName).toString(); logger.info("Injecting configuration component icon: {}", newResourceURL); icon.setResource(newResourceURL); } catch (Exception e) { if (tmpFile != null && tmpFile.exists()) { tmpFile.delete(); } icon.setResource("Default"); logger.error("Error while checking component configuration icon. Using the default plugin icon.", e); } } // // If not, all is fine. }
From source file:com.blackducksoftware.integration.hub.builder.HubServerConfigBuilder.java
public void validateHubUrl(final ValidationResults<GlobalFieldKey, HubServerConfig> result) { assertProxyValid();/*from w w w .j av a 2s.c o m*/ if (hubUrl == null) { result.addResult(HubServerConfigFieldEnum.HUBURL, new ValidationResult(ValidationResultEnum.ERROR, ERROR_MSG_URL_NOT_FOUND)); return; } URL hubURL = null; try { hubURL = new URL(hubUrl); hubURL.toURI(); } catch (final MalformedURLException e) { result.addResult(HubServerConfigFieldEnum.HUBURL, new ValidationResult(ValidationResultEnum.ERROR, ERROR_MSG_URL_NOT_VALID)); } catch (final URISyntaxException e) { result.addResult(HubServerConfigFieldEnum.HUBURL, new ValidationResult(ValidationResultEnum.ERROR, ERROR_MSG_URL_NOT_VALID)); } if (hubURL == null) { return; } try { URLConnection connection = null; if (proxyInfo != null) { if (!hubURL.getProtocol().equals("https") && proxyInfo.getUsername() != null && proxyInfo.getEncryptedPassword() != null) { result.addResult(HubProxyInfoFieldEnum.PROXYUSERNAME, new ValidationResult( ValidationResultEnum.ERROR, ERROR_MSG_AUTHENTICATED_PROXY_WITH_HTTPS)); return; } connection = proxyInfo.openConnection(hubURL); } else { connection = hubURL.openConnection(); } final int timeoutIntMillisec = 1000 * stringToNonNegativeInteger(timeoutSeconds); connection.setConnectTimeout(timeoutIntMillisec); connection.setReadTimeout(timeoutIntMillisec); connection.getContent(); } catch (final IOException ioe) { result.addResult(HubServerConfigFieldEnum.HUBURL, new ValidationResult(ValidationResultEnum.ERROR, ERROR_MSG_UNREACHABLE_PREFIX + hubUrl, ioe)); return; } catch (final RuntimeException e) { result.addResult(HubServerConfigFieldEnum.HUBURL, new ValidationResult(ValidationResultEnum.ERROR, ERROR_MSG_URL_NOT_VALID_PREFIX + hubUrl, e)); return; } result.addResult(HubServerConfigFieldEnum.HUBURL, new ValidationResult(ValidationResultEnum.OK, "")); }
From source file:org.sunnycode.zkws.socketio.impl.IOConnection.java
/** * Handshake.//from ww w . j a va2s . c o m * */ private void handshake() { URL url; String response; URLConnection connection; try { setState(STATE_HANDSHAKE); url = new URL(IOConnection.this.url.toString() + SOCKET_IO_1); connection = url.openConnection(); if (connection instanceof HttpsURLConnection) { ((HttpsURLConnection) connection).setSSLSocketFactory(sslContext.getSocketFactory()); } connection.setConnectTimeout(connectTimeout); connection.setReadTimeout(connectTimeout); /* Setting the request headers */ for (Entry<Object, Object> entry : headers.entrySet()) { connection.setRequestProperty((String) entry.getKey(), (String) entry.getValue()); } InputStream stream = connection.getInputStream(); Scanner in = new Scanner(stream); response = in.nextLine(); String[] data = response.split(":"); sessionId = data[0]; heartbeatTimeout = Long.parseLong(data[1]) * 1000; closingTimeout = Long.parseLong(data[2]) * 1000; protocols = Arrays.asList(data[3].split(",")); } catch (Exception e) { error(new SocketIOException("Error while handshaking", e)); } }