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:edu.mit.mobile.android.locast.sync.AbsMediaSync.java

public void onScanCompleted(String path, Uri locMediaUri) {
    if (locMediaUri == null) {
        Log.e(TAG, "Scan failed for newly downloaded content: " + path);
        return;//  w  ww.ja  va2  s. c om
    }

    final ScanQueueItem item = mScanMap.get(path);
    if (item == null) {
        Log.e(TAG, "Couldn't find media item (" + path + ") in scan map, so we couldn't update any casts.");
        return;
    }

    updateCastMediaLocalUri(item.castMediaUri, locMediaUri.toString(), item.contentType);
}

From source file:com.androidzeitgeist.dashwatch.common.IOUtil.java

public static InputStream openUri(Context context, Uri uri, String reqContentTypeSubstring)
        throws OpenUriException {

    if (uri == null) {
        throw new IllegalArgumentException("Uri cannot be empty");
    }// w  w  w. j  av a  2s  .com

    String scheme = uri.getScheme();
    if (scheme == null) {
        throw new OpenUriException(false, new IOException("Uri had no scheme"));
    }

    InputStream in = null;
    if ("content".equals(scheme)) {
        try {
            in = context.getContentResolver().openInputStream(uri);
        } catch (FileNotFoundException e) {
            throw new OpenUriException(false, e);
        } catch (SecurityException e) {
            throw new OpenUriException(false, e);
        }

    } else if ("file".equals(scheme)) {
        List<String> segments = uri.getPathSegments();
        if (segments != null && segments.size() > 1 && "android_asset".equals(segments.get(0))) {
            AssetManager assetManager = context.getAssets();
            StringBuilder assetPath = new StringBuilder();
            for (int i = 1; i < segments.size(); i++) {
                if (i > 1) {
                    assetPath.append("/");
                }
                assetPath.append(segments.get(i));
            }
            try {
                in = assetManager.open(assetPath.toString());
            } catch (IOException e) {
                throw new OpenUriException(false, e);
            }
        } else {
            try {
                in = new FileInputStream(new File(uri.getPath()));
            } catch (FileNotFoundException e) {
                throw new OpenUriException(false, e);
            }
        }

    } else if ("http".equals(scheme) || "https".equals(scheme)) {
        OkHttpClient client = new OkHttpClient();
        HttpURLConnection conn = null;
        int responseCode = 0;
        String responseMessage = null;
        try {
            conn = client.open(new URL(uri.toString()));
            conn.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT);
            conn.setReadTimeout(DEFAULT_READ_TIMEOUT);
            responseCode = conn.getResponseCode();
            responseMessage = conn.getResponseMessage();
            if (!(responseCode >= 200 && responseCode < 300)) {
                throw new IOException("HTTP error response.");
            }
            if (reqContentTypeSubstring != null) {
                String contentType = conn.getContentType();
                if (contentType == null || contentType.indexOf(reqContentTypeSubstring) < 0) {
                    throw new IOException("HTTP content type '" + contentType + "' didn't match '"
                            + reqContentTypeSubstring + "'.");
                }
            }
            in = conn.getInputStream();

        } catch (MalformedURLException e) {
            throw new OpenUriException(false, e);
        } catch (IOException e) {
            if (conn != null && responseCode > 0) {
                throw new OpenUriException(500 <= responseCode && responseCode < 600, responseMessage, e);
            } else {
                throw new OpenUriException(false, e);
            }

        }
    }

    return in;
}

From source file:edu.stanford.mobisocial.dungbeetle.DungBeetleContentProvider.java

/**
 * Inserts a message locally that has been received from some agent,
 * typically from a remote device./*  ww  w.j  a  v a 2 s .c  o  m*/
 */
