Example usage for android.net Uri buildUpon

List of usage examples for android.net Uri buildUpon

Introduction

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

Prototype

public abstract Builder buildUpon();

Source Link

Document

Constructs a new builder, copying the attributes from this Uri.

Usage

From source file:org.getlantern.firetweet.fragment.support.UserFragment.java

@Override
public void onLinkClick(final String link, final String orig, final long accountId, long extraId,
        final int type, final boolean sensitive, int start, int end) {
    final ParcelableUser user = getUser();
    if (user == null)
        return;//from   w w  w.  j a  v a2  s  .  co m
    switch (type) {
    case FiretweetLinkify.LINK_TYPE_MENTION: {
        openUserProfile(getActivity(), user.account_id, -1, link, null);
        break;
    }
    case FiretweetLinkify.LINK_TYPE_HASHTAG: {
        openTweetSearch(getActivity(), user.account_id, "#" + link);
        break;
    }
    case FiretweetLinkify.LINK_TYPE_LINK: {
        final Uri uri = Uri.parse(link);
        final Intent intent;
        if (uri.getScheme() != null) {
            intent = new Intent(Intent.ACTION_VIEW, uri);
        } else {
            intent = new Intent(Intent.ACTION_VIEW, uri.buildUpon().scheme("http").build());
        }
        startActivity(intent);
        break;
    }
    case FiretweetLinkify.LINK_TYPE_LIST: {
        if (link == null)
            break;
        final String[] mentionList = link.split("/");
        if (mentionList.length != 2) {
            break;
        }
        break;
    }
    case FiretweetLinkify.LINK_TYPE_STATUS: {
        openStatus(getActivity(), accountId, parseLong(link));
        break;
    }
    }
}

From source file:com.cerema.cloud2.authentication.AuthenticatorActivity.java

/**
 * Starts the OAuth 'grant type' flow to get an access token, with 
 * a GET AUTHORIZATION request to the BUILT-IN authorization server. 
 *//*  w  ww.j  av a2 s  .c om*/
private void startOauthorization() {
    // be gentle with the user
    mAuthStatusIcon = R.drawable.progress_small;
    mAuthStatusText = R.string.oauth_login_connection;
    showAuthStatus();

    // GET AUTHORIZATION request
    Uri uri = Uri.parse(mOAuthAuthEndpointText.getText().toString().trim());
    Uri.Builder uriBuilder = uri.buildUpon();
    uriBuilder.appendQueryParameter(OAuth2Constants.KEY_RESPONSE_TYPE,
            getString(R.string.oauth2_response_type));
    uriBuilder.appendQueryParameter(OAuth2Constants.KEY_REDIRECT_URI, getString(R.string.oauth2_redirect_uri));
    uriBuilder.appendQueryParameter(OAuth2Constants.KEY_CLIENT_ID, getString(R.string.oauth2_client_id));
    uriBuilder.appendQueryParameter(OAuth2Constants.KEY_SCOPE, getString(R.string.oauth2_scope));
    uri = uriBuilder.build();
    Log_OC.d(TAG, "Starting browser to view " + uri.toString());
    Intent i = new Intent(Intent.ACTION_VIEW, uri);
    startActivity(i);
}

From source file:com.owncloud.android.authentication.AuthenticatorActivity.java

/**
 * Starts the OAuth 'grant type' flow to get an access token, with a GET
 * AUTHORIZATION request to the BUILT-IN authorization server.
 *//*from   w  w w .  ja v  a 2  s  .  c  o  m*/
private void startOauthorization() {
    // be gentle with the user
    mAuthStatusIcon = R.drawable.progress_small;
    mAuthStatusText = R.string.oauth_login_connection;
    showAuthStatus();

    // GET AUTHORIZATION request
    // Uri uri = Uri.parse(getString(R.string.oauth2_url_endpoint_auth));
    Uri uri = Uri.parse(mOAuthAuthEndpointText.getText().toString().trim());
    Uri.Builder uriBuilder = uri.buildUpon();
    uriBuilder.appendQueryParameter(OAuth2Constants.KEY_RESPONSE_TYPE,
            getString(R.string.oauth2_response_type));
    uriBuilder.appendQueryParameter(OAuth2Constants.KEY_REDIRECT_URI, getString(R.string.oauth2_redirect_uri));
    uriBuilder.appendQueryParameter(OAuth2Constants.KEY_CLIENT_ID, getString(R.string.oauth2_client_id));
    uriBuilder.appendQueryParameter(OAuth2Constants.KEY_SCOPE, getString(R.string.oauth2_scope));
    // uriBuilder.appendQueryParameter(OAuth2Constants.KEY_STATE,
    // whateverwewant);
    uri = uriBuilder.build();
    Log_OC.d(TAG, "Starting browser to view " + uri.toString());
    Intent i = new Intent(Intent.ACTION_VIEW, uri);
    startActivity(i);
}

