Example usage for org.apache.http.util ByteArrayBuffer ByteArrayBuffer

List of usage examples for org.apache.http.util ByteArrayBuffer ByteArrayBuffer

Introduction

In this page you can find the example usage for org.apache.http.util ByteArrayBuffer ByteArrayBuffer.

Prototype

public ByteArrayBuffer(int i) 

Source Link

Usage

From source file:com.sonyericsson.android.drm.drmlicenseservice.DLSHttpClient.java

private static void writeDataToFile(String suffix, String data) {
    if (Constants.DEBUG && data != null) {
        ByteArrayBuffer bab = new ByteArrayBuffer(data.length());
        try {//from w  ww .j a va2  s . co  m
            bab.append(data.getBytes("UTF-8"), 0, data.length());
            writeDataToFile(suffix, bab);
        } catch (UnsupportedEncodingException e) {
            DrmLog.logException(e);
        }
    }
}

From source file:com.sim2dial.dialer.ChatFragment.java

public static Bitmap downloadImage(String stringUrl) {
    URL url;//from   w ww  .  ja  v  a2  s  .c o m
    Bitmap bm = null;
    try {
        url = new URL(stringUrl);
        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);
        }

        byte[] rawImage = baf.toByteArray();
        bm = BitmapFactory.decodeByteArray(rawImage, 0, rawImage.length);
        bis.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return bm;
}

From source file:ch.ethz.twimight.net.opportunistic.ScanningService.java

public static byte[] toByteArray(InputStream in) throws IOException {

    BufferedInputStream bis = new BufferedInputStream(in);
    ByteArrayBuffer baf = new ByteArrayBuffer(2048);
    // get the bytes one by one
    int current = 0;
    while ((current = bis.read()) != -1) {
        baf.append((byte) current);
    }/*from   w  w w .  j  ava2 s .  c o  m*/
    return baf.toByteArray();

}

From source file:net.yacy.cora.protocol.http.HTTPClient.java

/**
 * Return entity content loaded as a byte array
 * @param entity HTTP entity//from   ww w. j a  v a  2  s  .co  m
 * @param maxBytes maximum bytes to read. -1 means no maximum limit.
 * @return content bytes or null when entity content is null.
 * @throws IOException when a read error occured or content length is over maxBytes
 */
public static byte[] getByteArray(final HttpEntity entity, int maxBytes) throws IOException {
    final InputStream instream = entity.getContent();
    if (instream == null) {
        return null;
    }
    try {
        long contentLength = entity.getContentLength();
        /*
         * When no maxBytes is specified, the default limit is
         * Integer.MAX_VALUE as a byte array size can not be over
         */
        if (maxBytes < 0) {
            maxBytes = Integer.MAX_VALUE;
        }
        /*
         * Content length may already be known now : check it before
         * downloading
         */
        if (contentLength > maxBytes) {
            throw new IOException(
                    "Content to download exceed maximum value of " + Formatter.bytesToString(maxBytes));
        }
        int initialSize = Math.min(maxBytes, (int) contentLength);
        /* ContentLenght may be negative because unknown for now */
        if (initialSize < 0) {
            initialSize = 4096;
        }
        final ByteArrayBuffer buffer = new ByteArrayBuffer(initialSize);
        byte[] tmp = new byte[4096];
        int l = 0;
        /* Sum is a long to enable check against Integer.MAX_VALUE */
        long sum = 0;
        while ((l = instream.read(tmp)) != -1) {
            sum += l;
            /*
             * Check total length while downloading as content length might
             * not be known at beginning
             */
            if (sum > maxBytes) {
                throw new IOException(
                        "Download exceeded maximum value of " + Formatter.bytesToString(maxBytes));
            }
            buffer.append(tmp, 0, l);
        }
        return buffer.toByteArray();
    } catch (final OutOfMemoryError e) {
        throw new IOException(e.toString());
    } finally {
        instream.close();
    }
}

From source file:com.vuze.android.remote.SessionInfo.java

