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:org.apache.cordova.test.Echo.java

/**
* Executes the request and returns PluginResult.
*
* @param action            The action to execute.
* @param args              JSONArry of arguments for the plugin.
* @param callbackContext   The callback context from which we were invoked.
* @return                  A PluginResult object with a status and message.
*///from   w  w w  .j a v a2 s  .co m
@SuppressLint("NewApi")
public boolean execute(String action, final JSONArray args, final CallbackContext callbackContext)
        throws JSONException {
    try {
        if (action.equals("echo")) {
            callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, args.getString(0)));
            return true;
        } else if (action.equals("echoAsync")) {
            cordova.getActivity().runOnUiThread(new Runnable() {
                public void run() {
                    callbackContext
                            .sendPluginResult(new PluginResult(PluginResult.Status.OK, args.optString(0)));
                }
            });
            return true;
        } else if (action.equals("echoArrayBuffer")) {
            String data = args.optString(0);
            byte[] rawData = Base64.decode(data, Base64.DEFAULT);
            callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, rawData));
            return true;
        } else if (action.equals("echoArrayBufferAsync")) {
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    String data = args.optString(0);
                    byte[] rawData = Base64.decode(data, Base64.DEFAULT);
                    callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, rawData));
                }
            });
            return true;
        } else if (action.equals("echoMultiPart")) {
            callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, args.getJSONObject(0)));
            return true;
        } else if (action.equals("stopEchoBulk")) {
            bulkEchoing = false;
        } else if (action.equals("echoBulk")) {
            if (bulkEchoing) {
                return true;
            }
            final String payload = args.getString(0);
            final int delayMs = args.getInt(1);
            bulkEchoing = true;
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    while (bulkEchoing) {
                        try {
                            Thread.sleep(delayMs);
                        } catch (InterruptedException e) {
                        }
                        PluginResult pr = new PluginResult(PluginResult.Status.OK, payload);
                        pr.setKeepCallback(true);
                        callbackContext.sendPluginResult(pr);
                    }
                    PluginResult pr = new PluginResult(PluginResult.Status.OK, payload);
                    callbackContext.sendPluginResult(pr);
                }
            });
            return true;
        }
        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR));
        return false;
    } catch (JSONException e) {
        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
        return false;
    }
}

From source file:org.apache.cordova.crypt.Crypt.java

public String encrypt(String data, String publickey) throws Exception {
    publickey = publickey.replaceAll("(-+BEGIN PUBLIC KEY-+\\r?\\n|-+END PUBLIC KEY-+\\r?\\n?)", "");

    try {//from   w ww  .j  ava  2s  . c om
        byte[] publickeyRaw = Base64.decode(publickey, Base64.DEFAULT);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publickeyRaw);
        KeyFactory fact = KeyFactory.getInstance("RSA");
        PublicKey pub = fact.generatePublic(keySpec);

        byte[] text = data.getBytes(Charset.forName("UTF-8"));

        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.ENCRYPT_MODE, pub);
        byte[] cipherString = cipher.doFinal(text);

        return new String(Base64.encode(cipherString, Base64.DEFAULT));

    } catch (Exception e) {
        Log.w("Crypt", e);
        return null;
    }
}

From source file:com.coodesoft.notee.MyImageGetter.java

@Override
public Drawable getDrawable(String source) {
    Drawable d = null;/*from w  ww. jav  a 2 s  . co m*/

    String strSrcLeft5 = source.substring(0, 5);

    // data
    if (strSrcLeft5.equalsIgnoreCase("data:")) {
        InputStream is = new ByteArrayInputStream(source.getBytes());

        //d = Drawable.createFromStream(is, null);
        //d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());

        //Bitmap dBitmap = BitmapFactory.decodeByteArray(data, 0, length);
        int nPosComma = source.indexOf(',');
        if (nPosComma > 0) {
            byte[] arrBuffer = Base64.decode(source.substring(nPosComma + 1), Base64.DEFAULT);
            //byte[] arrBuffer = Base64Coder.decode(source.substring(nPosComma + 1));
            Bitmap dBitmap = BitmapFactory.decodeByteArray(arrBuffer, 0, arrBuffer.length);
            d = new BitmapDrawable(dBitmap);
            d.setBounds(0, 0, dBitmap.getWidth(), dBitmap.getHeight());
        }

    } else {
        // url

        try {

            InputStream is = (InputStream) new URL(source).getContent();
            Bitmap dBitmap = BitmapFactory.decodeStream(is);
            if (dBitmap == null) {
                d = Resources.getSystem().getDrawable(android.R.drawable.picture_frame);
            } else {
                d = new BitmapDrawable(dBitmap);
                d.setBounds(0, 0, dBitmap.getWidth(), dBitmap.getHeight());
            }

            d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());

        } catch (MalformedURLException e) {

            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();

        }

        /*
         URLDrawable urlDrawable = new URLDrawable();
                
         // get the actual source
         ImageGetterAsyncTask asyncTask = 
        new ImageGetterAsyncTask( urlDrawable);
                
         asyncTask.execute(source);
                
         // return reference to URLDrawable where I will change with actual image from
         // the src tag
         return urlDrawable;
         */

    }

    return d;
}

