Example usage for android.net Uri getQueryParameter

List of usage examples for android.net Uri getQueryParameter

Introduction

In this page you can find the example usage for android.net Uri getQueryParameter.

Prototype

@Nullable
public String getQueryParameter(String key) 

Source Link

Document

Searches the query string for the first value with the given key.

Usage

From source file:org.tweetalib.android.model.TwitterMediaEntity.java

private static String getYouTubeUrl(String url) {

    String lowerCaseUrl = url.toLowerCase();
    if (lowerCaseUrl.indexOf("youtube.com/watch?") > -1) {
        Uri uri = Uri.parse(url);
        String videoId = uri.getQueryParameter("v");
        if (videoId != null) {
            return videoId;
        }/*from   www.  j  a  v  a2s .  co  m*/
    }

    String prefix = "youtu.be/";
    int startIndex = lowerCaseUrl.indexOf(prefix);
    if (startIndex > -1) {
        startIndex += prefix.length();
        int endIndex = lowerCaseUrl.indexOf('?', startIndex);
        if (endIndex > -1) {
            return url.substring(startIndex, endIndex);
        } else {
            return url.substring(startIndex);
        }
    }

    return null;
}

From source file:air.com.snagfilms.utils.Utils.java

public static Map<String, String> getReferrerMapFromUri(Uri uri) {
    MapBuilder paramMap = new MapBuilder();
    // If no URI, return an empty Map.
    if (uri == null) {
        return paramMap.build();
    }/*from   w w w .  ja v  a 2s  .  co m*/
    // Source is the only required campaign field. No need to continue if
    // not
    // present.
    if (uri.getQueryParameter(AnalyticsAPI.CAMPAIGN_SOURCE_PARAM) != null) {
        // MapBuilder.setCampaignParamsFromUrl parses Google Analytics
        // campaign
        // ("UTM") parameters from a string URL into a Map that can be set
        // on
        // the Tracker.
        paramMap.setCampaignParamsFromUrl(uri.toString());
        // If no source parameter, set authority to source and medium to
        // "referral".
    } else if (uri.getAuthority() != null) {
        paramMap.set(Fields.CAMPAIGN_MEDIUM, "referral");
        paramMap.set(Fields.CAMPAIGN_SOURCE, uri.getAuthority());
    }

    return paramMap.build();
}

From source file:org.quantumbadger.redreader.reddit.api.RedditOAuth.java

private static FetchRefreshTokenResult fetchRefreshTokenSynchronous(final Context context,
        final Uri redirectUri) {

    final String error = redirectUri.getQueryParameter("error");

    if (error != null) {

        if (error.equals("access_denied")) {
            return new FetchRefreshTokenResult(FetchRefreshTokenResultStatus.USER_REFUSED_PERMISSION,
                    new RRError(context.getString(R.string.error_title_login_user_denied_permission),
                            context.getString(R.string.error_message_login_user_denied_permission)));

        } else {//from ww  w. j av a2 s  .c o  m
            return new FetchRefreshTokenResult(FetchRefreshTokenResultStatus.INVALID_REQUEST,
                    new RRError(context.getString(R.string.error_title_login_unknown_reddit_error) + error,
                            context.getString(R.string.error_unknown_message)));
        }
    }

    final String code = redirectUri.getQueryParameter("code");

    if (code == null) {
        return new FetchRefreshTokenResult(FetchRefreshTokenResultStatus.INVALID_RESPONSE,
                new RRError(context.getString(R.string.error_unknown_title),
                        context.getString(R.string.error_unknown_message)));
    }

    final String uri = ACCESS_TOKEN_URL;
    StatusLine responseStatus = null;

    try {
        final HttpClient httpClient = CacheManager.createHttpClient(context);

        final HttpPost request = new HttpPost(uri);

        final ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
        nameValuePairs.add(new BasicNameValuePair("grant_type", "authorization_code"));
        nameValuePairs.add(new BasicNameValuePair("code", code));
        nameValuePairs.add(new BasicNameValuePair("redirect_uri", REDIRECT_URI));
        request.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        request.addHeader("Authorization", "Basic "
                + Base64.encodeToString((CLIENT_ID + ":").getBytes(), Base64.URL_SAFE | Base64.NO_WRAP));

        final HttpResponse response = httpClient.execute(request);
        responseStatus = response.getStatusLine();

        if (responseStatus.getStatusCode() != 200) {
            return new FetchRefreshTokenResult(FetchRefreshTokenResultStatus.UNKNOWN_ERROR,
                    new RRError(context.getString(R.string.error_unknown_title),
                            context.getString(R.string.message_cannotlogin), null, responseStatus,
                            request.getURI().toString()));
        }

        final JsonValue jsonValue = new JsonValue(response.getEntity().getContent());
        jsonValue.buildInThisThread();
        final JsonBufferedObject responseObject = jsonValue.asObject();

        final RefreshToken refreshToken = new RefreshToken(responseObject.getString("refresh_token"));
        final AccessToken accessToken = new AccessToken(responseObject.getString("access_token"));

        return new FetchRefreshTokenResult(refreshToken, accessToken);

    } catch (IOException e) {
        return new FetchRefreshTokenResult(FetchRefreshTokenResultStatus.CONNECTION_ERROR,
                new RRError(context.getString(R.string.error_connection_title),
                        context.getString(R.string.error_connection_message), e, responseStatus, uri));

    } catch (Throwable t) {
        return new FetchRefreshTokenResult(FetchRefreshTokenResultStatus.UNKNOWN_ERROR,
                new RRError(context.getString(R.string.error_unknown_title),
                        context.getString(R.string.error_unknown_message), t, responseStatus, uri));
    }
}