@Override
public Uri insert(Uri uri, ContentValues values) {
    ContentResolver resolver = getContext().getContentResolver();
    if (DBG)
        Log.i(TAG, "Inserting at uri: " + uri + ", " + values);

    final String appId = getCallingActivityId();
    if (appId == null) {
        Log.d(TAG, "No AppId for calling activity. Ignoring query.");
        return null;
    }

    List<String> segs = uri.getPathSegments();
    if (match(uri, "feeds", "me")) {
        if (!appId.equals(SUPER_APP_ID)) {
            return null;
        }

        long objId = mHelper.addToFeed(appId, "friend", values);
        Uri objUri = DbObject.uriForObj(objId);
        resolver.notifyChange(Feed.uriForName("me"), null);
        resolver.notifyChange(Feed.uriForName("friend"), null);
        resolver.notifyChange(objUri, null);
        return objUri;
    } else if (match(uri, "feeds", ".+")) {
        String feedName = segs.get(1);
        String type = values.getAsString(DbObject.TYPE);
        try {
            JSONObject json = new JSONObject(values.getAsString(DbObject.JSON));
            String objHash = null;
            if (feedName.contains(":")) {
                String[] parts = feedName.split(":");
                feedName = parts[0];
                objHash = parts[1];
            }
            if (objHash != null) {
                json.put(DbObjects.TARGET_HASH, Long.parseLong(objHash));
                json.put(DbObjects.TARGET_RELATION, DbRelation.RELATION_PARENT);
                values.put(DbObject.JSON, json.toString());
            }

            String appAuthority = appId;
            if (SUPER_APP_ID.equals(appId)) {
                if (AppObj.TYPE.equals(type)) {
                    if (json.has(AppObj.ANDROID_PACKAGE_NAME)) {
                        appAuthority = json.getString(AppObj.ANDROID_PACKAGE_NAME);
                    }
                }
            }

            long objId = mHelper.addToFeed(appAuthority, feedName, values);
            Uri objUri = DbObject.uriForObj(objId);
            resolver.notifyChange(objUri, null);
            notifyDependencies(mHelper, resolver, segs.get(1));
            if (DBG)
                Log.d(TAG, "just inserted " + values.getAsString(DbObject.JSON));
            return objUri;
        } catch (JSONException e) {
            return null;
        }
    } else if (match(uri, "out")) {
        try {
            JSONObject obj = new JSONObject(values.getAsString("json"));
            long objId = mHelper.addToOutgoing(appId, values.getAsString(DbObject.DESTINATION),
                    values.getAsString(DbObject.TYPE), obj);
            resolver.notifyChange(Uri.parse(CONTENT_URI + "/out"), null);
            return DbObject.uriForObj(objId);
        } catch (JSONException e) {
            return null;
        }
    } else if (match(uri, "contacts")) {
        if (!appId.equals(SUPER_APP_ID)) {
            return null;
        }
        long id = mHelper.insertContact(values);
        resolver.notifyChange(Uri.parse(CONTENT_URI + "/contacts"), null);
        return uriWithId(uri, id);
    } else if (match(uri, "subscribers")) {
        // Question: Should this be restricted?
        // if(!appId.equals(SUPER_APP_ID)) return null;
        long id = mHelper.insertSubscriber(values);
        resolver.notifyChange(Uri.parse(CONTENT_URI + "/subscribers"), null);
        return uriWithId(uri, id);
    } else if (match(uri, "groups")) {
        if (!appId.equals(SUPER_APP_ID))
            return null;
        long id = mHelper.insertGroup(values);
        getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/groups"), null);
        return uriWithId(uri, id);
    } else if (match(uri, "group_members")) {
        if (!appId.equals(SUPER_APP_ID)) {
            return null;
        }
        long id = mHelper.insertGroupMember(values);
        getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/group_members"), null);
        getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/group_contacts"), null);
        return uriWithId(uri, id);
    }

    else if (match(uri, "group_invitations")) {
        if (!appId.equals(SUPER_APP_ID)) {
            return null;
        }
        String groupName = values.getAsString(InviteToGroupObj.GROUP_NAME);
        Uri dynUpdateUri = Uri.parse(values.getAsString(InviteToGroupObj.DYN_UPDATE_URI));
        long gid = values.getAsLong("groupId");
        SQLiteDatabase db = mHelper.getWritableDatabase();
        mHelper.addToOutgoing(db, appId, values.getAsString(InviteToGroupObj.PARTICIPANTS),
                InviteToGroupObj.TYPE, InviteToGroupObj.json(groupName, dynUpdateUri));
        getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/out"), null);
        return uriWithId(uri, gid);
    }

    else if (match(uri, "dynamic_groups")) {
        if (!appId.equals(SUPER_APP_ID)) {
            return null;
        }
        Uri gUri = Uri.parse(values.getAsString("uri"));
        GroupProviders.GroupProvider gp = GroupProviders.forUri(gUri);
        String feedName = gp.feedName(gUri);
        Maybe<Group> mg = mHelper.groupByFeedName(feedName);
        long id = -1;
        try {
            Group g = mg.get();
            id = g.id;
        } catch (Maybe.NoValError e) {
            ContentValues cv = new ContentValues();
            cv.put(Group.NAME, gp.groupName(gUri));
            cv.put(Group.FEED_NAME, feedName);
            cv.put(Group.DYN_UPDATE_URI, gUri.toString());

            String table = DbObject.TABLE;
            String[] columns = new String[] { DbObject.FEED_NAME };
            String selection = DbObject.CHILD_FEED_NAME + " = ?";
            String[] selectionArgs = new String[] { feedName };
            Cursor parent = mHelper.getReadableDatabase().query(table, columns, selection, selectionArgs, null,
                    null, null);
            try {
                if (parent.moveToFirst()) {
                    String parentName = parent.getString(0);
                    table = Group.TABLE;
                    columns = new String[] { Group._ID };
                    selection = Group.FEED_NAME + " = ?";
                    selectionArgs = new String[] { parentName };

                    Cursor parent2 = mHelper.getReadableDatabase().query(table, columns, selection,
                            selectionArgs, null, null, null);
                    try {
                        if (parent2.moveToFirst()) {
                            cv.put(Group.PARENT_FEED_ID, parent2.getLong(0));
                        } else {
                            Log.e(TAG, "Parent feed found but no id for " + parentName);
                        }
                    } finally {
                        parent2.close();
                    }
                } else {
                    Log.w(TAG, "No parent feed for " + feedName);
                }
            } finally {
                parent.close();
            }
            id = mHelper.insertGroup(cv);
            getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/dynamic_groups"), null);
            getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/groups"), null);
        }
        return uriWithId(uri, id);
    }

    else if (match(uri, "dynamic_group_member")) {
        if (!appId.equals(SUPER_APP_ID)) {
            return null;
        }
        SQLiteDatabase db = mHelper.getWritableDatabase();
        db.beginTransaction();
        try {
            ContentValues cv = new ContentValues();
            String pubKeyStr = values.getAsString(Contact.PUBLIC_KEY);
            RSAPublicKey k = RSACrypto.publicKeyFromString(pubKeyStr);
            String personId = mIdent.personIdForPublicKey(k);
            if (!personId.equals(mIdent.userPersonId())) {
                cv.put(Contact.PUBLIC_KEY, values.getAsString(Contact.PUBLIC_KEY));
                cv.put(Contact.NAME, values.getAsString(Contact.NAME));
                cv.put(Contact.EMAIL, values.getAsString(Contact.EMAIL));
                if (values.getAsString(Contact.PICTURE) != null) {
                    cv.put(Contact.PICTURE, values.getAsByteArray(Contact.PICTURE));
                }

                long cid = -1;
                Contact contact = mHelper.contactForPersonId(personId).otherwise(Contact.NA());
                if (contact.id > -1) {
                    cid = contact.id;
                } else {
                    cid = mHelper.insertContact(db, cv);
                }

                if (cid > -1) {

                    ContentValues gv = new ContentValues();
                    gv.put(GroupMember.GLOBAL_CONTACT_ID, values.getAsString(GroupMember.GLOBAL_CONTACT_ID));
                    gv.put(GroupMember.GROUP_ID, values.getAsLong(GroupMember.GROUP_ID));
                    gv.put(GroupMember.CONTACT_ID, cid);
                    mHelper.insertGroupMember(db, gv);
                    getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/group_members"),
                            null);
                    getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/contacts"), null);
                    getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/group_contacts"),
                            null);

                    // Add subscription to this private group feed
                    ContentValues sv = new ContentValues();
                    sv = new ContentValues();
                    sv.put(Subscriber.CONTACT_ID, cid);
                    sv.put(Subscriber.FEED_NAME, values.getAsString(Group.FEED_NAME));
                    mHelper.insertSubscriber(db, sv);

                    ContentValues xv = new ContentValues();
                    xv.put(Subscriber.CONTACT_ID, cid);
                    xv.put(Subscriber.FEED_NAME, "friend");
                    mHelper.insertSubscriber(db, xv);

                    getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/subscribers"),
                            null);

                    db.setTransactionSuccessful();
                }
                return uriWithId(uri, cid);
            } else {
                Log.i(TAG, "Omitting self.");
                return uriWithId(uri, Contact.MY_ID);
            }
        } finally {
            db.endTransaction();
        }
    } else {
        Log.e(TAG, "Failed to insert into " + uri);
        return null;
    }
}

