Example usage for android.net Uri toString

List of usage examples for android.net Uri toString

Introduction

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

Prototype

public abstract String toString();

Source Link

Document

Returns the encoded string representation of this URI.

Usage

From source file:com.android.dialer.lookup.gebeld.GebeldApi.java

public static ContactInfo reverseLookup(Context context, String number) throws IOException {
    String phoneNumber = number.replace("+31", "0");
    Uri uri = Uri.parse(REVERSE_LOOKUP_URL).buildUpon().appendQueryParameter("queryfield1", phoneNumber)
            .build();/*from   w  w w .  j  av  a  2  s  .  c  om*/
    // Cut out everything we're not interested in (scripts etc.) to
    // speed up the subsequent matching.
    String output = LookupUtils.firstRegexResult(LookupUtils.httpGet(new HttpGet(uri.toString())),
            "<div class=\"small-12 large-4 columns information\">(.*?)</div>", true);

    String name = null;
    String address = null;

    if (output == null) {
        return null;
    } else {
        Pattern pattern = Pattern.compile(REGEX, 0);
        Matcher m = pattern.matcher(output);

        if (m.find()) {
            name = LookupUtils.fromHtml(m.group(1).trim());

            if (m.find()) {
                address = LookupUtils.fromHtml(m.group(1).trim());

                if (m.find()) {
                    address += "\n" + LookupUtils.fromHtml(m.group(1).trim());
                }
            }
        }
    }

    if (name == null) {
        return null;
    }

    ContactInfo info = new ContactInfo();
    info.name = name;
    info.address = address;
    info.formattedNumber = phoneNumber != null ? phoneNumber : number;
    info.website = uri.toString();

    return info;
}

From source file:edu.mit.mobile.android.locast.sync.LocastSyncService.java

/**
 * Convenience method to request a sync.
 *
 * This wraps {@link ContentResolver#requestSync(Account, String, Bundle)}
 * and fills in the necessary extras.//from  w  ww.  jav a 2s .  c o m
 *
 * @param account
 * @param what the uri of the item that needs to be sync'd. can be null
 * @param explicitSync
 *            if true, adds {@link ContentResolver#SYNC_EXTRAS_MANUAL} to
 *            the extras
 * @param extras
 */
public static void startSync(Account account, Uri what, Bundle extras) {

    if (what != null) {
        extras.putString(LocastSyncService.EXTRA_SYNC_URI, what.toString());
    }

    if (extras.getBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, false)) {
        if (SYNC_ADAPTER != null) {
            if (DEBUG) {
                Log.d(TAG, "canceling current sync to make room for expedited sync of " + what);
            }
            // only cancel the ongoing sync, to leave the queue untouched.
            SYNC_ADAPTER.cancelCurrentSync();
        }
    }

    if (DEBUG) {
        Log.d(TAG, "requesting sync for " + account + " with extras: " + extras);
    }
    ContentResolver.requestSync(account, MediaProvider.AUTHORITY, extras);
}

From source file:com.google.android.libraries.cast.companionlibrary.utils.Utils.java

/**
 * Returns the URL of an image for the {@link MediaInfo} at the given index. Index should be a
 * number between 0 and {@code n-1} where {@code n} is the number of images for that given item.
 *///from ww  w.j  a va 2  s  . com
public static String getImageUrl(MediaInfo info, int index) {
    Uri uri = getImageUri(info, index);
    if (uri != null) {
        return uri.toString();
    }
    return null;
}

From source file:Main.java

public static InputStream openStreamForUri(Context context, Uri uri) throws IOException {
    switch (uri.getScheme()) {
    case ContentResolver.SCHEME_CONTENT:
    case ContentResolver.SCHEME_ANDROID_RESOURCE:
        try {//w w  w.ja  va 2s .  c om
            return context.getContentResolver().openInputStream(uri);
        } catch (RuntimeException ignore) {
        }
    case "file":
    case "http":
    case "https":
        return new URL(uri.toString()).openStream();
    }

    throw new IOException("Unable to open " + uri.toString());
}

