Example usage for android.util Base64 DEFAULT

List of usage examples for android.util Base64 DEFAULT

Introduction

In this page you can find the example usage for android.util Base64 DEFAULT.

Prototype

int DEFAULT

To view the source code for android.util Base64 DEFAULT.

Click Source Link

Document

Default values for encoder/decoder flags.

Usage

From source file:jog.my.memory.gcm.ServerUtilities.java

public static Bitmap convertStringRepToPhoto(String s) {
    byte[] b = Base64.decode(s, Base64.DEFAULT);
    ByteArrayInputStream bis = new ByteArrayInputStream(b);
    Bitmap bmp = BitmapFactory.decodeStream(bis);
    return bmp;/*w  w w.ja  v a2 s. co  m*/
}

From source file:org.telegram.android.MessagesController.java

public MessagesController() {
    ImageLoader.getInstance();//from   ww  w. java 2 s  .  com
    MessagesStorage.getInstance();
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.FileDidUpload);
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.FileDidFailUpload);
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.FileDidLoaded);
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.FileDidFailedLoad);
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.messageReceivedByServer);
    addSupportUser();
    SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications",
            Activity.MODE_PRIVATE);
    enableJoined = preferences.getBoolean("EnableContactJoined", true);

    preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig",
            Activity.MODE_PRIVATE);
    maxGroupCount = preferences.getInt("maxGroupCount", 200);
    maxBroadcastCount = preferences.getInt("maxBroadcastCount", 100);
    groupBigSize = preferences.getInt("groupBigSize", 10);
    fontSize = preferences.getInt("fons_size", AndroidUtilities.isTablet() ? 18 : 16);
    String disabledFeaturesString = preferences.getString("disabledFeatures", null);
    if (disabledFeaturesString != null && disabledFeaturesString.length() != 0) {
        try {
            byte[] bytes = Base64.decode(disabledFeaturesString, Base64.DEFAULT);
            if (bytes != null) {
                SerializedData data = new SerializedData(bytes);
                int count = data.readInt32(false);
                for (int a = 0; a < count; a++) {
                    TLRPC.TL_disabledFeature feature = TLRPC.TL_disabledFeature.TLdeserialize(data,
                            data.readInt32(false), false);
                    if (feature != null && feature.feature != null && feature.description != null) {
                        disabledFeatures.add(feature);
                    }
                }
            }
        } catch (Exception e) {
            FileLog.e("tmessages", e);
        }
    }
}

From source file:com.android.email.mail.internet.MimeUtility.java

/**
 * Removes any content transfer encoding from the stream and returns a Body.
 *//* w w  w  . j a v a  2 s .c o  m*/
public static Body decodeBody(InputStream in, String contentTransferEncoding) throws IOException {
    /*
     * We'll remove any transfer encoding by wrapping the stream.
     */
    if (contentTransferEncoding != null) {
        contentTransferEncoding = MimeUtility.getHeaderParameter(contentTransferEncoding, null);
        if ("quoted-printable".equalsIgnoreCase(contentTransferEncoding)) {
            in = new QuotedPrintableInputStream(in);
        } else if ("base64".equalsIgnoreCase(contentTransferEncoding)) {
            in = new Base64InputStream(in, Base64.DEFAULT);
        }
    }

    BinaryTempFileBody tempBody = new BinaryTempFileBody();
    OutputStream out = tempBody.getOutputStream();
    IOUtils.copy(in, out);
    out.close();
    return tempBody;
}

From source file:com.mobiperf_library.measurements.HttpTask.java

/** Runs the HTTP measurement task. Will acquire power lock to ensure wifi
 *  is not turned off *///from w w  w . ja  va  2s. c om
