Example usage for android.util Base64 decode

List of usage examples for android.util Base64 decode

Introduction

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

Prototype

public static byte[] decode(byte[] input, int flags) 

Source Link

Document

Decode the Base64-encoded data in input and return the data in a new byte array.

Usage

From source file:com.sythealth.fitness.util.Utils.java

public static String getStrFromBase64(String str) {
    byte[] bytes = Base64.decode(str, Base64.DEFAULT);
    return new String(bytes);
}

From source file:com.projectattitude.projectattitude.Activities.ViewProfileActivity.java

/**
 * Initial set up on creation including setting up references, adapters, and readying the search
 * button./*from   w  ww .  j  av  a2  s  .  c o m*/
 * @param savedInstanceState
 */

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_view_profile);
    searchBar = (EditText) findViewById(R.id.searchBar);
    searchButton = (Button) findViewById(R.id.searchButton);
    removeButton = (Button) findViewById(R.id.removeButton);

    image = (ImageView) findViewById(R.id.profileImage);
    nameView = (TextView) findViewById(R.id.profileUname);

    recentMoodView = (ListView) findViewById(R.id.latestMood);
    followUserList = (ListView) findViewById(R.id.followList);
    followedUserList = (ListView) findViewById(R.id.followedList);

    recentMoodAdapter = new MoodMainAdapter(this, recentMoodList);
    recentMoodView.setAdapter(recentMoodAdapter);

    user = userController.getActiveUser();

    followUserAdapter = new ArrayAdapter<String>(this, R.layout.list_item, user.getFollowList());
    followedUserAdapter = new ArrayAdapter<String>(this, R.layout.list_item, user.getFollowedList());
    followUserList.setAdapter(followUserAdapter);
    followedUserList.setAdapter(followedUserAdapter);

    searchButton.setOnClickListener(new View.OnClickListener() { // adding a new user to following list
        @Override
        public void onClick(View v) {

            String followingName = searchBar.getText().toString();

            User followedUser = new User();
            followedUser.setUserName(followingName);

            if (followingName.equals("")) { // no username entered to search for
                searchBar.requestFocus(); // search has been canceled
            }

            else {
                if (isNetworkAvailable()) {
                    ElasticSearchUserController.GetUserTask getUserTask = new ElasticSearchUserController.GetUserTask();
                    try {
                        if (getUserTask.execute(followedUser.getUserName()).get() == null) {
                            Log.d("Error", "User did not exist");
                            Toast.makeText(ViewProfileActivity.this, "User not found.", Toast.LENGTH_SHORT)
                                    .show();
                        } else {
                            Log.d("Error", "User did exist");
                            //grab user from db and add to following list
                            getUserTask = new ElasticSearchUserController.GetUserTask();
                            try {
                                followedUser = getUserTask.execute(followingName).get();
                                if (followedUser != null) { // user exists
                                    if (followedUser.getUserName().equals(user.getUserName())) {
                                        Toast.makeText(ViewProfileActivity.this,
                                                "You cannot be friends with yourself. Ever", Toast.LENGTH_SHORT)
                                                .show();
                                    } else {
                                        if (user.getFollowList().contains(followedUser.getUserName())) {
                                            Toast.makeText(ViewProfileActivity.this,
                                                    "You're already following that user.", Toast.LENGTH_SHORT)
                                                    .show();
                                        } else {// user not already in list
                                                //check if request between users already exists in database
                                            boolean isContained = false;
                                            ArrayList<FollowRequest> requests = followedUser.getRequests();
                                            for (int i = 0; i < followedUser.getRequests().size(); i++) { //Checks if request already exists
                                                if (requests.get(i).getRequester().equals(user.getUserName())
                                                        && requests.get(i).getRequestee()
                                                                .equals(followedUser.getUserName())) {
                                                    isContained = true;
                                                    break;
                                                }
                                            }
                                            if (!isContained) { //request doesn't exists - not sure why .get always returns an filled array or empty array
                                                followedUser.getRequests().add(new FollowRequest(
                                                        user.getUserName(), followedUser.getUserName()));
                                                ElasticSearchRequestController.UpdateRequestsTask updateRequestsTask = new ElasticSearchRequestController.UpdateRequestsTask();
                                                updateRequestsTask.execute(followedUser);
                                                Toast.makeText(ViewProfileActivity.this, "Request sent!",
                                                        Toast.LENGTH_SHORT).show();
                                            } else { // request exists
                                                Toast.makeText(ViewProfileActivity.this,
                                                        "Request already exists.", Toast.LENGTH_SHORT).show();
                                            }
                                        }
                                    }
                                }
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            } catch (ExecutionException e) {
                                e.printStackTrace();
                            }
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (ExecutionException e) {
                        e.printStackTrace();
                    }

                } else {
                    Toast.makeText(ViewProfileActivity.this,
                            "Must be connected to internet to search for users!", Toast.LENGTH_LONG).show();
                }
            }
        }
    });

    //On-click for removeButton
    removeButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String followingName = searchBar.getText().toString();

            if (followingName.equals("")) { // no username entered to search for
                searchBar.requestFocus(); // search has been canceled
            }

            else {
                if (isNetworkAvailable()) {
                    if (!user.getFollowList().contains(followingName)) { //If user not in following list
                        Log.d("Error", "Invalid user.");
                        Toast.makeText(ViewProfileActivity.this, "Invalid user. User not found.",
                                Toast.LENGTH_SHORT).show();
                    } else {
                        Log.d("Error", "Followed User exists");
                        setResult(RESULT_OK);
                        //remove followedList of who user is following
                        try {
                            ElasticSearchUserController.GetUserTask getUserTask = new ElasticSearchUserController.GetUserTask();
                            User followedUser = getUserTask.execute(followingName).get();
                            if (followedUser != null) {
                                //Remove followee and update database
                                followedUser.getFollowedList().remove(user.getUserName());
                                ElasticSearchUserController.UpdateUserRequestFollowedTask updateUserRequestFollowedTask = new ElasticSearchUserController.UpdateUserRequestFollowedTask();
                                updateUserRequestFollowedTask.execute(followedUser);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        //user exists --> delete follower and update database
                        user.removeFollow(followingName);
                        ElasticSearchUserController.UpdateUserRequestTask updateUserRequestTask = new ElasticSearchUserController.UpdateUserRequestTask();
                        updateUserRequestTask.execute(user);
                        Toast.makeText(ViewProfileActivity.this, "Followed user has been removed!",
                                Toast.LENGTH_SHORT).show();
                        followUserAdapter.notifyDataSetChanged();
                    }
                } else {
                    Toast.makeText(ViewProfileActivity.this, "Must be connected to internet to remove user!",
                            Toast.LENGTH_LONG).show();
                }
            }
        }
    });

    //If image exists in user, set image
    if (user.getPhoto() != null && user.getPhoto().length() > 0) {
        //decode base64 image stored in User
        byte[] imageBytes = Base64.decode(user.getPhoto(), Base64.DEFAULT);
        Bitmap decodedImage = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
        image.setImageBitmap(decodedImage);
    }

    /**
     * This handles when a user clicks on their most recent mood, taking them to the view mood screen
     */
    recentMoodView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent intentView = new Intent(ViewProfileActivity.this, ViewMoodActivity.class);
            intentView.putExtra("mood", recentMoodList.get(position));
            startActivityForResult(intentView, 1);
        }
    });

    //Adjusted from http://codetheory.in/android-pick-select-image-from-gallery-with-intents/
    //on 3/29/17
    /**
     * This handles when the user clicks on their image
     */
    image.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //Check if user has permission to get picture from gallery
            if (ContextCompat.checkSelfPermission(thisActivity,
                    android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(thisActivity,
                        new String[] { android.Manifest.permission.READ_EXTERNAL_STORAGE },
                        MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
            } else { //user already has permission
                Intent intent = new Intent();
                // Show only images, no videos or anything else
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                // Always show the chooser (if there are multiple options available)
                startActivityForResult(Intent.createChooser(intent, "Select Picture"), 1);
            }
        }
    });
}

