Example usage for android.net Uri getLastPathSegment

List of usage examples for android.net Uri getLastPathSegment

Introduction

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

Prototype

@Nullable
public abstract String getLastPathSegment();

Source Link

Document

Gets the decoded last segment in the path.

Usage

From source file:androidx.media.widget.VideoView2.java

private void openVideo(Uri uri, Map<String, String> headers) {
    resetPlayer();//from   ww  w .  ja  v  a2s.  c o  m
    if (isRemotePlayback()) {
        // TODO (b/77158231)
        // mRoutePlayer.openVideo(dsd);
        return;
    }

    try {
        Log.d(TAG, "openVideo(): creating new MediaPlayer instance.");
        mMediaPlayer = new MediaPlayer();
        mSurfaceView.setMediaPlayer(mMediaPlayer);
        mTextureView.setMediaPlayer(mMediaPlayer);
        mCurrentView.assignSurfaceToMediaPlayer(mMediaPlayer);

        final Context context = getContext();
        // TODO: Add timely firing logic for more accurate sync between CC and video frame
        // mSubtitleController = new SubtitleController(context);
        // mSubtitleController.registerRenderer(new ClosedCaptionRenderer(context));
        // mSubtitleController.setAnchor((SubtitleController.Anchor) mSubtitleView);

        mMediaPlayer.setOnPreparedListener(mPreparedListener);
        mMediaPlayer.setOnVideoSizeChangedListener(mSizeChangedListener);
        mMediaPlayer.setOnCompletionListener(mCompletionListener);
        mMediaPlayer.setOnSeekCompleteListener(mSeekCompleteListener);
        mMediaPlayer.setOnErrorListener(mErrorListener);
        mMediaPlayer.setOnInfoListener(mInfoListener);
        mMediaPlayer.setOnBufferingUpdateListener(mBufferingUpdateListener);

        mCurrentBufferPercentage = -1;
        mMediaPlayer.setDataSource(getContext(), uri, headers);
        mMediaPlayer.setAudioAttributes(mAudioAttributes);
        // mMediaPlayer.setOnSubtitleDataListener(mSubtitleListener);
        // we don't set the target state here either, but preserve the
        // target state that was there before.
        mCurrentState = STATE_PREPARING;
        mMediaPlayer.prepareAsync();

        // Save file name as title since the file may not have a title Metadata.
        mTitle = uri.getPath();
        String scheme = uri.getScheme();
        if (scheme != null && scheme.equals("file")) {
            mTitle = uri.getLastPathSegment();
        }
        mRetriever = new MediaMetadataRetriever();
        mRetriever.setDataSource(getContext(), uri);

        if (DEBUG) {
            Log.d(TAG, "openVideo(). mCurrentState=" + mCurrentState + ", mTargetState=" + mTargetState);
        }
    } catch (IOException | IllegalArgumentException ex) {
        Log.w(TAG, "Unable to open content: " + uri, ex);
        mCurrentState = STATE_ERROR;
        mTargetState = STATE_ERROR;
        mErrorListener.onError(mMediaPlayer, MediaPlayer.MEDIA_ERROR_UNKNOWN, MediaPlayer.MEDIA_ERROR_IO);
    }
}

From source file:org.matrix.androidsdk.fragments.MatrixMessageListFragment.java

/**
 * Upload a file content/*from   w  ww.j  ava2 s .  c  o  m*/
 *
 * @param mediaUrl      the media URL
 * @param mimeType      the media mime type
 * @param mediaFilename the media filename
 */
public void uploadFileContent(final String mediaUrl, String mimeType, final String mediaFilename) {
    // create a tmp row
    final FileMessage tmpFileMessage;

    if ((null != mimeType) && mimeType.startsWith("audio/")) {
        tmpFileMessage = new AudioMessage();
    } else {
        tmpFileMessage = new FileMessage();
    }

    tmpFileMessage.url = mediaUrl;
    tmpFileMessage.body = mediaFilename;

    MXEncryptedAttachments.EncryptionResult encryptionResult = null;
    InputStream fileStream = null;

    try {
        Uri uri = Uri.parse(mediaUrl);
        Room.fillFileInfo(getActivity(), tmpFileMessage, uri, mimeType);

        String filename = uri.getPath();
        fileStream = new FileInputStream(new File(filename));

        if (mRoom.isEncrypted() && mSession.isCryptoEnabled() && (null != fileStream)) {
            encryptionResult = MXEncryptedAttachments.encryptAttachment(fileStream, mimeType);
            fileStream.close();
            if (null != encryptionResult) {
                fileStream = encryptionResult.mEncryptedStream;
                mimeType = "application/octet-stream";
            } else {
                displayEncryptionAlert();
                return;
            }
        }

        if (null == tmpFileMessage.body) {
            tmpFileMessage.body = uri.getLastPathSegment();
        }

    } catch (Exception e) {
        Log.e(LOG_TAG, "uploadFileContent failed with " + e.getLocalizedMessage());
    }

    // remove any displayed MessageRow with this URL
    // to avoid duplicate
    final MessageRow messageRow = addMessageRow(tmpFileMessage);
    messageRow.getEvent().mSentState = Event.SentState.SENDING;

    final MXEncryptedAttachments.EncryptionResult fEncryptionResult = encryptionResult;

    getSession().getMediasCache().uploadContent(fileStream, tmpFileMessage.body, mimeType, mediaUrl,
            new MXMediaUploadListener() {
                @Override
                public void onUploadStart(String uploadId) {
                    getUiHandler().post(new Runnable() {
                        @Override
                        public void run() {
                            onMessageSendingSucceeded(messageRow.getEvent());
                            // display the pie chart.
                            mAdapter.notifyDataSetChanged();
                        }
                    });
                }

                @Override
                public void onUploadCancel(String uploadId) {
                    getUiHandler().post(new Runnable() {
                        @Override
                        public void run() {
                            onMessageSendingFailed(messageRow.getEvent());
                        }
                    });
                }

                @Override
                public void onUploadError(final String uploadId, final int serverResponseCode,
                        final String serverErrorMessage) {
                    getUiHandler().post(new Runnable() {
                        @Override
                        public void run() {
                            commonMediaUploadError(serverResponseCode, serverErrorMessage, messageRow);
                        }
                    });
                }

                @Override
                public void onUploadComplete(final String uploadId, final String contentUri) {
                    getUiHandler().post(new Runnable() {
                        @Override
                        public void run() {
                            // Build the image message
                            FileMessage message = tmpFileMessage.deepCopy();

                            // replace the thumbnail and the media contents by the computed ones
                            getMXMediasCache().saveFileMediaForUrl(contentUri, mediaUrl,
                                    tmpFileMessage.getMimeType());

                            if (null != fEncryptionResult) {
                                message.file = fEncryptionResult.mEncryptedFileInfo;
                                message.file.url = contentUri;
                                message.url = null;
                            } else {
                                message.url = contentUri;
                            }

                            // update the event content with the new message info
                            messageRow.getEvent().updateContent(JsonUtils.toJson(message));

                            Log.d(LOG_TAG, "Uploaded to " + contentUri);

                            send(messageRow);
                        }
                    });
                }
            });
}

