List of usage examples for java.net URLConnection getContentLength
public int getContentLength()
From source file:grafix.basedados.Download.java
public String baixaString() { String retorno = null;//w ww . j a va 2 s. c om URL url = null; URLConnection con = null; try { url = new URL(this.url); con = url.openConnection(); } catch (Exception ex) { ex.printStackTrace(); return retorno; } if (this.usaProxy) { System.setProperty("http.proxySet", "true"); System.setProperty("http.proxyHost", this.servidorProxy); System.setProperty("http.proxyPort", String.format("%d", this.portaProxy)); System.setProperty("http.proxyType", "4"); if (this.usuarioProxy != null) { if (this.usuarioProxy.length() > 0) { String proxyUser = this.usuarioProxy, proxyPassword = this.senhaProxy; con.setRequestProperty("Proxy-Authorization", "Basic " + Base64.encodeToString((proxyUser + ":" + proxyPassword).getBytes(), false)); } } } try { int len = con.getContentLength(); byte[] b = new byte[len]; InputStream is = con.getInputStream(); is.read(b, 0, len); String s = new String(b); return s; } catch (MalformedURLException ex) { System.out.println("Erro"); return ""; } catch (IOException ex) { System.out.println("Erro"); System.out.println(ex); return ""; } }
From source file:CB_Utils.Util.Downloader.java
/** * Start downloading the remote resource. The target object should not be accessed until after calling waitUntilCompleted(). *///w w w .j av a 2 s .co m @Override public void run() { synchronized (stateLock) { if (started) { return; } else { started = true; running = true; } } BufferedInputStream bis = null; BufferedOutputStream bos = null; BufferedReader br = null; try { /* open connection to the URL */ checkState(); progressString = "Opening connection to remote resource"; progressUpdated = true; final URLConnection link; try { link = url.openConnection(); link.connect(); } catch (Exception e) { progressString = "Failed to open connection to remote resource"; progressUpdated = true; throw e; } /* get length of the remote resource */ checkState(); progressString = "Getting length of remote resource"; progressUpdated = true; /* get size of webpage in bytes; -1 if unknown */ final int length = link.getContentLength(); synchronized (lengthLock) { totalLength = length; } progressUpdated = true; /* open input stream to remote resource */ checkState(); progressString = "Opening input stream to remote resource"; progressUpdated = true; InputStream input = null; try { if (totalLength < 1) { // load with http Request HttpGet httppost = new HttpGet(url.toString()); // Execute HTTP Post Request try { HttpParams httpParameters = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, HttpUtils.conectionTimeout); HttpConnectionParams.setSoTimeout(httpParameters, HttpUtils.socketTimeout); DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters); HttpResponse response = httpClient.execute(httppost); input = response.getEntity().getContent(); } catch (ConnectTimeoutException e1) { e1.printStackTrace(); } catch (ClientProtocolException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } } else { input = link.getInputStream(); } if (target instanceof File) { bis = new BufferedInputStream(input); } else if (target instanceof StringBuilder) { final String contentType = link.getContentType().toLowerCase(Locale.ENGLISH); /* look for charset, if specified */ String charset = null; final Matcher m = Pattern.compile(".*charset[\\s]*=([^;]++).*").matcher(contentType); if (m.find()) { charset = m.group(1).trim(); } if ((charset != null) && charset.length() > 0) { try { br = new BufferedReader(new InputStreamReader(input, charset)); } catch (Exception e) { br = null; } } if (br == null) { br = new BufferedReader(new InputStreamReader(input)); } } } catch (Exception e) { progressString = "Failed to open input stream to remote resource"; progressUpdated = true; throw e; } /* open output stream, if necessary */ if (target instanceof File) { checkState(); progressString = "Opening output stream to local file"; progressUpdated = true; try { /* create parent directories, if necessary */ final File f = (File) target; final File parent = f.getParentFile(); if ((parent != null) && !parent.exists()) { parent.mkdirs(); } bos = new BufferedOutputStream(f.getFileOutputStream()); } catch (Exception e) { progressString = "Failed to open output stream to local file"; progressUpdated = true; throw e; } } /* download remote resource iteratively */ progressString = "Downloading"; progressUpdated = true; try { if (target instanceof File) { final byte[] byteBuffer = new byte[BUFFER_SIZE]; while (true) { checkState(); final int byteCount = bis.read(byteBuffer, 0, BUFFER_SIZE); /* check for end-of-stream */ if (byteCount == -1) { break; } bos.write(byteBuffer, 0, byteCount); synchronized (lengthLock) { downloadedLength += byteCount; } progressUpdated = true; } } else if (target instanceof StringBuilder) { final char[] charBuffer = new char[BUFFER_SIZE]; final StringBuilder sb = (StringBuilder) target; while (true) { checkState(); final int charCount = br.read(charBuffer, 0, BUFFER_SIZE); /* check for end-of-stream */ if (charCount == -1) { break; } sb.append(charBuffer, 0, charCount); synchronized (lengthLock) { downloadedLength += charCount; /* may be inaccurate because byte != char */ } progressUpdated = true; } } } catch (Exception e) { progressString = "Failed to download remote resource"; progressUpdated = true; throw e; } /* download completed successfully */ progressString = "Download completed"; progressUpdated = true; } catch (Exception e) { error = e; } finally { /* clean-up */ for (Closeable c : new Closeable[] { bis, br, bos }) { if (c != null) { try { c.close(); } catch (Exception e) { /* ignore */ } } } synchronized (stateLock) { running = false; completed = true; } } }
From source file:org.springframework.js.resource.ResourceServlet.java
private void prepareResponse(HttpServletResponse response, URL[] resources, String rawResourcePath) throws IOException { long lastModified = -1; int contentLength = 0; String mimeType = null;/* w w w . j a v a 2 s.c o m*/ for (URL resource : resources) { URLConnection resourceConn = resource.openConnection(); if (resourceConn.getLastModified() > lastModified) { lastModified = resourceConn.getLastModified(); } String currentMimeType = getServletContext().getMimeType(resource.getPath()); if (currentMimeType == null) { String extension = resource.getPath().substring(resource.getPath().lastIndexOf('.')); currentMimeType = defaultMimeTypes.get(extension); } if (mimeType == null) { mimeType = currentMimeType; } else if (!mimeType.equals(currentMimeType)) { throw new MalformedURLException("Combined resource path: " + rawResourcePath + " is invalid. All resources in a combined resource path must be of the same mime type."); } contentLength += resourceConn.getContentLength(); } response.setContentType(mimeType); response.setHeader(HTTP_CONTENT_LENGTH_HEADER, Long.toString(contentLength)); response.setDateHeader(HTTP_LAST_MODIFIED_HEADER, lastModified); if (cacheTimeout > 0) { configureCaching(response, cacheTimeout); } }
From source file:org.impalaframework.web.servlet.ResourceServlet.java
private void prepareResponse(HttpServletResponse response, URL[] resources, String rawResourcePath) throws IOException { long lastModified = -1; int contentLength = 0; String mimeType = null;// w ww . j a v a 2 s .co m for (int i = 0; i < resources.length; i++) { URLConnection resourceConn = resources[i].openConnection(); if (resourceConn.getLastModified() > lastModified) { lastModified = resourceConn.getLastModified(); } String currentMimeType = getServletContext().getMimeType(resources[i].getPath()); if (currentMimeType == null) { String extension = resources[i].getPath().substring(resources[i].getPath().lastIndexOf('.')); currentMimeType = (String) defaultMimeTypes.get(extension); } if (mimeType == null) { mimeType = currentMimeType; } else if (!mimeType.equals(currentMimeType)) { throw new MalformedURLException("Combined resource path: " + rawResourcePath + " is invalid. All resources in a combined resource path must be of the same mime type."); } contentLength += resourceConn.getContentLength(); } response.setContentType(mimeType); response.setHeader(HTTP_CONTENT_LENGTH_HEADER, Long.toString(contentLength)); response.setDateHeader(HTTP_LAST_MODIFIED_HEADER, lastModified); if (cacheTimeout > 0) { configureCaching(response, cacheTimeout); } }
From source file:com.apache.ivy.BasicURLHandler.java
public void download(URL src, File dest, CopyProgressListener l) throws IOException { // Install the IvyAuthenticator if ("http".equals(src.getProtocol()) || "https".equals(src.getProtocol())) { IvyAuthenticator.install();/*from w w w . j a va 2s. c o m*/ } URLConnection srcConn = null; try { src = normalizeToURL(src); srcConn = src.openConnection(); srcConn.setRequestProperty("User-Agent", "Apache Ivy/1.0");// + Ivy.getIvyVersion()); srcConn.setRequestProperty("Accept-Encoding", "gzip,deflate"); if (srcConn instanceof HttpURLConnection) { HttpURLConnection httpCon = (HttpURLConnection) srcConn; if (!checkStatusCode(src, httpCon)) { throw new IOException("The HTTP response code for " + src + " did not indicate a success." + " See log for more detail."); } } // do the download InputStream inStream = getDecodingInputStream(srcConn.getContentEncoding(), srcConn.getInputStream()); FileUtil.copy(inStream, dest, l); // check content length only if content was not encoded if (srcConn.getContentEncoding() == null) { int contentLength = srcConn.getContentLength(); if (contentLength != -1 && dest.length() != contentLength) { dest.delete(); throw new IOException("Downloaded file size doesn't match expected Content Length for " + src + ". Please retry."); } } // update modification date long lastModified = srcConn.getLastModified(); if (lastModified > 0) { dest.setLastModified(lastModified); } } finally { disconnect(srcConn); } }
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. */// w ww. j av a 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.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 ww w. jav a 2 s. 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:com.ibm.iotf.sample.devicemgmt.device.HTTPFirmwareDownload.java
public String downloadFirmware() { System.out.println(CLASS_NAME + ": Firmware Download start..."); boolean success = false; URL firmwareURL = null;//from w ww.j a va 2 s . c om URLConnection urlConnection = null; String downloadedFirmwareName = null; Properties props = new Properties(); try { props.load(HTTPFirmwareDownload.class.getResourceAsStream(PROPERTIES_FILE_NAME)); } catch (IOException e1) { System.err.println("Not able to read the properties file, exiting.."); System.exit(-1); } String username = trimedValue(props.getProperty("User-Name")); String password = trimedValue(props.getProperty("Password")); String dbName = trimedValue(props.getProperty("Repository-DB")); /** * start downloading the firmware image */ try { System.out.println(CLASS_NAME + ": Downloading Firmware from URL " + deviceFirmware.getUrl()); firmwareURL = new URL(deviceFirmware.getUrl()); urlConnection = firmwareURL.openConnection(); byte[] encoding = Base64.encodeBase64(new String(username + ":" + password).getBytes()); String encodedString = "Basic " + new String(encoding); urlConnection.setRequestProperty("Authorization", encodedString); int fileSize = urlConnection.getContentLength(); if (deviceFirmware.getName() != null && !"".equals(deviceFirmware.getName())) { downloadedFirmwareName = deviceFirmware.getName(); } else { // use the timestamp as the name downloadedFirmwareName = "firmware_" + new Date().getTime() + ".deb"; } File file = new File(downloadedFirmwareName); BufferedInputStream bis = new BufferedInputStream(urlConnection.getInputStream()); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file.getName())); // count the download size to send the progress report as DiagLog to Watson IoT Platform int downloadedSize = 0; int data = bis.read(); downloadedSize += 1; if (data != -1) { bos.write(data); byte[] block = new byte[1024 * 10]; int previousProgress = 0; while (true) { int len = bis.read(block, 0, block.length); downloadedSize = downloadedSize + len; if (len != -1) { // Send the progress update if (fileSize > 0) { int progress = (int) (((float) downloadedSize / fileSize) * 100); if (progress > previousProgress) { String message = "Firmware Download progress: " + progress + "%"; addDiagLog(message, new Date(), LogSeverity.informational); System.out.println(message); } } else { // If we can't retrieve the filesize, let us update how much we have download so far String message = "Downloaded : " + downloadedSize + " bytes so far"; addDiagLog(message, new Date(), LogSeverity.informational); System.out.println(message); } bos.write(block, 0, len); } else { break; } } bos.close(); bis.close(); success = true; } else { //There is no data to read, so throw an exception if (requirePlatformUpdate) { deviceFirmware.setUpdateStatus(FirmwareUpdateStatus.INVALID_URI); } } // Verify the firmware image if verifier is set if (deviceFirmware.getVerifier() != null && !deviceFirmware.getVerifier().equals("")) { success = verifyFirmware(file, deviceFirmware.getVerifier()); /** * As per the documentation, If a firmware verifier has been set, the device should * attempt to verify the firmware image. * * If the image verification fails, mgmt.firmware.state should be set to 0 (Idle) * and mgmt.firmware.updateStatus should be set to the error status value 4 (Verification Failed). */ if (success == false) { if (requirePlatformUpdate) { deviceFirmware.setUpdateStatus(FirmwareUpdateStatus.VERIFICATION_FAILED); } // the firmware state is updated to IDLE below } } } catch (MalformedURLException me) { // Invalid URL, so set the status to reflect the same, if (requirePlatformUpdate) { deviceFirmware.setUpdateStatus(FirmwareUpdateStatus.INVALID_URI); } me.printStackTrace(); } catch (IOException e) { if (requirePlatformUpdate) { deviceFirmware.setUpdateStatus(FirmwareUpdateStatus.CONNECTION_LOST); } e.printStackTrace(); } catch (OutOfMemoryError oom) { if (requirePlatformUpdate) { deviceFirmware.setUpdateStatus(FirmwareUpdateStatus.OUT_OF_MEMORY); } } /** * Set the firmware download and possibly the firmware update status * (will be sent later) accordingly */ if (success == true) { if (requirePlatformUpdate) { deviceFirmware.setUpdateStatus(FirmwareUpdateStatus.SUCCESS); deviceFirmware.setState(FirmwareState.DOWNLOADED); } } else { if (requirePlatformUpdate) { deviceFirmware.setState(FirmwareState.IDLE); } return null; } System.out.println(CLASS_NAME + ": Firmware Download END...(" + success + ")"); return downloadedFirmwareName; }
From source file:grafix.basedados.Download.java
public String baixaArquivoGZIP() { String retorno = null;//from ww w.jav a 2 s .c o m URL url = null; URLConnection con = null; try { url = new URL(this.url); con = url.openConnection(); } catch (Exception ex) { ex.printStackTrace(); return retorno; } if (this.usaProxy) { System.setProperty("http.proxySet", "true"); System.setProperty("http.proxyHost", this.servidorProxy); System.setProperty("http.proxyPort", String.format("%d", this.portaProxy)); System.setProperty("http.proxyType", "4"); if (this.usuarioProxy != null) { if (this.usuarioProxy.length() > 0) { String proxyUser = this.usuarioProxy, proxyPassword = this.senhaProxy; con.setRequestProperty("Proxy-Authorization", "Basic " + Base64.encodeToString((proxyUser + ":" + proxyPassword).getBytes(), false)); } } } GZIPInputStream gzip; try { gzip = new GZIPInputStream(con.getInputStream()); ByteArrayOutputStream os = new ByteArrayOutputStream(); int readLen = 0; byte[] buffer = new byte[4096]; int bytes = 0; // int sfs = gzip. //con.getInputStream().available(); int total = con.getContentLength(); if (this.mostraProgresso) this.formAtualizacao.definirPercentualProgresso(0); while ((readLen = gzip.read(buffer, 0, buffer.length)) > 0) { os.write(buffer, 0, readLen); // int sfs = con.getInputStream().available(); bytes += readLen; if (this.mostraProgresso) this.formAtualizacao.informaBytesLidos(bytes); // float sd = (float)(total-sfs)/(float)total*100.0f; // this.formAtualizacao.informarLog("Baixados" + (total - sfs) + " bytes de " + total + "progresso " + (int) sd); // this.formAtualizacao.definirPercentualProgresso( (int) sd); } retorno = os.toString(); } catch (IOException ex) { ex.printStackTrace(); } return retorno; }
From source file:org.matrix.androidsdk.db.MXMediaWorkerTask.java
@Override protected Bitmap doInBackground(Integer... params) { try {/*from w ww . j a v a 2 s.co m*/ // check the in-memory cache String key = mUrl; URL url = new URL(mUrl); Log.d(LOG_TAG, "BitmapWorkerTask open >>>>> " + mUrl); InputStream stream = null; Bitmap bitmap = null; long filelen = -1; URLConnection connection = null; try { connection = url.openConnection(); if (mHsConfig != null && connection instanceof HttpsURLConnection) { // Add SSL Socket factory. HttpsURLConnection sslConn = (HttpsURLConnection) connection; try { sslConn.setSSLSocketFactory(CertUtil.newPinnedSSLSocketFactory(mHsConfig)); 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(10 * 1000); filelen = connection.getContentLength(); stream = connection.getInputStream(); } catch (FileNotFoundException e) { 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.d(LOG_TAG, "MediaWorkerTask " + mUrl + " does not exist"); if (isBitmapDownload()) { bitmap = BitmapFactory.decodeResource(mApplicationContext.getResources(), android.R.drawable.ic_menu_gallery); // if some medias are not found // do not try to reload them until the next application launch. synchronized (mFileNotFoundUrlsList) { mFileNotFoundUrlsList.add(mUrl); } } } sendStart(); String filename = MXMediaWorkerTask.buildFileName(mUrl, mMimeType) + ".tmp"; FileOutputStream fos = new FileOutputStream(new File(mDirectoryFile, filename)); // a bitmap has been provided if (null != bitmap) { bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos); } else { try { int totalDownloaded = 0; byte[] buf = new byte[1024 * 32]; int len; while ((len = stream.read(buf)) != -1) { fos.write(buf, 0, len); totalDownloaded += len; int progress = 0; if (filelen > 0) { if (totalDownloaded >= filelen) { progress = 99; } else { progress = (int) (totalDownloaded * 100 / filelen); } } else { progress = -1; } Log.d(LOG_TAG, "download " + progress + " (" + mUrl + ")"); publishProgress(mProgress = progress); } mProgress = 100; } catch (OutOfMemoryError outOfMemoryError) { Log.e(LOG_TAG, "MediaWorkerTask : out of memory"); } catch (Exception e) { Log.e(LOG_TAG, "MediaWorkerTask fail to read image " + e.getMessage()); } close(stream); } fos.flush(); fos.close(); // the file has been successfully downloaded if (mProgress == 100) { try { File originalFile = new File(mDirectoryFile, filename); String newFileName = MXMediaWorkerTask.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.d(LOG_TAG, "download is done (" + mUrl + ")"); synchronized (mPendingDownloadByUrl) { mPendingDownloadByUrl.remove(mUrl); } // load the bitmap from the cache if (isBitmapDownload()) { // get the bitmap from the filesytem if (null == bitmap) { bitmap = MXMediaWorkerTask.bitmapForURL(mApplicationContext, mDirectoryFile, key, mRotation, mMimeType); } } return bitmap; } catch (Exception e) { // remove the image from the loading one // else the loading will be stucked (and never be tried again). synchronized (mPendingDownloadByUrl) { mPendingDownloadByUrl.remove(mUrl); } Log.e(LOG_TAG, "Unable to load bitmap: " + e); return null; } }