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:android.webkit.cts.CtsTestServer.java

/**
 * Generate a response to the given request.
 * @throws InterruptedException//from  w ww .ja  v a  2s .co  m
 * @throws IOException
 */
private HttpResponse getResponse(HttpRequest request) throws Exception {
    RequestLine requestLine = request.getRequestLine();
    HttpResponse response = null;
    String uriString = requestLine.getUri();
    Log.i(TAG, requestLine.getMethod() + ": " + uriString);

    synchronized (this) {
        mQueries.add(uriString);
        mLastRequestMap.put(uriString, request);
        if (request instanceof HttpEntityEnclosingRequest) {
            mRequestEntities.add(((HttpEntityEnclosingRequest) request).getEntity());
        }
    }

    if (requestLine.getMethod().equals("POST")) {
        HttpResponse responseOnPost = onPost(request);
        if (responseOnPost != null) {
            return responseOnPost;
        }
    }

    URI uri = URI.create(uriString);
    String path = uri.getPath();
    String query = uri.getQuery();
    if (path.equals(FAVICON_PATH)) {
        path = FAVICON_ASSET_PATH;
    }
    if (path.startsWith(DELAY_PREFIX)) {
        String delayPath = path.substring(DELAY_PREFIX.length() + 1);
        String delay = delayPath.substring(0, delayPath.indexOf('/'));
        path = delayPath.substring(delay.length());
        try {
            Thread.sleep(Integer.valueOf(delay));
        } catch (InterruptedException ignored) {
            // ignore
        }
    }
    if (path.startsWith(AUTH_PREFIX)) {
        // authentication required
        Header[] auth = request.getHeaders("Authorization");
        if ((auth.length > 0 && auth[0].getValue().equals(AUTH_CREDENTIALS))
                // This is a hack to make sure that loads to this url's will always
                // ask for authentication. This is what the test expects.
                && !path.endsWith("embedded_image.html")) {
            // fall through and serve content
            path = path.substring(AUTH_PREFIX.length());
        } else {
            // request authorization
            response = createResponse(HttpStatus.SC_UNAUTHORIZED);
            response.addHeader("WWW-Authenticate", "Basic realm=\"" + AUTH_REALM + "\"");
        }
    }
    if (path.startsWith(BINARY_PREFIX)) {
        List<NameValuePair> args = URLEncodedUtils.parse(uri, "UTF-8");
        int length = 0;
        String mimeType = null;
        try {
            for (NameValuePair pair : args) {
                String name = pair.getName();
                if (name.equals("type")) {
                    mimeType = pair.getValue();
                } else if (name.equals("length")) {
                    length = Integer.parseInt(pair.getValue());
                }
            }
            if (length > 0 && mimeType != null) {
                ByteArrayEntity entity = new ByteArrayEntity(new byte[length]);
                entity.setContentType(mimeType);
                response = createResponse(HttpStatus.SC_OK);
                response.setEntity(entity);
                response.addHeader("Content-Disposition", "attachment; filename=test.bin");
                response.addHeader("Content-Type", mimeType);
                response.addHeader("Content-Length", "" + length);
            } else {
                // fall through, return 404 at the end
            }
        } catch (Exception e) {
            // fall through, return 404 at the end
            Log.w(TAG, e);
        }
    } else if (path.startsWith(ASSET_PREFIX)) {
        path = path.substring(ASSET_PREFIX.length());
        // request for an asset file
        try {
            InputStream in;
            if (path.startsWith(RAW_PREFIX)) {
                String resourceName = path.substring(RAW_PREFIX.length());
                int id = mResources.getIdentifier(resourceName, "raw", mContext.getPackageName());
                if (id == 0) {
                    Log.w(TAG, "Can't find raw resource " + resourceName);
                    throw new IOException();
                }
                in = mResources.openRawResource(id);
            } else {
                in = mAssets.open(path);
            }
            response = createResponse(HttpStatus.SC_OK);
            InputStreamEntity entity = new InputStreamEntity(in, in.available());
            String mimeType = mMap.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(path));
            if (mimeType == null) {
                mimeType = "text/html";
            }
            entity.setContentType(mimeType);
            response.setEntity(entity);
            if (query == null || !query.contains(NOLENGTH_POSTFIX)) {
                response.setHeader("Content-Length", "" + entity.getContentLength());
            }
        } catch (IOException e) {
            response = null;
            // fall through, return 404 at the end
        }
    } else if (path.startsWith(REDIRECT_PREFIX)) {
        response = createResponse(HttpStatus.SC_MOVED_TEMPORARILY);
        String location = getBaseUri() + path.substring(REDIRECT_PREFIX.length());
        Log.i(TAG, "Redirecting to: " + location);
        response.addHeader("Location", location);
    } else if (path.equals(QUERY_REDIRECT_PATH)) {
        String location = Uri.parse(uriString).getQueryParameter("dest");
        if (location != null) {
            Log.i(TAG, "Redirecting to: " + location);
            response = createResponse(HttpStatus.SC_MOVED_TEMPORARILY);
            response.addHeader("Location", location);
        }
    } else if (path.startsWith(COOKIE_PREFIX)) {
        /*
         * Return a page with a title containing a list of all incoming cookies,
         * separated by '|' characters. If a numeric 'count' value is passed in a cookie,
         * return a cookie with the value incremented by 1. Otherwise, return a cookie
         * setting 'count' to 0.
         */
        response = createResponse(HttpStatus.SC_OK);
        Header[] cookies = request.getHeaders("Cookie");
        Pattern p = Pattern.compile("count=(\\d+)");
        StringBuilder cookieString = new StringBuilder(100);
        cookieString.append(cookies.length);
        int count = 0;
        for (Header cookie : cookies) {
            cookieString.append("|");
            String value = cookie.getValue();
            cookieString.append(value);
            Matcher m = p.matcher(value);
            if (m.find()) {
                count = Integer.parseInt(m.group(1)) + 1;
            }
        }

        response.addHeader("Set-Cookie", "count=" + count + "; path=" + COOKIE_PREFIX);
        response.setEntity(createPage(cookieString.toString(), cookieString.toString()));
    } else if (path.startsWith(SET_COOKIE_PREFIX)) {
        response = createResponse(HttpStatus.SC_OK);
        Uri parsedUri = Uri.parse(uriString);
        String key = parsedUri.getQueryParameter("key");
        String value = parsedUri.getQueryParameter("value");
        String cookie = key + "=" + value;
        response.addHeader("Set-Cookie", cookie);
        response.setEntity(createPage(cookie, cookie));
    } else if (path.startsWith(LINKED_SCRIPT_PREFIX)) {
        response = createResponse(HttpStatus.SC_OK);
        String src = Uri.parse(uriString).getQueryParameter("url");
        String scriptTag = "<script src=\"" + src + "\"></script>";
        response.setEntity(createPage("LinkedScript", scriptTag));
    } else if (path.equals(USERAGENT_PATH)) {
        response = createResponse(HttpStatus.SC_OK);
        Header agentHeader = request.getFirstHeader("User-Agent");
        String agent = "";
        if (agentHeader != null) {
            agent = agentHeader.getValue();
        }
        response.setEntity(createPage(agent, agent));
    } else if (path.equals(TEST_DOWNLOAD_PATH)) {
        response = createTestDownloadResponse(Uri.parse(uriString));
    } else if (path.equals(SHUTDOWN_PREFIX)) {
        response = createResponse(HttpStatus.SC_OK);
        // We cannot close the socket here, because we need to respond.
        // Status must be set to OK, or else the test will fail due to
        // a RunTimeException.
    } else if (path.equals(APPCACHE_PATH)) {
        response = createResponse(HttpStatus.SC_OK);
        response.setEntity(createEntity("<!DOCTYPE HTML>" + "<html manifest=\"appcache.manifest\">" + "  <head>"
                + "    <title>Waiting</title>" + "    <script>"
                + "      function updateTitle(x) { document.title = x; }"
                + "      window.applicationCache.onnoupdate = "
                + "          function() { updateTitle(\"onnoupdate Callback\"); };"
                + "      window.applicationCache.oncached = "
                + "          function() { updateTitle(\"oncached Callback\"); };"
                + "      window.applicationCache.onupdateready = "
                + "          function() { updateTitle(\"onupdateready Callback\"); };"
                + "      window.applicationCache.onobsolete = "
                + "          function() { updateTitle(\"onobsolete Callback\"); };"
                + "      window.applicationCache.onerror = "
                + "          function() { updateTitle(\"onerror Callback\"); };" + "    </script>" + "  </head>"
                + "  <body onload=\"updateTitle('Loaded');\">AppCache test</body>" + "</html>"));
    } else if (path.equals(APPCACHE_MANIFEST_PATH)) {
        response = createResponse(HttpStatus.SC_OK);
        try {
            StringEntity entity = new StringEntity("CACHE MANIFEST");
            // This entity property is not used when constructing the response, (See
            // AbstractMessageWriter.write(), which is called by
            // AbstractHttpServerConnection.sendResponseHeader()) so we have to set this header
            // manually.
            // TODO: Should we do this for all responses from this server?
            entity.setContentType("text/cache-manifest");
            response.setEntity(entity);
            response.setHeader("Content-Type", "text/cache-manifest");
        } catch (UnsupportedEncodingException e) {
            Log.w(TAG, "Unexpected UnsupportedEncodingException");
        }
    }
    if (response == null) {
        response = createResponse(HttpStatus.SC_NOT_FOUND);
    }
    StatusLine sl = response.getStatusLine();
    Log.i(TAG, sl.getStatusCode() + "(" + sl.getReasonPhrase() + ")");
    setDateHeaders(response);
    return response;
}

