List of usage examples for java.net HttpURLConnection getContentLength
public int getContentLength()
From source file:com.aniruddhc.acemusic.player.AsyncTasks.AsyncAutoGetAlbumArtTask.java
@Override protected Void doInBackground(String... params) { //First, we'll go through all the songs in the music library DB and get their attributes. dbHelper = new DBAccessHelper(mContext); String selection = DBAccessHelper.SONG_SOURCE + "<>" + "'GOOGLE_PLAY_MUSIC'"; String[] projection = { DBAccessHelper._ID, DBAccessHelper.SONG_FILE_PATH, DBAccessHelper.SONG_ALBUM, DBAccessHelper.SONG_ARTIST, DBAccessHelper.SONG_TITLE }; Cursor cursor = dbHelper.getWritableDatabase().query(DBAccessHelper.MUSIC_LIBRARY_TABLE, projection, selection, null, null, null, null); if (cursor.getCount() != 0) { cursor.moveToFirst();//w w w. j a v a 2 s .c o m dataURIsList.add(cursor.getString(1)); albumsList.add(cursor.getString(2)); artistsList.add(cursor.getString(3)); while (cursor.moveToNext()) { dataURIsList.add(cursor.getString(1)); albumsList.add(cursor.getString(2)); artistsList.add(cursor.getString(3)); } } else { //The user doesn't have any music so let's get outta here. return null; } pd.setMax(dataURIsList.size()); //Now that we have the attributes of the songs, we'll go through them each and check for missing covers. for (int i = 0; i < dataURIsList.size(); i++) { try { file = new File(dataURIsList.get(i)); } catch (Exception e) { continue; } audioFile = null; try { audioFile = AudioFileIO.read(file); } catch (CannotReadException e2) { // TODO Auto-generated catch block continue; } catch (IOException e2) { // TODO Auto-generated catch block continue; } catch (TagException e2) { // TODO Auto-generated catch block continue; } catch (ReadOnlyFileException e2) { // TODO Auto-generated catch block continue; } catch (InvalidAudioFrameException e2) { // TODO Auto-generated catch block continue; } Tag tag = audioFile.getTag(); //Set the destination directory for the xml file. File SDCardRoot = Environment.getExternalStorageDirectory(); File xmlFile = new File(SDCardRoot, "albumArt.xml"); if (tag != null) { String title = tag.getFirst(FieldKey.TITLE); String checkingMessage = mContext.getResources().getString(R.string.checking_if) + " " + title + " " + mContext.getResources().getString(R.string.has_album_art) + "."; currentProgress = currentProgress + 1; String[] checkingProgressParams = { checkingMessage, "" + currentProgress }; publishProgress(checkingProgressParams); List<Artwork> artworkList = tag.getArtworkList(); if (artworkList.size() == 0) { //Since the file doesn't have any album artwork, we'll have to download it. //Get the artist and album name of the file we're working with. String artist = tag.getFirst(FieldKey.ARTIST); String album = tag.getFirst(FieldKey.ALBUM); //Update the progress dialog. String message = mContext.getResources().getString(R.string.downloading_artwork_for) + " " + title; String[] progressParams = { message, "" + currentProgress }; publishProgress(progressParams); //Remove any unacceptable characters. if (artist.contains("#")) { artist = artist.replace("#", ""); } if (artist.contains("$")) { artist = artist.replace("$", ""); } if (artist.contains("@")) { artist = artist.replace("@", ""); } if (album.contains("#")) { album = album.replace("#", ""); } if (album.contains("$")) { album = album.replace("$", ""); } if (album.contains("@")) { album = album.replace("@", ""); } //Replace any spaces in the artist and album fields with "%20". if (artist.contains(" ")) { artist = artist.replace(" ", "%20"); } if (album.contains(" ")) { album = album.replace(" ", "%20"); } //Construct the url for the HTTP request. URL url = null; try { url = new URL( "http://itunes.apple.com/search?term=" + artist + "+" + album + "&entity=album"); } catch (MalformedURLException e1) { // TODO Auto-generated catch block continue; } String xml = null; try { //Create a new HTTP connection. HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.connect(); //Check if albumArt.xml already exists and delete it. if (xmlFile.exists()) { xmlFile.delete(); } //Create the OuputStream that will be used to store the downloaded data into the file. FileOutputStream fileOutput = new FileOutputStream(xmlFile); //Create the InputStream that will read the data from the HTTP connection. InputStream inputStream = urlConnection.getInputStream(); //Total size of target file. int totalSize = urlConnection.getContentLength(); //Temp variable that stores the number of downloaded bytes. int downloadedSize = 0; //Create a buffer to store the downloaded bytes. buffer = new byte[1024]; int bufferLength = 0; //Now read through the buffer and write the contents to the file. while ((bufferLength = inputStream.read(buffer)) > 0) { fileOutput.write(buffer, 0, bufferLength); downloadedSize += bufferLength; } //Close the File Output Stream. fileOutput.close(); } catch (MalformedURLException e) { //TODO Auto-generated method stub continue; } catch (IOException e) { // TODO Auto-generated method stub continue; } //Load the XML file into a String variable for local use. String xmlAsString = null; try { xmlAsString = FileUtils.readFileToString(xmlFile); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } //Extract the albumArt parameter from the XML file. artworkURL = StringUtils.substringBetween(xmlAsString, "\"artworkUrl100\":\"", "\","); if (artworkURL == null) { //Check and see if a lower resolution image available. artworkURL = StringUtils.substringBetween(xmlAsString, "\"artworkUrl60\":\"", "\","); if (artworkURL == null) { //Can't do anything about that here. } else { //Replace "100x100" with "600x600" to retrieve larger album art images. artworkURL = artworkURL.replace("100x100", "600x600"); } } else { //Replace "100x100" with "600x600" to retrieve larger album art images. artworkURL = artworkURL.replace("100x100", "600x600"); } //If no URL has been found, there's no point in continuing. if (artworkURL != null) { artworkBitmap = null; artworkBitmap = mApp.getImageLoader().loadImageSync(artworkURL); File artworkFile = new File(Environment.getExternalStorageDirectory() + "/artwork.jpg"); //Save the artwork. try { FileOutputStream out = new FileOutputStream(artworkFile); artworkBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out); } catch (Exception e) { e.printStackTrace(); } finally { Artwork artwork = null; try { artwork = ArtworkFactory.createArtworkFromFile(artworkFile); } catch (IOException e) { // TODO Auto-generated catch block setArtworkAsFile(artworkFile, dataURIsList.get(i)); continue; } catch (ArrayIndexOutOfBoundsException e) { // TODO Auto-generated catch block setArtworkAsFile(artworkFile, dataURIsList.get(i)); continue; } catch (Exception e) { e.printStackTrace(); setArtworkAsFile(artworkFile, dataURIsList.get(i)); continue; } catch (Error e) { e.printStackTrace(); setArtworkAsFile(artworkFile, dataURIsList.get(i)); continue; } if (artwork != null) { try { //Remove the current artwork field and recreate it. tag.deleteArtworkField(); tag.addField(artwork); } catch (Exception e) { // TODO Auto-generated catch block setArtworkAsFile(artworkFile, dataURIsList.get(i)); continue; } catch (Error e) { e.printStackTrace(); setArtworkAsFile(artworkFile, dataURIsList.get(i)); continue; } try { audioFile.commit(); } catch (CannotWriteException e) { // TODO Auto-generated catch block setArtworkAsFile(artworkFile, dataURIsList.get(i)); continue; } catch (Error e) { e.printStackTrace(); setArtworkAsFile(artworkFile, dataURIsList.get(i)); continue; } } //Delete the temporary files that we stored during the fetching process. if (artworkFile.exists()) { artworkFile.delete(); } if (xmlFile.exists()) { xmlFile.delete(); } //Set the files to null to help clean up memory. artworkBitmap = null; audioFile = null; tag = null; xmlFile = null; artworkFile = null; } } } } } audioFile = null; file = null; //System.gc(); return null; }
From source file:com.sogrey.sinaweibo.utils.FileUtil.java
/** * ????./*from w ww .j av a2s.c o m*/ * * @param Url * * @return int ? */ public static int getContentLengthFromUrl(String Url) { int mContentLength = 0; try { URL url = new URL(Url); HttpURLConnection mHttpURLConnection = (HttpURLConnection) url.openConnection(); mHttpURLConnection.setConnectTimeout(5 * 1000); mHttpURLConnection.setRequestMethod("GET"); mHttpURLConnection.setRequestProperty("Accept", "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*"); mHttpURLConnection.setRequestProperty("Accept-Language", "zh-CN"); mHttpURLConnection.setRequestProperty("Referer", Url); mHttpURLConnection.setRequestProperty("Charset", "UTF-8"); mHttpURLConnection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)"); mHttpURLConnection.setRequestProperty("Connection", "Keep-Alive"); mHttpURLConnection.connect(); if (mHttpURLConnection.getResponseCode() == 200) { // ???? mContentLength = mHttpURLConnection.getContentLength(); } } catch (Exception e) { e.printStackTrace(); LogUtil.d(FileUtil.class, "?" + e.getMessage()); } return mContentLength; }
From source file:com.roamprocess1.roaming4world.ui.messages.MessageAdapter.java
public boolean resumeImages(String msgSubject) { File file = null;//from w w w . ja va2 s. c om long fileLength; try { String filename = "", num = ""; URL url = new URL(imageUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setDoOutput(true); connection.connect(); num = getNumber(msgSubject); filename = getTimestamp(msgSubject); file = new File(fileDir + "/" + getNumber(msgSubject) + "/Recieved", filename); if (!file.exists()) { file.createNewFile(); } FileOutputStream fileOutput = new FileOutputStream(file); InputStream inputStream = connection.getInputStream(); int totalSize = connection.getContentLength(); Long downloadedSize = (long) 0; byte[] buffer = new byte[1024]; int bufferLength = 0; while ((bufferLength = inputStream.read(buffer)) > 0) { fileOutput.write(buffer, 0, bufferLength); downloadedSize += bufferLength; Log.i("Progress:", "downloadedSize:" + downloadedSize + "totalSize:" + totalSize); } fileOutput.close(); Log.d("downloadedSize", downloadedSize + " @"); if (downloadedSize == totalSize) { downloadedimageuri = file.getAbsolutePath(); return true; } if (file.exists()) { connection.setAllowUserInteraction(true); connection.setRequestProperty("Range", "bytes=" + file.length() + "-"); } connection.setConnectTimeout(14000); connection.setReadTimeout(20000); connection.connect(); if (connection.getResponseCode() / 100 != 2) throw new Exception("Invalid response code!"); else { String connectionField = connection.getHeaderField("content-range"); if (connectionField != null) { String[] connectionRanges = connectionField.substring("bytes=".length()).split("-"); downloadedSize = Long.valueOf(connectionRanges[0]); } if (connectionField == null && file.exists()) file.delete(); fileLength = connection.getContentLength() + downloadedSize; BufferedInputStream input = new BufferedInputStream(connection.getInputStream()); RandomAccessFile output = new RandomAccessFile(file, "rw"); output.seek(downloadedSize); byte data[] = new byte[1024]; int count = 0; int __progress = 0; while ((count = input.read(data, 0, 1024)) != -1 && __progress != 100) { downloadedSize += count; output.write(data, 0, count); __progress = (int) ((downloadedSize * 100) / fileLength); } output.close(); input.close(); } } catch (Exception e) { e.printStackTrace(); return false; } return false; }
From source file:com.becapps.easydownloader.ShareActivity.java
private String getVideoFileSize(String link) { String size;//from w ww . j a va2 s . c o m try { final URL uri = new URL(link); HttpURLConnection ucon = (HttpURLConnection) uri.openConnection(); ucon.connect(); int file_size = ucon.getContentLength(); size = MakeSizeHumanReadable(file_size, true); } catch (IOException e) { size = "n.a."; } return size; }
From source file:RhodesService.java
private File downloadPackage(String url) throws IOException { final Context ctx = RhodesActivity.getContext(); final Thread thisThread = Thread.currentThread(); final Runnable cancelAction = new Runnable() { public void run() { thisThread.interrupt();/*w ww . j a v a 2 s .c o m*/ } }; BroadcastReceiver downloadReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(ACTION_ASK_CANCEL_DOWNLOAD)) { AlertDialog.Builder builder = new AlertDialog.Builder(ctx); builder.setMessage("Cancel download?"); AlertDialog dialog = builder.create(); dialog.setButton(AlertDialog.BUTTON_POSITIVE, ctx.getText(android.R.string.yes), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { cancelAction.run(); } }); dialog.setButton(AlertDialog.BUTTON_NEGATIVE, ctx.getText(android.R.string.no), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // Nothing } }); dialog.show(); } else if (action.equals(ACTION_CANCEL_DOWNLOAD)) { cancelAction.run(); } } }; IntentFilter filter = new IntentFilter(); filter.addAction(ACTION_ASK_CANCEL_DOWNLOAD); filter.addAction(ACTION_CANCEL_DOWNLOAD); ctx.registerReceiver(downloadReceiver, filter); File tmpFile = null; InputStream is = null; OutputStream os = null; try { updateDownloadNotification(url, -1, 0); /* List<File> folders = new ArrayList<File>(); folders.add(Environment.getDownloadCacheDirectory()); folders.add(Environment.getDataDirectory()); folders.add(ctx.getCacheDir()); folders.add(ctx.getFilesDir()); try { folders.add(new File(ctx.getPackageManager().getApplicationInfo(ctx.getPackageName(), 0).dataDir)); } catch (NameNotFoundException e1) { // Ignore } folders.add(Environment.getExternalStorageDirectory()); for (File folder : folders) { File tmpRootFolder = new File(folder, "rhodownload"); File tmpFolder = new File(tmpRootFolder, ctx.getPackageName()); if (tmpFolder.exists()) deleteFilesInFolder(tmpFolder.getAbsolutePath()); else tmpFolder.mkdirs(); File of = new File(tmpFolder, UUID.randomUUID().toString() + ".apk"); Logger.D(TAG, "Check path " + of.getAbsolutePath() + "..."); try { os = new FileOutputStream(of); } catch (FileNotFoundException e) { Logger.D(TAG, "Can't open file " + of.getAbsolutePath() + ", check next path"); continue; } Logger.D(TAG, "File " + of.getAbsolutePath() + " succesfully opened for write, start download app"); tmpFile = of; break; } */ tmpFile = ctx.getFileStreamPath(UUID.randomUUID().toString() + ".apk"); os = ctx.openFileOutput(tmpFile.getName(), Context.MODE_WORLD_READABLE); Logger.D(TAG, "Download " + url + " to " + tmpFile.getAbsolutePath() + "..."); URL u = new URL(url); URLConnection conn = u.openConnection(); int totalBytes = -1; if (conn instanceof HttpURLConnection) { HttpURLConnection httpConn = (HttpURLConnection) conn; totalBytes = httpConn.getContentLength(); } is = conn.getInputStream(); int downloaded = 0; updateDownloadNotification(url, totalBytes, downloaded); long prevProgress = 0; byte[] buf = new byte[65536]; for (;;) { if (thisThread.isInterrupted()) { tmpFile.delete(); Logger.D(TAG, "Download of " + url + " was canceled"); return null; } int nread = is.read(buf); if (nread == -1) break; //Logger.D(TAG, "Downloading " + url + ": got " + nread + " bytes..."); os.write(buf, 0, nread); downloaded += nread; if (totalBytes > 0) { // Update progress view only if current progress is greater than // previous by more than 10%. Otherwise, if update it very frequently, // user will no have chance to click on notification view and cancel if need long progress = downloaded * 10 / totalBytes; if (progress > prevProgress) { updateDownloadNotification(url, totalBytes, downloaded); prevProgress = progress; } } } Logger.D(TAG, "File stored to " + tmpFile.getAbsolutePath()); return tmpFile; } catch (IOException e) { if (tmpFile != null) tmpFile.delete(); throw e; } finally { try { if (is != null) is.close(); } catch (IOException e) { } try { if (os != null) os.close(); } catch (IOException e) { } mNM.cancel(DOWNLOAD_PACKAGE_ID); ctx.unregisterReceiver(downloadReceiver); } }
From source file:com.cloudexplorers.plugins.childBrowser.ChildBrowser.java
/** * Display a new browser with the specified URL. * /*from w ww. ja v a 2 s .c om*/ * @param url * The url to load. * @param usePhoneGap * Load url in PhoneGap webview * @return "" if ok, or error message. */ public String openExternal(String urlToOpen, String encodedCredentials) { try { // set the download URL, a url that points to a file on the internet // this is the file to be downloaded URL url = new URL(urlToOpen); // create the new connection HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); // set up some things on the connection urlConnection.setRequestMethod("GET"); urlConnection.setDoOutput(true); urlConnection.setRequestProperty("Authorization", encodedCredentials); // and connect! urlConnection.connect(); // set the path where we want to save the file // in this case, going to save it on the root directory of the // sd card. File SDCardRoot = Environment.getExternalStorageDirectory(); // create a new file, specifying the path, and the filename // which we want to save the file as. File file = new File(SDCardRoot, "temp.pdf"); // this will be used to write the downloaded data into the file we created FileOutputStream fileOutput = new FileOutputStream(file); // this will be used in reading the data from the internet InputStream inputStream = urlConnection.getInputStream(); // this is the total size of the file int totalSize = urlConnection.getContentLength(); // variable to store total downloaded bytes int downloadedSize = 0; // create a buffer... byte[] buffer = new byte[1024]; int bufferLength = 0; // used to store a temporary size of the buffer // now, read through the input buffer and write the contents to the file while ((bufferLength = inputStream.read(buffer)) > 0) { // add the data in the buffer to the file in the file output stream (the // file on the sd card fileOutput.write(buffer, 0, bufferLength); // add up the size so we know how much is downloaded downloadedSize += bufferLength; } // close the output stream when done fileOutput.close(); Uri path = Uri.fromFile(file); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(path, "application/pdf"); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); this.cordova.getActivity().startActivity(intent); // catch some possible errors... } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return ""; }
From source file:it.baywaylabs.jumpersumo.utility.Finder.java
private Boolean downloadFileUrl(String url, File folder) { InputStream input = null;// w w w . j a va 2 s .c om OutputStream output = null; String baseName = FilenameUtils.getBaseName(url); String extension = FilenameUtils.getExtension(url); Log.d(TAG, "FileName: " + baseName + " - FileExt: " + extension); boolean success = true; if (!folder.exists()) { success = folder.mkdir(); } HttpURLConnection connection = null; if (!this.isUrl(url)) return false; Boolean downloadSuccess = false; try { URL Url = new URL(url); connection = (HttpURLConnection) Url.openConnection(); connection.connect(); // expect HTTP 200 OK, so we don't mistakenly save error report // instead of the file if (!url.endsWith(".csv") || !url.endsWith(".txt") && connection.getResponseCode() != HttpURLConnection.HTTP_OK) { Log.e(TAG, "Server returned HTTP " + connection.getResponseCode() + " " + connection.getResponseMessage()); return false; } // this will be useful to display download percentage // might be -1: server did not report the length int fileLength = connection.getContentLength(); // download the file input = connection.getInputStream(); output = new FileOutputStream(folder.getAbsolutePath() + "/" + baseName + "." + extension); byte data[] = new byte[4096]; long total = 0; int count; while ((count = input.read(data)) != -1) { total += count; output.write(data, 0, count); downloadSuccess = true; } } catch (Exception e) { Log.e(TAG, e.getMessage()); } finally { try { if (output != null) output.close(); if (input != null) input.close(); } catch (IOException ignored) { } if (connection != null) connection.disconnect(); } return true; }
From source file:com.qweex.callisto.podcast.DownloadTask.java
@Override protected Boolean doInBackground(String... params) { String TAG = StaticBlob.TAG(); boolean isVideo; Cursor current;/* ww w .j a v a2s . c om*/ long id = 0, identity = 0; Log.e(TAG, "Preparing to start: " + StaticBlob.databaseConnector.getActiveDownloads().getCount() + " downloads"); boolean canceled = false; while (StaticBlob.databaseConnector.getActiveDownloads().getCount() > 0) { if (isCancelled()) //Checks to see if it has been canceled by somewhere else { mNotificationManager.cancel(NOTIFICATION_ID); return false; } try { Cursor c = StaticBlob.databaseConnector.getActiveDownloads(); c.moveToFirst(); id = c.getLong(c.getColumnIndex("_id")); identity = c.getLong(c.getColumnIndex("identity")); isVideo = c.getInt(c.getColumnIndex("video")) > 0; current = StaticBlob.databaseConnector.getOneEpisode(identity); current.moveToFirst(); //Get info AudLink = current.getString(current.getColumnIndex("mp3link")); VidLink = current.getString(current.getColumnIndex("vidlink")); AudSize = current.getLong(current.getColumnIndex("mp3size")); VidSize = current.getLong(current.getColumnIndex("vidsize")); Title = current.getString(current.getColumnIndex("title")); Date = current.getString(current.getColumnIndex("date")); Show = current.getString(current.getColumnIndex("show")); Date = StaticBlob.sdfFile.format(StaticBlob.sdfRaw.parse(Date)); //Getting target Target = new File(StaticBlob.storage_path + File.separator + Show); Target.mkdirs(); if (Title.indexOf("|") > 0) Title = Title.substring(0, Title.indexOf("|")); Title = Title.trim(); AudFile = new File(Target, Date + "__" + StaticBlob.makeFileFriendly(Title) + EpisodeDesc.getExtension(AudLink)); if (VidLink != null) VidFile = new File(Target, Date + "__" + StaticBlob.makeFileFriendly(Title) + EpisodeDesc.getExtension(VidLink)); Target = isVideo ? VidFile : AudFile; //Prepare the HTTP Log.i(TAG, "Path: " + Target.getPath()); URL url = new URL(isVideo ? VidLink : AudLink); Log.i(TAG, "Starting download: " + url.toString()); Log.i(TAG, "Opening the connection..."); HttpURLConnection ucon = (HttpURLConnection) url.openConnection(); String lastModified = ucon.getHeaderField("Last-Modified"); ucon = (HttpURLConnection) url.openConnection(); if (Target.exists()) { ucon.setRequestProperty("Range", "bytes=" + Target.length() + "-"); ucon.setRequestProperty("If-Range", lastModified); } ucon.setReadTimeout(TIMEOUT_CONNECTION); ucon.setConnectTimeout(TIMEOUT_SOCKET); ucon.connect(); //Notification mBuilder.setProgress(100, 0, true) .setContentTitle(this.context.getResources().getString(R.string.downloading) + " " + StaticBlob.current_download + " " + this.context.getResources().getString(R.string.of) + " " + downloading_count) .setContentText(Show + ": " + Title); // Displays the progress bar for the first time. mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build()); //Actually do the DLing InputStream is = ucon.getInputStream(); TotalSize = ucon.getContentLength() + Target.length(); BufferedInputStream inStream = new BufferedInputStream(is, 1024 * 5); FileOutputStream outStream; byte buff[]; Log.i(TAG, "mmk skipping the downloaded portion..." + Target.length() + " of " + TotalSize); if (Target.exists()) //Append if it exists outStream = new FileOutputStream(Target, true); else outStream = new FileOutputStream(Target); buff = new byte[5 * 1024]; Log.i(TAG, "Getting content length (size)"); int len = 0; long downloadedSize = Target.length(), percentDone = 0; //SPEED_COUNT == the number of times through the buffer loop to go through before updating the speed // currentDownloadLoopIndex == ??? // lastTime == The time that the last speed was calculated at // all_spds == All speeds tabulated thus far from currentDownloadLoopIndex to SPEED_COUNT // avg_speed == the average speed when SPEED_COUNT is reached int SPEED_COUNT = 200, currentDownloadLoopIndex = 0; long lastTime = (new java.util.Date()).getTime(), all_spds = 0; double avg_speed = 0; DecimalFormat df = new DecimalFormat("#.##"); //Wifi lock WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); if (DownloadList.Download_wifiLock == null) DownloadList.Download_wifiLock = wm.createWifiLock(WifiManager.WIFI_MODE_FULL, "Callisto_download"); if (!DownloadList.Download_wifiLock.isHeld()) DownloadList.Download_wifiLock.acquire(); Log.i(TAG, "FINALLY starting the download"); inner_failures = 0; //-----------------Here is where the actual downloading happens---------------- while (len != -1) { Cursor active = StaticBlob.databaseConnector.getActiveDownloads(); if (StaticBlob.databaseConnector.getActiveDownloads().getCount() == 0) canceled = true; else { active.moveToFirst(); canceled = active.getLong(active.getColumnIndex("identity")) != identity; } if (canceled) { Log.i(TAG, "Download has been canceled, deleting."); Target.delete(); break; } if (isCancelled()) { mNotificationManager.cancel(NOTIFICATION_ID); return false; } try { len = inStream.read(buff); if (len == -1) break; outStream.write(buff, 0, len); downloadedSize += len; percentDone = downloadedSize * 100; percentDone /= TotalSize; //Add to the average speed long temp_spd = 0; long time_diff = ((new java.util.Date()).getTime() - lastTime); if (time_diff > 0) { temp_spd = len * 100 / time_diff; currentDownloadLoopIndex++; all_spds += temp_spd; lastTime = (new java.util.Date()).getTime(); } } catch (IOException e) { Log.e(TAG + ":IOException", "IO is a moon - " + inner_failures); inner_failures++; if (inner_failures == INNER_LIMIT) break; try { Thread.sleep(500); } catch (InterruptedException e1) { } //Add failure to average currentDownloadLoopIndex++; lastTime = (new java.util.Date()).getTime(); } catch (Exception e) { Log.e(TAG + ":??Exception", e.getClass() + " : " + e.getMessage()); try { Thread.sleep(500); } catch (InterruptedException e1) { } //Add failure to average currentDownloadLoopIndex++; lastTime = (new java.util.Date()).getTime(); } //If the time is right, get the average if (currentDownloadLoopIndex >= SPEED_COUNT) { avg_speed = all_spds * 1.0 / currentDownloadLoopIndex / 100; all_spds = 0; currentDownloadLoopIndex = 0; if (DownloadList.thisInstance != null) { DownloadList.thisInstance.runOnUiThread( DownloadList.thisInstance.new DownloadProgressUpdater((int) (TotalSize / 1000), (int) (downloadedSize / 1000))); } mBuilder.setProgress((int) (TotalSize / 1000), (int) (downloadedSize / 1000), false) .setContentTitle(this.context.getResources().getString(R.string.downloading) + " " + StaticBlob.current_download + " " + this.context.getResources().getString(R.string.of) + " " + downloading_count + " - " + percentDone + "% (" + df.format(avg_speed) + "kb/s)") .setContentText(Show + ": " + Title); // Displays the progress bar for the first time. mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build()); } } // END download of single file outStream.flush(); outStream.close(); inStream.close(); if (inner_failures == INNER_LIMIT) { throw new Exception("Inner exception has passed " + INNER_LIMIT); } Cursor active = StaticBlob.databaseConnector.getActiveDownloads(); if (StaticBlob.databaseConnector.getActiveDownloads().getCount() == 0) canceled = true; else { active.moveToFirst(); canceled = active.getLong(active.getColumnIndex("identity")) != identity; } if (!canceled) { Log.i(TAG, "Trying to finish with " + Target.length() + "==" + TotalSize); if (Target.length() == TotalSize) { StaticBlob.current_download++; Log.i(TAG, (inner_failures < INNER_LIMIT ? "Successfully" : "FAILED") + " downloaded to : " + Target.getPath()); //Move the download from active to completed. StaticBlob.databaseConnector.markDownloadComplete(id); Log.i(TAG, " " + DownloadList.rebuildHeaderThings); if (DownloadList.rebuildHeaderThings != null) DownloadList.rebuildHeaderThings.sendEmptyMessage(0); boolean queue = PreferenceManager.getDefaultSharedPreferences(context) .getBoolean("download_to_queue", false); if (queue) { StaticBlob.databaseConnector.appendToQueue(identity, false, isVideo); StaticBlob.playerInfo.update(context); } //Episode Desc if (EpisodeDesc.currentInstance != null) EpisodeDesc.currentInstance.determineButtons(); //ShowList if (ShowList.thisInstance != null && ShowList.thisInstance.currentDownloadItem != null) { ShowList.thisInstance.runOnUiThread(ShowList.thisInstance.new updateBoldOrItalic(id, ShowList.thisInstance.currentDownloadItem, AudFile, VidFile, AudSize, VidSize)); ShowList.thisInstance.currentDownloadItem = null; } } } else Target.delete(); } catch (ParseException e) { Log.e(TAG + ":ParseException", "Error parsing a date from the SQLite db: "); Log.e(TAG + ":ParseException", Date); Log.e(TAG + ":ParseException", "(This should never happen)."); outer_failures++; e.printStackTrace(); } catch (Exception e) { outer_failures++; Log.e(TAG + ":Exception " + e.getClass(), "[" + outer_failures + "] Msg: " + e.getMessage()); e.printStackTrace(); try { Thread.sleep(1000); } catch (InterruptedException e1) { } } if (outer_failures == OUTER_LIMIT) { boolean quit = false; //if(quit = aDownloads.charAt(1)=='x') // aDownloads = aDownloads.replaceAll("x",""); quit = true; if (DownloadList.rebuildHeaderThings != null) DownloadList.rebuildHeaderThings.sendEmptyMessage(0); failed++; outer_failures = 0; if (quit) break; } } Log.i(TAG, "Finished Downloading"); if (DownloadList.thisInstance != null) DownloadList.thisInstance.updateMenu(); //Wifi lock if (DownloadList.Download_wifiLock != null && DownloadList.Download_wifiLock.isHeld()) DownloadList.Download_wifiLock.release(); //Notification mNotificationManager.cancel(NOTIFICATION_ID); if (downloading_count > 0) { mBuilder.setProgress(100, 0, false) .setContentTitle("Finished downloading " + downloading_count + " files"); if (failed > 0) mBuilder.setContentText(failed + " failed, try them again later"); mBuilder.setAutoCancel(true); mBuilder.setOngoing(false); mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build()); StaticBlob.current_download = 1; downloading_count = 0; } else { StaticBlob.current_download = 1; downloading_count = 0; return false; } return true; }
From source file:org.apache.maven.wagon.providers.http.LightweightHttpWagon.java
public void fillInputData(InputData inputData) throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException { Resource resource = inputData.getResource(); String visitingUrl = buildUrl(resource.getName()); try {/* w w w. j a v a 2s .c o m*/ List<String> visitedUrls = new ArrayList<String>(); for (int redirectCount = 0; redirectCount < MAX_REDIRECTS; redirectCount++) { if (visitedUrls.contains(visitingUrl)) { throw new TransferFailedException("Cyclic http redirect detected. Aborting! " + visitingUrl); } visitedUrls.add(visitingUrl); URL url = new URL(visitingUrl); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(this.proxy); urlConnection.setRequestProperty("Accept-Encoding", "gzip"); if (!useCache) { urlConnection.setRequestProperty("Pragma", "no-cache"); } addHeaders(urlConnection); // TODO: handle all response codes int responseCode = urlConnection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_FORBIDDEN || responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) { throw new AuthorizationException("Access denied to: " + buildUrl(resource.getName())); } if (responseCode == HttpURLConnection.HTTP_MOVED_PERM || responseCode == HttpURLConnection.HTTP_MOVED_TEMP) { visitingUrl = urlConnection.getHeaderField("Location"); continue; } InputStream is = urlConnection.getInputStream(); String contentEncoding = urlConnection.getHeaderField("Content-Encoding"); boolean isGZipped = contentEncoding != null && "gzip".equalsIgnoreCase(contentEncoding); if (isGZipped) { is = new GZIPInputStream(is); } inputData.setInputStream(is); resource.setLastModified(urlConnection.getLastModified()); resource.setContentLength(urlConnection.getContentLength()); break; } } catch (MalformedURLException e) { throw new ResourceDoesNotExistException("Invalid repository URL: " + e.getMessage(), e); } catch (FileNotFoundException e) { throw new ResourceDoesNotExistException("Unable to locate resource in repository", e); } catch (IOException e) { StringBuilder message = new StringBuilder("Error transferring file: "); message.append(e.getMessage()); message.append(" from " + visitingUrl); if (getProxyInfo() != null && getProxyInfo().getHost() != null) { message.append(" with proxyInfo ").append(getProxyInfo().toString()); } throw new TransferFailedException(message.toString(), e); } }
From source file:com.roamprocess1.roaming4world.syncadapter.SyncAdapter.java
public String getImages(String uri, String number) { String sdcardDir = Environment.getExternalStorageDirectory() + ""; File file = null;//from w w w . ja v a 2 s . c o m if (!uri.equals(no_image)) { String filepath = ""; try { URL url = new URL(uri); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.setDoOutput(true); urlConnection.connect(); String filename = number + ".png"; File imageDirectory = new File(sdcardDir + "/R4W/"); if (!imageDirectory.exists()) { imageDirectory.mkdir(); } File imageDirectoryprofile = new File(sdcardDir + "/R4W/ProfilePic"); if (!imageDirectoryprofile.exists()) { imageDirectoryprofile.mkdir(); } file = new File(imageDirectoryprofile.getAbsolutePath(), filename); if (file.createNewFile()) { file.createNewFile(); } FileOutputStream fileOutput = new FileOutputStream(file); InputStream inputStream = urlConnection.getInputStream(); int totalSize = urlConnection.getContentLength(); int downloadedSize = 0; byte[] buffer = new byte[1024]; int bufferLength = 0; while ((bufferLength = inputStream.read(buffer)) > 0) { fileOutput.write(buffer, 0, bufferLength); downloadedSize += bufferLength; Log.i("Progress:", "downloadedSize:" + downloadedSize + "totalSize:" + totalSize); } fileOutput.close(); if (downloadedSize == totalSize) filepath = file.getPath(); } catch (Exception e) { filepath = ""; e.printStackTrace(); if (file.exists()) { file.delete(); } } Log.i("filepath:", " " + filepath); return filepath; } else { return no_image; } }