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

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

Introduction

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

Prototype

public byte[] toByteArray() 

Source Link

Usage

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.  jav  a 2  s  .c  o  m
    return baf.toByteArray();

}

From source file:jp.co.brilliantservice.android.writertduri.HomeActivity.java

private NdefMessage createUriMessage(String uri) {
    try {/*from   w  ww  . ja  v a 2 s. com*/
        int index = getProtocolIndex(uri);
        String protocol = sProtocolList.get(index);

        String uriBody = uri.replace(protocol, "");
        byte[] uriBodyBytes = uriBody.getBytes("UTF-8");

        ByteArrayBuffer buffer = new ByteArrayBuffer(1 + uriBody.length());
        buffer.append((byte) index);
        buffer.append(uriBodyBytes, 0, uriBodyBytes.length);

        byte[] payload = buffer.toByteArray();
        NdefMessage message = new NdefMessage(new NdefRecord[] {
                new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_URI, new byte[0], payload) });

        return message;
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.frostwire.android.gui.httpserver.DesktopUploadRequestHandler.java

private DesktopUploadRequest readPOST(InputStream is) throws IOException {
    DesktopUploadRequest request = null;

    try {/*from   w  w w .ja  v a  2  s . co m*/
        ByteArrayBuffer arr = new ByteArrayBuffer(READ_BUFFER_SIZE);

        byte[] buff = new byte[READ_BUFFER_SIZE];
        int n;

        while ((n = is.read(buff, 0, buff.length)) != -1) {
            arr.append(buff, 0, n);
        }

        String json = new String(arr.toByteArray(), "UTF-8");
        request = JsonUtils.toObject(json, DesktopUploadRequest.class);

    } catch (Throwable e) {
        Log.e(TAG, "Error reading post from desktop upload request", e);
    } finally {
        try {
            is.close();
        } catch (Throwable e) {
            // ignore
        }
    }

    return request;
}

From source file:com.zoffcc.applications.aagtl.ImageManager.java

public void DownloadFromUrl(String imageURL, String fileName) { // this is
                                                                // the downloader method
    try {//from  ww  w .  java 2 s .  c  o  m
        URL url = new URL(imageURL);
        File file = new File(fileName);

        //long startTime = System.currentTimeMillis();
        //Log.d("ImageManager", "download begining");
        //Log.d("ImageManager", "download url:" + url);
        //Log.d("ImageManager", "downloaded file name:" + fileName);
        /* Open a connection to that URL. */
        URLConnection ucon = url.openConnection();
        ucon.setConnectTimeout(10000);
        ucon.setReadTimeout(7000);

        /*
         * Define InputStreams to read from the URLConnection.
         */
        InputStream is = ucon.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is, HTMLDownloader.large_buffer_size);

        /*
         * Read bytes to the Buffer until there is nothing more to read(-1).
         */
        ByteArrayBuffer baf = new ByteArrayBuffer(HTMLDownloader.default_buffer_size);
        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("ImageManager", "download ready in"
        //      + ((System.currentTimeMillis() - startTime) / 1000)
        //      + " sec");

    } catch (SocketTimeoutException e2) {
        Log.d("ImageManager", "Connectiont timout: " + e2);
    } catch (IOException e) {
        Log.d("ImageManager", "Error: " + e);
    } catch (Exception e) {
        Log.d("ImageManager", "Error: " + e);
    }

}

From source file:ca.christophersaunders.tutorials.sqlite.picasa.PicasaImage.java

private byte[] getBitmapBytesForLocation(String location) {
    try {/*from w w w.ja  va 2s  .co  m*/
        URL thumbnailUrl = new URL(location);
        URLConnection conn = thumbnailUrl.openConnection();

        InputStream is = conn.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);

        ByteArrayBuffer imageBytesBuffer = new ByteArrayBuffer(0x2000);
        byte[] buffer = new byte[1024];
        int current = 0;
        while ((current = bis.read(buffer)) != -1) {
            imageBytesBuffer.append(buffer, 0, current);
        }

        byte[] imageBytes = imageBytesBuffer.toByteArray();
        return imageBytes;

    } catch (Exception gottaCatchemAll) {
        Log.w("PicasaImage", "Gotta catch em' all!");
        Log.e("PicasaImage", String.format("Location string was probably bad: %s", location));
        gottaCatchemAll.printStackTrace();
    }
    return new byte[0];
}

