Example usage for android.os Bundle getString

List of usage examples for android.os Bundle getString

Introduction

In this page you can find the example usage for android.os Bundle getString.

Prototype

@Nullable
public String getString(@Nullable String key) 

Source Link

Document

Returns the value associated with the given key, or null if no mapping of the desired type exists for the given key or a null value is explicitly associated with the key.

Usage

From source file:org.linkdroid.PostJob.java

/**
 * Posts the data to our webhook./*w w  w .  java  2  s.c o m*/
 * 
 * The HMAC field calculation notes:
 * <ol>
 * <li>The Extras.HMAC field is calculated from all the non Extras.STREAM
 * fields; this includes all the original bundle extra fields, plus the
 * linkdroid fields (e.g Extras.STREAM_MIME_TYPE, and including
 * Extras.STREAM_HMAC); the NONCE is NOT prepended to the input since it will
 * be somewhere in the data bundle.</li>
 * <li>The Extras.STREAM_HMAC field is calculated by digesting the concat of
 * the NONCE (first) and the actual binary data obtained from the
 * EXTRAS_STREAM uri; this STREAM_HMAC field (along with the other
 * Extras.STREAM_* fields) are added to the data bundle, which will also be
 * hmac'd.</li>
 * <li>If no hmac secret is set, then the NONCEs will not be set in the upload
 * </li>
 * </ol>
 * 
 * @param contentResolver
 * @param webhook
 * @param data
 * @throws UnsupportedEncodingException
 * @throws IOException
 * @throws InvalidKeyException
 * @throws NoSuchAlgorithmException
 */
public static void execute(ContentResolver contentResolver, Bundle webhook, Bundle data)
        throws UnsupportedEncodingException, IOException, InvalidKeyException, NoSuchAlgorithmException {

    // Set constants that may be used in this method.
    final String secret = webhook.getString(WebhookColumns.SECRET);

    // This is the multipart form object that will contain all the data bundle
    // extras; it also will include the data of the extra stream and any other
    // extra linkdroid specific field required.
    MultipartEntity entity = new MultipartEntity();

    // Do the calculations to create our nonce string, if necessary.
    String nonce = obtainNonce(webhook);

    // Add the nonce to the data bundle if we have it.
    if (nonce != null) {
        data.putString(Extras.NONCE, nonce);
    }

    // We have a stream of data, so we need to add that to the multipart form
    // upload with a possible HMAC.
    if (data.containsKey(Intent.EXTRA_STREAM)) {
        Uri mediaUri = (Uri) data.get(Intent.EXTRA_STREAM);

        // Open our mediaUri, base 64 encode it and add it to our multipart upload
        // entity.
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Base64OutputStream b64os = new Base64OutputStream(baos);
        InputStream is = contentResolver.openInputStream(mediaUri);
        byte[] bytes = new byte[1024];
        int count;
        while ((count = is.read(bytes)) != -1) {
            b64os.write(bytes, 0, count);
        }
        is.close();
        baos.close();
        b64os.close();
        final String base64EncodedString = new String(baos.toByteArray(), UTF8);
        entity.addPart(Extras.STREAM, new StringBody(base64EncodedString, UTF8_CHARSET));

        // Add the mimetype of the stream to the data bundle.
        final String mimeType = contentResolver.getType(mediaUri);
        if (mimeType != null) {
            data.putString(Extras.STREAM_MIME_TYPE, mimeType);
        }

        // Do the hmac calculation of the stream and add it to the data bundle.
        // NOTE: This hmac string will be included as part of the input to the
        // other Extras hmac.
        if (shouldDoHmac(webhook)) {
            InputStream inputStream = contentResolver.openInputStream(mediaUri);
            final String streamHmac = hmacSha1(inputStream, secret, nonce);
            inputStream.close();
            data.putString(Extras.STREAM_HMAC, streamHmac);
            Log.d(TAG, "STREAM_HMAC: " + streamHmac);
        }
    }

    // Calculate the Hmac for all the items by iterating over the data bundle
    // keys in order.
    if (shouldDoHmac(webhook)) {
        final String dataHmac = calculateBundleExtrasHmac(data, secret);
        data.putString(Extras.HMAC, dataHmac);
        Log.d(TAG, "HMAC: " + dataHmac);
    }

    // Dump all the data bundle keys into the form.
    for (String k : data.keySet()) {
        Object value = data.get(k);
        // If the value is null, the key will still be in the form, but with
        // an empty string as its value.
        if (value != null) {
            entity.addPart(k, new StringBody(value.toString(), UTF8_CHARSET));
        } else {
            entity.addPart(k, new StringBody("", UTF8_CHARSET));
        }
    }

    // Create the client and request, then populate it with our multipart form
    // upload entity as part of the POST request; finally post the form.
    final String webhookUri = webhook.getString(WebhookColumns.URI);
    final HttpClient client = new DefaultHttpClient();
    client.getParams().setParameter(USER_AGENT_KEY, USER_AGENT);
    final HttpPost request = new HttpPost(webhookUri);
    request.setEntity(entity);
    HttpResponse response = client.execute(request);
    switch (response.getStatusLine().getStatusCode()) {
    case HttpStatus.SC_OK:
    case HttpStatus.SC_CREATED:
    case HttpStatus.SC_ACCEPTED:
        break;
    default:
        throw new RuntimeException(response.getStatusLine().toString());
    }
}

