Example usage for android.util Base64 encode

List of usage examples for android.util Base64 encode

Introduction

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

Prototype

public static byte[] encode(byte[] input, int flags) 

Source Link

Document

Base64-encode the given data and return a newly allocated byte[] with the result.

Usage

From source file:no.ntnu.idi.socialhitchhiking.myAccount.MyAccountCar.java

/**
 * Displaying the car information in the layout.
 * @param res/*from w  w  w. j av a  2 s  .  c om*/
 */
public void showMain(CarResponse res, PreferenceResponse prefResInit) {
    // Initializing the views
    setContentView(R.layout.my_account_car);
    this.imageView = (ImageView) this.findViewById(R.id.cameraView);
    carName = (EditText) this.findViewById(R.id.carName);
    bar = (RatingBar) this.findViewById(R.id.ratingBar1);
    seatsText = (EditText) this.findViewById(R.id.myAccountCarSeats);

    // Setting the number of seats available
    prefRes = prefResInit;
    seatsAvailable = prefRes.getPreferences().getSeatsAvailable();
    if (seatsAvailable > 0) {
        seatsText.setText(seatsAvailable.toString());
    } else {
        seatsText.setText("");
    }

    // If the user does have a car registered
    if (user.getCarId() != 0) {
        // Setting the car name
        carNameString = res.getCar().getCarName();
        // Setting the car ID
        id = res.getCar().getCarId();
        // Setting the comfort
        comfort = (float) res.getCar().getComfort();
        // Getting the car image
        byteArray = res.getCar().getPhoto();

        /*Values of the car from database*/

        // Display these values to the user
        carName.setText(carNameString);
        bar.setRating(comfort);

        String empty = "No car type set";
        byteArrayx = empty.getBytes();
        // If a new image is set, display it
        if (byteArray.length > 15) {
            if (!(res.getCar().getPhotoAsBase64().equals(Base64.encode(byteArrayx, Base64.URL_SAFE)))) {
                btm = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
                imageView.setImageBitmap(btm);
            }
        }
        // Indicates that the car is initialized
        isCarInitialized = true;
    }
    //if user does not yet have a car registated
    else {
        carNameString = "";
        id = -1;
        comfort = 0.0f;
        String empty = "No car type set";
        byteArray = empty.getBytes();
    }

    // Setting the button for taking a car picture
    Button photoButton = (Button) this.findViewById(R.id.cameraButton);
    photoButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            carChanged = true;
            Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, "tempName");
            cameraIntent.putExtra("return-data", true);
            startActivityForResult(cameraIntent, CAMERA_REQUEST);
        }
    });
    // Setting the button for getting a car picture from the phone
    Button getimageButton = (Button) this.findViewById(R.id.getimageButton);
    getimageButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            carChanged = true;
            Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
            photoPickerIntent.setType("image/*");
            startActivityForResult(photoPickerIntent, ALBUM_REQUEST);
        }
    });
}

From source file:com.chen.emailcommon.internet.Rfc822Output.java

/**
 * Write the body text.//from w ww  . j a  v a 2 s  .c om
 *
 * Note this always uses base64, even when not required.  Slightly less efficient for
 * US-ASCII text, but handles all formats even when non-ascii chars are involved.  A small
 * optimization might be to prescan the string for safety and send raw if possible.
 *
 * @param writer the output writer
 * @param out the output stream inside the writer (used for byte[] access)
 * @param bodyText Plain text and HTML versions of the original text of the message
 */
private static void writeTextWithHeaders(Writer writer, OutputStream out, String[] bodyText)
        throws IOException {
    boolean html = false;
    String text = bodyText[INDEX_BODY_TEXT];
    if (text == null) {
        text = bodyText[INDEX_BODY_HTML];
        html = true;
    }
    if (text == null) {
        writer.write("\r\n"); // a truly empty message
    } else {
        // first multipart element is the body
        String mimeType = "text/" + (html ? "html" : "plain");
        writeHeader(writer, "Content-Type", mimeType + "; charset=utf-8");
        writeHeader(writer, "Content-Transfer-Encoding", "base64");
        writer.write("\r\n");
        byte[] textBytes = text.getBytes("UTF-8");
        writer.flush();
        out.write(Base64.encode(textBytes, Base64.CRLF));
    }
}

