List of usage examples for org.apache.http.util ByteArrayBuffer toByteArray
public byte[] toByteArray()
From source file:ca.mudar.parkcatcher.utils.ParserUtils.java
/** * @author Andrew Pearson {@link http// w ww .ja v a 2s . c o m * ://blog.andrewpearson.org/2010/07/android * -why-to-use-json-and-how-to-use.html} * @param archiveQuery URL of JSON resources * @return String Raw content, requires use of JSONArray() and * getJSONObject() * @throws IOException * @throws JSONException */ public static JSONTokener newJsonTokenerParser(InputStream input) throws IOException { String queryResult = ""; BufferedInputStream bis = new BufferedInputStream(input); ByteArrayBuffer baf = new ByteArrayBuffer(50); int read = 0; int bufSize = 512; byte[] buffer = new byte[bufSize]; while (true) { read = bis.read(buffer); if (read == -1) { break; } baf.append(buffer, 0, read); } final byte[] ba = baf.toByteArray(); queryResult = new String(ba); JSONTokener data = new JSONTokener(queryResult); return data; }
From source file:info.unyttig.helladroid.newzbin.NewzBinController.java
/** * Finds reports based on the paramaters given in searchOptions * // w w w . j a v a2 s . 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:com.mpower.mintel.android.application.MIntel.java
private static void copyAudioFiles(String[] assetName) { for (int i = 0; i < assetName.length; i++) { File file = new File(METADATA_PATH, assetName[i]); if (!file.exists()) { AssetManager mngr = getAppContext().getAssets(); ByteArrayBuffer baf = new ByteArrayBuffer(2048); try { InputStream path = mngr.open(assetName[i]); BufferedInputStream bis = new BufferedInputStream(path, 1024); int current = 0; while ((current = bis.read()) != -1) { baf.append((byte) current); }/*w w w.j av a2 s.c o m*/ byte[] bitmapdata = baf.toByteArray(); FileOutputStream fos; fos = new FileOutputStream(file); fos.write(bitmapdata); fos.flush(); fos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
From source file:org.zywx.wbpalmstar.plugin.uexzxing.qrcode.decoder.DecodedBitStreamParser.java
@SuppressWarnings("unchecked") private static void decodeByteSegment(BitSource bits, StringBuffer result, int count, CharacterSetECI currentCharacterSetECI, Vector byteSegments, Hashtable hints) throws FormatException { byte[] readBytes = new byte[count]; if (count << 3 > bits.available()) { throw FormatException.getFormatInstance(); }/*from w ww . j a va 2 s . com*/ for (int i = 0; i < count; i++) { readBytes[i] = (byte) bits.readBits(8); } String encoding; if (currentCharacterSetECI == null) { // The spec isn't clear on this mode; see // section 6.4.5: t does not say which encoding to assuming // upon decoding. I have seen ISO-8859-1 used as well as // Shift_JIS -- without anything like an ECI designator to // give a hint. encoding = StringUtils.guessEncoding(readBytes, hints); } else { encoding = currentCharacterSetECI.getEncodingName(); } if (null != encoding && !encoding.equals("UTF8")) { encoding = StringUtils.GBK; } try { int len = readBytes.length; ByteArrayBuffer buffer = new ByteArrayBuffer(len + 20); for (int i = 0; i < len; ++i) { int c = readBytes[i]; if (c == 34 || c == 39 || c == 92 || c == 10 || c == 13 || c == 38) { buffer.append('\\'); } buffer.append(c); } readBytes = buffer.toByteArray(); result.append(new String(readBytes, encoding)); // result.append(new String(readBytes, encoding).replaceAll("\\s*|\t|\r|\n", "\\n")); } catch (UnsupportedEncodingException uce) { throw FormatException.getFormatInstance(); } byteSegments.addElement(readBytes); }
From source file:org.jared.synodroid.ds.utils.Utils.java
public static Uri moveToStorage(Activity a, Uri uri) { ContentResolver cr = a.getContentResolver(); try {//from w ww . j av a 2s. c o m InputStream is = cr.openInputStream(uri); File path = Environment.getExternalStorageDirectory(); path = new File(path, "Android/data/org.jared.synodroid.ds/cache/"); path.mkdirs(); String fname = getContentName(cr, uri); File file = null; if (fname != null) { file = new File(path, fname); } else { file = new File(path, "attachment.att"); } 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(); return uri = Uri.fromFile(file); } catch (FileNotFoundException e) { // do nothing } catch (IOException e) { // do nothing } return null; }
From source file:net.vexelon.bgrates.Utils.java
/** * Downloads a file given URL to specified destination * @param url/* w w w . j a v a2s .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.digitalpebble.stormcrawler.protocol.httpclient.HttpProtocol.java
private static final byte[] toByteArray(final HttpEntity entity, int maxContent, MutableBoolean trimmed) throws IOException { if (entity == null) return new byte[] {}; final InputStream instream = entity.getContent(); if (instream == null) { return null; }//ww w .j a v a2 s. c o m try { Args.check(entity.getContentLength() <= Integer.MAX_VALUE, "HTTP entity too large to be buffered in memory"); int i = (int) entity.getContentLength(); if (i < 0) { i = 4096; } final ByteArrayBuffer buffer = new ByteArrayBuffer(i); final byte[] tmp = new byte[4096]; int l; int total = 0; while ((l = instream.read(tmp)) != -1) { // check whether we need to trim if (maxContent != -1 && total + l > maxContent) { buffer.append(tmp, 0, maxContent - total); trimmed.setValue(true); break; } buffer.append(tmp, 0, l); total += l; } return buffer.toByteArray(); } finally { instream.close(); } }
From source file:com.example.shutapp.DatabaseHandler.java
private static boolean downloadDatabase(Context context) { try {/* w ww . j av a2s . 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; }
From source file:crow.weibo.util.WeiboUtil.java
public static String multipartPost(HttpURLConnection conn, List<PostParameter> params) throws IOException { OutputStream os;/*from w w w. j av a2 s . c om*/ List<PostParameter> dataparams = new ArrayList<PostParameter>(); for (PostParameter key : params) { if (key.isFile()) { dataparams.add(key); } } String BOUNDARY = Util.md5(String.valueOf(System.currentTimeMillis())); conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Charsert", "UTF-8"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDARY); ByteArrayBuffer buff = new ByteArrayBuffer(1000); for (PostParameter p : params) { byte[] arr = p.toMultipartByte(BOUNDARY, "UTF-8"); buff.append(arr, 0, arr.length); } String end = "--" + BOUNDARY + "--" + "\r\n"; byte[] endArr = end.getBytes(); buff.append(endArr, 0, endArr.length); conn.setRequestProperty("Content-Length", buff.length() + ""); conn.connect(); os = new BufferedOutputStream(conn.getOutputStream()); os.write(buff.toByteArray()); buff.clear(); os.flush(); String response = ""; response = Util.inputStreamToString(conn.getInputStream()); return response; }
From source file:org.ligi.android.dubwise_uavtalk.dashboard.DownloadDashboardImagesStatusAlertDialog.java
/** * /*from w ww . j a v a2 s . com*/ * @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(); }