@Override
public MeasurementResult[] call() throws MeasurementError {

    int statusCode = HttpTask.DEFAULT_STATUS_CODE;
    long duration = 0;
    long originalHeadersLen = 0;
    long originalBodyLen;
    String headers = null;
    ByteBuffer body = ByteBuffer.allocate(HttpTask.MAX_BODY_SIZE_TO_UPLOAD);
    //    boolean success = false;
    TaskProgress taskProgress = TaskProgress.FAILED;
    String errorMsg = "";
    InputStream inputStream = null;

    try {
        // set the download URL, a URL that points to a file on the Internet
        // this is the file to be downloaded
        HttpDesc task = (HttpDesc) this.measurementDesc;
        String urlStr = task.url;

        // TODO(Wenjie): Need to set timeout for the HTTP methods
        httpClient = AndroidHttpClient.newInstance(Util.prepareUserAgent());
        HttpRequestBase request = null;
        if (task.method.compareToIgnoreCase("head") == 0) {
            request = new HttpHead(urlStr);
        } else if (task.method.compareToIgnoreCase("get") == 0) {
            request = new HttpGet(urlStr);
        } else if (task.method.compareToIgnoreCase("post") == 0) {
            request = new HttpPost(urlStr);
            HttpPost postRequest = (HttpPost) request;
            postRequest.setEntity(new StringEntity(task.body));
        } else {
            // Use GET by default
            request = new HttpGet(urlStr);
        }

        if (task.headers != null && task.headers.trim().length() > 0) {
            for (String headerLine : task.headers.split("\r\n")) {
                String tokens[] = headerLine.split(":");
                if (tokens.length == 2) {
                    request.addHeader(tokens[0], tokens[1]);
                } else {
                    throw new MeasurementError("Incorrect header line: " + headerLine);
                }
            }
        }

        byte[] readBuffer = new byte[HttpTask.READ_BUFFER_SIZE];
        int readLen;
        int totalBodyLen = 0;

        long startTime = System.currentTimeMillis();
        HttpResponse response = httpClient.execute(request);

        /* TODO(Wenjie): HttpClient does not automatically handle the following codes
         * 301 Moved Permanently. HttpStatus.SC_MOVED_PERMANENTLY
         * 302 Moved Temporarily. HttpStatus.SC_MOVED_TEMPORARILY
         * 303 See Other. HttpStatus.SC_SEE_OTHER
         * 307 Temporary Redirect. HttpStatus.SC_TEMPORARY_REDIRECT
         * 
         * We may want to fetch instead from the redirected page. 
         */
        StatusLine statusLine = response.getStatusLine();
        if (statusLine != null) {
            statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {
                taskProgress = TaskProgress.COMPLETED;
            } else {
                taskProgress = TaskProgress.FAILED;
            }
        }

        /* For HttpClient to work properly, we still want to consume the entire
         * response even if the status code is not 200 
         */
        HttpEntity responseEntity = response.getEntity();
        originalBodyLen = responseEntity.getContentLength();
        long expectedResponseLen = HttpTask.MAX_HTTP_RESPONSE_SIZE;
        // getContentLength() returns negative number if body length is unknown
        if (originalBodyLen > 0) {
            expectedResponseLen = originalBodyLen;
        }

        if (responseEntity != null) {
            inputStream = responseEntity.getContent();
            while ((readLen = inputStream.read(readBuffer)) > 0
                    && totalBodyLen <= HttpTask.MAX_HTTP_RESPONSE_SIZE) {
                totalBodyLen += readLen;
                // Fill in the body to report up to MAX_BODY_SIZE
                if (body.remaining() > 0) {
                    int putLen = body.remaining() < readLen ? body.remaining() : readLen;
                    body.put(readBuffer, 0, putLen);
                }
            }
            duration = System.currentTimeMillis() - startTime;//TODO check this
        }

        Header[] responseHeaders = response.getAllHeaders();
        if (responseHeaders != null) {
            headers = "";
            for (Header hdr : responseHeaders) {
                /*
                 * TODO(Wenjie): There can be preceding and trailing white spaces in
                 * each header field. I cannot find internal methods that return the
                 * number of bytes in a header. The solution here assumes the encoding
                 * is one byte per character.
                 */
                originalHeadersLen += hdr.toString().length();
                headers += hdr.toString() + "\r\n";
            }
        }

        PhoneUtils phoneUtils = PhoneUtils.getPhoneUtils();

        MeasurementResult result = new MeasurementResult(phoneUtils.getDeviceInfo().deviceId,
                phoneUtils.getDeviceProperty(), HttpTask.TYPE, System.currentTimeMillis() * 1000, taskProgress,
                this.measurementDesc);

        result.addResult("code", statusCode);

        if (taskProgress == TaskProgress.COMPLETED) {
            result.addResult("time_ms", duration);
            result.addResult("headers_len", originalHeadersLen);
            result.addResult("body_len", totalBodyLen);
            result.addResult("headers", headers);
            result.addResult("body", Base64.encodeToString(body.array(), Base64.DEFAULT));
        }

        Logger.i(MeasurementJsonConvertor.toJsonString(result));
        MeasurementResult[] mrArray = new MeasurementResult[1];
        mrArray[0] = result;
        return mrArray;
    } catch (MalformedURLException e) {
        errorMsg += e.getMessage() + "\n";
        Logger.e(e.getMessage());
    } catch (IOException e) {
        errorMsg += e.getMessage() + "\n";
        Logger.e(e.getMessage());
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                Logger.e("Fails to close the input stream from the HTTP response");
            }
        }
        if (httpClient != null) {
            httpClient.close();
        }

    }
    throw new MeasurementError("Cannot get result from HTTP measurement because " + errorMsg);
}