From source file:com.amaze.carbonfilemanager.fragments.ZipViewer.java

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    Sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
    s = getArguments().getString(KEY_PATH);
    Uri uri = Uri.parse(s);
    f = new File(uri.getPath());
    mToolbarContainer = getActivity().findViewById(R.id.lin);
    mToolbarContainer.setOnTouchListener(new View.OnTouchListener() {
        @Override/*w  ww .  j  a  va 2s  .  co  m*/
        public boolean onTouch(View view, MotionEvent motionEvent) {
            if (stopAnims) {
                if ((!rarAdapter.stoppedAnimation)) {
                    stopAnim();
                }
                rarAdapter.stoppedAnimation = true;

            }
            stopAnims = false;
            return false;
        }
    });
    hidemode = Sp.getInt("hidemode", 0);
    listView.setVisibility(View.VISIBLE);
    mLayoutManager = new LinearLayoutManager(getActivity());
    listView.setLayoutManager(mLayoutManager);
    res = getResources();
    mainActivity.supportInvalidateOptionsMenu();
    if (utilsProvider.getAppTheme().equals(AppTheme.DARK))
        rootView.setBackgroundColor(Utils.getColor(getContext(), R.color.holo_dark_background));
    else
        listView.setBackgroundColor(Utils.getColor(getContext(), android.R.color.background_light));

    gobackitem = Sp.getBoolean("goBack_checkbox", false);
    coloriseIcons = Sp.getBoolean("coloriseIcons", true);
    Calendar calendar = Calendar.getInstance();
    showSize = Sp.getBoolean("showFileSize", false);
    showLastModified = Sp.getBoolean("showLastModified", true);
    showDividers = Sp.getBoolean("showDividers", true);
    year = ("" + calendar.get(Calendar.YEAR)).substring(2, 4);
    skin = mainActivity.getColorPreference().getColorAsString(ColorUsage.PRIMARY);
    accentColor = mainActivity.getColorPreference().getColorAsString(ColorUsage.ACCENT);
    iconskin = mainActivity.getColorPreference().getColorAsString(ColorUsage.ICON_SKIN);

    //mainActivity.findViewById(R.id.buttonbarframe).setBackgroundColor(Color.parseColor(skin));

    if (savedInstanceState == null && f != null) {

        files = new ArrayList<>();
        // adding a cache file to delete where any user interaction elements will be cached
        String fileName = f.getName().substring(0, f.getName().lastIndexOf("."));
        files.add(new BaseFile(getActivity().getExternalCacheDir().getPath() + "/" + fileName));
        if (f.getPath().endsWith(".rar")) {
            openmode = 1;
            SetupRar(null);
        } else {
            openmode = 0;
            SetupZip(null);
        }
    } else {

        f = new File(savedInstanceState.getString(KEY_FILE));
        s = savedInstanceState.getString(KEY_URI);
        uri = Uri.parse(s);
        f = new File(uri.getPath());
        files = savedInstanceState.getParcelableArrayList(KEY_CACHE_FILES);
        isOpen = savedInstanceState.getBoolean(KEY_OPEN);
        if (f.getPath().endsWith(".rar")) {
            openmode = 1;
            SetupRar(savedInstanceState);
        } else {
            openmode = 0;
            SetupZip(savedInstanceState);
        }

    }
    String fileName = null;
    try {
        if (uri.getScheme().equals(KEY_FILE)) {
            fileName = uri.getLastPathSegment();
        } else {
            Cursor cursor = null;
            try {
                cursor = getActivity().getContentResolver().query(uri,
                        new String[] { MediaStore.Images.ImageColumns.DISPLAY_NAME }, null, null, null);

                if (cursor != null && cursor.moveToFirst()) {
                    fileName = cursor
                            .getString(cursor.getColumnIndex(MediaStore.Images.ImageColumns.DISPLAY_NAME));
                }
            } finally {

                if (cursor != null) {
                    cursor.close();
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    if (fileName == null || fileName.trim().length() == 0)
        fileName = f.getName();
    try {
        mainActivity.setActionBarTitle(fileName);
    } catch (Exception e) {
        mainActivity.setActionBarTitle(getResources().getString(R.string.zip_viewer));
    }
    mainActivity.supportInvalidateOptionsMenu();
    mToolbarHeight = getToolbarHeight(getActivity());
    paddingTop = (mToolbarHeight) + dpToPx(72);
    mToolbarContainer.getViewTreeObserver()
            .addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    paddingTop = mToolbarContainer.getHeight();
                    mToolbarHeight = mainActivity.toolbar.getHeight();

                    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
                        mToolbarContainer.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                    } else {
                        mToolbarContainer.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                    }
                }

            });

}

From source file:org.matrix.console.activity.RoomActivity.java

/**
 * Send a list of images from their URIs
 * @param mediaUris the media URIs//from ww w .j a v a 2 s  . co m
 */
