Example usage for android.util Base64 DEFAULT

List of usage examples for android.util Base64 DEFAULT

Introduction

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

Prototype

int DEFAULT

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

Click Source Link

Document

Default values for encoder/decoder flags.

Usage

From source file:com.appfirst.communication.AFClient.java

/**
 * Make a get request and return a JSONArray.
 * //from w w w  . jav  a2 s .  c  o m
 * @param getRequest
 *            a HTTPGet request.
 * @return JSONArray, null if error occurs.
 */
private JSONArray makeJsonArrayRequest(HttpGet getRequest) {
    JSONArray jsonArray = null;
    this.mEncodedAuthString = String.format("Basic %s",
            Base64.encodeToString(this.mAuthString, Base64.DEFAULT).trim());
    getRequest.setHeader(this.mAuthName, this.mEncodedAuthString);
    try {
        HttpResponse response = this.mClient.execute(getRequest);
        if (!Helper.checkStatus(response)) {
            android.util.Log.e(TAG, String.format("Request failed with :%s", response.getStatusLine()));
            return null;
        }
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream instream = entity.getContent();
            String result = Helper.convertStreamToString(instream);
            jsonArray = new JSONArray(result);
            instream.close();
        }
    } catch (ClientProtocolException cpe) {
        cpe.printStackTrace();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    } catch (JSONException je) {
        je.printStackTrace();
    }
    return jsonArray;
}

From source file:com.ved.musicmapapp.LoginAcitivity.java

private void getFaceAccInfo1(String userid) {
    if (!pd.isShowing())
        pd.show();/*from w  ww . j a  v  a 2 s . c o m*/
    String fqlQuery = "SELECT uid,first_name,last_name,name,email,birthday_date,current_location,"
            + "about_me,sex,religion,languages, music, movies, books,games,work,education, "
            + "favorite_athletes,inspirational_people,favorite_teams " + "FROM user WHERE uid='" + userid + "'";
    Bundle params = new Bundle();
    params.putString("q", fqlQuery);
    params.putString("access_token", ACCESS_TOKEN);
    Session session = Session.getActiveSession();
    Request request = new Request(session, "/fql", params, HttpMethod.GET, new Request.Callback() {
        public void onCompleted(Response response) {
            GraphObject graphObject = response.getGraphObject();
            JSONObject jsonObject = graphObject.getInnerJSONObject();

            try {
                JSONObject obj = jsonObject.getJSONArray("data").getJSONObject(0)
                        .getJSONObject("current_location");

                Toast.makeText(getApplicationContext(), "" + jsonObject.getJSONArray("data"), Toast.LENGTH_LONG)
                        .show();
                Log.i("json", jsonObject.getJSONArray("data") + "");

                edt.putString("LAST_LONGITUDE", obj.getString("longitude"));
                edt.putString("LAST_LATITUDE", obj.getString("latitude"));

                Log.i("JSON_DATA", jsonObject.toString());
                edt.commit();
            } catch (JSONException e) {
                e.printStackTrace();
            }

            //
            try {
                String data = Base64.encodeToString(jsonObject.toString().getBytes(), Base64.DEFAULT);
                edt.putString("FB_JSON", data);
                edt.commit();
            } catch (Exception e) {
                e.printStackTrace();
            }

            pd.dismiss();

            // Go to home page
            goToHome();
        }
    });
    Request.executeBatchAsync(request);
}

From source file:com.appfirst.communication.AFClient.java

/**
 * Make a get request and return a JSONObject;
 * /* w  w w  .jav  a 2s . com*/
 * @param jsonObject
 *            a HttpGet request.
 * @return JSONObject, null if error occurs.
 */
private JSONObject makeJsonObjectRequest(HttpGet getRequest) {
    JSONObject jsonObject = null;
    this.mEncodedAuthString = String.format("Basic %s",
            Base64.encodeToString(this.mAuthString, Base64.DEFAULT).trim());
    getRequest.setHeader(this.mAuthName, this.mEncodedAuthString);
    try {
        HttpResponse response = this.mClient.execute(getRequest);
        if (!Helper.checkStatus(response)) {
            android.util.Log.e(TAG, String.format("Request failed with :%s", response.getStatusLine()));
            return null;
        }
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream instream = entity.getContent();
            String result = Helper.convertStreamToString(instream);
            jsonObject = new JSONObject(result);
            instream.close();
        }
    } catch (ClientProtocolException cpe) {
        cpe.printStackTrace();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    } catch (JSONException je) {
        je.printStackTrace();
    }
    return jsonObject;
}

