Example usage for android.net Uri getQuery

List of usage examples for android.net Uri getQuery

Introduction

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

Prototype

@Nullable
public abstract String getQuery();

Source Link

Document

Gets the decoded query component from this URI.

Usage

From source file:com.adjust.sdk.ActivityHandler.java

private void readOpenUrlInternal(Uri url, long clickTime) {
    if (url == null) {
        return;//from   ww w .  j  a va2 s  .  co m
    }

    String queryString = url.getQuery();

    ActivityPackage clickPackage = buildQueryStringClickPackage(queryString, "deeplink", clickTime);
    if (clickPackage == null) {
        return;
    }

    packageHandler.addPackage(clickPackage);
}

From source file:com.appbase.androidquery.callback.AbstractAjaxCallback.java

private static Map<String, Object> extractParams(Uri uri) {

    Map<String, Object> params = new HashMap<String, Object>();
    String[] pairs = uri.getQuery().split("&");

    for (String pair : pairs) {
        String[] split = pair.split("=");
        if (split.length >= 2) {
            params.put(split[0], split[1]);
        } else if (split.length == 1) {
            params.put(split[0], "");
        }//from   w  w w  . j  a  va2 s  . c  o  m
    }
    return params;
}

From source file:com.microsoft.services.msa.AuthorizationRequest.java

/**
 * Called when the end uri is loaded./*from w w  w.j a va 2s. c  om*/
 *
 * This method will read the uri's query parameters and fragment, and respond with the
 * appropriate action.
 *
 * @param endUri that was loaded
 */
private void onEndUri(Uri endUri) {
    // If we are on an end uri, the response could either be in
    // the fragment or the query parameters. The response could
    // either be successful or it could contain an error.
    // Check all situations and call the listener's appropriate callback.
    // Callback the listener on the UI/main thread. We could call it right away since
    // we are on the UI/main thread, but it is probably better that we finish up with
    // the WebView code before we callback on the listener.
    boolean hasFragment = endUri.getFragment() != null;
    boolean hasQueryParameters = endUri.getQuery() != null;
    boolean invalidUri = !hasFragment && !hasQueryParameters;
    boolean isHierarchical = endUri.isHierarchical();

    // check for an invalid uri, and leave early
    if (invalidUri) {
        this.onInvalidUri();
        return;
    }

    if (hasFragment) {
        Map<String, String> fragmentParameters = AuthorizationRequest.getFragmentParametersMap(endUri);

        boolean isSuccessfulResponse = fragmentParameters.containsKey(OAuth.ACCESS_TOKEN)
                && fragmentParameters.containsKey(OAuth.TOKEN_TYPE);
        if (isSuccessfulResponse) {

            //                SharedPreferences preferences = activity.getSharedPreferences("csPrivateSpace", Context.MODE_PRIVATE);
            //                SharedPreferences.Editor editor = preferences.edit();
            //                editor.putString("funUserID", fragmentParameters.get("user_id"));
            //                editor.apply();

            this.onAccessTokenResponse(fragmentParameters);
            return;
        }

        String error = fragmentParameters.get(OAuth.ERROR);
        if (error != null) {
            String errorDescription = fragmentParameters.get(OAuth.ERROR_DESCRIPTION);
            String errorUri = fragmentParameters.get(OAuth.ERROR_URI);
            this.onError(error, errorDescription, errorUri);
            return;
        }
    }

    if (hasQueryParameters && isHierarchical) {
        String code = endUri.getQueryParameter(OAuth.CODE);
        if (code != null) {
            this.onAuthorizationResponse(code);
            return;
        }

        String error = endUri.getQueryParameter(OAuth.ERROR);
        if (error != null) {
            String errorDescription = endUri.getQueryParameter(OAuth.ERROR_DESCRIPTION);
            String errorUri = endUri.getQueryParameter(OAuth.ERROR_URI);
            this.onError(error, errorDescription, errorUri);
            return;
        }
    }

    if (hasQueryParameters && !isHierarchical) {
        String[] pairs = endUri.getQuery().split("&|=");
        for (int i = 0; i < pairs.length; i = +2) {
            if (pairs[i].equals(OAuth.CODE)) {
                this.onAuthorizationResponse(pairs[i + 1]);
                return;
            }
        }
    }

    // if the code reaches this point, the uri was invalid
    // because it did not contain either a successful response
    // or an error in either the queryParameter or the fragment
    this.onInvalidUri();
}

