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

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

Introduction

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

Prototype

public void append(int i) 

Source Link

Usage

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

/**
 * @param conn/*  w ww  .j a  v  a 2  s  .co 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:jp.co.brilliantservice.android.writertduri.HomeActivity.java

private NdefMessage createUriMessage(String uri) {
    try {/*  w ww  .j  a v a  2  s  . c  o  m*/
        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: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 {/*www.ja v a 2s . c o m*/
        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.panoskrt.dbadapter.DBAdapter.java

public void downloadDB(Context context, String dbName, String urlLink) {
    try {//w  ww  .j  a va 2  s .com
        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:moodle.android.moodle.helpers.FileManager.java

public File DownloadFromUrl(String fileURL, String fileName, String courseDirectoryAndType) { //this is the downloader method

    File file = null;/*from w  w  w  . j a  v  a  2  s. com*/
    try {
        URL url = new URL(fileURL); //you can write here any link

        boolean mExternalStorageAvailable = false;
        boolean mExternalStorageWriteable = false;
        String state = Environment.getExternalStorageState();

        if (Environment.MEDIA_MOUNTED.equals(state)) {
            // We can read and write the media
            mExternalStorageAvailable = mExternalStorageWriteable = true;
        } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
            // We can only read the media
            mExternalStorageAvailable = true;
            mExternalStorageWriteable = false;
        } else {
            // Something else is wrong. It may be one of many other states, but all we need
            //  to know is we can neither read nor write
            mExternalStorageAvailable = mExternalStorageWriteable = false;
        }

        if (mExternalStorageAvailable || mExternalStorageWriteable) {

            // create a File object for the parent directory 
            File fileDirectory = new File(PATH + "/Moodle/" + courseDirectoryAndType);
            // have the object build the directory structure, if needed. 
            fileDirectory.mkdirs();
            // create a File object for the output file 
            file = new File(fileDirectory, fileName);

            long startTime = System.currentTimeMillis();
            Log.d(TAG, "download begining");
            Log.d(TAG, "download url:" + url);
            Log.d(TAG, "downloaded file name:" + fileName);

            /* 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(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(TAG, "download ready in" + ((System.currentTimeMillis() - startTime) / 1000) + " sec");
        }

    } catch (IOException e) {
        Log.d(TAG, "Error: " + e);
    }

    return file;
}

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  ww.j a  v  a  2s .  c  om*/
    return baf.toByteArray();

}

From source file:com.emobc.android.activities.generators.PdfActivityGenerator.java

/**
 * Download a pdf file to web.//from   w  w w  .j a va 2 s  .  c  o m
 * @param file
 * @param urlString
 * @return
 */
protected boolean downloadPdfToFile(File file, String urlString) {
    try {
        URL url = new URL(urlString);

        long startTime = System.currentTimeMillis();
        Log.d("ImageManager", "download begining");
        Log.d("ImageManager", "download url:" + url);
        Log.d("ImageManager", "downloaded file name:" + file.getAbsolutePath());

        // 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(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("ImageManager", "download ready in" + ((System.currentTimeMillis() - startTime) / 1000) + " sec");

        return true;
    } catch (IOException e) {
        Log.d("ImageManager", "Error: " + e);
    }
    return false;
}

From source file:org.uribeacon.beacon.UriBeaconTest.java

private byte[] jsonToByteArray(JSONArray jsonArray) throws JSONException {
    ByteArrayBuffer bb = new ByteArrayBuffer(31);
    for (int i = 0; i < jsonArray.length(); i++) {
        Object item = jsonArray.get(i);
        if (item instanceof Integer) {
            bb.append(jsonArray.getInt(i));
        } else if (item instanceof String) {
            byte[] itemBytes = ((String) item).getBytes();
            bb.append(itemBytes, 0, itemBytes.length);
        } else {//from  ww w  .  j a va2s.c  o  m
            throw new JSONException("Unknown type in array");
        }
    }
    return bb.toByteArray();
}

From source file:com.zbrown.droidsteal.activities.UpdateChecker.java

private void checkupdate() {
    if (alertUpdate != null && alertUpdate.isShowing()) {
        // There is already an download message
        return;/*from  ww  w. j  a  va  2  s .c om*/
    }
    Log.v(TAG, "Checking updates...");
    try {
        URL updateURL = new URL(versionUrl);
        URLConnection conn = updateURL.openConnection();
        InputStream is = conn.getInputStream();
        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. */
        final String s = new String(baf.toByteArray());

        /* Get current Version Number */
        String curVersion = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;

        Log.d(TAG, "Current version is: " + curVersion + " and new one is: " + s);
        /* Is a higher version than the current already out? */
        if (!curVersion.equals(s)) {
            /* Post a Handler for the UI to pick up and open the Dialog */
            if (alertUpdate == null || !alertUpdate.isShowing()) {
                if (alertError != null && alertError.isShowing())
                    alertError.dismiss();
                mHandler.post(showUpdate);
            }
        } else
            Log.v(TAG, "The software is updated to the latest version: " + s);
    } catch (Exception e) {
        e.printStackTrace();
        // if(alertError==null || !alertError.isShowing())
        // mHandler.post(showError);
    }
}

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  w w w. j  av  a  2s.  c  o 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;
}