From source file:org.voidsink.anewjkuapp.update.ImportExamTask.java

@Override
protected Void doInBackground(Void... params) {
    Log.d(TAG, "Start importing exams");

    synchronized (sync_lock) {
        final DateFormat df = DateFormat.getDateInstance();

        try {/*  ww  w. j a  v a2 s  .c  om*/
            Log.d(TAG, "setup connection");

            updateNotify(mContext.getString(R.string.notification_sync_connect));

            if (KusssHandler.getInstance().isAvailable(mContext,
                    AppUtils.getAccountAuthToken(mContext, mAccount),
                    AppUtils.getAccountName(mContext, mAccount),
                    AppUtils.getAccountPassword(mContext, mAccount))) {

                updateNotify(mContext.getString(R.string.notification_sync_exam_loading));

                List<Exam> exams;
                if (PreferenceWrapper.getNewExamsByCourseId(mContext)) {
                    CourseMap courseMap = new CourseMap(mContext);
                    List<Term> terms = KusssContentProvider.getTerms(mContext);

                    Log.d(TAG, "load exams by courseId");
                    exams = KusssHandler.getInstance().getNewExamsByCourseId(mContext, courseMap.getCourses(),
                            terms);
                } else {
                    Log.d(TAG, "load exams");
                    exams = KusssHandler.getInstance().getNewExams(mContext);
                }
                if (exams == null) {
                    mSyncResult.stats.numParseExceptions++;
                } else {
                    Map<String, Exam> examMap = new HashMap<>();
                    for (Exam exam : exams) {
                        Exam old = examMap.put(
                                KusssHelper.getExamKey(exam.getCourseId(),
                                        AppUtils.termToString(exam.getTerm()), exam.getDtStart().getTime()),
                                exam);
                        if (old != null) {
                            Log.w(TAG, "exam alread loaded: " + KusssHelper.getExamKey(old.getCourseId(),
                                    AppUtils.termToString(old.getTerm()), old.getDtStart().getTime()));
                        }
                    }

                    Log.d(TAG, String.format("got %s exams", exams.size()));

                    updateNotify(mContext.getString(R.string.notification_sync_exam_updating));

                    ArrayList<ContentProviderOperation> batch = new ArrayList<>();

                    Uri examUri = KusssContentContract.Exam.CONTENT_URI;
                    Cursor c = mProvider.query(examUri, EXAM_PROJECTION, null, null, null);

                    if (c == null) {
                        Log.w(TAG, "selection failed");
                    } else {
                        Log.d(TAG, "Found " + c.getCount() + " local entries. Computing merge solution...");
                        int examId;
                        String examTerm;
                        String examCourseId;
                        long examDtStart;
                        long examDtEnd;
                        String examLocation;

                        while (c.moveToNext()) {
                            examId = c.getInt(COLUMN_EXAM_ID);
                            examTerm = c.getString(COLUMN_EXAM_TERM);
                            examCourseId = c.getString(COLUMN_EXAM_COURSEID);
                            examDtStart = c.getLong(COLUMN_EXAM_DTSTART);
                            examDtEnd = c.getLong(COLUMN_EXAM_DTEND);
                            examLocation = c.getString(COLUMN_EXAM_LOCATION);

                            Exam exam = examMap
                                    .remove(KusssHelper.getExamKey(examCourseId, examTerm, examDtStart));
                            if (exam != null) {
                                // Check to see if the entry needs to be
                                // updated
                                Uri existingUri = examUri.buildUpon().appendPath(Integer.toString(examId))
                                        .build();
                                Log.d(TAG, "Scheduling update: " + existingUri);

                                if (!DateUtils.isSameDay(new Date(examDtStart), exam.getDtStart())
                                        || !new Date(examDtEnd).equals(exam.getDtEnd())
                                        || !examLocation.equals(exam.getLocation())) {
                                    mNewExamNotification.addUpdate(getEventString(exam));
                                }

                                batch.add(ContentProviderOperation
                                        .newUpdate(KusssContentContract.asEventSyncAdapter(existingUri,
                                                mAccount.name, mAccount.type))
                                        .withValue(KusssContentContract.Exam.COL_ID, Integer.toString(examId))
                                        .withValues(KusssHelper.getExamContentValues(exam)).build());
                                mSyncResult.stats.numUpdates++;
                            } else if (examDtStart > mSyncFromNow - DateUtils.MILLIS_PER_DAY) {
                                // Entry doesn't exist. Remove only newer
                                // events from the database.
                                Uri deleteUri = examUri.buildUpon().appendPath(Integer.toString(examId))
                                        .build();
                                Log.d(TAG, "Scheduling delete: " + deleteUri);

                                batch.add(ContentProviderOperation.newDelete(KusssContentContract
                                        .asEventSyncAdapter(deleteUri, mAccount.name, mAccount.type)).build());
                                mSyncResult.stats.numDeletes++;
                            }
                        }
                        c.close();

                        for (Exam exam : examMap.values()) {
                            batch.add(ContentProviderOperation
                                    .newInsert(KusssContentContract.asEventSyncAdapter(examUri, mAccount.name,
                                            mAccount.type))
                                    .withValues(KusssHelper.getExamContentValues(exam)).build());
                            Log.d(TAG, "Scheduling insert: " + exam.getTerm() + " " + exam.getCourseId());

                            mNewExamNotification.addInsert(getEventString(exam));

                            mSyncResult.stats.numInserts++;
                        }

                        if (batch.size() > 0) {
                            updateNotify(mContext.getString(R.string.notification_sync_exam_saving));

                            Log.d(TAG, "Applying batch update");
                            mProvider.applyBatch(batch);
                            Log.d(TAG, "Notify resolver");
                            mResolver.notifyChange(KusssContentContract.Exam.CONTENT_CHANGED_URI, null, // No
                                    // local
                                    // observer
                                    false); // IMPORTANT: Do not
                            // sync to
                            // network
                        } else {
                            Log.w(TAG, "No batch operations found! Do nothing");
                        }
                    }
                }
                KusssHandler.getInstance().logout(mContext);
            } else {
                mSyncResult.stats.numAuthExceptions++;
            }
        } catch (Exception e) {
            Analytics.sendException(mContext, e, true);
            Log.e(TAG, "import failed", e);
        }
    }

    setImportDone();

    return null;
}