From source file:com.silverpop.engage.deeplinking.EngageDeepLinkManager.java

Uri trimDeeplink(Uri deeplink) {
    String host = deeplink.getHost();
    List<String> pathSegments = new LinkedList<String>(deeplink.getPathSegments());
    if (pathSegments.isEmpty()) {
        // trim off host
        if (!TextUtils.isEmpty(host)) {
            host = null;/*w  ww  .  j  a va 2  s .co m*/
        }
    }

    for (int i = pathSegments.size() - 1; i >= 0; i--) {
        // remove trailing slashes
        if (pathSegments.get(i).equals("/")) {
            pathSegments.remove(i);
        } else {
            pathSegments.remove(i);
            break;
        }
    }

    String pathString = "";
    for (int i = 0; i < pathSegments.size(); i++) {
        pathString += "/";
        pathString += pathSegments.get(i);
    }

    Uri.Builder builder = new Uri.Builder();
    builder.scheme(deeplink.getScheme());
    builder.path(pathString);
    builder.query(deeplink.getQuery());

    return builder.build();
}

From source file:net.wequick.small.Bundle.java

private Boolean matchesRule(Uri uri) {
    /* e.g.//w w  w  .j  av  a  2 s. c  om
     *  input
     *      - uri: http://base/abc.html
     *      - self.uri: http://base
     *      - self.rules: abc.html -> AbcController
     *  output
     *      - target => AbcController
     */
    String uriString = uri.toString();
    if (this.uriString == null || !uriString.startsWith(this.uriString))
        return false;

    String srcPath = uriString.substring(this.uriString.length());
    String srcQuery = uri.getQuery();
    if (srcQuery != null) {
        srcPath = srcPath.substring(0, srcPath.length() - srcQuery.length() - 1);
    }

    String dstPath = null;
    String dstQuery = srcQuery;
    if (srcPath.equals("")) {
        dstPath = srcPath;
    } else {
        for (String key : this.rules.keySet()) {
            // TODO: regex match and replace
            if (key.equals(srcPath))
                dstPath = this.rules.get(key);
            if (dstPath != null)
                break;
        }
        if (dstPath == null)
            return false;

        int index = dstPath.indexOf("?");
        if (index > 0) {
            if (dstQuery != null) {
                dstQuery = dstQuery + "&" + dstPath.substring(index + 1);
            } else {
                dstQuery = dstPath.substring(index + 1);
            }
            dstPath = dstPath.substring(0, index);
        }
    }

    this.path = dstPath;
    this.query = dstQuery;
    return true;
}

From source file:nodomain.freeyourgadget.gadgetbridge.service.devices.pebble.webview.GBWebClient.java

private WebResourceResponse mimicReply(Uri requestedUri) {
    if (requestedUri.getHost() != null && (org.apache.commons.lang3.StringUtils
            .indexOfAny(requestedUri.getHost(), AllowedDomains) != -1)) {
        if (internetHelperBound) {
            LOG.debug("WEBVIEW forwarding request to the internet helper");
            Bundle bundle = new Bundle();
            bundle.putString("URL", requestedUri.toString());
            Message webRequest = Message.obtain();
            webRequest.replyTo = internetHelperListener;
            webRequest.setData(bundle);/*  w  ww. j  a v  a 2s.c  o  m*/
            try {
                latch = new CountDownLatch(1); //the messenger should run on a single thread, hence we don't need to be worried about concurrency. This approach however is certainly not ideal.
                internetHelper.send(webRequest);
                latch.await();
                return internetResponse;

            } catch (RemoteException | InterruptedException e) {
                LOG.warn("Error downloading data from " + requestedUri, e);
            }

        } else {
            LOG.debug("WEBVIEW request to openweathermap.org detected of type: " + requestedUri.getPath()
                    + " params: " + requestedUri.getQuery());
            return mimicOpenWeatherMapResponse(requestedUri.getPath(), requestedUri.getQueryParameter("units"));
        }
    } else {
        LOG.debug("WEBVIEW request:" + requestedUri.toString() + " not intercepted");
    }
    return null;
}

