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:kr.co.sangcomz.facebooklogin.HelloFacebookSampleActivity.java

public static void showHashKey(Context context) {
    try {//from   w w  w . j av  a2  s  . c o  m
        PackageInfo info = context.getPackageManager().getPackageInfo("kr.co.sangcomz.facebooklogin",
                PackageManager.GET_SIGNATURES); //Your            package name here
        for (Signature signature : info.signatures) {
            MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(signature.toByteArray());
            Log.i("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
        }
    } catch (PackageManager.NameNotFoundException e) {
    } catch (NoSuchAlgorithmException e) {
    }
}

From source file:io.realm.RealmJsonTests.java

@Test
public void createObjectFromJson_allSimpleObjectAllTypes() throws JSONException {
    JSONObject json = new JSONObject();
    json.put("columnString", "String");
    json.put("columnLong", 1L);
    json.put("columnFloat", 1.23F);
    json.put("columnDouble", 1.23D);
    json.put("columnBoolean", true);
    json.put("columnBinary", new String(Base64.encode(new byte[] { 1, 2, 3 }, Base64.DEFAULT)));

    realm.beginTransaction();/*from  w w  w.ja  v  a2 s . c  o m*/
    realm.createObjectFromJson(AllTypes.class, json);
    realm.commitTransaction();
    AllTypes obj = realm.allObjects(AllTypes.class).first();

    // Check that all primitive types are imported correctly
    assertEquals("String", obj.getColumnString());
    assertEquals(1L, obj.getColumnLong());
    assertEquals(1.23F, obj.getColumnFloat(), 0F);
    assertEquals(1.23D, obj.getColumnDouble(), 0D);
    assertEquals(true, obj.isColumnBoolean());
    assertArrayEquals(new byte[] { 1, 2, 3 }, obj.getColumnBinary());
}

From source file:org.n52.geoar.newdata.PluginLoader.java

/**
 * Saves the state of plugins to {@link SharedPreferences}.
 *///from w  w  w .ja  va  2  s .  c o m
public static void saveState() {
    try {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);

        // store plugin state version
        objectOutputStream.writeInt(PLUGIN_STATE_VERSION);

        List<InstalledPluginHolder> checkedPlugins = mInstalledPlugins.getCheckedItems();
        objectOutputStream.writeInt(checkedPlugins.size());

        for (InstalledPluginHolder plugin : checkedPlugins) {
            objectOutputStream.writeUTF(plugin.getIdentifier());
            plugin.saveState(objectOutputStream);
        }

        SharedPreferences preferences = GeoARApplication.applicationContext
                .getSharedPreferences(GeoARApplication.PREFERENCES_FILE, Context.MODE_PRIVATE);
        Editor editor = preferences.edit();
        objectOutputStream.flush();
        editor.putString(PLUGIN_STATE_PREF, Base64.encodeToString(outputStream.toByteArray(), Base64.DEFAULT));
        editor.commit();
        objectOutputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
        // TODO
    }
}

From source file:at.diamonddogs.util.Utils.java

/**
 * Base64 byte array to string/*  w ww  . ja  va2  s .com*/
 *
 * @param encMsg the message to be converted from base64
 * @return the string
 */
public static String decrypt(byte[] encMsg) {
    return new String(Base64.decode(encMsg, Base64.DEFAULT));
}