From source file:com.mail163.email.mail.transport.Rfc822Output.java

/**
 * Write text (either as main body or inside a multipart), preceded by appropriate headers.
 *
 * Note this always uses base64, even when not required.  Slightly less efficient for
 * US-ASCII text, but handles all formats even when non-ascii chars are involved.  A small
 * optimization might be to prescan the string for safety and send raw if possible.
 *
 * @param writer the output writer/*from   w w  w .j  a v a2s .com*/
 * @param out the output stream inside the writer (used for byte[] access)
 * @param text The original text of the message
 */
private static void writeTextWithHeaders(Writer writer, OutputStream out, String text) throws IOException {
    Logs.v(Logs.LOG_MessageView, "isContentType >>>>>>>>> :" + isContentType);

    //=============2012.3.4===========
    if (isContentType) {//Content-Type
        writeHeader(writer, "Content-Type", "text/html; charset=utf-8");
    } else {
        writeHeader(writer, "Content-Type", "text/plain; charset=utf-8");
    }

    //=============2012.3.4===========
    writeHeader(writer, "Content-Transfer-Encoding", "base64");
    writer.write("\r\n");
    byte[] bytes = text.getBytes("UTF-8");
    writer.flush();
    out.write(Base64.encode(bytes, Base64.CRLF));
}

From source file:com.android.emailcommon.internet.Rfc822Output.java

/**
 * Write the body text. If only one version of the body is specified (either plain text
 * or HTML), the text is written directly. Otherwise, the plain text and HTML bodies
 * are both written with the appropriate headers.
 *
 * Note this always uses base64, even when not required.  Slightly less efficient for
 * US-ASCII text, but handles all formats even when non-ascii chars are involved.  A small
 * optimization might be to prescan the string for safety and send raw if possible.
 *
 * @param writer the output writer//from w w  w  .  jav a2 s . co  m
 * @param out the output stream inside the writer (used for byte[] access)
 * @param bodyText Plain text and HTML versions of the original text of the message
 */
private static void writeTextWithHeaders(Writer writer, OutputStream out, String[] bodyText)
        throws IOException {
    String text = bodyText[INDEX_BODY_TEXT];
    String html = bodyText[INDEX_BODY_HTML];

    if (text == null) {
        writer.write("\r\n"); // a truly empty message
    } else {
        String multipartBoundary = null;
        boolean multipart = html != null;

        // Simplified case for no multipart - just emit text and be done.
        if (multipart) {
            // continue with multipart headers, then into multipart body
            multipartBoundary = getNextBoundary();

            writeHeader(writer, "Content-Type",
                    "multipart/alternative; boundary=\"" + multipartBoundary + "\"");
            // Finish headers and prepare for body section(s)
            writer.write("\r\n");
            writeBoundary(writer, multipartBoundary, false);
        }

        // first multipart element is the body
        writeHeader(writer, "Content-Type", "text/plain; charset=utf-8");
        writeHeader(writer, "Content-Transfer-Encoding", "base64");
        writer.write("\r\n");
        byte[] textBytes = text.getBytes("UTF-8");
        writer.flush();
        out.write(Base64.encode(textBytes, Base64.CRLF));

        if (multipart) {
            // next multipart section
            writeBoundary(writer, multipartBoundary, false);

            writeHeader(writer, "Content-Type", "text/html; charset=utf-8");
            writeHeader(writer, "Content-Transfer-Encoding", "base64");
            writer.write("\r\n");
            byte[] htmlBytes = html.getBytes("UTF-8");
            writer.flush();
            out.write(Base64.encode(htmlBytes, Base64.CRLF));

            // end of multipart section
            writeBoundary(writer, multipartBoundary, true);
        }
    }
}