From source file:com.ferjuarez.androidthingsdemo.PhotoEntryAdapter.java

@Override
protected void populateViewHolder(DoorbellEntryViewHolder viewHolder, PhotoEntry model, int position) {
    // Display the timestamp
    if (model != null && model.getTimestamp() != null) {
        CharSequence prettyTime = DateUtils.getRelativeDateTimeString(mApplicationContext, model.getTimestamp(),
                DateUtils.SECOND_IN_MILLIS, DateUtils.WEEK_IN_MILLIS, 0);
        viewHolder.time.setText(prettyTime);

        // Display the image
        if (model.getThumbnail() != null) {
            // Decode image data encoded by the Cloud Vision library
            byte[] imageBytes = Base64.decode(model.getThumbnail(), Base64.NO_WRAP | Base64.URL_SAFE);
            Bitmap bitmap = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
            if (bitmap != null) {
                viewHolder.image.setImageBitmap(bitmap);
            } else {
                Drawable placeholder = ContextCompat.getDrawable(mApplicationContext, R.mipmap.ic_launcher);
                viewHolder.image.setImageDrawable(placeholder);
            }//ww  w. j  a v  a  2 s  .  c o  m
        }
    }

    // Display the metadata
    /*if (model.getAnnotations() != null) {
    ArrayList<String> keywords = new ArrayList<>(model.getAnnotations().keySet());
            
    int limit = Math.min(keywords.size(), 3);
    viewHolder.metadata.setText(TextUtils.join("\n", keywords.subList(0, limit)));
    } else {
    viewHolder.metadata.setText("no annotations yet");
    }*/
}

From source file:com.vladstirbu.cordova.CDVInstagramPlugin.java

private void share(String imageString) {
    if (imageString != null && imageString.length() > 0) {
        byte[] imageData = Base64.decode(imageString, 0);

        FileOutputStream os = null;

        File filePath = new File(this.webView.getContext().getExternalFilesDir(null), "instagram.png");

        try {//  ww w . j  av a  2s  . co m
            os = new FileOutputStream(filePath, true);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            os.write(imageData);
            os.flush();
            os.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.setType("image/*");
        shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + filePath));
        shareIntent.setPackage("com.instagram.android");

        this.cordova.startActivityForResult((CordovaPlugin) this, shareIntent, 12345);

    } else {
        this.cbContext.error("Expected one non-empty string argument.");
    }
}

From source file:com.owncloud.android.jobs.NotificationJob.java

@NonNull
@Override// ww w  .  j av a  2  s. c  o m
protected Result onRunJob(@NonNull Params params) {

    Context context = getContext();
    PersistableBundleCompat persistableBundleCompat = getParams().getExtras();
    String subject = persistableBundleCompat.getString(KEY_NOTIFICATION_SUBJECT, "");
    String signature = persistableBundleCompat.getString(KEY_NOTIFICATION_SIGNATURE, "");

    if (!TextUtils.isEmpty(subject) && !TextUtils.isEmpty(signature)) {
        try {
            byte[] base64DecodedSubject = Base64.decode(subject, Base64.DEFAULT);
            byte[] base64DecodedSignature = Base64.decode(signature, Base64.DEFAULT);
            PushUtils pushUtils = new PushUtils();
            PrivateKey privateKey = (PrivateKey) PushUtils.readKeyFromFile(false);

            try {
                SignatureVerification signatureVerification = pushUtils.verifySignature(context,
                        base64DecodedSignature, base64DecodedSubject);

                if (signatureVerification.isSignatureValid()) {
                    Cipher cipher = Cipher.getInstance("RSA/None/PKCS1Padding");
                    cipher.init(Cipher.DECRYPT_MODE, privateKey);
                    byte[] decryptedSubject = cipher.doFinal(base64DecodedSubject);

                    Gson gson = new Gson();
                    DecryptedPushMessage decryptedPushMessage = gson.fromJson(new String(decryptedSubject),
                            DecryptedPushMessage.class);

                    // We ignore Spreed messages for now
                    if (!decryptedPushMessage.getApp().equals("spreed")) {
                        sendNotification(decryptedPushMessage.getSubject(), signatureVerification.getAccount());
                    }
                }
            } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException e1) {
                Log.d(TAG,
                        "Error decrypting message " + e1.getClass().getName() + " " + e1.getLocalizedMessage());
            }
        } catch (Exception exception) {
            Log.d(TAG, "Something went very wrong" + exception.getLocalizedMessage());
        }
    }
    return Result.SUCCESS;
}

