Example usage for android.util Base64 NO_WRAP

List of usage examples for android.util Base64 NO_WRAP

Introduction

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

Prototype

int NO_WRAP

To view the source code for android.util Base64 NO_WRAP.

Click Source Link

Document

Encoder flag bit to omit all line terminators (i.e., the output will be on one long line).

Usage

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.
 *///w ww  .j a  v  a2s.co  m
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.ruesga.rview.fragments.SnippetFragment.java

private void loadContent(byte[] data) {
    final String fileName;
    if (mNeedPermissions) {
        fileName = DEFAULT_SNIPPED_NAME + ".txt";
    } else {//w w  w  . j  a  v a2  s. c o  m
        String ext = AceEditorView.resolveExtensionFromMimeType(mMimeType);
        fileName = DEFAULT_SNIPPED_NAME + "." + ext;
    }

    mBinding.editor.scrollTo(0, 0);
    mBinding.editor.loadEncodedContent(fileName, Base64.encode(data, Base64.NO_WRAP));
}

From source file:org.runnerup.export.JoggSE.java

private void saveGPX(final Writer wr, final String gpx)
        throws IllegalArgumentException, IllegalStateException, IOException {
    final XmlSerializer mXML = Xml.newSerializer();
    mXML.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
    mXML.setOutput(wr);/* w w w .j ava  2  s  . c  o m*/
    mXML.startDocument("UTF-8", true);
    mXML.startTag("", "soap12:Envelope");
    mXML.attribute("", "xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
    mXML.attribute("", "xmlns:xsd", "http://www.w3.org/2001/XMLSchema");
    mXML.attribute("", "xmlns:soap12", "http://www.w3.org/2003/05/soap-envelope");
    mXML.startTag("", "soap12:Body");
    mXML.startTag("", "SaveGpx");
    mXML.attribute("", "xmlns", "http://jogg.se/IphoneService");

    mXML.startTag("", "gpx");
    mXML.text(android.util.Base64.encodeToString(gpx.getBytes(), Base64.NO_WRAP));
    mXML.endTag("", "gpx");

    mXML.startTag("", "user");
    mXML.startTag("", "Email");
    mXML.text(username);
    mXML.endTag("", "Email");
    mXML.startTag("", "Password");
    mXML.text(password);
    mXML.endTag("", "Password");
    mXML.endTag("", "user");

    mXML.startTag("", "credentials");
    mXML.startTag("", "MasterUser");
    mXML.text(MASTER_USER);
    mXML.endTag("", "MasterUser");
    mXML.startTag("", "MasterKey");
    mXML.text(MASTER_KEY);
    mXML.endTag("", "MasterKey");
    mXML.endTag("", "credentials");
    mXML.endTag("", "SaveGpx");
    mXML.endTag("", "soap12:Body");
    mXML.endTag("", "soap12:Envelope");
    mXML.endDocument();
    mXML.flush();
}

From source file:org.runnerup.export.JoggSESynchronizer.java

private void saveGPX(final Writer wr, final String gpx)
        throws IllegalArgumentException, IllegalStateException, IOException {
    final KXmlSerializer mXML = new KXmlSerializer();
    mXML.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
    mXML.setOutput(wr);/*from  w  w w  .  j  a  v  a2s. c o  m*/
    mXML.startDocument("UTF-8", true);
    mXML.startTag("", "soap12:Envelope");
    mXML.attribute("", "xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
    mXML.attribute("", "xmlns:xsd", "http://www.w3.org/2001/XMLSchema");
    mXML.attribute("", "xmlns:soap12", "http://www.w3.org/2003/05/soap-envelope");
    mXML.startTag("", "soap12:Body");
    mXML.startTag("", "SaveGpx");
    mXML.attribute("", "xmlns", "http://jogg.se/IphoneService");

    mXML.startTag("", "gpx");
    mXML.text(android.util.Base64.encodeToString(gpx.getBytes(), Base64.NO_WRAP));
    mXML.endTag("", "gpx");

    mXML.startTag("", "user");
    mXML.startTag("", "Email");
    mXML.text(username);
    mXML.endTag("", "Email");
    mXML.startTag("", "Password");
    mXML.text(password);
    mXML.endTag("", "Password");
    mXML.endTag("", "user");

    mXML.startTag("", "credentials");
    mXML.startTag("", "MasterUser");
    mXML.text(MASTER_USER);
    mXML.endTag("", "MasterUser");
    mXML.startTag("", "MasterKey");
    mXML.text(MASTER_KEY);
    mXML.endTag("", "MasterKey");
    mXML.endTag("", "credentials");
    mXML.endTag("", "SaveGpx");
    mXML.endTag("", "soap12:Body");
    mXML.endTag("", "soap12:Envelope");
    mXML.endDocument();
    mXML.flush();
}

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 ww w.j a  v a 2s. c o m
    // 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;
}

From source file:com.owncloud.android.utils.PushUtils.java

public static void pushRegistrationToServer() {
    String token = PreferenceManager.getPushToken(MainApp.getAppContext());
    arbitraryDataProvider = new ArbitraryDataProvider(MainApp.getAppContext().getContentResolver());

    if (!TextUtils.isEmpty(MainApp.getAppContext().getResources().getString(R.string.push_server_url))
            && !TextUtils.isEmpty(token)) {
        PushUtils.generateRsa2048KeyPair();
        String pushTokenHash = PushUtils.generateSHA512Hash(token).toLowerCase();
        PublicKey devicePublicKey = (PublicKey) PushUtils.readKeyFromFile(true);
        if (devicePublicKey != null) {
            byte[] publicKeyBytes = Base64.encode(devicePublicKey.getEncoded(), Base64.NO_WRAP);
            String publicKey = new String(publicKeyBytes);
            publicKey = publicKey.replaceAll("(.{64})", "$1\n");

            publicKey = "-----BEGIN PUBLIC KEY-----\n" + publicKey + "\n-----END PUBLIC KEY-----\n";

            Context context = MainApp.getAppContext();
            String providerValue;
            PushConfigurationState accountPushData = null;
            Gson gson = new Gson();
            for (Account account : AccountUtils.getAccounts(context)) {
                providerValue = arbitraryDataProvider.getValue(account, KEY_PUSH);
                if (!TextUtils.isEmpty(providerValue)) {
                    accountPushData = gson.fromJson(providerValue, PushConfigurationState.class);
                } else {
                    accountPushData = null;
                }//  w  w  w.java 2  s.  c o m

                if (accountPushData != null && !accountPushData.getPushToken().equals(token)
                        && !accountPushData.isShouldBeDeleted() || TextUtils.isEmpty(providerValue)) {
                    try {
                        OwnCloudAccount ocAccount = new OwnCloudAccount(account, context);
                        OwnCloudClient mClient = OwnCloudClientManagerFactory.getDefaultSingleton()
                                .getClientFor(ocAccount, context);

                        RemoteOperation registerAccountDeviceForNotificationsOperation = new RegisterAccountDeviceForNotificationsOperation(
                                pushTokenHash, publicKey,
                                context.getResources().getString(R.string.push_server_url));

                        RemoteOperationResult remoteOperationResult = registerAccountDeviceForNotificationsOperation
                                .execute(mClient);

                        if (remoteOperationResult.isSuccess()) {
                            PushResponse pushResponse = remoteOperationResult.getPushResponseData();

                            RemoteOperation registerAccountDeviceForProxyOperation = new RegisterAccountDeviceForProxyOperation(
                                    context.getResources().getString(R.string.push_server_url), token,
                                    pushResponse.getDeviceIdentifier(), pushResponse.getSignature(),
                                    pushResponse.getPublicKey());

                            remoteOperationResult = registerAccountDeviceForProxyOperation.execute(mClient);

                            if (remoteOperationResult.isSuccess()) {
                                PushConfigurationState pushArbitraryData = new PushConfigurationState(token,
                                        pushResponse.getDeviceIdentifier(), pushResponse.getSignature(),
                                        pushResponse.getPublicKey(), false);
                                arbitraryDataProvider.storeOrUpdateKeyValue(account.name, KEY_PUSH,
                                        gson.toJson(pushArbitraryData));
                            }
                        }
                    } catch (com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException e) {
                        Log_OC.d(TAG, "Failed to find an account");
                    } catch (AuthenticatorException e) {
                        Log_OC.d(TAG, "Failed via AuthenticatorException");
                    } catch (IOException e) {
                        Log_OC.d(TAG, "Failed via IOException");
                    } catch (OperationCanceledException e) {
                        Log_OC.d(TAG, "Failed via OperationCanceledException");
                    }
                } else if (accountPushData != null && accountPushData.isShouldBeDeleted()) {
                    deleteRegistrationForAccount(account);
                }
            }
        }
    }
}

From source file:org.chromium.ChromeBluetooth.java

private JSONObject getLeDeviceInfo(ScanResult leScanResult) throws JSONException {
    JSONObject deviceInfo = getBasicDeviceInfo(leScanResult.getDevice());
    Set<String> uuidStrings = new HashSet<String>();
    uuidStrings.addAll(getUuidStringsFromDevice(leScanResult.getDevice()));
    uuidStrings.addAll(getUuidStringsFromLeScanRecord(leScanResult.getScanRecord()));

    JSONArray uuids = new JSONArray(uuidStrings);

    if (!uuidStrings.isEmpty()) {
        deviceInfo.put("uuids", uuids);
    }/* w  w  w  . j a v  a 2s .  co  m*/

    deviceInfo.put("rssi", leScanResult.getRssi());
    deviceInfo.put("tx_power", leScanResult.getScanRecord().getTxPowerLevel());

    Iterator serviceDataIt = leScanResult.getScanRecord().getServiceData().entrySet().iterator();
    if (serviceDataIt.hasNext()) {
        Map.Entry<ParcelUuid, byte[]> serviceDataPair = (Map.Entry<ParcelUuid, byte[]>) serviceDataIt.next();
        deviceInfo.put("serviceDataUuid", serviceDataPair.getKey().toString());
        deviceInfo.put("serviceData", Base64.encodeToString(serviceDataPair.getValue(), Base64.NO_WRAP));
    }

    return deviceInfo;
}

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

/**
 * Sends a https request to website to check if server accepts user name and password
 * @return true if server confirms credentials
 *//*from  www . j  a v  a 2 s.  co  m*/
private boolean credentialsAccepted(String user, String password) {

    if (user == null || password == null) {
        return false;
    }

    final DefaultHttpClient httpclient = new DefaultHttpClient();
    final HttpPost httppost = new HttpPost(Preferences.PASSWORD_VALIDATION_URL);
    try {
        final String authorizationString = "Basic "
                + Base64.encodeToString((user + ":" + password).getBytes(), Base64.NO_WRAP);
        httppost.setHeader("Authorization", authorizationString);
        final HttpResponse response = httpclient.execute(httppost);

        final int reply = response.getStatusLine().getStatusCode();
        if (reply == 200) {
            Log.v(TAG, "Server accepted credentials");
            return true;
        } else if (reply == 401) {
            Log.e(TAG, "Server authentication failed");
            return false;
        } else {
            Log.w(TAG, "Generic error: server reply " + reply);
            return false;
        }
        // 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(), e);
    } catch (final IOException e) {
        Log.e(TAG, "I/O exception while checking credentials " + e.getMessage(), e);
    }
    return false;
}

From source file:com.example.bookstoremb.utils.RestClient.java

/**
 * create authorization for header of request
 * //from w  ww .  j  a  v  a  2  s. c  o m
 * @return
 */
private String getAuthorization() {
    return "Basic "
            + Base64.encodeToString((Constants.USERNAME + ":" + Constants.PASSWORD).getBytes(), Base64.NO_WRAP);
}

From source file:com.bourke.kitchentimer.utils.Utils.java

public static void notifyServer(final String serverUrl) {
    new Thread(new Runnable() {
        @Override// ww  w .j  a  va2 s  .c o  m
        public void run() {
            try {
                Log.d("Utils", "notifyServer:" + serverUrl);
                DefaultHttpClient httpclient = new DefaultHttpClient();
                HttpGet httpget = new HttpGet(serverUrl);

                URL url = new URL(serverUrl);
                String userInfo = url.getUserInfo();
                if (userInfo != null) {
                    httpget.addHeader("Authorization",
                            "Basic " + Base64.encodeToString(userInfo.getBytes(), Base64.NO_WRAP));
                }

                HttpResponse response = httpclient.execute(httpget);
                response.getEntity().getContent().close();
                httpclient.getConnectionManager().shutdown();

                int status = response.getStatusLine().getStatusCode();
                if (status < 200 || status > 299) {
                    throw new Exception(response.getStatusLine().toString());
                }
            } catch (Exception ex) {
                Log.e("Utils", "Error notifying server: ", ex);
            }
        }
    }).start();
}