Example usage for android.net Uri getLastPathSegment

List of usage examples for android.net Uri getLastPathSegment

Introduction

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

Prototype

@Nullable
public abstract String getLastPathSegment();

Source Link

Document

Gets the decoded last segment in the path.

Usage

From source file:org.getlantern.firetweet.provider.FiretweetDataProvider.java

@Override
public Cursor query(final Uri uri, final String[] projection, final String selection,
        final String[] selectionArgs, final String sortOrder) {
    try {//from  w  w w. j a v a 2s .  c  om
        final int tableId = getTableId(uri);
        final String table = getTableNameById(tableId);
        checkReadPermission(tableId, table, projection);
        switch (tableId) {
        case VIRTUAL_TABLE_ID_DATABASE_READY: {
            if (mDatabaseWrapper.isReady())
                return new MatrixCursor(projection != null ? projection : new String[0]);
            return null;
        }
        case VIRTUAL_TABLE_ID_PERMISSIONS: {
            final MatrixCursor c = new MatrixCursor(FiretweetDataStore.Permissions.MATRIX_COLUMNS);
            final Map<String, String> map = mPermissionsManager.getAll();
            for (final Map.Entry<String, String> item : map.entrySet()) {
                c.addRow(new Object[] { item.getKey(), item.getValue() });
            }
            return c;
        }
        case VIRTUAL_TABLE_ID_ALL_PREFERENCES: {
            return getPreferencesCursor(mPreferences, null);
        }
        case VIRTUAL_TABLE_ID_PREFERENCES: {
            return getPreferencesCursor(mPreferences, uri.getLastPathSegment());
        }
        case VIRTUAL_TABLE_ID_DNS: {
            return getDNSCursor(uri.getLastPathSegment());
        }
        case VIRTUAL_TABLE_ID_CACHED_IMAGES: {
            return getCachedImageCursor(uri.getQueryParameter(QUERY_PARAM_URL));
        }
        case VIRTUAL_TABLE_ID_NOTIFICATIONS: {
            final List<String> segments = uri.getPathSegments();
            if (segments.size() == 2)
                return getNotificationsCursor(ParseUtils.parseInt(segments.get(1), -1));
            else
                return getNotificationsCursor();
        }
        case VIRTUAL_TABLE_ID_UNREAD_COUNTS: {
            final List<String> segments = uri.getPathSegments();
            if (segments.size() == 2)
                return getUnreadCountsCursor(ParseUtils.parseInt(segments.get(1), -1));
            else
                return getUnreadCountsCursor();
        }
        case VIRTUAL_TABLE_ID_UNREAD_COUNTS_BY_TYPE: {
            final List<String> segments = uri.getPathSegments();
            if (segments.size() != 3)
                return null;
            return getUnreadCountsCursorByType(segments.get(2));
        }
        case TABLE_ID_DIRECT_MESSAGES_CONVERSATION: {
            final List<String> segments = uri.getPathSegments();
            if (segments.size() != 4)
                return null;
            final long accountId = ParseUtils.parseLong(segments.get(2));
            final long conversationId = ParseUtils.parseLong(segments.get(3));
            final SQLSelectQuery query = ConversationQueryBuilder.buildByConversationId(projection, accountId,
                    conversationId, selection, sortOrder);
            final Cursor c = mDatabaseWrapper.rawQuery(query.getSQL(), selectionArgs);
            setNotificationUri(c, DirectMessages.CONTENT_URI);
            return c;
        }
        case TABLE_ID_DIRECT_MESSAGES_CONVERSATION_SCREEN_NAME: {
            final List<String> segments = uri.getPathSegments();
            if (segments.size() != 4)
                return null;
            final long accountId = ParseUtils.parseLong(segments.get(2));
            final String screenName = segments.get(3);
            final SQLSelectQuery query = ConversationQueryBuilder.buildByScreenName(projection, accountId,
                    screenName, selection, sortOrder);
            final Cursor c = mDatabaseWrapper.rawQuery(query.getSQL(), selectionArgs);
            setNotificationUri(c, DirectMessages.CONTENT_URI);
            return c;
        }
        case VIRTUAL_TABLE_ID_CACHED_USERS_WITH_RELATIONSHIP: {
            final long accountId = ParseUtils.parseLong(uri.getLastPathSegment(), -1);
            final SQLSelectQuery query = CachedUsersQueryBuilder.withRelationship(projection, selection,
                    sortOrder, accountId);
            final Cursor c = mDatabaseWrapper.rawQuery(query.getSQL(), selectionArgs);
            setNotificationUri(c, CachedUsers.CONTENT_URI);
            return c;
        }
        case VIRTUAL_TABLE_ID_CACHED_USERS_WITH_SCORE: {
            final long accountId = ParseUtils.parseLong(uri.getLastPathSegment(), -1);
            final SQLSelectQuery query = CachedUsersQueryBuilder.withScore(projection, selection, sortOrder,
                    accountId);
            final Cursor c = mDatabaseWrapper.rawQuery(query.getSQL(), selectionArgs);
            setNotificationUri(c, CachedUsers.CONTENT_URI);
            return c;
        }
        case VIRTUAL_TABLE_ID_DRAFTS_UNSENT: {
            final FiretweetApplication app = FiretweetApplication.getInstance(getContext());
            final AsyncTwitterWrapper twitter = app.getTwitterWrapper();
            final RawItemArray sendingIds = new RawItemArray(twitter.getSendingDraftIds());
            final Expression where;
            if (selection != null) {
                where = Expression.and(new Expression(selection),
                        Expression.notIn(new Column(Drafts._ID), sendingIds));
            } else {
                where = Expression.and(Expression.notIn(new Column(Drafts._ID), sendingIds));
            }
            final Cursor c = mDatabaseWrapper.query(Drafts.TABLE_NAME, projection, where.getSQL(),
                    selectionArgs, null, null, sortOrder);
            setNotificationUri(c, getNotificationUri(tableId, uri));
            return c;
        }
        }
        if (table == null)
            return null;
        final Cursor c = mDatabaseWrapper.query(table, projection, selection, selectionArgs, null, null,
                sortOrder);
        setNotificationUri(c, getNotificationUri(tableId, uri));
        return c;
    } catch (final SQLException e) {
        Crashlytics.logException(e);
        throw new IllegalStateException(e);
    }
}