From source file:hochschuledarmstadt.photostream_tools.PhotoStreamClientImpl.java

private JSONObject createJsonObject(byte[] imageBytes, String comment) throws JSONException {
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("image", Base64.encodeToString(imageBytes, 0, imageBytes.length, Base64.DEFAULT));
    jsonObject.put("comment", comment);
    return jsonObject;
}

From source file:com.appfirst.communication.AFClient.java

/**
 * @param post//  ww w. ja va2  s. co 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.  jav  a2 s  .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 w  w  w .  j  ava  2 s.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.ac.horizon.ubihelper.service.PeerManager.java

private synchronized void sendPeerRequest(PeerRequestInfo pi) {

    // create peer request
    JSONObject msg = new JSONObject();
    try {/*w w  w .j  av  a2 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:eu.operando.operandoapp.database.DatabaseHelper.java

public void sendSettingsToServer(final String imei) {
    new Thread(new Runnable() {
        @Override//from  ww w .  j a v  a 2  s.  c  o  m
        public void run() {
            String xml_settings = exportAllPermissionsPerDomain();
            if (xml_settings != null) {
                try {
                    String urlParameters = "userxml=" + xml_settings + "&userID="
                            + Base64.encode(DigestUtils.sha1(imei), Base64.DEFAULT);
                    byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);
                    URL url = new URL(serverUrl + "/prefs");
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setReadTimeout(15000);
                    conn.setConnectTimeout(15000);
                    conn.setRequestMethod("POST");
                    conn.setDoInput(true);
                    conn.setDoOutput(true);
                    try (DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
                        wr.write(postData);
                    }
                    int responseCode = conn.getResponseCode();
                    if (responseCode == HttpURLConnection.HTTP_OK) {
                        //Do something on HTTP_OK ?????
                    } else {
                        throw new Exception();
                    }
                    Log.d("SENT", Integer.toString(responseCode));
                } catch (Exception e) {
                    //create a file as database to resend later
                    Writer writer = null;
                    try {
                        File file = new File(MainContext.INSTANCE.getContext().getFilesDir(), "resend.inf");
                        if (!file.exists()) {
                            writer = new BufferedWriter(new FileWriter(file));
                            writer.write("1"); //currently putting 1 for "true" to resend
                        }
                    } catch (Exception ex) {
                        ex.getMessage();
                    } finally {
                        try {
                            writer.close();
                        } catch (Exception ex) {
                            ex.getMessage();
                        }
                    }
                }
            }
        }
    }).start();
}

From source file:com.raceyourself.android.samsung.ProviderService.java

private void authorize() {
    UserDetail me = Helper.getUser();//from w  ww. ja  v  a2  s.c  o m
    if (me != null && me.getApiAccessToken() != null)
        return;

    AccountManager mAccountManager = AccountManager.get(this);
    List<Account> accounts = new ArrayList<Account>();
    accounts.addAll(Arrays.asList(mAccountManager.getAccountsByType("com.google")));
    accounts.addAll(Arrays.asList(mAccountManager.getAccountsByType("com.googlemail")));
    String email = null;
    for (Account account : accounts) {
        if (account.name != null && account.name.contains("@")) {
            email = account.name;
            break;
        }
    }
    // Potential fault: Can there be multiple accounts? Do we need to sort or provide a selector?

    // hash email so we don't send user's identity to server
    // can't guarantee uniqueness but want very low probability of collisions
    // using SHA-256 means we'd expect a collision on approx. our 1-millionth user
    // TODO: make this more unique before Samsung sell 1m Gear IIs.
    MessageDigest messageDigest;
    try {
        messageDigest = MessageDigest.getInstance("SHA-256");
        messageDigest.update(email.getBytes());
        String hash = new String(messageDigest.digest());
        hash = new String(Base64.encode(hash.getBytes(), Base64.DEFAULT)).replace("@", "_").replace("\n", "_"); //base64 encode and substitute @ symbols
        hash += "@hashed.raceyourself.com"; // make it look like an email so it passes server validation
        Helper.login(hash, SERVER_TOKEN);
    } catch (NoSuchAlgorithmException e) {
        Log.e(TAG, "Implementation of SHA-256 algorithm not found. Authorisation failed. Exiting.");
        throw new RuntimeException();
    }
}