From source file:com.cloudbees.gasp.service.RESTService.java

private static void attachUriWithQuery(HttpRequestBase request, Uri uri, Bundle params) {
    try {/*from   w  w w  .ja  v  a2 s . c om*/
        if (params == null) {
            // No params were given or they have already been
            // attached to the Uri.
            request.setURI(new URI(uri.toString()));
        } else {
            Uri.Builder uriBuilder = uri.buildUpon();

            // Loop through our params and append them to the Uri.
            for (BasicNameValuePair param : paramsToList(params)) {
                uriBuilder.appendQueryParameter(param.getName(), param.getValue());
            }

            uri = uriBuilder.build();
            request.setURI(new URI(uri.toString()));
        }
    } catch (URISyntaxException e) {
        Log.e(TAG, "URI syntax was incorrect: " + uri.toString(), e);
    }
}

From source file:com.quantcast.measurement.service.QCPolicy.java

public static QCPolicy getQuantcastPolicy(Context context, String apiKey, String networkCode,
        String packageName, boolean kidDirected) {
    Uri.Builder builder = Uri.parse(QCUtility.addScheme(POLICY_REQUEST_BASE_WITHOUT_SCHEME)).buildUpon();
    builder.appendQueryParameter(POLICY_REQUEST_API_VERSION_PARAMETER, QCUtility.API_VERSION);
    builder.appendQueryParameter(POLICY_REQUEST_DEVICE_TYPE_PARAMETER, POLICY_REQUEST_DEVICE_TYPE);

    String mcc = null;//from ww  w .  j  a  v a 2s . c  om
    try {
        TelephonyManager tel = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        if (tel != null) {
            mcc = tel.getNetworkCountryIso();
            if (mcc == null) {
                mcc = tel.getSimCountryIso();
            }
        }
    } catch (SecurityException ignored) {
    }

    if (mcc == null) {
        mcc = Locale.getDefault().getCountry();
    }
    if (mcc != null) {
        builder.appendQueryParameter(POLICY_REQUEST_DEVICE_COUNTRY, mcc);
    }

    if (apiKey != null) {
        builder.appendQueryParameter(POLICY_REQUEST_API_KEY_PARAMETER, apiKey);
    } else {
        builder.appendQueryParameter(POLICY_REQUEST_NETWORK_CODE_PARAMETER, networkCode);
        builder.appendQueryParameter(POLICY_REQUEST_PACKAGE_PARAMETER, packageName);
    }

    if (kidDirected) {
        builder.appendQueryParameter(POLICY_REQUEST_KID_DIRECTED_PARAMETER, "YES");
    }

    Uri builtURL = builder.build();
    if (builtURL != null) {
        return new QCPolicy(context, builtURL.toString());
    } else {
        QCLog.e(TAG, "Policy URL was not built correctly for some reason.  Should not happen");
        return null;
    }
}

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

private static InputStream httpGet(Uri uri) throws IOException {
    DefaultHttpClient client = new DefaultHttpClient();
    HttpGet request = new HttpGet(uri.toString());
    HttpResponse response = client.execute(request);
    StatusLine status = response.getStatusLine();
    if (status.getStatusCode() != 200)
        throw new IOException("HTTP error " + status);
    return response.getEntity().getContent();
}

From source file:Main.java

public static InputStream getInputStream(Context context, Uri uri) throws IOException {
    InputStream inputStream;// ww  w. j  a  va  2s. c  o  m
    if (ContentResolver.SCHEME_ANDROID_RESOURCE.equals(uri.getScheme())
            || ContentResolver.SCHEME_ANDROID_RESOURCE.equals(uri.getScheme())
            || ContentResolver.SCHEME_FILE.equals(uri.getScheme())) {
        inputStream = context.getContentResolver().openInputStream(uri);
    } else {
        URLConnection urlConnection = new URL(uri.toString()).openConnection();
        urlConnection.setConnectTimeout(URLCONNECTION_CONNECTION_TIMEOUT_MS);
        urlConnection.setReadTimeout(URLCONNECTION_READ_TIMEOUT_MS);
        inputStream = urlConnection.getInputStream();
    }
    return new BufferedInputStream(inputStream);
}

