Example usage for android.util Base64 NO_WRAP

List of usage examples for android.util Base64 NO_WRAP

Introduction

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

Prototype

int NO_WRAP

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

Click Source Link

Document

Encoder flag bit to omit all line terminators (i.e., the output will be on one long line).

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//ww  w . ja  va  2  s. c  o  m
            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.example.socketmobile.android.warrantychecker.network.UserRegistration.java

private Object fetchWarranty(String id, String authString, String query) throws IOException {
    InputStream is = null;/*from w w  w  .j  av  a  2 s  .co  m*/
    RegistrationApiResponse result = null;
    RegistrationApiErrorResponse errorResult = null;
    String authHeader = "Basic " + Base64.encodeToString(authString.getBytes(), Base64.NO_WRAP);

    try {
        URL url = new URL(baseUrl + id + "/registrations");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(10000 /* milliseconds */);
        conn.setConnectTimeout(10000 /* milliseconds */);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Accept", "application/json");
        conn.setRequestProperty("Authorization", authHeader);
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setDoInput(true);
        conn.setDoOutput(true);

        OutputStream os = conn.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
        writer.write(query);
        writer.flush();
        writer.close();
        os.close();

        conn.connect();
        int response = conn.getResponseCode();

        Log.d(TAG, "Warranty query responded: " + response);
        switch (response / 100) {
        case 2:
            is = conn.getInputStream();
            RegistrationApiResponse.Reader reader = new RegistrationApiResponse.Reader();
            result = reader.readJsonStream(is);
            break;
        case 4:
        case 5:
            is = conn.getErrorStream();

            RegistrationApiErrorResponse.Reader errorReader = new RegistrationApiErrorResponse.Reader();
            errorResult = errorReader.readErrorJsonStream(is);

            break;
        }

    } catch (IOException e) {
        e.printStackTrace();
        return null;
    } finally {
        if (is != null) {
            is.close();
        }
    }
    return (result != null) ? result : errorResult;
}

From source file:no.digipost.android.authentication.OAuth.java

private static String getB64Auth() {
    String source = Secret.CLIENT_ID + ":" + Secret.CLIENT_SECRET;
    return ApiConstants.BASIC + Base64.encodeToString(source.getBytes(), Base64.URL_SAFE | Base64.NO_WRAP);
}

From source file:com.facebook.stetho.websocket.WebSocketHandler.java