From source file:org.mariotaku.twidere.fragment.support.UserFragment.java

@Override
public void onLinkClick(final String link, final String orig, final long accountId, long extraId,
        final int type, final boolean sensitive, int start, int end) {
    final ParcelableUser user = getUser();
    if (user == null)
        return;//from  w w w .j a  va 2s . c o m
    switch (type) {
    case TwidereLinkify.LINK_TYPE_MENTION: {
        Utils.openUserProfile(getActivity(), user.account_id, -1, link, null);
        break;
    }
    case TwidereLinkify.LINK_TYPE_HASHTAG: {
        Utils.openTweetSearch(getActivity(), user.account_id, "#" + link);
        break;
    }
    case TwidereLinkify.LINK_TYPE_LINK: {
        final Uri uri = Uri.parse(link);
        final Intent intent;
        if (uri.getScheme() != null) {
            intent = new Intent(Intent.ACTION_VIEW, uri);
        } else {
            intent = new Intent(Intent.ACTION_VIEW, uri.buildUpon().scheme("http").build());
        }
        startActivity(intent);
        break;
    }
    case TwidereLinkify.LINK_TYPE_LIST: {
        if (link == null)
            break;
        final String[] mentionList = link.split("/");
        if (mentionList.length != 2) {
            break;
        }
        break;
    }
    case TwidereLinkify.LINK_TYPE_STATUS: {
        Utils.openStatus(getActivity(), accountId, ParseUtils.parseLong(link));
        break;
    }
    }
}

From source file:de.arcus.playmusiclib.PlayMusicManager.java

/**
 * Exports a track to the sd card// w w w  .j a  va  2s. c  om
 * @param musicTrack The music track you want to export
 * @param uri The document tree
 * @return Returns whether the export was successful
 */
