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:com.moki.touch.util.management.ContentManager.java

/**
 * Get a list of urls that indicate what urls exist in the settings of the application
 * @return an arraylist of strings for content urls in the settings
 *//*  ww  w  . ja v  a  2  s.  c  o  m*/
public ArrayList<String> getAllSettingsUrls() {
    ArrayList<String> settingsUrls = new ArrayList<String>();
    JSONArray urls = SettingsUtil.getSettingsValues().optJSONArray(CONTENT_KEY);
    for (int i = 0; i < urls.length(); i++) {
        settingsUrls.add(Base64.encodeToString(
                urls.optJSONObject(i).optString(ContentObject.CONTENT_URL).getBytes(), Base64.DEFAULT));
    }
    return settingsUrls;
}

From source file:org.openbmap.soapclient.AsyncUploader.java

/**
 * Sends an authenticated http post request to upload file
 * @param file File to upload (full path)
 * @return true on response code 200, false otherwise
 *//*  w  ww  .  ja  v a 2s .  c o m*/
private UploadResult httpPostRequest(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 MultipartEntity entity = new MultipartEntity();
        entity.addPart(FILE_FIELD, new FileBody(new File(file), "text/xml"));

        if ((mUser != null) && (mPassword != null)) {
            final String authorizationString = "Basic "
                    + Base64.encodeToString((mUser + ":" + mPassword).getBytes(), Base64.NO_WRAP);
            httppost.setHeader("Authorization", authorizationString);
        }

        if (mToken != null) {
            entity.addPart(API_FIELD, new StringBody(mToken));
        }

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

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

From source file:net.olejon.spotcommander.PlaylistsActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Allow landscape?
    if (!mTools.allowLandscape())
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    // Intent/*from w  w w.ja v  a 2 s. c om*/
    final Intent intent = getIntent();

    // Computer
    final long computerId = mTools.getSharedPreferencesLong(
            "WIDGET_" + intent.getStringExtra(WidgetLarge.WIDGET_LARGE_INTENT_EXTRA) + "_COMPUTER_ID");

    final String[] computer = mTools.getComputer(computerId);

    // Layout
    setContentView(R.layout.activity_playlists);

    // Toolbar
    final Toolbar toolbar = (Toolbar) findViewById(R.id.playlists_toolbar);
    toolbar.setNavigationIcon(R.drawable.ic_close_white_24dp);
    toolbar.setTitle(getString(R.string.playlists_title));

    setSupportActionBar(toolbar);

    // Progress bar
    mProgressBar = (ProgressBar) findViewById(R.id.playlists_progressbar);
    mProgressBar.setVisibility(View.VISIBLE);

    // Listview
    mListView = (ListView) findViewById(R.id.playlists_list);

    // Get playlists
    final Cache cache = new DiskBasedCache(getCacheDir(), 0);

    final Network network = new BasicNetwork(new HurlStack());

    final RequestQueue requestQueue = new RequestQueue(cache, network);

    requestQueue.start();

    final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
            computer[0] + "/playlists.php?get_playlists_as_json", null, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    requestQueue.stop();

                    try {
                        final ArrayList<String> playlistNames = new ArrayList<>();

                        final Iterator<?> iterator = response.keys();

                        while (iterator.hasNext()) {
                            String key = (String) iterator.next();

                            playlistNames.add(key);
                        }

                        Collections.sort(playlistNames, new Comparator<String>() {
                            @Override
                            public int compare(String string1, String string2) {
                                return string1.compareToIgnoreCase(string2);
                            }
                        });

                        for (String playlistName : playlistNames) {
                            mPlaylistUris.add(response.getString(playlistName));
                        }

                        final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(mContext,
                                R.layout.activity_playlists_list_item, playlistNames);

                        mProgressBar.setVisibility(View.GONE);

                        mListView.setAdapter(arrayAdapter);
                        mListView.setVisibility(View.VISIBLE);

                        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                mTools.remoteControl(computerId, "shuffle_play_uri",
                                        mPlaylistUris.get(position));

                                finish();
                            }
                        });
                    } catch (Exception e) {
                        mProgressBar.setVisibility(View.GONE);

                        final TextView textView = (TextView) findViewById(R.id.playlists_error);
                        textView.setVisibility(View.VISIBLE);
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    requestQueue.stop();

                    mProgressBar.setVisibility(View.GONE);

                    final TextView textView = (TextView) findViewById(R.id.playlists_error);
                    textView.setVisibility(View.VISIBLE);
                }
            }) {
        @Override
        public HashMap<String, String> getHeaders() {
            final HashMap<String, String> hashMap = new HashMap<>();

            if (!computer[1].equals("") && !computer[2].equals(""))
                hashMap.put("Authorization", "Basic "
                        + Base64.encodeToString((computer[1] + ":" + computer[2]).getBytes(), Base64.NO_WRAP));

            return hashMap;
        }
    };

    jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(2500, 0, 0));

    requestQueue.add(jsonObjectRequest);
}

