@Override public ParcelFileDescriptor openDocument( String documentId, String mode, CancellationSignal signal) throws FileNotFoundException { final File file = getFileForDocId(documentId); final File visibleFile = getFileForDocId(documentId, true); final int pfdMode = ParcelFileDescriptor.parseMode(mode); if (pfdMode == ParcelFileDescriptor.MODE_READ_ONLY || visibleFile == null) { return ParcelFileDescriptor.open(file, pfdMode); } else { try { // When finished writing, kick off media scanner return ParcelFileDescriptor.open( file, pfdMode, mHandler, new OnCloseListener() { @Override public void onClose(IOException e) { final Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); intent.setData(Uri.fromFile(visibleFile)); getContext().sendBroadcast(intent); } }); } catch (IOException e) { throw new FileNotFoundException("Failed to open for writing: " + e); } } }
@Override public ParcelFileDescriptor openDocument( final String documentId, final String mode, final CancellationSignal signal) throws FileNotFoundException { File file = new File(documentId); final boolean isWrite = (mode.indexOf('w') != -1); if (isWrite) { return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_WRITE); } else { return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY); } }
private ParcelFileDescriptor getTempStoreFd() { String fileName = getScrapPath(getContext()); /// M: Code analyze 002, fix bug unknown, If the filename is null,it // should run null @{ if (fileName == null) { return null; } /// @} ParcelFileDescriptor pfd = null; try { File file = new File(fileName); // make sure the path is valid and directories created for this file. File parentFile = file.getParentFile(); if (!parentFile.exists() && !parentFile.mkdirs()) { Log.e(TAG, "[TempFileProvider] tempStoreFd: " + parentFile.getPath() + "does not exist!"); return null; } pfd = ParcelFileDescriptor.open( file, ParcelFileDescriptor.MODE_READ_WRITE | android.os.ParcelFileDescriptor.MODE_CREATE); } catch (Exception ex) { Log.e(TAG, "getTempStoreFd: error creating pfd for " + fileName, ex); } return pfd; }
private FileOutputStream zznR() { if (zzabc == null) { throw new IllegalStateException("setTempDir() must be called before writing this object to a parcel"); } File file; FileOutputStream fileoutputstream; try { file = File.createTempFile("teleporter", ".tmp", zzabc); } catch (IOException ioexception) { throw new IllegalStateException("Could not create temporary file", ioexception); } try { fileoutputstream = new FileOutputStream(file); zzEo = ParcelFileDescriptor.open(file, 0x10000000); } catch (FileNotFoundException filenotfoundexception) { throw new IllegalStateException("Temporary file is somehow already deleted"); } file.delete(); return fileoutputstream; }
@Override public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException { String LOG_TAG = CLASS_NAME + " "; Log.d(LOG_TAG, "Called with uri: '" + uri + "'." + uri.getLastPathSegment()); // Check incoming Uri against the matcher switch (uriMatcher.match(uri)) { // If it returns 1 - then it matches the Uri defined in onCreate case 1: // The desired file name is specified by the last segment of the // path // // Take this and build the path to the file String fileLocation = getContext().getCacheDir() + File.separator + uri.getLastPathSegment(); // Create & return a ParcelFileDescriptor pointing to the file // Note: I don't care what mode they ask for - they're only getting // read only ParcelFileDescriptor pfd = ParcelFileDescriptor.open(new File(fileLocation), ParcelFileDescriptor.MODE_READ_ONLY); return pfd; // Otherwise unrecognised Uri default: Log.v(LOG_TAG, "Unsupported uri: '" + uri + "'."); throw new FileNotFoundException("Unsupported uri: " + uri.toString()); } }
@Override public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException { List<String> pseg = uri.getPathSegments(); if (pseg.size() < 2) { throw new FileNotFoundException("invalid uri error " + uri); } File path = getFileFromUri(uri); Log.v("openFile(uri=" + uri + ", file=" + path + ")"); int imode = 0; if (mode.contains("w")) { imode |= ParcelFileDescriptor.MODE_WRITE_ONLY; if (!path.exists()) { try { path.createNewFile(); } catch (IOException e) { e.printStackTrace(); throw new FileNotFoundException("Error creating " + uri); } } else { throw new FileNotFoundException("File with name " + path + " already exists"); } } else if (mode.contains("r")) { if (!path.exists()) { throw new FileNotFoundException("File not found " + uri); } } if (mode.contains("r")) imode |= ParcelFileDescriptor.MODE_READ_ONLY; if (mode.contains("+")) imode |= ParcelFileDescriptor.MODE_APPEND; return ParcelFileDescriptor.open(path, imode); }
/* to save images (or maybe only thumbnails */ @Override public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException { File file = new File(this.getContext().getFilesDir(), uri.getPath()); ParcelFileDescriptor parcel = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY); return parcel; }
// Provide access to the private file as read only @Override public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException { if (!mode.equals("r")) { throw new SecurityException("Only read access is allowed"); } return ParcelFileDescriptor.open(generatePictureFile(uri), ParcelFileDescriptor.MODE_READ_ONLY); }
/** * Full size bitmap. * * @param maxNumberOfPixels the max number of pixels * @param rotateAsNeeded the rotate as needed * @return the bitmap */ public Bitmap fullSizeBitmap(int maxNumberOfPixels, boolean rotateAsNeeded) { Logger.v(TAG, "fullSizeBitmap entry"); int minSideLength = getProperWindowSize(); String path = mUri.getPath(); ParcelFileDescriptor pfdInput = null; try { pfdInput = ParcelFileDescriptor.open(new File(path), ParcelFileDescriptor.MODE_READ_ONLY); } catch (FileNotFoundException e) { Logger.e(TAG, "got exception decoding bitmap "); e.printStackTrace(); } Bitmap bitmap = null; bitmap = makeBitmap(minSideLength, maxNumberOfPixels, null, null, pfdInput, null); if (bitmap != null && rotateAsNeeded) { Bitmap rotatedBitmap = rotate(bitmap, getDegreesRotated()); if (rotatedBitmap != null && rotatedBitmap != bitmap) { Logger.v(TAG, "fullSizeBitmap rotate"); bitmap.recycle(); bitmap = rotatedBitmap; } else { Logger.d(TAG, "fullSizeBitmap no need to roate"); } } Logger.v(TAG, "fullSizeBitmap exit"); return bitmap; }
/** * Open an attachment file. There are two "modes" - "raw", which returns an actual file, and * "thumbnail", which attempts to generate a thumbnail image. * * <p>Thumbnails are cached for easy space recovery and cleanup. * * <p>TODO: The thumbnail mode returns null for its failure cases, instead of throwing * FileNotFoundException, and should be fixed for consistency. * * @throws FileNotFoundException */ @Override public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException { List<String> segments = uri.getPathSegments(); String accountId = segments.get(0); String id = segments.get(1); String format = segments.get(2); if (FORMAT_THUMBNAIL.equals(format)) { int width = Integer.parseInt(segments.get(3)); int height = Integer.parseInt(segments.get(4)); String filename = "thmb_" + accountId + "_" + id; File dir = getContext().getCacheDir(); File file = new File(dir, filename); if (!file.exists()) { Uri attachmentUri = getAttachmentUri(Long.parseLong(accountId), Long.parseLong(id)); Cursor c = query(attachmentUri, new String[] {AttachmentProviderColumns.DATA}, null, null, null); if (c != null) { try { if (c.moveToFirst()) { attachmentUri = Uri.parse(c.getString(0)); } else { return null; } } finally { c.close(); } } String type = getContext().getContentResolver().getType(attachmentUri); try { InputStream in = getContext().getContentResolver().openInputStream(attachmentUri); Bitmap thumbnail = createThumbnail(type, in); thumbnail = Bitmap.createScaledBitmap(thumbnail, width, height, true); FileOutputStream out = new FileOutputStream(file); thumbnail.compress(Bitmap.CompressFormat.PNG, 100, out); out.close(); in.close(); } catch (IOException ioe) { return null; } } return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY); } else { return ParcelFileDescriptor.open( new File(getContext().getDatabasePath(accountId + ".db_att"), id), ParcelFileDescriptor.MODE_READ_ONLY); } }
/** * Set photo to be published * * @param file */ public Builder setImage(File file) { try { mParcelable = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY); } catch (FileNotFoundException e) { Logger.logError(Photo.class, "Failed to create photo from file", e); } return this; }
/** * Constructor. * * @author Ian Copland * @param in_file - The file which this descriptor should point to. * @param in_mode - The file mode. * @param in_listener - The listener which should be notified of the closed event. * @throws FileNotFoundException - Thrown if the file cannot be found. Note that this is the only * case in which the closed event will not be fired. */ public ListenableParcelFileDescriptor(File in_file, int in_mode, OnClose in_listener) throws FileNotFoundException { super(ParcelFileDescriptor.open(in_file, in_mode)); assert (in_listener != null) : "Cannot create a ListenableParcelFileDescriptor without a listener."; m_listener = in_listener; }
@Override public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException { int fileIndex = sUriMatcher.match(uri); if (fileIndex != -1 && sPaths[fileIndex] != null) { return ParcelFileDescriptor.open( new File(sPaths[fileIndex]), ParcelFileDescriptor.MODE_READ_ONLY); } return super.openFile(uri, mode); }
@Nullable @Override public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException { Log.d(this, "openFile:" + uri.getLastPathSegment()); File dir = new File(Environment.getExternalStorageDirectory().getAbsoluteFile(), "/radar"); return ParcelFileDescriptor.open( new File(dir, uri.getLastPathSegment()), ParcelFileDescriptor.MODE_READ_ONLY); }
@Override public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException { File f = new File(getContext().getFilesDir(), uri.getPath()); if (f.exists()) { return (ParcelFileDescriptor.open(f, ParcelFileDescriptor.MODE_READ_ONLY)); } throw new FileNotFoundException(uri.getPath()); }
// Check: openPipeHelper in // https://github.com/android/platform_frameworks_base/blob/master/core/java/android/content/ContentProvider.java // for example to use IOCipher @Override public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException { return ParcelFileDescriptor.open( new java.io.File( getNonVirtualFileSystemInternalDir(), SocialReader.CONTENT_BUNDLE_FILE_PREFIX + uri.getLastPathSegment() + "." + SocialReader.CONTENT_SHARING_EXTENSION), ParcelFileDescriptor.MODE_READ_ONLY); }
@Override public AssetFileDescriptor openDocumentThumbnail( final String documentId, final Point sizeHint, final CancellationSignal signal) throws FileNotFoundException { // Assume documentId points to an image file. Build a thumbnail no // larger than twice the sizeHint BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(documentId, options); final int targetHeight = 2 * sizeHint.y; final int targetWidth = 2 * sizeHint.x; final int height = options.outHeight; final int width = options.outWidth; options.inSampleSize = 1; if (height > targetHeight || width > targetWidth) { final int halfHeight = height / 2; final int halfWidth = width / 2; // Calculate the largest inSampleSize value that is a power of 2 and // keeps both // height and width larger than the requested height and width. while ((halfHeight / options.inSampleSize) > targetHeight || (halfWidth / options.inSampleSize) > targetWidth) { options.inSampleSize *= 2; } } options.inJustDecodeBounds = false; Bitmap bitmap = BitmapFactory.decodeFile(documentId, options); // Write out the thumbnail to a temporary file File tempFile = null; FileOutputStream out = null; try { tempFile = File.createTempFile("thumbnail", null, getContext().getCacheDir()); out = new FileOutputStream(tempFile); bitmap.compress(Bitmap.CompressFormat.PNG, 90, out); } catch (IOException e) { Log.e(LocalStorageProvider.class.getSimpleName(), "Error writing thumbnail", e); return null; } finally { if (out != null) try { out.close(); } catch (IOException e) { Log.e(LocalStorageProvider.class.getSimpleName(), "Error closing thumbnail", e); } } // It appears the Storage Framework UI caches these results quite // aggressively so there is little reason to // write your own caching layer beyond what you need to return a single // AssetFileDescriptor return new AssetFileDescriptor( ParcelFileDescriptor.open(tempFile, ParcelFileDescriptor.MODE_READ_ONLY), 0, AssetFileDescriptor.UNKNOWN_LENGTH); }
private ParcelFileDescriptor getPFD() { try { if (mUri.getScheme().equals("file")) { String path = mUri.getPath(); return ParcelFileDescriptor.open(new File(path), ParcelFileDescriptor.MODE_READ_ONLY); } else { return mContentResolver.openFileDescriptor(mUri, "r"); } } catch (FileNotFoundException ex) { return null; } }
public static ParcelFileDescriptor openParcelFd(String path) { forceFile(path); try { Logger.D(TAG, "Opening file from file system: " + absolutePath(path)); File file = new File(path); return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY); } catch (FileNotFoundException e) { Logger.E(TAG, "Can not open ParcelFileDescriptor" + e.getMessage()); return null; } }
@NonNull private ParcelFileDescriptor safeOpenFileHelper(@NonNull Uri uri, @NonNull String mode) throws FileNotFoundException { Cursor c = query(uri, new String[] {"_data"}, null, null, null); int count = (c != null) ? c.getCount() : 0; if (count != 1) { // If there is not exactly one result, throw an appropriate // exception. if (c != null) { c.close(); } if (count == 0) { throw new FileNotFoundException("No entry for " + uri); } throw new FileNotFoundException("Multiple items at " + uri); } c.moveToFirst(); int i = c.getColumnIndex("_data"); String path = (i >= 0 ? c.getString(i) : null); c.close(); if (path == null) { throw new FileNotFoundException("Column _data not found."); } File filePath = new File(path); try { // The MmsProvider shouldn't open a file that isn't MMS data, so we verify that the // _data path actually points to MMS data. That safeguards ourselves from callers who // inserted or updated a URI (more specifically the _data column) with disallowed paths. // TODO(afurtado): provide a more robust mechanism to avoid disallowed _data paths to // be inserted/updated in the first place, including via SQL injection. if (!filePath .getCanonicalPath() .startsWith(getContext().getDir(PARTS_DIR_NAME, 0).getCanonicalPath())) { Log.e( TAG, "openFile: path " + filePath.getCanonicalPath() + " does not start with " + getContext().getDir(PARTS_DIR_NAME, 0).getCanonicalPath()); // Don't care return value return null; } } catch (IOException e) { Log.e(TAG, "openFile: create path failed " + e, e); return null; } int modeBits = ParcelFileDescriptor.parseMode(mode); return ParcelFileDescriptor.open(filePath, modeBits); }
@TargetApi(Build.VERSION_CODES.LOLLIPOP) private static boolean weOwnFileLollipop(Uri uri) { try { File file = new File(uri.getPath()); FileDescriptor fd = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY).getFileDescriptor(); StructStat st = Os.fstat(fd); return st.st_uid == android.os.Process.myUid(); } catch (FileNotFoundException e) { return false; } catch (Exception e) { return true; } }
@Override public ParcelFileDescriptor openFile(final Uri uri, final String mode) throws FileNotFoundException { try { this.setApplicationActivated(); Log.d(TAG, "Writing filters..."); final File filterFile = Engine.getOrCreateCachedFilterFile(getContext()); Log.d(TAG, "Delivering filters..."); return ParcelFileDescriptor.open(filterFile, ParcelFileDescriptor.MODE_READ_ONLY); } catch (IOException e) { Log.e(TAG, "File creation failed: " + e.getMessage(), e); return null; } }
@Override public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException { if (!"r".equals(mode)) { throw new FileNotFoundException( "The SLIC FileContentProvider does not support mode \"" + mode + "\" for " + uri); } String rootOmPath = System.getProperty("root.openmeap.path"); String filename = uri.toString().substring(BASE_URI_LEN); String relFN = filename.replace(rootOmPath, ""); filename = rootOmPath + FILE_SEP + getInternalStorageFileName(relFN); File file = new File(filename); ParcelFileDescriptor toRet = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY); return toRet; }
public Bitmap getMusicImg(String mAlbumArtURI) { File file = new File(mAlbumArtURI); Bitmap bt = null; try { ParcelFileDescriptor fd = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY); bt = BitmapFactory.decodeFileDescriptor(fd.getFileDescriptor(), null, null); if (bt == null) { } else { } } catch (FileNotFoundException e) { e.printStackTrace(); } return bt; }
/** Remotely opens a file */ @Override public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException { if (Constants.LOGVV) { logVerboseOpenFileInfo(uri, mode); } Cursor cursor = query(uri, new String[] {"_data"}, null, null, null); String path; try { int count = (cursor != null) ? cursor.getCount() : 0; if (count != 1) { // If there is not exactly one result, throw an appropriate // exception. if (count == 0) { throw new FileNotFoundException("No entry for " + uri); } throw new FileNotFoundException("Multiple items at " + uri); } cursor.moveToFirst(); path = cursor.getString(0); } finally { if (cursor != null) { cursor.close(); } } if (path == null) { throw new FileNotFoundException("No filename found."); } if (!Helpers.isFilenameValid(path)) { throw new FileNotFoundException("Invalid filename."); } if (!"r".equals(mode)) { throw new FileNotFoundException("Bad mode for " + uri + ": " + mode); } ParcelFileDescriptor ret = ParcelFileDescriptor.open(new File(path), ParcelFileDescriptor.MODE_READ_ONLY); if (ret == null) { if (Constants.LOGV) { Log.v(Constants.TAG, "couldn't open file"); } throw new FileNotFoundException("couldn't open file"); } return ret; }
@Override public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException { File file; List<String> segments = uri.getPathSegments(); String accountUuid = segments.get(0); String attachmentId = segments.get(1); String format = segments.get(2); if (FORMAT_THUMBNAIL.equals(format)) { int width = Integer.parseInt(segments.get(3)); int height = Integer.parseInt(segments.get(4)); file = getThumbnailFile(getContext(), accountUuid, attachmentId); if (!file.exists()) { String type = getType(accountUuid, attachmentId, FORMAT_VIEW, null); try { FileInputStream in = new FileInputStream(getFile(accountUuid, attachmentId)); try { Bitmap thumbnail = createThumbnail(type, in); if (thumbnail != null) { thumbnail = Bitmap.createScaledBitmap(thumbnail, width, height, true); FileOutputStream out = new FileOutputStream(file); try { thumbnail.compress(Bitmap.CompressFormat.PNG, 100, out); } finally { out.close(); } } } finally { try { in.close(); } catch (Throwable ignore) { /* ignore */ } } } catch (IOException ioe) { return null; } } } else { file = getFile(accountUuid, attachmentId); } return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY); }
private int openOrDownloadInner(JobContext jc) { String scheme = mUri.getScheme(); if (ContentResolver.SCHEME_CONTENT.equals(scheme) || ContentResolver.SCHEME_ANDROID_RESOURCE.equals(scheme) || ContentResolver.SCHEME_FILE.equals(scheme)) { try { if (MIME_TYPE_JPEG.equalsIgnoreCase(mContentType)) { InputStream is = mApplication.getContentResolver().openInputStream(mUri); mRotation = Exif.getOrientation(is); Utils.closeSilently(is); } mFileDescriptor = mApplication.getContentResolver().openFileDescriptor(mUri, "r"); if (jc.isCancelled()) return STATE_INIT; return STATE_DOWNLOADED; } catch (FileNotFoundException e) { Log.w(TAG, "fail to open: " + mUri, e); return STATE_ERROR; } } else { try { URL url = new URI(mUri.toString()).toURL(); mCacheEntry = mApplication.getDownloadCache().download(jc, url); if (jc.isCancelled()) return STATE_INIT; if (mCacheEntry == null) { Log.w(TAG, "download failed " + url); return STATE_ERROR; } if (MIME_TYPE_JPEG.equalsIgnoreCase(mContentType)) { InputStream is = new FileInputStream(mCacheEntry.cacheFile); mRotation = Exif.getOrientation(is); Utils.closeSilently(is); } mFileDescriptor = ParcelFileDescriptor.open(mCacheEntry.cacheFile, ParcelFileDescriptor.MODE_READ_ONLY); return STATE_DOWNLOADED; } catch (Throwable t) { Log.w(TAG, "download error", t); return STATE_ERROR; } } }
@SmallTest @Feature({"Cronet"}) public void testFileDescriptorProvider() throws Exception { ParcelFileDescriptor descriptor = ParcelFileDescriptor.open(mFile, ParcelFileDescriptor.MODE_READ_ONLY); assertTrue(descriptor.getFileDescriptor().valid()); TestUrlRequestCallback callback = new TestUrlRequestCallback(); UrlRequest.Builder builder = new UrlRequest.Builder( NativeTestServer.getRedirectToEchoBody(), callback, callback.getExecutor(), mTestFramework.mCronetEngine); UploadDataProvider dataProvider = UploadDataProviders.create(descriptor); builder.setUploadDataProvider(dataProvider, callback.getExecutor()); builder.addHeader("Content-Type", "useless/string"); builder.build().start(); callback.blockForDone(); assertEquals(200, callback.mResponseInfo.getHttpStatusCode()); assertEquals(LOREM, callback.mResponseAsString); }
@Override public ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode) throws FileNotFoundException { File file = new File(uri.getPath()); return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY); }
public ParcelFileDescriptor openFile(Uri uri, String s) { return ParcelFileDescriptor.open(mStrategy.getFileForUri(uri), modeToMode(s)); }