From source file:com.fututel.db.DBProvider.java

@Override
public int delete(Uri uri, String where, String[] whereArgs) {

    SQLiteDatabase db = mOpenHelper.getWritableDatabase();
    String finalWhere;// www.j a  va  2 s.  c om
    int count = 0;
    int matched = URI_MATCHER.match(uri);
    Uri regUri = uri;

    ArrayList<Long> oldRegistrationsAccounts = null;

    switch (matched) {
    case ACCOUNTS:
        count = db.delete(SipProfile.ACCOUNTS_TABLE_NAME, where, whereArgs);
        break;
    case ACCOUNTS_ID:
        finalWhere = DatabaseUtilsCompat
                .concatenateWhere(SipProfile.FIELD_ID + " = " + ContentUris.parseId(uri), where);
        count = db.delete(SipProfile.ACCOUNTS_TABLE_NAME, finalWhere, whereArgs);
        break;
    case CALLLOGS:
        count = db.delete(SipManager.CALLLOGS_TABLE_NAME, where, whereArgs);
        break;
    case CALLLOGS_ID:
        finalWhere = DatabaseUtilsCompat.concatenateWhere(CallLog.Calls._ID + " = " + ContentUris.parseId(uri),
                where);
        count = db.delete(SipManager.CALLLOGS_TABLE_NAME, finalWhere, whereArgs);
        break;
    case FILTERS:
        count = db.delete(SipManager.FILTERS_TABLE_NAME, where, whereArgs);
        break;
    case FILTERS_ID:
        finalWhere = DatabaseUtilsCompat.concatenateWhere(Filter._ID + " = " + ContentUris.parseId(uri), where);
        count = db.delete(SipManager.FILTERS_TABLE_NAME, finalWhere, whereArgs);
        break;
    case MESSAGES:
        count = db.delete(SipMessage.MESSAGES_TABLE_NAME, where, whereArgs);
        break;
    case MESSAGES_ID:
        finalWhere = DatabaseUtilsCompat
                .concatenateWhere(SipMessage.FIELD_ID + " = " + ContentUris.parseId(uri), where);
        count = db.delete(SipMessage.MESSAGES_TABLE_NAME, finalWhere, whereArgs);
        break;
    case THREADS_ID:
        String from = uri.getLastPathSegment();
        if (!TextUtils.isEmpty(from)) {
            count = db.delete(SipMessage.MESSAGES_TABLE_NAME, MESSAGES_THREAD_SELECTION,
                    new String[] { from, from });
        } else {
            count = 0;
        }
        regUri = SipMessage.MESSAGE_URI;
        break;
    case ACCOUNTS_STATUS:
        oldRegistrationsAccounts = new ArrayList<Long>();
        synchronized (profilesStatus) {
            for (Long accId : profilesStatus.keySet()) {
                oldRegistrationsAccounts.add(accId);
            }
            profilesStatus.clear();
        }
        break;
    case ACCOUNTS_STATUS_ID:
        long id = ContentUris.parseId(uri);
        synchronized (profilesStatus) {
            profilesStatus.remove(id);
        }
        break;
    default:
        throw new IllegalArgumentException(UNKNOWN_URI_LOG + uri);
    }

    getContext().getContentResolver().notifyChange(regUri, null);

    if (matched == ACCOUNTS_ID || matched == ACCOUNTS_STATUS_ID) {
        long rowId = ContentUris.parseId(uri);
        if (rowId >= 0) {
            if (matched == ACCOUNTS_ID) {
                broadcastAccountChange(rowId);
            } else if (matched == ACCOUNTS_STATUS_ID) {
                broadcastRegistrationChange(rowId);
            }
        }
    }
    if (matched == FILTERS || matched == FILTERS_ID) {
        Filter.resetCache();
    }
    if (matched == ACCOUNTS_STATUS && oldRegistrationsAccounts != null) {
        for (Long accId : oldRegistrationsAccounts) {
            if (accId != null) {
                broadcastRegistrationChange(accId);
            }
        }
    }

    return count;
}