From source file:com.playhaven.android.data.DataCollectionField.java

public static ArrayList<DataCollectionField> fromUrl(Uri uri) throws PlayHavenException {
    ArrayList<DataCollectionField> toReturn = new ArrayList<DataCollectionField>();
    if (uri == null)
        return toReturn;

    for (String paramKey : getQueryParameterNames(uri)) {
        if (paramKey.equals("dcDataCallback"))
            continue;
        if (paramKey.equals("_"))
            continue;
        toReturn.add(new DataCollectionField(String.format("{\"name\":\"%s\", \"value\":\"%s\"}", paramKey,
                uri.getQueryParameter(paramKey))));
    }//from  ww  w  . j a v a 2s . c  o  m

    return toReturn;
}

From source file:com.popdeem.sdk.core.PopdeemSDK.java

/**
 * Process a referral if one is present.
 *
 * @param context Application context//from  ww w  . j av a2s .  co  m
 * @param intent  Incoming intent
 */
public static void processReferral(Context context, Intent intent) {
    if (intent != null && intent.getData() != null) {
        // Compare schemes
        String scheme = context.getString(R.string.facebook_url_scheme);
        String schemeFromIntent = intent.getData().getScheme();
        if (!scheme.equalsIgnoreCase(schemeFromIntent)) {
            // Schemes are not the same, ignore the intent data.
            return;
        }

        Bundle appLinkData = AppLinks.getAppLinkData(intent);
        if (appLinkData != null) {
            //                PDLog.d(PopdeemSDK.class, "appLinkData: " + appLinkData.toString());
            PDRealmReferral referral = new PDRealmReferral();
            referral.setId(0); // Always 0. Only used for storage as we only want to save one referral at a time.
            referral.setType("open");
            referral.setSenderAppName("");
            referral.setSenderId(-1);
            referral.setRequestId(-1);

            Bundle referrerBundle = appLinkData.getBundle("referer_app_link");
            if (referrerBundle != null && referrerBundle.containsKey("app_name")) {
                referral.setSenderAppName(referrerBundle.getString("app_name", ""));
            }

            Uri data = intent.getData();
            if (data != null) {
                referral.setSenderId(PDNumberUtils.toLong(data.getQueryParameter("user_id"), -1));
            }

            Uri targetUri = AppLinks.getTargetUrlFromInboundIntent(context, intent);
            int requestId = PDReferralUtils.getRequestIdFromUrl(targetUri);
            referral.setRequestId(requestId);

            // Save PDReferral
            Realm realm = Realm.getDefaultInstance();
            realm.beginTransaction();
            realm.copyToRealmOrUpdate(referral);
            realm.commitTransaction();

            // Send Referral in Update call if logged in
            PDRealmUserDetails userDetails = realm.where(PDRealmUserDetails.class).findFirst();
            if (userDetails == null) {
                return;
            }

            PDRealmGCM gcm = realm.where(PDRealmGCM.class).findFirst();
            String deviceToken = gcm == null ? "" : gcm.getRegistrationToken();

            PDRealmUserLocation userLocation = realm.where(PDRealmUserLocation.class).findFirst();
            String lat = "", lng = "";
            if (userLocation != null) {
                lat = String.valueOf(userLocation.getLatitude());
                lng = String.valueOf(userLocation.getLongitude());
            }

            PDAPIClient.instance().updateUserLocationAndDeviceToken("", userDetails.getId(), deviceToken, lat,
                    lng, new PDAPICallback<PDUser>() {
                        @Override
                        public void success(PDUser user) {
                            PDUtils.updateSavedUser(user);
                        }

                        @Override
                        public void failure(int statusCode, Exception e) {

                        }
                    });

            realm.close();
        }
    }
}

From source file:com.google.samples.apps.iosched.ui.SessionLivestreamActivity.java

public static String getVideoIdFromUrl(String youtubeUrl) {
    if (!TextUtils.isEmpty(youtubeUrl) && youtubeUrl.startsWith("http")) {
        Uri youTubeUri = Uri.parse(youtubeUrl);
        return youTubeUri.getQueryParameter("v");
    }//  w  w  w  .  j av a  2 s.  c o  m
    return youtubeUrl;
}

From source file:android.webkit.cts.CtsTestServer.java