From source file:com.xgf.inspection.qrcode.google.zxing.client.CaptureActivity.java

@Override
protected void onResume() {
    super.onResume();

    // CameraManager must be initialized here, not in onCreate(). This is
    // necessary because we don't
    // want to open the camera driver and measure the screen size if we're
    // going to show the help on
    // first launch. That led to bugs where the scanning rectangle was the
    // wrong size and partially
    // off screen.
    cameraManager = new CameraManager(getApplication());

    viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
    viewfinderView.setCameraManager(cameraManager);

    resultView = findViewById(R.id.result_view);
    statusView = (TextView) findViewById(R.id.status_view);

    handler = null;//from w  w w  .ja  va  2 s  .c o m
    lastResult = null;

    resetStatusView();

    SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
    SurfaceHolder surfaceHolder = surfaceView.getHolder();
    if (hasSurface) {
        // The activity was paused but not stopped, so the surface still
        // exists. Therefore
        // surfaceCreated() won't be called, so init the camera here.
        initCamera(surfaceHolder);
    } else {
        // Install the callback and wait for surfaceCreated() to init the
        // camera.
        surfaceHolder.addCallback(this);
        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    beepManager.updatePrefs();

    inactivityTimer.onResume();

    Intent intent = getIntent();

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    copyToClipboard = prefs.getBoolean(PreferencesActivity.KEY_COPY_TO_CLIPBOARD, true)
            && (intent == null || intent.getBooleanExtra(Intents.Scan.SAVE_HISTORY, true));

    source = IntentSource.NONE;
    decodeFormats = null;
    characterSet = null;

    if (intent != null) {

        String action = intent.getAction();
        String dataString = intent.getDataString();

        if (Intents.Scan.ACTION.equals(action)) {

            // Scan the formats the intent requested, and return the result
            // to the calling activity.
            source = IntentSource.NATIVE_APP_INTENT;
            decodeFormats = DecodeFormatManager.parseDecodeFormats(intent);

            if (intent.hasExtra(Intents.Scan.WIDTH) && intent.hasExtra(Intents.Scan.HEIGHT)) {
                int width = intent.getIntExtra(Intents.Scan.WIDTH, 0);
                int height = intent.getIntExtra(Intents.Scan.HEIGHT, 0);
                if (width > 0 && height > 0) {
                    cameraManager.setManualFramingRect(width, height);
                }
            }

            String customPromptMessage = intent.getStringExtra(Intents.Scan.PROMPT_MESSAGE);
            if (customPromptMessage != null) {
                statusView.setText(customPromptMessage);
            }

        } else if (dataString != null && dataString.contains(PRODUCT_SEARCH_URL_PREFIX)
                && dataString.contains(PRODUCT_SEARCH_URL_SUFFIX)) {

            // Scan only products and send the result to mobile Product
            // Search.
            source = IntentSource.PRODUCT_SEARCH_LINK;
            sourceUrl = dataString;
            decodeFormats = DecodeFormatManager.PRODUCT_FORMATS;

        } else if (isZXingURL(dataString)) {

            // Scan formats requested in query string (all formats if none
            // specified).
            // If a return URL is specified, send the results there.
            // Otherwise, handle it ourselves.
            source = IntentSource.ZXING_LINK;
            sourceUrl = dataString;
            Uri inputUri = Uri.parse(sourceUrl);
            returnUrlTemplate = inputUri.getQueryParameter(RETURN_URL_PARAM);
            returnRaw = inputUri.getQueryParameter(RAW_PARAM) != null;
            decodeFormats = DecodeFormatManager.parseDecodeFormats(inputUri);

        }

        characterSet = intent.getStringExtra(Intents.Scan.CHARACTER_SET);

    }
}

From source file:org.kontalk.provider.UsersProvider.java

@Override
public Cursor query(@NonNull Uri uri, String[] projection, String selection, String[] selectionArgs,
        String sortOrder) {// w w w  .  j a  va 2 s .c o m
    SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
    boolean offline = Boolean.parseBoolean(uri.getQueryParameter(Users.OFFLINE));

    int match = sUriMatcher.match(uri);
    if (match == USERS || match == USERS_JID) {
        // use the same table name as an alias
        String table = offline ? (TABLE_USERS_OFFLINE + " " + TABLE_USERS) : TABLE_USERS;
        qb.setTables(table);
        qb.setProjectionMap(usersProjectionMap);
    } else if (match == KEYS || match == KEYS_JID || match == KEYS_JID_FINGERPRINT) {
        qb.setTables(TABLE_KEYS);
        qb.setProjectionMap(keysProjectionMap);
    }

    switch (match) {
    case USERS:
        // nothing to do
        break;

    case USERS_JID: {
        // TODO append to selection
        String userId = uri.getPathSegments().get(1);
        selection = TABLE_USERS + "." + Users.JID + " = ?";
        selectionArgs = new String[] { userId };
        break;
    }

    case KEYS:
        // nothing to do
        break;

    case KEYS_JID:
    case KEYS_JID_FINGERPRINT:
        String userId = uri.getPathSegments().get(1);
        selection = DatabaseUtilsCompat.concatenateWhere(selection, Keys.JID + "=?");
        selectionArgs = DatabaseUtilsCompat.appendSelectionArgs(selectionArgs, new String[] { userId });
        // TODO support for fingerprint in Uri
        break;

    default:
        throw new IllegalArgumentException("Unknown URI " + uri);
    }

    SQLiteDatabase db = dbHelper.getReadableDatabase();
    Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, sortOrder);
    if ((match == USERS || match == USERS_JID) && c.getCount() == 0
            && (match != USERS_JID || !XMPPUtils.isDomainJID(uri.getPathSegments().get(1)))) {
        // empty result set and sync requested
        SyncAdapter.requestSync(getContext(), false);
    }
    if (Boolean.parseBoolean(uri.getQueryParameter(Users.EXTRA_INDEX)) && c.getCount() > 0) {
        UsersCursor uc = new UsersCursor(c);
        bundleFastScrollingIndexExtras(uc, uri, db, qb, selection, selectionArgs, sortOrder, null);
        c = uc;
    }

    c.setNotificationUri(getContext().getContentResolver(), uri);
    return c;
}

