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:mobisocial.musubi.util.UriImage.java

private InputStream openInputStream(Uri uri) throws IOException {
    String scheme = uri.getScheme();
    if ("content".equals(scheme)) {
        return mContext.getContentResolver().openInputStream(mUri);
    } else if (scheme.startsWith("http")) {
        if (mByteCache == null) {
            DefaultHttpClient c = new DefaultHttpClient();
            HttpGet get = new HttpGet(uri.toString());
            HttpResponse response = c.execute(get);
            mByteCache = IOUtils.toByteArray(response.getEntity().getContent());
        }/* w w  w  .  j  av  a2 s .  c  o m*/
        return new ByteArrayInputStream(mByteCache);
    } else if (scheme.equals("file")) {
        return new FileInputStream(uri.getPath());
    } else {
        throw new IOException("Unmatched uri scheme " + scheme);
    }
}

From source file:com.facebook.applinks.FacebookAppLinkResolver.java

/**
 * Asynchronously resolves App Link data for multiple URLs
 *
 * @param uris A list of Uri objects to resolve into App Links
 * @return A Task that, when successful, will return a Map of Uri->AppLink for each Uri that was
 * successfully resolved into an App Link. Uris that could not be resolved into App Links will
 * not be present in the Map. In the case of general server errors, the task will be completed
 * with the corresponding error.//from w w w .j  a v a  2s  . co m
 */
public Task<Map<Uri, AppLink>> getAppLinkFromUrlsInBackground(List<Uri> uris) {
    final Map<Uri, AppLink> appLinkResults = new HashMap<Uri, AppLink>();
    final HashSet<Uri> urisToRequest = new HashSet<Uri>();
    StringBuilder graphRequestFields = new StringBuilder();

    for (Uri uri : uris) {
        AppLink appLink = null;
        synchronized (cachedAppLinks) {
            appLink = cachedAppLinks.get(uri);
        }

        if (appLink != null) {
            appLinkResults.put(uri, appLink);
        } else {
            if (!urisToRequest.isEmpty()) {
                graphRequestFields.append(',');
            }
            graphRequestFields.append(uri.toString());
            urisToRequest.add(uri);
        }
    }

    if (urisToRequest.isEmpty()) {
        return Task.forResult(appLinkResults);
    }

    final Task<Map<Uri, AppLink>>.TaskCompletionSource taskCompletionSource = Task.create();

    Bundle appLinkRequestParameters = new Bundle();

    appLinkRequestParameters.putString("ids", graphRequestFields.toString());
    appLinkRequestParameters.putString("fields", String.format("%s.fields(%s,%s)", APP_LINK_KEY,
            APP_LINK_ANDROID_TARGET_KEY, APP_LINK_WEB_TARGET_KEY));
    GraphRequest appLinkRequest = new GraphRequest(
            // We will use the current access token if we have one else we will use the client
            // token
            AccessToken.getCurrentAccessToken(), /* Access Token */
            "", /* Graph path */
            appLinkRequestParameters, /* Query parameters */
            null, /* HttpMethod */
            new GraphRequest.Callback() { /* Callback */
                @Override
                public void onCompleted(GraphResponse response) {
                    FacebookRequestError error = response.getError();
                    if (error != null) {
                        taskCompletionSource.setError(error.getException());
                        return;
                    }

                    JSONObject responseJson = response.getJSONObject();
                    if (responseJson == null) {
                        taskCompletionSource.setResult(appLinkResults);
                        return;
                    }

                    for (Uri uri : urisToRequest) {
                        String uriString = uri.toString();
                        if (!responseJson.has(uriString)) {
                            continue;
                        }

                        JSONObject urlData = null;
                        try {
                            urlData = responseJson.getJSONObject(uri.toString());
                            JSONObject appLinkData = urlData.getJSONObject(APP_LINK_KEY);

                            JSONArray rawTargets = appLinkData.getJSONArray(APP_LINK_ANDROID_TARGET_KEY);

                            int targetsCount = rawTargets.length();
                            List<AppLink.Target> targets = new ArrayList<AppLink.Target>(targetsCount);

                            for (int i = 0; i < targetsCount; i++) {
                                AppLink.Target target = getAndroidTargetFromJson(rawTargets.getJSONObject(i));
                                if (target != null) {
                                    targets.add(target);
                                }
                            }

                            Uri webFallbackUrl = getWebFallbackUriFromJson(uri, appLinkData);
                            AppLink appLink = new AppLink(uri, targets, webFallbackUrl);

                            appLinkResults.put(uri, appLink);
                            synchronized (cachedAppLinks) {
                                cachedAppLinks.put(uri, appLink);
                            }
                        } catch (JSONException e) {
                            // The data for this uri was missing or badly formed.
                            continue;
                        }
                    }

                    taskCompletionSource.setResult(appLinkResults);
                }
            });

    appLinkRequest.executeAsync();

    return taskCompletionSource.getTask();
}

