Example usage for android.util Base64 encode

List of usage examples for android.util Base64 encode

Introduction

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

Prototype

public static byte[] encode(byte[] input, int flags) 

Source Link

Document

Base64-encode the given data and return a newly allocated byte[] with the result.

Usage

From source file:com.darktalker.cordova.screenshot.Screenshot.java

@Override
public boolean execute(String action, JSONArray args, final CallbackContext callbackContext)
        throws JSONException {
    // starting on ICS, some WebView methods
    // can only be called on UI threads

    if (action.equals("saveScreenshot")) {
        final String format = (String) args.get(0);
        final Integer quality = (Integer) args.get(1);
        final String fileName = (String) args.get(2);

        super.cordova.getActivity().runOnUiThread(new Runnable() {
            @Override/*from   w w w  .j  a  v  a2  s . c om*/
            public void run() {

                try {
                    if (format.equals("png") || format.equals("jpg")) {
                        Bitmap bitmap = getBitmap();
                        File folder = new File(Environment.getExternalStorageDirectory(), "Pictures");
                        if (!folder.exists()) {
                            folder.mkdirs();
                        }

                        File f = new File(folder, fileName + "." + format);

                        FileOutputStream fos = new FileOutputStream(f);
                        if (format.equals("png")) {
                            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
                        }
                        if (format.equals("jpg")) {
                            bitmap.compress(Bitmap.CompressFormat.JPEG, quality == null ? 100 : quality, fos);
                        }
                        JSONObject jsonRes = new JSONObject();
                        jsonRes.put("filePath", f.getAbsolutePath());
                        PluginResult result = new PluginResult(PluginResult.Status.OK, jsonRes);
                        callbackContext.sendPluginResult(result);

                        scanPhoto(f.getAbsolutePath());
                    } else {
                        callbackContext.error("format " + format + " not found");

                    }

                } catch (JSONException e) {
                    callbackContext.error(e.getMessage());

                } catch (IOException e) {
                    callbackContext.error(e.getMessage());

                }
            }
        });
        return true;
    } else if (action.equals("getScreenshotAsURI")) {
        final Integer quality = (Integer) args.get(0);

        super.cordova.getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    Bitmap bitmap = getBitmap();

                    ByteArrayOutputStream jpeg_data = new ByteArrayOutputStream();

                    if (bitmap.compress(CompressFormat.JPEG, quality, jpeg_data)) {
                        byte[] code = jpeg_data.toByteArray();
                        byte[] output = Base64.encode(code, Base64.NO_WRAP);
                        String js_out = new String(output);
                        js_out = "data:image/jpeg;base64," + js_out;
                        JSONObject jsonRes = new JSONObject();
                        jsonRes.put("URI", js_out);
                        PluginResult result = new PluginResult(PluginResult.Status.OK, jsonRes);
                        callbackContext.sendPluginResult(result);

                        js_out = null;
                        output = null;
                        code = null;
                    }

                    jpeg_data = null;

                } catch (JSONException e) {
                    callbackContext.error(e.getMessage());

                } catch (Exception e) {
                    callbackContext.error(e.getMessage());

                }
            }
        });

        return true;
    }
    callbackContext.error("action not found");
    return false;
}

From source file:com.wodify.cordova.plugin.filepicker.FilePicker.java

/**
 * Converts byte array to base 64 representation of string.
 * //from w ww  .  ja v  a  2s.  c  om
 * @param  bytes
 *         Byte representation of file
 */
private String getBase64EncodedStringFromBytes(byte[] bytes) {
    if (bytes != null && bytes.length > 0) {
        byte[] base64EncodedFile = Base64.encode(bytes, Base64.NO_WRAP);
        return new String(base64EncodedFile);
    }
    return null;
}

From source file:com.ruesga.rview.fragments.SnippetFragment.java

private void loadContent(byte[] data) {
    final String fileName;
    if (mNeedPermissions) {
        fileName = DEFAULT_SNIPPED_NAME + ".txt";
    } else {// w w w  .  j a v a 2s .  com
        String ext = AceEditorView.resolveExtensionFromMimeType(mMimeType);
        fileName = DEFAULT_SNIPPED_NAME + "." + ext;
    }

    mBinding.editor.scrollTo(0, 0);
    mBinding.editor.loadEncodedContent(fileName, Base64.encode(data, Base64.NO_WRAP));
}

