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.liferay.mobile.android.util.PortraitUtil.java

protected static void appendToken(StringBuilder sb, String uuid) {
    if (Validator.isNull(uuid)) {
        return;//  w w w  .j a v  a 2 s.co m
    }

    try {
        MessageDigest digest = MessageDigest.getInstance("SHA-1");
        digest.update(uuid.getBytes());

        byte[] bytes = digest.digest();
        String token = null;

        try {
            token = Base64.encodeToString(bytes, Base64.NO_WRAP);
        } catch (RuntimeException re) {
            if ("Stub!".equals(re.getMessage())) {
                token = org.apache.commons.codec.binary.Base64.encodeBase64String(bytes);
            }
        }

        if (token != null) {
            sb.append("&img_id_token=");
            sb.append(URLEncoder.encode(token, "UTF8"));
        }
    } catch (Exception e) {
        Log.e(_CLASS_NAME, "Couldn't generate portrait image token", e);
    }
}

From source file:de.skubware.opentraining.db.rest.ExerciseImageGSONSerializer.java

@Override
public JsonElement serialize(ExerciseImage ex, Type typeOfSrc, JsonSerializationContext context) {

    JsonObject mainObject = new JsonObject();

    FileInputStream fis = null;//from w w  w. j a  v  a  2 s  .c o m
    String imgString = null;

    try {
        fis = new FileInputStream(ex.getRealImagePath());
    } catch (FileNotFoundException e) {
        Log.i(TAG, "File not found: " + ex.getRealImagePath());
        e.printStackTrace();
    }

    Bitmap bm = BitmapFactory.decodeStream(fis);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bm.compress(CompressFormat.JPEG, 100, baos);
    byte[] imgByte = baos.toByteArray();
    imgString = Base64.encodeToString(imgByte, Base64.DEFAULT);

    Log.i("Minion", "imgString -> JSONObject SUCCESS");
    mainObject.addProperty("image", imgString);

    mainObject.addProperty("license", 3);
    mainObject.addProperty("exercise", 260);

    return mainObject;

}

From source file:br.com.hotforms.FacebookHash.java

/**
 * Executes the request and returns PluginResult.
 *
 * @param action            The action to execute.
 * @param args              JSONArry of arguments for the plugin.
 * @param callbackContext   The callback id used when calling back into JavaScript.
 * @return                  True if the action was valid, false otherwise.
 *//*  ww w  .java 2 s.c o  m*/
@Override
public boolean execute(String action, CordovaArgs args, final CallbackContext callbackContext)
        throws JSONException {
    Log.v(TAG, "Executing action: " + action);
    final Activity activity = this.cordova.getActivity();
    final Window window = activity.getWindow();

    if ("getHash".equals(action)) {
        try {
            String packageName = activity.getClass().getPackage().getName();
            PackageManager packageManager = activity.getPackageManager();
            PackageInfo info = packageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
            for (Signature signature : info.signatures) {
                MessageDigest md = MessageDigest.getInstance("SHA");
                md.update(signature.toByteArray());
                String hash = Base64.encodeToString(md.digest(), Base64.DEFAULT);

                String result = String.format("{ FacebookHash : \"%s\", PackageName : \"%s\"}", hash.trim(),
                        packageName);
                callbackContext.success(result);
            }
        } catch (NameNotFoundException e) {
            callbackContext.error(e.getMessage());
        } catch (NoSuchAlgorithmException e) {
            callbackContext.error(e.getMessage());
        }
        return true;
    }

    return false;
}

From source file:edu.stanford.mobisocial.dungbeetle.feed.objects.VoiceObj.java