From source file:com.mobilyzer.measurements.HttpTask.java

/** Runs the HTTP measurement task. Will acquire power lock to ensure wifi
 *  is not turned off */// ww  w  . ja v a  2  s.c  o m
@Override
public MeasurementResult[] call() throws MeasurementError {

    int statusCode = HttpTask.DEFAULT_STATUS_CODE;
    long duration = 0;
    long originalHeadersLen = 0;
    long originalBodyLen;
    String headers = null;
    ByteBuffer body = ByteBuffer.allocate(HttpTask.MAX_BODY_SIZE_TO_UPLOAD);
    //    boolean success = false;
    TaskProgress taskProgress = TaskProgress.FAILED;
    String errorMsg = "";
    InputStream inputStream = null;

    long currentRxTx = Util.getCurrentRxTxBytes();

    try {
        // set the download URL, a URL that points to a file on the Internet
        // this is the file to be downloaded
        HttpDesc task = (HttpDesc) this.measurementDesc;
        String urlStr = task.url;

        // TODO(Wenjie): Need to set timeout for the HTTP methods
        httpClient = AndroidHttpClient.newInstance(Util.prepareUserAgent());
        HttpRequestBase request = null;
        if (task.method.compareToIgnoreCase("head") == 0) {
            request = new HttpHead(urlStr);
        } else if (task.method.compareToIgnoreCase("get") == 0) {
            request = new HttpGet(urlStr);
        } else if (task.method.compareToIgnoreCase("post") == 0) {
            request = new HttpPost(urlStr);
            HttpPost postRequest = (HttpPost) request;
            postRequest.setEntity(new StringEntity(task.body));
        } else {
            // Use GET by default
            request = new HttpGet(urlStr);
        }

        if (task.headers != null && task.headers.trim().length() > 0) {
            for (String headerLine : task.headers.split("\r\n")) {
                String tokens[] = headerLine.split(":");
                if (tokens.length == 2) {
                    request.addHeader(tokens[0], tokens[1]);
                } else {
                    throw new MeasurementError("Incorrect header line: " + headerLine);
                }
            }
        }

        byte[] readBuffer = new byte[HttpTask.READ_BUFFER_SIZE];
        int readLen;
        int totalBodyLen = 0;

        long startTime = System.currentTimeMillis();
        HttpResponse response = httpClient.execute(request);

        /* TODO(Wenjie): HttpClient does not automatically handle the following codes
         * 301 Moved Permanently. HttpStatus.SC_MOVED_PERMANENTLY
         * 302 Moved Temporarily. HttpStatus.SC_MOVED_TEMPORARILY
         * 303 See Other. HttpStatus.SC_SEE_OTHER
         * 307 Temporary Redirect. HttpStatus.SC_TEMPORARY_REDIRECT
         * 
         * We may want to fetch instead from the redirected page. 
         */
        StatusLine statusLine = response.getStatusLine();
        if (statusLine != null) {
            statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {
                taskProgress = TaskProgress.COMPLETED;
            } else {
                taskProgress = TaskProgress.FAILED;
            }
        }

        /* For HttpClient to work properly, we still want to consume the entire
         * response even if the status code is not 200 
         */
        HttpEntity responseEntity = response.getEntity();
        originalBodyLen = responseEntity.getContentLength();
        long expectedResponseLen = HttpTask.MAX_HTTP_RESPONSE_SIZE;
        // getContentLength() returns negative number if body length is unknown
        if (originalBodyLen > 0) {
            expectedResponseLen = originalBodyLen;
        }

        if (responseEntity != null) {
            inputStream = responseEntity.getContent();
            while ((readLen = inputStream.read(readBuffer)) > 0
                    && totalBodyLen <= HttpTask.MAX_HTTP_RESPONSE_SIZE) {
                totalBodyLen += readLen;
                // Fill in the body to report up to MAX_BODY_SIZE
                if (body.remaining() > 0) {
                    int putLen = body.remaining() < readLen ? body.remaining() : readLen;
                    body.put(readBuffer, 0, putLen);
                }
            }
            duration = System.currentTimeMillis() - startTime;//TODO check this
        }

        Header[] responseHeaders = response.getAllHeaders();
        if (responseHeaders != null) {
            headers = "";
            for (Header hdr : responseHeaders) {
                /*
                 * TODO(Wenjie): There can be preceding and trailing white spaces in
                 * each header field. I cannot find internal methods that return the
                 * number of bytes in a header. The solution here assumes the encoding
                 * is one byte per character.
                 */
                originalHeadersLen += hdr.toString().length();
                headers += hdr.toString() + "\r\n";
            }
        }

        PhoneUtils phoneUtils = PhoneUtils.getPhoneUtils();

        MeasurementResult result = new MeasurementResult(phoneUtils.getDeviceInfo().deviceId,
                phoneUtils.getDeviceProperty(this.getKey()), HttpTask.TYPE, System.currentTimeMillis() * 1000,
                taskProgress, this.measurementDesc);

        result.addResult("code", statusCode);

        dataConsumed += (Util.getCurrentRxTxBytes() - currentRxTx);

        if (taskProgress == TaskProgress.COMPLETED) {
            result.addResult("time_ms", duration);
            result.addResult("headers_len", originalHeadersLen);
            result.addResult("body_len", totalBodyLen);
            result.addResult("headers", headers);
            result.addResult("body", Base64.encodeToString(body.array(), Base64.DEFAULT));
        }

        Logger.i(MeasurementJsonConvertor.toJsonString(result));
        MeasurementResult[] mrArray = new MeasurementResult[1];
        mrArray[0] = result;
        return mrArray;
    } catch (MalformedURLException e) {
        errorMsg += e.getMessage() + "\n";
        Logger.e(e.getMessage());
    } catch (IOException e) {
        errorMsg += e.getMessage() + "\n";
        Logger.e(e.getMessage());
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                Logger.e("Fails to close the input stream from the HTTP response");
            }
        }
        if (httpClient != null) {
            httpClient.close();
        }

    }
    throw new MeasurementError("Cannot get result from HTTP measurement because " + errorMsg);
}