private static HttpResponse createTestDownloadResponse(Uri uri) throws IOException {
    String downloadId = uri.getQueryParameter(DOWNLOAD_ID_PARAMETER);
    int numBytes = uri.getQueryParameter(NUM_BYTES_PARAMETER) != null
            ? Integer.parseInt(uri.getQueryParameter(NUM_BYTES_PARAMETER))
            : 0;//from   www  .j a v  a  2 s .  co  m
    HttpResponse response = createResponse(HttpStatus.SC_OK);
    response.setHeader("Content-Length", Integer.toString(numBytes));
    response.setEntity(createFileEntity(downloadId, numBytes));
    return response;
}

From source file:com.android.contacts.common.model.ContactLoader.java

private static Contact loadEncodedContactEntity(Uri uri, Uri lookupUri) throws JSONException {
    final String jsonString = uri.getEncodedFragment();
    final JSONObject json = new JSONObject(jsonString);

    final long directoryId = Long.valueOf(uri.getQueryParameter(ContactsContract.DIRECTORY_PARAM_KEY));

    final String displayName = json.optString(Contacts.DISPLAY_NAME);
    final String altDisplayName = json.optString(Contacts.DISPLAY_NAME_ALTERNATIVE, displayName);
    final int displayNameSource = json.getInt(Contacts.DISPLAY_NAME_SOURCE);
    final String photoUri = json.optString(Contacts.PHOTO_URI, null);
    final Contact contact = new Contact(uri, uri, lookupUri, directoryId, null /* lookupKey */, -1 /* id */,
            -1 /* nameRawContactId */, displayNameSource, 0 /* photoId */, photoUri, displayName,
            altDisplayName, null /* phoneticName */, false /* starred */, null /* presence */,
            false /* sendToVoicemail */, null /* customRingtone */, false /* isUserProfile */);

    contact.setStatuses(new ImmutableMap.Builder<Long, DataStatus>().build());

    final String accountName = json.optString(RawContacts.ACCOUNT_NAME, null);
    final String directoryName = uri.getQueryParameter(Directory.DISPLAY_NAME);
    if (accountName != null) {
        final String accountType = json.getString(RawContacts.ACCOUNT_TYPE);
        contact.setDirectoryMetaData(directoryName, null, accountName, accountType,
                json.optInt(Directory.EXPORT_SUPPORT, Directory.EXPORT_SUPPORT_SAME_ACCOUNT_ONLY));
    } else {//from   w w  w.  ja v a2 s . co m
        contact.setDirectoryMetaData(directoryName, null, null, null,
                json.optInt(Directory.EXPORT_SUPPORT, Directory.EXPORT_SUPPORT_ANY_ACCOUNT));
    }

    final ContentValues values = new ContentValues();
    values.put(Data._ID, -1);
    values.put(Data.CONTACT_ID, -1);
    final RawContact rawContact = new RawContact(values);

    final JSONObject items = json.getJSONObject(Contacts.CONTENT_ITEM_TYPE);
    final Iterator keys = items.keys();
    while (keys.hasNext()) {
        final String mimetype = (String) keys.next();

        // Could be single object or array.
        final JSONObject obj = items.optJSONObject(mimetype);
        if (obj == null) {
            final JSONArray array = items.getJSONArray(mimetype);
            for (int i = 0; i < array.length(); i++) {
                final JSONObject item = array.getJSONObject(i);
                processOneRecord(rawContact, item, mimetype);
            }
        } else {
            processOneRecord(rawContact, obj, mimetype);
        }
    }

    contact.setRawContacts(new ImmutableList.Builder<RawContact>().add(rawContact).build());
    return contact;
}

From source file:com.hyperkode.friendshare.fragment.TwitterWebViewFragment.java

public void onResume() {
    super.onResume();
    String url = null;/*from   w  ww .ja  v  a2s  . co  m*/
    FragmentManager fragmentManager = TwitterWebViewFragment.this.getActivity().getSupportFragmentManager();
    Bundle args = this.getArguments();
    if (args != null) {
        url = args.getString("URL");
        loginFragment = (LoginFragment) fragmentManager.getFragment(args, "LoginFragment");
    }

    WebView webView = (WebView) mThisActivity.findViewById(R.id.twitter_webview);
    WebSettings webSettings = webView.getSettings();
    webSettings.setSavePassword(false);
    webSettings.setSaveFormData(false);
    webSettings.setJavaScriptEnabled(true);
    webSettings.setSupportZoom(false);

    webView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.contains(getString(R.string.TWITTER_CALLBACK_URL))) {
                Uri uri = Uri.parse(url);
                String oauthVerifier = uri.getQueryParameter("oauth_verifier");
                if (loginFragment != null) {
                    loginFragment.setOAuthVerifierResult(oauthVerifier);
                }
                return true;
            }
            return false;
        }
    });
    webView.loadUrl(url);
}

From source file:com.feigdev.fourcolumngv.FourColumnGridViewActivity.java

protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    Log.d(TAG, "onNewIntent called: " + intent.toString());
    Uri uri = intent.getData();
    if (uri != null) {
        String uriVar = uri.getQueryParameter("var");
        if (uriVar != null) {
            Log.d(TAG, uriVar);//from www. ja  va 2s . c o  m
        }
    }
}