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.tlongdev.bktf.interactor.TlongdevPriceListInteractor.java

public Integer run() {

    if (System.currentTimeMillis()
            - mPrefs.getLong(mContext.getString(R.string.pref_last_price_list_update), 0) < 3600000L
            && !manualSync) {/*w w  w .j a  v  a 2s  .c  o  m*/
        //This task ran less than an hour ago and wasn't a manual sync, nothing to do.
        return 0;
    }

    try {
        //Get the youngest price from the database. If it's an update only prices newer than this
        //will be updated to speed up the update and reduce data usage.
        if (updateDatabase) {
            String[] columns = { PriceEntry.COLUMN_LAST_UPDATE };
            Cursor cursor = mContext.getContentResolver().query(PriceEntry.CONTENT_URI, columns, null, null,
                    PriceEntry.COLUMN_LAST_UPDATE + " DESC LIMIT 1");
            if (cursor != null) {
                if (cursor.moveToFirst())
                    latestUpdate = cursor.getInt(0);
                cursor.close();
            }
        }

        Uri uri = Uri.parse("http://tlongdev.com/api/v1/prices").buildUpon()
                .appendQueryParameter("since", String.valueOf(latestUpdate)).build();

        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(uri.toString()).build();

        Response response = client.newCall(request).execute();

        if (response.body() != null) {
            return parseJson(response.body().byteStream());
        } else if (response.code() >= 500) {
            errorMessage = "Server error: " + response.code();
        } else if (response.code() >= 400) {
            errorMessage = "Client error: " + response.code();
        }
        return -1;

    } catch (IOException e) {
        //There was a network error
        errorMessage = mContext.getString(R.string.error_network);
        e.printStackTrace();
    }

    return -1;
}

From source file:mobisocial.musubi.nearby.GpsBroadcastTask.java