From source file:org.kontalk.provider.UsersProvider.java

@Override
public Uri insert(@NonNull Uri uri, ContentValues values) {
    try {//from  w w  w  . j  a v a 2s .  c o  m
        int match = sUriMatcher.match(uri);
        switch (match) {
        case USERS:
        case USERS_JID:
            return insertUser(values, Boolean.parseBoolean(uri.getQueryParameter(Users.OFFLINE)),
                    Boolean.parseBoolean(uri.getQueryParameter(Users.DISCARD_NAME)));

        case KEYS:
        case KEYS_JID:
        case KEYS_JID_FINGERPRINT:
            List<String> segs = uri.getPathSegments();
            String jid, fingerprint;
            if (segs.size() >= 2) {
                // Uri-based insert/update
                jid = segs.get(1);
                fingerprint = segs.get(2);
            } else {
                // take jid and fingerprint from values
                jid = values.getAsString(Keys.JID);
                fingerprint = values.getAsString(Keys.FINGERPRINT);
            }

            return insertOrUpdateKey(jid, fingerprint, values,
                    Boolean.parseBoolean(uri.getQueryParameter(Keys.INSERT_ONLY)));

        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }
    } finally {
        invalidateFastScrollingIndexCache();
    }
}

From source file:com.nappking.movietimesup.HomeFragment.java