From source file:com.facebook.appevents.codeless.internal.ViewHierarchy.java

public static JSONObject setAppearanceOfView(View view, JSONObject json, float displayDensity) {
    try {/*from  w  w w . j av  a  2 s  .  co  m*/
        JSONObject textStyle = new JSONObject();
        if (view instanceof TextView) {
            TextView textView = (TextView) view;
            Typeface typeface = textView.getTypeface();
            if (typeface != null) {
                textStyle.put(TEXT_SIZE, textView.getTextSize());
                textStyle.put(TEXT_IS_BOLD, typeface.isBold());
                textStyle.put(TEXT_IS_ITALIC, typeface.isItalic());
                json.put(TEXT_STYLE, textStyle);
            }
        }
        if (view instanceof ImageView) {
            Drawable drawable = ((ImageView) view).getDrawable();
            if (drawable instanceof BitmapDrawable) {
                if (view.getHeight() / displayDensity <= ICON_MAX_EDGE_LENGTH
                        && view.getWidth() / displayDensity <= ICON_MAX_EDGE_LENGTH) {
                    Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
                    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
                    byte[] byteArray = byteArrayOutputStream.toByteArray();
                    String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);
                    json.put(ICON_BITMAP, encoded);
                }
            }
        }
    } catch (JSONException e) {
        Utility.logd(TAG, e);
    }

    return json;
}

From source file:com.example.SmartBoard.MQTTHandler.java

public static String bitmapToString(Bitmap bitmapImage) {
    if (bitmapImage == null)
        return null;
    Bitmap bitmap = bitmapImage;//from  w  ww . jav a 2  s . c  o  m
    ByteArrayOutputStream blob = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 0 /*ignored for PNG*/, blob);
    byte[] bitmapdata = blob.toByteArray();
    return Base64.encodeToString(bitmapdata, Base64.DEFAULT);
}

From source file:com.pedox.plugin.HttpClient.HttpClient.java

