List of usage examples for org.apache.http.util ByteArrayBuffer toByteArray
public byte[] toByteArray()
From source file:com.juick.android.WsClient.java
public void readLoop() { try {//from ww w .j a va 2s . co m int b; int byteCnt = 0; boolean bigPacket = false; int PacketLength = 0; ByteArrayBuffer buf = new ByteArrayBuffer(16); boolean flagInside = false; while (!terminated) { try { b = is.read(); if (b == -1) break; if (terminated) break; } catch (SocketTimeoutException e) { if (beforePausedCounter-- < 0) { sock.setSoTimeout(3 * 60 * 1000); } Log.w("UgnichWS", "inst=" + toString() + ": read sotimeout, terminated=" + terminated); continue; } if (flagInside) { byteCnt++; if (byteCnt == 1) { if (b < 126) { PacketLength = b + 1; bigPacket = false; } else { bigPacket = true; } } else { if (byteCnt == 2 && bigPacket) { PacketLength = b << 8; } if (byteCnt == 3 && bigPacket) { PacketLength |= b; PacketLength += 3; } if (byteCnt > 3 || !bigPacket) { buf.append((char) b); } } if (byteCnt == PacketLength && listener != null) { if (PacketLength > 2) { if (listener != null) { String incomingData = new String(buf.toByteArray(), "utf-8"); final ArrayList<JuickMessage> messages = convertMessages(incomingData); if (messages.size() > 0) { listener.onNewMessages(messages); } } } else { os.write(keepAlive); os.flush(); } flagInside = false; } } else if (b == 0x81) { buf.clear(); flagInside = true; byteCnt = 0; } } } catch (Exception e) { Log.e("UgnichWS", "inst=" + toString(), e); } finally { Log.w("UgnichWS", "inst=" + toString() + " DISCONNECTED readLoop"); } }
From source file:org.apache.shindig.gadgets.http.BasicHttpFetcher.java
/** * This method is Safe replica version of org.apache.http.util.EntityUtils.toByteArray. * The try block embedding 'instream.read' has a corresponding catch block for 'EOFException' * (that's Ignored) and all other IOExceptions are let pass. * * @param entity//from w w w .j a v a 2 s. c o m * @return byte array containing the entity content. May be empty/null. * @throws IOException if an error occurs reading the input stream */ public byte[] toByteArraySafe(final HttpEntity entity) throws IOException { if (entity == null) { return null; } InputStream instream = entity.getContent(); if (instream == null) { return new byte[] {}; } Preconditions.checkArgument(entity.getContentLength() < Integer.MAX_VALUE, "HTTP entity too large to be buffered in memory"); // The raw data stream (inside JDK) is read in a buffer of size '512'. The original code // org.apache.http.util.EntityUtils.toByteArray reads the unzipped data in a buffer of // 4096 byte. For any data stream that has a compression ratio lesser than 1/8, this may // result in the buffer/array overflow. Increasing the buffer size to '16384'. It's highly // unlikely to get data compression ratios lesser than 1/32 (3%). final int bufferLength = 16384; int i = (int) entity.getContentLength(); if (i < 0) { i = bufferLength; } ByteArrayBuffer buffer = new ByteArrayBuffer(i); try { byte[] tmp = new byte[bufferLength]; int l; while ((l = instream.read(tmp)) != -1) { buffer.append(tmp, 0, l); } } catch (EOFException eofe) { /** * Ref: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4040920 * Due to a bug in JDK ZLIB (InflaterInputStream), unexpected EOF error can occur. * In such cases, even if the input stream is finished reading, the * 'Inflater.finished()' call erroneously returns 'false' and * 'java.util.zip.InflaterInputStream.fill' throws the 'EOFException'. * So for such case, ignore the Exception in case Exception Cause is * 'Unexpected end of ZLIB input stream'. * * Also, ignore this exception in case the exception has no message * body as this is the case where {@link GZIPInputStream#readUByte} * throws EOFException with empty message. A bug has been filed with Sun * and will be mentioned here once it is accepted. */ if (instream.available() == 0 && (eofe.getMessage() == null || eofe.getMessage().equals("Unexpected end of ZLIB input stream"))) { LOG.log(Level.FINE, "EOFException: ", eofe); } else { throw eofe; } } finally { instream.close(); } return buffer.toByteArray(); }
From source file:com.tapcentive.sdk.touchpoint.nfc.SEManager.java
/** * Send and receive.//from w ww . jav a2 s . co m * * @param cmd the cmd * @return the data that was read or null if an error occurred */ public byte[] sendAndReceive(byte[] cmd) { byte[] result; byte[] fullBytes = null; ByteArrayBuffer fullresult = new ByteArrayBuffer(255); boolean hasMore = true; byte[] command = cmd; boolean gotSuccessSW = false; long time1 = SystemClock.uptimeMillis(); while (hasMore) { try { result = partialSendAndReceive(command); fullresult.append(result, 0, result.length - 2); if (result.length < 2) { Log.d(TAG, "READ command issue"); return null; } // Check if more data is available from touchpoint if (result[result.length - 2] == (byte) 0x61) { hasMore = true; } else { if (result[result.length - 2] != (byte) 0x90) { Log.d(TAG, "Bad SW on READ (command/response):" + ApduUtil.getHexString(command, 0, command.length, "") + " / " + ApduUtil.getHexString(result, 0, result.length, "")); return null; /*throw new TapcentiveException("An error occurred. Please try again and if this problem persists contact customer service");*/ } else { // SW 9000 hasMore = false; gotSuccessSW = true; } } command = getResponse; // After the first iteration change the command header to a GET RESPONSE } catch (IOException e) { e.printStackTrace(); return null; } } long time2 = SystemClock.uptimeMillis(); Log.d(TAG, "TIME: send&Receive: " + (time2 - time1)); /*if (!gotSuccessSW){ throw new TapcentiveException("An error occurred. Please try again and if this problem persists contact customer service"); }*/ if (gotSuccessSW) { fullBytes = fullresult.toByteArray(); Log.d(TAG, "TIME: send&receive apdu size: " + fullBytes.length); } return fullBytes; }
From source file:info.icefilms.icestream.browse.Location.java
protected static String DownloadPage(URL url, String sendCookie, String sendData, StringBuilder getCookie, Callback callback) {// w ww. j a v a 2 s . c o m // Declare our buffer ByteArrayBuffer byteArrayBuffer; try { // Setup the connection HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; Linux i686; rv:2.0) Gecko/20100101 Firefox/4.0"); urlConnection.setRequestProperty("Referer", mIceFilmsURL.toString()); if (sendCookie != null) urlConnection.setRequestProperty("Cookie", sendCookie); if (sendData != null) { urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); urlConnection.setDoOutput(true); } urlConnection.setConnectTimeout(callback.GetConnectionTimeout()); urlConnection.setReadTimeout(callback.GetConnectionTimeout()); urlConnection.connect(); // Get the output stream and send the data if (sendData != null) { OutputStream outputStream = urlConnection.getOutputStream(); outputStream.write(sendData.getBytes()); outputStream.flush(); outputStream.close(); } // Get the cookie if (getCookie != null) { // Clear the string builder getCookie.delete(0, getCookie.length()); // Loop thru the header fields String headerName; String cookie; for (int i = 1; (headerName = urlConnection.getHeaderFieldKey(i)) != null; ++i) { if (headerName.equalsIgnoreCase("Set-Cookie")) { // Get the cookie cookie = GetGroup("([^=]+=[^=;]+)", urlConnection.getHeaderField(i)); // Add it to the string builder if (cookie != null) getCookie.append(cookie); break; } } } // Get the input stream InputStream inputStream = urlConnection.getInputStream(); // For some reason we can actually get a null InputStream instead of an exception if (inputStream == null) { Log.e("Ice Stream", "Page download failed. Unable to create Input Stream."); if (callback.GetErrorBoolean() == false) { callback.SetErrorBoolean(true); callback.SetErrorStringID(R.string.browse_page_download_error); } urlConnection.disconnect(); return null; } // Get the file size final int fileSize = urlConnection.getContentLength(); // Create our buffers byte[] byteBuffer = new byte[2048]; byteArrayBuffer = new ByteArrayBuffer(2048); // Download the page int amountDownloaded = 0; int count; while ((count = inputStream.read(byteBuffer, 0, 2048)) != -1) { // Check if we got canceled if (callback.IsCancelled()) { inputStream.close(); urlConnection.disconnect(); return null; } // Add data to the buffer byteArrayBuffer.append(byteBuffer, 0, count); // Update the downloaded amount amountDownloaded += count; } // Close the connection inputStream.close(); urlConnection.disconnect(); // Check for amount downloaded calculation error if (fileSize != -1 && amountDownloaded != fileSize) { Log.w("Ice Stream", "Total amount downloaded (" + amountDownloaded + " bytes) does not " + "match reported content length (" + fileSize + " bytes)."); } } catch (SocketTimeoutException exception) { Log.e("Ice Stream", "Page download failed.", exception); if (callback.GetErrorBoolean() == false) { callback.SetErrorBoolean(true); callback.SetErrorStringID(R.string.browse_page_timeout_error); } return null; } catch (IOException exception) { Log.e("Ice Stream", "Page download failed.", exception); if (callback.GetErrorBoolean() == false) { callback.SetErrorBoolean(true); callback.SetErrorStringID(R.string.browse_page_download_error); } return null; } // Convert things to a string return new String(byteArrayBuffer.toByteArray()); }
From source file:com.racoon.ampdroid.Mp3PlayerService.java
public void DownloadFromUrl(String DownloadURL, String LocalFileName, String User, String Password) { try {//from w w w. j av a2 s.c o m URL url = new URL(DownloadURL); File file = new File(LocalFileName); long startTime = System.currentTimeMillis(); //Log.d("bugs", "download begining"); //Log.d("bugs", "download url:" + url); //Log.d("bugs", "download to file:" + fileName); HttpURLConnection con = (HttpURLConnection) url.openConnection(); String credentials = User + ":" + Password; credentials = Base64.encodeToString(credentials.getBytes(), Base64.DEFAULT); con.setRequestMethod("POST"); con.setDoOutput(true); con.setRequestProperty("Authorization", "Basic " + credentials); con.connect(); InputStream is = con.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(); Log.d("bugs", "download ready in" + ((System.currentTimeMillis() - startTime) / 1000) + " sec"); con.disconnect(); } catch (IOException e) { Log.d("bugs", "Error: " + e); } }
From source file:com.undatech.opaque.RemoteCanvasActivity.java
/** * Launches a remote desktop session using a .vv file. * @param i/*from w w w . j a v a 2 s .c om*/ * @return the vv file name or NULL if no file was discovered. */ private String startSessionFromVvFile(Intent i) { final Uri data = i.getData(); String vvFileName = null; android.util.Log.d(TAG, "got intent: " + i.toString()); if (data != null) { android.util.Log.d(TAG, "got data: " + data.toString()); if (data.toString().startsWith("http")) { android.util.Log.d(TAG, "Intent is with http scheme."); final String tempVvFile = getFilesDir() + "/tempfile.vv"; vvFileName = tempVvFile; // Spin up a thread to grab the file over the network. Thread t = new Thread() { @Override public void run() { try { URL url = new URL(data.toString()); File file = new File(tempVvFile); URLConnection ucon = url.openConnection(); InputStream is = ucon.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is); ByteArrayBuffer baf = new ByteArrayBuffer(3000); int current = 0; while ((current = bis.read()) != -1) { baf.append((byte) current); } FileOutputStream fos = new FileOutputStream(file); fos.write(baf.toByteArray()); fos.close(); synchronized (RemoteCanvasActivity.this) { RemoteCanvasActivity.this.notify(); } } catch (Exception e) { } } }; t.start(); synchronized (this) { try { this.wait(5000); } catch (InterruptedException e) { vvFileName = null; e.printStackTrace(); } } } else if (data.toString().startsWith("file")) { android.util.Log.d(TAG, "Intent is with file scheme."); vvFileName = data.getPath(); } else if (data.toString().startsWith("content")) { android.util.Log.d(TAG, "Intent is with content scheme."); String[] projection = { MediaStore.MediaColumns.DATA }; ContentResolver resolver = getApplicationContext().getContentResolver(); Cursor cursor = resolver.query(data, projection, null, null, null); if (cursor != null) { if (cursor.moveToFirst()) { vvFileName = cursor.getString(0); } cursor.close(); } } File f = new File(vvFileName); android.util.Log.d(TAG, "got filename: " + vvFileName); if (f.exists()) { android.util.Log.d(TAG, "Initializing session from vv file: " + vvFileName); connection = new ConnectionSettings("defaultSettings"); connection.loadFromSharedPreferences(getApplicationContext()); } else { vvFileName = null; // Quit with an error if the file does not exist. MessageDialogs.displayMessageAndFinish(this, R.string.vv_file_not_found, R.string.error_dialog_title); } } return vvFileName; }
From source file:org.kaaproject.kaa.client.transport.AndroidHttpClient.java
private static byte[] toByteArray(final HttpEntity entity) throws IOException { if (entity == null) { throw new IllegalArgumentException("HTTP entity may not be null"); }/*from w w w .j a v a 2 s.co m*/ InputStream instream = entity.getContent(); if (instream == null) { return new byte[] {}; } if (entity.getContentLength() > Integer.MAX_VALUE) { throw new IllegalArgumentException("HTTP entity too large to be buffered in memory"); } int count = (int) entity.getContentLength(); if (count < 0) { count = 4096; } ByteArrayBuffer buffer = new ByteArrayBuffer(count); try { byte[] tmp = new byte[4096]; int len; while ((len = instream.read(tmp)) != -1) { buffer.append(tmp, 0, len); } } finally { instream.close(); } return buffer.toByteArray(); }
From source file:org.trancecode.http.BodypartResponseParser.java
public BodypartEntity parseBodypart(final boolean hasHeaders) throws IOException { if (hasHeaders) { parseHeaders();//from w ww . j a v a2 s .c o m } if (isBinary()) { if (headers.containsHeader(HttpHeaders.CONTENT_LENGTH)) { int length = Integer.parseInt(headers.getFirstHeader(HttpHeaders.CONTENT_LENGTH).getValue()); final byte[] in = new byte[length]; int off = 0; while (length > 0) { final int lect = sessionBuffer.read(in, off, length); if (lect == -1) { break; } off += lect; length -= lect; } sessionBuffer.readLine(); sessionBuffer.readLine(); return new BodypartEntity(new ByteArrayEntity(in), hasHeaders ? headers.copy() : null); } else { final ByteArrayBuffer buffer = new ByteArrayBuffer(40); final byte[] in = new byte[40]; while (true) { final int lect = sessionBuffer.read(in, 0, 40); if (lect == -1) { break; } buffer.append(in, 0, lect); } if (!buffer.isEmpty()) { sessionBuffer.readLine(); sessionBuffer.readLine(); return new BodypartEntity(new ByteArrayEntity(buffer.toByteArray()), hasHeaders ? headers.copy() : null); } } } else { final String ch = partCharset == null ? charset : partCharset; final String mime = partContentType == null ? contentType : partContentType; final StringBuilder builder = new StringBuilder(); boolean finish = false; do { final String line = sessionBuffer.readLine(); if (line == null || StringUtils.startsWith(line, boundary)) { finish = true; } else { if (builder.length() > 0 && !isBinary()) { builder.append("\n"); } builder.append(line); } } while (!finish); if (builder.length() > 0) { return new BodypartEntity(new StringEntity(builder.toString(), mime, ch), hasHeaders ? headers.copy() : null); } } return null; }