From source file:mobisocial.musubi.objects.IntroductionObj.java

/**
 * Extracts the list of identities from an introductionObj.
 *//*from   ww w  .j av a  2  s. c o m*/
static List<IBHashedIdentity> getIdentitiesForObj(Obj obj) {
    ArrayList<IBHashedIdentity> ids = new ArrayList<IBHashedIdentity>();

    JSONObject json = obj.getJson();
    if (json == null) {
        return ids;
    }
    JSONArray array;
    try {
        array = json.getJSONArray(IDENTITIES);
    } catch (JSONException e) {
        return ids;
    }

    for (int i = 0; i < array.length(); ++i) {
        JSONObject identity;
        try {
            identity = array.getJSONObject(i);
        } catch (JSONException e) {
            Log.e(TAG, "identity entry in introduction access error", e);
            continue;
        }
        int authority = -1;
        String principalHashString = null;
        try {
            authority = identity.getInt(ID_AUTHORITY);
            principalHashString = identity.getString(ID_PRINCIPAL_HASH);
        } catch (JSONException e) {
            Log.e(TAG, "identity entry in introduction missing key fields", e);
            continue;
        }
        String principal = null;
        try {
            principal = identity.getString(ID_PRINCIPAL);
        } catch (JSONException e) {
        }
        String name = null;
        try {
            name = identity.getString(ID_NAME);
        } catch (JSONException e) {
        }
        if (name == null && principal == null) {
            //not much of an introduction
            continue;
        }

        byte[] principalHash = Base64.decode(principalHashString, Base64.DEFAULT);
        ids.add(new IBHashedIdentity(Authority.values()[authority], principalHash, 0));
    }
    return ids;
}