@Override
public void onResume() {
    super.onResume();

    if (application.getCurrentFBUser() != null && !gameLaunchedFromDeepLinking) {
        // As long as the user is logged in and the game hasn't been launched yet
        // from deep linking, see if it has been deep linked and launch the game appropriately
        Uri target = getActivity().getIntent().getData();
        if (target != null) {
            Intent i = new Intent(getActivity(), GameActivity.class);

            // Target is the deep-link Uri, so skip loading this home screen and load the game
            // directly with the sending user's picture to smash
            String graphRequestIDsForSendingUser = target.getQueryParameter("request_ids");
            String feedPostIDForSendingUser = target.getQueryParameter("challenge_brag");

            if (graphRequestIDsForSendingUser != null) {
                // Deep linked through a Request and use the latest request (request_id) if multiple requests have been sent
                String[] graphRequestIDsForSendingUsers = graphRequestIDsForSendingUser.split(",");
                String graphRequestIDForSendingUser = graphRequestIDsForSendingUsers[graphRequestIDsForSendingUsers.length
                        - 1];//ww  w. ja v  a 2  s .c o m
                Bundle bundle = new Bundle();
                bundle.putString("request_id", graphRequestIDForSendingUser);
                i.putExtras(bundle);
                gameLaunchedFromDeepLinking = true;
                startActivityForResult(i, 0);

                // Delete the Request now it has been consumed and processed
                Request deleteFBRequestRequest = new Request(Session.getActiveSession(),
                        graphRequestIDForSendingUser + "_" + application.getCurrentFBUser().getId(),
                        new Bundle(), HttpMethod.DELETE, new Request.Callback() {

                            @Override
                            public void onCompleted(Response response) {
                                FacebookRequestError error = response.getError();
                                if (error != null) {
                                    Log.e(FriendSmashApplication.TAG,
                                            "Deleting consumed Request failed: " + error.getErrorMessage());
                                } else {
                                    Log.i(FriendSmashApplication.TAG, "Consumed Request deleted");
                                }
                            }
                        });
                Request.executeBatchAsync(deleteFBRequestRequest);
            } else if (feedPostIDForSendingUser != null) {
                // Deep linked through a feed post, so start the game smashing the user specified by the id attached to the
                // challenge_brag parameter
                Bundle bundle = new Bundle();
                bundle.putString("user_id", feedPostIDForSendingUser);
                i.putExtras(bundle);
                gameLaunchedFromDeepLinking = true;
                startActivityForResult(i, 0);
            }
        } else {
            // Launched with no deep-link Uri, so just continue as normal and load the home screen
        }
    }

    if (!gameLaunchedFromDeepLinking && gameOverMessageDisplaying) {
        // The game hasn't just been launched from deep linking and the game over message should still be displaying, so ...

        // Complete the game over logic
        completeGameOver(750);
    }
}