From source file:gc.david.dfm.ui.activity.MainActivity.java

private void handleGeoSchemeIntent(final Uri uri) {
    final String schemeSpecificPart = uri.getSchemeSpecificPart();
    final Matcher matcher = getMatcherForUri(schemeSpecificPart);
    if (matcher.find()) {
        if (matcher.group(1).equals("0") && matcher.group(2).equals("0")) {
            if (matcher.find()) { // Manage geo:0,0?q=lat,lng(label)
                setDestinationPosition(matcher);
            } else { // Manage geo:0,0?q=my+street+address
                String destination = Uri.decode(uri.getQuery()).replace('+', ' ');
                destination = destination.replace("q=", "");

                // TODO check this ugly workaround
                addressPresenter.searchPositionByName(destination);
                searchMenuItem.collapseActionView();
                mustShowPositionWhenComingFromOutside = true;
            }/*from w  w  w.ja v a  2s.  c om*/
        } else { // Manage geo:latitude,longitude or geo:latitude,longitude?z=zoom
            setDestinationPosition(matcher);
        }
    } else {
        final NoSuchFieldException noSuchFieldException = new NoSuchFieldException(
                "Error al obtener las coordenadas. Matcher = " + matcher.toString());
        DFMLogger.logException(noSuchFieldException);
        toastIt("Unable to parse address", this);
    }
}

From source file:gc.david.dfm.ui.MainActivity.java

/**
 * Handles a send intent with position data.
 *
 * @param intent Input intent with position data.
 *///from   w ww .  j  a v  a  2 s .com
private void handleViewPositionIntent(final Intent intent) throws Exception {
    Mint.leaveBreadcrumb("MainActivity::handleViewPositionIntent");
    final Uri uri = intent.getData();
    Mint.addExtraData("queryParameter", uri.toString());

    final String uriScheme = uri.getScheme();
    if (uriScheme.equals("geo")) {
        final String schemeSpecificPart = uri.getSchemeSpecificPart();
        final Matcher matcher = getMatcherForUri(schemeSpecificPart);
        if (matcher.find()) {
            if (matcher.group(1).equals("0") && matcher.group(2).equals("0")) {
                if (matcher.find()) { // Manage geo:0,0?q=lat,lng(label)
                    setDestinationPosition(matcher);
                } else { // Manage geo:0,0?q=my+street+address
                    String destination = Uri.decode(uri.getQuery()).replace('+', ' ');
                    destination = destination.replace("q=", "");

                    // TODO check this ugly workaround
                    new SearchPositionByName().execute(destination);
                    mustShowPositionWhenComingFromOutside = true;
                }
            } else { // Manage geo:latitude,longitude or geo:latitude,longitude?z=zoom
                setDestinationPosition(matcher);
            }
        } else {
            final NoSuchFieldException noSuchFieldException = new NoSuchFieldException(
                    "Error al obtener las coordenadas. Matcher = " + matcher.toString());
            Mint.logException(noSuchFieldException);
            throw noSuchFieldException;
        }
    } else if ((uriScheme.equals("http") || uriScheme.equals("https"))
            && (uri.getHost().equals("maps.google.com"))) { // Manage maps.google.com?q=latitude,longitude

        final String queryParameter = uri.getQueryParameter("q");
        if (queryParameter != null) {
            final Matcher matcher = getMatcherForUri(queryParameter);
            if (matcher.find()) {
                setDestinationPosition(matcher);
            } else {
                final NoSuchFieldException noSuchFieldException = new NoSuchFieldException(
                        "Error al obtener las coordenadas. Matcher = " + matcher.toString());
                Mint.logException(noSuchFieldException);
                throw noSuchFieldException;
            }
        } else {
            final NoSuchFieldException noSuchFieldException = new NoSuchFieldException(
                    "Query sin parmetro q.");
            Mint.logException(noSuchFieldException);
            throw noSuchFieldException;
        }
    } else {
        final Exception exception = new Exception("Imposible tratar la query " + uri.toString());
        Mint.logException(exception);
        throw exception;
    }
}