From source file:com.appdupe.flamer.LoginUsingFacebook.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity);/*from w  ww  .  ja v  a2s .c  om*/

    /**
     * This code is required only once, to get the KeyHash, which will be
     * used in facebook while signing the app. The KeyHash will be displayed
     * in LogCat. Once the Keyhash has been generated, use it for signing
     * app, and then comment the code. Replace the package name with your
     * package name.
     */
    try {
        PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_SIGNATURES);
        for (Signature signature : info.signatures) {
            MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(signature.toByteArray());
            Log.i("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
        }
    } catch (NameNotFoundException e) {
        Log.e(TAG, "Exception(NameNotFoundException) : " + e);

    } catch (NoSuchAlgorithmException e) {
        Log.e(TAG, "Exception(NoSuchAlgorithmException) : " + e);
    }

    res = getResources();
    initdata();
    context = getApplicationContext();

    imagelist = new ArrayList<GellaryData>();
    mAdapterForGalery = new HomeAdapter(this, imagelist);
    galleryforsuprvisore.setAdapter(mAdapterForGalery);

    getTemplateFromResource();
    galleryforsuprvisore.setOnItemSelectedListener(new OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
            // logDebug("onItemSelected  ");
            // try
            // {

            System.out.println("Item Selected Position=======>>>" + pos);
            System.out.println("Item Selected Position=======>>>  count" + count);
            for (int i = 0; i < count; i++) {
                page_text[i].setTextColor(android.graphics.Color.GRAY);
            }
            page_text[pos].setTextColor(android.graphics.Color.BLUE);
            // } catch (Exception e)
            // //{
            // logError("onItemSelected  Exception "+e);
            // }

        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {

        }
    });

    Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);

    Session session = Session.getActiveSession();
    // logDebug("onCreate session "+session);
    if (session == null) {
        // logDebug("onCreate savedInstanceState "+savedInstanceState);
        if (savedInstanceState != null) {
            session = Session.restoreSession(this, null, statusCallback, savedInstanceState);
            // logDebug("onCreate savedInstanceState restore session   "+session);
        }
        if (session == null) {
            session = new Session(this);
            // logDebug("onCreate savedInstanceState create session   "+session);
        }
        Session.setActiveSession(session);
        logDebug("onCreate savedInstanceState state session    " + session.getState());
        if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
            // session.openForRead(new
            // Session.OpenRequest(this).setPermissions(Arrays.asList("user_birthday",
            // "email","user_relationships","user_photos")).setCallback(statusCallback));
        }
    }
    animeBottomTOUp = AnimationUtils.loadAnimation(this, R.anim.helpscreen_in_to_out);
    gellarybottom = AnimationUtils.loadAnimation(this, R.anim.helpscreen_in_to_out);
    gellarybottom.setFillAfter(true);

    gellarybottom.setAnimationListener(new AnimationListener() {
        @Override
        public void onAnimationStart(Animation animation) {
        }

        @Override
        public void onAnimationRepeat(Animation animation) {
        }

        @Override
        public void onAnimationEnd(Animation animation) {
        }
    });

    updateView();

    cd = new ConnectionDetector(getApplicationContext());
    if (cd.isConnectingToInternet()) {
        if (checkPlayServices()) {
            regid = getRegistrationId(this);
            if (regid.isEmpty()) {
                registerInBackground();
            } else {
                logDebug("reg id saved : " + regid);
            }
        } else {
            return;
        }

        // LocationManager locationManager = (LocationManager)
        // getSystemService(LOCATION_SERVICE);
        // if
        // (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
        // {
        // newLocationFinder = new LocationFinder();
        // newLocationFinder.getLocation(LoginUsingFacebook.this,
        // mLocationResult);
        // } else {
        // showGPSDisabledAlertToUser();
        //
        // }
    } else {
        AlertDialogManager.internetConnetionErrorAlertDialog(LoginUsingFacebook.this);
    }
}

From source file:com.lillicoder.newsblurry.net.PreferenceCookieStore.java

/**
 * Encodes the given {@link SerializableCookie} as a base-64 encoded string.
 * This string is what will be persisted to preferences.
 * @param cookie {@link SerializableCookie} to encode.
 * @return Encoded base-64 string for the given cookie,
 *          <code>null</code> if we failed to serialize the given cookie.
 *//*from w  ww . jav  a 2  s.  co  m*/
private String encodeCookie(Cookie cookie) {
    Assert.assertTrue(cookie != null);

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        ObjectOutputStream outStream = new ObjectOutputStream(out);

        SerializableCookie wrappedCookie = new SerializableCookie(cookie);
        outStream.writeObject(wrappedCookie);

        outStream.close();
    } catch (IOException e) {
        Log.w(TAG, WARNING_FAILED_TO_WRITE_COOKIE_TO_STREAM);
        return null;
    }

    try {
        out.close();
    } catch (IOException e) {
        Log.w(TAG, WARNING_FAILED_TO_CLOSE_ARRAY_OUTPUT_STREAM, e);
    }

    return Base64.encodeToString(out.toByteArray(), Base64.DEFAULT);
}

From source file:com.android.server.MigratorService.java

/**
 * set file bodies to ArrayList<byte[]>
 * @hide// w w  w .  jav  a2s. c  om
 * @param bodies the file bodies
 */
public void setFileBody(List bodies) {
    ArrayList<byte[]> tmp = (ArrayList<byte[]>) bodies;
    targetFileBody = new ArrayList<String>();
    for (byte[] array : tmp) {
        String data = Base64.encodeToString(array, Base64.DEFAULT);
        targetFileBody.add(data);
    }
}

From source file:com.example.android.apis.graphics.FingerPaint.java

