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.letv.commonjar.http.HttpJsonCallBack.java

/**
 * /* w w  w  .j  a  v  a 2s.c  o  m*/
 * @param entity
 * @return
 * @throws IOException
 */
byte[] getResponseData(HttpEntity entity) throws IOException {
    byte[] responseBody = null;
    if (entity != null) {
        InputStream instream = entity.getContent();
        if (instream != null) {
            long contentLength = entity.getContentLength();
            if (contentLength > Integer.MAX_VALUE) {
                throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");
            }
            if (contentLength < 0) {
                contentLength = BUFFER_SIZE;
            }
            try {
                ByteArrayBuffer buffer = new ByteArrayBuffer((int) contentLength);
                try {
                    byte[] tmp = new byte[BUFFER_SIZE];
                    int l, count = 0;
                    // do not send messages if request has been cancelled
                    while ((l = instream.read(tmp)) != -1 && !Thread.currentThread().isInterrupted()) {
                        count += l;
                        buffer.append(tmp, 0, l);
                        onProgress(count, (int) contentLength);
                    }
                } finally {
                    instream.close();
                }
                responseBody = buffer.toByteArray();
            } catch (OutOfMemoryError e) {
                System.gc();
                throw new IOException("File too large to fit into available memory");
            }
        }
    }
    return responseBody;
}

From source file:com.digitalpebble.stormcrawler.protocol.okhttp.HttpProtocol.java

private final byte[] toByteArray(final ResponseBody responseBody, MutableBoolean trimmed) throws IOException {

    if (responseBody == null)
        return new byte[] {};

    final InputStream instream = responseBody.byteStream();
    if (instream == null) {
        return null;
    }/*from   w  w  w  . j  a v a 2s.  com*/
    if (responseBody.contentLength() > Integer.MAX_VALUE) {
        throw new IOException("Cannot buffer entire body for content length: " + responseBody.contentLength());
    }
    int reportedLength = (int) responseBody.contentLength();
    // set default size for buffer: 100 KB
    int bufferInitSize = 102400;
    if (reportedLength != -1) {
        bufferInitSize = reportedLength;
    }
    // avoid init of too large a buffer when we will trim anyway
    if (maxContent != -1 && bufferInitSize > maxContent) {
        bufferInitSize = maxContent;
    }
    long endDueFor = -1;
    if (completionTimeout != -1) {
        endDueFor = System.currentTimeMillis() + (completionTimeout * 1000);
    }
    final ByteArrayBuffer buffer = new ByteArrayBuffer(bufferInitSize);
    final byte[] tmp = new byte[4096];
    int lengthRead;
    while ((lengthRead = instream.read(tmp)) != -1) {
        // check whether we need to trim
        if (maxContent != -1 && buffer.length() + lengthRead > maxContent) {
            buffer.append(tmp, 0, maxContent - buffer.length());
            trimmed.setValue(true);
            break;
        }
        buffer.append(tmp, 0, lengthRead);
        // check whether we hit the completion timeout
        if (endDueFor != -1 && endDueFor <= System.currentTimeMillis()) {
            trimmed.setValue(true);
            break;
        }
    }
    return buffer.toByteArray();
}

From source file:com.googlecode.android_scripting.ZipExtractorTask.java

private long unzip() throws Exception {
    long extractedSize = 0l;
    Enumeration<? extends ZipEntry> entries;
    if (mInput.isFile() && mInput.getName().contains(".gz")) {
        InputStream stream = new FileInputStream(mInput);
        GZIPInputStream gzipStream = new GZIPInputStream(stream);
        InputSource is = new InputSource(gzipStream);
        InputStream input = new BufferedInputStream(is.getByteStream());
        File destination = new File(mOutput, "php");
        ByteArrayBuffer baf = new ByteArrayBuffer(255000);
        int current = 0;
        while ((current = input.read()) != -1) {
            baf.append((byte) current);
        }/*from  ww w .  j  av  a  2  s  .co  m*/

        FileOutputStream output = new FileOutputStream(destination);
        output.write(baf.toByteArray());
        output.close();
        Log.d("written!");
        return baf.toByteArray().length;
    }
    ZipFile zip = new ZipFile(mInput);
    long uncompressedSize = getOriginalSize(zip);

    publishProgress(0, (int) uncompressedSize);

    entries = zip.entries();

    try {
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            if (entry.isDirectory()) {
                // Not all zip files actually include separate directory entries.
                // We'll just ignore them
                // and create them as necessary for each actual entry.
                continue;
            }
            File destination = new File(mOutput, entry.getName());
            if (!destination.getParentFile().exists()) {
                destination.getParentFile().mkdirs();
            }
            if (destination.exists() && mContext != null && !mReplaceAll) {
                Replace answer = showDialog(entry.getName());
                switch (answer) {
                case YES:
                    break;
                case NO:
                    continue;
                case YESTOALL:
                    mReplaceAll = true;
                    break;
                default:
                    return extractedSize;
                }
            }
            ProgressReportingOutputStream outStream = new ProgressReportingOutputStream(destination);
            extractedSize += IoUtils.copy(zip.getInputStream(entry), outStream);
            outStream.close();
        }
    } finally {
        try {
            zip.close();
        } catch (Exception e) {
            // swallow this exception, we are only interested in the original one
        }
    }
    Log.v("Extraction is complete.");
    return extractedSize;
}

