Example usage for android.util Base64 encodeToString

List of usage examples for android.util Base64 encodeToString

Introduction

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

Prototype

public static String encodeToString(byte[] input, int flags) 

Source Link

Document

Base64-encode the given data and return a newly allocated String with the result.

Usage

From source file:cn.sharesdk.net.NetworkHelper.java

public static String Base64Gzip(String str) {
    ByteArrayInputStream bais = new ByteArrayInputStream(str.getBytes());
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    String result = null;//ww w .  j  a va 2 s . c om
    // gzip
    GZIPOutputStream gos;
    try {
        gos = new GZIPOutputStream(baos);
        int count;
        byte data[] = new byte[1024];
        while ((count = bais.read(data, 0, 1024)) != -1) {
            gos.write(data, 0, count);
        }
        gos.finish();
        gos.close();

        byte[] output = baos.toByteArray();
        baos.flush();
        baos.close();
        bais.close();

        result = Base64.encodeToString(output, Base64.NO_WRAP);
    } catch (IOException e) {
        e.printStackTrace();
        Ln.i("NetworkHelper", "Base64Gzip == >>", e);
    }
    return result;
}

From source file:kr.co.sangcomz.facebooklogin.HelloFacebookSampleActivity.java

public static void showHashKey(Context context) {
    try {//from w w  w.  j  a  v a  2  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:org.n52.geoar.newdata.PluginLoader.java

/**
 * Saves the state of plugins to {@link SharedPreferences}.
 *//*ww  w  . j a  v  a 2 s. co  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:jp.gr.java_conf.petit_lycee.subsonico.MethodConstants.java

private HttpResponse getServerResponse(String reqMethod, List<BasicNameValuePair> params) throws IOException {
    String url = getRequestUrl(reqMethod, params);
    HttpGet method = new HttpGet(url);

    DefaultHttpClient client = new DefaultHttpClient();

    // ?//  w  ww  . j  a  v  a 2s  .  c  om
    String tmp = Base64.encodeToString((user_id + ":" + passwd).getBytes(), Base64.NO_WRAP);
    method.setHeader("Authorization", "Basic " + tmp);

    HttpResponse response = client.execute(method);
    int status = response.getStatusLine().getStatusCode();
    if (status == HttpStatus.SC_OK) {
        return response;
    } else {
        //TODO:?
        return null;
    }
}

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

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity);/*  ww  w.  j a v a2s  .c  o m*/

    /**
     * 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:org.openbmap.soapclient.FileUploader.java

/**
 * @param file//from  w  ww. jav a 2  s  .  c  o m
 * @return
 */
private boolean performUpload(final String file) {
    // TODO check network state
    // @see http://developer.android.com/training/basics/network-ops/connecting.html

    // Adjust HttpClient parameters
    final HttpParams httpParameters = new BasicHttpParams();
    // Set the timeout in milliseconds until a connection is established.
    // The default value is zero, that means the timeout is not used. 
    //HttpConnectionParams.setConnectionTimeout(httpParameters, CONNECTION_TIMEOUT);
    // Set the default socket timeout (SO_TIMEOUT) 
    // in milliseconds which is the timeout for waiting for data.
    //HttpConnectionParams.setSoTimeout(httpParameters, SOCKET_TIMEOUT);
    final DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters);

    final HttpPost httppost = new HttpPost(mServer);
    try {

        final String authorizationString = "Basic "
                + Base64.encodeToString((mUser + ":" + mPassword).getBytes(), Base64.NO_WRAP);
        httppost.setHeader("Authorization", authorizationString);

        final MultipartEntity entity = new MultipartEntity();

        // TODO we don't need passwords for the new service
        entity.addPart(LOGIN_FIELD, new StringBody(mUser));
        entity.addPart(PASSWORD_FIELD, new StringBody(mPassword));
        entity.addPart(FILE_FIELD, new FileBody(new File(file), "text/xml"));

        httppost.setEntity(entity);
        final HttpResponse response = httpclient.execute(httppost);

        final int reply = response.getStatusLine().getStatusCode();
        if (reply == 200) {
            Log.i(TAG, "Uploaded " + file + ": Server reply " + reply);
        } else {
            Log.w(TAG, "Error while uploading" + file + ": Server reply " + reply);
        }
        // everything is ok if we receive HTTP 200
        // TODO: redirects (301, 302) are NOT handled here 
        // thus if something changes on the server side we're dead here
        return (reply == HttpStatus.SC_OK);
    } catch (final ClientProtocolException e) {
        Log.e(TAG, e.getMessage());
    } catch (final IOException e) {
        Log.e(TAG, "I/O exception on file " + file);
    }
    return false;
}

From source file:com.danielme.muspyforandroid.services.MuspyClient.java

public UserSettings getUserSettings(String email, String pass) throws Exception {
    UserSettings userSettings = null;/*from ww w.j  a  v  a2s . c  om*/
    HttpGet httpGet = new HttpGet(Constants.API.USER);
    httpGet.setHeader(CONTENT_TYPE, APPLICATION_JSON);
    httpGet.setHeader(AUTHORIZATION,
            "Basic " + Base64.encodeToString((email + ":" + pass).getBytes(), Base64.NO_WRAP));

    HttpResponse response = getDefaultHttpClient().execute(TARGETHOST, httpGet, getBasicHttpContext());

    String responseString = EntityUtils.toString(response.getEntity());

    if (checkAuth(response)) {
        userSettings = populateSettings(responseString);
    }

    return userSettings;
}

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 w w. ja va  2 s.  c  o  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/*from  w  w  w  .  j ava 2  s .  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.karura.framework.plugins.Contacts.java

@JavascriptInterface
@SupportJavascriptInterface/*from w ww.  j a v  a2  s  . c o 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);
            }
        }
    });
}