From source file:com.siahmsoft.soundroid.sdk7.provider.tracks.TracksStore.java

/**
 * Usarlo cuando el resultado va a ser un elemento Track
 *
 * @param uri/*from   w ww.  ja v a2s  .c o m*/
 * @param listener
 */
private void getTrackFromUri(Uri uri, final ResultListener<Track> listener) {
    final HttpGet get = new HttpGet(uri.toString());
    final Track track = createTrack();

    try {
        executeRequest(get, new ResponseHandler() {
            public void handleResponse(InputStream in) throws IOException {
                parseSingleResponse(in, new ResponseParserSingle() {
                    @Override
                    public void parseResponse(JSONObject parser) throws JSONException {
                        parseTrack(parser, track, listener);
                    }
                });
            }
        });

    } catch (IOException e) {
        android.util.Log.e(LOG_TAG, "Could not perform search with query: ", e);
        listener.onError(e);
    }

    return;
}

From source file:edu.stanford.mobisocial.dungbeetle.feed.objects.PictureObj.java

public static DbObject from(Context context, Uri imageUri) throws IOException {
    // Query gallery for camera picture via
    // Android ContentResolver interface
    ContentResolver cr = context.getContentResolver();

    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;//from w w w. j  a  v a 2 s.  c  o  m
    BitmapFactory.decodeStream(cr.openInputStream(imageUri), null, options);

    int targetSize = 200;
    int xScale = (options.outWidth + targetSize - 1) / targetSize;
    int yScale = (options.outHeight + targetSize - 1) / targetSize;

    int scale = xScale < yScale ? xScale : yScale;
    //uncomment this to get faster power of two scaling
    //for(int i = 0; i < 32; ++i) {
    //   int mushed = scale & ~(1 << i);
    //   if(mushed != 0)
    //      scale = mushed;
    //}

    options.inJustDecodeBounds = false;
    options.inSampleSize = scale;

    Bitmap sourceBitmap = BitmapFactory.decodeStream(cr.openInputStream(imageUri), null, options);

    int width = sourceBitmap.getWidth();
    int height = sourceBitmap.getHeight();
    int cropSize = Math.min(width, height);

    float scaleSize = ((float) targetSize) / cropSize;

    Matrix matrix = new Matrix();
    matrix.postScale(scaleSize, scaleSize);
    float rotation = PhotoTaker.rotationForImage(context, imageUri);
    if (rotation != 0f) {
        matrix.preRotate(rotation);
    }

    Bitmap resizedBitmap = Bitmap.createBitmap(sourceBitmap, 0, 0, width, height, matrix, true);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    resizedBitmap.compress(Bitmap.CompressFormat.JPEG, 90, baos);
    byte[] data = baos.toByteArray();
    sourceBitmap.recycle();
    sourceBitmap = null;
    resizedBitmap.recycle();
    resizedBitmap = null;
    System.gc(); // TODO: gross.

    JSONObject base = new JSONObject();
    if (ContentCorral.CONTENT_CORRAL_ENABLED) {
        try {
            String type = cr.getType(imageUri);
            if (type == null) {
                type = "image/jpeg";
            }
            base.put(CorralClient.OBJ_LOCAL_URI, imageUri.toString());
            base.put(CorralClient.OBJ_MIME_TYPE, type);
            String localIp = ContentCorral.getLocalIpAddress();
            if (localIp != null) {
                base.put(Contact.ATTR_LAN_IP, localIp);
            }
        } catch (JSONException e) {
            Log.e(TAG, "impossible json error possible!");
        }
    }
    return from(base, data);
}

