Example usage for android.net Uri getPathSegments

List of usage examples for android.net Uri getPathSegments

Introduction

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

Prototype

public abstract List<String> getPathSegments();

Source Link

Document

Gets the decoded path segments.

Usage

From source file:com.microsoft.windowsazure.mobileservices.sdk.testapp.test.MobileServiceFeaturesTests.java

private void testSyncTablePullOperationsFeatureHeader(OfflineTableTestOperation operation,
        final String expectedFeaturesHeader) {
    MobileServiceClient client = null;//w  w w .  ja v a 2 s. c  o  m
    try {
        client = new MobileServiceClient(appUrl, appKey, getInstrumentation().getTargetContext());
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }

    MobileServiceLocalStoreMock store = new MobileServiceLocalStoreMock();
    // Add a new filter to the client
    client = client.withFilter(new ServiceFilter() {

        @Override
        public ListenableFuture<ServiceFilterResponse> handleRequest(ServiceFilterRequest request,
                NextServiceFilterCallback nextServiceFilterCallback) {

            boolean isFirstPage = request.getUrl().contains("$skip=0");

            final SettableFuture<ServiceFilterResponse> resultFuture = SettableFuture.create();
            String featuresHeaderName = "X-ZUMO-FEATURES";

            Header[] headers = request.getHeaders();
            String features = null;
            for (int i = 0; i < headers.length; i++) {
                if (headers[i].getName() == featuresHeaderName) {
                    features = headers[i].getValue();
                }
            }

            if (features == null) {
                resultFuture.setException(new Exception("No " + featuresHeaderName + " header on API call"));
            } else if (!features.equals(expectedFeaturesHeader)) {
                resultFuture.setException(new Exception("Incorrect features header; expected "
                        + expectedFeaturesHeader + ", actual " + features));
            } else {
                ServiceFilterResponseMock response = new ServiceFilterResponseMock();
                Uri requestUri = Uri.parse(request.getUrl());

                String content = "[]";

                if (isFirstPage) {
                    content = "{\"id\":\"the-id\",\"firstName\":\"John\",\"lastName\":\"Doe\",\"age\":33}";

                    if (request.getMethod().equalsIgnoreCase("GET")
                            && requestUri.getPathSegments().size() == 2) {
                        // GET which should return an array of results
                        content = "[" + content + "]";
                    }

                }

                response.setContent(content);
                resultFuture.set(response);
            }

            return resultFuture;
        }
    });

    try {
        Map<String, ColumnDataType> tableDefinition = new HashMap<String, ColumnDataType>();
        tableDefinition.put("id", ColumnDataType.String);
        tableDefinition.put("firstName", ColumnDataType.String);
        tableDefinition.put("lastName", ColumnDataType.String);
        tableDefinition.put("age", ColumnDataType.Integer);
        store.defineTable("Person", tableDefinition);

        client.getSyncContext().initialize(store, new SimpleSyncHandler()).get();

        MobileServiceSyncTable<PersonTestObjectWithStringId> typedTable = client
                .getSyncTable(PersonTestObjectWithStringId.class);
        MobileServiceJsonSyncTable jsonTable = client.getSyncTable("Person");
        operation.executeOperation(client, typedTable, jsonTable);
    } catch (Exception exception) {
        Throwable ex = exception;
        while (ex instanceof ExecutionException || ex instanceof MobileServiceException) {
            ex = ex.getCause();
        }
        fail(ex.getMessage());
    }
}

From source file:pl.selvin.android.syncframework.content.BaseContentProvider.java

@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
    final int code = contentHelper.matchUri(uri);
    if (code != UriMatcher.NO_MATCH) {
        if (code == ContentHelper.uriSyncCode) {
            return null;
        }//  w  w w. j a  va 2  s .  co m
        SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
        final TableInfo tab = contentHelper.getTableFromCode(code & ContentHelper.uriCode);
        builder.setTables(tab.name);
        if (isItemCode(code)) {
            if (isItemRowIDCode(code)) {
                selection = "isDeleted=0 AND ROWID=" + uri.getPathSegments().get(2)
                        + (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : "");
            } else {
                selection = "isDeleted=0" + tab.getSelection()
                        + (!TextUtils.isEmpty(selection) ? " AND (" + selection + ")" : "");
                int i = 0;
                final String[] old = selectionArgs;
                final int len = (old == null) ? 0 : old.length;
                selectionArgs = new String[len + tab.primaryKey.length];
                for (; i < tab.primaryKey.length; i++) {
                    selectionArgs[i] = uri.getPathSegments().get(i + 1);
                }
                if (len > 0) {
                    for (; i < old.length; i++) {
                        selectionArgs[i] = old[i - tab.primaryKey.length];
                    }
                }
            }
        } else {
            selection = "isDeleted=0" + (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : "");
        }
        builder.setProjectionMap(tab.map);

        Cursor cursor = builder.query(getReadableDatabase(), projection, selection, selectionArgs, null, null,
                sortOrder);
        if (DEBUG) {
            Log.d("Query",
                    builder.buildQuery(projection, selection, selectionArgs, null, null, sortOrder, null));
        }
        cursor.setNotificationUri(getContext().getContentResolver(), uri);
        return cursor;
    }
    throw new IllegalArgumentException("Unknown Uri " + uri);
}