From source file:com.madrobot.net.client.XMLRPCClient.java

/**
 * Call method with optional parameters. This is general method. If you want to call your method with 0-8
 * parameters, you can use more convenience call() methods
 * /*from   ww  w. j  ava 2s  .c o  m*/
 * @param method
 *            name of method to call
 * @param params
 *            parameters to pass to method (may be null if method has no parameters)
 * @return deserialized method return value
 * @throws XMLRPCException
 */
@SuppressWarnings("unchecked")
public Object callEx(String method, Object[] params) throws XMLRPCException {
    try {
        // prepare POST body
        String body = methodCall(method, params);

        // set POST body
        HttpEntity entity = new StringEntity(body);
        postMethod.setEntity(entity);

        // This code slightly tweaked from the code by erickok in issue #6
        // Force preemptive authentication
        // This makes sure there is an 'Authentication: ' header being send before trying and failing and retrying
        // by the basic authentication mechanism of DefaultHttpClient
        if (this.httpPreAuth == true) {
            String auth = this.username + ":" + this.password;
            postMethod.addHeader("Authorization",
                    "Basic " + Base64.encode(auth.getBytes(), Base64.DEFAULT).toString());
        }

        // Log.d(Tag.LOG, "ros HTTP POST");
        // execute HTTP POST request
        HttpResponse response = client.execute(postMethod);
        // Log.d(Tag.LOG, "ros HTTP POSTed");

        // check status code
        int statusCode = response.getStatusLine().getStatusCode();
        // Log.d(Tag.LOG, "ros status code:" + statusCode);
        if (statusCode != HttpStatus.SC_OK) {
            throw new XMLRPCException("HTTP status code: " + statusCode + " != " + HttpStatus.SC_OK);
        }

        // parse response stuff
        //
        // setup pull parser
        XmlPullParser pullParser = XmlPullParserFactory.newInstance().newPullParser();
        entity = response.getEntity();
        Reader reader = new InputStreamReader(new BufferedInputStream(entity.getContent()));
        // for testing purposes only
        // reader = new
        // StringReader("<?xml version='1.0'?><methodResponse><params><param><value>\n\n\n</value></param></params></methodResponse>");
        pullParser.setInput(reader);

        // lets start pulling...
        pullParser.nextTag();
        pullParser.require(XmlPullParser.START_TAG, null, Tag.METHOD_RESPONSE);

        pullParser.nextTag(); // either Tag.PARAMS (<params>) or Tag.FAULT (<fault>)
        String tag = pullParser.getName();
        if (tag.equals(Tag.PARAMS)) {
            // normal response
            pullParser.nextTag(); // Tag.PARAM (<param>)
            pullParser.require(XmlPullParser.START_TAG, null, Tag.PARAM);
            pullParser.nextTag(); // Tag.VALUE (<value>)
            // no parser.require() here since its called in XMLRPCSerializer.deserialize() below

            // deserialize result
            Object obj = iXMLRPCSerializer.deserialize(pullParser);
            entity.consumeContent();
            return obj;
        } else if (tag.equals(Tag.FAULT)) {
            // fault response
            pullParser.nextTag(); // Tag.VALUE (<value>)
            // no parser.require() here since its called in XMLRPCSerializer.deserialize() below

            // deserialize fault result
            Map<String, Object> map = (Map<String, Object>) iXMLRPCSerializer.deserialize(pullParser);
            String faultString = (String) map.get(Tag.FAULT_STRING);
            int faultCode = (Integer) map.get(Tag.FAULT_CODE);
            entity.consumeContent();
            throw new XMLRPCFault(faultString, faultCode);
        } else {
            entity.consumeContent();
            throw new XMLRPCException(
                    "Bad tag <" + tag + "> in XMLRPC response - neither <params> nor <fault>");
        }
    } catch (XMLRPCException e) {
        // catch & propagate XMLRPCException/XMLRPCFault
        throw e;
    } catch (Exception e) {
        e.printStackTrace();
        // wrap any other Exception(s) around XMLRPCException
        throw new XMLRPCException(e);
    }
}

