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:se.leap.bitmaskclient.ProviderAPI.java

private String base64toHex(String base64_input) {
    byte[] byteArray = Base64.decode(base64_input, Base64.DEFAULT);
    int readBytes = byteArray.length;
    StringBuffer hexData = new StringBuffer();
    int onebyte;// www  . j  a va2  s .  c  om
    for (int i = 0; i < readBytes; i++) {
        onebyte = ((0x000000ff & byteArray[i]) | 0xffffff00);
        hexData.append(Integer.toHexString(onebyte).substring(6));
    }
    return hexData.toString();
}

From source file:com.chaosinmotion.securechat.messages.SCMessageQueue.java

/************************************************************************/

private void encodeMessages(byte[] cdata, final String sender, final int senderID,
        List<SCDeviceCache.Device> sarray, List<SCDeviceCache.Device> marray, final SenderCompletion callback)
        throws UnsupportedEncodingException {
    /*//from  ww  w .j av a2s .c  om
     *  Calculate message checksum
     */

    String checksum = SCSHA256.sha256(cdata);

    /*
     *  Build the encoding list to encode all sent messages.
     */

    JSONArray messages = new JSONArray();

    // Devices we're sending to
    for (SCDeviceCache.Device d : sarray) {
        SCRSAEncoder encoder = d.getPublicKey();
        byte[] encoded = new byte[0];
        try {
            encoded = encoder.encodeData(cdata);
            String message = Base64.encodeToString(encoded, Base64.DEFAULT);
            JSONObject ds = new JSONObject();
            ds.put("checksum", checksum);
            ds.put("message", message);
            ds.put("deviceid", d.getDeviceID());
            messages.put(ds);
        } catch (Exception e) {
            Log.d("SecureChat", "Exception", e);
            // Should not happen; only if there is a constant error above
        }
    }

    // My devices
    for (SCDeviceCache.Device d : marray) {
        if (d.getDeviceID().equals(SCRSAManager.shared().getDeviceUUID())) {
            // Skip me; we put me last
            continue;
        }

        SCRSAEncoder encoder = d.getPublicKey();
        byte[] encoded = new byte[0];
        try {
            encoded = encoder.encodeData(cdata);
            String message = Base64.encodeToString(encoded, Base64.DEFAULT);
            JSONObject ds = new JSONObject();
            ds.put("checksum", checksum);
            ds.put("message", message);
            ds.put("deviceid", d.getDeviceID());
            ds.put("destuser", senderID);
            messages.put(ds);
        } catch (Exception e) {
            Log.d("SecureChat", "Exception", e);
            // Should not happen; only if there is a constant error above
        }
    }

    // Encode for myself. This is kind of a kludge; we need
    // the message ID from the back end to assure proper sorting.
    // But we only get that if this is the last message in the
    // array of messages. (See SendMessages.java.)
    SCRSAEncoder encoder = new SCRSAEncoder(SCRSAManager.shared().getPublicKey());
    byte[] encoded = new byte[0];
    try {
        encoded = encoder.encodeData(cdata);
        String message = Base64.encodeToString(encoded, Base64.DEFAULT);
        JSONObject ds = new JSONObject();
        ds.put("checksum", checksum);
        ds.put("message", message);
        ds.put("deviceid", SCRSAManager.shared().getDeviceUUID());
        ds.put("destuser", senderID);
        messages.put(ds);
    } catch (Exception e) {
        Log.d("SecureChat", "Exception", e);
        // Should not happen; only if there is a constant error above
    }

    /*
     *  Send all messages to the back end.
     */

    JSONObject params = new JSONObject();
    try {
        params.put("messages", messages);
    } catch (JSONException ex) {
        // Should never happen
    }

    final byte[] encodedData = encoded;
    SCNetwork.get().request("messages/sendmessages", params, false, this, new SCNetwork.ResponseInterface() {
        @Override
        public void responseResult(SCNetwork.Response response) {
            if (response.isSuccess()) {
                int messageID = response.getData().optInt("messageid");

                // Insert sent message into myself. This is so we
                // immediately see the sent message right away.
                // Note we may have a race condition but we don't
                // care; the messageID will screen out duplicates.
                insertMessage(senderID, sender, true, messageID, new Date(), encodedData);
            }

            callback.senderCallback(response.isSuccess());
        }
    });
}

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

private void setBasicAuth(HttpURLConnection conn) {
    String auth = Pref.USERNAME.get(mContext) + ":" + Pref.PIN.get(mContext);
    String encoded = Base64.encodeToString(auth.getBytes(), Base64.DEFAULT);
    conn.setRequestProperty("Authorization", "Basic " + encoded);
    conn.setRequestProperty("APIKey", "random1234");
}