From source file:group.pals.android.lib.ui.filechooser.FragmentFiles.java

@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    mLoading = true;//  w  w  w  .j  av a 2s  .c  om
    mNewLoader = true;

    mViewGroupFiles.setVisibility(View.GONE);
    mViewLoadingHandler.postDelayed(new Runnable() {

        @Override
        public void run() {
            mViewLoading.setVisibility(View.VISIBLE);
        }// run()
    }, DisplayPrefs.DELAY_TIME_FOR_SHORT_ANIMATION);

    getActivity().supportInvalidateOptionsMenu();

    final Uri path = ((Uri) args.getParcelable(PATH));
    buildAddressBar(path);

    String positiveRegex = getArguments().getString(FileChooserActivity.EXTRA_POSITIVE_REGEX_FILTER);
    String negativeRegex = getArguments().getString(FileChooserActivity.EXTRA_NEGATIVE_REGEX_FILTER);

    if (BuildConfig.DEBUG)
        Log.d(CLASSNAME, "onCreateLoader() >> path = " + path);

    return new CursorLoader(getActivity(), BaseFile.genContentUriBase(path.getAuthority()).buildUpon()
            .appendPath(path.getLastPathSegment())
            .appendQueryParameter(BaseFile.PARAM_TASK_ID, Integer.toString(mIdLoaderData))
            .appendQueryParameter(BaseFile.PARAM_SHOW_HIDDEN_FILES,
                    Boolean.toString(getArguments().getBoolean(FileChooserActivity.EXTRA_DISPLAY_HIDDEN_FILES)))
            .appendQueryParameter(BaseFile.PARAM_FILTER_MODE, Integer.toString(mFilterMode))
            .appendQueryParameter(BaseFile.PARAM_SORT_BY,
                    Integer.toString(DisplayPrefs.getSortType(getActivity())))
            .appendQueryParameter(BaseFile.PARAM_SORT_ASCENDING,
                    Boolean.toString(DisplayPrefs.isSortAscending(getActivity())))
            .appendQueryParameter(BaseFile.PARAM_LIMIT, Integer.toString(mMaxFileCount))
            .appendQueryParameter(BaseFile.PARAM_POSITIVE_REGEX_FILTER,
                    TextUtils.isEmpty(positiveRegex) ? "" : positiveRegex)
            .appendQueryParameter(BaseFile.PARAM_NEGATIVE_REGEX_FILTER,
                    TextUtils.isEmpty(negativeRegex) ? "" : negativeRegex)
            .build(), null, null, null, null);
}

From source file:com.applozic.mobicommons.file.FileUtils.java

/**
 * Get a file path from a Uri. This will get the the path for Storage Access
 * Framework Documents, as well as the _data field for the MediaStore and
 * other file-based ContentProviders.<br>
 * <br>/*from  w  ww . j av a  2  s  .c om*/
 * Callers should check whether the path is local before assuming it
 * represents a local file.
 *
 * @param context The context.
 * @param uri     The Uri to query.
 * @author paulburke
 * @see #isLocal(String)
 * @see #getFile(android.content.Context, android.net.Uri)
 */