From source file:co.uk.socialticker.ticker.TickerActivity.java

private void onCreateTwitter() {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);/* w w  w  .  ja  v  a 2 s. c o  m*/

    cd = new ConnectionDetector(getApplicationContext());

    // Check if Internet present
    if (!cd.isConnectingToInternet()) {
        // Internet Connection is not present
        alert.showAlertDialog(TickerActivity.this, "Internet Connection Error",
                "Please connect to working Internet connection", false);
        // stop executing code by return
        return;
    }

    // Check if twitter keys are set
    if (TWITTER_CONSUMER_KEY.trim().length() == 0 || TWITTER_CONSUMER_SECRET.trim().length() == 0) {
        // Internet Connection is not present
        alert.showAlertDialog(TickerActivity.this, "Twitter oAuth tokens",
                "Please set your twitter oauth tokens first!", false);
        // stop executing code by return
        return;
    }

    // All UI elements
    btnLoginTwitter = (Button) findViewById(R.id.btnLoginTwitter);
    btnUpdateStatus = (Button) findViewById(R.id.btnUpdateStatus);
    btnLogoutTwitter = (Button) findViewById(R.id.btnLogoutTwitter);
    txtUpdate = (EditText) findViewById(R.id.txtUpdateStatus);
    lblUpdate = (TextView) findViewById(R.id.lblUpdate);

    llTwitter = (LinearLayout) findViewById(R.id.llTwitter);
    llCast = (LinearLayout) findViewById(R.id.llCast);

    /**
     * Twitter login button click event will call loginToTwitter() function
     * */
    btnLoginTwitter.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // Call login twitter function
            loginToTwitter();
        }
    });

    /**
     * Button click event to Update Status, will call updateTwitterStatus()
     * function
     * */
    btnUpdateStatus.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // Call update status function
            // Get the status from EditText
            String status = txtUpdate.getText().toString();

            // Check for blank text
            if (status.trim().length() > 0) {
                // update status
                new updateTwitterStatus().execute(status);
            } else {
                // EditText is empty
                Toast.makeText(getApplicationContext(), "Please enter status message", Toast.LENGTH_SHORT)
                        .show();
            }
        }
    });

    /**
     * Button click event for logout from twitter
     * */
    btnLogoutTwitter.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // Call logout twitter function
            logoutFromTwitter();
        }
    });

    /** This if conditions is tested once is
     * redirected from twitter page. Parse the uri to get oAuth
     * Verifier
     * */
    if (!isTwitterLoggedInAlready()) {
        Uri uri = getIntent().getData();
        if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
            // oAuth verifier
            String verifier = uri.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);

            try {
                // Get the access token
                AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);

                // Shared Preferences
                Editor e = mSharedPreferences.edit();

                // After getting access token, access token secret
                // store them in application preferences
                e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
                e.putString(PREF_KEY_OAUTH_SECRET, accessToken.getTokenSecret());
                // Store login status - true
                e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
                e.commit(); // save changes

                Log.e("Twitter OAuth Token", "> " + accessToken.getToken());

                // Hide login button
                btnLoginTwitter.setVisibility(View.GONE);

                // Show Update Twitter
                lblUpdate.setVisibility(View.VISIBLE);
                txtUpdate.setVisibility(View.VISIBLE);
                btnUpdateStatus.setVisibility(View.VISIBLE);
                btnLogoutTwitter.setVisibility(View.VISIBLE);

                // Getting user details from twitter
                // For now i am getting his name only
                long userID = accessToken.getUserId();
                User user = twitter.showUser(userID);

            } catch (Exception e) {
                // Check log for login errors
                Log.e("Twitter Login Error", "> " + e.getMessage());
            }
        }
    }
}