private void sendMedias(final ArrayList<Uri> mediaUris) {

    final View progressBackground = findViewById(R.id.medias_processing_progress_background);
    final View progress = findViewById(R.id.medias_processing_progress);

    progressBackground.setVisibility(View.VISIBLE);
    progress.setVisibility(View.VISIBLE);

    final HandlerThread handlerThread = new HandlerThread("MediasEncodingThread");
    handlerThread.start();

    final android.os.Handler handler = new android.os.Handler(handlerThread.getLooper());

    Runnable r = new Runnable() {
        @Override
        public void run() {
            handler.post(new Runnable() {
                public void run() {
                    final int mediaCount = mediaUris.size();

                    for (Uri anUri : mediaUris) {
                        // crash from Google Analytics : null URI on a nexus 5
                        if (null != anUri) {
                            final Uri mediaUri = anUri;
                            String filename = null;

                            if (mediaUri.toString().startsWith("content://")) {
                                Cursor cursor = null;
                                try {
                                    cursor = RoomActivity.this.getContentResolver().query(mediaUri, null, null,
                                            null, null);
                                    if (cursor != null && cursor.moveToFirst()) {
                                        filename = cursor
                                                .getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
                                    }
                                } catch (Exception e) {
                                    Log.e(LOG_TAG, "cursor.getString " + e.getMessage());
                                } finally {
                                    if (null != cursor) {
                                        cursor.close();
                                    }
                                }

                                if (TextUtils.isEmpty(filename)) {
                                    List uriPath = mediaUri.getPathSegments();
                                    filename = (String) uriPath.get(uriPath.size() - 1);
                                }
                            } else if (mediaUri.toString().startsWith("file://")) {
                                // try to retrieve the filename from the file url.
                                try {
                                    filename = anUri.getLastPathSegment();
                                } catch (Exception e) {
                                }

                                if (TextUtils.isEmpty(filename)) {
                                    filename = null;
                                }
                            }

                            final String fFilename = filename;

                            ResourceUtils.Resource resource = ResourceUtils.openResource(RoomActivity.this,
                                    mediaUri);

                            if (null == resource) {
                                RoomActivity.this.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        handlerThread.quit();
                                        progressBackground.setVisibility(View.GONE);
                                        progress.setVisibility(View.GONE);

                                        Toast.makeText(RoomActivity.this,
                                                getString(R.string.message_failed_to_upload), Toast.LENGTH_LONG)
                                                .show();
                                    }

                                    ;
                                });

                                return;
                            }

                            // save the file in the filesystem
                            String mediaUrl = mMediasCache.saveMedia(resource.contentStream, null,
                                    resource.mimeType);
                            String mimeType = resource.mimeType;
                            Boolean isManaged = false;

                            if ((null != resource.mimeType) && resource.mimeType.startsWith("image/")) {
                                // manage except if there is an error
                                isManaged = true;

                                // try to retrieve the gallery thumbnail
                                // if the image comes from the gallery..
                                Bitmap thumbnailBitmap = null;

                                try {
                                    ContentResolver resolver = getContentResolver();

                                    List uriPath = mediaUri.getPathSegments();
                                    long imageId = -1;
                                    String lastSegment = (String) uriPath.get(uriPath.size() - 1);

                                    // > Kitkat
                                    if (lastSegment.startsWith("image:")) {
                                        lastSegment = lastSegment.substring("image:".length());
                                    }

                                    imageId = Long.parseLong(lastSegment);

                                    thumbnailBitmap = MediaStore.Images.Thumbnails.getThumbnail(resolver,
                                            imageId, MediaStore.Images.Thumbnails.MINI_KIND, null);
                                } catch (Exception e) {
                                    Log.e(LOG_TAG,
                                            "MediaStore.Images.Thumbnails.getThumbnail " + e.getMessage());
                                }

                                double thumbnailWidth = mConsoleMessageListFragment.getMaxThumbnailWith();
                                double thumbnailHeight = mConsoleMessageListFragment.getMaxThumbnailHeight();

                                // no thumbnail has been found or the mimetype is unknown
                                if ((null == thumbnailBitmap) || (thumbnailBitmap.getHeight() > thumbnailHeight)
                                        || (thumbnailBitmap.getWidth() > thumbnailWidth)) {
                                    // need to decompress the high res image
                                    BitmapFactory.Options options = new BitmapFactory.Options();
                                    options.inPreferredConfig = Bitmap.Config.ARGB_8888;
                                    resource = ResourceUtils.openResource(RoomActivity.this, mediaUri);

                                    // get the full size bitmap
                                    Bitmap fullSizeBitmap = null;

                                    if (null == thumbnailBitmap) {
                                        fullSizeBitmap = BitmapFactory.decodeStream(resource.contentStream,
                                                null, options);
                                    }

                                    if ((fullSizeBitmap != null) || (thumbnailBitmap != null)) {
                                        double imageWidth;
                                        double imageHeight;

                                        if (null == thumbnailBitmap) {
                                            imageWidth = fullSizeBitmap.getWidth();
                                            imageHeight = fullSizeBitmap.getHeight();
                                        } else {
                                            imageWidth = thumbnailBitmap.getWidth();
                                            imageHeight = thumbnailBitmap.getHeight();
                                        }

                                        if (imageWidth > imageHeight) {
                                            thumbnailHeight = thumbnailWidth * imageHeight / imageWidth;
                                        } else {
                                            thumbnailWidth = thumbnailHeight * imageWidth / imageHeight;
                                        }

                                        try {
                                            thumbnailBitmap = Bitmap.createScaledBitmap(
                                                    (null == fullSizeBitmap) ? thumbnailBitmap : fullSizeBitmap,
                                                    (int) thumbnailWidth, (int) thumbnailHeight, false);
                                        } catch (OutOfMemoryError ex) {
                                            Log.e(LOG_TAG, "Bitmap.createScaledBitmap " + ex.getMessage());
                                        }
                                    }

                                    // the valid mimetype is not provided
                                    if ("image/*".equals(mimeType)) {
                                        // make a jpg snapshot.
                                        mimeType = null;
                                    }

                                    // unknown mimetype
                                    if ((null == mimeType) || (mimeType.startsWith("image/"))) {
                                        try {
                                            // try again
                                            if (null == fullSizeBitmap) {
                                                System.gc();
                                                fullSizeBitmap = BitmapFactory
                                                        .decodeStream(resource.contentStream, null, options);
                                            }

                                            if (null != fullSizeBitmap) {
                                                Uri uri = Uri.parse(mediaUrl);

                                                if (null == mimeType) {
                                                    // the images are save in jpeg format
                                                    mimeType = "image/jpeg";
                                                }

                                                resource.contentStream.close();
                                                resource = ResourceUtils.openResource(RoomActivity.this,
                                                        mediaUri);

                                                try {
                                                    mMediasCache.saveMedia(resource.contentStream,
                                                            uri.getPath(), mimeType);
                                                } catch (OutOfMemoryError ex) {
                                                    Log.e(LOG_TAG, "mMediasCache.saveMedia" + ex.getMessage());
                                                }

                                            } else {
                                                isManaged = false;
                                            }

                                            resource.contentStream.close();

                                        } catch (Exception e) {
                                            isManaged = false;
                                            Log.e(LOG_TAG, "sendMedias " + e.getMessage());
                                        }
                                    }

                                    // reduce the memory consumption
                                    if (null != fullSizeBitmap) {
                                        fullSizeBitmap.recycle();
                                        System.gc();
                                    }
                                }

                                String thumbnailURL = mMediasCache.saveBitmap(thumbnailBitmap, null);

                                if (null != thumbnailBitmap) {
                                    thumbnailBitmap.recycle();
                                }

                                //
                                if (("image/jpg".equals(mimeType) || "image/jpeg".equals(mimeType))
                                        && (null != mediaUrl)) {

                                    Uri imageUri = Uri.parse(mediaUrl);
                                    // get the exif rotation angle
                                    final int rotationAngle = ImageUtils
                                            .getRotationAngleForBitmap(RoomActivity.this, imageUri);

                                    if (0 != rotationAngle) {
                                        // always apply the rotation to the image
                                        ImageUtils.rotateImage(RoomActivity.this, thumbnailURL, rotationAngle,
                                                mMediasCache);

                                        // the high res media orientation should be not be done on uploading
                                        //ImageUtils.rotateImage(RoomActivity.this, mediaUrl, rotationAngle, mMediasCache))
                                    }
                                }

                                // is the image content valid ?
                                if (isManaged && (null != thumbnailURL)) {

                                    final String fThumbnailURL = thumbnailURL;
                                    final String fMediaUrl = mediaUrl;
                                    final String fMimeType = mimeType;

                                    RoomActivity.this.runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            // if there is only one image
                                            if (mediaCount == 1) {
                                                // display an image preview before sending it
                                                mPendingThumbnailUrl = fThumbnailURL;
                                                mPendingMediaUrl = fMediaUrl;
                                                mPendingMimeType = fMimeType;
                                                mPendingFilename = fFilename;

                                                mConsoleMessageListFragment.scrollToBottom();

                                                manageSendMoreButtons();
                                            } else {
                                                mConsoleMessageListFragment.uploadImageContent(fThumbnailURL,
                                                        fMediaUrl, fFilename, fMimeType);
                                            }
                                        }
                                    });
                                }
                            }

                            // default behaviour
                            if ((!isManaged) && (null != mediaUrl)) {
                                final String fMediaUrl = mediaUrl;
                                final String fMimeType = mimeType;

                                RoomActivity.this.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        if ((null != fMimeType) && fMimeType.startsWith("video/")) {
                                            mConsoleMessageListFragment.uploadVideoContent(fMediaUrl, null,
                                                    fMimeType);
                                        } else {
                                            mConsoleMessageListFragment.uploadFileContent(fMediaUrl, fMimeType,
                                                    fFilename);
                                        }
                                    }
                                });
                            }
                        }
                    }

                    RoomActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            handlerThread.quit();
                            progressBackground.setVisibility(View.GONE);
                            progress.setVisibility(View.GONE);
                        };
                    });
                }
            });
        }
    };

    Thread t = new Thread(r);
    t.start();
}

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