public static String getPath(final Context context, final Uri uri) {

    if (DEBUG)
        Log.d(TAG + " File -",
                "Authority: " + uri.getAuthority() + ", Fragment: " + uri.getFragment() + ", Port: "
                        + uri.getPort() + ", Query: " + uri.getQuery() + ", Scheme: " + uri.getScheme()
                        + ", Host: " + uri.getHost() + ", Segments: " + uri.getPathSegments().toString());

    final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

    // DocumentProvider
    if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
        // LocalStorageProvider
        if (isLocalStorageDocument(uri)) {
            // The path is the id
            return DocumentsContract.getDocumentId(uri);
        }
        // ExternalStorageProvider
        else if (isExternalStorageDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            if ("primary".equalsIgnoreCase(type)) {
                return Environment.getExternalStorageDirectory() + "/" + split[1];
            }

            // TODO handle non-primary volumes
        }
        // DownloadsProvider
        else if (isDownloadsDocument(uri)) {

            final String id = DocumentsContract.getDocumentId(uri);
            final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),
                    Long.valueOf(id));

            return getDataColumn(context, contentUri, null, null);
        }
        // MediaProvider
        else if (isMediaDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            Uri contentUri = null;
            if ("image".equals(type)) {
                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else if ("video".equals(type)) {
                contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } else if ("audio".equals(type)) {
                contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }

            final String selection = "_id=?";
            final String[] selectionArgs = new String[] { split[1] };

            return getDataColumn(context, contentUri, selection, selectionArgs);
        }
    }
    // MediaStore (and general)
    else if ("content".equalsIgnoreCase(uri.getScheme())) {

        // Return the remote address
        if (isGooglePhotosUri(uri))
            return uri.getLastPathSegment();

        return getDataColumn(context, uri, null, null);
    }
    // File
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return null;
}

From source file:mil.nga.giat.mage.sdk.utils.MediaUtility.java

/**
* From:/*from  ww w  . jav  a 2  s .  c  o m*/
* https://github.com/iPaulPro/aFileChooser/blob/master/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java
*
* MODIFIED FOR MAGE:
*
* - Removed LocalStorageProvider references
* - Added and modified to use isDocumentUri and getDocumentId methods with KITKAT target api annotation
* - Added ExternalStorageProvider SD card handler section in the getPath method
* - Added getFileIfExists method
*
 * Get a file path from a Uri. This will get the the path for Storage Access
 * Framework Documents, as well as the _data field for the MediaStore and
 * other file-based ContentProviders.<br>
 * <br>
 * Callers should check whether the path is local before assuming it
 * represents a local file.
 * 
 * @param context The context.
 * @param uri The Uri to query.
* @author paulburke
 */
public static String getPath(final Context context, final Uri uri) {

    final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

    // DocumentProvider
    if (isKitKat && isDocumentUri(context, uri)) {

        // ExternalStorageProvider
        if (isExternalStorageDocument(uri)) {
            final String docId = getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            if ("primary".equalsIgnoreCase(type)) {
                return Environment.getExternalStorageDirectory() + "/" + split[1];
            }

            // Handle SD cards
            File file = getFileIfExists("/storage/extSdCard", split[1]);
            if (file != null) {
                return file.getAbsolutePath();
            }
            file = getFileIfExists("/storage/sdcard1", split[1]);
            if (file != null) {
                return file.getAbsolutePath();
            }
            file = getFileIfExists("/storage/usbcard1", split[1]);
            if (file != null) {
                return file.getAbsolutePath();
            }
            file = getFileIfExists("/storage/sdcard0", split[1]);
            if (file != null) {
                return file.getAbsolutePath();
            }

            // TODO handle non-primary volumes
        }
        // DownloadsProvider
        else if (isDownloadsDocument(uri)) {

            final String id = getDocumentId(uri);
            final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),
                    Long.valueOf(id));

            return getDataColumn(context, contentUri, null, null);
        }
        // MediaProvider
        else if (isMediaDocument(uri)) {
            final String docId = getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            Uri contentUri = null;
            if ("image".equals(type)) {
                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else if ("video".equals(type)) {
                contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } else if ("audio".equals(type)) {
                contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }

            final String selection = "_id=?";
            final String[] selectionArgs = new String[] { split[1] };

            return getDataColumn(context, contentUri, selection, selectionArgs);
        }
    }
    // MediaStore (and general)
    else if ("content".equalsIgnoreCase(uri.getScheme())) {

        // Return the remote address
        if (isGooglePhotosUri(uri))
            return uri.getLastPathSegment();

        return getDataColumn(context, uri, null, null);
    }
    // File
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return null;
}

From source file:com.haibison.android.anhuu.FragmentFiles.java

/**
 * As the name means.//w  ww. j a  v a 2 s .co m
 */