From source file:com.strato.hidrive.api.utils.multipart.BasePart.java

private byte[] generateHeader(Boundary boundary) {
    if (headersProvider == null) {
        throw new RuntimeException("Uninitialized headersProvider"); //$NON-NLS-1$
    }//from  w ww  .  j a  v  a 2  s  .co m
    final ByteArrayBuffer buf = new ByteArrayBuffer(256);
    append(buf, boundary.getStartingBoundary());
    append(buf, headersProvider.getContentDisposition());
    append(buf, CRLF);
    append(buf, headersProvider.getContentType());
    append(buf, CRLF);
    append(buf, headersProvider.getContentTransferEncoding());
    append(buf, CRLF);
    append(buf, CRLF);
    return buf.toByteArray();
}

From source file:org.andicar.service.UpdateCheckService.java

@Override
public void onStart(Intent intent, int startId) {
    super.onStart(intent, startId);

    if (getSharedPreferences(StaticValues.GLOBAL_PREFERENCE_NAME, Context.MODE_MULTI_PROCESS)
            .getBoolean("SendCrashReport", true))
        Thread.setDefaultUncaughtExceptionHandler(
                new AndiCarExceptionHandler(Thread.getDefaultUncaughtExceptionHandler(), this));

    try {/* w  w w  .  ja  va 2  s .  c  om*/
        Bundle extras = intent.getExtras();
        if (extras == null || extras.getBoolean("setJustNextRun") || !extras.getBoolean("AutoUpdateCheck")) {
            setNextRun();
            stopSelf();
        }

        URL updateURL = new URL(StaticValues.VERSION_FILE_URL);
        URLConnection conn = updateURL.openConnection();
        if (conn == null)
            return;
        InputStream is = conn.getInputStream();
        if (is == null)
            return;
        BufferedInputStream bis = new BufferedInputStream(is);
        ByteArrayBuffer baf = new ByteArrayBuffer(50);
        int current = 0;
        while ((current = bis.read()) != -1) {
            baf.append((byte) current);
        }

        /* Convert the Bytes read to a String. */
        String s = new String(baf.toByteArray());
        /* Get current Version Number */
        int curVersion = getPackageManager().getPackageInfo("org.andicar.activity", 0).versionCode;
        int newVersion = Integer.valueOf(s);

        /* Is a higher version than the current already out? */
        if (newVersion > curVersion) {
            //get the whats new message
            updateURL = new URL(StaticValues.WHATS_NEW_FILE_URL);
            conn = updateURL.openConnection();
            if (conn == null)
                return;
            is = conn.getInputStream();
            if (is == null)
                return;
            bis = new BufferedInputStream(is);
            baf = new ByteArrayBuffer(50);
            current = 0;
            while ((current = bis.read()) != -1) {
                baf.append((byte) current);
            }

            /* Convert the Bytes read to a String. */
            s = new String(baf.toByteArray());

            mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            notification = null;
            Intent i = new Intent(this, WhatsNewDialog.class);
            i.putExtra("UpdateMsg", s);
            PendingIntent contentIntent = PendingIntent.getActivity(UpdateCheckService.this, 0, i, 0);

            CharSequence title = getText(R.string.Notif_UpdateTitle);
            String message = getString(R.string.Notif_UpdateMsg);
            notification = new Notification(R.drawable.icon_sys_info, message, System.currentTimeMillis());
            notification.flags |= Notification.DEFAULT_LIGHTS;
            notification.flags |= Notification.DEFAULT_SOUND;
            notification.flags |= Notification.FLAG_AUTO_CANCEL;
            notification.setLatestEventInfo(UpdateCheckService.this, title, message, contentIntent);
            mNM.notify(StaticValues.NOTIF_UPDATECHECK_ID, notification);
            setNextRun();
        }
        stopSelf();
    } catch (Exception e) {
        Log.i("UpdateService", "Service failed.");
        e.printStackTrace();
    }
}