@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
    ContentResolver resolver = getContext().getContentResolver();
    final String realAppId = getCallingActivityId();

    if (realAppId == null) {
        Log.d(TAG, "No AppId for calling activity. Ignoring query.");
        return null;
    }//from  ww w. j  ava  2s . com

    if (DBG)
        Log.d(TAG, "Processing query: " + uri + " from appId " + realAppId);

    int match = sUriMatcher.match(uri);
    switch (match) {
    case UriMatcher.NO_MATCH:
        break;
    case FEEDS:
        Cursor c = mHelper.queryFeedList(realAppId, projection, selection, selectionArgs, sortOrder);
        c.setNotificationUri(resolver, Feed.feedListUri());
        return c;
    case FEEDS_ID:
        List<String> segs = uri.getPathSegments();
        switch (Feed.typeOf(uri)) {
        case APP:
            String queriedAppId = segs.get(1);
            queriedAppId = queriedAppId.substring(queriedAppId.lastIndexOf('^') + 1);
            int pos = queriedAppId.lastIndexOf(':');
            if (pos > 0) {
                queriedAppId = queriedAppId.substring(0, pos);
            }
            if (!realAppId.equals(queriedAppId)) {
                Log.w(TAG, "Illegal data access.");
                return null;
            }
            String table = DbObj.TABLE;
            String select = DbObj.COL_APP_ID + " = ?";
            String[] selectArgs = new String[] { realAppId };
            String[] columns = projection;
            String groupBy = null;
            String having = null;
            String orderBy = null;
            select = DBHelper.andClauses(select, selection);
            selectArgs = DBHelper.andArguments(selectArgs, selectionArgs);
            c = mHelper.getReadableDatabase().query(table, columns, select, selectArgs, groupBy, having,
                    orderBy);
            c.setNotificationUri(resolver, uri);
            return c;
        default:
            boolean isMe = segs.get(1).equals("me");
            String feedName = isMe ? "friend" : segs.get(1);
            if (Feed.FEED_NAME_GLOBAL.equals(feedName)) {
                feedName = null;
            }
            select = isMe ? DBHelper.andClauses(selection, DbObject.CONTACT_ID + "=" + Contact.MY_ID)
                    : selection;
            c = mHelper.queryFeed(realAppId, feedName, projection, select, selectionArgs, sortOrder);
            c.setNotificationUri(resolver, uri);
            return c;
        }
    case OBJS:
        if (!SUPER_APP_ID.equals(realAppId)) {
            String selection2 = DbObj.COL_APP_ID + " = ?";
            String[] selectionArgs2 = new String[] { realAppId };
            selection = DBHelper.andClauses(selection, selection2);
            selectionArgs = DBHelper.andArguments(selectionArgs, selectionArgs2);
        }
        return mHelper.getReadableDatabase().query(DbObject.TABLE, projection, selection, selectionArgs, null,
                null, sortOrder);
    case OBJS_ID:
        if (!SUPER_APP_ID.equals(realAppId)) {
            return null;
        }
        // objects by database id
        String objId = uri.getLastPathSegment();
        selectionArgs = DBHelper.andArguments(selectionArgs, new String[] { objId });
        selection = DBHelper.andClauses(selection, DbObject._ID + " = ?");
        return mHelper.getReadableDatabase().query(DbObject.TABLE, projection, selection, selectionArgs, null,
                null, sortOrder);
    }

    ///////////////////////////////////////////////////////
    // TODO: Remove code from here down, add to UriMatcher
    List<String> segs = uri.getPathSegments();
    if (match(uri, "feeds", ".+", "head")) {
        boolean isMe = segs.get(1).equals("me");
        String feedName = isMe ? "friend" : segs.get(1);
        String select = isMe ? DBHelper.andClauses(selection, DbObject.CONTACT_ID + "=" + Contact.MY_ID)
                : selection;
        Cursor c = mHelper.queryFeedLatest(realAppId, feedName, projection, select, selectionArgs, sortOrder);
        c.setNotificationUri(resolver, Uri.parse(CONTENT_URI + "/feeds/" + feedName));
        if (isMe)
            c.setNotificationUri(resolver, Uri.parse(CONTENT_URI + "/feeds/me"));
        return c;
    } else if (match(uri, "groups_membership", ".+")) {
        if (!realAppId.equals(SUPER_APP_ID))
            return null;
        Long contactId = Long.valueOf(segs.get(1));
        Cursor c = mHelper.queryGroupsMembership(contactId);
        c.setNotificationUri(resolver, uri);
        return c;
    } else if (match(uri, "group_contacts", ".+")) {
        if (!realAppId.equals(SUPER_APP_ID))
            return null;
        Long group_id = Long.valueOf(segs.get(1));
        Cursor c = mHelper.queryGroupContacts(group_id);
        c.setNotificationUri(resolver, uri);
        return c;
    } else if (match(uri, "local_user", ".+")) {
        // currently available to any local app with a feed id.
        String feed_name = uri.getLastPathSegment();
        Cursor c = mHelper.queryLocalUser(realAppId, feed_name);
        c.setNotificationUri(resolver, uri);
        return c;
    } else if (match(uri, "members", ".+")) {
        // TODO: This is a hack so we can us SocialKit
        // to get the sender of a mass message.
        if (match(uri, "members", "friend")) {
            if (!realAppId.equals(SUPER_APP_ID))
                return null;
            return mHelper.getReadableDatabase().query(Contact.TABLE, projection, selection, selectionArgs,
                    null, null, sortOrder);
        }

        switch (Feed.typeOf(uri)) {
        case FRIEND:
            String personId = Feed.friendIdForFeed(uri);
            if (personId == null) {
                Log.w(TAG, "no  person id in person feed");
                return null;
            }
            selection = DBHelper.andClauses(selection, Contact.PERSON_ID + " = ?");
            selectionArgs = DBHelper.andArguments(selectionArgs, new String[] { personId });
            return mHelper.getReadableDatabase().query(Contact.TABLE, projection, selection, selectionArgs,
                    null, null, sortOrder);
        case GROUP:
        case APP:
            String feedName = segs.get(1);
            if (feedName == null || Feed.FEED_NAME_GLOBAL.equals(feedName)) {
                if (!SUPER_APP_ID.equals(realAppId)) {
                    return null;
                }
            }
            Cursor c = mHelper.queryFeedMembers(projection, selection, selectionArgs, uri, realAppId);
            c.setNotificationUri(resolver, uri);
            return c;
        default:
            return null;
        }
    } else if (match(uri, "groups")) {
        if (!realAppId.equals(SUPER_APP_ID))
            return null;
        Cursor c = mHelper.queryGroups();
        c.setNotificationUri(resolver, Uri.parse(CONTENT_URI + "/groups"));
        return c;
    } else if (match(uri, "contacts") || match(uri, "subscribers") || match(uri, "group_members")) {

        if (!realAppId.equals(SUPER_APP_ID))
            return null;

        Cursor c = mHelper.getReadableDatabase().query(segs.get(0), projection, selection, selectionArgs, null,
                null, sortOrder);
        c.setNotificationUri(resolver, Uri.parse(CONTENT_URI + "/" + segs.get(0)));
        return c;
    } else if (match(uri, "users")) {
        if (!realAppId.equals(SUPER_APP_ID))
            return null;
        Cursor c = mHelper.getReadableDatabase().query(Contact.TABLE, projection, selection, selectionArgs,
                null, null, sortOrder);
        return c;
    } else {
        Log.d(TAG, "Unrecognized query: " + uri);
        return null;
    }
}