From source file:com.andrewshu.android.reddit.comments.CommentsListActivity.java

/**
 * Called when the activity starts up. Do activity initialization
 * here, not in a constructor.// w w  w . java2  s . co m
 * 
 * @see Activity#onCreate
 */
@SuppressWarnings("unchecked")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    CookieSyncManager.createInstance(getApplicationContext());

    mSettings.loadRedditPreferences(this, mClient);

    setRequestedOrientation(mSettings.getRotation());
    setTheme(mSettings.getTheme());
    requestWindowFeature(Window.FEATURE_PROGRESS);
    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);

    setContentView(R.layout.comments_list_content);
    registerForContextMenu(getListView());

    if (savedInstanceState != null) {
        mReplyTargetName = savedInstanceState.getString(Constants.REPLY_TARGET_NAME_KEY);
        mReportTargetName = savedInstanceState.getString(Constants.REPORT_TARGET_NAME_KEY);
        mEditTargetBody = savedInstanceState.getString(Constants.EDIT_TARGET_BODY_KEY);
        mDeleteTargetKind = savedInstanceState.getString(Constants.DELETE_TARGET_KIND_KEY);
        mThreadTitle = savedInstanceState.getString(Constants.THREAD_TITLE_KEY);
        mSubreddit = savedInstanceState.getString(Constants.SUBREDDIT_KEY);
        mThreadId = savedInstanceState.getString(Constants.THREAD_ID_KEY);
        mVoteTargetThing = savedInstanceState.getParcelable(Constants.VOTE_TARGET_THING_INFO_KEY);

        if (mThreadTitle != null) {
            setTitle(mThreadTitle + " : " + mSubreddit);
        }

        mCommentsList = (ArrayList<ThingInfo>) getLastNonConfigurationInstance();
        if (mCommentsList == null) {
            getNewDownloadCommentsTask().execute(Constants.DEFAULT_COMMENT_DOWNLOAD_LIMIT);
        } else {
            // Orientation change. Use prior instance.
            resetUI(new CommentsListAdapter(this, mCommentsList));
        }
    }

    // No saved state; use info from Intent.getData()
    else {
        String commentPath;
        String commentQuery;
        String jumpToCommentId = null;
        int jumpToCommentContext = 0;
        // We get the URL through getIntent().getData()
        Uri data = getIntent().getData();
        if (data != null) {
            // Comment path: a URL pointing to a thread or a comment in a thread.
            commentPath = data.getPath();
            commentQuery = data.getQuery();
        } else {
            if (Constants.LOGGING)
                Log.e(TAG, "Quitting because no subreddit and thread id data was passed into the Intent.");
            finish();
            return;
        }

        if (commentPath != null) {
            if (Constants.LOGGING)
                Log.d(TAG, "comment path: " + commentPath);

            if (Util.isRedditShortenedUri(data)) {
                // http://redd.it/abc12
                mThreadId = commentPath.substring(1);
            } else {
                // http://www.reddit.com/...
                Matcher m = COMMENT_PATH_PATTERN.matcher(commentPath);
                if (m.matches()) {
                    mSubreddit = m.group(1);
                    mThreadId = m.group(2);
                    jumpToCommentId = m.group(3);
                }
            }
        } else {
            if (Constants.LOGGING)
                Log.e(TAG, "Quitting because of bad comment path.");
            finish();
            return;
        }

        if (commentQuery != null) {
            Matcher m = COMMENT_CONTEXT_PATTERN.matcher(commentQuery);
            if (m.find()) {
                jumpToCommentContext = m.group(1) != null ? Integer.valueOf(m.group(1)) : 0;
            }
        }

        // Extras: subreddit, threadTitle, numComments
        // subreddit is not always redundant to Intent.getData(),
        // since URL does not always contain the subreddit. (e.g., self posts)
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            // subreddit could have already been set from the Intent.getData. don't overwrite with null here!
            String subreddit = extras.getString(Constants.EXTRA_SUBREDDIT);
            if (subreddit != null)
                mSubreddit = subreddit;
            // mThreadTitle has not been set yet, so no need for null check before setting it
            mThreadTitle = extras.getString(Constants.EXTRA_TITLE);
            if (mThreadTitle != null) {
                setTitle(mThreadTitle + " : " + mSubreddit);
            }
            // TODO: use extras.getInt(Constants.EXTRA_NUM_COMMENTS) somehow
        }

        if (!StringUtils.isEmpty(jumpToCommentId)) {
            getNewDownloadCommentsTask().prepareLoadAndJumpToComment(jumpToCommentId, jumpToCommentContext)
                    .execute(Constants.DEFAULT_COMMENT_DOWNLOAD_LIMIT);
        } else {
            getNewDownloadCommentsTask().execute(Constants.DEFAULT_COMMENT_DOWNLOAD_LIMIT);
        }
    }
}