From source file:Main.java

public static String encodeUrl(Bundle parameters) {
    if (parameters == null) {
        return "";
    }/*from   www .  j av a  2s  .  c o m*/

    StringBuilder sb = new StringBuilder();
    boolean first = true;
    for (String key : parameters.keySet()) {
        Object parameter = parameters.get(key);
        if (!(parameter instanceof String)) {
            continue;
        }

        if (first)
            first = false;
        else
            sb.append("&");
        sb.append(URLEncoder.encode(key) + "=" + URLEncoder.encode(parameters.getString(key)));
    }
    return sb.toString();
}

From source file:Main.java

@Deprecated
public static String encodeUrl(Bundle parameters) {
    if (parameters == null) {
        return "";
    }//  w w w  . j  a v  a  2  s . c  o  m

    StringBuilder sb = new StringBuilder();
    boolean first = true;
    for (String key : parameters.keySet()) {
        Object parameter = parameters.get(key);
        if (!(parameter instanceof String)) {
            continue;
        }

        if (first)
            first = false;
        else
            sb.append("&");
        sb.append(URLEncoder.encode(key) + "=" + URLEncoder.encode(parameters.getString(key)));
    }
    return sb.toString();
}

From source file:com.facebook.LegacyTokenHelper.java

public static String getToken(Bundle bundle) {
    Validate.notNull(bundle, "bundle");
    return bundle.getString(TOKEN_KEY);
}

From source file:com.facebook.LegacyTokenHelper.java

public static String getApplicationId(Bundle bundle) {
    Validate.notNull(bundle, "bundle");
    return bundle.getString(APPLICATION_ID_KEY);
}

From source file:de.evilbrain.sendtosftp.config.java

private static JSONObject getJsonFromIntent(Intent intent, String intentKey) {
    // Vars//from   w ww.  ja va  2 s  .co  m
    JSONObject jsonObject = null;

    // get extras
    final Bundle extras = intent.getExtras();
    if (extras != null) {

        try {
            String jsonString = extras.getString(intentKey);

            if (jsonString == null)
                jsonString = "{}";
            jsonObject = new JSONObject(jsonString);

        } catch (JSONException e) {
            e.printStackTrace();
            jsonObject = new JSONObject();
        }

    } else {
        jsonObject = new JSONObject();
    }

    return jsonObject;
}

From source file:jp.sonymusicstudio.cast.castcompanionlibrary.utils.Utils.java

/**
 * Builds and returns a {@link MediaInfo} that was wrapped in a {@link Bundle} by
 * <code>mediaInfoToBundle</code>. It is assumed that the type of the {@link MediaInfo} is
 * {@code MediaMetaData.MEDIA_TYPE_MOVIE}
 *
 * @see <code>mediaInfoToBundle()</code>
 *//*  www.ja  v  a2 s .c o  m*/