From source file:com.siahmsoft.soundroid.sdk7.provider.tracks.TracksStore.java

private void deleteTrack(Uri uri, final ResultListener<Track> listener) {
    final HttpDelete delete = new HttpDelete(uri.toString());
    try {/*from  w w w  .  j av  a  2  s .com*/
        executeRequest(delete, new ResponseHandler() {
            public void handleResponse(InputStream in) throws IOException {
                parseSingleResponse(in, new ResponseParserSingle() {
                    @Override
                    public void parseResponse(JSONObject parser) throws JSONException {
                        //parseTrack(parser, track, listener);
                        listener.onSuccess((Track) new Object());//TODO VER COMO ARREGLAR ESTO
                    }
                });
            }
        });

    } catch (IOException e) {
        android.util.Log.e(LOG_TAG, "Could not perform search with query: ", e);
        listener.onError(e);
    }

    return;
}

From source file:com.siahmsoft.soundroid.sdk7.provider.tracks.TracksStore.java

/**
 * Usarlo cuando el resultado va a ser un array de elementos Track
 *
 * @param uri/*from w w  w.ja v a2s. co m*/
 * @param listener
 */
private void getTracksfromUri(Uri uri, final ResultListener<ArrayList<Track>> listener) {
    final HttpGet get = new HttpGet(uri.toString());
    final ArrayList<Track> tracks = new ArrayList<Track>();

    try {
        executeRequest(get, new ResponseHandler() {
            public void handleResponse(InputStream in) throws IOException {
                parseArrayResponse(in, new ResponseParserArray() {
                    @Override
                    public void parseResponse(JSONArray parser) {
                        parseTracks(parser, tracks, listener);
                    }
                });
            }
        });

    } catch (IOException e) {
        android.util.Log.e(LOG_TAG, "Could not perform search with query: ", e);
        listener.onError(e);
    }

    return;
}

