Example usage for android.net Uri getFragment

List of usage examples for android.net Uri getFragment

Introduction

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

Prototype

@Nullable
public abstract String getFragment();

Source Link

Document

Gets the decoded fragment part of this URI, everything after the '#'.

Usage

From source file:fpt.isc.nshreport.utilities.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>/* w ww .java2s  .c o m*/
 * 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(Context, Uri)
 */
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
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)) {
        if (false) {
            // 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:Main.java

public static String encodeUrl(String url) {
    Uri uri = Uri.parse(url);

    try {/*from ww w  . j ava  2s  .co m*/
        Map<String, List<String>> splitQuery = splitQuery(uri);
        StringBuilder encodedQuery = new StringBuilder();
        for (String key : splitQuery.keySet()) {
            for (String value : splitQuery.get(key)) {
                if (encodedQuery.length() > 0) {
                    encodedQuery.append("&");
                }
                encodedQuery.append(key + "=" + URLEncoder.encode(value, "UTF-8"));
            }
        }
        String queryString = encodedQuery != null && encodedQuery.length() > 0 ? "?" + encodedQuery : "";

        URI baseUri = new URI(uri.getScheme(), uri.getAuthority(), uri.getPath(), null, uri.getFragment());
        return baseUri + queryString;
    } catch (UnsupportedEncodingException ignore) {
    } catch (URISyntaxException ignore) {
    }

    return uri.toString();
}

From source file:org.apache.cordova.engine.crosswalk.XWalkCordovaWebViewClient.java

private static boolean needsSpecialsInAssetUrlFix(Uri uri) {
    if (CordovaResourceApi.getUriType(uri) != CordovaResourceApi.URI_TYPE_ASSET) {
        return false;
    }/*from   w  ww.  ja v  a2 s .c  om*/
    if (uri.getQuery() != null || uri.getFragment() != null) {
        return true;
    }

    if (!uri.toString().contains("%")) {
        return false;
    }

    switch (android.os.Build.VERSION.SDK_INT) {
    case android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH:
    case android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1:
        return true;
    }
    return false;
}

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>//  w  ww.  j a  va 2  s.  c  o m
 * 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:me.philio.disqus.AuthorizeFragment.java

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    mWebView = (WebView) view.findViewById(R.id.disqus_authorize_webview);

    // Setup custom client to catch the redirect
    mWebView.setWebViewClient(new WebViewClient() {
        @Override/*from www  . ja v  a  2  s.  c  om*/
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.startsWith(mRedirectUri)) {
                // Get fragment from url
                Log.d(TAG, "Processing redirect: " + url);
                Uri uri = Uri.parse(url);
                String uriFragment = uri.getFragment();

                // Extract data from fragment and pass to callback
                Uri queryUri = new Uri.Builder().encodedQuery(uriFragment).build();
                AccessToken accessToken = new AccessToken();
                accessToken.username = queryUri.getQueryParameter(DisqusConstants.PARAM_USERNAME);
                accessToken.userId = Long.parseLong(queryUri.getQueryParameter(DisqusConstants.PARAM_USER_ID));
                accessToken.accessToken = queryUri.getQueryParameter(DisqusConstants.PARAM_ACCESS_TOKEN);
                accessToken.expiresIn = Long
                        .parseLong(queryUri.getQueryParameter(DisqusConstants.PARAM_EXPIRES_IN));
                accessToken.tokenType = queryUri.getQueryParameter(DisqusConstants.PARAM_TOKEN_TYPE);
                accessToken.state = queryUri.getQueryParameter(DisqusConstants.PARAM_STATE);
                accessToken.scope = queryUri.getQueryParameter(DisqusConstants.PARAM_SCOPE);
                mListener.onSuccess(accessToken);
                return true;
            }
            return super.shouldOverrideUrlLoading(view, url);
        }
    });

    // Load authorize url
    String scope = AuthorizeUtils.buildScope(mScopes);
    Uri uri = AuthorizeUtils.buildAuthorizeUri(mApiKey, scope, mRedirectUri);
    Log.d(TAG, "Loading authorize url: " + uri.toString());
    mWebView.loadUrl(uri.toString());
}

From source file:com.example.sans.myapplication.Utility.Map.MapsActivity.java

@Override
public void onFragmentInteraction(Uri uri) {
    uri.getFragment();
}

From source file:org.sufficientlysecure.keychain.ui.dialog.AddKeyserverDialogFragment.java