From source file:com.android.contacts.list.DefaultContactBrowseListFragment.java

/**
 * Share all contacts that are currently selected. This method is pretty inefficient for
 * handling large numbers of contacts. I don't expect this to be a problem.
 *///from   www. java2  s .  c o m
private void shareSelectedContacts() {
    final StringBuilder uriListBuilder = new StringBuilder();
    for (Long contactId : getSelectedContactIds()) {
        final Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactId);
        final Uri lookupUri = ContactsContract.Contacts.getLookupUri(getContext().getContentResolver(),
                contactUri);
        if (lookupUri == null) {
            continue;
        }
        final List<String> pathSegments = lookupUri.getPathSegments();
        if (pathSegments.size() < 2) {
            continue;
        }
        final String lookupKey = pathSegments.get(pathSegments.size() - 2);
        if (uriListBuilder.length() > 0) {
            uriListBuilder.append(':');
        }
        uriListBuilder.append(Uri.encode(lookupKey));
    }
    if (uriListBuilder.length() == 0) {
        return;
    }
    final Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_MULTI_VCARD_URI,
            Uri.encode(uriListBuilder.toString()));
    final Intent intent = new Intent(Intent.ACTION_SEND);
    intent.setType(ContactsContract.Contacts.CONTENT_VCARD_TYPE);
    intent.putExtra(Intent.EXTRA_STREAM, uri);
    try {
        startActivityForResult(Intent.createChooser(intent, getResources()
                .getQuantityString(R.plurals.title_share_via, /* quantity */ getSelectedContactIds().size())),
                ACTIVITY_REQUEST_CODE_SHARE);
    } catch (final ActivityNotFoundException ex) {
        Toast.makeText(getContext(), R.string.share_error, Toast.LENGTH_SHORT).show();
    }
}

From source file:org.tomahawk.tomahawk_android.activities.TomahawkMainActivity.java

private void handleIntent(Intent intent) {
    if (SHOW_PLAYBACKFRAGMENT_ON_STARTUP.equals(intent.getAction())) {
        // if this Activity is being shown after the user clicked the notification
        if (mSlidingUpPanelLayout != null) {
            mSlidingUpPanelLayout.expandPanel();
        }//from  ww w.ja  v a2 s. c  om
    }
    if (intent.hasExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE)) {
        Bundle bundle = new Bundle();
        bundle.putInt(TomahawkFragment.CONTENT_HEADER_MODE, ContentHeaderFragment.MODE_HEADER_STATIC_SMALL);
        FragmentUtils.replace(this, PreferencePagerFragment.class, bundle);
    }

    if (intent.getData() != null) {
        final Uri data = intent.getData();
        intent.setData(null);
        List<String> pathSegments = data.getPathSegments();
        String host = data.getHost();
        String scheme = data.getScheme();
        if ((scheme != null && (scheme.equals("spotify") || scheme.equals("tomahawk"))) || (host != null
                && (host.contains("spotify.com") || host.contains("hatchet.is") || host.contains("toma.hk")
                        || host.contains("beatsmusic.com") || host.contains("deezer.com")
                        || host.contains("rdio.com") || host.contains("soundcloud.com")))) {
            PipeLine.get().lookupUrl(data.toString());
        } else if ((pathSegments != null && pathSegments.get(pathSegments.size() - 1).endsWith(".xspf"))
                || (intent.getType() != null && intent.getType().equals("application/xspf+xml"))) {
            TomahawkRunnable r = new TomahawkRunnable(TomahawkRunnable.PRIORITY_IS_INFOSYSTEM_HIGH) {
                @Override
                public void run() {
                    Playlist pl = XspfParser.parse(data);
                    if (pl != null) {
                        final Bundle bundle = new Bundle();
                        bundle.putString(TomahawkFragment.PLAYLIST, pl.getCacheKey());
                        bundle.putInt(TomahawkFragment.CONTENT_HEADER_MODE,
                                ContentHeaderFragment.MODE_HEADER_DYNAMIC);
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                FragmentUtils.replace(TomahawkMainActivity.this, PlaylistEntriesFragment.class,
                                        bundle);
                            }
                        });
                    }
                }
            };
            ThreadManager.get().execute(r);
        } else if (pathSegments != null && (pathSegments.get(pathSegments.size() - 1).endsWith(".axe")
                || pathSegments.get(pathSegments.size() - 1).endsWith(".AXE"))) {
            InstallPluginConfigDialog dialog = new InstallPluginConfigDialog();
            Bundle args = new Bundle();
            args.putString(InstallPluginConfigDialog.PATH_TO_AXE_URI_STRING, data.toString());
            dialog.setArguments(args);
            dialog.show(getSupportFragmentManager(), null);
        } else {
            String albumName;
            String trackName;
            String artistName;
            try {
                MediaMetadataRetriever retriever = new MediaMetadataRetriever();
                retriever.setDataSource(this, data);
                albumName = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM);
                artistName = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST);
                trackName = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE);
                retriever.release();
            } catch (Exception e) {
                Log.e(TAG, "handleIntent: " + e.getClass() + ": " + e.getLocalizedMessage());
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        String msg = TomahawkApp.getContext().getString(R.string.invalid_file);
                        Toast.makeText(TomahawkApp.getContext(), msg, Toast.LENGTH_LONG).show();
                    }
                });
                return;
            }
            if (TextUtils.isEmpty(trackName) && pathSegments != null) {
                trackName = pathSegments.get(pathSegments.size() - 1);
            }
            Query query = Query.get(trackName, albumName, artistName, false);
            Result result = Result.get(data.toString(), query.getBasicTrack(),
                    UserCollectionStubResolver.get());
            float trackScore = query.howSimilar(result);
            query.addTrackResult(result, trackScore);
            Bundle bundle = new Bundle();
            List<Query> queries = new ArrayList<>();
            queries.add(query);
            Playlist playlist = Playlist.fromQueryList(TomahawkMainActivity.getSessionUniqueStringId(), false,
                    "", "", queries);
            bundle.putString(TomahawkFragment.PLAYLIST, playlist.getCacheKey());
            bundle.putInt(TomahawkFragment.CONTENT_HEADER_MODE, ContentHeaderFragment.MODE_HEADER_DYNAMIC);
            FragmentUtils.replace(TomahawkMainActivity.this, PlaylistEntriesFragment.class, bundle);
        }
    }
}