From source file:de.audioattack.yacy32c3search.activity.SettingsDialog.java

public static String load(final Context context, final String key, String dflt) {
    final SharedPreferences sharedPreferences = context.getSharedPreferences("settings", Context.MODE_PRIVATE);
    final String base64Value = sharedPreferences.getString(key, "");

    final String value;
    if (base64Value.length() == 0) {
        value = dflt;/*from  www.  ja  v a 2 s  .  c  om*/
    } else {
        value = new String(Base64.decode(base64Value, Base64.NO_WRAP));
    }

    return value;
}

From source file:com.example.androidthings.doorbell.DoorbellEntryAdapter.java

@Override
protected void populateViewHolder(DoorbellEntryViewHolder viewHolder, DoorbellEntry model, int position) {
    // Display the timestamp
    CharSequence prettyTime = DateUtils.getRelativeDateTimeString(mApplicationContext, model.getTimestamp(),
            DateUtils.SECOND_IN_MILLIS, DateUtils.WEEK_IN_MILLIS, 0);
    viewHolder.time.setText(prettyTime);

    // Display the image
    if (model.getImage() != null) {
        // Decode image data encoded by the Cloud Vision library
        byte[] imageBytes = Base64.decode(model.getImage(), Base64.NO_WRAP | Base64.URL_SAFE);
        Bitmap bitmap = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
        if (bitmap != null) {
            viewHolder.image.setImageBitmap(bitmap);
        } else {/* w ww. j a va2 s  .  c  o  m*/
            Drawable placeholder = ContextCompat.getDrawable(mApplicationContext, R.drawable.ic_image);
            viewHolder.image.setImageDrawable(placeholder);
        }
    }

    // Display the metadata
    if (model.getAnnotations() != null) {
        ArrayList<String> keywords = new ArrayList<>(model.getAnnotations().keySet());

        int limit = Math.min(keywords.size(), 3);
        viewHolder.metadata.setText(TextUtils.join("\n", keywords.subList(0, limit)));
    } else {
        viewHolder.metadata.setText("no annotations yet");
    }
}

From source file:com.example.administrator.winsoftsalesproject.activity.NavHomeActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_nav_home);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);/*from   ww  w  .jav a 2  s .c o m*/
    sessionManger = new SessionManger(this);
    sessionManger.checkLogin();
    HashMap<String, String> user = sessionManger.getUserDetails();
    home = new Home();
    fragmentTransaction(home);

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
            R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    View header = navigationView.getHeaderView(0);
    TextView headerName = (TextView) header.findViewById(R.id.nav_name);
    TextView designation = (TextView) header.findViewById(R.id.nav_designation);
    ImageView headerImage = (ImageView) header.findViewById(R.id.nav_image);

    headerName.setText(user.get(sessionManger.KEY_EMPLOYEE_NAME).toUpperCase());
    designation.setText(user.get(sessionManger.KEY_DEPARTMENT).toUpperCase());

    byte[] decodeString = Base64.decode(user.get(sessionManger.KEY_EMPLOYEE_PHOTO).getBytes(), Base64.DEFAULT);
    Bitmap bitmap = BitmapFactory.decodeByteArray(decodeString, 0, decodeString.length);
    headerImage.setImageBitmap(bitmap);
}

From source file:hochschuledarmstadt.photostream_tools.ImageCacher.java

boolean cacheImage(Photo photo) throws IOException {
    int photoId = photo.getId();
    if (isCached(photoId)) {
        File filePath = getImageFilePathForPhotoId(photoId);
        String imageFilePath = filePath.getAbsolutePath();
        injectImageFilePath(photo, imageFilePath);
        return true;
    } else {/*from   ww  w.ja v a 2s. c  o  m*/
        String imageFilePath = photo.getImageFilePath();
        return cacheImage(photo, Base64.decode(imageFilePath, Base64.DEFAULT));
    }
}