From source file:com.zetaDevelopment.phonegap.plugin.sqlitePlugin.SQLitePlugin.java

/**
 * Convert results cursor to JSON string.
 *
 * @param cur/*ww w.  jav a  2 s  .  c  om*/
 *            Cursor into query results
 *
 * @return results in string form
 *
 */
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private String results2string(Cursor cur) {
    String result = "[]";

    // If query result has rows
    if (cur.moveToFirst()) {
        JSONArray fullresult = new JSONArray();
        String key = "";
        int colCount = cur.getColumnCount();

        // Build up JSON result object for each row
        do {
            JSONObject row = new JSONObject();
            try {
                for (int i = 0; i < colCount; ++i) {
                    key = cur.getColumnName(i);

                    // for old Android SDK remove lines from HERE:
                    if (android.os.Build.VERSION.SDK_INT >= 11) {
                        switch (cur.getType(i)) {
                        case Cursor.FIELD_TYPE_NULL:
                            row.put(key, null);
                            break;
                        case Cursor.FIELD_TYPE_INTEGER:
                            row.put(key, cur.getInt(i));
                            break;
                        case Cursor.FIELD_TYPE_FLOAT:
                            row.put(key, cur.getFloat(i));
                            break;
                        case Cursor.FIELD_TYPE_STRING:
                            row.put(key, cur.getString(i));
                            break;
                        case Cursor.FIELD_TYPE_BLOB:
                            //row.put(key, cur.getBlob(i));
                            row.put(key, new String(Base64.encode(cur.getBlob(i), Base64.DEFAULT)));
                            break;
                        }
                    } else // to HERE.
                    {
                        row.put(key, cur.getString(i));
                    }
                }

                fullresult.put(row);

            } catch (JSONException e) {
                e.printStackTrace();
            }

        } while (cur.moveToNext());

        result = fullresult.toString();
    }

    return result;
}

From source file:com.mobilyzer.measurements.HttpTask_original.java

/** Runs the HTTP measurement task. Will acquire power lock to ensure wifi
 *  is not turned off *//* w w  w  .j a v  a2s  .  co m*/