From source file:org.openhab.habdroid.ui.OpenHABWidgetListActivity.java

/**
 * This method processes new intents generated by NFC subsystem
 * @param nfcData - a data which NFC subsystem got from the NFC tag
 * @param pushCurrentToStack/*  w  ww .java 2s  . c o  m*/
 */
public void onNfcTag(String nfcData, boolean pushCurrentToStack) {
    Uri openHABURI = Uri.parse(nfcData);
    Log.d(TAG, openHABURI.getScheme());
    Log.d(TAG, openHABURI.getHost());
    Log.d(TAG, openHABURI.getPath());
    if (openHABURI.getHost().equals("sitemaps")) {
        Log.d(TAG, "Tag indicates a sitemap link");
        String newPageUrl = this.openHABBaseUrl + "rest/sitemaps" + openHABURI.getPath();
        String widgetId = openHABURI.getQueryParameter("widget");
        String command = openHABURI.getQueryParameter("command");
        Log.d(TAG, "widgetId = " + widgetId);
        Log.d(TAG, "command = " + command);
        if (widgetId != null && command != null) {
            this.nfcWidgetId = widgetId;
            this.nfcCommand = command;
            // If we have widget+command and not pushing current page to stack
            // this means we started through NFC read when HABDroid was not running
            // so we need to put a flag to automatically close activity after we
            // finish nfc action
            if (!pushCurrentToStack)
                this.nfcAutoClose = true;
        }
        Log.d(TAG, "Should go to " + newPageUrl);
        if (pushCurrentToStack)
            navigateToPage(newPageUrl, "");
        else
            openSitemap(newPageUrl);
    }
}