From source file:org.mobisocial.corral.CorralDownloadClient.java

private Uri getFileOverLan(DbIdentity user, DbObj obj, CorralDownloadFuture future,
        DownloadProgressCallback callback) throws IOException {
    DownloadChannel channel = DownloadChannel.LAN;
    callback.onProgress(DownloadState.PREPARING_CONNECTION, channel, 0);
    InputStream in = null;//w  w w  . j a v a  2 s .  c om
    OutputStream out = null;
    try {
        // Remote
        String ip = getUserLanIp(mContext, user);
        Uri remoteUri = uriForLanContent(ip, obj);

        if (DBG) {
            Log.d(TAG, "Attempting to pull lan file " + remoteUri);
        }

        HttpClient http = new DefaultHttpClient();
        HttpGet get = new HttpGet(remoteUri.toString());
        HttpResponse response = http.execute(get);
        long contentLength = response.getEntity().getContentLength();

        File localFile = localFileForContent(obj, false);
        if (!localFile.exists()) {
            if (future.isCancelled()) {
                throw new IOException("User error");
            }
            localFile.getParentFile().mkdirs();
            try {
                in = response.getEntity().getContent();
                out = new FileOutputStream(localFile);
                byte[] buf = new byte[1024];
                int len;

                callback.onProgress(DownloadState.TRANSFER_IN_PROGRESS, channel, 0);
                int read = 0;
                int progress = 0;
                while (!future.isCancelled() && (len = in.read(buf)) > 0) {
                    read += len;
                    if (contentLength > 0) {
                        int newProgress = Math.round(100f * read / contentLength);
                        if (progress != newProgress) {
                            progress = newProgress;
                            callback.onProgress(DownloadState.TRANSFER_IN_PROGRESS, channel, progress);
                        }
                    }
                    out.write(buf, 0, len);
                }
                if (future.isCancelled()) {
                    throw new IOException("user cancelled");
                }
                if (DBG)
                    Log.d(TAG, "successfully fetched content over lan");
                callback.onProgress(DownloadState.TRANSFER_COMPLETE, channel, DownloadProgressCallback.SUCCESS);
            } catch (IOException e) {
                if (DBG)
                    Log.d(TAG, "failed to get content from lan");
                callback.onProgress(DownloadState.TRANSFER_COMPLETE, channel, DownloadProgressCallback.FAILURE);
                if (localFile.exists()) {
                    localFile.delete();
                }
                throw e;
            }
        }

        return Uri.fromFile(localFile);
    } catch (Exception e) {
        throw new IOException(e);
    } finally {
        try {
            if (in != null)
                in.close();
            if (out != null)
                out.close();
        } catch (IOException e) {
            Log.e(TAG, "failed to close handle on get corral content", e);
        }
    }
}

From source file:com.example.asaldanha.sunshine.app.FetchWeatherTask.java

