Example usage for android.util Base64 encodeToString

List of usage examples for android.util Base64 encodeToString

Introduction

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

Prototype

public static String encodeToString(byte[] input, int flags) 

Source Link

Document

Base64-encode the given data and return a newly allocated String with the result.

Usage

From source file:com.hybris.mobile.data.WebServiceDataProvider.java

/**
 * Synchronous call for logging in//w ww  . j av  a 2  s .  c o  m
 * 
 * @param httpBody
 * @return The data from the server as a string, in almost all cases JSON
 * @throws MalformedURLException
 * @throws IOException
 * @throws JSONException
 */
public static String getLoginResponse(Bundle httpBody) throws MalformedURLException, IOException {
    String response = "";
    URL url = new URL(WebServiceAuthProvider.tokenURL());
    trustAllHosts();
    HttpsURLConnection connection = createSecureConnection(url);
    connection.setHostnameVerifier(DO_NOT_VERIFY);
    String authString = "mobile_android:secret";
    String authValue = "Basic " + Base64.encodeToString(authString.getBytes(), Base64.NO_WRAP);

    connection.setRequestMethod("POST");
    connection.setRequestProperty("Authorization", authValue);
    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.connect();

    OutputStream os = new BufferedOutputStream(connection.getOutputStream());
    os.write(encodePostBody(httpBody).getBytes());
    os.flush();
    try {
        LoggingUtils.d(LOG_TAG, connection.toString());
        response = readFromStream(connection.getInputStream());
    } catch (MalformedURLException e) {
        LoggingUtils.e(LOG_TAG,
                "Error reading stream \"" + connection.getInputStream() + "\". " + e.getLocalizedMessage(),
                null);
    } catch (IOException e) {
        response = readFromStream(connection.getErrorStream());
    } finally {
        connection.disconnect();
    }

    return response;
}

From source file:mobisocial.bento.todo.io.BentoManager.java

synchronized public void addTodo(TodoListItem item, Bitmap image, String msg) {
    mBento.bento.todoList.add(0, item);//w  w w  . j  a  va  2s  .  c o m

    if (image == null) {
        pushUpdate(msg);
    } else {
        String data = Base64.encodeToString(BitmapHelper.bitmapToBytes(image), Base64.DEFAULT);
        pushUpdate(msg, item.uuid, data, false);
    }
}

From source file:com.ferid.app.frequentcontacts.MainActivity.java