private void buildAddressBar(final Uri path) {
    if (path == null)
        return;

    mViewAddressBar.removeAllViews();

    new LoadingDialog<Void, Cursor, Void>(getActivity(), false) {

        LinearLayout.LayoutParams lpBtnLoc;
        LinearLayout.LayoutParams lpDivider;
        LayoutInflater inflater = getLayoutInflater(null);
        final int dim = getResources().getDimensionPixelSize(R.dimen.anhuu_f5be488d_5dp);
        int count = 0;

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

            lpBtnLoc = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT);
            lpBtnLoc.gravity = Gravity.CENTER;
        }// onPreExecute()

        @Override
        protected Void doInBackground(Void... params) {
            Cursor cursor = getActivity().getContentResolver().query(path, null, null, null, null);
            while (cursor != null) {
                if (cursor.moveToFirst()) {
                    publishProgress(cursor);
                    cursor.close();
                } else
                    break;

                /*
                 * Process the parent directory.
                 */
                Uri uri = Uri.parse(cursor.getString(cursor.getColumnIndex(BaseFile.COLUMN_URI)));
                cursor = getActivity().getContentResolver()
                        .query(BaseFile.genContentUriApi(uri.getAuthority()).buildUpon()
                                .appendPath(BaseFile.CMD_GET_PARENT)
                                .appendQueryParameter(BaseFile.PARAM_SOURCE, uri.getLastPathSegment()).build(),
                                null, null, null, null);
            } // while

            return null;
        }// doInBackground()

        @Override
        protected void onProgressUpdate(Cursor... progress) {
            /*
             * Add divider.
             */
            if (mViewAddressBar.getChildCount() > 0) {
                View divider = inflater.inflate(R.layout.anhuu_f5be488d_view_locations_divider, null);

                if (lpDivider == null) {
                    lpDivider = new LinearLayout.LayoutParams(dim, dim);
                    lpDivider.gravity = Gravity.CENTER;
                    lpDivider.setMargins(dim, dim, dim, dim);
                }
                mViewAddressBar.addView(divider, 0, lpDivider);
            }

            Uri lastUri = Uri.parse(progress[0].getString(progress[0].getColumnIndex(BaseFile.COLUMN_URI)));

            TextView btnLoc = (TextView) inflater.inflate(R.layout.anhuu_f5be488d_button_location, null);
            String name = BaseFileProviderUtils.getFileName(progress[0]);
            btnLoc.setText(TextUtils.isEmpty(name) ? getString(R.string.anhuu_f5be488d_root) : name);
            btnLoc.setTag(lastUri);
            btnLoc.setOnClickListener(mBtnLocationOnClickListener);
            btnLoc.setOnLongClickListener(mBtnLocationOnLongClickListener);
            mViewAddressBar.addView(btnLoc, 0, lpBtnLoc);

            if (count++ == 0) {
                Rect r = new Rect();
                btnLoc.getPaint().getTextBounds(name, 0, name.length(), r);
                if (r.width() >= getResources()
                        .getDimensionPixelSize(R.dimen.anhuu_f5be488d_button_location_max_width)
                        - btnLoc.getPaddingLeft() - btnLoc.getPaddingRight()) {
                    mTextFullDirName
                            .setText(progress[0].getString(progress[0].getColumnIndex(BaseFile.COLUMN_NAME)));
                    mTextFullDirName.setVisibility(View.VISIBLE);
                } else
                    mTextFullDirName.setVisibility(View.GONE);
            } // if
        }// onProgressUpdate()

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);

            /*
             * Sometimes without delay time, it doesn't work...
             */
            mViewLocationsContainer.postDelayed(new Runnable() {

                public void run() {
                    mViewLocationsContainer.fullScroll(HorizontalScrollView.FOCUS_RIGHT);
                }// run()
            }, Display.DELAY_TIME_FOR_VERY_SHORT_ANIMATION);
        }// onPostExecute()

    }.execute();
}

From source file:im.vector.receiver.VectorUniversalLinkReceiver.java

/***
 * Tries to parse an universal link./*w  w  w  .j a  v a2 s .  c o  m*/
 *
 * @param uri the uri to parse
 * @return the universal link items, null if the universal link is invalid
 */