From source file:org.thomnichols.android.gmarks.GmarksProvider.java

@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
    SQLiteQueryBuilder qb = new SQLiteQueryBuilder();

    //        Log.d(TAG, "Managed query: " + uri);
    String groupBy = null;//from   ww w  .j a v  a  2 s  .c  o  m
    String orderBy = null;
    String limit = null;
    switch (sUriMatcher.match(uri)) {
    case BOOKMARKS_URI:
        qb.setTables(BOOKMARKS_TABLE_NAME);
        qb.setProjectionMap(bookmarksProjectionMap);

        String labelID = uri.getQueryParameter("label_id");
        if (labelID != null) {
            qb.setTables("bookmarks join bookmark_labels on bookmarks._id = bookmark_labels.bookmark_id");
            qb.appendWhere("bookmark_labels.label_id=?");
            selectionArgs = (String[]) ArrayUtils.addAll(selectionArgs, new String[] { labelID });
        }
        break;

    case BOOKMARK_SEARCH_URI:
    case BOOKMARK_SEARCH_SUGGEST_URI:
        String query = null;
        if (sUriMatcher.match(uri) == BOOKMARK_SEARCH_SUGGEST_URI) {
            qb.setProjectionMap(searchSuggestProjectionMap);
            // path looks like "search_suggest_query/[query]?limit=50
            query = uri.getLastPathSegment();
            limit = uri.getQueryParameter("limit");
            if (sortOrder == null)
                sortOrder = Bookmark.Columns.SORT_MODIFIED;
        } else
            query = uri.getQueryParameter("q");

        if (query != null) {
            qb.setTables("bookmarks join bookmarks_FTS on bookmarks._id = bookmarks_FTS.docid");
            qb.appendWhere("bookmarks_FTS MATCH ?");
            if (selectionArgs == null)
                selectionArgs = new String[] { query };
            else
                selectionArgs = (String[]) ArrayUtils.addAll(selectionArgs, new String[] { query });
        } else if (selectionArgs == null || selectionArgs.length < 1)
            throw new IllegalArgumentException("No search criteria given for query!");
        break;

    case BOOKMARK_ID_URI:
        qb.setTables(BOOKMARKS_TABLE_NAME);
        qb.setProjectionMap(bookmarksProjectionMap);
        qb.appendWhere(Bookmark.Columns._ID + "=" + uri.getPathSegments().get(1));
        break;

    case LABELS_URI:
        qb.setTables("labels join bookmark_labels on labels._id = bookmark_labels.label_id");
        groupBy = "label";
        if (sortOrder == null)
            sortOrder = Label.Columns.DEFAULT_SORT_ORDER;
        qb.setProjectionMap(labelsProjectionMap);
        break;

    case LIVE_FOLDER_BOOKMARKS_URI:
        qb.setTables(BOOKMARKS_TABLE_NAME);
        qb.setProjectionMap(sLiveFolderProjectionMap);
        String labelId = uri.getQueryParameter("label_id");
        if (labelId != null) {
            qb.setTables("bookmarks join bookmark_labels on bookmarks._id = bookmark_labels.bookmark_id");
            qb.appendWhere("bookmark_labels.label_id=?");
            selectionArgs = (String[]) ArrayUtils.addAll(selectionArgs, new String[] { labelId });
        }
        sortOrder = "modified DESC"; // for some reason this gets set to 'name ASC'
        break;

    case BOOKMARK_LISTS_URI:
        qb.setTables(BookmarkList.TABLE_NAME);
        qb.setProjectionMap(listsProjectionMap);
        if (sortOrder == null)
            sortOrder = BookmarkList.Columns.DEFAULT_SORT_ORDER;
        String type = uri.getQueryParameter(BookmarkList.PARAM_CATEGORY);
        if (BookmarkList.LISTS_PRIVATE.equals(type))
            qb.appendWhere("owned=1");
        else if (BookmarkList.LISTS_SHARED.equals(type))
            qb.appendWhere("shared=1");
        else if (BookmarkList.LISTS_PUBLIC.equals(type))
            qb.appendWhere("publshed=1");
        break;

    default:
        throw new IllegalArgumentException("Unknown URI " + uri);
    }

    // If no sort order is specified use the default
    if (TextUtils.isEmpty(sortOrder)) {
        orderBy = Bookmark.Columns.DEFAULT_SORT_ORDER;
    } else {
        orderBy = sortOrder;
    }

    // Get the database and run the query
    SQLiteDatabase db = dbHelper.getReadableDatabase();
    Cursor c = qb.query(db, projection, selection, selectionArgs, groupBy, null, orderBy, limit);

    // Tell the cursor what uri to watch, so it knows when its source data changes
    c.setNotificationUri(getContext().getContentResolver(), uri);
    return c;
}