From source file:com.ledger.android.u2f.bridge.MainActivity.java

private U2FContext parseU2FContextRegister(JSONObject json) {
    try {//  ww  w.  j av  a 2  s  . c o  m
        byte[] challenge = null;
        String appId = json.getString(TAG_JSON_APPID);
        int requestId = json.getInt(TAG_JSON_REQUESTID);
        JSONArray array = json.getJSONArray(TAG_JSON_REGISTER_REQUESTS);
        for (int i = 0; i < array.length(); i++) {
            // TODO : only handle USB transport if several are present
            JSONObject registerItem = array.getJSONObject(i);
            if (!registerItem.getString(TAG_JSON_VERSION).equals(VERSION_U2F_V2)) {
                Log.e(TAG, "Invalid register version");
                return null;
            }
            challenge = Base64.decode(registerItem.getString(TAG_JSON_CHALLENGE), Base64.URL_SAFE);
        }
        return new U2FContext(appId, challenge, null, requestId, false);
    } catch (JSONException e) {
        Log.e(TAG, "Error decoding request");
        return null;
    }
}

From source file:com.quarterfull.newsAndroid.NewsReaderListFragment.java

/** Read the object from Base64 string. */
public static Object fromString(String s) throws IOException, ClassNotFoundException {
    byte[] data = Base64.decode(s, Base64.DEFAULT);
    ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(data));
    Object o = ois.readObject();/*  ww  w .j a  v  a2 s.  c om*/
    ois.close();
    return o;
}

From source file:org.webinos.android.app.wrt.ui.WidgetListActivity.java

private Store readStore(Context ctx, JSONObject json) {
    Store result = new Store();
    try {/*from  w ww.  ja v a2s . com*/
        result.name = json.getString("name");
        result.description = json.getString("description");
        result.location = Uri.parse(json.getString("location"));
        byte[] decodedString = Base64.decode(json.getString("logo"), Base64.DEFAULT);
        result.icon = (Drawable) new BitmapDrawable(
                BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length));
    } catch (JSONException e) {
        result = null;
    }
    return result;
}

From source file:com.remobile.file.LocalFilesystem.java