From source file:org.golang.app.WViewActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //Fixed Portrait orientation
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    /*this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
    WindowManager.LayoutParams.FLAG_FULLSCREEN);*/

    setContentView(R.layout.webview);//from  w ww . jav  a  2s. c om
    WebView webView = (WebView) findViewById(R.id.webView1);

    initWebView(webView);
    webView.setWebViewClient(new WebViewClient() {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            Log.d("JavaGoWV: ", url);

            final Pattern p = Pattern.compile("dcoinKey&password=(.*)$");
            final Matcher m = p.matcher(url);
            if (m.find()) {
                try {
                    Thread thread = new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                //File root = android.os.Environment.getExternalStorageDirectory();
                                File dir = Environment
                                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
                                Log.d("JavaGoWV", "dir " + dir);

                                URL keyUrl = new URL(
                                        "http://127.0.0.1:8089/ajax?controllerName=dcoinKey&first=1"); //you can write here any link
                                //URL keyUrl = new URL("http://yandex.ru/"); //you can write here any link
                                File file = new File(dir, "dcoin-key.png");

                                long startTime = System.currentTimeMillis();
                                Log.d("JavaGoWV", "download begining");
                                Log.d("JavaGoWV", "download keyUrl:" + keyUrl);

                                /* Open a connection to that URL. */
                                URLConnection ucon = keyUrl.openConnection();

                                Log.d("JavaGoWV", "0");
                                /*
                                * Define InputStreams to read from the URLConnection.
                                */
                                InputStream is = ucon.getInputStream();

                                Log.d("JavaGoWV", "01");

                                BufferedInputStream bis = new BufferedInputStream(is);

                                Log.d("JavaGoWV", "1");
                                /*
                                * Read bytes to the Buffer until there is nothing more to read(-1).
                                */
                                ByteArrayBuffer baf = new ByteArrayBuffer(5000);
                                int current = 0;
                                while ((current = bis.read()) != -1) {
                                    baf.append((byte) current);
                                }

                                Log.d("JavaGoWV", "2");
                                /* Convert the Bytes read to a String. */
                                FileOutputStream fos = new FileOutputStream(file);
                                fos.write(baf.toByteArray());
                                fos.flush();
                                fos.close();

                                Log.d("JavaGoWV", "3");
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                                    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                                    Uri contentUri = Uri.fromFile(file);
                                    mediaScanIntent.setData(contentUri);
                                    WViewActivity.this.sendBroadcast(mediaScanIntent);
                                } else {
                                    sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
                                            Uri.parse("file://" + Environment.getExternalStorageDirectory())));
                                }

                                Log.d("JavaGoWV", "4");
                            } catch (Exception e) {
                                Log.e("JavaGoWV error 0", e.toString());
                                e.printStackTrace();
                            }
                        }
                    });
                    thread.start();

                } catch (Exception e) {
                    Log.e("JavaGoWV error", e.toString());
                    e.printStackTrace();
                }
            }
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            Log.e("JavaGoWV", "shouldOverrideUrlLoading " + url);

            if (url.endsWith(".mp4")) {
                Intent in = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(in);
                return true;
            } else {
                return false;
            }
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            Log.d("JavaGoWV",
                    "failed: " + failingUrl + ", error code: " + errorCode + " [" + description + "]");
        }
    });

    SystemClock.sleep(1500);
    //if (MyService.DcoinStarted(8089)) {
    webView.loadUrl("http://localhost:8089/");
    //}

}

From source file:com.gsbabil.antitaintdroid.UtilityFunctions.java

public long httpDownload(String strUrl, String path) {
    int length = 0;

    try {//  ww  w  .j a  v a2  s .  c o m
        URL url = new URL(strUrl);
        File file = new File(path);

        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);
            length++;
        }

        FileOutputStream fos = new FileOutputStream(file);
        fos.write(baf.toByteArray());
        fos.close();

    } catch (Exception e) {
        Log.d(MyApp.TAG, e.getMessage().toString());
    }

    Log.d(MyApp.TAG, "Downloaded " + length + " bytes");
    return length;
}