From source file:com.towson.wavyleaf.Sighting.java

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == EDIT_REQUEST && resultCode == RESULT_OK) {
        editedCoordinatesInOtherActivitySoDontGetGPSLocation = true;
        Location fixedLocation = data.getExtras().getParcelable("location");

        // Current marker is expired, remove that crap
        mMap.clear();//from ww w . j  ava 2 s  .  co  m
        mapHasMarker = !mapHasMarker;
        setUpMapIfNeeded();
        updateUILocation(fixedLocation);

        // Update location to be send with JSON sighting
        currentEditableLocation.setLatitude(fixedLocation.getLatitude());
        currentEditableLocation.setLongitude(fixedLocation.getLongitude());
        // Since user edited their coordinates, they obviously know it's right
        cb.setChecked(true);

        Toast.makeText(getApplicationContext(), "New position set", Toast.LENGTH_SHORT).show();
    }

    // http://stackoverflow.com/a/15432979/1097170
    else if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {

        // Set global string (_64bitencoding) immediately
        Bitmap bm = (Bitmap) data.getExtras().get("data");
        ib.setImageBitmap(bm);

        // Encode
        _64BitEncoding = Base64.encodeToString(encodeInBase64(bm), Base64.DEFAULT);

        //         Toast.makeText(getApplicationContext(), _64BitEncoding, Toast.LENGTH_SHORT).show();

    } //else if (requestCode == GALLERY_REQUEST && resultCode == RESULT_OK) {
    //         Uri selectedImage = data.getData();
    //         InputStream imageStream = null;
    //         
    //         try {
    //            imageStream = getContentResolver().openInputStream(selectedImage);
    //         } catch (FileNotFoundException e) {}
    //         
    //         Bitmap img = BitmapFactory.decodeStream(imageStream);
    //         ib.setImageBitmap(img);
}

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

/**
 * Make a HttpPut request and update the content.
 * /*from  w ww  .  j  a va2  s  .  c  o  m*/
 * @param request
 *            a HttpPut request contains the content to be updated.
 * @return the updated content in JSONObject format, null if query failed.
 */