public static MediaInfo bundleToMediaInfo(Bundle wrapper) {
    if (wrapper == null) {
        return null;
    }

    MediaMetadata metaData = new MediaMetadata(wrapper.getInt(KEY_MEDIA_TYPE));

    metaData.putString(MediaMetadata.KEY_SUBTITLE, wrapper.getString(MediaMetadata.KEY_SUBTITLE));
    metaData.putString(MediaMetadata.KEY_TITLE, wrapper.getString(MediaMetadata.KEY_TITLE));
    metaData.putString(MediaMetadata.KEY_STUDIO, wrapper.getString(MediaMetadata.KEY_STUDIO));
    metaData.putString(MediaMetadata.KEY_ALBUM_ARTIST, wrapper.getString(MediaMetadata.KEY_ALBUM_ARTIST));
    metaData.putString(MediaMetadata.KEY_ALBUM_TITLE, wrapper.getString(MediaMetadata.KEY_ALBUM_TITLE));
    metaData.putString(MediaMetadata.KEY_COMPOSER, wrapper.getString(MediaMetadata.KEY_COMPOSER));
    metaData.putString(MediaMetadata.KEY_SERIES_TITLE, wrapper.getString(MediaMetadata.KEY_SERIES_TITLE));

    metaData.putInt(MediaMetadata.KEY_SEASON_NUMBER, wrapper.getInt(MediaMetadata.KEY_SEASON_NUMBER));
    metaData.putInt(MediaMetadata.KEY_EPISODE_NUMBER, wrapper.getInt(MediaMetadata.KEY_EPISODE_NUMBER));

    long releaseDateMillis = wrapper.getLong(MediaMetadata.KEY_RELEASE_DATE, 0);
    if (releaseDateMillis > 0) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(releaseDateMillis);
        metaData.putDate(MediaMetadata.KEY_RELEASE_DATE, calendar);
    }

    ArrayList<String> images = wrapper.getStringArrayList(KEY_IMAGES);
    if (images != null && !images.isEmpty()) {
        for (String url : images) {
            Uri uri = Uri.parse(url);
            metaData.addImage(new WebImage(uri));
        }
    }

    String customDataStr = wrapper.getString(KEY_CUSTOM_DATA);
    JSONObject customData = null;
    if (!TextUtils.isEmpty(customDataStr)) {
        try {
            customData = new JSONObject(customDataStr);
        } catch (JSONException e) {
            LOGE(TAG, "Failed to deserialize the custom data string: custom data= " + customDataStr);
        }
    }

    List<MediaTrack> mediaTracks = null;
    if (wrapper.getString(KEY_TRACKS_DATA) != null) {
        try {
            JSONArray jsonArray = new JSONArray(wrapper.getString(KEY_TRACKS_DATA));
            mediaTracks = new ArrayList<MediaTrack>();

            if (jsonArray.length() > 0) {
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsonObj = (JSONObject) jsonArray.get(i);
                    MediaTrack.Builder builder = new MediaTrack.Builder(jsonObj.getLong(KEY_TRACK_ID),
                            jsonObj.getInt(KEY_TRACK_TYPE));
                    if (jsonObj.has(KEY_TRACK_NAME)) {
                        builder.setName(jsonObj.getString(KEY_TRACK_NAME));
                    }
                    if (jsonObj.has(KEY_TRACK_SUBTYPE)) {
                        builder.setSubtype(jsonObj.getInt(KEY_TRACK_SUBTYPE));
                    }
                    if (jsonObj.has(KEY_TRACK_CONTENT_ID)) {
                        builder.setContentType(jsonObj.getString(KEY_TRACK_CONTENT_ID));
                    }
                    if (jsonObj.has(KEY_TRACK_LANGUAGE)) {
                        builder.setLanguage(jsonObj.getString(KEY_TRACK_LANGUAGE));
                    }
                    if (jsonObj.has(KEY_TRACKS_DATA)) {
                        builder.setCustomData(new JSONObject(jsonObj.getString(KEY_TRACKS_DATA)));
                    }
                    mediaTracks.add(builder.build());
                }
            }

        } catch (JSONException e) {
            LOGE(TAG, "Failed to build media tracks from the wrapper bundle", e);
        }
    }
    MediaInfo.Builder mediaBuilder = new MediaInfo.Builder(wrapper.getString(KEY_URL))
            .setStreamType(wrapper.getInt(KEY_STREAM_TYPE)).setContentType(wrapper.getString(KEY_CONTENT_TYPE))
            .setMetadata(metaData).setCustomData(customData).setMediaTracks(mediaTracks);

    if (wrapper.containsKey(KEY_STREAM_DURATION) && wrapper.getLong(KEY_STREAM_DURATION) >= 0) {
        mediaBuilder.setStreamDuration(wrapper.getLong(KEY_STREAM_DURATION));
    }

    return mediaBuilder.build();
}

From source file:com.ocp.picasa.PicasaApi.java

public static AuthAccount[] getAuthenticatedAccounts(Context context) {
    AccountManager accountManager = AccountManager.get(context);
    Account[] accounts = getAccounts(context);
    if (accounts == null)
        accounts = new Account[0];
    int numAccounts = accounts.length;

    ArrayList<AuthAccount> authAccounts = new ArrayList<AuthAccount>(numAccounts);
    for (int i = 0; i != numAccounts; ++i) {
        Account account = accounts[i];//  w  w w .  ja va2 s  .c  o m
        String authToken;
        try {
            // Get the token without user interaction.
            authToken = accountManager.blockingGetAuthToken(account, PicasaService.SERVICE_NAME, true);

            // TODO: Remove this once the build is signed by Google, since
            // we will always have permission.
            // This code requests permission from the user explicitly.
            if (context instanceof Activity) {
                Bundle bundle = accountManager
                        .getAuthToken(account, PicasaService.SERVICE_NAME, null, (Activity) context, null, null)
                        .getResult();
                authToken = bundle.getString("authtoken");
                PicasaService.requestSync(context, PicasaService.TYPE_USERS_ALBUMS, -1);
            }

            // Add the account information to the list of accounts.
            if (authToken != null) {
                String username = canonicalizeUsername(account.name);
                authAccounts.add(new AuthAccount(username, authToken, account));
            }
        } catch (OperationCanceledException e) {
        } catch (IOException e) {
        } catch (AuthenticatorException e) {
        } catch (Exception e) {
            ;
        }
    }
    AuthAccount[] authArray = new AuthAccount[authAccounts.size()];
    authAccounts.toArray(authArray);
    return authArray;
}