public void verifyConnection(String keyserver) {

    new AsyncTask<String, Void, FailureReason>() {
        ProgressDialog mProgressDialog;/*from w  w w  .java 2 s.  c  o  m*/
        String mKeyserver;

        @Override
        protected void onPreExecute() {
            mProgressDialog = new ProgressDialog(getActivity());
            mProgressDialog.setMessage(getString(R.string.progress_verifying_keyserver_url));
            mProgressDialog.setCancelable(false);
            mProgressDialog.show();
        }

        @Override
        protected FailureReason doInBackground(String... keyservers) {
            mKeyserver = keyservers[0];
            FailureReason reason = null;
            try {
                // replace hkps/hkp scheme and reconstruct Uri
                Uri keyserverUri = Uri.parse(mKeyserver);
                String scheme = keyserverUri.getScheme();
                String schemeSpecificPart = keyserverUri.getSchemeSpecificPart();
                String fragment = keyserverUri.getFragment();
                if (scheme == null)
                    throw new MalformedURLException();
                if (scheme.equalsIgnoreCase("hkps"))
                    scheme = "https";
                else if (scheme.equalsIgnoreCase("hkp"))
                    scheme = "http";
                URI newKeyserver = new URI(scheme, schemeSpecificPart, fragment);

                Log.d("Converted URL", newKeyserver.toString());
                TlsHelper.openConnection(newKeyserver.toURL()).getInputStream();
            } catch (TlsHelper.TlsHelperException e) {
                reason = FailureReason.CONNECTION_FAILED;
            } catch (MalformedURLException e) {
                Log.w(Constants.TAG, "Invalid keyserver URL entered by user.");
                reason = FailureReason.INVALID_URL;
            } catch (URISyntaxException e) {
                Log.w(Constants.TAG, "Invalid keyserver URL entered by user.");
                reason = FailureReason.INVALID_URL;
            } catch (IOException e) {
                Log.w(Constants.TAG, "Could not connect to entered keyserver url");
                reason = FailureReason.CONNECTION_FAILED;
            }
            return reason;
        }

        @Override
        protected void onPostExecute(FailureReason failureReason) {
            mProgressDialog.dismiss();
            if (failureReason == null) {
                addKeyserver(mKeyserver, true);
            } else {
                verificationFailed(failureReason);
            }
        }
    }.execute(keyserver);
}

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

/***
 * Tries to parse an universal link.//from   w ww .j  a  v  a  2s  .c om
 *
 * @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.benefit.buy.library.http.query.callback.AbstractAjaxCallback.java

private static String extractUrl(Uri uri) {
    String result = uri.getScheme() + "://" + uri.getAuthority() + uri.getPath();
    String fragment = uri.getFragment();
    if (fragment != null) {
        result += "#" + fragment;
    }/*from   www .  j  a va2 s .  c  o  m*/
    return result;
}

From source file:net.sf.asap.Player.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Uri uri = getIntent().getData();
    filename = uri.getLastPathSegment();
    ZipFile zip = null;//from   ww  w. ja v a 2 s  .com
    final byte[] module = new byte[ASAPInfo.MAX_MODULE_LENGTH];
    int moduleLen;
    try {
        InputStream is;
        if (Util.isZip(filename)) {
            zip = new ZipFile(uri.getPath());
            filename = uri.getFragment();
            is = zip.getInputStream(zip.getEntry(filename));
        } else {
            try {
                is = getContentResolver().openInputStream(uri);
            } catch (FileNotFoundException ex) {
                if (uri.getScheme().equals("http"))
                    is = httpGet(uri);
                else
                    throw ex;
            }
        }
        moduleLen = readAndClose(is, module);
    } catch (IOException ex) {
        showError(R.string.error_reading_file);
        return;
    } finally {
        Util.close(zip);
    }
    try {
        asap.load(filename, module, moduleLen);
    } catch (Exception ex) {
        showError(R.string.invalid_file);
        return;
    }
    info = asap.getInfo();

    setTitle(R.string.playing_title);
    setContentView(R.layout.playing);
    setTag(R.id.name, info.getTitleOrFilename());
    setTag(R.id.author, info.getAuthor());
    setTag(R.id.date, info.getDate());
    findViewById(R.id.stop_button).setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            finish();
        }
    });
    mediaController = new MediaController(this, false);
    mediaController.setAnchorView(getContentView());
    mediaController.setMediaPlayer(new MediaController.MediaPlayerControl() {
        public boolean canPause() {
            return !isPaused();
        }

        public boolean canSeekBackward() {
            return false;
        }

        public boolean canSeekForward() {
            return false;
        }

        public int getBufferPercentage() {
            return 100;
        }

        public int getCurrentPosition() {
            return asap.getPosition();
        }

        public int getDuration() {
            return info.getDuration(song);
        }

        public boolean isPlaying() {
            return !isPaused();
        }

        public void pause() {
            audioTrack.pause();
        }

        public void seekTo(int pos) {
            seek(pos);
        }

        public void start() {
            resume();
        }
    });
    if (info.getSongs() > 1) {
        mediaController.setPrevNextListeners(new OnClickListener() {
            public void onClick(View v) {
                playNextSong();
            }
        }, new OnClickListener() {
            public void onClick(View v) {
                playPreviousSong();
            }
        });
    }
    new Handler().postDelayed(new Runnable() {
        public void run() {
            mediaController.show();
        }
    }, 500);

    stop = false;
    playSong(info.getDefaultSong());
    new Thread(this).start();
}