public void getImage(final Activity context, String url, JSONObject options,
        final CallbackContext callbackContext) throws JSONException {
    final AsyncHttpClient client = new AsyncHttpClient();
    this.setArgument(client, options);
    client.get(url, new FileAsyncHttpResponseHandler(context) {
        @Override//w ww .ja va  2 s.c o  m
        public void onFailure(int statusCode, Header[] headers, Throwable throwable, File file) {
            HttpClient.handleResult(false, statusCode, headers, "kekacauan", callbackContext, throwable);
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, File file) {

            InputStream inputStream = null;
            try {
                inputStream = new FileInputStream(file.getPath());
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            byte[] bytes;
            byte[] buffer = new byte[8192];
            int bytesRead;
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            try {
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    output.write(buffer, 0, bytesRead);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            bytes = output.toByteArray();
            String encodedImage = Base64.encodeToString(bytes, Base64.DEFAULT);

            HttpClient.handleResult(true, statusCode, headers, encodedImage, callbackContext, null);
        }
    });
}

From source file:org.wso2.iot.agent.utils.CommonUtils.java

/**
 * Generates keys, CSR and certificates for the devices.
 * @param context - Application context.
 * @param listener - DeviceCertCreationListener which provide device .
 *///  w  ww.j a va  2s  . co  m
public static void generateDeviceCertificate(final Context context, final DeviceCertCreationListener listener)
        throws AndroidAgentException {

    if (context.getFileStreamPath(Constants.DEVICE_CERTIFCATE_NAME).exists()) {
        try {
            listener.onDeviceCertCreated(
                    new BufferedInputStream(context.openFileInput(Constants.DEVICE_CERTIFCATE_NAME)));
        } catch (FileNotFoundException e) {
            Log.e(TAG, e.getMessage());
        }
    } else {

        try {
            ServerConfig utils = new ServerConfig();
            final KeyPair deviceKeyPair = KeyPairGenerator.getInstance(Constants.DEVICE_KEY_TYPE)
                    .generateKeyPair();
            X500Principal subject = new X500Principal(Constants.DEVICE_CSR_INFO);
            PKCS10CertificationRequest csr = new PKCS10CertificationRequest(Constants.DEVICE_KEY_ALGO, subject,
                    deviceKeyPair.getPublic(), null, deviceKeyPair.getPrivate());

            EndPointInfo endPointInfo = new EndPointInfo();
            endPointInfo.setHttpMethod(org.wso2.iot.agent.proxy.utils.Constants.HTTP_METHODS.POST);
            endPointInfo.setEndPoint(utils.getAPIServerURL(context) + Constants.SCEP_ENDPOINT);
            endPointInfo.setRequestParams(Base64.encodeToString(csr.getEncoded(), Base64.DEFAULT));

            new APIController().invokeAPI(endPointInfo, new APIResultCallBack() {
                @Override
                public void onReceiveAPIResult(Map<String, String> result, int requestCode) {
                    try {
                        CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
                        InputStream in = new ByteArrayInputStream(
                                Base64.decode(result.get("response"), Base64.DEFAULT));
                        X509Certificate cert = (X509Certificate) certFactory.generateCertificate(in);
                        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                        KeyStore keyStore = KeyStore.getInstance("PKCS12");
                        keyStore.load(null);
                        keyStore.setKeyEntry(Constants.DEVICE_CERTIFCATE_ALIAS,
                                (Key) deviceKeyPair.getPrivate(),
                                Constants.DEVICE_CERTIFCATE_PASSWORD.toCharArray(),
                                new java.security.cert.Certificate[] { cert });
                        keyStore.store(byteArrayOutputStream,
                                Constants.DEVICE_CERTIFCATE_PASSWORD.toCharArray());
                        FileOutputStream outputStream = context.openFileOutput(Constants.DEVICE_CERTIFCATE_NAME,
                                Context.MODE_PRIVATE);
                        outputStream.write(byteArrayOutputStream.toByteArray());
                        byteArrayOutputStream.close();
                        outputStream.close();
                        try {
                            listener.onDeviceCertCreated(new BufferedInputStream(
                                    context.openFileInput(Constants.DEVICE_CERTIFCATE_NAME)));
                        } catch (FileNotFoundException e) {
                            Log.e(TAG, e.getMessage());
                        }
                    } catch (CertificateException | KeyStoreException | NoSuchAlgorithmException
                            | IOException e) {
                        Log.e(TAG, e.getMessage(), e);
                    }
                }
            }, Constants.SCEP_REQUEST_CODE, context, true);

        } catch (NoSuchAlgorithmException e) {
            throw new AndroidAgentException("No algorithm for key generation", e);
        } catch (SignatureException e) {
            throw new AndroidAgentException("Invalid Signature", e);
        } catch (NoSuchProviderException e) {
            throw new AndroidAgentException("Invalid provider", e);
        } catch (InvalidKeyException e) {
            throw new AndroidAgentException("Invalid key", e);
        }
    }
}

From source file:com.beacon.afterui.imageUtils.ImageCache.java

public String getBitmapArrayFromBitmap(Bitmap bitmap) {
    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bao);
    byte[] ba = bao.toByteArray();
    String ba1 = Base64.encodeToString(ba, 0);
    return ba1;/*from   ww w . ja v a2 s.  c o  m*/
}

From source file:org.wso2.app.catalog.api.ApplicationManager.java

/**
 * Returns a base64 encoded string for a particular image.
 *
 * @param drawable - Image as a Drawable object.
 * @return - Base64 encoded value of the drawable.
 *//*  www .j  av a 2s  .  c om*/
public String encodeImage(Drawable drawable) {
    Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, COMPRESSION_LEVEL, outStream);
    byte[] bitmapContent = outStream.toByteArray();
    String encodedImage = Base64.encodeToString(bitmapContent, Base64.NO_WRAP);
    StreamHandler.closeOutputStream(outStream, TAG);

    return encodedImage;
}