From source file:com.mb.android.playbackmediator.utils.Utils.java

/**
 * Builds and returns a {@link MediaInfo} that was wrapped in a {@link Bundle} by
 * <code>fromMediaInfo</code>.
 *
 * @param wrapper/*from  w  ww .j  av  a  2 s .  c  o m*/
 * @return
 * @see <code>fromMediaInfo()</code>
 */
public static MediaInfo toMediaInfo(Bundle wrapper) {
    if (null == wrapper) {
        return null;
    }

    MediaMetadata metaData = new MediaMetadata(MediaMetadata.MEDIA_TYPE_MOVIE);

    metaData.putString(MediaMetadata.KEY_SUBTITLE, wrapper.getString(MediaMetadata.KEY_SUBTITLE));
    metaData.putString(MediaMetadata.KEY_TITLE, wrapper.getString(MediaMetadata.KEY_TITLE));
    metaData.putString(MediaMetadata.KEY_STUDIO, wrapper.getString(MediaMetadata.KEY_STUDIO));
    ArrayList<String> images = wrapper.getStringArrayList(KEY_IMAGES);
    if (null != images && !images.isEmpty()) {
        for (String url : images) {
            Uri uri = Uri.parse(url);
            metaData.addImage(new WebImage(uri));
        }
    }
    String customDataStr = wrapper.getString(KEY_CUSTOM_DATA);
    JSONObject customData = null;
    if (!TextUtils.isEmpty(customDataStr)) {
        try {
            customData = new JSONObject(customDataStr);
        } catch (JSONException e) {
            LOGE(TAG, "Failed to deserialize the custom data string: custom data= " + customDataStr);
        }
    }
    return new MediaInfo.Builder(wrapper.getString(KEY_URL)).setStreamType(wrapper.getInt(KEY_STREAM_TYPE))
            .setContentType(wrapper.getString(KEY_CONTENT_TYPE)).setMetadata(metaData).setCustomData(customData)
            .setStreamDuration(wrapper.getLong(KEY_STREAM_DURATION)).build();
}

From source file:com.facebook.AccessToken.java

/**
 * Creates a new AccessToken using the information contained in an Intent populated by the
 * Facebook application in order to launch a native link. For more information on native
 * linking, please see https://developers.facebook.com/docs/mobile/android/deep_linking/.
 *
 * @param intent        the Intent that was used to start an Activity; must not be null
 * @param applicationId the ID of the Facebook Application associated with this access token
 *///from   w  w  w .  j  av  a2s  . co  m
public static void createFromNativeLinkingIntent(Intent intent, final String applicationId,
        final AccessTokenCreationCallback accessTokenCallback) {
    Validate.notNull(intent, "intent");
    if (intent.getExtras() == null) {
        accessTokenCallback.onError(new FacebookException("No extras found on intent"));
        return;
    }
    final Bundle extras = new Bundle(intent.getExtras());

    String accessToken = extras.getString(ACCESS_TOKEN_KEY);
    if (accessToken == null || accessToken.isEmpty()) {
        accessTokenCallback.onError(new FacebookException("No access token found on intent"));
        return;
    }

    String userId = extras.getString(USER_ID_KEY);
    // Old versions of facebook for android don't provide the UserId. Obtain the id if missing
    if (userId == null || userId.isEmpty()) {
        Utility.getGraphMeRequestWithCacheAsync(accessToken, new Utility.GraphMeRequestWithCacheCallback() {
            @Override
            public void onSuccess(JSONObject userInfo) {
                try {
                    String userId = userInfo.getString("id");
                    extras.putString(USER_ID_KEY, userId);
                    accessTokenCallback.onSuccess(createFromBundle(null, extras,
                            AccessTokenSource.FACEBOOK_APPLICATION_WEB, new Date(), applicationId));
                } catch (JSONException ex) {
                    accessTokenCallback.onError(
                            new FacebookException("Unable to generate access token due to missing user id"));
                }

            }

            @Override
            public void onFailure(FacebookException error) {
                accessTokenCallback.onError(error);
            }
        });
    } else {
        accessTokenCallback.onSuccess(createFromBundle(null, extras, AccessTokenSource.FACEBOOK_APPLICATION_WEB,
                new Date(), applicationId));
    }
}