From source file:org.matrix.androidsdk.fragments.MatrixMessageListFragment.java

/**
 * upload an image content.//from  ww w  .  j av a  2s  . co m
 * It might be triggered from a media selection : imageUri is used to compute thumbnails.
 * Or, it could have been called to resend an image.
 *
 * @param thumbnailUrl  the thumbnail Url
 * @param anImageUrl      the image Uri
 * @param mediaFilename the mediaFilename
 * @param imageMimeType the image mine type
 */
public void uploadImageContent(ImageMessage imageMessage, final MessageRow aImageRow, final String thumbnailUrl,
        final String anImageUrl, final String mediaFilename, final String imageMimeType) {
    if (null == imageMessage) {
        imageMessage = new ImageMessage();
        imageMessage.url = anImageUrl;
        imageMessage.thumbnailUrl = thumbnailUrl;
        imageMessage.body = mediaFilename;
    }

    String mimeType = null;
    MXEncryptedAttachments.EncryptionResult encryptionResult = null;
    InputStream imageStream = null;
    String url = null;

    try {
        Uri imageUri = Uri.parse(anImageUrl);

        if (null == imageMessage.info) {
            Room.fillImageInfo(getActivity(), imageMessage, imageUri, imageMimeType);
        }

        if ((null != thumbnailUrl) && (null == imageMessage.thumbnailInfo)) {
            Uri thumbUri = Uri.parse(thumbnailUrl);
            Room.fillThumbnailInfo(getActivity(), imageMessage, thumbUri, "image/jpeg");
        }

        String filename;

        if (imageMessage.isThumbnailLocalContent()) {
            url = thumbnailUrl;
            mimeType = "image/jpeg";
            filename = Uri.parse(thumbnailUrl).getPath();
        } else {
            url = anImageUrl;
            mimeType = imageMimeType;
            filename = imageUri.getPath();
        }

        imageStream = new FileInputStream(new File(filename));

        if (mRoom.isEncrypted() && mSession.isCryptoEnabled() && (null != imageStream)) {
            encryptionResult = MXEncryptedAttachments.encryptAttachment(imageStream, mimeType);
            imageStream.close();

            if (null != encryptionResult) {
                imageStream = encryptionResult.mEncryptedStream;
                mimeType = "application/octet-stream";
            } else {
                displayEncryptionAlert();
                return;
            }
        }

        imageMessage.body = imageUri.getLastPathSegment();

    } catch (Exception e) {
        Log.e(LOG_TAG, "uploadImageContent failed with " + e.getMessage());
    }

    if (TextUtils.isEmpty(imageMessage.body)) {
        imageMessage.body = "Image";
    }

    // remove any displayed MessageRow with this URL
    // to avoid duplicate
    final String fMimeType = mimeType;
    final MessageRow imageRow = (null == aImageRow) ? addMessageRow(imageMessage) : aImageRow;
    final ImageMessage fImageMessage = imageMessage;
    imageRow.getEvent().mSentState = Event.SentState.SENDING;

    final MXEncryptedAttachments.EncryptionResult fEncryptionResult = encryptionResult;

    getSession().getMediasCache().uploadContent(imageStream,
            imageMessage.isThumbnailLocalContent() ? ("thumb" + imageMessage.body) : imageMessage.body,
            mimeType, url, new MXMediaUploadListener() {
                @Override
                public void onUploadStart(String uploadId) {
                    getUiHandler().post(new Runnable() {
                        @Override
                        public void run() {
                            onMessageSendingSucceeded(imageRow.getEvent());
                            mAdapter.notifyDataSetChanged();
                        }
                    });
                }

                @Override
                public void onUploadCancel(String uploadId) {
                    getUiHandler().post(new Runnable() {
                        @Override
                        public void run() {
                            onMessageSendingFailed(imageRow.getEvent());
                        }
                    });
                }

                @Override
                public void onUploadError(final String uploadId, final int serverResponseCode,
                        final String serverErrorMessage) {
                    getUiHandler().post(new Runnable() {
                        @Override
                        public void run() {
                            commonMediaUploadError(serverResponseCode, serverErrorMessage, imageRow);
                        }
                    });
                }

                @Override
                public void onUploadComplete(final String uploadId, final String contentUri) {
                    getUiHandler().post(new Runnable() {
                        @Override
                        public void run() {
                            if (fImageMessage.isThumbnailLocalContent()) {
                                if (null != fEncryptionResult) {
                                    fImageMessage.info.thumbnail_file = fEncryptionResult.mEncryptedFileInfo;
                                    fImageMessage.info.thumbnail_file.url = contentUri;
                                    fImageMessage.thumbnailUrl = null;
                                    getMXMediasCache().saveFileMediaForUrl(contentUri, thumbnailUrl, -1, -1,
                                            "image/jpeg");

                                } else {
                                    fImageMessage.thumbnailUrl = contentUri;
                                    getMXMediasCache().saveFileMediaForUrl(contentUri, thumbnailUrl,
                                            mAdapter.getMaxThumbnailWith(), mAdapter.getMaxThumbnailHeight(),
                                            "image/jpeg");
                                }

                                // update the event content with the new message info
                                imageRow.getEvent().updateContent(JsonUtils.toJson(fImageMessage));

                                // upload the high res picture
                                uploadImageContent(fImageMessage, imageRow, contentUri, anImageUrl,
                                        mediaFilename, fMimeType);
                            } else {
                                // replace the thumbnail and the media contents by the computed one
                                getMXMediasCache().saveFileMediaForUrl(contentUri, anImageUrl,
                                        fImageMessage.getMimeType());

                                if (null != fEncryptionResult) {
                                    fImageMessage.file = fEncryptionResult.mEncryptedFileInfo;
                                    fImageMessage.file.url = contentUri;
                                    fImageMessage.url = null;
                                } else {
                                    fImageMessage.url = contentUri;
                                }

                                // update the event content with the new message info
                                imageRow.getEvent().updateContent(JsonUtils.toJson(fImageMessage));

                                Log.d(LOG_TAG, "Uploaded to " + contentUri);

                                send(imageRow);
                            }
                        }
                    });
                }
            });
}