From source file:ch.lipsch.deshortener.Deshortener.java

/**
 * Deshortens the provided uri.//  ww  w .  j a  v a 2 s .c  o  m
 *
 * @param uriToDeshorten
 *            The uri to deshorten.
 * @return Returns the result of the deshorten process. The result is only
 *         successful when the given uri returns an 30x. Then value of the
 *         Location header is returned within the result.
 * @throws IllegalArgumentException
 *             If the provided uri is invalid.
 */
public static Result deshorten(Uri uriToDeshorten) {
    // Checks if the url shortener shows a preview
    if (checkForPreview(uriToDeshorten)) {
        return new Result(ResultType.SHOWS_PREVIEW);
    }

    // Open the network connetion
    HttpGet get = new HttpGet(uriToDeshorten.toString());
    DefaultHttpClient client = new DefaultHttpClient();
    HttpParams clientParams = client.getParams();
    HttpClientParams.setRedirecting(clientParams, false);
    HttpResponse response = null;
    try {
        response = client.execute(get);
    } catch (ClientProtocolException e) {
        Log.e(LOG_TAG, "Unable to communicate to shortened url: " + uriToDeshorten.toString(), e);
        return new Result(ResultType.NETWORK_ERROR);
    } catch (IOException e) {
        Log.e(LOG_TAG, "Unable to communicate to shortened url: " + uriToDeshorten.toString(), e);
        return new Result(ResultType.NETWORK_ERROR);
    }

    // Check for redirection
    boolean isRedirection = ((response.getStatusLine().getStatusCode() == HttpStatus.SC_MOVED_PERMANENTLY)
            || (response.getStatusLine().getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY)
            || (response.getStatusLine().getStatusCode() == HttpStatus.SC_SEE_OTHER));
    if (response != null && isRedirection) {
        Header header = response.getFirstHeader("Location");
        String redirectValue = header.getValue();
        Uri deshortenedUri = Uri.parse(redirectValue);
        return new Result(deshortenedUri);
    } else {
        return new Result(ResultType.CANNOT_DESHORTEN);
    }
}

From source file:Main.java

static String convertUriToPath(Context context, Uri uri) {
    Log.v(TAG, "convertUriToPath : " + uri + " @" + context);

    String path = null;/*from  ww w . ja  va  2 s  .c  o m*/
    if (null != uri) {
        String scheme = uri.getScheme();
        if (null == scheme || scheme.equals("") || scheme.equals(ContentResolver.SCHEME_FILE)) {
            path = uri.getPath();
        } else if (scheme.equals("http")) {
            path = uri.toString();
        } else if (scheme.equals(ContentResolver.SCHEME_CONTENT)) {
            String[] projection = new String[] { MediaStore.MediaColumns.DATA };
            Cursor cursor = null;
            try {
                cursor = context.getContentResolver().query(uri, projection, null, null, null);
                if (null == cursor || 0 == cursor.getCount() || !cursor.moveToFirst()) {
                    throw new IllegalArgumentException("Given Uri could not be found in media store");
                }
                int pathIndex = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
                path = cursor.getString(pathIndex);
            } catch (SQLiteException e) {
                throw new IllegalArgumentException(
                        "Given Uri is not formatted in a way so that it can be found in media store.");
            } finally {
                if (null != cursor) {
                    cursor.close();
                }
            }
        } else {
            throw new IllegalArgumentException("Given Uri scheme is not supported");
        }
    }

    Log.v(TAG, "convertUriToPath : >" + path);
    return path;
}