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.appfirst.communication.AFClient.java

/**
 * @param post//w ww.j a va2 s .c o  m
 *            the HttpPost request.
 * @param postContent
 *            the post content.
 * @return a JSONObject for the result
 */
private JSONObject makeHttpPostRequest(HttpPost post, List<NameValuePair> postContent) {
    JSONObject jsonObject = null;
    this.mEncodedAuthString = String.format("Basic %s",
            Base64.encodeToString(this.mAuthString, Base64.DEFAULT).trim());
    post.setHeader(this.mAuthName, this.mEncodedAuthString);

    try {
        post.setEntity(new UrlEncodedFormEntity(postContent));
    } catch (Exception e) {
        return jsonObject;
    }

    try {
        HttpResponse response = this.mClient.execute(post);
        if (Helper.checkStatus(response)) {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream instream = entity.getContent();
                String result = Helper.convertStreamToString(instream);
                jsonObject = new JSONObject(result);
                instream.close();
            }
        } else {
            android.util.Log.e(TAG, String.format("Request failed with :%s", response.getStatusLine()));
            return jsonObject;
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return jsonObject;
}

From source file:ch.ethz.twimight.net.opportunistic.ScanningService.java

private String getProcessedImage(String photoFileUri) {
    Bitmap bitmap = ImageLoader.getInstance().loadImageSync(photoFileUri);
    String encodedImage = null;//from   w  w  w. j  a  v a2s .c  o  m
    if (bitmap != null) {
        // scale down large images
        if (bitmap.getHeight() > MAX_IMAGE_DIMENSIONS_PX || bitmap.getWidth() > MAX_IMAGE_DIMENSIONS_PX) {
            double shrinkFactor = ((double) MAX_IMAGE_DIMENSIONS_PX)
                    / Math.max(bitmap.getWidth(), bitmap.getHeight());
            bitmap = Bitmap.createScaledBitmap(bitmap, (int) (bitmap.getWidth() * shrinkFactor),
                    (int) (bitmap.getHeight() * shrinkFactor), false);
        }
        ByteArrayOutputStream byteArrayBitmapStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayBitmapStream);
        byte[] bytes = byteArrayBitmapStream.toByteArray();
        encodedImage = Base64.encodeToString(bytes, Base64.DEFAULT);
    }
    return encodedImage;
}

From source file:com.farmerbb.notepad.activity.MainActivity.java

@SuppressLint("SetJavaScriptEnabled")
@TargetApi(Build.VERSION_CODES.KITKAT)/*from  ww  w  .  j a v  a  2s.c o m*/
public void printNote(String contentToPrint) {
    SharedPreferences pref = getSharedPreferences(getPackageName() + "_preferences", MODE_PRIVATE);

    // Create a WebView object specifically for printing
    boolean generateHtml = !(pref.getBoolean("markdown", false)
            && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP);
    WebView webView = generateHtml ? new WebView(this) : new MarkdownView(this);

    // Apply theme
    String theme = pref.getString("theme", "light-sans");
    int textSize = -1;

    String fontFamily = null;

    if (theme.contains("sans")) {
        fontFamily = "sans-serif";
    }

    if (theme.contains("serif")) {
        fontFamily = "serif";
    }

    if (theme.contains("monospace")) {
        fontFamily = "monospace";
    }

    switch (pref.getString("font_size", "normal")) {
    case "smallest":
        textSize = 12;
        break;
    case "small":
        textSize = 14;
        break;
    case "normal":
        textSize = 16;
        break;
    case "large":
        textSize = 18;
        break;
    case "largest":
        textSize = 20;
        break;
    }

    String topBottom = " " + Float.toString(getResources().getDimension(R.dimen.padding_top_bottom_print)
            / getResources().getDisplayMetrics().density) + "px";
    String leftRight = " " + Float.toString(getResources().getDimension(R.dimen.padding_left_right_print)
            / getResources().getDisplayMetrics().density) + "px";
    String fontSize = " " + Integer.toString(textSize) + "px";

    String css = "body { " + "margin:" + topBottom + topBottom + leftRight + leftRight + "; " + "font-family:"
            + fontFamily + "; " + "font-size:" + fontSize + "; " + "}";

    webView.getSettings().setJavaScriptEnabled(false);
    webView.getSettings().setLoadsImagesAutomatically(false);
    webView.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageFinished(final WebView view, String url) {
            createWebPrintJob(view);
        }
    });

    // Load content into WebView
    if (generateHtml) {
        webView.loadDataWithBaseURL(null,
                "<link rel='stylesheet' type='text/css' href='data:text/css;base64,"
                        + Base64.encodeToString(css.getBytes(), Base64.DEFAULT) + "' /><html><body><p>"
                        + StringUtils.replace(contentToPrint, "\n", "<br>") + "</p></body></html>",
                "text/HTML", "UTF-8", null);
    } else
        ((MarkdownView) webView).loadMarkdown(contentToPrint,
                "data:text/css;base64," + Base64.encodeToString(css.getBytes(), Base64.DEFAULT));
}