@Override
protected Void doInBackground(String... params) {

    // If there's no zip code, there's nothing to look up.  Verify size of params.
    //        if (params.length == 0) {
    //            return null;
    //        }//from  ww  w  .  ja  v a 2 s.c om

    String locationQuery = params[0];
    //        String locationQuery = "75035";

    // These two need to be declared outside the try/catch
    // so that they can be closed in the finally block.
    HttpURLConnection urlConnection = null;
    BufferedReader reader = null;

    // Will contain the raw JSON response as a string.
    String forecastJsonStr = null;

    String format = "json";
    String units = "metric";
    int numDays = 14;

    try {
        // Construct the URL for the OpenWeatherMap query
        // Possible parameters are avaiable at OWM's forecast API page, at
        // http://openweathermap.org/API#forecast
        final String FORECAST_BASE_URL = "http://api.openweathermap.org/data/2.5/forecast/daily?";
        final String QUERY_PARAM = "q";
        final String FORMAT_PARAM = "mode";
        final String UNITS_PARAM = "units";
        final String DAYS_PARAM = "cnt";

        Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon().appendQueryParameter(QUERY_PARAM, params[0])
                .appendQueryParameter(FORMAT_PARAM, format).appendQueryParameter(UNITS_PARAM, units)
                .appendQueryParameter(DAYS_PARAM, Integer.toString(numDays)).build();

        URL url = new URL(builtUri.toString());

        // Create the request to OpenWeatherMap, and open the connection
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.connect();

        // Read the input stream into a String
        InputStream inputStream = urlConnection.getInputStream();
        StringBuffer buffer = new StringBuffer();
        if (inputStream == null) {
            // Nothing to do.
            //return null;
        }
        reader = new BufferedReader(new InputStreamReader(inputStream));

        String line;
        while ((line = reader.readLine()) != null) {
            // Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
            // But it does make debugging a *lot* easier if you print out the completed
            // buffer for debugging.
            buffer.append(line + "\n");
        }

        if (buffer.length() == 0) {
            // Stream was empty.  No point in parsing.
            //return null;
        }
        forecastJsonStr = buffer.toString();
        getWeatherDataFromJson(forecastJsonStr, locationQuery);

    } catch (IOException e) {
        Log.e(LOG_TAG, "Error ", e);
        // If the code didn't successfully get the weather data, there's no point in attemping
        // to parse it.
        //return null;
    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        e.printStackTrace();
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
        if (reader != null) {
            try {
                reader.close();
            } catch (final IOException e) {
                Log.e(LOG_TAG, "Error closing stream", e);
            }
        }
    }

    // This will only happen if there was an error getting or parsing the forecast.
    return null;
}

From source file:sjizl.com.FileUploadTest.java

public void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (resultCode == RESULT_OK) {
        if (data != null) {
            // Get the URI of the selected file
            final Uri uri = data.getData();
            Log.i("ffff:", "Uri = " + uri.toString());
            try {
                // Get the file path from the URI
                final String path = FileUtils.getPath(this, uri);
                Toast.makeText(FileUploadTest.this, "File Selected: " + path, Toast.LENGTH_LONG).show();

                CommonUtilities.custom_toast(getApplicationContext(), FileUploadTest.this,
                        "File Selected: " + path, null, R.drawable.iconbd);

                Thread thread = new Thread(new Runnable() {
                    public void run() {
                        doFileUpload(path);
                        runOnUiThread(new Runnable() {
                            public void run() {

                            }//from w  ww.  ja v a2  s  . c  o  m
                        });
                    }
                });
                thread.start();

            } catch (Exception e) {
                Log.e("FileSelectorTestActivity", "File select error", e);
            }
        }
    }

}

From source file:de.stadtrallye.rallyesoft.model.pictures.PictureManager.java

private void saveReservedFilename(Uri mediaFile, SourceHint sourceHint) {
    if (unconfirmed != null) {
        Log.w(THIS, "Overwriting unconfirmed Picture: " + unconfirmed);
    }//from www .  java 2  s.c  om

    ContentValues insert = new ContentValues();
    insert.put(Pictures.KEY_FILE, mediaFile.toString());
    insert.put(Pictures.KEY_STATE, STATE_RESERVED);
    try {
        insert.put(Pictures.KEY_SOURCE_HINT, Serialization.getJsonInstance().writeValueAsString(sourceHint));
    } catch (JsonProcessingException e) {
        Log.e(THIS, "Could not serialize SourceHint", e);
    }

    int lastID = (int) getDb().insert(Pictures.TABLE, null, insert);
    Log.d(THIS, lastID + ": reserved: " + mediaFile.toString());
    unconfirmed = new Picture(lastID, mediaFile.toString(), STATE_RESERVED, sourceHint);
    queuedUnconfirmed = false;
}

From source file:itreverie.weatherapp.FetchWeatherTask.java