From source file:com.owncloud.android.utils.PushUtils.java

public static void pushRegistrationToServer() {
    String token = PreferenceManager.getPushToken(MainApp.getAppContext());
    arbitraryDataProvider = new ArbitraryDataProvider(MainApp.getAppContext().getContentResolver());

    if (!TextUtils.isEmpty(MainApp.getAppContext().getResources().getString(R.string.push_server_url))
            && !TextUtils.isEmpty(token)) {
        PushUtils.generateRsa2048KeyPair();
        String pushTokenHash = PushUtils.generateSHA512Hash(token).toLowerCase();
        PublicKey devicePublicKey = (PublicKey) PushUtils.readKeyFromFile(true);
        if (devicePublicKey != null) {
            byte[] publicKeyBytes = Base64.encode(devicePublicKey.getEncoded(), Base64.NO_WRAP);
            String publicKey = new String(publicKeyBytes);
            publicKey = publicKey.replaceAll("(.{64})", "$1\n");

            publicKey = "-----BEGIN PUBLIC KEY-----\n" + publicKey + "\n-----END PUBLIC KEY-----\n";

            Context context = MainApp.getAppContext();
            String providerValue;
            PushConfigurationState accountPushData = null;
            Gson gson = new Gson();
            for (Account account : AccountUtils.getAccounts(context)) {
                providerValue = arbitraryDataProvider.getValue(account, KEY_PUSH);
                if (!TextUtils.isEmpty(providerValue)) {
                    accountPushData = gson.fromJson(providerValue, PushConfigurationState.class);
                } else {
                    accountPushData = null;
                }//from  ww w  . j a  va2s  .c om

                if (accountPushData != null && !accountPushData.getPushToken().equals(token)
                        && !accountPushData.isShouldBeDeleted() || TextUtils.isEmpty(providerValue)) {
                    try {
                        OwnCloudAccount ocAccount = new OwnCloudAccount(account, context);
                        OwnCloudClient mClient = OwnCloudClientManagerFactory.getDefaultSingleton()
                                .getClientFor(ocAccount, context);

                        RemoteOperation registerAccountDeviceForNotificationsOperation = new RegisterAccountDeviceForNotificationsOperation(
                                pushTokenHash, publicKey,
                                context.getResources().getString(R.string.push_server_url));

                        RemoteOperationResult remoteOperationResult = registerAccountDeviceForNotificationsOperation
                                .execute(mClient);

                        if (remoteOperationResult.isSuccess()) {
                            PushResponse pushResponse = remoteOperationResult.getPushResponseData();

                            RemoteOperation registerAccountDeviceForProxyOperation = new RegisterAccountDeviceForProxyOperation(
                                    context.getResources().getString(R.string.push_server_url), token,
                                    pushResponse.getDeviceIdentifier(), pushResponse.getSignature(),
                                    pushResponse.getPublicKey());

                            remoteOperationResult = registerAccountDeviceForProxyOperation.execute(mClient);

                            if (remoteOperationResult.isSuccess()) {
                                PushConfigurationState pushArbitraryData = new PushConfigurationState(token,
                                        pushResponse.getDeviceIdentifier(), pushResponse.getSignature(),
                                        pushResponse.getPublicKey(), false);
                                arbitraryDataProvider.storeOrUpdateKeyValue(account.name, KEY_PUSH,
                                        gson.toJson(pushArbitraryData));
                            }
                        }
                    } catch (com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException e) {
                        Log_OC.d(TAG, "Failed to find an account");
                    } catch (AuthenticatorException e) {
                        Log_OC.d(TAG, "Failed via AuthenticatorException");
                    } catch (IOException e) {
                        Log_OC.d(TAG, "Failed via IOException");
                    } catch (OperationCanceledException e) {
                        Log_OC.d(TAG, "Failed via OperationCanceledException");
                    }
                } else if (accountPushData != null && accountPushData.isShouldBeDeleted()) {
                    deleteRegistrationForAccount(account);
                }
            }
        }
    }
}

From source file:io.realm.RealmJsonTests.java