@Override
public MeasurementResult[] call() throws MeasurementError {

    int statusCode = HttpTask.DEFAULT_STATUS_CODE;
    long duration = 0;
    long originalHeadersLen = 0;
    long originalBodyLen;
    String headers = null;
    ByteBuffer body = ByteBuffer.allocate(HttpTask_original.MAX_BODY_SIZE_TO_UPLOAD);
    //    boolean success = false;
    TaskProgress taskProgress = TaskProgress.FAILED;
    String errorMsg = "";
    InputStream inputStream = null;

    long currentRxTx = Util.getCurrentRxTxBytes();

    try {
        // set the download URL, a URL that points to a file on the Internet
        // this is the file to be downloaded
        HttpDesc task = (HttpDesc) this.measurementDesc;
        String urlStr = task.url;

        // TODO(Wenjie): Need to set timeout for the HTTP methods
        httpClient = AndroidHttpClient.newInstance(Util.prepareUserAgent());
        HttpRequestBase request = null;
        if (task.method.compareToIgnoreCase("head") == 0) {
            request = new HttpHead(urlStr);
        } else if (task.method.compareToIgnoreCase("get") == 0) {
            request = new HttpGet(urlStr);
        } else if (task.method.compareToIgnoreCase("post") == 0) {
            request = new HttpPost(urlStr);
            HttpPost postRequest = (HttpPost) request;
            postRequest.setEntity(new StringEntity(task.body));
        } else {
            // Use GET by default
            request = new HttpGet(urlStr);
        }

        if (task.headers != null && task.headers.trim().length() > 0) {
            for (String headerLine : task.headers.split("\r\n")) {
                String tokens[] = headerLine.split(":");
                if (tokens.length == 2) {
                    request.addHeader(tokens[0], tokens[1]);
                } else {
                    throw new MeasurementError("Incorrect header line: " + headerLine);
                }
            }
        }

        byte[] readBuffer = new byte[HttpTask.READ_BUFFER_SIZE];
        int readLen;
        int totalBodyLen = 0;

        long startTime = System.currentTimeMillis();
        HttpResponse response = httpClient.execute(request);

        /* TODO(Wenjie): HttpClient does not automatically handle the following codes
         * 301 Moved Permanently. HttpStatus.SC_MOVED_PERMANENTLY
         * 302 Moved Temporarily. HttpStatus.SC_MOVED_TEMPORARILY
         * 303 See Other. HttpStatus.SC_SEE_OTHER
         * 307 Temporary Redirect. HttpStatus.SC_TEMPORARY_REDIRECT
         * 
         * We may want to fetch instead from the redirected page. 
         */
        StatusLine statusLine = response.getStatusLine();
        if (statusLine != null) {
            statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {
                taskProgress = TaskProgress.COMPLETED;
            } else {
                taskProgress = TaskProgress.FAILED;
            }
        }

        /* For HttpClient to work properly, we still want to consume the entire
         * response even if the status code is not 200 
         */
        HttpEntity responseEntity = response.getEntity();
        originalBodyLen = responseEntity.getContentLength();
        long expectedResponseLen = HttpTask.MAX_HTTP_RESPONSE_SIZE;
        // getContentLength() returns negative number if body length is unknown
        if (originalBodyLen > 0) {
            expectedResponseLen = originalBodyLen;
        }

        if (responseEntity != null) {
            inputStream = responseEntity.getContent();
            while ((readLen = inputStream.read(readBuffer)) > 0
                    && totalBodyLen <= HttpTask.MAX_HTTP_RESPONSE_SIZE) {
                totalBodyLen += readLen;
                // Fill in the body to report up to MAX_BODY_SIZE
                if (body.remaining() > 0) {
                    int putLen = body.remaining() < readLen ? body.remaining() : readLen;
                    body.put(readBuffer, 0, putLen);
                }
            }
            duration = System.currentTimeMillis() - startTime;//TODO check this
        }

        Header[] responseHeaders = response.getAllHeaders();
        if (responseHeaders != null) {
            headers = "";
            for (Header hdr : responseHeaders) {
                /*
                 * TODO(Wenjie): There can be preceding and trailing white spaces in
                 * each header field. I cannot find internal methods that return the
                 * number of bytes in a header. The solution here assumes the encoding
                 * is one byte per character.
                 */
                originalHeadersLen += hdr.toString().length();
                headers += hdr.toString() + "\r\n";
            }
        }

        PhoneUtils phoneUtils = PhoneUtils.getPhoneUtils();

        MeasurementResult result = new MeasurementResult(phoneUtils.getDeviceInfo().deviceId,
                phoneUtils.getDeviceProperty(this.getKey()), HttpTask.TYPE, System.currentTimeMillis() * 1000,
                taskProgress, this.measurementDesc);

        result.addResult("code", statusCode);

        dataConsumed += (Util.getCurrentRxTxBytes() - currentRxTx);

        if (taskProgress == TaskProgress.COMPLETED) {
            result.addResult("time_ms", duration);
            result.addResult("headers_len", originalHeadersLen);
            result.addResult("body_len", totalBodyLen);
            result.addResult("headers", headers);
            result.addResult("body", Base64.encodeToString(body.array(), Base64.DEFAULT));
        }

        Logger.i(MeasurementJsonConvertor.toJsonString(result));
        MeasurementResult[] mrArray = new MeasurementResult[1];
        mrArray[0] = result;
        return mrArray;
    } catch (MalformedURLException e) {
        errorMsg += e.getMessage() + "\n";
        Logger.e(e.getMessage());
    } catch (IOException e) {
        errorMsg += e.getMessage() + "\n";
        Logger.e(e.getMessage());
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                Logger.e("Fails to close the input stream from the HTTP response");
            }
        }
        if (httpClient != null) {
            httpClient.close();
        }

    }
    throw new MeasurementError("Cannot get result from HTTP measurement because " + errorMsg);
}