From source file:com.gelakinetic.mtgfam.FamiliarActivity.java

private boolean processIntent(Intent intent) {
    boolean isDeepLink = false;

    if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
        /* Do a search by name, launched from the quick search */
        String query = intent.getStringExtra(SearchManager.QUERY);
        Bundle args = new Bundle();
        SearchCriteria sc = new SearchCriteria();
        sc.name = query;// w ww  .  j  a  v  a 2 s.c  o m
        args.putSerializable(SearchViewFragment.CRITERIA, sc);
        selectItem(R.string.main_card_search, args, false,
                true); /* Don't clear backstack, do force the intent */

    } else if (Intent.ACTION_VIEW.equals(intent.getAction())) {

        boolean shouldSelectItem = true;

        Uri data = intent.getData();
        Bundle args = new Bundle();
        assert data != null;

        boolean shouldClearFragmentStack = true; /* Clear backstack for deep links */
        if (data.getAuthority().toLowerCase().contains("gatherer.wizards")) {
            SQLiteDatabase database = DatabaseManager.getInstance(this, false).openDatabase(false);
            try {
                String queryParam;
                if ((queryParam = data.getQueryParameter("multiverseid")) != null) {
                    Cursor cursor = CardDbAdapter.fetchCardByMultiverseId(Long.parseLong(queryParam),
                            new String[] { CardDbAdapter.DATABASE_TABLE_CARDS + "." + CardDbAdapter.KEY_ID },
                            database);
                    if (cursor.getCount() != 0) {
                        isDeepLink = true;
                        args.putLongArray(CardViewPagerFragment.CARD_ID_ARRAY,
                                new long[] { cursor.getInt(cursor.getColumnIndex(CardDbAdapter.KEY_ID)) });
                    }
                    cursor.close();
                    if (args.size() == 0) {
                        throw new Exception("Not Found");
                    }
                } else if ((queryParam = data.getQueryParameter("name")) != null) {
                    Cursor cursor = CardDbAdapter.fetchCardByName(queryParam,
                            new String[] { CardDbAdapter.DATABASE_TABLE_CARDS + "." + CardDbAdapter.KEY_ID },
                            true, database);
                    if (cursor.getCount() != 0) {
                        isDeepLink = true;
                        args.putLongArray(CardViewPagerFragment.CARD_ID_ARRAY,
                                new long[] { cursor.getInt(cursor.getColumnIndex(CardDbAdapter.KEY_ID)) });
                    }
                    cursor.close();
                    if (args.size() == 0) {
                        throw new Exception("Not Found");
                    }
                } else {
                    throw new Exception("Not Found");
                }
            } catch (Exception e) {
                /* empty cursor, just return */
                ToastWrapper.makeText(this, R.string.no_results_found, ToastWrapper.LENGTH_LONG).show();
                this.finish();
                shouldSelectItem = false;
            } finally {
                DatabaseManager.getInstance(this, false).closeDatabase(false);
            }
        } else if (data.getAuthority().contains("CardSearchProvider")) {
            /* User clicked a card in the quick search autocomplete, jump right to it */
            args.putLongArray(CardViewPagerFragment.CARD_ID_ARRAY,
                    new long[] { Long.parseLong(data.getLastPathSegment()) });
            shouldClearFragmentStack = false; /* Don't clear backstack for search intents */
        } else {
            /* User clicked a deep link, jump to the card(s) */
            isDeepLink = true;

            SQLiteDatabase database = DatabaseManager.getInstance(this, false).openDatabase(false);
            try {
                Cursor cursor = null;
                boolean screenLaunched = false;
                if (data.getScheme().toLowerCase().equals("card")
                        && data.getAuthority().toLowerCase().equals("multiverseid")) {
                    if (data.getLastPathSegment() == null) {
                        /* Home screen deep link */
                        launchHomeScreen();
                        screenLaunched = true;
                        shouldSelectItem = false;
                    } else {
                        try {
                            /* Don't clear the fragment stack for internal links (thanks Meld cards) */
                            if (data.getPathSegments().contains("internal")) {
                                shouldClearFragmentStack = false;
                            }
                            cursor = CardDbAdapter.fetchCardByMultiverseId(
                                    Long.parseLong(data.getLastPathSegment()),
                                    new String[] {
                                            CardDbAdapter.DATABASE_TABLE_CARDS + "." + CardDbAdapter.KEY_ID },
                                    database);
                        } catch (NumberFormatException e) {
                            cursor = null;
                        }
                    }
                }

                if (cursor != null) {
                    if (cursor.getCount() != 0) {
                        args.putLongArray(CardViewPagerFragment.CARD_ID_ARRAY,
                                new long[] { cursor.getInt(cursor.getColumnIndex(CardDbAdapter.KEY_ID)) });
                    } else {
                        /* empty cursor, just return */
                        ToastWrapper.makeText(this, R.string.no_results_found, ToastWrapper.LENGTH_LONG).show();
                        this.finish();
                        shouldSelectItem = false;
                    }
                    cursor.close();
                } else if (!screenLaunched) {
                    /* null cursor, just return */
                    ToastWrapper.makeText(this, R.string.no_results_found, ToastWrapper.LENGTH_LONG).show();
                    this.finish();
                    shouldSelectItem = false;
                }
            } catch (FamiliarDbException e) {
                e.printStackTrace();
            }
            DatabaseManager.getInstance(this, false).closeDatabase(false);
        }
        args.putInt(CardViewPagerFragment.STARTING_CARD_POSITION, 0);
        if (shouldSelectItem) {
            selectItem(R.string.main_card_search, args, shouldClearFragmentStack, true);
        }
    } else if (ACTION_ROUND_TIMER.equals(intent.getAction())) {
        selectItem(R.string.main_timer, null, true, false);
    } else if (ACTION_CARD_SEARCH.equals(intent.getAction())) {
        selectItem(R.string.main_card_search, null, true, false);
    } else if (ACTION_LIFE.equals(intent.getAction())) {
        selectItem(R.string.main_life_counter, null, true, false);
    } else if (ACTION_DICE.equals(intent.getAction())) {
        selectItem(R.string.main_dice, null, true, false);
    } else if (ACTION_TRADE.equals(intent.getAction())) {
        selectItem(R.string.main_trade, null, true, false);
    } else if (ACTION_MANA.equals(intent.getAction())) {
        selectItem(R.string.main_mana_pool, null, true, false);
    } else if (ACTION_WISH.equals(intent.getAction())) {
        selectItem(R.string.main_wishlist, null, true, false);
    } else if (ACTION_RULES.equals(intent.getAction())) {
        selectItem(R.string.main_rules, null, true, false);
    } else if (ACTION_JUDGE.equals(intent.getAction())) {
        selectItem(R.string.main_judges_corner, null, true, false);
    } else if (ACTION_MOJHOSTO.equals(intent.getAction())) {
        selectItem(R.string.main_mojhosto, null, true, false);
    } else if (ACTION_PROFILE.equals(intent.getAction())) {
        selectItem(R.string.main_profile, null, true, false);
    } else if (ACTION_DECKLIST.equals(intent.getAction())) {
        selectItem(R.string.main_decklist, null, true, false);
    } else if (Intent.ACTION_MAIN.equals(intent.getAction())) {
        /* App launched as regular, show the default fragment if there isn't one already */
        if (getSupportFragmentManager().getFragments() == null) {
            launchHomeScreen();
        }
    } else {
        /* Some unknown intent, just finish */
        finish();
    }

    mDrawerList.setItemChecked(mCurrentFrag, true);
    return isDeepLink;
}