From source file:uk.bowdlerize.API.java

@Deprecated
private String SignHeaders(String dataToSign, boolean isUser) throws NoSuchAlgorithmException,
        InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException,
        BadPaddingException, UnsupportedEncodingException, NoSuchProviderException, SignatureException {
    PKCS8EncodedKeySpec spec;/*from  ww  w  .  j  a  v  a2s.co  m*/
    if (isUser) {
        spec = new PKCS8EncodedKeySpec(
                Base64.decode(settings.getString(SETTINGS_USER_PRIVATE_KEY, "").getBytes(), 0));
    } else {
        spec = new PKCS8EncodedKeySpec(
                Base64.decode(settings.getString(SETTINGS_PROBE_PRIVATE_KEY, "").getBytes(), 0));
    }

    KeyFactory kf = KeyFactory.getInstance("RSA", "BC");
    PrivateKey pk = kf.generatePrivate(spec);
    byte[] signed = null;

    //Log.e("algorithm", pk.getAlgorithm());

    Signature instance = Signature.getInstance("SHA1withRSA");
    instance.initSign(pk);
    instance.update(dataToSign.getBytes());
    signed = instance.sign();

    Log.e("privateKey", settings.getString(SETTINGS_USER_PRIVATE_KEY, ""));
    Log.e("privateKey", settings.getString(SETTINGS_PROBE_PRIVATE_KEY, ""));
    //Log.e("Signature",Base64.encodeToString(signed, Base64.NO_WRAP));

    return Base64.encodeToString(signed, Base64.NO_WRAP);
}

From source file:uk.ac.horizon.ubihelper.service.PeerManager.java

private synchronized void sendPeerRequest(PeerRequestInfo pi) {

    // create peer request
    JSONObject msg = new JSONObject();
    try {/*from   www  .  j a va 2  s . c  o m*/
        msg.put(MessageUtils.KEY_TYPE, MessageUtils.MSG_INIT_PEER_REQ);
        // pass key
        byte pbuf[] = new byte[4];
        protocol.getRandom(pbuf);
        StringBuilder pb = new StringBuilder();
        for (int i = 0; i < pbuf.length; i++)
            pb.append((char) ('0' + ((pbuf[i] & 0xff) % 10)));
        pi.pin = pb.toString();
        // pin nonce and digest
        byte nbuf[] = new byte[8];
        protocol.getRandom(nbuf);
        pi.pinnonce = Base64.encodeToString(nbuf, Base64.DEFAULT);
        messageDigest.reset();
        messageDigest.update(nbuf);
        messageDigest.update(pi.pin.getBytes("UTF-8"));
        byte dbuf[] = messageDigest.digest();
        pi.pindigest = Base64.encodeToString(dbuf, Base64.DEFAULT);
        msg.put(MessageUtils.KEY_PINDIGEST, pi.pindigest);

        msg.put(MessageUtils.KEY_ID, getDeviceId());
        msg.put(MessageUtils.KEY_NAME, service.getDeviceName());
        msg.put(MessageUtils.KEY_PORT, this.serverPort);
        Message m = new Message(Message.Type.MANAGEMENT, null, null, msg.toString());
        pi.pc.sendMessage(m);

        pi.state = PeerRequestState.STATE_PEER_REQ;
        pi.detail = "Pin is " + pi.pin;
        broadcastPeerState(pi);
    } catch (JSONException e) {
        // shouldn't happen!
        Log.e(TAG, "JSON error (shoulnd't be): " + e);
    } catch (UnsupportedEncodingException e) {
        // shouldn't happen!
        Log.e(TAG, "Unsupported encoding (shoulnd't be): " + e);
    }
}