private void saveBitmap(Bitmap bitmap) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 0, baos);
    byte[] b = baos.toByteArray();

    String encodedImage = Base64.encodeToString(b, Base64.DEFAULT);

    SharedPreferences shre = PreferenceManager.getDefaultSharedPreferences(this);
    Editor edit = shre.edit();//from   ww  w.java2 s  .c om
    edit.putString("paint_image_data", encodedImage);
    edit.commit();
}

From source file:com.karura.framework.plugins.Contacts.java

@JavascriptInterface
@SupportJavascriptInterface//from  w w w.ja va 2s .  co m
@Description("Resolve the content URI to a base64 image.")
@Asynchronous(retVal = "Returns the base64 encoded photograph of the specified contact")
@Params({ @Param(name = "callId", description = "The method correlator between javascript and java."),
        @Param(name = "contactContentUri", description = "Content URI of the photograph which was returned by the plugin in the call to getContact API") })
public void getPhoto(final String callId, final String contactContentUri) {
    runInBackground(new Runnable() {
        public void run() {
            try {
                String decodedUri = URLDecoder.decode(contactContentUri, "UTF-8");

                ByteArrayOutputStream buffer = new ByteArrayOutputStream();

                int bytesRead = 0;
                byte[] data = new byte[8192];

                Uri uri = Uri.parse(decodedUri);

                InputStream in = getActivity().getContentResolver().openInputStream(uri);

                while ((bytesRead = in.read(data, 0, data.length)) != -1) {
                    buffer.write(data, 0, bytesRead);
                }

                in.close();
                buffer.flush();

                String base64EncodedImage = Base64.encodeToString(buffer.toByteArray(), Base64.DEFAULT);
                resolveWithResult(callId, base64EncodedImage);

            } catch (Exception e) {
                if (BuildConfig.DEBUG) {
                    e.printStackTrace();
                }
                rejectWithCode(callId, ERR_INVALID_ARG);
            }
        }
    });
}

From source file:com.primitive.applicationmanager.ApplicationManager.java

/**
 * Package??????//w  ww .j av  a2 s  . c  o  m
 * @return Package[]
 * @throws ApplicationManagerException
 */
private Package[] requestPackages() throws ApplicationManagerException {
    Logger.start();
    final ApplicationSummary summary = this.requestApplicationSummary();
    if (this.beforePackages != null) {
        if (summary == null) {
            return null;
        } else {
            if (!this.isUpgrade(summary)) {
                return this.beforePackages;
            }
        }
    }
    final String applicationID = summary.getID();
    final String applicationName = summary.getName();
    final String url = this.config.buildServerURL(ApplicationManager.PackagesURI);

    final Map<String, String> params = new HashMap<String, String>();
    params.put("name", applicationName);
    params.put("application", applicationID);
    params.put("region", Locale.getDefault().getCountry());
    final JSONObject json = super.requestToResponse(url, params);
    try {
        final boolean success = json.getBoolean("sucess");
        if (!success) {
            return this.beforePackages;
        }
        final String secret = summary.getSecret();
        final String hash = json.getString("hash");
        final String result = json.getString("result");
        final String passphrase = HashMacHelper.getHMACBase64(HashMacHelper.Algorithm.HmacSHA256,
                hash.getBytes("UTF-8"), secret.getBytes("UTF-8"));

        byte[] passPhraseBytes = new byte[256 / 8];
        System.arraycopy(passphrase.getBytes(), 0, passPhraseBytes, 0, 256 / 8);

        final byte[] decriptDataByte = CipherHelper.decrypt(CipherHelper.Algorithm.AES, Mode.CBC,
                Padding.PKCS7Padding, Base64.decode(result.getBytes("UTF-8"), Base64.DEFAULT),
                hash.getBytes("UTF-8"), passPhraseBytes);
        final String decriptData = new String(decriptDataByte, "UTF-8");

        final JSONObject decript = new JSONObject(decriptData);
        final JSONArray packagesJSON = decript.getJSONArray("packages");
        final ArrayList<Package> packages = new ArrayList<Package>();
        for (int i = 0; i < packagesJSON.length(); i++) {
            final JSONObject object = packagesJSON.getJSONObject(i);
            final Package packageObject = new Package(object);
            packages.add(packageObject);
            Logger.debug(packageObject);
        }
        this.beforePackages = packages.toArray(new Package[] {});
    } catch (final JSONException ex) {
        Logger.err(ex);
    } catch (final UnsupportedEncodingException ex) {
        Logger.err(ex);
    } catch (CipherException ex) {
        Logger.err(ex);
    }
    return this.beforePackages;
}