@Test
public void createObjectFromJson_allSimpleObjectAllTypes() throws JSONException {
    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();/*from   ww w  . java  2  s. c  o m*/
    realm.createObjectFromJson(AllTypes.class, json);
    realm.commitTransaction();
    AllTypes obj = realm.allObjects(AllTypes.class).first();

    // Check that all primitive types are imported correctly
    assertEquals("String", obj.getColumnString());
    assertEquals(1L, obj.getColumnLong());
    assertEquals(1.23F, obj.getColumnFloat(), 0F);
    assertEquals(1.23D, obj.getColumnDouble(), 0D);
    assertEquals(true, obj.isColumnBoolean());
    assertArrayEquals(new byte[] { 1, 2, 3 }, obj.getColumnBinary());
}

From source file:com.samknows.measurement.net.Connection.java

/** Get the HTTP digest authentication. Uses Base64 to encode credentials.
 * /*from w w  w .j a v  a2 s  .  co m*/
 * @return String
 */
public String getCredentials() {
    return new String(Base64.encode((mUsername + ":" + mPassword).getBytes(), Base64.DEFAULT));
}

From source file:libcore.tzdata.update_test_app.installupdatetestapp.MainActivity.java

private static String createSignature(File contentFile, String version, String requiredHash) throws Exception {
    byte[] contentBytes = readBytes(contentFile);
    Signature signer = Signature.getInstance("SHA512withRSA");
    signer.initSign(createKey());/*from w w w. j  a  v  a2  s.  co m*/
    signer.update(contentBytes);
    signer.update(version.trim().getBytes());
    signer.update(requiredHash.getBytes());
    return new String(Base64.encode(signer.sign(), Base64.DEFAULT));
}

From source file:com.kik.phonegap.plugin.messenger.KikMessengerPlugin.java

public String SerializeKikData(KikData data_in) {
    try {//w w  w  .j a v  a  2  s . c  o  m
        JSONObject wrapper = new JSONObject();
        JSONObject ret_object = new JSONObject();
        int result = 0;

        if ((data_in.getType() == KikData.TYPE_PICK)) {
            result = 2;
        } else if ((data_in.getType() == KikData.TYPE_VIEW)) {
            result = 1;
        } else {
            result = 0;
        }

        ret_object.put("type", result);
        ret_object.put("myName", data_in.getMyName());
        ret_object.put("senderName", data_in.getSenderName());
        ret_object.put("contentID", data_in.getConvoId());

        if (data_in.getType() == KikData.TYPE_VIEW) {
            JSONObject message_data = new JSONObject();
            KikMessage msg = data_in.getMessage();
            message_data.put("title", msg.getTitle());
            message_data.put("description", msg.getText());
            message_data.put("fileUrl", msg.getFileUrl());
            ret_object.put("message", message_data);

            // We are going to put the preview image 
            // as serialized data
            Drawable d = msg.getPreviewImage();
            Bitmap bitmap = ((BitmapDrawable) d).getBitmap();
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
            byte[] bitmap_data = stream.toByteArray();
            message_data.put("preview", new String(Base64.encode(bitmap_data, 0)));

        }

        wrapper.put("message", ret_object);
        return wrapper.toString();
    } catch (JSONException e) {
        return "";
    }

}

From source file:com.owncloud.android.utils.EncryptionUtils.java

public static byte[] encodeStringToBase64Bytes(String string) {
    try {/*w w  w  . j a v a  2 s  . c o  m*/
        return Base64.encode(string.getBytes(), Base64.NO_WRAP);
    } catch (Exception e) {
        return new byte[0];
    }
}

From source file:com.playhaven.android.req.PlayHavenRequest.java

protected String createHmac(SharedPreferences pref, String content, boolean stripEquals)
        throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
    String secret = getString(pref, Secret);
    SecretKeySpec key = new SecretKeySpec(secret.getBytes(UTF8), HMAC);
    Mac hmac = Mac.getInstance(HMAC);
    hmac.init(key);/*from w  w w.j  a  v  a  2  s . co  m*/
    hmac.update(content.getBytes(UTF8));
    byte[] bytes = hmac.doFinal();
    String derived = new String(Base64.encode(bytes, Base64.URL_SAFE), UTF8).trim();
    if (stripEquals)
        derived = derived.replaceAll("=", "");

    return derived;
}