public JSONObject mergeRaw(JSONObject objData, byte[] raw) {
    try {//from   w  w  w.  j  a  va2 s  . co m
        if (raw != null)
            objData = objData.put(DATA, Base64.encodeToString(raw, Base64.DEFAULT));
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return objData;
}

From source file:com.amazonaws.mobileconnectors.kinesis.kinesisrecorder.JSONRecordAdapter.java

/**
 * @param source the PutRecordRequest to that will be stored
 * @return JSONObject the json representation of the request
 *///from   w  w w. j  a  va  2s .  c  o  m
public JSONObject translateFromRecord(PutRecordRequest source) {
    if (null == source) {
        LOGGER.warn("The Record provided was null");
        return null;
    }
    if (source.getData() == null || source.getPartitionKey() == null || source.getPartitionKey().isEmpty()
            || source.getStreamName() == null || source.getStreamName().isEmpty()) {
        throw new AmazonClientException("RecordRequests must specify a partition key, stream name, and data");
    }
    if (!source.getData().hasArray()) {
        throw new AmazonClientException("ByteBuffer must be based on array for proper storage");
    }
    final JSONObject recordJson = new JSONObject();
    try {
        recordJson.put(DATA_FIELD_KEY, Base64.encodeToString(source.getData().array(), Base64.DEFAULT));
        recordJson.put(STREAM_NAME_FIELD, source.getStreamName());
        recordJson.put(PARTITION_KEY_FIELD, source.getPartitionKey());
        recordJson.putOpt(EXPLICIT_HASH_FIELD, source.getExplicitHashKey());
        recordJson.putOpt(SEQUENCE_NUMBER_FIELD, source.getSequenceNumberForOrdering());
    } catch (final JSONException e) {
        throw new AmazonClientException("Unable to convert KinesisRecord to JSON " + e.getMessage());
    }

    return recordJson;
}

From source file:com.distimo.sdk.Utils.java

@SuppressLint({ "NewApi", "InlinedApi" })
static String base64Encode(byte[] data) {
    String result = null;//from w  w w.  j a v a2 s . c  om

    if (Build.VERSION.SDK_INT < 8) { //Build.VERSION.FROYO
        try {
            result = OldBase64.encodeBytes(data, OldBase64.URL_SAFE).replace("=", "");
        } catch (final IOException ioe) {
            if (Utils.DEBUG) {
                ioe.printStackTrace();
            }
        }
    } else {
        result = Base64.encodeToString(data, Base64.NO_PADDING | Base64.URL_SAFE | Base64.NO_WRAP);
    }

    return result;
}

From source file:com.idean.atthack.network.RequestHelper.java

public Result login(Bundle params) {
    String username = params.getString(Param.username.name());
    String vin = params.getString(Param.vin.name());
    String pin = params.getString(Param.pin.name());
    if (username == null || vin == null || pin == null) {
        return new Result(400);
    }/* w w w .ja v a  2s  .c  o  m*/

    HttpURLConnection conn = null;
    try {
        URL url = new URL(getUrlBase() + "remoteservices/v1/vehicle/login/" + vin);

        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod(HttpVerb.POST.name());
        String auth = username + ":" + pin;
        String encoded = Base64.encodeToString(auth.getBytes(), Base64.DEFAULT);
        conn.setRequestProperty("Authorization", "Basic " + encoded);

        conn.connect();
        // Closes input stream afterwards
        String body = readStream(conn.getInputStream());
        return new Result(conn.getResponseCode(), body);

    } catch (IOException e) {
        Log.w(TAG, "Unable to login " + e.getMessage(), e);
        return new Result("Unable to login: " + e.getMessage());
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}

From source file:com.wms.opensource.shopfast.task.LoadProductsInCollectionTask.java

protected Void doInBackground(Integer... params) { // params[0] is the collection ID
    collectionID = params[0];/*  www. ja v a  2 s  . c  o m*/

    /** Directly use HTTPClient to load products */
    String urlString = "https://" + context.getString(R.string.ShopifyShopName)
            + ".myshopify.com/admin/products.json?collection_id=" + collectionID + "&page=" + page + "&limit="
            + Constants.PRODUCTS_PER_PAGE;
    HttpClient client = new DefaultHttpClient();
    HttpGet get = new HttpGet(urlString);
    try {
        String authentication = context.getString(R.string.ShopifyAPIKey) + ":"
                + context.getString(R.string.ShopifyPassword);
        byte[] byteArray = authentication.getBytes("UTF-8");
        String base64 = Base64.encodeToString(byteArray, Base64.NO_WRAP);
        get.setHeader("Authorization", "Basic " + base64);
        get.setHeader("User-Agent", "Mozilla/5.0 ( compatible ) ");
        get.setHeader("Accept", "*/*");
        HttpResponse resp = client.execute(get);
        if (resp.getStatusLine().getStatusCode() == 200) {
            HttpEntity entity = resp.getEntity();
            if (entity != null) {
                String jsonString = EntityUtils.toString(entity);
                JSONObject productsObject = new JSONObject(jsonString);
                productsArrayString = productsObject.getString("products");
                products = JSONProcessor.getProductsFromJSONArrayString(productsArrayString);
            }
        } else {
            errorString = "Error: " + resp.getStatusLine();
        }
    } catch (ClientProtocolException e) {
        errorString = context.getString(R.string.retryOnError);
    } catch (IOException e) {
        errorString = context.getString(R.string.retryOnError);
    } catch (JSONException e) {
        errorString = context.getString(R.string.retryOnError);
    }
    return null;
}

From source file:com.letsgood.synergykitsdkandroid.requestmethods.Delete.java

@Override
public BufferedReader execute() {
    String uri = null;//  w  w w. ja  v  a  2  s.c om

    //init check
    if (!Synergykit.isInit()) {

        SynergykitLog.print(Errors.MSG_SK_NOT_INITIALIZED);
        statusCode = Errors.SC_SK_NOT_INITIALIZED;
        return null;
    }

    //URI check
    uri = getUri().toString();

    if (uri == null) {
        statusCode = Errors.SC_URI_NOT_VALID;
        return null;
    }

    //session token check
    if (sessionTokenRequired && sessionToken == null) {
        statusCode = Errors.SC_NO_SESSION_TOKEN;
        return null;
    }

    try {
        url = new URL(uri); // init url

        httpURLConnection = (HttpURLConnection) url.openConnection(); //open connection
        httpURLConnection.setConnectTimeout(CONNECT_TIMEOUT); //set connect timeout
        httpURLConnection.setReadTimeout(READ_TIMEOUT); //set read timeout
        httpURLConnection.setRequestMethod(REQUEST_METHOD); //set method
        httpURLConnection.addRequestProperty(PROPERTY_USER_AGENT, PROPERTY_USER_AGENT_VALUE); //set property
        httpURLConnection.addRequestProperty(PROPERTY_CONTENT_TYPE, ACCEPT_APPLICATION_VALUE);
        httpURLConnection.addRequestProperty(PROPERTY_AUTHORIZATION,
                "Basic " + Base64.encodeToString(
                        (Synergykit.getTenant() + ":" + Synergykit.getApplicationKey()).getBytes(),
                        Base64.NO_WRAP)); //set authorization

        if (Synergykit.getSessionToken() != null)
            httpURLConnection.addRequestProperty(PROPERTY_SESSION_TOKEN, Synergykit.getSessionToken());

        statusCode = httpURLConnection.getResponseCode(); //get status code

        //read stream
        if (statusCode >= HttpURLConnection.HTTP_OK && statusCode < HttpURLConnection.HTTP_MULT_CHOICE) {
            return null;
        } else {
            return readStream(httpURLConnection.getErrorStream());
        }

    } catch (Exception e) {
        statusCode = HttpStatus.SC_SERVICE_UNAVAILABLE;
        e.printStackTrace();
        return null;
    }

}

From source file:eu.codeplumbers.cosi.services.CosiNoteService.java

@Override
protected void onHandleIntent(Intent intent) {
    // Do the task here
    Log.i(CosiNoteService.class.getName(), "Cosi Service running");

    // Release the wake lock provided by the WakefulBroadcastReceiver.
    WakefulBroadcastReceiver.completeWakefulIntent(intent);

    Device device = Device.registeredDevice();

    // delete all local notes
    new Delete().from(Note.class).execute();

    // cozy register device url
    this.url = device.getUrl() + "/ds-api/request/note/cosiall/";

    // concatenate username and password with colon for authentication
    final String credentials = device.getLogin() + ":" + device.getPassword();
    authHeader = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);

    showNotification();//from w ww .  j  a v  a2 s .com

    if (isNetworkAvailable()) {
        try {
            URL urlO = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
            conn.setConnectTimeout(5000);
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            conn.setRequestProperty("Authorization", authHeader);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");

            // read the response
            int status = conn.getResponseCode();
            InputStream in = null;

            if (status >= HttpURLConnection.HTTP_BAD_REQUEST) {
                in = conn.getErrorStream();
            } else {
                in = conn.getInputStream();
            }

            StringWriter writer = new StringWriter();
            IOUtils.copy(in, writer, "UTF-8");
            String result = writer.toString();

            JSONArray jsonArray = new JSONArray(result);

            if (jsonArray != null) {
                for (int i = 0; i < jsonArray.length(); i++) {
                    String version = "0";
                    if (jsonArray.getJSONObject(i).has("version")) {
                        version = jsonArray.getJSONObject(i).getString("version");
                    }
                    JSONObject noteJson = jsonArray.getJSONObject(i).getJSONObject("value");
                    Note note = Note.getByRemoteId(noteJson.get("_id").toString());

                    if (note == null) {
                        note = new Note(noteJson);
                    } else {
                        boolean versionIncremented = note.getVersion() < Integer
                                .valueOf(noteJson.getString("version"));

                        int modifiedOnServer = DateUtils.compareDateStrings(
                                Long.valueOf(note.getLastModificationValueOf()),
                                noteJson.getLong("lastModificationValueOf"));

                        if (versionIncremented || modifiedOnServer == -1) {
                            note.setTitle(noteJson.getString("title"));
                            note.setContent(noteJson.getString("content"));
                            note.setCreationDate(noteJson.getString("creationDate"));
                            note.setLastModificationDate(noteJson.getString("lastModificationDate"));
                            note.setLastModificationValueOf(noteJson.getString("lastModificationValueOf"));
                            note.setParentId(noteJson.getString("parent_id"));
                            // TODO: 10/3/16
                            // handle note paths
                            note.setPath(noteJson.getString("path"));
                            note.setVersion(Integer.valueOf(version));
                        }

                    }

                    mBuilder.setProgress(jsonArray.length(), i, false);
                    mBuilder.setContentText("Getting note : " + note.getTitle());
                    mNotifyManager.notify(notification_id, mBuilder.build());

                    EventBus.getDefault()
                            .post(new NoteSyncEvent(SYNC_MESSAGE, "Getting note : " + note.getTitle()));
                    note.save();
                }
            } else {
                EventBus.getDefault().post(new NoteSyncEvent(SERVICE_ERROR, "Failed to parse API response"));
            }

            in.close();
            conn.disconnect();

            mNotifyManager.cancel(notification_id);
            EventBus.getDefault().post(new NoteSyncEvent(REFRESH, "Sync OK"));
        } catch (MalformedURLException e) {
            EventBus.getDefault().post(new NoteSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            mNotifyManager.notify(notification_id, mBuilder.build());
            stopSelf();
        } catch (ProtocolException e) {
            EventBus.getDefault().post(new NoteSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            mNotifyManager.notify(notification_id, mBuilder.build());
            stopSelf();
        } catch (IOException e) {
            EventBus.getDefault().post(new NoteSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            mNotifyManager.notify(notification_id, mBuilder.build());
            stopSelf();
        } catch (JSONException e) {
            EventBus.getDefault().post(new NoteSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            mNotifyManager.notify(notification_id, mBuilder.build());
            stopSelf();
        }
    } else {
        mSyncRunning = false;
        EventBus.getDefault().post(new NoteSyncEvent(SERVICE_ERROR, "No Internet connection"));
        mBuilder.setContentText("Sync failed because no Internet connection was available");
        mNotifyManager.notify(notification_id, mBuilder.build());
    }
}