From source file:com.platform.middlewares.plugins.CameraPlugin.java

@Override
public boolean handle(String target, final Request baseRequest, final HttpServletRequest request,
        final HttpServletResponse response) {

    // GET /_camera/take_picture
    ////from   w ww. java2  s  .c  om
    // Optionally pass ?overlay=<id> (see overlay ids below) to show an overlay
    // in picture taking mode
    //
    // Status codes:
    //   - 200: Successful image capture
    //   - 204: User canceled image picker
    //   - 404: Camera is not available on this device
    //   - 423: Multiple concurrent take_picture requests. Only one take_picture request may be in flight at once.
    //

    if (target.startsWith("/_camera/take_picture")) {
        Log.i(TAG, "handling: " + target + " " + baseRequest.getMethod());
        final MainActivity app = MainActivity.app;
        if (app == null) {
            Log.e(TAG, "handle: context is null: " + target + " " + baseRequest.getMethod());

            return BRHTTPHelper.handleError(500, "context is null", baseRequest, response);
        }

        if (globalBaseRequest != null) {
            Log.e(TAG, "handle: already taking a picture: " + target + " " + baseRequest.getMethod());

            return BRHTTPHelper.handleError(423, null, baseRequest, response);
        }

        PackageManager pm = app.getPackageManager();

        if (!pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
            Log.e(TAG, "handle: no camera available: ");
            return BRHTTPHelper.handleError(402, null, baseRequest, response);
        }
        if (ContextCompat.checkSelfPermission(app,
                Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(app, Manifest.permission.CAMERA)) {
                Log.e(TAG, "handle: no camera access, showing instructions");
                ((BreadWalletApp) app.getApplication()).showCustomToast(app,
                        app.getString(R.string.allow_camera_access), MainActivity.screenParametersPoint.y / 2,
                        Toast.LENGTH_LONG, 0);
            } else {
                // No explanation needed, we can request the permission.
                ActivityCompat.requestPermissions(app, new String[] { Manifest.permission.CAMERA },
                        BRConstants.CAMERA_REQUEST_GLIDERA_ID);
            }
        } else {
            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (takePictureIntent.resolveActivity(app.getPackageManager()) != null) {
                app.startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
            }

            continuation = ContinuationSupport.getContinuation(request);
            continuation.suspend(response);
            globalBaseRequest = baseRequest;
        }

        return true;
    } else if (target.startsWith("/_camera/picture/")) {
        Log.i(TAG, "handling: " + target + " " + baseRequest.getMethod());
        final MainActivity app = MainActivity.app;
        if (app == null) {
            Log.e(TAG, "handle: context is null: " + target + " " + baseRequest.getMethod());
            return BRHTTPHelper.handleError(500, "context is null", baseRequest, response);
        }
        String id = target.replace("/_camera/picture/", "");
        byte[] pictureBytes = readPictureForId(app, id);
        if (pictureBytes == null) {
            Log.e(TAG, "handle: WARNING pictureBytes is null: " + target + " " + baseRequest.getMethod());
            return BRHTTPHelper.handleError(500, "pictureBytes is null", baseRequest, response);
        }
        byte[] imgBytes = pictureBytes;
        String b64opt = request.getParameter("base64");
        String contentType = "image/jpeg";
        if (b64opt != null && !b64opt.isEmpty()) {
            contentType = "text/plain";
            String b64 = "data:image/jpeg;base64," + Base64.encodeToString(pictureBytes, Base64.NO_WRAP);
            try {
                imgBytes = b64.getBytes("UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return BRHTTPHelper.handleError(500, null, baseRequest, response);
            }
        }
        return BRHTTPHelper.handleSuccess(200, null, baseRequest, response, contentType);
    } else
        return false;
}