From source file:com.cloudbase.CBBasePart.java

private byte[] generateHeader(CBBoundary boundary) {
    if (headersProvider == null) {
        throw new RuntimeException("Uninitialized headersProvider"); //$NON-NLS-1$
    }/*from   w  w w  .j  ava  2 s  .co  m*/
    final ByteArrayBuffer buf = new ByteArrayBuffer(256);
    append(buf, boundary.getStartingBoundary());
    append(buf, headersProvider.getContentDisposition());
    append(buf, CRLF);
    append(buf, headersProvider.getContentType());
    append(buf, CRLF);
    append(buf, headersProvider.getContentTransferEncoding());
    append(buf, CRLF);
    append(buf, CRLF);
    return buf.toByteArray();
}

From source file:jp.co.brilliantservice.android.writertdtext.HomeActivity.java

/**
 * RTD Text Record??NdefMessage????//from   w  w w.ja  v  a2 s. c o m
 * 
 * @param text 
 * @param languageCode (ISO/IANA)
 * @return
 */
private NdefMessage createTextMessage(String text, String languageCode) {
    try {
        byte statusByte = (byte) languageCode.length();
        byte[] rawLanguageCode = languageCode.getBytes("US-ASCII");
        byte[] rawText = text.getBytes("UTF-8");

        ByteArrayBuffer buffer = new ByteArrayBuffer(1 + rawLanguageCode.length + rawText.length);
        buffer.append(statusByte);
        buffer.append(rawLanguageCode, 0, rawLanguageCode.length);
        buffer.append(rawText, 0, rawText.length);

        byte[] payload = buffer.toByteArray();
        NdefMessage message = new NdefMessage(new NdefRecord[] {
                new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, new byte[0], payload) });
        return message;
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}

From source file:de.luhmer.owncloudnewsreader.async_tasks.GetImageThreaded.java

@Override
public void run() {
    try {/* w w  w . j a v  a  2  s  .c om*/
        File cacheFile = ImageHandler.getFullPathOfCacheFile(WEB_URL_TO_FILE.toString(), rootPath);

        DatabaseConnectionOrm dbConn = new DatabaseConnectionOrm(cont);
        Feed feed = dbConn.getFeedById(ThreadId);
        if (!cacheFile.isFile() || feed.getAvgColour() == null) {
            File dir = new File(rootPath);
            dir.mkdirs();
            cacheFile = ImageHandler.getFullPathOfCacheFile(WEB_URL_TO_FILE.toString(), rootPath);
            //cacheFile.createNewFile();

            /* Open a connection to that URL. */
            URLConnection urlConn = WEB_URL_TO_FILE.openConnection();

            urlConn.setRequestProperty("User-Agent",
                    "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");

            /*
             * Define InputStreams to read from the URLConnection.
             */
            InputStream is = urlConn.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;
            while ((current = bis.read()) != -1) {
                baf.append((byte) current);
            }

            //If the file is not empty
            if (baf.length() > 0) {
                bmp = BitmapFactory.decodeByteArray(baf.toByteArray(), 0, baf.length());

                FileOutputStream fos = new FileOutputStream(cacheFile);
                fos.write(baf.toByteArray());
                fos.close();
            }
        }
        //return cacheFile.getPath();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    //return bmp;

    if (imageDownloadFinished != null)
        imageDownloadFinished.DownloadFinished(ThreadId, bmp);

    super.run();
}