@Override
public long writeToFileAtURL(LocalFilesystemURL inputURL, String data, int offset, boolean isBinary)
        throws IOException, NoModificationAllowedException {

    boolean append = false;
    if (offset > 0) {
        this.truncateFileAtURL(inputURL, offset);
        append = true;//  www  .ja va2  s.co  m
    }

    byte[] rawData;
    if (isBinary) {
        rawData = Base64.decode(data, Base64.DEFAULT);
    } else {
        rawData = data.getBytes();
    }
    ByteArrayInputStream in = new ByteArrayInputStream(rawData);
    try {
        byte buff[] = new byte[rawData.length];
        String absolutePath = filesystemPathForURL(inputURL);
        FileOutputStream out = new FileOutputStream(absolutePath, append);
        try {
            in.read(buff, 0, buff.length);
            out.write(buff, 0, rawData.length);
            out.flush();
        } finally {
            // Always close the output
            out.close();
        }
        if (isPublicDirectory(absolutePath)) {
            broadcastNewFile(Uri.fromFile(new File(absolutePath)));
        }
    } catch (NullPointerException e) {
        // This is a bug in the Android implementation of the Java Stack
        NoModificationAllowedException realException = new NoModificationAllowedException(inputURL.toString());
        throw realException;
    }

    return rawData.length;
}

From source file:io.winch.phonegap.plugin.WinchPlugin.java

private void putBase64(CallbackContext callbackContext, JSONArray args) {
    try {//from  w ww.  ja va 2s .c  o  m
        String namespace = args.getString(0);
        String key = args.getString(1);
        String base64 = args.getString(2);
        byte[] data = Base64.decode(base64, Base64.NO_WRAP);

        mWinch.getNamespace(namespace).put(key, data);
        callbackContext.success();
    } catch (WinchError e) {
        e.printStackTrace();
        PluginResult r = buildErrorResult(e.getErrorCode(), e.getMessage());
        callbackContext.sendPluginResult(r);
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

From source file:com.mytalentfolio.h_daforum.CconnectToServer.java

/**
 * Creates a new instance of {@code PublicKey}. Convert the string formatted
 * public key into {@code PublicKey} type.
 * // w w  w .j  a  v a2 s . co m
 * @param key
 *            the string formated public key.
 * @return the new {@code PublicKey} instance.
 * @throws NoSuchAlgorithmException
 *             if no provider provides the requested algorithm.
 * @throws InvalidKeyException
 *             if the specified keySpec is invalid.
 * 
 */
// Converting the Server Public key format to Java compatible from
private PublicKey getServerPublicKey(String key) throws NoSuchAlgorithmException, InvalidKeySpecException {

    // Converting the Server Public key format to Java compatible from
    key = key.replace("-----BEGIN PUBLIC KEY-----\n", "");
    key = key.replace("\n-----END PUBLIC KEY-----", "");

    // Creating the public key from the string format received from server
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    PublicKey serverPublicKeySig = keyFactory
            .generatePublic(new X509EncodedKeySpec(Base64.decode(key.toString(), Base64.DEFAULT)));
    return serverPublicKeySig;
}

From source file:android.framework.util.jar.JarVerifier.java

private boolean verify(Attributes attributes, String entry, byte[] data, int start, int end,
        boolean ignoreSecondEndline, boolean ignorable) {
    String algorithms = attributes.getValue("Digest-Algorithms");
    if (algorithms == null) {
        algorithms = "SHA SHA1";
    }//from   w  ww .  ja  v a 2  s . c o m
    StringTokenizer tokens = new StringTokenizer(algorithms);
    while (tokens.hasMoreTokens()) {
        String algorithm = tokens.nextToken();
        String hash = attributes.getValue(algorithm + entry);
        if (hash == null) {
            continue;
        }

        MessageDigest md;
        try {
            md = MessageDigest.getInstance(algorithm);
        } catch (NoSuchAlgorithmException e) {
            continue;
        }
        if (ignoreSecondEndline && data[end - 1] == '\n' && data[end - 2] == '\n') {
            md.update(data, start, end - 1 - start);
        } else {
            md.update(data, start, end - start);
        }
        byte[] b = md.digest();
        byte[] hashBytes = hash.getBytes(Charsets.ISO_8859_1);
        return MessageDigest.isEqual(b, Base64.decode(hashBytes, Base64.DEFAULT));
    }
    return ignorable;
}