From source file:com.oakesville.mythling.MediaActivity.java

protected void downloadItem(final Item item) {
    try {/*from w w w . ja va2 s. c o  m*/
        final URL baseUrl = getAppSettings().getMythTvServicesBaseUrlWithCredentials();

        String fileUrl = baseUrl + "/Content/GetFile?";
        if (item.getStorageGroup() == null)
            fileUrl += "StorageGroup=None&";
        else
            fileUrl += "StorageGroup=" + item.getStorageGroup().getName() + "&";
        fileUrl += "FileName=" + URLEncoder.encode(item.getFilePath(), "UTF-8");

        Uri uri = Uri.parse(fileUrl.toString());
        ProxyInfo proxyInfo = MediaStreamProxy.needsAuthProxy(uri);
        if (proxyInfo != null) {
            // needs proxying to support authentication since DownloadManager doesn't support
            MediaStreamProxy proxy = new MediaStreamProxy(proxyInfo,
                    AuthType.valueOf(appSettings.getMythTvServicesAuthType()));
            proxy.init();
            proxy.start();
            fileUrl = "http://" + proxy.getLocalhost().getHostAddress() + ":" + proxy.getPort() + uri.getPath();
            if (uri.getQuery() != null)
                fileUrl += "?" + uri.getQuery();
        }

        Log.i(TAG, "Media download URL: " + fileUrl);

        stopProgress();

        DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        Request request = new Request(Uri.parse(fileUrl));
        request.setTitle(item.getOneLineTitle());
        String downloadFilePath = null;
        try {
            if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
                File downloadDir = Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
                if (downloadDir.exists()) {
                    String downloadPath = AppSettings.getExternalStorageDir() + "/";
                    if (getPath() != null && !getPath().isEmpty() && !getPath().equals("/"))
                        downloadPath += getPath() + "/";
                    File destDir = new File(downloadDir + "/" + downloadPath);
                    if (destDir.isDirectory() || destDir.mkdirs()) {
                        downloadFilePath = downloadPath + item.getDownloadFilename();
                        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
                                downloadFilePath);
                        request.allowScanningByMediaScanner();
                    }
                }
            }
        } catch (IllegalStateException ex) {
            // store internal
        } catch (Exception ex) {
            // log, report and store internal
            Log.e(TAG, ex.getMessage(), ex);
            if (getAppSettings().isErrorReportingEnabled())
                new Reporter(ex).send();
            Toast.makeText(getApplicationContext(), getString(R.string.error_) + ex.toString(),
                    Toast.LENGTH_LONG).show();
        }
        long downloadId = dm.enqueue(request);
        registerDownloadReceiver(item, downloadId);
        Toast.makeText(getApplicationContext(), getString(R.string.downloading_) + item.getOneLineTitle(),
                Toast.LENGTH_LONG).show();
        getAppData().addDownload(new Download(item.getId(), downloadId, downloadFilePath, new Date()));
        if (item.isRecording() && (mediaList.isMythTv28() || getAppSettings().isMythlingMediaServices()))
            new GetCutListTask((Recording) item, downloadId).execute();
    } catch (Exception ex) {
        stopProgress();
        Log.e(TAG, ex.getMessage(), ex);
        if (getAppSettings().isErrorReportingEnabled())
            new Reporter(ex).send();
        Toast.makeText(getApplicationContext(), getString(R.string.error_) + ex.toString(), Toast.LENGTH_LONG)
                .show();
    }
}