From source file:de.vanita5.twittnuker.provider.TwidereDataProvider.java

@Override
public ParcelFileDescriptor openFile(final Uri uri, final String mode) throws FileNotFoundException {
    if (uri == null || mode == null)
        throw new IllegalArgumentException();
    final int table_id = getTableId(uri);
    switch (table_id) {
    case VIRTUAL_TABLE_ID_CACHED_IMAGES: {
        return getCachedImageFd(uri.getQueryParameter(QUERY_PARAM_URL));
    }/*from  ww  w. j  a v a 2s. c o m*/
    case VIRTUAL_TABLE_ID_CACHE_FILES: {
        return getCacheFileFd(uri.getLastPathSegment());
    }
    }
    return null;
}

From source file:org.mariotaku.twidere.provider.TwidereDataProvider.java

@Override
public Uri insert(final Uri uri, final ContentValues values) {
    try {/*from   ww w  .j a va 2 s .  com*/
        final int table_id = getTableId(uri);
        final String table = getTableNameById(table_id);
        checkWritePermission(table_id, table);
        switch (table_id) {
        case TABLE_ID_DIRECT_MESSAGES_CONVERSATION:
        case TABLE_ID_DIRECT_MESSAGES:
        case TABLE_ID_DIRECT_MESSAGES_CONVERSATIONS_ENTRY:
            return null;
        }
        if (table == null)
            return null;
        final long row_id = mDatabase.insert(table, null, values);
        if (!"false".equals(uri.getQueryParameter(QUERY_PARAM_NOTIFY))) {
            switch (getTableId(uri)) {
            case TABLE_ID_STATUSES: {
                mNewStatusesCount++;
                break;
            }
            default:
            }
        }
        onDatabaseUpdated(uri);
        onNewItemsInserted(uri, values);
        return Uri.withAppendedPath(uri, String.valueOf(row_id));
    } catch (final SQLException e) {
        throw new IllegalStateException(e);
    }
}