public void openTorrent(final Activity activity, final String name, InputStream is) {
    try {/* ww w.j  a  v a 2s  .c o m*/
        int available = is.available();
        if (available <= 0) {
            available = 32 * 1024;
        }
        ByteArrayBuffer bab = new ByteArrayBuffer(available);

        boolean ok = AndroidUtils.readInputStreamIfStartWith(is, bab, new byte[] { 'd' });
        if (!ok) {
            String s;
            if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT && bab.length() == 0) {
                s = activity.getResources().getString(R.string.not_torrent_file_kitkat, name);
            } else {
                s = activity.getResources().getString(R.string.not_torrent_file, name,
                        Math.max(bab.length(), 5));
            }
            AndroidUtils.showDialog(activity, R.string.add_torrent, Html.fromHtml(s));
            return;
        }
        final String metainfo = Base64Encode.encodeToString(bab.buffer(), 0, bab.length());
        openTorrentWithMetaData(activity, name, metainfo);
    } catch (IOException e) {
        if (AndroidUtils.DEBUG) {
            e.printStackTrace();
        }
        VuzeEasyTracker.getInstance(activity).logError(e);
    } catch (OutOfMemoryError em) {
        VuzeEasyTracker.getInstance(activity).logError(em);
        AndroidUtils.showConnectionError(activity, "Out of Memory", true);
    }
}

From source file:com.vkassin.mtrade.Common.java

public static String generalWebServiceCall(String urlStr, ContentHandler handler) {

    String errorMsg = "";

    try {//w  w w.  j  a v  a 2 s  .co  m
        URL url = new URL(urlStr);

        HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
        urlc.setRequestProperty("User-Agent", "Android Application: aMTrade");
        urlc.setRequestProperty("Connection", "close");
        // urlc.setRequestProperty("Accept-Charset", "windows-1251");
        // urlc.setRequestProperty("Accept-Charset",
        // "windows-1251,utf-8;q=0.7,*;q=0.7");
        urlc.setRequestProperty("Accept-Charset", "utf-8");

        urlc.setConnectTimeout(1000 * 5); // mTimeout is in seconds
        urlc.setDoInput(true);
        urlc.connect();

        if (urlc.getResponseCode() == HttpURLConnection.HTTP_OK) {
            // Get a SAXParser from the SAXPArserFactory.
            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp = spf.newSAXParser();

            // Get the XMLReader of the SAXParser we created.
            XMLReader xr = sp.getXMLReader();

            // Apply the handler to the XML-Reader
            xr.setContentHandler(handler);

            // Parse the XML-data from our URL.
            InputStream is = urlc.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
            ByteArrayBuffer baf = new ByteArrayBuffer(500);
            int current = 0;
            while ((current = bis.read()) != -1) {
                baf.append((byte) current);
            }
            ByteArrayInputStream bais = new ByteArrayInputStream(baf.toByteArray());
            // Reader isr = new InputStreamReader(bais, "windows-1251");
            Reader isr = new InputStreamReader(bais, "utf-8");
            InputSource ist = new InputSource();
            // ist.setEncoding("UTF-8");
            ist.setCharacterStream(isr);
            xr.parse(ist);
            // Parsing has finished.

            bis.close();
            baf.clear();
            bais.close();
            is.close();
        }

        urlc.disconnect();

    } catch (SAXException e) {
        // All is OK :)
    } catch (MalformedURLException e) {
        Log.e(TAG, errorMsg = "MalformedURLException");
    } catch (IOException e) {
        Log.e(TAG, errorMsg = "IOException");
    } catch (ParserConfigurationException e) {
        Log.e(TAG, errorMsg = "ParserConfigurationException");
    } catch (ArrayIndexOutOfBoundsException e) {
        Log.e(TAG, errorMsg = "ArrayIndexOutOfBoundsException");
    }

    return errorMsg;
}

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  a v a 2s.c om
        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 ww.j av a 2s . co m*/
 * @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");
    }//  w  ww.  j  av a 2s . c om
    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();//  w  ww  .ja v a2  s .  com
    }
    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;
}