From source file:org.xbmc.kore.ui.sections.remote.RemoteActivity.java

/**
 * Converts a video url to a Kodi plugin URL.
 *
 * @param playuri some URL/*from   ww w .  j  a  va  2  s.c  o m*/
 * @return plugin URL
 */
private String toPluginUrl(Uri playuri) {
    String host = playuri.getHost();
    if (host.endsWith("svtplay.se")) {
        Pattern pattern = Pattern.compile("^(?:https?:\\/\\/)?(?:www\\.)?svtplay\\.se\\/video\\/(\\d+\\/.*)",
                Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(playuri.toString());
        if (matcher.matches()) {
            return "plugin://plugin.video.svtplay/?url=%2Fvideo%2F" + URLEncoder.encode(matcher.group(1))
                    + "&mode=video";
        }
    } else if (host.endsWith("vimeo.com")) {
        String last = playuri.getLastPathSegment();
        if (last.matches("\\d+")) {
            return "plugin://plugin.video.vimeo/play/?video_id=" + last;
        }
    } else if (host.endsWith("youtube.com")) {
        if (playuri.getPathSegments().contains("playlist")) {
            return "plugin://plugin.video.youtube/play/?order=default&playlist_id="
                    + playuri.getQueryParameter("list");
        } else {
            return "plugin://plugin.video.youtube/play/?video_id=" + playuri.getQueryParameter("v");
        }
    } else if (host.endsWith("youtu.be")) {
        return "plugin://plugin.video.youtube/play/?video_id=" + playuri.getLastPathSegment();
    }
    return null;
}

From source file:com.android.calendar.AllInOneActivity.java

private long parseViewAction(final Intent intent) {
    long timeMillis = -1;
    Uri data = intent.getData();
    if (data != null && data.isHierarchical()) {
        List<String> path = data.getPathSegments();
        if (path.size() == 2 && path.get(0).equals("events")) {
            try {
                mViewEventId = Long.valueOf(data.getLastPathSegment());
                if (mViewEventId != -1) {
                    mIntentEventStartMillis = intent.getLongExtra(EXTRA_EVENT_BEGIN_TIME, 0);
                    mIntentEventEndMillis = intent.getLongExtra(EXTRA_EVENT_END_TIME, 0);
                    mIntentAttendeeResponse = intent.getIntExtra(ATTENDEE_STATUS,
                            Attendees.ATTENDEE_STATUS_NONE);
                    mIntentAllDay = intent.getBooleanExtra(EXTRA_EVENT_ALL_DAY, false);
                    timeMillis = mIntentEventStartMillis;
                }/*from ww w. ja  va 2s.  c  o  m*/
            } catch (NumberFormatException e) {
                // Ignore if mViewEventId can't be parsed
            }
        }
    }
    return timeMillis;
}

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

@Override
public Uri insert(@NonNull Uri uri, ContentValues values) {
    try {// ww  w .  jav  a  2 s. 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.android.contacts.activities.PeopleActivity.java

/**
 * Share all contacts that are currently selected in mAllFragment. This method is pretty
 * inefficient for handling large numbers of contacts. I don't expect this to be a problem.
 *//*from www.j ava  2 s  . co m*/
private void shareSelectedContacts() {
    final StringBuilder uriListBuilder = new StringBuilder();
    for (Long contactId : mAllFragment.getSelectedContactIds()) {
        final Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId);
        final Uri lookupUri = Contacts.getLookupUri(getContentResolver(), contactUri);
        if (lookupUri == null) {
            continue;
        }
        final List<String> pathSegments = lookupUri.getPathSegments();
        if (pathSegments.size() < 2) {
            continue;
        }
        final String lookupKey = pathSegments.get(pathSegments.size() - 2);
        if (uriListBuilder.length() > 0) {
            uriListBuilder.append(':');
        }
        uriListBuilder.append(Uri.encode(lookupKey));
    }
    if (uriListBuilder.length() == 0) {
        return;
    }
    final Uri uri = Uri.withAppendedPath(Contacts.CONTENT_MULTI_VCARD_URI,
            Uri.encode(uriListBuilder.toString()));
    final Intent intent = new Intent(Intent.ACTION_SEND);
    intent.setType(Contacts.CONTENT_VCARD_TYPE);
    intent.putExtra(Intent.EXTRA_STREAM, uri);
    ImplicitIntentsUtil.startActivityOutsideApp(this, intent);
}

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

@Override
public int delete(final Uri uri, final String selection, final String[] selectionArgs) {
    try {/* w w  w .j a v  a 2s  .  c  o  m*/
        final int tableId = getTableId(uri);
        final String table = getTableNameById(tableId);
        switch (tableId) {
        case TABLE_ID_DIRECT_MESSAGES_CONVERSATION:
        case TABLE_ID_DIRECT_MESSAGES:
        case TABLE_ID_DIRECT_MESSAGES_CONVERSATIONS_ENTRIES:
            return 0;
        case VIRTUAL_TABLE_ID_NOTIFICATIONS: {
            final List<String> segments = uri.getPathSegments();
            if (segments.size() == 1) {
                clearNotification();
            } else if (segments.size() == 2) {
                final int notificationType = ParseUtils.parseInt(segments.get(1));
                clearNotification(notificationType, 0);
            } else if (segments.size() == 3) {
                final int notificationType = ParseUtils.parseInt(segments.get(1));
                final long accountId = ParseUtils.parseLong(segments.get(2));
                clearNotification(notificationType, accountId);
            }
            return 1;
        }
        case VIRTUAL_TABLE_ID_UNREAD_COUNTS: {
            final List<String> segments = uri.getPathSegments();
            final int segmentsSize = segments.size();
            if (segmentsSize == 1)
                return clearUnreadCount();
            else if (segmentsSize == 2)
                return clearUnreadCount(ParseUtils.parseInt(segments.get(1)));
            else if (segmentsSize == 4)
                return removeUnreadItems(ParseUtils.parseInt(segments.get(1)),
                        ParseUtils.parseLong(segments.get(2)),
                        TwidereArrayUtils.parseLongArray(segments.get(3), ','));
            return 0;
        }
        }
        if (table == null)
            return 0;
        final int result = mDatabaseWrapper.delete(table, selection, selectionArgs);
        if (result > 0) {
            onDatabaseUpdated(tableId, uri);
        }
        return result;
    } catch (final SQLException e) {
        throw new IllegalStateException(e);
    }
}

From source file:com.android.mail.browse.ConversationCursor.java

/**
 * Regenerate the original Uri from a forwarding (ConversationProvider) Uri
 * NOTE: See note above for uriToCachingUri
 * @param uri the forwarding Uri// w  w w  .j  av a 2  s . c o  m
 * @return the original Uri
 */
private static Uri uriFromCachingUri(Uri uri) {
    String authority = uri.getAuthority();
    // Don't modify uri's that aren't ours
    if (!authority.equals(ConversationProvider.AUTHORITY)) {
        return uri;
    }
    List<String> path = uri.getPathSegments();
    Uri.Builder builder = new Uri.Builder().scheme(uri.getScheme()).authority(path.get(0));
    for (int i = 1; i < path.size(); i++) {
        builder.appendPath(path.get(i));
    }
    return builder.build();
}