@Override
protected Void doInBackground(String... params) {

    // If there's no zip code, there's nothing to look up.  Verify size of params.
    if (params.length == 0) {
        return null;
    }/*from   ww  w. j av  a2s  . c o  m*/

    String locationQuery = params[0];
    // These two need to be declared outside the try/catch
    // so that they can be closed in the finally block.
    HttpURLConnection urlConnection = null;
    BufferedReader reader = null;

    // Will contain the raw JSON response as a string.
    String forecastJsonStr = null;

    String format = "json";
    String units = "metric";
    int numDays = 14;

    try {
        // Construct the URL for the OpenWeatherMap query
        // Possible parameters are avaiable at OWM's forecast API page, at
        // http://openweathermap.org/API#forecast
        final String FORECAST_BASE_URL = "http://api.openweathermap.org/data/2.5/forecast/daily?";
        final String QUERY_PARAM = "q";
        final String FORMAT_PARAM = "mode";
        final String UNITS_PARAM = "units";
        final String DAYS_PARAM = "cnt";

        Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon().appendQueryParameter(QUERY_PARAM, params[0])
                .appendQueryParameter(FORMAT_PARAM, format).appendQueryParameter(UNITS_PARAM, units)
                .appendQueryParameter(DAYS_PARAM, Integer.toString(numDays)).build();

        URL url = new URL(builtUri.toString());

        // Create the request to OpenWeatherMap, and open the connection
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.connect();

        // Read the input stream into a String
        InputStream inputStream = urlConnection.getInputStream();
        StringBuffer buffer = new StringBuffer();
        if (inputStream == null) {
            // Nothing to do.
            return null;
        }
        reader = new BufferedReader(new InputStreamReader(inputStream));

        String line;
        while ((line = reader.readLine()) != null) {
            // Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
            // But it does make debugging a *lot* easier if you print out the completed
            // buffer for debugging.
            buffer.append(line + "\n");
        }

        if (buffer.length() == 0) {
            // Stream was empty.  No point in parsing.
            return null;
        }
        forecastJsonStr = buffer.toString();
    } catch (IOException e) {
        Log.e(LOG_TAG, "Error ", e);
        // If the code didn't successfully get the weather data, there's no point in attemping
        // to parse it.
        return null;
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
        if (reader != null) {
            try {
                reader.close();
            } catch (final IOException e) {
                Log.e(LOG_TAG, "Error closing stream", e);
            }
        }
    }

    try { //return
        getWeatherDataFromJson(forecastJsonStr, numDays, locationQuery);
    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        e.printStackTrace();
    }

    // This will only happen if there was an error getting or parsing the forecast.
    return null;
}

From source file:com.example.joel.sunshine.FetchWeatherTask.java

@Override
protected String[] doInBackground(String... params) {

    // If there's no zip code, there's nothing to look up.  Verify size of params.
    if (params.length == 0) {
        return null;
    }/*w  w  w .  ja v a2  s.c  om*/
    String locationQuery = params[0];

    // These two need to be declared outside the try/catch
    // so that they can be closed in the finally block.
    HttpURLConnection urlConnection = null;
    BufferedReader reader = null;

    // Will contain the raw JSON response as a string.
    String forecastJsonStr = null;

    String format = "json";
    String units = "metric";
    int numDays = 14;

    try {
        // Construct the URL for the OpenWeatherMap query
        // Possible parameters are avaiable at OWM's forecast API page, at
        // http://openweathermap.org/API#forecast
        final String FORECAST_BASE_URL = "http://api.openweathermap.org/data/2.5/forecast/daily?";
        final String QUERY_PARAM = "q";
        final String FORMAT_PARAM = "mode";
        final String UNITS_PARAM = "units";
        final String DAYS_PARAM = "cnt";

        Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon().appendQueryParameter(QUERY_PARAM, params[0])
                .appendQueryParameter(FORMAT_PARAM, format).appendQueryParameter(UNITS_PARAM, units)
                .appendQueryParameter(DAYS_PARAM, Integer.toString(numDays)).build();

        URL url = new URL(builtUri.toString());

        // Create the request to OpenWeatherMap, and open the connection
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.connect();

        // Read the input stream into a String
        InputStream inputStream = urlConnection.getInputStream();
        StringBuffer buffer = new StringBuffer();
        if (inputStream == null) {
            // Nothing to do.
            return null;
        }
        reader = new BufferedReader(new InputStreamReader(inputStream));

        String line;
        while ((line = reader.readLine()) != null) {
            // Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
            // But it does make debugging a *lot* easier if you print out the completed
            // buffer for debugging.
            buffer.append(line + "\n");
        }

        if (buffer.length() == 0) {
            // Stream was empty.  No point in parsing.
            return null;
        }
        forecastJsonStr = buffer.toString();
    } catch (IOException e) {
        Log.e(LOG_TAG, "Error ", e);
        // If the code didn't successfully get the weather data, there's no point in attemping
        // to parse it.
        return null;
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
        if (reader != null) {
            try {
                reader.close();
            } catch (final IOException e) {
                Log.e(LOG_TAG, "Error closing stream", e);
            }
        }
    }

    try {
        return getWeatherDataFromJson(forecastJsonStr, numDays, locationQuery);
    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        e.printStackTrace();
    }
    // This will only happen if there was an error getting or parsing the forecast.
    return null;
}