/**
 * After photo process return/*from w ww  .j  a v  a2s. c om*/
 */
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == RESULT_LOAD_IMAGE) {
        //a photo picked from the gallery
        if (resultCode == RESULT_OK) {
            try {
                Uri photoUri = data.getData();

                InputStream is = this.getContentResolver().openInputStream(photoUri);
                BitmapFactory.Options dbo = new BitmapFactory.Options();
                dbo.inJustDecodeBounds = true;
                BitmapFactory.decodeStream(is, null, dbo);
                if (is != null)
                    is.close();

                int rotatedWidth, rotatedHeight;
                int orientation = getOrientation(this, photoUri);

                if (orientation == 90 || orientation == 270) {
                    rotatedWidth = dbo.outHeight;
                    rotatedHeight = dbo.outWidth;
                } else {
                    rotatedWidth = dbo.outWidth;
                    rotatedHeight = dbo.outHeight;
                }

                Bitmap srcBitmap;
                is = this.getContentResolver().openInputStream(photoUri);
                int MAX_IMAGE_HEIGHT = 250;
                int MAX_IMAGE_WIDTH = 250;
                if (rotatedWidth > MAX_IMAGE_WIDTH || rotatedHeight > MAX_IMAGE_HEIGHT) {
                    float widthRatio = ((float) rotatedWidth) / ((float) MAX_IMAGE_WIDTH);
                    float heightRatio = ((float) rotatedHeight) / ((float) MAX_IMAGE_HEIGHT);
                    float maxRatio = Math.max(widthRatio, heightRatio);

                    // Create the bitmap from file
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inSampleSize = (int) maxRatio;
                    srcBitmap = BitmapFactory.decodeStream(is, null, options);
                } else {
                    srcBitmap = BitmapFactory.decodeStream(is);
                }
                if (is != null)
                    is.close();

                //if the orientation is not 0 (or -1, which means we don't know), we have to do a rotation.
                if (orientation > 0) {
                    Matrix matrix = new Matrix();
                    matrix.postRotate(orientation);

                    srcBitmap = Bitmap.createBitmap(srcBitmap, 0, 0, srcBitmap.getWidth(),
                            srcBitmap.getHeight(), matrix, true);
                }

                //srcBitmap is ready now
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                srcBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
                byte[] byteArray = stream.toByteArray();

                // byte[] to String convert.
                String encodedImage = Base64.encodeToString(byteArray, Base64.DEFAULT);

                //anti-memory leak
                srcBitmap.recycle();

                //ready to set photo
                contact.setPhoto(encodedImage);
                save_refresh();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    } else if (requestCode == SELECT_NUMBER) {
        //a contact selected from the list
        if (resultCode == RESULT_OK) {
            try {
                Contact contact = (Contact) data.getSerializableExtra("contact");
                if (contact != null) {
                    contactsList.add(contact);
                    save_refresh();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

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

public void updateConfig(final TLRPC.TL_config config) {
    AndroidUtilities.runOnUIThread(new Runnable() { //TODO use new config params
        @Override/*from ww  w. j av a2s  .c  o  m*/
        public void run() {
            maxBroadcastCount = config.broadcast_size_max;
            maxGroupCount = config.chat_size_max;
            groupBigSize = config.chat_big_size;
            disabledFeatures = config.disabled_features;

            SharedPreferences preferences = ApplicationLoader.applicationContext
                    .getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
            SharedPreferences.Editor editor = preferences.edit();
            editor.putInt("maxGroupCount", maxGroupCount);
            editor.putInt("maxBroadcastCount", maxBroadcastCount);
            editor.putInt("groupBigSize", groupBigSize);
            try {
                SerializedData data = new SerializedData();
                data.writeInt32(disabledFeatures.size());
                for (TLRPC.TL_disabledFeature disabledFeature : disabledFeatures) {
                    disabledFeature.serializeToStream(data);
                }
                String string = Base64.encodeToString(data.toByteArray(), Base64.DEFAULT);
                if (string != null && string.length() != 0) {
                    editor.putString("disabledFeatures", string);
                }
            } catch (Exception e) {
                editor.remove("disabledFeatures");
                FileLog.e("tmessages", e);
            }
            editor.commit();
        }
    });
}

From source file:com.diona.fileReader.CipherUtil.java

/**
 * Generates a random Base64 encoded string value.
 * /*from   ww w.ja va  2  s  .c  om*/
 * @param length
 *          The length of the key.
 * @return A random key value.
 */
public String generateRandomKeyString(final int length) {
    return Base64.encodeToString(generateRandomKeyBytes(length), Base64.DEFAULT);
}

From source file:com.aknowledge.v1.automation.RemoteActivity.java

private void doCommand(String myTag, String command) {
    final String curCommand = command;
    final String curTag = myTag;
    HashMap<String, String> params = new HashMap<String, String>();
    params.put("command=", "off");
    Log.d("RemoteActivity", "doCommand:" + hostname + "/api/device/" + myTag + " " + params.toString());
    JsonObjectRequest req = new JsonObjectRequest(Method.POST, hostname + "/api/device/" + myTag, null,
            new Response.Listener<JSONObject>() {

                @Override//from ww  w. j  ava2  s  . c o m
                public void onResponse(JSONObject response) {
                    if (dialog != null && dialog.isShowing()) {
                        dialog.dismiss();
                    }
                    Log.d("RemoteActivity", "doCommand" + response.toString());
                    for (PytoDevice dev : myDevices) {
                        View myView = remoteFrag.getView().findViewWithTag(curTag);
                        if (dev.getDevID().equalsIgnoreCase(curTag)) {
                            try {

                                String devState = response.getString("state");
                                dev.setDevState(devState);
                                if (devState.equalsIgnoreCase("on")) {
                                    myView.setBackgroundResource(R.drawable.light_bulb_on);
                                } else {
                                    if (devState.equalsIgnoreCase("off")) {
                                        myView.setBackgroundResource(R.drawable.light_bulb_off);
                                    } else {
                                        myView.setBackgroundResource(R.drawable.light_bulb_dimmed);
                                    }
                                }

                            } catch (JSONException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }
                    }
                    // pDialog.hide();
                }
            }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.d("RemoteActivity", "doCommand Error: " + error.getMessage());
                    // pDialog.hide();
                }
            }) {
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<String, String>();
            String authString = user + ":" + pass;
            String encodedPass = null;
            try {
                encodedPass = Base64.encodeToString(authString.getBytes(), Base64.DEFAULT);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            Log.d("Remote Activity", pass + " " + encodedPass);
            // headers.put("Content-Type", "application/json");
            headers.put("Authorization", "Basic " + encodedPass);
            return headers;
        }

        @Override
        public byte[] getBody() {
            // Map<String, String> params = new HashMap<String, String>();
            // params.put("command", "on");
            // params.put("email", "abc@androidhive.info");
            // params.put("password", "password123");
            String params = "command=" + curCommand;
            return params.getBytes();
        }

    };

    PyHomeController.getInstance().addToRequestQueue(req, commandTag);
}

From source file:com.jrummyapps.android.safetynet.SafetyNetHelper.java

private SafetyNetVerification verify(SafetyNetResponse response) {
    Boolean isValidSignature = null;
    if (!TextUtils.isEmpty(apiKey)) {
        try {//  w w w .  j  a v  a  2  s .  co m
            isValidSignature = validate(response.jws, apiKey);
        } catch (SafetyNetError e) {
            Log.d(TAG, "An error occurred while using the Android Device Verification API", e);
        }
    }

    String nonce = Base64.encodeToString(this.nonce, Base64.DEFAULT).trim();
    boolean isValidNonce = TextUtils.equals(nonce, response.nonce);

    long durationOfReq = response.timestampMs - requestTimestamp;
    boolean isValidResponseTime = durationOfReq < MAX_TIMESTAMP_DURATION;

    boolean isValidApkSignature = true;
    if (response.apkCertificateDigestSha256 != null && response.apkCertificateDigestSha256.length > 0) {
        isValidApkSignature = Arrays.equals(getApkCertificateDigests().toArray(),
                response.apkCertificateDigestSha256);
    }

    boolean isValidApkDigest = true;
    if (!TextUtils.isEmpty(response.apkDigestSha256)) {
        isValidApkDigest = TextUtils.equals(getApkDigestSha256(), response.apkDigestSha256);
    }

    return new SafetyNetVerification(isValidSignature, isValidNonce, isValidResponseTime, isValidApkSignature,
            isValidApkDigest);
}

From source file:mobisocial.bento.ebento.io.EventManager.java

synchronized public void updateEvent(Event event, String msg, boolean bFirst) {
    mEvent = event;/*  w  w w  .jav a  2  s .  c  o m*/

    String uuid = null;
    String data = null;
    if (mEvent.image != null) {
        uuid = mEvent.uuid;
        data = Base64.encodeToString(BitmapHelper.bitmapToBytes(mEvent.image), Base64.DEFAULT);
    }
    pushUpdate(msg, uuid, data, bFirst);
}

From source file:com.theonespy.util.Util.java

public static String encodeToBase64(Bitmap image) {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    image.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
    byte[] b = outputStream.toByteArray();
    return Base64.encodeToString(b, Base64.DEFAULT);
}

From source file:com.ledger.android.u2f.bridge.MainActivity.java

private String createClientData(U2FContext context) {
    try {// www . j a va 2  s  .c o m
        JSONObject clientData = new JSONObject();
        clientData.put(TAG_JSON_TYP, (context.isSign() ? SIGN_RESPONSE_TYP : REGISTER_RESPONSE_TYP));
        clientData.put(TAG_JSON_CHALLENGE, Base64.encodeToString(context.getChallenge(),
                Base64.URL_SAFE | Base64.NO_WRAP | Base64.NO_PADDING));
        clientData.put(TAG_JSON_ORIGIN, context.getAppId());
        clientData.put(TAG_JSON_CID_PUBKEY, CID_UNAVAILABLE);
        return clientData.toString();
    } catch (Exception e) {
        Log.e(TAG, "Error encoding client data");
        return null;
    }
}