List of usage examples for org.apache.http.util ByteArrayBuffer append
public void append(int i)
From source file:pl.lewica.util.FileUtil.java
public static boolean fetchAndSaveImage(String sourceUrl, String destinationPath, boolean overwrite) throws IOException { File destinationFile = new File(destinationPath); if (destinationFile.exists() && !overwrite) { return false; }//from ww w . java 2s. c o m BufferedInputStream bis = null; FileOutputStream fos = null; try { URL url = new URL(sourceUrl); // See http://stackoverflow.com/questions/3498643/dalvik-message-default-buffer-size-used-in-bufferedinputstream-constructor-it/7516554#7516554 int bufferSize = 8192; bis = new BufferedInputStream(url.openStream(), bufferSize); ByteArrayBuffer bab = new ByteArrayBuffer(50); int current = 0; while ((current = bis.read()) != -1) { bab.append((byte) current); } fos = new FileOutputStream(destinationFile); fos.write(bab.toByteArray()); fos.close(); } catch (MalformedURLException e) { throw e; } catch (IOException e) { throw e; } finally { if (fos != null) { try { fos.close(); } catch (IOException ioe) { // This issue can be safely skipped but there's no harm in logging it Log.w("FileUtil", "Unable to close file output stream for " + sourceUrl); } } if (bis != null) { try { bis.close(); } catch (IOException ioe) { // This issue can be safely skipped but there's no harm in logging it Log.w("FileUtil", "Unable to close buffered input stream for " + sourceUrl); } } } return true; }
From source file:com.BibleQuote.utils.FsUtils.java
public static boolean loadContentFromURL(String fromURL, String toFile) { try {/*www .j a v a 2 s . c om*/ URL url = new URL("http://bible-desktop.com/xml" + fromURL); File file = new File(toFile); /* Open a connection to that URL. */ URLConnection ucon = url.openConnection(); /* Define InputStreams to read from the URLConnection */ InputStream is = ucon.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is); /* Read bytes to the Buffer until there is nothing more to read(-1) */ ByteArrayBuffer baf = new ByteArrayBuffer(50); int current = 0; while ((current = bis.read()) != -1) { baf.append((byte) current); } /* Convert the Bytes read to a String. */ FileOutputStream fos = new FileOutputStream(file); fos.write(baf.toByteArray()); fos.close(); } catch (IOException e) { Log.e(TAG, String.format("loadContentFromURL(%1$s, %2$s)", fromURL, toFile), e); return false; } return true; }
From source file:ota.otaupdates.utils.Utils.java
public static void DownloadFromUrl(String download_url, String fileName) { final String TAG = "Downloader"; if (!isMainThread()) { try {/*from ww w .j a v a 2 s.c om*/ URL url = new URL(download_url); if (!new File(DL_PATH).isDirectory()) { if (!new File(DL_PATH).mkdirs()) { Log.e(TAG, "Creating the directory " + DL_PATH + "failed"); } } File file = new File(DL_PATH + fileName); long startTine = System.currentTimeMillis(); Log.d(TAG, "Beginning download of " + url.getPath() + " to " + DL_PATH + fileName); /* * Open a connection and define Streams */ URLConnection ucon = url.openConnection(); InputStream is = ucon.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is); /* * Read bytes until there is nothing left */ ByteArrayBuffer baf = new ByteArrayBuffer(50); int current = 0; while ((current = bis.read()) != -1) { baf.append((byte) current); } /* Convert Bytes to a String */ FileOutputStream fos = new FileOutputStream(file); fos.write(baf.toByteArray()); fos.close(); Log.d(TAG, "Download finished in " + ((System.currentTimeMillis() - startTine) / 1000) + " seconds"); } catch (Exception e) { Log.e(TAG, "Error: " + e); e.printStackTrace(); } } else { Log.e(TAG, "Tried to run in Main Thread. Aborting..."); } }
From source file:com.fastbootmobile.encore.api.common.HttpGet.java
/** * Downloads the data from the provided URL. * @param inUrl The URL to get from//from w w w . ja va 2 s .c o m * @param query The query field. '?' + query will be appended automatically, and the query data * MUST be encoded properly. * @return A byte array of the data */ public static byte[] getBytes(String inUrl, String query, boolean cached) throws IOException, RateLimitException { final String formattedUrl = inUrl + (query.isEmpty() ? "" : ("?" + query)); Log.d(TAG, "Formatted URL: " + formattedUrl); URL url = new URL(formattedUrl); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestProperty("User-Agent", "OmniMusic/1.0-dev (http://www.omnirom.org)"); urlConnection.setUseCaches(cached); urlConnection.setInstanceFollowRedirects(true); int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale urlConnection.addRequestProperty("Cache-Control", "max-stale=" + maxStale); try { final int status = urlConnection.getResponseCode(); // MusicBrainz returns 503 Unavailable on rate limit errors. Parse the JSON anyway. if (status == HttpURLConnection.HTTP_OK) { InputStream in = new BufferedInputStream(urlConnection.getInputStream()); int contentLength = urlConnection.getContentLength(); if (contentLength <= 0) { // No length? Let's allocate 100KB. contentLength = 100 * 1024; } ByteArrayBuffer bab = new ByteArrayBuffer(contentLength); BufferedInputStream bis = new BufferedInputStream(in); int character; while ((character = bis.read()) != -1) { bab.append(character); } return bab.toByteArray(); } else if (status == HttpURLConnection.HTTP_NOT_FOUND) { // 404 return new byte[] {}; } else if (status == HttpURLConnection.HTTP_FORBIDDEN) { return new byte[] {}; } else if (status == HttpURLConnection.HTTP_UNAVAILABLE) { throw new RateLimitException(); } else if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == 307 /* HTTP/1.1 TEMPORARY REDIRECT */ || status == HttpURLConnection.HTTP_SEE_OTHER) { // We've been redirected, follow the new URL final String followUrl = urlConnection.getHeaderField("Location"); Log.e(TAG, "Redirected to: " + followUrl); return getBytes(followUrl, "", cached); } else { Log.e(TAG, "Error when fetching: " + formattedUrl + " (" + urlConnection.getResponseCode() + ")"); return new byte[] {}; } } finally { urlConnection.disconnect(); } }
From source file:org.ligi.android.dubwise_uavtalk.dashboard.DownloadDashboardImagesStatusAlertDialog.java
/** * //ww w. ja v a 2 s .co m * @param activity * @param autoclose - if the alert should close when connection is established * */ public static void show(Context activity, boolean autoclose, Intent after_connection_intent) { LinearLayout lin = new LinearLayout(activity); lin.setOrientation(LinearLayout.VERTICAL); ScrollView sv = new ScrollView(activity); TextView details_text_view = new TextView(activity); LinearLayout lin_in_scrollview = new LinearLayout(activity); lin_in_scrollview.setOrientation(LinearLayout.VERTICAL); sv.addView(lin_in_scrollview); lin_in_scrollview.addView(details_text_view); details_text_view.setText("no text"); ProgressBar progress = new ProgressBar(activity, null, android.R.attr.progressBarStyleHorizontal); progress.setMax(img_lst.length); lin.addView(progress); lin.addView(sv); new AlertDialog.Builder(activity).setTitle("Download Status").setView(lin) .setPositiveButton("OK", new DialogDiscardingOnClickListener()).show(); class AlertDialogUpdater implements Runnable { private Handler h = new Handler(); private TextView myTextView; private ProgressBar myProgress; public AlertDialogUpdater(TextView ab, ProgressBar progress) { myTextView = ab; myProgress = progress; } public void run() { for (int i = 0; i < img_lst.length; i++) { class MsgUpdater implements Runnable { private int i; public MsgUpdater(int i) { this.i = i; } public void run() { myProgress.setProgress(i + 1); if (i != img_lst.length - 1) myTextView.setText("Downloading " + img_lst[i] + ".png"); else myTextView.setText("Ready - please restart DUBwise to apply changes!"); } } h.post(new MsgUpdater(i)); try { URLConnection ucon = new URL(url_lst[i]).openConnection(); BufferedInputStream bis = new BufferedInputStream(ucon.getInputStream()); ByteArrayBuffer baf = new ByteArrayBuffer(50); int current = 0; while ((current = bis.read()) != -1) baf.append((byte) current); File path = new File( Environment.getExternalStorageDirectory() + "/dubwise/images/dashboard"); path.mkdirs(); FileOutputStream fos = new FileOutputStream( new File(path.getAbsolutePath() + "/" + img_lst[i] + ".png")); fos.write(baf.toByteArray()); fos.close(); } catch (Exception e) { } try { Thread.sleep(199); } catch (InterruptedException e) { } } } } new Thread(new AlertDialogUpdater(details_text_view, progress)).start(); }
From source file:bala.padio.Settings.java
public static String DownloadFromUrl(String u) { try {//from www .ja v a 2 s.c om URL url = new URL(u); URLConnection ucon = url.openConnection(); InputStream is = ucon.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is); ByteArrayBuffer baf = new ByteArrayBuffer(50); int current = 0; while ((current = bis.read()) != -1) { baf.append((byte) current); } return new String(baf.toByteArray()); } catch (Exception e) { Log.e(TAG, "Error: " + e); } return null; }
From source file:info.unyttig.helladroid.newzbin.NewzBinController.java
/** * Finds reports based on the paramaters given in searchOptions * /*from www .j a va2s . co m*/ * @param searchOptions * @return ArrayList<NewzBinReport> - list of result reports. */ public static ArrayList<NewzBinReport> findReport(final Handler messageHandler, final HashMap<String, String> searchOptions) { String url = NBAPIURL + "reportfind/"; ArrayList<NewzBinReport> searchRes = new ArrayList<NewzBinReport>(); try { HttpResponse response = doPost(url, searchOptions); checkReturnCode(response.getStatusLine().getStatusCode(), false); InputStream is = response.getEntity().getContent(); BufferedInputStream bis = new BufferedInputStream(is); ByteArrayBuffer baf = new ByteArrayBuffer(20); int current = 0; while ((current = bis.read()) != -1) { baf.append((byte) current); } /* Convert the Bytes read to a String. */ String text = new String(baf.toByteArray()); // Log.d(LOG_NAME, text); BufferedReader reader = new BufferedReader(new StringReader(text)); String str = reader.readLine(); totalRes = Integer.parseInt(str.substring(str.indexOf("=") + 1)); while ((str = reader.readLine()) != null) { String[] values = str.split(" "); NewzBinReport temp2 = new NewzBinReport(); temp2.setNzbId(Integer.parseInt(values[0])); temp2.setSize(Long.parseLong(values[1])); temp2.setTitle(values[2]); if (!reports.containsKey(temp2.getNzbId())) { reports.put(temp2.getNzbId(), temp2); searchRes.add(temp2); } else searchRes.add(reports.get(temp2.getNzbId())); } Object[] result = new Object[2]; result[0] = totalRes; result[1] = searchRes; return searchRes; // TODO message handling } catch (ClientProtocolException e) { Log.e(LOG_NAME, "ClientProtocol thrown: ", e); sendUserMsg(messageHandler, e.toString()); } catch (IOException e) { Log.e(LOG_NAME, "IOException thrown: ", e); sendUserMsg(messageHandler, e.toString()); } catch (NewzBinPostReturnCodeException e) { Log.e(LOG_NAME, "POST ReturnCode error: " + e.toString()); sendUserMsg(messageHandler, e.getMessage()); } return searchRes; }
From source file:Main.java
public static byte[] hexToBytes(String hex) { ByteArrayBuffer bytes = new ByteArrayBuffer(hex.length() / 2); for (int i = 0; i < hex.length(); i++) { if (hex.charAt(i) == ' ') { continue; }/*from w w w. j a v a2 s .c o m*/ String hexByte; if (i + 1 < hex.length()) { hexByte = hex.substring(i, i + 2).trim(); i++; } else { hexByte = hex.substring(i, i + 1); } bytes.append(Integer.parseInt(hexByte, 16)); } return bytes.buffer(); }
From source file:net.vexelon.bgrates.Utils.java
/** * Downloads a file given URL to specified destination * @param url/*from w w w .j a va2 s . c o m*/ * @param destFile * @return */ //public static boolean downloadFile(Context context, String url, String destFile) { public static boolean downloadFile(Context context, String url, File destFile) { //Log.v(TAG, "@downloadFile()"); //Log.d(TAG, "Downloading " + url); boolean ret = false; BufferedInputStream bis = null; FileOutputStream fos = null; InputStream is = null; try { URL myUrl = new URL(url); URLConnection connection = myUrl.openConnection(); is = connection.getInputStream(); bis = new BufferedInputStream(is); ByteArrayBuffer baf = new ByteArrayBuffer(1024); int n = 0; while ((n = bis.read()) != -1) baf.append((byte) n); // save to internal storage //Log.v(TAG, "Saving downloaded file ..."); fos = new FileOutputStream(destFile); //context.openFileOutput(destFile, context.MODE_PRIVATE); fos.write(baf.toByteArray()); fos.close(); //Log.v(TAG, "File saved successfully."); ret = true; } catch (Exception e) { //Log.e(TAG, "Error while downloading and saving file !", e); } finally { try { if (fos != null) fos.close(); } catch (IOException e) { } try { if (bis != null) bis.close(); } catch (IOException e) { } try { if (is != null) is.close(); } catch (IOException e) { } } return ret; }
From source file:com.example.shutapp.DatabaseHandler.java
private static boolean downloadDatabase(Context context) { try {//from w w w . j a v a 2 s . c o m Log.d(TAG, "downloading database"); URL url = new URL(StringLiterals.SERVER_DB_URL); /* Open a connection to that URL. */ URLConnection ucon = url.openConnection(); /* * Define InputStreams to read from the URLConnection. */ InputStream is = ucon.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is); /* * Read bytes to the Buffer until there is nothing more to read(-1). */ ByteArrayBuffer baf = new ByteArrayBuffer(StringLiterals.DATABASE_BUFFER); int current = 0; while ((current = bis.read()) != -1) { baf.append((byte) current); } /* Convert the Bytes read to a String. */ FileOutputStream fos = null; // Select storage location fos = context.openFileOutput("db_name.s3db", Context.MODE_PRIVATE); fos.write(baf.toByteArray()); fos.close(); Log.d(TAG, "downloaded"); } catch (IOException e) { String exception = e.toString(); Log.e(TAG, "downloadDatabase Error: " + exception); return false; } catch (Exception e) { String exception = e.toString(); Log.e(TAG, "downloadDatabase Error: " + exception); return false; } return true; }