From source file:com.vegnab.vegnab.MainVNActivity.java

void logPurchaseActivity(Purchase p, IabResult result, boolean isConsumed, String notes) {
    Uri uri, purchUri = Uri.withAppendedPath(ContentProvider_VegNab.CONTENT_URI, "purchases");
    ContentResolver rs = getContentResolver();
    ContentValues contentValues = new ContentValues();
    if (p == null) {
        contentValues.put("ProductIdCode", "(purchase object is null)");
        contentValues.put("Type", "null");
        contentValues.put("PurchaseState", -2); // purchase is null
    } else {// w  w  w.  j  a  v  a 2s. c o m
        String sku = p.getSku();
        contentValues.put("ProductIdCode", sku); // also called 'SKU'
        contentValues.put("DevPayload", p.getDeveloperPayload());
        contentValues.put("Type", p.getItemType()); // "inapp" for an in-app product or "subs" for subscriptions.
        contentValues.put("OrderIDCode", p.getOrderId());
        // corresponds to the Google payments order ID
        contentValues.put("PkgName", p.getPackageName());
        contentValues.put("Signature", p.getSignature());
        contentValues.put("Token", p.getToken());
        // uniquely identifies a purchase for a given item and user pair
        contentValues.put("PurchaseState", p.getPurchaseState());
        // standard: 0 (purchased), 1 (canceled), or 2 (refunded). or nonstandard: -1 (initiated), -2 (null)
        SimpleDateFormat dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
        long t = p.getPurchaseTime();
        contentValues.put("PurchaseTime", dateTimeFormat.format(new Date(t)));
        contentValues.put("PurchJSON", p.getOriginalJson());
        try { // inventory object may not exist yet
            if (mInventory.hasDetails(sku)) {
                SkuDetails skuDetails = mInventory.getSkuDetails(sku);
                contentValues.put("Price", skuDetails.getPrice());
                contentValues.put("Description", skuDetails.getDescription());
                contentValues.put("Title", skuDetails.getTitle());
            } else {
                contentValues.putNull("Price");
                contentValues.putNull("Description");
                contentValues.putNull("Title");
            }
        } catch (Exception e) {
            contentValues.putNull("Price");
            contentValues.putNull("Description");
            contentValues.putNull("Title");
        }
    }

    contentValues.put("Consumed", isConsumed ? 1 : 0);
    if (result == null) {
        contentValues.putNull("IABResponse");
        contentValues.putNull("IABMessage");
    } else {
        contentValues.put("IABResponse", result.getResponse());
        contentValues.put("IABMessage", result.getMessage());
    }
    if (notes == null) {
        contentValues.putNull("Notes");
    } else {
        contentValues.put("Notes", notes);
    }
    // create a new record
    uri = rs.insert(purchUri, contentValues);
    mNewPurcRecId = Long.parseLong(uri.getLastPathSegment());
    if (LDebug.ON)
        Log.d(LOG_TAG, "mNewPurcRecId of new record stored in DB: " + mNewPurcRecId);
}

From source file:com.odoo.support.provider.OContentProvider.java