From source file:com.example.len.sunshinelessons1.FetchWeatherTask.java

@Override
protected Void doInBackground(String... params) {

    // If there's no zip code, there's nothing to look up.  Verify size of params.
    if (params.length == 0) {
        return null;
    }//from   www. jav  a  2s . c  o m
    String locationQuery = params[0];

    // These two need to be declared outside the try/catch
    // so that they can be closed in the finally block.
    HttpURLConnection urlConnection = null;
    BufferedReader reader = null;

    // Will contain the raw JSON response as a string.
    String forecastJsonStr = null;

    String format = "json";
    String units = "metric";
    int numDays = 14;

    try {
        // Construct the URL for the OpenWeatherMap query
        // Possible parameters are avaiable at OWM's forecast API page, at
        // http://openweathermap.org/API#forecast
        final String FORECAST_BASE_URL = "http://api.openweathermap.org/data/2.5/forecast/daily?";
        final String QUERY_PARAM = "q";
        final String FORMAT_PARAM = "mode";
        final String UNITS_PARAM = "units";
        final String DAYS_PARAM = "cnt";

        Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon().appendQueryParameter(QUERY_PARAM, params[0])
                .appendQueryParameter(FORMAT_PARAM, format).appendQueryParameter(UNITS_PARAM, units)
                .appendQueryParameter(DAYS_PARAM, Integer.toString(numDays)).build();

        URL url = new URL(builtUri.toString());

        // Create the request to OpenWeatherMap, and open the connection
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.connect();

        // Read the input stream into a String
        InputStream inputStream = urlConnection.getInputStream();
        StringBuffer buffer = new StringBuffer();
        if (inputStream == null) {
            // Nothing to do.
            return null;
        }
        reader = new BufferedReader(new InputStreamReader(inputStream));

        String line;
        while ((line = reader.readLine()) != null) {
            // Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
            // But it does make debugging a *lot* easier if you print out the completed
            // buffer for debugging.
            buffer.append(line + "\n");
        }

        if (buffer.length() == 0) {
            // Stream was empty.  No point in parsing.
            return null;
        }
        forecastJsonStr = buffer.toString();
        getWeatherDataFromJson(forecastJsonStr, locationQuery);
    } catch (IOException e) {
        Log.e(LOG_TAG, "Error ", e);
        // If the code didn't successfully get the weather data, there's no point in attemping
        // to parse it.

    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        e.printStackTrace();
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
        if (reader != null) {
            try {
                reader.close();
            } catch (final IOException e) {
                Log.e(LOG_TAG, "Error closing stream", e);
            }
        }
    }

    return null;
}

From source file:io.ionic.links.IonicDeeplink.java

public void handleIntent(Intent intent) {
    final String intentString = intent.getDataString();

    // read intent
    String action = intent.getAction();
    Uri url = intent.getData();
    JSONObject bundleData = this._bundleToJson(intent.getExtras());
    Log.d(TAG, "Got a new intent: " + intentString + " " + intent.getScheme() + " " + action + " " + url);

    // if app was not launched by the url - ignore
    if (!Intent.ACTION_VIEW.equals(action) || url == null) {
        return;/*from   w ww . jav a 2 s  .c  o m*/
    }

    // store message and try to consume it
    try {
        lastEvent = new JSONObject();
        lastEvent.put("url", url.toString());
        lastEvent.put("path", url.getPath());
        lastEvent.put("queryString", url.getQuery());
        lastEvent.put("scheme", url.getScheme());
        lastEvent.put("host", url.getHost());
        lastEvent.put("fragment", url.getFragment());
        lastEvent.put("extra", bundleData);
        consumeEvents();
    } catch (JSONException ex) {
        Log.e(TAG, "Unable to process URL scheme deeplink", ex);
    }
}