public static HashMap<String, String> parseUniversalLink(Uri uri) {
    HashMap<String, String> map = null;

    try {
        // sanity check
        if ((null == uri) || TextUtils.isEmpty(uri.getPath())) {
            Log.e(LOG_TAG, "## parseUniversalLink : null");
            return null;
        }

        if (!TextUtils.equals(uri.getHost(), "vector.im") && !TextUtils.equals(uri.getHost(), "riot.im")
                && !TextUtils.equals(uri.getHost(), "matrix.to")) {
            Log.e(LOG_TAG, "## parseUniversalLink : unsupported host " + uri.getHost());
            return null;
        }

        boolean isSupportedHost = TextUtils.equals(uri.getHost(), "vector.im")
                || TextUtils.equals(uri.getHost(), "riot.im");

        // when the uri host is vector.im, it is followed by a dedicated path
        if (isSupportedHost && !mSupportedVectorLinkPaths.contains(uri.getPath())) {
            Log.e(LOG_TAG, "## parseUniversalLink : not supported");
            return null;
        }

        // remove the server part
        String uriFragment;
        if (null != (uriFragment = uri.getFragment())) {
            uriFragment = uriFragment.substring(1); // get rid of first "/"
        } else {
            Log.e(LOG_TAG, "## parseUniversalLink : cannot extract path");
            return null;
        }

        String temp[] = uriFragment.split("/", 3); // limit to 3 for security concerns (stack overflow injection)

        if (!isSupportedHost) {
            ArrayList<String> compliantList = new ArrayList<>(Arrays.asList(temp));
            compliantList.add(0, "room");
            temp = compliantList.toArray(new String[compliantList.size()]);
        }

        if (temp.length < 2) {
            Log.e(LOG_TAG, "## parseUniversalLink : too short");
            return null;
        }

        if (!TextUtils.equals(temp[0], "room") && !TextUtils.equals(temp[0], "user")) {
            Log.e(LOG_TAG, "## parseUniversalLink : not supported " + temp[0]);
            return null;
        }

        map = new HashMap<>();

        String firstParam = temp[1];

        if (MXSession.isUserId(firstParam)) {
            if (temp.length > 2) {
                Log.e(LOG_TAG, "## parseUniversalLink : universal link to member id is too long");
                return null;
            }

            map.put(ULINK_MATRIX_USER_ID_KEY, firstParam);
        } else if (MXSession.isRoomAlias(firstParam) || MXSession.isRoomId(firstParam)) {
            map.put(ULINK_ROOM_ID_OR_ALIAS_KEY, firstParam);
        } else if (MXSession.isGroupId(firstParam)) {
            map.put(ULINK_GROUP_ID_KEY, firstParam);
        }

        // room id only ?
        if (temp.length > 2) {
            String eventId = temp[2];

            if (MXSession.isMessageId(eventId)) {
                map.put(ULINK_EVENT_ID_KEY, temp[2]);
            } else {
                uri = Uri.parse(uri.toString().replace("#/room/", "room/"));

                map.put(ULINK_ROOM_ID_OR_ALIAS_KEY, uri.getLastPathSegment());

                Set<String> names = uri.getQueryParameterNames();

                for (String name : names) {
                    String value = uri.getQueryParameter(name);

                    try {
                        value = URLDecoder.decode(value, "UTF-8");
                    } catch (Exception e) {
                        Log.e(LOG_TAG, "## parseUniversalLink : URLDecoder.decode " + e.getMessage());
                        return null;
                    }

                    map.put(name, value);
                }
            }
        }
    } catch (Exception e) {
        Log.e(LOG_TAG, "## parseUniversalLink : crashes " + e.getLocalizedMessage());
    }

    // check if the parsing succeeds
    if ((null != map) && (map.size() < 1)) {
        Log.e(LOG_TAG, "## parseUniversalLink : empty dictionary");
        return null;
    }

    return map;
}

From source file:com.haibison.android.anhuu.FragmentFiles.java

@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    mLoading = true;/*from   ww  w . ja  va2  s  .  c om*/
    mNewLoader = true;

    mViewGroupFiles.setVisibility(View.GONE);
    mViewLoadingHandler.postDelayed(new Runnable() {

        @Override
        public void run() {
            mViewLoading.setVisibility(View.VISIBLE);
        }// run()
    }, Display.DELAY_TIME_FOR_SHORT_ANIMATION);

    getActivity().supportInvalidateOptionsMenu();

    final Uri path = ((Uri) args.getParcelable(PATH));
    buildAddressBar(path);

    String positiveRegex = getArguments().getString(FileChooserActivity.EXTRA_POSITIVE_REGEX_FILTER);
    String negativeRegex = getArguments().getString(FileChooserActivity.EXTRA_NEGATIVE_REGEX_FILTER);

    if (BuildConfig.DEBUG)
        Log.d(CLASSNAME, "onCreateLoader() >> path = " + path);

    return new CursorLoader(getActivity(), BaseFile.genContentUriBase(path.getAuthority()).buildUpon()
            .appendPath(path.getLastPathSegment())
            .appendQueryParameter(BaseFile.PARAM_TASK_ID, Integer.toString(mIdLoaderData))
            .appendQueryParameter(BaseFile.PARAM_SHOW_HIDDEN_FILES,
                    Boolean.toString(getArguments().getBoolean(FileChooserActivity.EXTRA_DISPLAY_HIDDEN_FILES)))
            .appendQueryParameter(BaseFile.PARAM_FILTER_MODE, Integer.toString(mFilterMode))
            .appendQueryParameter(BaseFile.PARAM_SORT_BY, Integer.toString(Display.getSortType(getActivity())))
            .appendQueryParameter(BaseFile.PARAM_SORT_ASCENDING,
                    Boolean.toString(Display.isSortAscending(getActivity())))
            .appendQueryParameter(BaseFile.PARAM_LIMIT, Integer.toString(mMaxFileCount))
            .appendQueryParameter(BaseFile.PARAM_POSITIVE_REGEX_FILTER,
                    TextUtils.isEmpty(positiveRegex) ? "" : positiveRegex)
            .appendQueryParameter(BaseFile.PARAM_NEGATIVE_REGEX_FILTER,
                    TextUtils.isEmpty(negativeRegex) ? "" : negativeRegex)
            .build(), null, null, null, null);
}