From source file:ch.ethz.twimight.net.opportunistic.ScanningService.java

private JSONObject getJSONFromXml(File xml) {
    try {/*from   ww w .  j  a  v a 2  s  . c o m*/

        JSONObject jsonObj = new JSONObject();
        FileInputStream xmlStream = null;
        try {
            xmlStream = new FileInputStream(xml);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024];
            int length;
            while ((length = xmlStream.read(buffer)) != -1) {
                bos.write(buffer, 0, length);
            }
            byte[] b = bos.toByteArray();
            String xmlString = Base64.encodeToString(b, Base64.DEFAULT);
            jsonObj.put(HtmlPage.COL_HTML, xmlString);

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (xmlStream != null) {
                try {
                    xmlStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        jsonObj.put(TYPE, MESSAGE_TYPE_HTML);
        return jsonObj;
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        Log.d(TAG, "exception:" + e.getMessage());
        return null;
    }
}

From source file:ch.bfh.evoting.alljoyn.BusHandler.java

/**
 * Helper method send my identity to the other peers
 *//*  w w w  . ja  v a2  s  . co m*/
private void sendMyIdentity() {
    Log.d(TAG, "Sending my identity");

    String myName = userDetails.getString("identification", "");

    //save my own identity in identityMap
    Identity myIdentity = new Identity(myName, messageAuthenticater.getMyPublicKey());
    identityMap.put(this.getIdentification(), myIdentity);

    byte[] publicKeyBytes = messageAuthenticater.getMyPublicKey().getEncoded();
    if (publicKeyBytes == null) {
        Log.e(TAG, "Key encoding not supported");
    }
    String myKey = Base64.encodeToString(publicKeyBytes, Base64.DEFAULT);
    String identity = myName + MESSAGE_PARTS_SEPARATOR + myKey;
    Log.d(TAG, "Send my identity");

    //send my identity
    Message msg = obtainMessage(BusHandler.PING);
    Bundle data = new Bundle();
    data.putString("groupName", lastJoinedNetwork);
    data.putString("pingString", identity);
    data.putSerializable("type", Type.IDENTITY);
    msg.setData(data);
    sendMessage(msg);
}

From source file:com.imaginamos.taxisya.taxista.activities.RegisterDriverActivity.java

public static String convertImageToStringForServer(Bitmap imageBitmap) {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    if (imageBitmap != null) {
        imageBitmap.compress(Bitmap.CompressFormat.JPEG, 15, stream);
        byte[] byteArray = stream.toByteArray();
        return Base64.encodeToString(byteArray, Base64.DEFAULT);
    } else {/*from w w w  . j  av  a 2  s  . com*/
        return null;
    }
}

From source file:com.imaginamos.taxisya.taxista.activities.RegisterDriverActivity.java

public static String encodeTobase64(Bitmap image) {
    Bitmap immage = image;//w w w . ja va  2s.co m
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    immage.compress(Bitmap.CompressFormat.PNG, 100, baos);
    byte[] b = baos.toByteArray();
    String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);

    Log.d("Image Log:", imageEncoded);
    return imageEncoded;

}