@Override
protected Void doInBackground(Void... params) {
    if (DBG)/* w  w  w .j  a  v a 2  s  . c  o m*/
        Log.d(TAG, "Uploading group for nearby gps...");
    while (!mmLocationScanComplete) {
        synchronized (mmLocationResult) {
            if (!mmLocationScanComplete) {
                try {
                    if (DBG)
                        Log.d(TAG, "Waiting for location results...");
                    mmLocationResult.wait();
                } catch (InterruptedException e) {
                }
            }
        }
    }
    if (DBG)
        Log.d(TAG, "Got location " + mmLocation);
    if (isCancelled()) {
        return null;
    }

    try {
        SQLiteOpenHelper db = App.getDatabaseSource(mContext);
        FeedManager fm = new FeedManager(db);
        IdentitiesManager im = new IdentitiesManager(db);
        String group_name = UiUtil.getFeedNameFromMembersList(fm, mFeed);
        byte[] group_capability = mFeed.capability_;
        List<MIdentity> owned = im.getOwnedIdentities();
        MIdentity sharer = null;
        for (MIdentity i : owned) {
            if (i.type_ != Authority.Local) {
                sharer = i;
                break;
            }
        }
        String sharer_name = UiUtil.safeNameForIdentity(sharer);
        byte[] sharer_hash = sharer.principalHash_;

        byte[] thumbnail = fm.getFeedThumbnailForId(mFeed.id_);
        if (thumbnail == null)
            thumbnail = im.getMusubiThumbnail(sharer) != null ? sharer.musubiThumbnail_
                    : im.getThumbnail(sharer);
        int member_count = fm.getFeedMemberCount(mFeed.id_);

        JSONObject group = new JSONObject();
        group.put("group_name", group_name);
        group.put("group_capability", Base64.encodeToString(group_capability, Base64.DEFAULT));
        group.put("sharer_name", sharer_name);
        group.put("sharer_type", sharer.type_.ordinal());
        group.put("sharer_hash", Base64.encodeToString(sharer_hash, Base64.DEFAULT));
        if (thumbnail != null)
            group.put("thumbnail", Base64.encodeToString(thumbnail, Base64.DEFAULT));
        group.put("member_count", member_count);

        byte[] key = Util.sha256(("happysalt621" + mmPassword).getBytes());
        byte[] data = group.toString().getBytes();
        byte[] iv = new byte[16];
        new SecureRandom().nextBytes(iv);

        byte[] partial_enc_data;
        Cipher cipher;
        AlgorithmParameterSpec iv_spec;
        SecretKeySpec sks;
        try {
            cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
        } catch (Exception e) {
            throw new RuntimeException("AES not supported on this platform", e);
        }
        try {
            iv_spec = new IvParameterSpec(iv);
            sks = new SecretKeySpec(key, "AES");
            cipher.init(Cipher.ENCRYPT_MODE, sks, iv_spec);
        } catch (Exception e) {
            throw new RuntimeException("bad iv or key", e);
        }
        try {
            partial_enc_data = cipher.doFinal(data);
        } catch (Exception e) {
            throw new RuntimeException("body encryption failed", e);
        }

        TByteArrayList bal = new TByteArrayList(iv.length + partial_enc_data.length);
        bal.add(iv);
        bal.add(partial_enc_data);
        byte[] enc_data = bal.toArray();

        if (DBG)
            Log.d(TAG, "Posting to gps server...");

        Uri uri = Uri.parse("http://bumblebee.musubi.us:6253/nearbyapi/0/sharegroup");

        StringBuffer sb = new StringBuffer();
        DefaultHttpClient client = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(uri.toString());
        httpPost.addHeader("Content-Type", "application/json");
        JSONArray buckets = new JSONArray();
        JSONObject descriptor = new JSONObject();

        double lat = mmLocation.getLatitude();
        double lng = mmLocation.getLongitude();
        long[] coords = GridHandler.getGridCoords(lat, lng, 5280 / 2);
        for (long c : coords) {
            MessageDigest md;
            try {
                byte[] obfuscate = ("sadsalt193s" + mmPassword).getBytes();
                md = MessageDigest.getInstance("SHA-256");
                ByteBuffer b = ByteBuffer.allocate(8 + obfuscate.length);
                b.putLong(c);
                b.put(obfuscate);
                String secret_bucket = Base64.encodeToString(md.digest(b.array()), Base64.DEFAULT);
                buckets.put(buckets.length(), secret_bucket);
            } catch (NoSuchAlgorithmException e) {
                throw new RuntimeException("your platform does not support sha256", e);
            }
        }
        descriptor.put("buckets", buckets);
        descriptor.put("data", Base64.encodeToString(enc_data, Base64.DEFAULT));
        descriptor.put("expiration", new Date().getTime() + 1000 * 60 * 60);

        httpPost.setEntity(new StringEntity(descriptor.toString()));
        try {
            HttpResponse execute = client.execute(httpPost);
            InputStream content = execute.getEntity().getContent();
            BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
            String s = "";
            while ((s = buffer.readLine()) != null) {
                if (isCancelled()) {
                    return null;
                }
                sb.append(s);
            }
            if (sb.toString().equals("ok"))
                mSucceeded = true;
            else {
                System.err.println(sb);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //TODO: report failures etc
    } catch (Exception e) {
        Log.e(TAG, "Failed to broadcast group", e);
    }
    return null;
}

From source file:com.maass.android.imgur_uploader.ImgurUpload.java

private void handleResponse() {
    Log.i(this.getClass().getName(), "in handleResponse()");
    // close progress notification
    mNotificationManager.cancel(NOTIFICATION_ID);

    String notificationMessage = getString(R.string.upload_success);

    // notification intent with result
    final Intent notificationIntent = new Intent(getBaseContext(), ImageDetails.class);

    if (mImgurResponse == null) {
        notificationMessage = getString(R.string.connection_failed);
    } else if (mImgurResponse.get("error") != null) {
        notificationMessage = getString(R.string.unknown_error) + mImgurResponse.get("error");
    } else {/*from  www.j a  v a2  s .  c om*/
        // create thumbnail
        if (mImgurResponse.get("image_hash").length() > 0) {
            createThumbnail(imageLocation);
        }

        // store result in database
        final HistoryDatabase histData = new HistoryDatabase(getBaseContext());
        final SQLiteDatabase data = histData.getWritableDatabase();

        final HashMap<String, String> dataToSave = new HashMap<String, String>();
        dataToSave.put("delete_hash", mImgurResponse.get("delete_hash"));
        dataToSave.put("image_url", mImgurResponse.get("original"));
        final Uri imageUri = Uri
                .parse(getFilesDir() + "/" + mImgurResponse.get("image_hash") + THUMBNAIL_POSTFIX);
        dataToSave.put("local_thumbnail", imageUri.toString());
        dataToSave.put("upload_time", "" + System.currentTimeMillis());

        for (final Map.Entry<String, String> entry : dataToSave.entrySet()) {
            final ContentValues content = new ContentValues();
            content.put("hash", mImgurResponse.get("image_hash"));
            content.put("key", entry.getKey());
            content.put("value", entry.getValue());
            data.insert("imgur_history", null, content);
        }

        //set intent to go to image details
        notificationIntent.putExtra("hash", mImgurResponse.get("image_hash"));
        notificationIntent.putExtra("image_url", mImgurResponse.get("original"));
        notificationIntent.putExtra("delete_hash", mImgurResponse.get("delete_hash"));
        notificationIntent.putExtra("local_thumbnail", imageUri.toString());

        data.close();
        histData.close();

        // if the main activity is already open then refresh the gridview
        sendBroadcast(new Intent(BROADCAST_ACTION));
    }

    //assemble notification
    final Notification notification = new Notification(R.drawable.icon, notificationMessage,
            System.currentTimeMillis());
    notification.setLatestEventInfo(this, getString(R.string.app_name), notificationMessage, PendingIntent
            .getActivity(getBaseContext(), 0, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT));
    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    mNotificationManager.notify(NOTIFICATION_ID, notification);

}

From source file:com.hivewallet.androidclient.wallet.AddressBookProvider.java

@Override
public Uri insert(final Uri uri, final ContentValues values) {
    if (uri.getPathSegments().size() != 1)
        throw new IllegalArgumentException(uri.toString());

    final String address = uri.getLastPathSegment();
    values.put(KEY_ADDRESS, address);/*from  w  w w .  ja  v a2 s  . com*/

    long rowId = helper.getWritableDatabase().insertOrThrow(DATABASE_TABLE, null, values);

    final Uri rowUri = contentUri(getContext().getPackageName()).buildUpon().appendPath(address)
            .appendPath(Long.toString(rowId)).build();

    String photo = values.getAsString(KEY_PHOTO);
    if (photo != null)
        helper.setPhotoAssetAsPermanent(photo, true);

    getContext().getContentResolver().notifyChange(rowUri, null);

    return rowUri;
}

From source file:org.geometerplus.android.fbreader.network.NetworkLibraryActivity.java

private boolean openTreeByIntent(Intent intent) {
    if (FBReaderIntents.Action.OPEN_NETWORK_CATALOG.equals(intent.getAction())) {
        final Uri uri = intent.getData();
        if (uri != null) {
            final NetworkTree tree = NetworkLibrary.Instance().getCatalogTreeByUrl(uri.toString());
            if (tree != null) {
                checkAndRun(new OpenCatalogAction(this), tree);
                return true;
            }/*ww  w .j  a  v  a  2 s . c o m*/
        }
    }
    return false;
}

From source file:com.snail.imagechooser.threads.MediaProcessorThread.java

@SuppressLint("NewApi")
protected String getAbsoluteImagePathFromUri(Uri imageUri) {
    String[] proj = { MediaColumns.DATA, MediaColumns.DISPLAY_NAME };

    if (Config.DEBUG) {
        Log.i(TAG, "Image Uri: " + imageUri.toString());
    }//from  www .j  a  v a 2  s  . c o  m

    if (imageUri.toString().startsWith("content://com.android.gallery3d.provider")) {
        imageUri = Uri
                .parse(imageUri.toString().replace("com.android.gallery3d", "com.google.android.gallery3d"));
    }

    String filePath = "";
    String imageUriString = imageUri.toString();
    if (imageUriString.startsWith("content://com.google.android.gallery3d")
            || imageUriString.startsWith("content://com.google.android.apps.photos.content")
            || imageUriString.startsWith("content://com.android.providers.media.documents")
            || imageUriString.startsWith("content://com.google.android.apps.docs.storage")
            || imageUriString.startsWith("content://com.microsoft.skydrive.content.external")) {
        filePath = imageUri.toString();
    } else {
        Cursor cursor = context.getContentResolver().query(imageUri, proj, null, null, null);
        cursor.moveToFirst();
        filePath = cursor.getString(cursor.getColumnIndexOrThrow(MediaColumns.DATA));
        cursor.close();
    }

    return filePath;
}

From source file:com.haru.ui.image.workers.MediaProcessorThread.java

@SuppressLint("NewApi")
protected String getAbsoluteImagePathFromUri(Uri imageUri) {
    String[] proj = { MediaColumns.DATA, MediaColumns.DISPLAY_NAME };

    if (/* TODO: DEBUG */ true) {
        Log.i(TAG, "Image Uri: " + imageUri.toString());
    }/*from ww w .  j a  v a2 s .c  o m*/

    if (imageUri.toString().startsWith("content://com.android.gallery3d.provider")) {
        imageUri = Uri
                .parse(imageUri.toString().replace("com.android.gallery3d", "com.google.android.gallery3d"));
    }

    String filePath = "";
    String imageUriString = imageUri.toString();
    if (imageUriString.startsWith("content://com.google.android.gallery3d")
            || imageUriString.startsWith("content://com.google.android.apps.photos.content")
            || imageUriString.startsWith("content://com.android.providers.media.documents")
            || imageUriString.startsWith("content://com.google.android.apps.docs.storage")
            || imageUriString.startsWith("content://com.microsoft.skydrive.content.external")) {
        filePath = imageUri.toString();
    } else {
        Cursor cursor = context.getContentResolver().query(imageUri, proj, null, null, null);
        cursor.moveToFirst();
        filePath = cursor.getString(cursor.getColumnIndexOrThrow(MediaColumns.DATA));
        cursor.close();
    }

    return filePath;
}

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

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

    // 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;

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

    try {//from   www  .  j a  v  a 2  s.co m
        // 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();
        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");
        }

    } catch (IOException e) {
        Log.e(LOG_TAG, "Error ", e);
    } 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:com.eincs.athens.android.OlympusFeedActivity.java

private void getTimeline(final String after, final String before) {

    final HttpClient httpClient = new DefaultHttpClient();
    new DefaultAsyncTask<JSONObject>(ProgressDialogs.createDialog(this)) {

        @Override//  w  w  w  .  ja  v  a2 s  .co m
        protected JSONObject doInBackground(Object... params) {
            Uri uri = Uri.parse(OlympusConst.SERVER_HOST + OlympusConst.PATH_TIMELINE);
            Uri.Builder builder = uri.buildUpon();

            if (!StringUtils.isEmptyOrNull(after)) {
                builder.appendQueryParameter("after", after);
            }

            if (!StringUtils.isEmptyOrNull(after)) {
                builder.appendQueryParameter("before", before);
            }

            HttpGet httpGet = new HttpGet(uri.toString());

            try {
                JSONObject result = httpClient.execute(httpGet, new JSONResponseHandler());
                return result;

            } catch (Exception e) {
                Log.e("Olympus", e.getMessage(), e);
                return null;
            }
        }

        protected void onPostExecute(JSONObject result) {
            super.onPostExecute(result);

            if (result == null) {
                Toast.makeText(mContext, "error", Toast.LENGTH_SHORT).show();

            } else if (result.has("error")) {
                try {
                    Toast.makeText(mContext, result.getString("error"), Toast.LENGTH_SHORT).show();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                try {
                    JSONArray jsonList = result.getJSONArray("result");
                    List<Post> postList = Post.createList(jsonList);

                    mData.clear();
                    for (Post post : postList) {
                        mData.put(post.getId(), post);
                    }

                    mDataArray.clear();
                    for (Integer integer : mData.keySet()) {
                        mDataArray.add(mData.get(integer));
                    }
                    mAdapter.notifyDataSetChanged();

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        };
    }.execute();
}