From source file:com.techmighty.baseplayer.MusicService.java

public boolean openFile(final String path) {
    if (D)/*  www  .ja v a2s.  c  om*/
        Log.d(TAG, "openFile: path = " + path);
    synchronized (this) {
        if (path == null) {
            return false;
        }

        if (mCursor == null) {
            Uri uri = Uri.parse(path);
            boolean shouldAddToPlaylist = true;
            long id = -1;
            try {
                id = Long.valueOf(uri.getLastPathSegment());
            } catch (NumberFormatException ex) {
                // Ignore
            }

            if (id != -1 && path.startsWith(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI.toString())) {
                updateCursor(uri);

            } else if (id != -1 && path.startsWith(MediaStore.Files.getContentUri("external").toString())) {
                updateCursor(id);

            } else if (path.startsWith("content://downloads/")) {

                String mpUri = getValueForDownloadedFile(this, uri, "mediaprovider_uri");
                if (D)
                    Log.i(TAG, "Downloaded file's MP uri : " + mpUri);
                if (!TextUtils.isEmpty(mpUri)) {
                    if (openFile(mpUri)) {
                        notifyChange(META_CHANGED);
                        return true;
                    } else {
                        return false;
                    }
                } else {
                    updateCursorForDownloadedFile(this, uri);
                    shouldAddToPlaylist = false;
                }

            } else {
                String where = MediaStore.Audio.Media.DATA + "=?";
                String[] selectionArgs = new String[] { path };
                updateCursor(where, selectionArgs);
            }
            try {
                if (mCursor != null && shouldAddToPlaylist) {
                    mPlaylist.clear();
                    mPlaylist.add(new MusicPlaybackTrack(mCursor.getLong(IDCOLIDX), -1,
                            BasePlayerUtils.IdType.NA, -1));
                    notifyChange(QUEUE_CHANGED);
                    mPlayPos = 0;
                    mHistory.clear();
                }
            } catch (final UnsupportedOperationException ex) {
                // Ignore
            }
        }

        mFileToPlay = path;
        mPlayer.setDataSource(mFileToPlay);
        if (mPlayer.isInitialized()) {
            mOpenFailedCounter = 0;
            return true;
        }

        String trackName = getTrackName();
        if (TextUtils.isEmpty(trackName)) {
            trackName = path;
        }
        sendErrorMessage(trackName);

        stop(true);
        return false;
    }
}

From source file:com.csipsimple.db.DBProvider.java