From source file:io.realm.TypeBasedNotificationsTests.java

@Test
@RunTestInLooperThread//from w  w w .j ava2s .  c o  m
public void callback_should_trigger_for_createObjectFromJson_from_JSONObject() {
    final Realm realm = looperThread.realm;
    realm.addChangeListener(new RealmChangeListener() {
        @Override
        public void onChange() {
            if (globalCommitInvocations.incrementAndGet() == 1) {
                realm.handler.post(new Runnable() {
                    @Override
                    public void run() {
                        assertEquals(1, typebasedCommitInvocations.get());
                        looperThread.testComplete();
                    }
                });
            }
        }
    });

    try {
        JSONObject json = new JSONObject();
        json.put("columnString", "String");
        json.put("columnLong", 1L);
        json.put("columnFloat", 1.23f);
        json.put("columnDouble", 1.23d);
        json.put("columnBoolean", true);
        json.put("columnBinary", new String(Base64.encode(new byte[] { 1, 2, 3 }, Base64.DEFAULT)));

        realm.beginTransaction();
        final AllTypes objectFromJson = realm.createObjectFromJson(AllTypes.class, json);
        realm.commitTransaction();

        objectFromJson.addChangeListener(new RealmChangeListener() {
            @Override
            public void onChange() {
                assertEquals("ObjectFromJson", objectFromJson.getColumnString());
                assertEquals(1L, objectFromJson.getColumnLong());
                assertEquals(1.23F, objectFromJson.getColumnFloat(), 0F);
                assertEquals(1.23D, objectFromJson.getColumnDouble(), 0D);
                assertEquals(true, objectFromJson.isColumnBoolean());
                assertArrayEquals(new byte[] { 1, 2, 3 }, objectFromJson.getColumnBinary());
                typebasedCommitInvocations.incrementAndGet();
            }
        });

        realm.beginTransaction();
        objectFromJson.setColumnString("ObjectFromJson");
        realm.commitTransaction();

    } catch (JSONException e) {
        fail(e.getMessage());
    }
}

From source file:OAUTHnesia.java

private static String sha1(String s, String keyString)
        throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {

    SecretKeySpec key = new SecretKeySpec((keyString).getBytes("UTF-8"), "HmacSHA1");
    Mac mac = Mac.getInstance("HmacSHA1");
    mac.init(key);/*from   w  ww  .  j ava  2  s.  co m*/

    byte[] bytes = mac.doFinal(s.getBytes("UTF-8"));

    return new String(Base64.encode(bytes, Base64.DEFAULT));
}

From source file:org.jboss.aerogear.android.unifiedpush.gcm.AeroGearGCMPushRegistrar.java

private String getHashedAuth(String username, char[] password) {
    StringBuilder headerValueBuilder = new StringBuilder(AUTHORIZATION_METHOD).append(" ");
    String unhashedCredentials = new StringBuilder(username).append(":").append(password).toString();
    String hashedCrentials = Base64.encodeToString(unhashedCredentials.getBytes(),
            Base64.DEFAULT | Base64.NO_WRAP);
    return headerValueBuilder.append(hashedCrentials).toString();
}