From source file:com.hybris.mobile.lib.commerce.provider.CatalogProvider.java

@Override
public String getType(Uri uri) {
    String type;//from w  w  w  . j a  v  a 2s  .  c  o m

    switch (URI_MATCHER.match(uri)) {
    case CatalogContract.Provider.CODE_GROUP:
        type = CatalogContract.Provider.getTypeGroupAll(authority);
        break;

    case CatalogContract.Provider.CODE_GROUP_ID:
        type = CatalogContract.Provider.getTypeGroup(authority);
        break;

    case CatalogContract.Provider.CODE_DATA_ID:
        type = CatalogContract.Provider.getTypeData(authority);
        break;

    case CatalogContract.Provider.CODE_DATA_DETAILS_ID:
        type = CatalogContract.Provider.getTypeDataDetails(authority);
        break;

    case CatalogContract.Provider.CODE_SYNC_GROUP:
        type = CatalogContract.Provider.getTypeSyncGroup(authority);
        break;

    default:
        Log.e(TAG, "URI not recognized: " + uri.toString());
        throw new IllegalArgumentException("URI not recognized" + uri.toString());
    }

    return type;
}

From source file:org.planetmono.dcuploader.ActivityUploader.java

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    if (tempFile != null)
        outState.putString("tempfile", tempFile.getAbsolutePath());
    if (target != null)
        outState.putString("target", target);
    if (tempFiles.size() > 0)
        outState.putStringArrayList("tempfiles", tempFiles);
    if (contents.size() > 0) {
        String[] carr = new String[contents.size()];

        int t = 0;
        for (Uri u : contents)
            carr[t++] = u.toString();

        outState.putStringArray("contents", carr);
    }/*from   w w w  .  ja  va  2 s.  c  o m*/
}