private static String generateServerKey(String clientKey) {
    try {//  w  ww  . j a va 2 s .  c o m
        String serverKey = clientKey + SERVER_KEY_GUID;
        MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
        sha1.update(Utf8Charset.encodeUTF8(serverKey));
        return Base64.encodeToString(sha1.digest(), Base64.NO_WRAP);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
}

From source file:io.teak.sdk.Request.java

@Override
public void run() {
    HttpsURLConnection connection = null;
    SecretKeySpec keySpec = new SecretKeySpec(this.session.appConfiguration.apiKey.getBytes(), "HmacSHA256");
    String requestBody;//from  www. j a  v  a  2s.  c o m

    String hostnameForEndpoint = this.hostname;
    if (hostnameForEndpoint == null) {
        hostnameForEndpoint = this.session.remoteConfiguration.getHostnameForEndpoint(this.endpoint);
    }

    try {
        ArrayList<String> payloadKeys = new ArrayList<>(this.payload.keySet());
        Collections.sort(payloadKeys);

        StringBuilder builder = new StringBuilder();
        for (String key : payloadKeys) {
            Object value = this.payload.get(key);
            if (value != null) {
                String valueString;
                if (value instanceof Map) {
                    valueString = new JSONObject((Map) value).toString();
                } else if (value instanceof Array) {
                    valueString = new JSONArray(Collections.singletonList(value)).toString();
                } else if (value instanceof Collection) {
                    valueString = new JSONArray((Collection) value).toString();
                } else {
                    valueString = value.toString();
                }
                builder.append(key).append("=").append(valueString).append("&");
            } else {
                Log.e(LOG_TAG, "Value for key: " + key + " is null.");
            }
        }
        builder.deleteCharAt(builder.length() - 1);

        String stringToSign = "POST\n" + hostnameForEndpoint + "\n" + this.endpoint + "\n" + builder.toString();
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(keySpec);
        byte[] result = mac.doFinal(stringToSign.getBytes());

        builder = new StringBuilder();
        for (String key : payloadKeys) {
            Object value = this.payload.get(key);
            String valueString;
            if (value instanceof Map) {
                valueString = new JSONObject((Map) value).toString();
            } else if (value instanceof Array) {
                valueString = new JSONArray(Collections.singletonList(value)).toString();
            } else if (value instanceof Collection) {
                valueString = new JSONArray((Collection) value).toString();
            } else {
                valueString = value.toString();
            }
            builder.append(key).append("=").append(URLEncoder.encode(valueString, "UTF-8")).append("&");
        }
        builder.append("sig=")
                .append(URLEncoder.encode(Base64.encodeToString(result, Base64.NO_WRAP), "UTF-8"));

        requestBody = builder.toString();
    } catch (Exception e) {
        Log.e(LOG_TAG, "Error signing payload: " + Log.getStackTraceString(e));
        return;
    }

    try {
        if (Teak.isDebug) {
            Log.d(LOG_TAG, "Submitting request to '" + this.endpoint + "': "
                    + new JSONObject(this.payload).toString(2));
        }

        URL url = new URL("https://" + hostnameForEndpoint + this.endpoint);
        connection = (HttpsURLConnection) url.openConnection();

        connection.setRequestProperty("Accept-Charset", "UTF-8");
        connection.setUseCaches(false);
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("Content-Length", "" + Integer.toString(requestBody.getBytes().length));

        // Send request
        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.writeBytes(requestBody);
        wr.flush();
        wr.close();

        // Get Response
        InputStream is;
        if (connection.getResponseCode() < 400) {
            is = connection.getInputStream();
        } else {
            is = connection.getErrorStream();
        }
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        StringBuilder response = new StringBuilder();
        while ((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\r');
        }
        rd.close();

        if (Teak.isDebug) {
            String responseText = response.toString();
            try {
                responseText = new JSONObject(response.toString()).toString(2);
            } catch (Exception ignored) {
            }
            Log.d(LOG_TAG, "Reply from '" + this.endpoint + "': " + responseText);
        }

        // For extending classes
        done(connection.getResponseCode(), response.toString());
    } catch (Exception e) {
        Log.e(LOG_TAG, Log.getStackTraceString(e));
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:com.jefftharris.passwdsafe.SavedPasswordsMgr.java

/**
 * Load a saved password for a file//w w  w  . j  av a2s .  c om
 */
public String loadSavedPassword(Uri fileUri, Cipher cipher)
        throws IOException, BadPaddingException, IllegalBlockSizeException {
    String keyName = getPrefsKey(fileUri);
    SharedPreferences prefs = getPrefs();
    String encStr = prefs.getString(keyName, null);
    if (TextUtils.isEmpty(encStr)) {
        throw new IOException(itsContext.getString(R.string.password_not_found, fileUri));
    }

    byte[] enc = Base64.decode(encStr, Base64.NO_WRAP);
    byte[] decPassword = cipher.doFinal(enc);
    return new String(decPassword, "UTF-8");
}

From source file:com.fabernovel.alertevoirie.webservice.AVService.java

/**
 * Post the image related to the incident, with httpPost method. The comment has to be encoded in base64
 * /*  w  w w  .  j  a v a 2 s .  c o m*/
 * @param udid
 *            The device id
 * @param img_comment
 *            The far image comment
 * @param incident_id
 *            The id of the related incident
 * @param image_far
 *            The file containing far image
 * @param image_near
 *            The file containing close image
 */
@SuppressWarnings("unchecked")
public void postImage(RequestListener listener, String udid, String img_comment, String incident_id,
        File image_far, File image_near, boolean newIncident) {
    this.listener = listener;

    ArrayList<Object> image_1 = new ArrayList<Object>();
    ArrayList<Object> image_2 = new ArrayList<Object>();

    if (image_far != null) {
        image_1.add(AV_URL + "photo/");
        image_1.add(udid);
        try {
            image_1.add(Base64.encodeToString(img_comment.getBytes("UTF-8"), Base64.NO_WRAP));// .replace("=", "%3D"));
        } catch (UnsupportedEncodingException e) {
            Log.e(Constants.PROJECT_TAG, "UTF-8 not supported", e);
            image_1.add(Base64.encodeToString(img_comment.getBytes(), Base64.NO_WRAP));// .replace("=", "%3D"));
        }
        image_1.add(incident_id);
        image_1.add(AV_IMG_FAR);
        image_1.add(image_far);
        image_1.add(newIncident);
    }

    if (image_near != null) {
        image_2.add(AV_URL + "photo/");
        image_2.add(udid);
        image_2.add("");
        image_2.add(incident_id);
        image_2.add(AV_IMG_CLOSE);
        image_2.add(image_near);
        image_2.add(newIncident);
    }

    cancelTask();

    currentTask = new postImage().execute(image_1.size() > 0 ? image_1 : null,
            image_2.size() > 0 ? image_2 : null);
    // if (image_far != null) {
    // currentTask = new postImage().execute(image_1, image_2);
    // } else {
    // currentTask = new postImage().execute(image_2);
    // }

}

From source file:fr.unix_experience.owncloud_sms.engine.OCHttpClient.java

public int execute(HttpMethod req) throws IOException {
    String basicAuth = "Basic "
            + Base64.encodeToString((_username + ":" + _password).getBytes(), Base64.NO_WRAP);
    req.setDoAuthentication(true);/*  www . j  ava2s.co m*/
    req.addRequestHeader("Authorization", basicAuth);
    executeMethod(req);
    return followRedirections(req);
}