From source file:jp.app_mart.billing.AppmartHelper.java

/**
 * ?//from ww w  .  jav a2s.com
 * @param serviceId
 * @param developId
 * @param strLicenseKey
 * @param strPublicKey
 * @return
 */
public static String createEncryptedData(String serviceId, String developId, String strLicenseKey,
        String strPublicKey) {
    final String SEP_SYMBOL = "&";
    StringBuilder infoDataSB = new StringBuilder();
    infoDataSB.append(serviceId).append(SEP_SYMBOL);
    // ?ID 
    infoDataSB.append(developId).append(SEP_SYMBOL);
    // 
    infoDataSB.append(strLicenseKey);
    String strEncryInfoData = "";
    try {
        KeyFactory keyFac = KeyFactory.getInstance("RSA");
        KeySpec keySpec = new X509EncodedKeySpec(Base64.decode(strPublicKey.getBytes(), Base64.DEFAULT));
        Key publicKey = keyFac.generatePublic(keySpec);
        if (publicKey != null) {
            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            byte[] EncryInfoData = cipher.doFinal(infoDataSB.toString().getBytes());
            strEncryInfoData = new String(Base64.encode(EncryInfoData, Base64.DEFAULT));
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        strEncryInfoData = "";
        Log.e("AppmartHelper", "?");
    }
    return strEncryInfoData.replaceAll("(\\r|\\n)", "");
}

From source file:com.jafme.mobile.activity.CropImageActivity.java

private void uploadImage(Bitmap croppedBitmap) {

    if (!needUpload) {

        final File file = new File(getCacheDir(), "wizard_avatar");
        final Uri fileUri = Uri.fromFile(file);
        OutputStream fileOutputStream = null;
        try {//from   ww w. j  a v a2 s . co  m
            fileOutputStream = getContentResolver().openOutputStream(fileUri);
            if (fileOutputStream == null)
                throw new IOException("Can't open output stream");
            if (croppedBitmap.compress(Bitmap.CompressFormat.JPEG, 90, fileOutputStream)) {
                fileOutputStream.flush();

                final Photo photo = new Photo(-1, fileUri.toString());
                setResultPhoto(photo, -1);

            }
        } catch (IOException e) {
            setResultException(e);
        } finally {
            CropUtil.closeSilently(fileOutputStream);
        }

    } else {

        long startTime = System.currentTimeMillis();

        ByteArrayOutputStream baos = null;
        try {

            // ??   JPG  baos
            baos = new ByteArrayOutputStream();
            if (!croppedBitmap.compress(Bitmap.CompressFormat.JPEG, 90, baos)) {
                throw new IOException("Can't compress photo");
            }
            baos.flush();

            // encod  base64
            final byte[] encodedJpgImage = Base64.encode(baos.toByteArray(), Base64.DEFAULT);
            final String base64Photo = new String(encodedJpgImage, "UTF-8");

            /*
            try {
               FileWriter fileWriter = new FileWriter(new File(getExternalFilesDir(null), "photo.base64"));
               fileWriter.write(base64Photo);
               fileWriter.close();
            } catch (IOException e) {
               e.printStackTrace();
            }
            */

            // ?   ?
            final JsonObject jsonRequest = new JsonObject();
            jsonRequest.addProperty("image_string", base64Photo);
            jsonRequest.addProperty("image_extension", "jpg");

            final ApiRest api = Api.getInstance(this);

            long vacancyId = 0;
            Response response;
            Photo photo;
            switch (type) {
            case TYPE_APPLICANT_PHOTO:
                response = api.uploadApplicantPhoto(jsonRequest);
                photo = Network.responseToObject(response, Photo.class, false);
                break;

            case TYPE_USER_AVATAR:
                response = api.uploadUserAvatar(jsonRequest);
                if (response == null)
                    throw new IOException("No response received");
                final int statusCode = response.getStatus();
                if (statusCode < 200 || statusCode >= 300)
                    throw new IOException(response.getReason());

                // HTTP 204 No content -   ? GET /user/avatar
                response = api.getUserAvatar();
                @SuppressWarnings("unchecked")
                Map<String, String> paths = Network.responseToObject(response, HashMap.class, false);
                photo = new Photo(paths);
                break;

            case TYPE_VACANCY_PHOTO:
                vacancyId = args != null ? args.getLong(ARG_VACANCY_ID, -1) : -1;
                boolean isPrimary = args != null && args.getBoolean(ARG_IS_PRIMARY);

                if (vacancyId == -1) {
                    // ? ?  ?

                    JsonObject jsonRequest2 = new JsonObject();
                    jsonRequest2.addProperty("position", getString(R.string.new_vacancy));

                    response = api.createEmployerVacancy(jsonRequest2);
                    Vacancy newVacancy = Network.responseToObject(response, Vacancy.class, false);

                    vacancyId = newVacancy.id;
                }

                jsonRequest.addProperty("is_primary", isPrimary);
                response = api.uploadVacancyPhoto(vacancyId, jsonRequest);
                photo = Network.responseToObject(response, Photo.class, false);

                break;

            default:
                throw new RuntimeException("Invalid photo type specified: " + type);
            }

            setResultPhoto(photo, vacancyId);

            long uploadTime = System.currentTimeMillis() - startTime;

            final Tracker tracker = ((JafmeApp) getApplication()).getDefaultTracker();
            tracker.send(new HitBuilders.TimingBuilder().setCategory("UX").setValue(uploadTime)
                    .setVariable("Photo upload").setLabel("Type: " + type).build());

        } catch (IOException | RetrofitError e) {
            e.printStackTrace();
            setResultException(e);
        } finally {
            CropUtil.closeSilently(baos);
        }

    }

    if (removeOriginal && "file".equals(sourceUri.getScheme())) {
        File file = new File(sourceUri.getPath());
        if (!file.delete()) {
            file.deleteOnExit();
        }
    }

    // ? bitmap  ?
    final Bitmap b = croppedBitmap;
    handler.post(new Runnable() {
        public void run() {
            imageView.clear();
            b.recycle();
        }
    });

    finish();
}

From source file:com.tct.emailcommon.internet.Rfc822Output.java

/**
 * Write the body text.// www.  j  a  v  a  2 s. c  o m
 *
 * Note this always uses base64, even when not required.  Slightly less efficient for
 * US-ASCII text, but handles all formats even when non-ascii chars are involved.  A small
 * optimization might be to prescan the string for safety and send raw if possible.
 *
 * @param writer the output writer
 * @param out the output stream inside the writer (used for byte[] access)
 * @param bodyText Plain text and HTML versions of the original text of the message
 */
private static void writeTextWithHeaders(Writer writer, OutputStream out, String[] bodyText,
        List<Attachment> atts) throws IOException {
    boolean html = false;
    String text = bodyText[INDEX_BODY_TEXT];
    // TS: zheng.zou 2015-03-31 EMAIL BUGFIX-962573 MOD_S
    String htmlText = bodyText[INDEX_BODY_HTML];
    if (TextUtils.isEmpty(text) || !TextUtils.isEmpty(htmlText)) {
        // TS: zheng.zou 2015-03-31 EMAIL BUGFIX-962573 MOD_E
        text = bodyText[INDEX_BODY_HTML];
        html = true;
    }
    //TS: zhaotianyong 2015-04-13 EMAIL BUGFIX_962560 ADD_S
    if (atts != null && html) {
        for (Attachment att : atts) {
            text = AttachmentUtilities.refactorHtmlBody(text, att);
        }
    }
    //TS: zhaotianyong 2015-04-13 EMAIL BUGFIX_962560 ADD_E
    if (TextUtils.isEmpty(text)) {
        writer.write("\r\n"); // a truly empty message
    } else {
        // first multipart element is the body
        final String mimeType = "text/" + (html ? "html" : "plain");
        writeHeader(writer, "Content-Type", mimeType + "; charset=utf-8");
        writeHeader(writer, "Content-Transfer-Encoding", "base64");
        writer.write("\r\n");
        final byte[] textBytes = text.getBytes("UTF-8");
        writer.flush();
        out.write(Base64.encode(textBytes, Base64.CRLF));
    }
}

From source file:es.javocsoft.android.lib.toucan.client.ToucanClient.java

/**
 * Gets the list of tags for the application and device Id.
 * /*  w ww.ja v a2s  .  c  om*/
 * @param callback A callback to run when operation finishes.
 */
public void doListTags(ResponseCallback callback) {
    try {
        String appHashSignature = generateSHA1(appPublicKey + apiToken);

        String urlParams = "dUId=" + toucanClient.deviceUniqueId + "&appPubKey=" + appPublicKey
                + "&appHashSignature=" + appHashSignature;
        String encodedUrlParams = new String(Base64.encode(urlParams.getBytes(), 0), "UTF-8");
        String urlEncodedUrlParams = URLEncoder.encode(encodedUrlParams, "UTF-8");

        String finalUrl = API_ENDPOINT_LIST_TAGS + "=" + urlEncodedUrlParams;

        if (callback != null)
            callback.setCallbackOperation(ResponseCallback.CALLBACK_OPERATION_LIST_TAGS);

        if (ToolBox.net_isNetworkAvailable(context)) {
            new ToucanGetWorker(context, apiToken, finalUrl, API_OPERATION_LIST_TAGS, callback).start();
        } else {
            cacheOperationRequest(
                    new ToucanGetWorker(context, apiToken, finalUrl, API_OPERATION_LIST_TAGS, callback), true);
        }

    } catch (Exception e) {
        Log.e(LOG_TAG, "Error doing operation " + API_OPERATION_LIST_TAGS.toUpperCase() + " to Toucan API ("
                + e.getMessage() + ")", e);
    }
}

From source file:es.javocsoft.android.lib.toucan.client.ToucanClient.java

/**
 * Un-registers a device from server. Avoiding delivering 
 * notifications to it.//from  w  w w. ja  v a 2 s . c o  m
 * 
 * @param callback   A callback to run when operation finishes.
 */
public void doDeviceUnregister(ResponseCallback callback) {
    try {
        String appHashSignature = generateSHA1(appPublicKey + apiToken);

        String urlParams = "dUId=" + toucanClient.deviceUniqueId + "&appPubKey=" + appPublicKey
                + "&appHashSignature=" + appHashSignature;
        String encodedUrlParams = new String(Base64.encode(urlParams.getBytes(), 0), "UTF-8");
        String urlEncodedUrlParams = URLEncoder.encode(encodedUrlParams, "UTF-8");

        String finalUrl = API_ENDPOINT_UNREGISTRATION + "=" + urlEncodedUrlParams;

        if (ToolBox.net_isNetworkAvailable(context)) {
            new ToucanGetWorker(context, apiToken, finalUrl, API_OPERATION_DEVICE_UNREGISTRATION, callback)
                    .start();
        } else {
            cacheOperationRequest(new ToucanGetWorker(context, apiToken, finalUrl,
                    API_OPERATION_DEVICE_UNREGISTRATION, callback), true);
        }

    } catch (Exception e) {
        Log.e(LOG_TAG, "Error doing operation " + API_OPERATION_DEVICE_UNREGISTRATION.toUpperCase()
                + " to Toucan API (" + e.getMessage() + ")", e);
    }
}