private JSONObject makeJsonObjectPutRequest(HttpPut request) {
    JSONObject jsonObject = null;
    this.mEncodedAuthString = String.format("Basic %s",
            Base64.encodeToString(this.mAuthString, Base64.DEFAULT).trim());
    request.setHeader(this.mAuthName, this.mEncodedAuthString);
    try {
        HttpResponse response = this.mClient.execute(request);
        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:com.tenmiles.helpstack.gears.HSDeskGear.java

private void uploadAttachmentToServer(String cancelTag, String caseId, HSUploadAttachment attachmentObject,
        RequestQueue queue, Response.Listener<JSONObject> successListener, Response.ErrorListener errorListener)
        throws JSONException {

    Uri.Builder builder = new Uri.Builder();
    builder.encodedPath(instanceUrl);/*from  w ww .j a v  a 2 s  . com*/
    builder.appendEncodedPath(caseId.substring(1));
    builder.appendEncodedPath("attachments");

    String attachmentUrl = builder.build().toString();

    String attachmentFileName = attachmentObject.getAttachment().getFileName() == null ? "picture"
            : attachmentObject.getAttachment().getFileName();
    String attachmentMimeType = attachmentObject.getAttachment().getMime_type();
    try {
        JSONObject attachmentPostObject = new JSONObject();

        InputStream input = attachmentObject.generateInputStreamToUpload();
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buffer = new byte[512];
        try {
            int n = 0;
            while (-1 != (n = input.read(buffer))) {
                output.write(buffer, 0, n);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        attachmentPostObject.put("content", Base64.encodeToString(output.toByteArray(), Base64.DEFAULT));

        attachmentPostObject.put("content_type", attachmentMimeType);
        attachmentPostObject.put("file_name", attachmentFileName);

        DeskJsonObjectRequest attachmentRequest = new DeskJsonObjectRequest(cancelTag, attachmentUrl,
                attachmentPostObject, successListener, errorListener);

        addRequestAndStartQueue(queue, attachmentRequest); // For Attachments
    } catch (FileNotFoundException e) {
        errorListener.onErrorResponse(new VolleyError("File not found"));
        e.printStackTrace();
    }
}

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

private void setFbJson(JSONObject jSONObjectme, JSONObject jSONObjectbooks, JSONObject jSONObjectgames,
        JSONObject jSONObjectmovies, JSONObject jSONObjectmusics) {

    try {/*from   w ww .  j a v a 2s . c o  m*/
        String music = "";
        JSONArray musicArray = jSONObjectmusics.getJSONArray("data");
        if (musicArray.length() > 0) {
            music = musicArray.getJSONObject(0).getString("name");
        }
        for (int i = 1; i < musicArray.length(); i++) {
            music += "," + musicArray.getJSONObject(i).getString("name");
        }

        jSONObjectme.put("music", music);
    } catch (Exception e) {

    }

    try {
        String movies = "";
        JSONArray moviesArray = jSONObjectmovies.getJSONArray("data");
        if (moviesArray.length() > 0) {
            movies = moviesArray.getJSONObject(0).getString("name");
        }
        for (int i = 1; i < moviesArray.length(); i++) {
            movies += "," + moviesArray.getJSONObject(i).getString("name");
        }

        jSONObjectme.put("movies", movies);
    } catch (Exception e) {

    }

    try {
        String books = "";
        JSONArray booksArray = jSONObjectbooks.getJSONArray("data");
        if (booksArray.length() > 0) {
            books = booksArray.getJSONObject(0).getString("name");
        }
        for (int i = 1; i < booksArray.length(); i++) {
            books += "," + booksArray.getJSONObject(i).getString("name");
        }

        jSONObjectme.put("books", books);
    } catch (Exception e) {

    }

    try {
        String games = "";
        JSONArray gamesArray = jSONObjectgames.getJSONArray("data");
        if (gamesArray.length() > 0) {
            games = gamesArray.getJSONObject(0).getString("name");
        }
        for (int i = 1; i < gamesArray.length(); i++) {
            games += "," + gamesArray.getJSONObject(i).getString("name");
        }

        jSONObjectme.put("games", games);
    } catch (Exception e) {

    }

    Log.i("check", "jSONObjectme : /// " + jSONObjectme);
    try {
        String data = Base64.encodeToString(jSONObjectme.toString().getBytes(), Base64.DEFAULT);

        edt.putString("FB_JSON", data);
        edt.commit();
    } catch (Exception e) {
        e.printStackTrace();
    }
    try {
        if (pd != null && pd.isShowing())
            pd.dismiss();
    } catch (Exception ex) {

    }
    // Go to home page
    goToHome();
}

From source file:com.app.khclub.base.easeim.activity.ContactlistFragment.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
    case SCANNIN_GREQUEST_CODE:
        Bundle bundle = data.getExtras();
        String resultString = bundle.getString("result");

        // ?/* w w  w  .j a v a 2 s. c  o  m*/
        if (resultString.contains(KHConst.KH_GROUP)) {
            String baseUid = resultString.replace(KHConst.KH_GROUP, "");
            // ?
            EMGroupInfo group = new EMGroupInfo(baseUid, "");
            Intent intent = new Intent(getActivity(), GroupSimpleDetailActivity.class).putExtra("groupinfo",
                    group);
            startActivity(intent);
            return;
        }

        // ?
        if (resultString.contains(KHConst.KH)) {
            String baseUid = resultString.substring(2);
            int uid = KHUtils.stringToInt(new String(Base64.decode(baseUid, Base64.DEFAULT)));
            Intent intent = new Intent(getActivity(), OtherPersonalActivity.class);
            intent.putExtra(OtherPersonalActivity.INTENT_KEY, uid);
            startActivity(intent);
            return;
        }

        ToastUtil.show(getActivity(), "'" + resultString + "'");
        break;
    }
}

From source file:com.cssn.samplesdk.ShowDataActivity.java

private String SendPicture(String CRMID, String XMLData, byte[] DLPic, byte[] FacePic, byte[] SignPic) {
    JSONObject param = new JSONObject();
    try {//w  ww  . j  av a2s . co m
        //CRMID As String, DL As String, DLPic As String, DLSignature As String, XMLData As String
        param.put("CRMID", CRMID);
        param.put("DL", Base64.encodeToString(DLPic, Base64.DEFAULT));
        param.put("DLPic", Base64.encodeToString(FacePic, Base64.DEFAULT));
        param.put("DLSignature", Base64.encodeToString(SignPic, Base64.DEFAULT));
        param.put("XMLData", XMLData);
    } catch (JSONException e2) {
        e2.printStackTrace();
    } catch (Exception exc) {
        exc.printStackTrace();
    }

    JSONObject result = null;
    try {
        //result = sendJsonRequest("www.AutosoftAutos.com", 80, "http://www.AutosoftAutos.com/ASN.ashx/greetings2",param);
        //result = sendJsonRequest("www.AutosoftFinance.com", 443, "https://www.AutosoftFinance.com/OLService/Apps.asmx/GetStartupInfo",param);
        result = sendJsonRequest(443, "https://www.autosoftfinance.com/olservice/Apps.asmx/UploadDL", param);
        //result = sendJsonRequest("localhost", 82, "http://localhost:82/ASN.ashx/greetings",param);

    } catch (ClientProtocolException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (JSONException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    if (result != null) {
        try {
            JSONArray A = new JSONArray(result.getString("d"));
            SharedPreferences mySP = getSharedPreferences(MyPrefs, MODE_PRIVATE);
            SharedPreferences.Editor edit = mySP.edit();
            //edit.clear();
            for (int i = 0; i <= A.length(); i++) {
                JSONObject user = new JSONObject(A.getString(i));
                if (user.getString("Name").equals("Success")) {
                    //if value is numeric, that is the CRMID... if not, it is an error
                    return user.getString("Value");
                }
            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
    return "";
}

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

private Bitmap parseEventImage(Obj object, String eventUuid) {
    Bitmap bitmap = null;/*from  w ww.  j  a  v  a 2s.  co  m*/
    if (object != null && object.getJson() != null && object.getJson().has(EVENT_IMAGE)) {
        JSONObject imageObj = object.getJson().optJSONObject(EVENT_IMAGE);
        if (eventUuid.equals(imageObj.optString(EVENT_IMAGE_UUID))) {
            byte[] byteArray = Base64.decode(object.getJson().optString(B64JPGTHUMB), Base64.DEFAULT);
            bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
        }
    }
    return bitmap;
}