List of usage examples for java.net URLConnection setReadTimeout
public void setReadTimeout(int timeout)
From source file:com.tc.util.io.ServerURL.java
private HttpURLConnection createSecureConnection(PwProvider pwProvider) { if (securityInfo.isSecure()) { Assert.assertNotNull("Secured URL '" + theURL + "', yet PwProvider instance", pwProvider); }/* w w w . j a v a 2s .c o m*/ URLConnection urlConnection; try { urlConnection = theURL.openConnection(); String uri = null; if (securityInfo.isSecure()) { if (securityInfo.getUsername() != null) { String encodedUsername = URLEncoder.encode(securityInfo.getUsername(), "UTF-8").replace("+", "%20"); uri = "tc://" + encodedUsername + "@" + theURL.getHost() + ":" + theURL.getPort(); final char[] passwordTo; try { final URI theURI = new URI(uri); passwordTo = pwProvider.getPasswordFor(theURI); } catch (URISyntaxException e) { throw new TCRuntimeException("Couldn't create URI to connect to " + uri, e); } Assert.assertNotNull("No password for " + theURL + " found!", passwordTo); urlConnection.addRequestProperty("Authorization", "Basic " + new BASE64Encoder() .encode((securityInfo.getUsername() + ":" + new String(passwordTo)).getBytes())); } if (DISABLE_HOSTNAME_VERIFIER || TRUST_ALL_CERTS) { tweakSecureConnectionSettings(urlConnection); } } } catch (IOException e1) { throw new IllegalStateException(e1); } if (timeout > -1) { urlConnection.setConnectTimeout(timeout); urlConnection.setReadTimeout(timeout); } return (HttpURLConnection) urlConnection; }
From source file:com.hichinaschool.flashcards.async.Connection.java
private Payload doInBackgroundDownloadSharedDeck(Payload data) { String url = (String) data.data[0]; String colFilename = AnkiDroidApp.getCurrentAnkiDroidDirectory() + "/tmpImportFile.apkg"; URL fileUrl;/* w w w . j a v a 2 s. c om*/ URLConnection conn; InputStream cont = null; try { fileUrl = new URL(url); if (url.startsWith("https")) { SSLContext context = SSLContext.getInstance("TLS"); context.init(null, new TrustManager[] { new EasyX509TrustManager(null) }, null); HttpsURLConnection httpsConn = (HttpsURLConnection) fileUrl.openConnection(); httpsConn.setSSLSocketFactory(context.getSocketFactory()); conn = httpsConn; } else { conn = (HttpURLConnection) fileUrl.openConnection(); } conn.setConnectTimeout(10000); conn.setReadTimeout(10000); cont = conn.getInputStream(); } catch (MalformedURLException e) { Log.e(AnkiDroidApp.TAG, "doInBackgroundDownloadSharedDeck: ", e); data.success = false; return data; } catch (IOException e) { Log.e(AnkiDroidApp.TAG, "doInBackgroundDownloadSharedDeck: ", e); data.success = false; return data; } catch (NoSuchAlgorithmException e) { Log.e(AnkiDroidApp.TAG, "doInBackgroundDownloadSharedDeck: ", e); data.success = false; return data; } catch (KeyStoreException e) { Log.e(AnkiDroidApp.TAG, "doInBackgroundDownloadSharedDeck: ", e); return data; } catch (KeyManagementException e) { Log.e(AnkiDroidApp.TAG, "doInBackgroundDownloadSharedDeck: ", e); data.success = false; return data; } if (cont == null) { data.success = false; return data; } File file = new File(colFilename); OutputStream output = null; try { file.createNewFile(); output = new BufferedOutputStream(new FileOutputStream(file)); byte[] buf = new byte[Utils.CHUNK_SIZE]; int len; int count = 0; while ((len = cont.read(buf)) >= 0) { output.write(buf, 0, len); count += len; publishProgress(new Object[] { count / 1024 }); } output.close(); } catch (IOException e) { try { output.close(); } catch (IOException e1) { // do nothing } // no write access or sd card full file.delete(); data.success = false; return data; } data.success = true; data.result = colFilename; return data; }
From source file:org.matrix.androidsdk.db.MXMediaDownloadWorkerTask.java
@Override protected Void doInBackground(Integer... params) { try {/* ww w .j ava2 s . c o m*/ URL url = new URL(mUrl); Log.d(LOG_TAG, "MXMediaDownloadWorkerTask " + this + " starts"); mDownloadStats = new IMXMediaDownloadListener.DownloadStats(); // don't known yet mDownloadStats.mEstimatedRemainingTime = -1; InputStream stream = null; int filelen = -1; URLConnection connection = null; try { connection = url.openConnection(); if (mHsConfig != null && connection instanceof HttpsURLConnection) { // Add SSL Socket factory. HttpsURLConnection sslConn = (HttpsURLConnection) connection; try { Pair<SSLSocketFactory, X509TrustManager> pair = CertUtil .newPinnedSSLSocketFactory(mHsConfig); sslConn.setSSLSocketFactory(pair.first); sslConn.setHostnameVerifier(CertUtil.newHostnameVerifier(mHsConfig)); } catch (Exception e) { Log.e(LOG_TAG, "doInBackground SSL exception " + e.getLocalizedMessage()); } } // add a timeout to avoid infinite loading display. connection.setReadTimeout(DOWNLOAD_TIME_OUT); filelen = connection.getContentLength(); stream = connection.getInputStream(); } catch (Exception e) { Log.e(LOG_TAG, "bitmapForURL : fail to open the connection " + e.getMessage()); InputStream errorStream = ((HttpsURLConnection) connection).getErrorStream(); if (null != errorStream) { try { BufferedReader streamReader = new BufferedReader( new InputStreamReader(errorStream, "UTF-8")); StringBuilder responseStrBuilder = new StringBuilder(); String inputStr; while ((inputStr = streamReader.readLine()) != null) { responseStrBuilder.append(inputStr); } mErrorAsJsonElement = new JsonParser().parse(responseStrBuilder.toString()); } catch (Exception ee) { Log.e(LOG_TAG, "bitmapForURL : Error parsing error " + ee.getLocalizedMessage()); } } // privacy //Log.d(LOG_TAG, "MediaWorkerTask " + mUrl + " does not exist"); Log.d(LOG_TAG, "MediaWorkerTask an url does not exist"); // if some medias are not found // do not try to reload them until the next application launch. synchronized (mUnreachableUrls) { mUnreachableUrls.add(mUrl); } } dispatchDownloadStart(); // test if the download has not been cancelled if (!isDownloadCancelled() && (null == mErrorAsJsonElement)) { final long startDownloadTime = System.currentTimeMillis(); String filename = MXMediaDownloadWorkerTask.buildFileName(mUrl, mMimeType) + ".tmp"; FileOutputStream fos = new FileOutputStream(new File(mDirectoryFile, filename)); mDownloadStats.mDownloadId = mUrl; mDownloadStats.mProgress = 0; mDownloadStats.mDownloadedSize = 0; mDownloadStats.mFileSize = filelen; mDownloadStats.mElapsedTime = 0; mDownloadStats.mEstimatedRemainingTime = -1; mDownloadStats.mBitRate = 0; final android.os.Handler uiHandler = new android.os.Handler(Looper.getMainLooper()); final Timer refreshTimer = new Timer(); uiHandler.post(new Runnable() { @Override public void run() { refreshTimer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { uiHandler.post(new Runnable() { @Override public void run() { if (!mIsDone) { publishProgress(startDownloadTime); } } }); } }, new java.util.Date(), 100); } }); try { byte[] buf = new byte[DOWNLOAD_BUFFER_READ_SIZE]; int len; while (!isDownloadCancelled() && (len = stream.read(buf)) != -1) { fos.write(buf, 0, len); mDownloadStats.mDownloadedSize += len; } if (!isDownloadCancelled()) { mDownloadStats.mProgress = 100; } } catch (OutOfMemoryError outOfMemoryError) { Log.e(LOG_TAG, "doInBackground: out of memory"); } catch (Exception e) { Log.e(LOG_TAG, "doInBackground fail to read image " + e.getMessage()); } mIsDone = true; close(stream); fos.flush(); fos.close(); if (null != mEncryptedFileInfo) { File file = new File(mDirectoryFile, filename); FileInputStream fis = new FileInputStream(file); InputStream is = MXEncryptedAttachments.decryptAttachment(fis, mEncryptedFileInfo); fis.close(); // if the decryption succeeds, replace the encrypted file content by the unencrypted one if (null != is) { mApplicationContext.deleteFile(filename); fos = new FileOutputStream(file); byte[] buf = new byte[DOWNLOAD_BUFFER_READ_SIZE]; int len; while ((len = is.read(buf)) != -1) { fos.write(buf, 0, len); } } else { mDownloadStats.mProgress = 0; } } uiHandler.post(new Runnable() { @Override public void run() { refreshTimer.cancel(); } }); if ((null != connection) && (connection instanceof HttpsURLConnection)) { ((HttpsURLConnection) connection).disconnect(); } // the file has been successfully downloaded if (mDownloadStats.mProgress == 100) { try { File originalFile = new File(mDirectoryFile, filename); String newFileName = MXMediaDownloadWorkerTask.buildFileName(mUrl, mMimeType); File newFile = new File(mDirectoryFile, newFileName); if (newFile.exists()) { // Or you could throw here. mApplicationContext.deleteFile(newFileName); } originalFile.renameTo(newFile); } catch (Exception e) { Log.e(LOG_TAG, "doInBackground : renaming error " + e.getLocalizedMessage()); } } } if (mDownloadStats.mProgress == 100) { Log.d(LOG_TAG, "The download " + this + " is done."); } else { if (null != mErrorAsJsonElement) { Log.d(LOG_TAG, "The download " + this + " failed : mErrorAsJsonElement " + mErrorAsJsonElement.toString()); } else { Log.d(LOG_TAG, "The download " + this + " failed."); } } } catch (Exception e) { Log.e(LOG_TAG, "Unable to download media " + this); } // remove the image from the loading one synchronized (mPendingDownloadByUrl) { mPendingDownloadByUrl.remove(mUrl); } return null; }
From source file:uk.ac.ebi.intact.editor.controller.curate.publication.PublicationController.java
public boolean isCitexploreOnline() { if (isCitexploreActive) { return true; }// w w w . j av a 2 s . c o m if (log.isDebugEnabled()) log.debug("Checking Europe Pubmed Central status"); try { URL url = new URL("http://www.ebi.ac.uk/webservices/citexplore/v3.0.1/service?wsdl"); final URLConnection urlConnection = url.openConnection(); urlConnection.setConnectTimeout(1000); urlConnection.setReadTimeout(1000); urlConnection.connect(); } catch (Exception e) { log.debug("\tEurope Pubmed Central is not reachable"); isCitexploreActive = false; return false; } isCitexploreActive = true; return true; }
From source file:org.apache.synapse.config.SynapseConfigUtils.java
/** * Returns a URLCOnnection for given URL. If the URL is https one , then URLConnectin is a * HttpsURLCOnnection and it is configured with KeyStores given in the synapse.properties file * * @param url URL/* w w w .j a v a 2s . c o m*/ * @return URLConnection for given URL */ public static URLConnection getURLConnection(URL url) { try { if (url == null) { if (log.isDebugEnabled()) { log.debug("Provided URL is null"); } return null; } URLConnection connection; if (url.getProtocol().equalsIgnoreCase("http") || url.getProtocol().equalsIgnoreCase("https")) { Properties synapseProperties = SynapsePropertiesLoader.loadSynapseProperties(); String proxyHost = synapseProperties.getProperty(SynapseConstants.SYNPASE_HTTP_PROXY_HOST); String proxyPort = synapseProperties.getProperty(SynapseConstants.SYNPASE_HTTP_PROXY_PORT); // get the list of excluded hosts for proxy List<String> excludedHosts = getExcludedHostsForProxy(synapseProperties); if (proxyHost != null && proxyPort != null && !excludedHosts.contains(proxyHost)) { SocketAddress sockaddr = new InetSocketAddress(proxyHost, Integer.parseInt(proxyPort)); Proxy proxy = new Proxy(Proxy.Type.HTTP, sockaddr); if (url.getProtocol().equalsIgnoreCase("https")) { connection = getHttpsURLConnection(url, synapseProperties, proxy); } else { connection = url.openConnection(proxy); } } else { if (url.getProtocol().equalsIgnoreCase("https")) { connection = getHttpsURLConnection(url, synapseProperties, null); } else { connection = url.openConnection(); } } // try to see weather authentication is required String userName = synapseProperties.getProperty(SynapseConstants.SYNPASE_HTTP_PROXY_USER); String password = synapseProperties.getProperty(SynapseConstants.SYNPASE_HTTP_PROXY_PASSWORD); if (userName != null && password != null) { String header = userName + ":" + password; byte[] encodedHeaderBytes = new Base64().encode(header.getBytes()); String encodedHeader = new String(encodedHeaderBytes); connection.setRequestProperty("Proxy-Authorization", "Basic " + encodedHeader); } } else { connection = url.openConnection(); } connection.setReadTimeout(getReadTimeout()); connection.setConnectTimeout(getConnectTimeout()); connection.setRequestProperty("Connection", "close"); // if http is being used return connection; } catch (IOException e) { handleException("Error reading at URI ' " + url + " ' ", e); } return null; }
From source file:com.mobiletin.inputmethod.indic.LatinIME.java
public boolean downloadFile(final String path) { try {/*from ww w .ja v a2 s. c o m*/ URL url = new URL(path); URLConnection ucon = url.openConnection(); ucon.setReadTimeout(5000); ucon.setConnectTimeout(10000); /* ucon.setReadTimeout(1000); ucon.setConnectTimeout(1000);*/ InputStream is = ucon.getInputStream(); BufferedInputStream inStream = new BufferedInputStream(is, 1024 * 5); File file = new File(LatinIME.this.getDir("filesdir", Context.MODE_PRIVATE) + "/text.txt"); if (file.exists()) { file.delete(); } file.createNewFile(); FileOutputStream outStream = new FileOutputStream(file); byte[] buff = new byte[5 * 1024]; int len; while ((len = inStream.read(buff)) != -1) { outStream.write(buff, 0, len); } outStream.flush(); outStream.close(); inStream.close(); } catch (Exception e) { e.printStackTrace(); Log.e("exce", e.toString()); return false; } return true; }
From source file:cm.aptoide.pt.MainActivity.java
private void getUpdateParameters() { try {/* w w w .j av a 2s. c o m*/ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); URLConnection url = new URL(LATEST_VERSION_CODE_URI).openConnection(); url.setReadTimeout(3000); url.setConnectTimeout(3000); InputStream a = new BufferedInputStream(url.getInputStream()); Document dom = builder.parse(new InputSource(a)); dom.getDocumentElement().normalize(); NodeList items = dom.getElementsByTagName("versionCode"); if (items.getLength() > 0) { Node item = items.item(0); Log.d("Aptoide-XmlElement Name", item.getNodeName()); Log.d("Aptoide-XmlElement Value", item.getFirstChild().getNodeValue().trim()); updateParams.put("versionCode", item.getFirstChild().getNodeValue().trim()); } items = dom.getElementsByTagName("uri"); if (items.getLength() > 0) { Node item = items.item(0); Log.d("Aptoide-XmlElement Name", item.getNodeName()); Log.d("Aptoide-XmlElement Value", item.getFirstChild().getNodeValue().trim()); updateParams.put("uri", item.getFirstChild().getNodeValue().trim()); } items = dom.getElementsByTagName("md5"); if (items.getLength() > 0) { Node item = items.item(0); Log.d("Aptoide-XmlElement Name", item.getNodeName()); Log.d("Aptoide-XmlElement Value", item.getFirstChild().getNodeValue().trim()); updateParams.put("md5", item.getFirstChild().getNodeValue().trim()); } } catch (Exception e) { e.printStackTrace(); } }
From source file:com.jp.miaulavirtual.DisplayMessageActivity.java
public int downloadFile(String request) { URL url2;/*from w w w . j av a 2 s.c o m*/ URLConnection conn; int lastSlash; Long fileSize = null; BufferedInputStream inStream; BufferedOutputStream outStream; FileOutputStream fileStream; String cookies = cookieFormat(scookie); // format cookie for URL setRequestProperty final int BUFFER_SIZE = 23 * 1024; int id = 1; File file = null; Log.d("Document", "2 respueesta"); try { // Just resources lastSlash = url.toString().lastIndexOf('/'); // Directory creation String root = Environment.getExternalStorageDirectory().toString(); Boolean isSDPresent = android.os.Environment.getExternalStorageState() .equals(android.os.Environment.MEDIA_MOUNTED); // check if is there external storage if (!isSDPresent) { task_status = false; id = 9; } else { String folder; if (comunidades) { folder = onData.get(2)[1]; } else { folder = onData.get(1)[1]; } folder = folder.replaceAll( "\\d{4}-\\d{4}\\s|\\d{4}-\\d{2}\\s|Documentos\\sde\\s?|Gr\\..+?\\s|\\(.+?\\)", ""); folder = folder.toString().trim(); Log.d("Folder", folder); File myDir = new File(root + "/Android/data/com.jp.miaulavirtual/files/" + folder); myDir.mkdirs(); // Document creation String name = url.toString().substring(lastSlash + 1); file = new File(myDir, name); Log.d("Document", name); fileSize = (long) file.length(); // Check if we have already downloaded the whole file if (file.exists()) { dialog.setProgress(100); // full progress if file already donwloaded } else { // Start the connection with COOKIES (we already verified that the cookies aren't expired and we can use them) url2 = new URL(request); conn = url2.openConnection(); conn.setUseCaches(false); conn.setRequestProperty("Cookie", cookies); conn.setConnectTimeout(10 * 1000); conn.setReadTimeout(20 * 1000); fileSize = (long) conn.getContentLength(); // Check if we have necesary space if (fileSize >= myDir.getUsableSpace()) { task_status = false; id = 2; } else { // Start downloading inStream = new BufferedInputStream(conn.getInputStream()); fileStream = new FileOutputStream(file); outStream = new BufferedOutputStream(fileStream, BUFFER_SIZE); byte[] data = new byte[BUFFER_SIZE]; int bytesRead = 0; int setMax = (conn.getContentLength() / 1024); dialog.setMax(setMax); while (task_status && (bytesRead = inStream.read(data, 0, data.length)) >= 0) { outStream.write(data, 0, bytesRead); // update progress bar dialog.incrementProgressBy((int) (bytesRead / 1024)); } // Close stream outStream.close(); fileStream.close(); inStream.close(); // Delete file if Cancel button if (!task_status) { file.delete(); if (myDir.listFiles().length <= 0) myDir.delete(); id = 0; } } } Log.d("Status", String.valueOf(task_status)); // Open file if (task_status) { Log.d("Type", "Hola2"); dialog.dismiss(); Intent intent = new Intent(); intent.setAction(android.content.Intent.ACTION_VIEW); MimeTypeMap mime = MimeTypeMap.getSingleton(); // Get extension file String file_s = file.toString(); String extension = ""; int i = file_s.lastIndexOf('.'); int p = Math.max(file_s.lastIndexOf('/'), file_s.lastIndexOf('\\')); if (i > p) { extension = file_s.substring(i + 1); } // Get extension reference String doc_type = mime.getMimeTypeFromExtension(extension); Log.d("Type", extension); intent.setDataAndType(Uri.fromFile(file), doc_type); startActivity(intent); } } } catch (MalformedURLException e) // Invalid URL { task_status = false; if (file.exists()) { file.delete(); } id = 3; } catch (FileNotFoundException e) // FIle not found { task_status = false; if (file.exists()) { file.delete(); } id = 4; } catch (SocketTimeoutException e) // time out { Log.d("Timeout", "Timeout"); task_status = false; if (file.exists()) { file.delete(); } id = 7; } catch (Exception e) // General error { task_status = false; if (file.exists()) { file.delete(); } id = 8; } Log.d("Type", String.valueOf(id)); Log.d("StartOk3", "Como he llegado hasta aqu?"); // notify completion Log.d("ID", String.valueOf(id)); return id; }
From source file:org.sakaiproject.lessonbuildertool.tool.beans.SimplePageBean.java
public String getTypeOfUrl(String url) { String mimeType = "text/html"; // try to find the mime type of the remote resource // this is only likely to be a problem if someone is pointing to // a url within Sakai. We think in realistic cases those that are // files will be handled as files, so anything that comes where // will be HTML. That's the default if this fails. URLConnection conn = null;//from w ww .ja v a 2 s . c om try { conn = new URL(new URL(ServerConfigurationService.getServerUrl()), url).openConnection(); conn.setConnectTimeout(10000); conn.setReadTimeout(10000); // generate cookie based on code in RequestFilter.java //String suffix = System.getProperty("sakai.serverId"); //if (suffix == null || suffix.equals("")) // suffix = "sakai"; //Session s = sessionManager.getCurrentSession(); //conn.setRequestProperty("Cookie", "JSESSIONID=" + s.getId() + "." + suffix); conn.connect(); String t = conn.getContentType(); if (t != null && !t.equals("")) { int i = t.indexOf(";"); if (i >= 0) t = t.substring(0, i); t = t.trim(); mimeType = t; } } catch (Exception e) { log.error("getTypeOfUrl connection error " + e); } finally { if (conn != null) { try { conn.getInputStream().close(); } catch (Exception e) { log.error("getTypeOfUrl unable to close " + e); } } } return mimeType; }
From source file:com.cloud.hypervisor.xen.resource.CitrixResourceBase.java
protected Answer executeProxyLoadScan(final Command cmd, final long proxyVmId, final String proxyVmName, final String proxyManagementIp, final int cmdPort) { String result = null;//from ww w. j a v a 2 s .c o m final StringBuffer sb = new StringBuffer(); sb.append("http://").append(proxyManagementIp).append(":" + cmdPort).append("/cmd/getstatus"); boolean success = true; try { final URL url = new URL(sb.toString()); final URLConnection conn = url.openConnection(); // setting TIMEOUTs to avoid possible waiting until death situations conn.setConnectTimeout(5000); conn.setReadTimeout(5000); final InputStream is = conn.getInputStream(); final BufferedReader reader = new BufferedReader(new InputStreamReader(is)); final StringBuilder sb2 = new StringBuilder(); String line = null; try { while ((line = reader.readLine()) != null) { sb2.append(line + "\n"); } result = sb2.toString(); } catch (final IOException e) { success = false; } finally { try { is.close(); } catch (final IOException e) { s_logger.warn("Exception when closing , console proxy address : " + proxyManagementIp); success = false; } } } catch (final IOException e) { s_logger.warn( "Unable to open console proxy command port url, console proxy address : " + proxyManagementIp); success = false; } return new ConsoleProxyLoadAnswer(cmd, proxyVmId, proxyVmName, success, result); }