From source file:eu.liveandgov.ar.utilities.Download_Data.java

/**                      DownAndCopy
 * //  w w  w. jav  a  2s .  co m
 * Download file from URL and Copy to Android file system folder
 * 
 * @param fileUrl
 * @param StringAndroidPath
 */
public static boolean DownAndCopy(String fileUrlSTR, String StringAndroidPath, boolean preservefilename,
        String Caller) {

    if (compareRemoteWithLocal(fileUrlSTR, StringAndroidPath)) {
        //Log.e("fileUrlSTR", "SKIP WITH HASH");
        return true;
    } else {
        Log.e("TRY TO DOWNLOAD BY " + Caller, fileUrlSTR);
    }

    SimpleDateFormat sdf = new SimpleDateFormat("mm");

    // Check if downloaded at least just 2 minutes ago
    for (String[] mem : MemDown)
        if (fileUrlSTR.equals(mem[0])) {
            int diff = Integer.parseInt(sdf.format(new Date())) - Integer.parseInt(mem[1]);
            Log.e("diff", " " + diff);
            if (diff < 2) {
                Log.d("Download_Data", "I am not downloading " + fileUrlSTR + " because it was downloaded "
                        + diff + " minutes ago");
                return true;
            }
        }

    if (!OS_Utils.exists(fileUrlSTR)) {
        Log.e("Download_Data", "URL: " + fileUrlSTR + " called from " + Caller + " not exists to copy it to "
                + StringAndroidPath);
        return false;
    }

    int DEBUG_FLAG = 0;

    HttpURLConnection conn;
    URL fileUrl = null;
    try {
        fileUrl = new URL(fileUrlSTR);
    } catch (MalformedURLException e1) {
        return false;
    }

    try {
        conn = (HttpURLConnection) fileUrl.openConnection();

        DEBUG_FLAG = 1;

        conn.setDoInput(true);
        conn.connect();
        InputStream is = conn.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);
        ByteArrayBuffer baf = new ByteArrayBuffer(100);

        DEBUG_FLAG = 2;

        int current = 0;
        byte[] buffer = new byte[10];
        while ((current = bis.read(buffer)) != -1)
            baf.append(buffer, 0, current);

        DEBUG_FLAG = 3;

        /* Convert the Bytes read to a String. */
        File fileAndroid;

        try {

            if (preservefilename) {
                int iSlash = fileUrlSTR.lastIndexOf("/");
                fileAndroid = new File(StringAndroidPath + "/" + fileUrlSTR.substring(iSlash + 1));
            } else
                fileAndroid = new File(StringAndroidPath);

        } catch (Exception e) {
            Log.e("Download_Data.DownAndCopy", "I can not create " + StringAndroidPath);
            bis.close();
            conn.disconnect();
            return false;
        }

        DEBUG_FLAG = 4;

        FileOutputStream fos = new FileOutputStream(fileAndroid);
        fos.write(baf.toByteArray());

        DEBUG_FLAG = 5;

        bis.close();
        fos.close();
        conn.disconnect();

        MemDown.add(new String[] { fileUrlSTR, sdf.format(new Date()) });

        return true; //returns including the filename
    } catch (IOException e) {
        Log.e("Download_Data", "Download_Data: Error when trying to download:  " + fileUrl.toString() + " to "
                + StringAndroidPath + " DEBUG_FLAG=" + DEBUG_FLAG);
        return false;
    }

}

From source file:com.panoskrt.dbadapter.DBAdapter.java

public void downloadDB(Context context, String dbName, String urlLink) {
    try {//from w  w  w  .  ja v a  2  s.c o m
        URL url = new URL(urlLink);
        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);
        }

        FileOutputStream fos = context.openFileOutput(dbName, Context.MODE_PRIVATE);
        fos.write(baf.toByteArray());
        fos.close();

        File dbFile = new File(context.getFilesDir() + "/" + dbName);
        InputStream in = new FileInputStream(dbFile);
        OutputStream out = new FileOutputStream(dbPath + dbName);
        bufCopy(in, out);
        dbFile.delete();

    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:it.unicaradio.android.gcm.GcmServerRpcCall.java

/**
 * @param conn// w ww  .j av  a2s  . c o  m
 * @throws IOException
 */
private String getResult(HttpURLConnection conn) throws IOException {
    InputStream is = conn.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);
    }

    String result = new String(baf.toByteArray());
    Log.d(TAG, result);

    return result;
}

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 .jav a  2s  .  co  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:crow.weibo.util.WeiboUtil.java

public static String multipartPost(HttpURLConnection conn, List<PostParameter> params) throws IOException {
    OutputStream os;//from   w w  w. ja  v  a 2s.c  o m
    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;
}