private Cursor createQuery(Uri uri, String[] projection, String selection, String[] selectionArgs,
        String sort) {/*  w ww .j  a  v a2  s .  c  o  m*/
    reInitModel();
    SQLiteQueryBuilder query = new SQLiteQueryBuilder();
    boolean withAlias = (projection.length < model.projection().length);
    StringBuffer joins = new StringBuffer();
    String base_table = model.getTableName();
    String base_alias = base_table + "_base";
    HashMap<String, String> projectionMap = new HashMap<String, String>();
    List<String> mJoinTables = new ArrayList<String>();
    for (String col_name : projection) {
        String col = col_name;
        if (col_name.contains(".")) {
            col = col_name.split("\\.")[0];
        }
        OColumn column = model.getColumn(col);
        String display_col = col;
        if (withAlias) {
            display_col = base_alias + "." + col + " AS " + col;
            boolean many2oneJoin = col_name.contains(".");
            if (column.getRelationType() != null && many2oneJoin) {
                OModel rel_model = model.createInstance(column.getType());
                String table = rel_model.getTableName();
                String alias = table;
                alias = table + "_self";
                table += " AS " + alias;
                if (!mJoinTables.contains(alias)) {
                    mJoinTables.add(alias);
                    joins.append(" JOIN ");
                    joins.append(table);
                    joins.append(" ON ");
                    joins.append(base_alias + "." + column.getName());
                    joins.append(" = ");
                    joins.append(alias + "." + OColumn.ROW_ID);
                    joins.append(" ");
                }
                String rel_col = col;
                String rel_col_name = "";
                if (col_name.contains(".")) {
                    rel_col += "_" + col_name.split("\\.")[1];
                    rel_col_name = col_name.split("\\.")[1];
                }
                projectionMap.put(rel_col, alias + "." + rel_col_name + " AS " + rel_col);
            }
        }
        projectionMap.put(col, display_col);
    }
    StringBuffer tables = new StringBuffer();
    tables.append(base_table + ((withAlias) ? " AS " + base_alias : " "));
    tables.append(joins.toString());
    query.setTables(tables.toString());
    query.setProjectionMap(projectionMap);
    StringBuffer whr = new StringBuffer();
    String where = null;
    if (selection != null && selectionArgs != null) {
        if (withAlias) {
            // Check for and
            Pattern pattern = Pattern.compile(" and | AND ");
            String[] data = pattern.split(selection);
            StringBuffer or_string = new StringBuffer();
            for (String token : data) {
                if (token.contains("OR") || token.contains("or")) {
                    or_string.append(token.trim());
                    or_string.append(" OR ");
                } else {
                    whr.append(base_alias + "." + token.trim());
                    whr.append(" AND ");
                }
            }
            if (whr.length() > 0)
                whr.delete(whr.length() - 5, whr.length());
            // Check for or
            if (or_string.length() > 0) {
                if (whr.length() > 0)
                    whr.append(" AND ");
                pattern = Pattern.compile(" or | OR ");
                data = pattern.split(or_string.toString());
                for (String token : data) {
                    if (!token.contains(base_alias)) {
                        if (token.contains("(")) {
                            whr.append("(");
                            token = token.replaceAll("\\(", "");
                            whr.append(base_alias + "." + token.trim());
                        } else if (token.contains(")")) {
                            token = token.replaceAll("\\)", "");
                            whr.append(base_alias + "." + token.trim());
                            whr.append(")");
                        } else {
                            whr.append(base_alias + "." + token.trim());
                        }
                    } else {
                        whr.append(token.trim());
                    }
                    whr.append(" OR ");
                }
                if (whr.length() > 0)
                    whr.delete(whr.length() - 4, whr.length());
            }
        } else {
            whr.append(selection);
        }
        where = whr.toString();
    }
    Cursor c = null;
    int uriMatch = matcher.match(uri);
    switch (uriMatch) {
    case SINGLE_ROW:
        // Return a single entry, by ID.
        String id = uri.getLastPathSegment();
        query.appendWhere(base_alias + "." + OColumn.ROW_ID + " = " + id);
    case COLLECTION:
        c = query.query(model.getReadableDatabase(), null, where, selectionArgs, null, null, sort);
        return c;
    default:
        throw new UnsupportedOperationException("Unknown uri: " + uri);
    }
}

From source file:edu.cmu.cylab.starslinger.view.HomeActivity.java

private long getOutStreamSizeAndData(Uri uri, String contentType) throws IOException {

    String name = null;/*from   ww  w  .  ja v  a2  s .c  om*/
    try {
        Cursor c = getContentResolver().query(uri, new String[] { MediaColumns.DISPLAY_NAME }, null, null,
                null);
        if (c != null) {
            try {
                if (c.moveToFirst()) {
                    name = c.getString(c.getColumnIndex(MediaColumns.DISPLAY_NAME));
                }
            } finally {
                c.close();
            }
        }
    } catch (IllegalArgumentException e) {
        // column may not exist
    }

    long size = -1;
    try {
        Cursor c = getContentResolver().query(uri, new String[] { MediaColumns.SIZE }, null, null, null);
        if (c != null) {
            try {
                if (c.moveToFirst()) {
                    size = c.getInt(c.getColumnIndex(MediaColumns.SIZE));
                }
            } finally {
                c.close();
            }
        }
    } catch (IllegalArgumentException e) {
        // column may not exist
    }

    String data = null;
    try {
        Cursor c = getContentResolver().query(uri, new String[] { MediaColumns.DATA }, null, null, null);
        if (c != null) {
            try {
                if (c.moveToFirst()) {
                    data = c.getString(c.getColumnIndex(MediaColumns.DATA));
                }
            } finally {
                c.close();
            }
        }
    } catch (IllegalArgumentException e) {
        // column may not exist
    }

    if (name == null) {
        name = uri.getLastPathSegment();
    }

    File f = null;
    if (size <= 0) {
        String uriString = uri.toString();
        if (uriString.startsWith("file://")) {
            MyLog.v(TAG, uriString.substring("file://".length()));
            f = new File(uriString.substring("file://".length()));
            size = f.length();
        } else {
            MyLog.v(TAG, "not a file: " + uriString);
        }
    }

    ContentResolver cr = getContentResolver();
    InputStream is;
    // read file bytes
    try {
        is = cr.openInputStream(uri);
    } catch (FileNotFoundException e) {
        if (!TextUtils.isEmpty(data)) {
            is = new FileInputStream(data);
        } else {
            return -1; // unable to load file at all
        }
    }

    if ((contentType != null) && (contentType.indexOf('*') != -1)) {
        contentType = getContentResolver().getType(uri);
    }

    if (contentType == null) {
        contentType = URLConnection.guessContentTypeFromStream(is);
        if (contentType == null) {
            String extension = SSUtil.getFileExtensionOnly(name);
            contentType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
            if (contentType == null) {
                contentType = SafeSlingerConfig.MIMETYPE_OPEN_ATTACH_DEF;
            }
        }
    }
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    byte[] buf = new byte[4096];
    while (is.read(buf) > -1) {
        baos.write(buf);
    }
    baos.flush();

    final byte[] fileBytes = baos.toByteArray();
    DraftData d = DraftData.INSTANCE;
    d.setFileData(fileBytes);
    d.setFileSize(fileBytes.length);
    d.setFileType(contentType);
    d.setFileName(name);
    if (f != null && f.exists()) {
        d.setFileDir(f.getAbsolutePath());
    } else if (!TextUtils.isEmpty(data)) {
        d.setFileDir(new File(data).getAbsolutePath());
    }
    return d.getFileSize();
}