public boolean exportMusicTrack(MusicTrack musicTrack, Uri uri, String path) {

    // Check for null
    if (musicTrack == null)
        return false;

    String srcFile = musicTrack.getSourceFile();

    // Could not find the source file
    if (srcFile == null)
        return false;

    String fileTmp = getTempPath() + "/tmp.mp3";

    // Copy to temp path failed
    if (!SuperUserTools.fileCopy(srcFile, fileTmp))
        return false;

    // Encrypt the file
    if (musicTrack.isEncoded()) {
        String fileTmpCrypt = getTempPath() + "/crypt.mp3";

        // Encrypts the file
        if (trackEncrypt(musicTrack, fileTmp, fileTmpCrypt)) {
            // Remove the old tmp file
            FileTools.fileDelete(fileTmp);

            // New tmp file
            fileTmp = fileTmpCrypt;
        } else {
            Logger.getInstance().logWarning("ExportMusicTrack",
                    "Encrypting failed! Continue with decrypted file.");
        }
    }

    String dest;
    Uri copyUri = null;
    if (uri.toString().startsWith("file://")) {
        // Build the full path
        dest = uri.buildUpon().appendPath(path).build().getPath();

        String parentDirectory = new File(dest).getParent();
        FileTools.directoryCreate(parentDirectory);
    } else {
        // Complex uri (Lollipop)
        dest = getTempPath() + "/final.mp3";

        // The root
        DocumentFile document = DocumentFile.fromTreeUri(mContext, uri);

        // Creates the subdirectories
        String[] directories = path.split("\\/");
        for (int i = 0; i < directories.length - 1; i++) {
            String directoryName = directories[i];
            boolean found = false;

            // Search all sub elements
            for (DocumentFile subDocument : document.listFiles()) {
                // Directory exists
                if (subDocument.isDirectory() && subDocument.getName().equals(directoryName)) {
                    document = subDocument;
                    found = true;
                    break;
                }
            }

            if (!found) {
                // Create the directory
                document = document.createDirectory(directoryName);
            }
        }

        // Gets the filename
        String filename = directories[directories.length - 1];

        for (DocumentFile subDocument : document.listFiles()) {
            // Directory exists
            if (subDocument.isFile() && subDocument.getName().equals(filename)) {
                // Delete the file
                subDocument.delete();
                break;
            }
        }

        // Create the mp3 file
        document = document.createFile("music/mp3", filename);

        // Create the directories
        copyUri = document.getUri();
    }

    // We want to export the ID3 tags
    if (mID3Enable) {
        // Adds the meta data
        if (!trackWriteID3(musicTrack, fileTmp, dest)) {
            Logger.getInstance().logWarning("ExportMusicTrack",
                    "ID3 writer failed! Continue without ID3 tags.");

            // Failed, moving without meta data
            if (!FileTools.fileMove(fileTmp, dest)) {
                Logger.getInstance().logError("ExportMusicTrack", "Moving the raw file failed!");

                // Could not copy the file
                return false;
            }
        }
    } else {
        // Moving the file
        if (!FileTools.fileMove(fileTmp, dest)) {
            Logger.getInstance().logError("ExportMusicTrack", "Moving the raw file failed!");

            // Could not copy the file
            return false;
        }
    }

    // We need to copy the file to a uri
    if (copyUri != null) {
        // Lollipop only
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            try {
                // Gets the file descriptor
                ParcelFileDescriptor parcelFileDescriptor = mContext.getContentResolver()
                        .openFileDescriptor(copyUri, "w");

                // Gets the output stream
                FileOutputStream fileOutputStream = new FileOutputStream(
                        parcelFileDescriptor.getFileDescriptor());

                // Gets the input stream
                FileInputStream fileInputStream = new FileInputStream(dest);

                // Copy the stream
                FileTools.fileCopy(fileInputStream, fileOutputStream);

                // Close all streams
                fileOutputStream.close();
                fileInputStream.close();
                parcelFileDescriptor.close();

            } catch (FileNotFoundException e) {
                Logger.getInstance().logError("ExportMusicTrack", "File not found!");

                // Could not copy the file
                return false;
            } catch (IOException e) {
                Logger.getInstance().logError("ExportMusicTrack",
                        "Failed to write the document: " + e.toString());

                // Could not copy the file
                return false;
            }
        }
    }

    // Delete temp files
    cleanUp();

    // Adds the file to the media system
    //new MediaScanner(mContext, dest);

    // Done
    return true;
}

From source file:org.mariotaku.twidere.fragment.UserFragment.java

