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.zbrown.droidsteal.activities.UpdateChecker.java

private void checkupdate() {
    if (alertUpdate != null && alertUpdate.isShowing()) {
        // There is already an download message
        return;// www.  j a  v  a  2  s.  c o  m
    }
    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:org.zywx.wbpalmstar.plugin.uexzxing.qrcode.decoder.DecodedBitStreamParser.java

@SuppressWarnings("unchecked")
private static void decodeByteSegment(BitSource bits, StringBuffer result, int count,
        CharacterSetECI currentCharacterSetECI, Vector byteSegments, Hashtable hints) throws FormatException {
    byte[] readBytes = new byte[count];
    if (count << 3 > bits.available()) {
        throw FormatException.getFormatInstance();
    }/*w  ww. j a  va  2 s .  c om*/
    for (int i = 0; i < count; i++) {
        readBytes[i] = (byte) bits.readBits(8);
    }

    String encoding;
    if (currentCharacterSetECI == null) {
        // The spec isn't clear on this mode; see
        // section 6.4.5: t does not say which encoding to assuming
        // upon decoding. I have seen ISO-8859-1 used as well as
        // Shift_JIS -- without anything like an ECI designator to
        // give a hint.
        encoding = StringUtils.guessEncoding(readBytes, hints);
    } else {
        encoding = currentCharacterSetECI.getEncodingName();
    }
    if (null != encoding && !encoding.equals("UTF8")) {
        encoding = StringUtils.GBK;
    }
    try {
        int len = readBytes.length;
        ByteArrayBuffer buffer = new ByteArrayBuffer(len + 20);
        for (int i = 0; i < len; ++i) {
            int c = readBytes[i];
            if (c == 34 || c == 39 || c == 92 || c == 10 || c == 13 || c == 38) {
                buffer.append('\\');
            }
            buffer.append(c);
        }
        readBytes = buffer.toByteArray();
        result.append(new String(readBytes, encoding));
        //    result.append(new String(readBytes, encoding).replaceAll("\\s*|\t|\r|\n", "\\n"));
    } catch (UnsupportedEncodingException uce) {
        throw FormatException.getFormatInstance();
    }
    byteSegments.addElement(readBytes);
}

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

private NdefMessage createUriMessage(String uri) {
    try {/*  w  w w  .ja  va 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:com.example.shutapp.DatabaseHandler.java

private static boolean downloadDatabase(Context context) {
    try {//from w  w  w .  j av a  2 s .  c  o m
        Log.d(TAG, "downloading database");
        URL url = new URL(StringLiterals.SERVER_DB_URL);
        /* 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(StringLiterals.DATABASE_BUFFER);
        int current = 0;
        while ((current = bis.read()) != -1) {
            baf.append((byte) current);
        }

        /* Convert the Bytes read to a String. */
        FileOutputStream fos = null;
        // Select storage location
        fos = context.openFileOutput("db_name.s3db", Context.MODE_PRIVATE);

        fos.write(baf.toByteArray());
        fos.close();
        Log.d(TAG, "downloaded");
    } catch (IOException e) {
        String exception = e.toString();
        Log.e(TAG, "downloadDatabase Error: " + exception);
        return false;
    } catch (Exception e) {
        String exception = e.toString();
        Log.e(TAG, "downloadDatabase Error: " + exception);
        return false;
    }
    return true;
}

From source file:de.rub.syssec.saaf.misc.ByteUtils.java

/**
 * Read a line from an inputstream into a byte buffer. A line might end with a LF or an CRLF. CR's are accepted inside a line and
 * are not understood as a beginning new line. This should work therefore on Mac OS X, Unix, Linux and Windows.
 * /*from w  w  w.ja va2  s.  com*/
 * See http://en.wikipedia.org/wiki/Newline for more.
 *  
 * @param in the inputstream
 * @param maxSize the maximum amount of bytes to read until a CRLF or LF is reached, a value of zero or smaller disables a limit (use w/ care!)
 * @return the buffer where read bytes are appended, this buffer will not contain any CR's or or CRLF's at the end of the array. Null is
 * returned if EOF is reached.
 * @throws IOException if something is wrong w/ the stream or the maxSize is reached
 */
public static byte[] parseLine(BufferedInputStream in, int maxSize) throws IOException {
    ByteArrayBuffer bab = new ByteArrayBuffer(512);
    int b;
    while (true) {
        if (!(maxSize <= 0 || bab.length() <= maxSize)) {
            throw new IOException("Maximal bytearraybuffer size of " + maxSize + " exceeded!");
        }
        b = in.read();
        if (b == -1) {
            if (bab.isEmpty()) {
                // we have nothing read yet and could nothing read, we will therefore return 'null' as this
                // indicates EOF.
                return null;
            } else {
                // return what we got so far
                return bab.toByteArray();
            }
        }
        // CRLF case
        if (b == '\r') { // check if we find a \n
            int next = in.read();
            if (b == -1) {
                // EOF; return what we got
                return bab.toByteArray();
            } else if (next == '\n') { // we did
                in.mark(-1); // rest mark
                return bab.toByteArray(); // return the line without CRLF
            } else {
                // found no CRLF but only a CR and some other byte, so we need to add both to the buffer and proceed
                bab.append('\r');
                bab.append(b);
            }
        }
        // LF case
        else if (b == '\n') { // we found a LF and therefore the end of a line
            return bab.toByteArray();
        } else { // we just found a byte which is happily appended
            bab.append(b);
        }
    }
}

From source file:net.reichholf.dreamdroid.helpers.SimpleHttpClient.java

/**
 * @param uri//from   w  w  w.  j a  v  a  2s  .  c  o m
 * @param parameters
 * @return
 */
public boolean fetchPageContent(String uri, List<NameValuePair> parameters) {
    // Set login, ssl, port, host etc;
    applyConfig();

    mErrorText = "";
    mErrorTextId = -1;
    mError = false;
    mBytes = new byte[0];
    if (!uri.startsWith("/")) {
        uri = "/".concat(uri);
    }

    HttpURLConnection conn = null;
    try {
        if (mProfile.getSessionId() != null)
            parameters.add(new BasicNameValuePair("sessionid", mProfile.getSessionId()));
        URL url = new URL(buildUrl(uri, parameters));
        conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(mConnectionTimeoutMillis);
        if (DreamDroid.featurePostRequest())
            conn.setRequestMethod("POST");
        setAuth(conn);
        if (conn.getResponseCode() != 200) {
            if (conn.getResponseCode() == HttpURLConnection.HTTP_BAD_METHOD
                    && mRememberedReturnCode != HttpURLConnection.HTTP_BAD_METHOD) {
                // Method not allowed, the target device either can't handle
                // POST or GET requests (old device or Anti-Hijack enabled)
                DreamDroid.setFeaturePostRequest(!DreamDroid.featurePostRequest());
                conn.disconnect();
                mRememberedReturnCode = HttpURLConnection.HTTP_BAD_METHOD;
                return fetchPageContent(uri, parameters);
            }
            if (conn.getResponseCode() == HttpURLConnection.HTTP_PRECON_FAILED
                    && mRememberedReturnCode != HttpURLConnection.HTTP_PRECON_FAILED) {
                createSession();
                conn.disconnect();
                mRememberedReturnCode = HttpURLConnection.HTTP_PRECON_FAILED;
                return fetchPageContent(uri, parameters);
            }
            mRememberedReturnCode = 0;
            Log.e(LOG_TAG, Integer.toString(conn.getResponseCode()));
            switch (conn.getResponseCode()) {
            case HttpURLConnection.HTTP_UNAUTHORIZED:
                mErrorTextId = R.string.auth_error;
                break;
            default:
                mErrorTextId = -1;
            }
            mErrorText = conn.getResponseMessage();
            mError = true;
            return false;
        }

        BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
        ByteArrayBuffer baf = new ByteArrayBuffer(50);
        int read = 0;
        int bufSize = 512;
        byte[] buffer = new byte[bufSize];
        while ((read = bis.read(buffer)) != -1) {
            baf.append(buffer, 0, read);
        }

        mBytes = baf.toByteArray();
        if (DreamDroid.dumpXml())
            dumpToFile(url);
        return true;

    } catch (MalformedURLException e) {
        mError = true;
        mErrorTextId = R.string.illegal_host;
    } catch (UnknownHostException e) {
        mError = true;
        mErrorText = null;
        mErrorTextId = R.string.host_not_found;
    } catch (ProtocolException e) {
        mError = true;
        mErrorText = e.getLocalizedMessage();
    } catch (ConnectException e) {
        mError = true;
        mErrorTextId = R.string.host_unreach;
    } catch (IOException e) {
        e.printStackTrace();
        mError = true;
        mErrorText = e.getLocalizedMessage();
    } finally {
        if (conn != null)
            conn.disconnect();
        if (mError)
            if (mErrorText == null)
                mErrorText = "Error text is null";
        Log.e(LOG_TAG, mErrorText);
    }

    return false;
}

From source file:com.uf.togathor.db.couchdb.ConnectionHandler.java

/**
 * Get a File object from an URL/*from   www  .  ja  v a 2  s  .com*/
 * 
 * @param url
 * @param path
 * @return
 * @throws IOException 
 * @throws ClientProtocolException 
 * @throws TogathorException
 * @throws JSONException 
 * @throws IllegalStateException 
 * @throws TogathorForbiddenException
 */
public static void getFile(String url, File file, String userId, String token) throws IOException,
        TogathorException, IllegalStateException, JSONException, TogathorForbiddenException {

    File mFile = file;

    //URL mUrl = new URL(url); // you can write here any link

    InputStream is = httpGetRequest(url, userId);
    BufferedInputStream bis = new BufferedInputStream(is);

    ByteArrayBuffer baf = new ByteArrayBuffer(20000);
    int current = 0;
    while ((current = bis.read()) != -1) {
        baf.append((byte) current);
    }

    /* Convert the Bytes read to a String. */
    FileOutputStream fos = new FileOutputStream(mFile);
    fos.write(baf.toByteArray());
    fos.flush();
    fos.close();
    is.close();

}

From source file:com.cloverstudio.spikademo.couchdb.ConnectionHandler.java

/**
 * Get a File object from an URL/* www  .  j av  a2s  .  co m*/
 * 
 * @param url
 * @param path
 * @return
 */
public static void getFile(String url, File file, String userId, String token) {

    File mFile = file;

    try {

        //URL mUrl = new URL(url); // you can write here any link

        InputStream is = httpGetRequest(url, userId);
        BufferedInputStream bis = new BufferedInputStream(is);

        ByteArrayBuffer baf = new ByteArrayBuffer(20000);
        int current = 0;
        while ((current = bis.read()) != -1) {
            baf.append((byte) current);
        }

        /* Convert the Bytes read to a String. */
        FileOutputStream fos = new FileOutputStream(mFile);
        fos.write(baf.toByteArray());
        fos.flush();
        fos.close();
        is.close();

    } catch (Exception e) {
        Logger.error(TAG + "getFile", "Error retrieving file: ", e);
    }

}

From source file:se.dw.okhttpwrapper.ImageRequest.java

private Bitmap downloadBitmap(String url) {
    OkHttpClient client = OkHttpWrapper.getClient();

    if (client == null) {
        Log.w(LOG_TAG, "OkHttpWrapper not initialized, " + url);
        return null;
    }/*from ww w.ja  va  2s. c  om*/

    InputStream in = null;
    HttpURLConnection connection = null;
    try {

        connection = client.open(new URL(url));

        /*
         * http://stackoverflow.com/questions/10550349/retriving-image-from-server-to-android-app
         * Reading directly from stream sometimes BitmapFactory returns null.
         */

        in = connection.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(in, 8190);

        ByteArrayBuffer baf = new ByteArrayBuffer(50);
        int current = 0;
        while ((current = bis.read()) != -1) {
            baf.append((byte) current);
        }
        byte[] imageData = baf.toByteArray();

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;

        BitmapFactory.decodeByteArray(imageData, 0, imageData.length, options);

        int reqWidth = maxImageWidth;
        int reqHeight = maxImageHeight;

        options.inJustDecodeBounds = false;

        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

        Bitmap bitmap = BitmapFactory.decodeByteArray(imageData, 0, imageData.length, options);

        return bitmap;

    } catch (IOException e) {
        Log.w(LOG_TAG, "I/O error while retrieving bitmap from " + url + "\n" + e.toString());
    } catch (IllegalStateException e) {
        Log.w(LOG_TAG, "Incorrect URL: " + url);
    } catch (Exception e) {
        Log.w(LOG_TAG, "Error while retrieving bitmap from " + url, e);
    } finally {
        if (in != null) {
        }
        if (connection != null) {
        }
    }

    return null;
}

From source file:com.tapcentive.sdk.touchpoint.nfc.SEManager.java

/**
 * Send and receive.//from www  . j  a v a2s  .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;
}