@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {

    // Constructs a new query builder and sets its table name
    SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
    String finalSortOrder = sortOrder;
    String[] finalSelectionArgs = selectionArgs;
    String finalGrouping = null;//from  w  ww . j  a  v a 2 s.c  o  m
    String finalHaving = null;
    int type = URI_MATCHER.match(uri);

    Uri regUri = uri;

    // Security check to avoid data retrieval from outside
    int remoteUid = Binder.getCallingUid();
    int selfUid = android.os.Process.myUid();
    if (remoteUid != selfUid) {
        if (type == ACCOUNTS || type == ACCOUNTS_ID) {
            for (String proj : projection) {
                if (proj.toLowerCase().contains(SipProfile.FIELD_DATA) || proj.toLowerCase().contains("*")) {
                    throw new SecurityException("Password not readable from external apps");
                }
            }
        }
    }
    // Security check to avoid project of invalid fields or lazy projection
    List<String> possibles = getPossibleFieldsForType(type);
    if (possibles == null) {
        throw new SecurityException("You are asking wrong values " + type);
    }
    checkProjection(possibles, projection);
    checkSelection(possibles, selection);

    Cursor c;
    long id;
    switch (type) {
    case ACCOUNTS:
        qb.setTables(SipProfile.ACCOUNTS_TABLE_NAME);
        if (sortOrder == null) {
            finalSortOrder = SipProfile.FIELD_PRIORITY + " ASC";
        }
        break;
    case ACCOUNTS_ID:
        qb.setTables(SipProfile.ACCOUNTS_TABLE_NAME);
        qb.appendWhere(SipProfile.FIELD_ID + "=?");
        finalSelectionArgs = DatabaseUtilsCompat.appendSelectionArgs(selectionArgs,
                new String[] { uri.getLastPathSegment() });
        break;
    case CALLLOGS:
        qb.setTables(SipManager.CALLLOGS_TABLE_NAME);
        if (sortOrder == null) {
            finalSortOrder = CallLog.Calls.DATE + " DESC";
        }
        break;
    case CALLLOGS_ID:
        qb.setTables(SipManager.CALLLOGS_TABLE_NAME);
        qb.appendWhere(CallLog.Calls._ID + "=?");
        finalSelectionArgs = DatabaseUtilsCompat.appendSelectionArgs(selectionArgs,
                new String[] { uri.getLastPathSegment() });
        break;
    case FILTERS:
        qb.setTables(SipManager.FILTERS_TABLE_NAME);
        if (sortOrder == null) {
            finalSortOrder = Filter.DEFAULT_ORDER;
        }
        break;
    case FILTERS_ID:
        qb.setTables(SipManager.FILTERS_TABLE_NAME);
        qb.appendWhere(Filter._ID + "=?");
        finalSelectionArgs = DatabaseUtilsCompat.appendSelectionArgs(selectionArgs,
                new String[] { uri.getLastPathSegment() });
        break;
    case MESSAGES:
        qb.setTables(SipMessage.MESSAGES_TABLE_NAME);
        if (sortOrder == null) {
            finalSortOrder = SipMessage.FIELD_DATE + " DESC";
        }
        break;
    case MESSAGES_ID:
        qb.setTables(SipMessage.MESSAGES_TABLE_NAME);
        qb.appendWhere(SipMessage.FIELD_ID + "=?");
        finalSelectionArgs = DatabaseUtilsCompat.appendSelectionArgs(selectionArgs,
                new String[] { uri.getLastPathSegment() });
        break;
    case THREADS:
        qb.setTables(SipMessage.MESSAGES_TABLE_NAME);
        if (sortOrder == null) {
            finalSortOrder = SipMessage.FIELD_DATE + " DESC";
        }
        projection = new String[] { "ROWID AS _id", SipMessage.FIELD_FROM, SipMessage.FIELD_FROM_FULL,
                SipMessage.FIELD_TO,
                "CASE " + "WHEN " + SipMessage.FIELD_FROM + "='SELF' THEN " + SipMessage.FIELD_TO + " WHEN "
                        + SipMessage.FIELD_FROM + "!='SELF' THEN " + SipMessage.FIELD_FROM
                        + " END AS message_ordering",
                SipMessage.FIELD_BODY, "MAX(" + SipMessage.FIELD_DATE + ") AS " + SipMessage.FIELD_DATE,
                "MIN(" + SipMessage.FIELD_READ + ") AS " + SipMessage.FIELD_READ,
                //SipMessage.FIELD_READ,
                "COUNT(" + SipMessage.FIELD_DATE + ") AS counter" };
        //qb.appendWhere(SipMessage.FIELD_TYPE + " in (" + SipMessage.MESSAGE_TYPE_INBOX
        //        + "," + SipMessage.MESSAGE_TYPE_SENT + ")");
        finalGrouping = "message_ordering";
        regUri = SipMessage.MESSAGE_URI;
        break;
    case THREADS_ID:
        qb.setTables(SipMessage.MESSAGES_TABLE_NAME);
        if (sortOrder == null) {
            finalSortOrder = SipMessage.FIELD_DATE + " DESC";
        }
        projection = new String[] { "ROWID AS _id", SipMessage.FIELD_FROM, SipMessage.FIELD_TO,
                SipMessage.FIELD_BODY, SipMessage.FIELD_DATE, SipMessage.FIELD_MIME_TYPE, SipMessage.FIELD_TYPE,
                SipMessage.FIELD_STATUS, SipMessage.FIELD_FROM_FULL };
        qb.appendWhere(MESSAGES_THREAD_SELECTION);
        String from = uri.getLastPathSegment();
        finalSelectionArgs = DatabaseUtilsCompat.appendSelectionArgs(selectionArgs,
                new String[] { from, from });
        regUri = SipMessage.MESSAGE_URI;
        break;
    case ACCOUNTS_STATUS:
        synchronized (profilesStatus) {
            ContentValues[] cvs = new ContentValues[profilesStatus.size()];
            int i = 0;
            for (ContentValues ps : profilesStatus.values()) {
                cvs[i] = ps;
                i++;
            }
            c = getCursor(cvs);
        }
        if (c != null) {
            c.setNotificationUri(getContext().getContentResolver(), uri);
        }
        return c;
    case ACCOUNTS_STATUS_ID:
        id = ContentUris.parseId(uri);
        synchronized (profilesStatus) {
            ContentValues cv = profilesStatus.get(id);
            if (cv == null) {
                return null;
            }
            c = getCursor(new ContentValues[] { cv });
        }
        c.setNotificationUri(getContext().getContentResolver(), uri);
        return c;
    default:
        throw new IllegalArgumentException(UNKNOWN_URI_LOG + uri);
    }

    SQLiteDatabase db = mOpenHelper.getReadableDatabase();

    c = qb.query(db, projection, selection, finalSelectionArgs, finalGrouping, finalHaving, finalSortOrder);

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