@Override
public boolean onLinkClick(final String link, final String orig, final UserKey accountKey, final long extraId,
        final int type, final boolean sensitive, int start, int end) {
    final ParcelableUser user = getUser();
    if (user == null)
        return false;
    switch (type) {
    case TwidereLinkify.LINK_TYPE_MENTION: {
        IntentUtils.openUserProfile(getActivity(), user.account_key, null, link, null,
                mPreferences.getBoolean(KEY_NEW_DOCUMENT_API), Referral.USER_MENTION);
        return true;
    }//  w  ww  . j a va 2 s.  c  o m
    case TwidereLinkify.LINK_TYPE_HASHTAG: {
        IntentUtils.openTweetSearch(getActivity(), user.account_key, "#" + link);
        return true;
    }
    case TwidereLinkify.LINK_TYPE_LINK_IN_TEXT:
    case TwidereLinkify.LINK_TYPE_ENTITY_URL: {
        final Uri uri = Uri.parse(link);
        final Intent intent;
        if (uri.getScheme() != null) {
            intent = new Intent(Intent.ACTION_VIEW, uri);
        } else {
            intent = new Intent(Intent.ACTION_VIEW, uri.buildUpon().scheme("http").build());
        }
        startActivity(intent);
        return true;
    }
    case TwidereLinkify.LINK_TYPE_LIST: {
        if (link == null)
            break;
        final String[] mentionList = link.split("/");
        if (mentionList.length != 2) {
            break;
        }
        return true;
    }
    }
    return false;
}

From source file:org.appcelerator.titanium.util.TiUIHelper.java

/**
 * To get the redirected Uri/*from   w ww. ja v  a  2s.c  om*/
 * @param Uri
 */
public static Uri getRedirectUri(Uri mUri) throws MalformedURLException, IOException {
    if (!TiC.HONEYCOMB_OR_GREATER && ("http".equals(mUri.getScheme()) || "https".equals(mUri.getScheme()))) {
        // Media player doesn't handle redirects, try to follow them
        // here. (Redirects work fine without this in ICS.)
        while (true) {
            // java.net.URL doesn't handle rtsp
            if (mUri.getScheme() != null && mUri.getScheme().equals("rtsp"))
                break;

            URL url = new URL(mUri.toString());
            HttpURLConnection cn = (HttpURLConnection) url.openConnection();
            cn.setInstanceFollowRedirects(false);
            String location = cn.getHeaderField("Location");
            if (location != null) {
                String host = mUri.getHost();
                int port = mUri.getPort();
                String scheme = mUri.getScheme();
                mUri = Uri.parse(location);
                if (mUri.getScheme() == null) {
                    // Absolute URL on existing host/port/scheme
                    if (scheme == null) {
                        scheme = "http";
                    }
                    String authority = port == -1 ? host : host + ":" + port;
                    mUri = mUri.buildUpon().scheme(scheme).encodedAuthority(authority).build();
                }
            } else {
                break;
            }
        }
    }
    return mUri;
}

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

private UnderlyingCursorWrapper doQuery(boolean withLimit) {
    Uri uri = qUri;
    if (withLimit) {
        uri = uri.buildUpon().appendQueryParameter(ConversationListQueryParameters.LIMIT,
                ConversationListQueryParameters.DEFAULT_LIMIT).build();
    }/*from   w  ww  .ja  v a  2  s.  c o m*/
    long time = System.currentTimeMillis();

    Utils.traceBeginSection("query");
    final Cursor result = mResolver.query(uri, qProjection, null, null, null);
    Utils.traceEndSection();
    if (result == null) {
        LogUtils.w(LOG_TAG, "doQuery returning null cursor, uri: " + uri);
    } else if (DEBUG) {
        time = System.currentTimeMillis() - time;
        LogUtils.i(LOG_TAG, "ConversationCursor query: %s, %dms, %d results", uri, time, result.getCount());
    }
    System.gc();
    return new UnderlyingCursorWrapper(result);
}

From source file:info.guardianproject.otr.app.im.app.NewChatActivity.java

public void updateChatList() {

    if (mContactList != null && mContactList.mFilterView != null) {
        mLastPagePosition = -1;//from ww  w  . ja  v a2  s.c om
        Uri baseUri = Imps.Contacts.CONTENT_URI_CHAT_CONTACTS_BY;
        Uri.Builder builder = baseUri.buildUpon();

        mContactList.mFilterView.doFilter(builder.build(), null);
    }

    mChatPager.invalidate();
}