@Override public void writeToParcel(Parcel out, int flags) { if (mRelroFd >= 0) { out.writeLong(mLoadAddress); out.writeLong(mLoadSize); out.writeLong(mRelroStart); out.writeLong(mRelroSize); try { ParcelFileDescriptor fd = ParcelFileDescriptor.fromFd(mRelroFd); fd.writeToParcel(out, 0); fd.close(); } catch (java.io.IOException e) { Log.e(TAG, "Can't write LibInfo file descriptor to parcel", e); } } }
private ParcelFileDescriptor openReadInternal(String name) throws IOException { assertPreparedAndNotSealed("openRead"); try { if (!FileUtils.isValidExtFilename(name)) { throw new IllegalArgumentException("Invalid name: " + name); } final File target = new File(resolveStageDir(), name); final FileDescriptor targetFd = Os.open(target.getAbsolutePath(), O_RDONLY, 0); return ParcelFileDescriptor.dup(targetFd); } catch (ErrnoException e) { throw new IOException(e); } }
@Rpc(description = "Compute MD5 hash on a content URI. Return the MD5 has has a hex string.") public String fileMd5Hash(String uri) throws IOException, NoSuchAlgorithmException { Uri uri_ = Uri.parse(uri); ParcelFileDescriptor pfd = mContext.getContentResolver().openFileDescriptor(uri_, "r"); MessageDigest md = MessageDigest.getInstance("MD5"); int length = (int) pfd.getStatSize(); byte[] buf = new byte[length]; ParcelFileDescriptor.AutoCloseInputStream stream = new ParcelFileDescriptor.AutoCloseInputStream(pfd); DigestInputStream dis = new DigestInputStream(stream, md); try { dis.read(buf, 0, length); return Utils.bytesToHexString(md.digest()); } finally { dis.close(); stream.close(); } }
protected AssetFileDescriptor openVideoThumbnailCleared(long id, CancellationSignal signal) throws FileNotFoundException { final ContentResolver resolver = getContext().getContentResolver(); Cursor cursor = null; try { cursor = resolver.query(Video.Thumbnails.EXTERNAL_CONTENT_URI, VideoThumbnailQuery.PROJECTION, Video.Thumbnails.VIDEO_ID + "=" + id, null, null); if (cursor.moveToFirst()) { final String data = cursor.getString(VideoThumbnailQuery._DATA); return new AssetFileDescriptor(ParcelFileDescriptor.open( new File(data), ParcelFileDescriptor.MODE_READ_ONLY), 0, AssetFileDescriptor.UNKNOWN_LENGTH); } } finally { IoUtils.closeQuietly(cursor); } return null; }
public FileDescriptorFactory() { super(new FileOpener<ParcelFileDescriptor>() { @Override public ParcelFileDescriptor open(File file) throws FileNotFoundException { return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY); } @Override public void close(ParcelFileDescriptor parcelFileDescriptor) throws IOException { parcelFileDescriptor.close(); } @Override public Class<ParcelFileDescriptor> getDataClass() { return ParcelFileDescriptor.class; } }); }
/** * Copied from ContentResolver.java */ private static int modeToMode(String mode) { int modeBits; if ("r".equals(mode)) { modeBits = ParcelFileDescriptor.MODE_READ_ONLY; } else if ("w".equals(mode) || "wt".equals(mode)) { modeBits = ParcelFileDescriptor.MODE_WRITE_ONLY | ParcelFileDescriptor.MODE_CREATE | ParcelFileDescriptor.MODE_TRUNCATE; } else if ("wa".equals(mode)) { modeBits = ParcelFileDescriptor.MODE_WRITE_ONLY | ParcelFileDescriptor.MODE_CREATE | ParcelFileDescriptor.MODE_APPEND; } else if ("rw".equals(mode)) { modeBits = ParcelFileDescriptor.MODE_READ_WRITE | ParcelFileDescriptor.MODE_CREATE; } else if ("rwt".equals(mode)) { modeBits = ParcelFileDescriptor.MODE_READ_WRITE | ParcelFileDescriptor.MODE_CREATE | ParcelFileDescriptor.MODE_TRUNCATE; } else { throw new IllegalArgumentException("Invalid mode: " + mode); } return modeBits; }
protected ParcelFileDescriptor openImageThumbnailCleared(long id, CancellationSignal signal) throws FileNotFoundException { final ContentResolver resolver = getContext().getContentResolver(); Cursor cursor = null; try { cursor = resolver.query(Images.Thumbnails.EXTERNAL_CONTENT_URI, ImageThumbnailQuery.PROJECTION, Images.Thumbnails.IMAGE_ID + "=" + id, null, null); if (cursor.moveToFirst()) { final String data = cursor.getString(ImageThumbnailQuery._DATA); return ParcelFileDescriptor.open( new File(data), ParcelFileDescriptor.MODE_READ_ONLY); } } finally { IoUtils.closeQuietly(cursor); } return null; }
@Test public void testLoadResource_returnsFileDescriptor() throws Exception { Context context = RuntimeEnvironment.application; Uri uri = Uri.parse("file://nothing"); ContentResolver contentResolver = context.getContentResolver(); ContentResolverShadow shadow = Shadow.extract(contentResolver); AssetFileDescriptor assetFileDescriptor = mock(AssetFileDescriptor.class); ParcelFileDescriptor parcelFileDescriptor = mock(ParcelFileDescriptor.class); when(assetFileDescriptor.getParcelFileDescriptor()).thenReturn(parcelFileDescriptor); shadow.registerFileDescriptor(uri, assetFileDescriptor); FileDescriptorLocalUriFetcher fetcher = new FileDescriptorLocalUriFetcher(context.getContentResolver(), uri); fetcher.loadData(Priority.NORMAL, callback); verify(callback).onDataReady(eq(parcelFileDescriptor)); }
@Override public android.os.ParcelFileDescriptor openFile(android.net.Uri uri, java.lang.String mode) throws java.io.FileNotFoundException { Pair<UUID, String> callIdAndAttachmentName = parseCallIdAndAttachmentName(uri); if (callIdAndAttachmentName == null) { throw new FileNotFoundException(); } try { File file = NativeAppCallAttachmentStore.openAttachment( callIdAndAttachmentName.first, callIdAndAttachmentName.second); return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY); } catch (FileNotFoundException exception) { Log.e(TAG, "Got unexpected exception:" + exception); throw exception; } }
private void initialize() throws FileNotFoundException { ParcelFileDescriptor fileDescriptor = null; try { if (Utility.isFileUri(videoUri)) { fileDescriptor = ParcelFileDescriptor.open( new File(videoUri.getPath()), ParcelFileDescriptor.MODE_READ_ONLY); videoSize = fileDescriptor.getStatSize(); videoStream = new ParcelFileDescriptor.AutoCloseInputStream(fileDescriptor); } else if (Utility.isContentUri(videoUri)) { videoSize = Utility.getContentSize(videoUri); videoStream = FacebookSdk .getApplicationContext() .getContentResolver() .openInputStream(videoUri); } else { throw new FacebookException("Uri must be a content:// or file:// uri"); } } catch (FileNotFoundException e) { Utility.closeQuietly(videoStream); throw e; } }
@Override public ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode) throws FileNotFoundException { final MasterSecret masterSecret = KeyCachingService.getMasterSecret(getContext()); Log.w(TAG, "openFile() called!"); if (masterSecret == null) { Log.w(TAG, "masterSecret was null, abandoning."); return null; } switch (uriMatcher.match(uri)) { case SINGLE_ROW: Log.w(TAG, "Parting out a single row..."); try { final PartUriParser partUri = new PartUriParser(uri); return getParcelStreamForAttachment(masterSecret, partUri.getPartId()); } catch (IOException ioe) { Log.w(TAG, ioe); throw new FileNotFoundException("Error opening file"); } } throw new FileNotFoundException("Request for bad part."); }
@Override public ParcelFileDescriptor openDocument(String docId, String mode, CancellationSignal signal) throws FileNotFoundException { if (!"r".equals(mode)) { throw new IllegalArgumentException("Media is read-only"); } final Uri target = getUriForDocumentId(docId); // Delegate to real provider final long token = Binder.clearCallingIdentity(); try { return getContext().getContentResolver().openFileDescriptor(target, mode); } finally { Binder.restoreCallingIdentity(token); } }
public static int parseMode(String mode) { final int modeBits; if ("r".equals(mode)) { modeBits = ParcelFileDescriptor.MODE_READ_ONLY; } else if ("w".equals(mode) || "wt".equals(mode)) { modeBits = ParcelFileDescriptor.MODE_WRITE_ONLY | ParcelFileDescriptor.MODE_CREATE | ParcelFileDescriptor.MODE_TRUNCATE; } else if ("wa".equals(mode)) { modeBits = ParcelFileDescriptor.MODE_WRITE_ONLY | ParcelFileDescriptor.MODE_CREATE | ParcelFileDescriptor.MODE_APPEND; } else if ("rw".equals(mode)) { modeBits = ParcelFileDescriptor.MODE_READ_WRITE | ParcelFileDescriptor.MODE_CREATE; } else if ("rwt".equals(mode)) { modeBits = ParcelFileDescriptor.MODE_READ_WRITE | ParcelFileDescriptor.MODE_CREATE | ParcelFileDescriptor.MODE_TRUNCATE; } else { throw new IllegalArgumentException("Bad mode '" + mode + "'"); } return modeBits; }
@Override public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException { initIfNecessary(); AssetFileDescriptor af = openAssetFile(uri, mode); if ( null != af ) { return af.getParcelFileDescriptor(); } return null; }
private void openRenderer( ) { // In this sample, we read a PDF from the assets directory. File f = new File(uri.getPath()); try { mFileDescriptor = ParcelFileDescriptor.open(f, ParcelFileDescriptor.MODE_READ_ONLY); mPdfRenderer = new PdfRenderer(mFileDescriptor); cnt=mPdfRenderer.getPageCount(); } catch (Exception e) { log.e(e); } }
@Override public ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode) throws FileNotFoundException { List<String> segments = uri.getPathSegments(); String accountUuid = segments.get(0); String attachmentId = segments.get(1); ParcelFileDescriptor parcelFileDescriptor = openAttachment(accountUuid, attachmentId); if (parcelFileDescriptor == null) { throw new FileNotFoundException("Attachment missing or cannot be opened!"); } return parcelFileDescriptor; }
/** * Return album artwork given the id * if nothing is found, we try a downloaded one * * @param context * @param album_id * @return */ public static Bitmap getArtworkQuick_Base1(Context context, long album_id) { if (album_id != -1) { ContentResolver res = context.getContentResolver(); Uri uri = ContentUris.withAppendedId(MusicUtils.sArtworkUri, album_id); if (uri != null) { // ParcelFileDescriptor fd = null; try { ParcelFileDescriptor fd = res.openFileDescriptor(uri, "r"); BitmapFactory.Options o2 = new BitmapFactory.Options(); o2.inSampleSize = 2; o2.inDither = false; o2.inPreferredConfig = Bitmap.Config.RGB_565; Bitmap b = BitmapFactory.decodeFileDescriptor( fd.getFileDescriptor(), null, o2); if (b != null) { return b; } else { b = getArtworkDownloadedResized(context, album_id); if (b != null) { return b; } else { return null; } } } catch (FileNotFoundException e) { return null; } } } return null; }
private int transferIncrementalRestoreData(String packageName, ParcelFileDescriptor outputFileDescriptor) throws IOException, InvalidAlgorithmParameterException, InvalidKeyException { ParcelFileDescriptor inputFileDescriptor = buildInputFileDescriptor(); ZipInputStream inputStream = buildInputStream(inputFileDescriptor); BackupDataOutput backupDataOutput = new BackupDataOutput(outputFileDescriptor.getFileDescriptor()); Optional<ZipEntry> zipEntryOptional = seekToEntry(inputStream, configuration.getIncrementalBackupDirectory() + packageName); while (zipEntryOptional.isPresent()) { String fileName = new File(zipEntryOptional.get().getName()).getName(); String blobKey = new String(Base64.decode(fileName, Base64.DEFAULT)); byte[] backupData = Streams.readFullyNoClose(inputStream); backupDataOutput.writeEntityHeader(blobKey, backupData.length); backupDataOutput.writeEntityData(backupData, backupData.length); inputStream.closeEntry(); zipEntryOptional = seekToEntry(inputStream, configuration.getIncrementalBackupDirectory() + packageName); } IoUtils.closeQuietly(inputFileDescriptor); IoUtils.closeQuietly(outputFileDescriptor); return TRANSPORT_OK; }
public static <T> DataSinkTransferThread<T> asyncPipeToDataSink( SMimeDataSink<T> dataSink, ParcelFileDescriptor output) throws IOException { InputStream inputStream = new BufferedInputStream(new AutoCloseInputStream(output)); DataSinkTransferThread<T> dataSinkTransferThread = new DataSinkTransferThread<T>(dataSink, inputStream); dataSinkTransferThread.start(); return dataSinkTransferThread; }
public final int startActivity(IApplicationThread caller, String callingPackage, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, String profileFile, ParcelFileDescriptor profileFd, Bundle options) { return PreventRunningUtils.onStartActivity( startActivity$Pr(caller, callingPackage, intent, resolvedType, resultTo, resultWho, requestCode, startFlags, profileFile, profileFd, options), caller, callingPackage, intent); }
public static ParcelFileDescriptor pipeFrom(InputStream inputStream) throws IOException { ParcelFileDescriptor[] pipe = ParcelFileDescriptor.createPipe(); ParcelFileDescriptor readSide = pipe[0]; ParcelFileDescriptor writeSide = pipe[1]; new TransferThread(inputStream, new ParcelFileDescriptor.AutoCloseOutputStream(writeSide)) .start(); return readSide; }
public static TransferThread pipeTo(OutputStream outputStream, ParcelFileDescriptor output) throws IOException { AutoCloseInputStream InputStream = new AutoCloseInputStream(output); TransferThread t = new TransferThread(InputStream, outputStream); t.start(); return t; }
private ParcelFileDescriptor openWriteInternal(String name, long offsetBytes, long lengthBytes) throws IOException { // Quick sanity check of state, and allocate a pipe for ourselves. We // then do heavy disk allocation outside the lock, but this open pipe // will block any attempted install transitions. final FileBridge bridge; synchronized (mLock) { assertPreparedAndNotSealed("openWrite"); bridge = new FileBridge(); mBridges.add(bridge); } try { final File target = new File(resolveStageDir(), name); // TODO: this should delegate to DCS so the system process avoids // holding open FDs into containers. final FileDescriptor targetFd = Os.open(target.getAbsolutePath(), O_CREAT | O_WRONLY, 0644); // If caller specified a total length, allocate it for them. Free up // cache space to grow, if needed. if (lengthBytes > 0) { Os.posix_fallocate(targetFd, 0, lengthBytes); } if (offsetBytes > 0) { Os.lseek(targetFd, offsetBytes, OsConstants.SEEK_SET); } bridge.setTargetFile(targetFd); bridge.start(); return ParcelFileDescriptor.dup(bridge.getClientSocket()); } catch (ErrnoException e) { throw new IOException(e); } }
/** * Implementation is provided by the parent class. Cannot be overriden. * * @see #openDocument(String, String, CancellationSignal) */ @Override public final AssetFileDescriptor openAssetFile(Uri uri, String mode, CancellationSignal signal) throws FileNotFoundException { enforceTree(uri); final ParcelFileDescriptor fd = openDocument(getDocumentId(uri), mode, signal); return fd != null ? new AssetFileDescriptor(fd, 0, -1) : null; }
private static void closeLoudly(ParcelFileDescriptor input) { if (input != null) { try { input.close(); } catch (IOException e) { Log.e(OpenPgpApi.TAG, "IOException when closing ParcelFileDescriptor!", e); } } }
private boolean loadFromTag() { Uri imgLink = getIntent().getParcelableExtra(EXTRA_PARAM_P2P_VAL); try { ParcelFileDescriptor pfd = getContentResolver().openFileDescriptor(imgLink, "r"); if (pfd == null) { return false; } Bitmap raw = BitmapFactory.decodeFileDescriptor(pfd.getFileDescriptor()); if (raw == null) { return false; } setCoverImage(raw); return true; } catch (FileNotFoundException e) { Log.e(LOG_TAG, "Passed Uri points to invalid fd! " + imgLink, e); } return false; }
@Override public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException { ParcelFileDescriptor pfd = null; int match = URI_MATCHER.match(uri); // let scraper handle it's part if (ScraperProvider.handles(match)) return mScraperProvider.openFile(uri, mode); try { pfd = openFileHelper(uri, mode); } catch (FileNotFoundException ex) { if (mode.contains("w")) { // if the file couldn't be created, we shouldn't extract album art throw ex; } if (pfd == null) { throw ex; } } return pfd; }
/** * Write out the new state file: the version number, followed by the * three bits of data as we sent them off to the backup transport. */ void writeStateFile(ParcelFileDescriptor stateFile) throws IOException { FileOutputStream outstream = new FileOutputStream(stateFile.getFileDescriptor()); DataOutputStream out = new DataOutputStream(outstream); out.writeInt(AGENT_VERSION); out.writeInt(mFilling); out.writeBoolean(mAddMayo); out.writeBoolean(mAddTomato); }
@Override protected ParcelFileDescriptor loadResource(Uri uri, ContentResolver contentResolver) throws FileNotFoundException { AssetFileDescriptor assetFileDescriptor = contentResolver.openAssetFileDescriptor(uri, "r"); if (assetFileDescriptor == null) { throw new FileNotFoundException("FileDescriptor is null for: " + uri); } return assetFileDescriptor.getParcelFileDescriptor(); }
ReadFileTask(String uri, SmbClient client, ParcelFileDescriptor pfd, ByteBufferPool bufferPool) { mUri = uri; mClient = client; mPfd = pfd; mBufferPool = bufferPool; }
protected ParcelFileDescriptor openAudioThumbnailCleared(long id, CancellationSignal signal) throws FileNotFoundException { final ContentResolver resolver = getContext().getContentResolver(); Cursor cursor = null; try { cursor = resolver.query(Audio.Albums.EXTERNAL_CONTENT_URI, AudioThumbnailQuery.PROJECTION, Audio.Albums._ID + "=" + id, null, null); if (cursor.moveToFirst()) { final String data = cursor.getString(AudioThumbnailQuery._DATA); return ParcelFileDescriptor.open( new File(data), ParcelFileDescriptor.MODE_READ_ONLY); } } finally { IoUtils.closeQuietly(cursor); } return null; }
public static void closeSilently(ParcelFileDescriptor c) { if (c == null) return; try { c.close(); } catch (Throwable t) { Log.w(TAG, "fail to close", t); } }
/** * Executes a statement that returns a single BLOB result as a * file descriptor to a shared memory region. * * @param sql The SQL statement to execute. * @param bindArgs The arguments to bind, or null if none. * @param connectionFlags The connection flags to use if a connection must be * acquired by this operation. Refer to {@link SQLiteConnectionPool}. * @param cancellationSignal A signal to cancel the operation in progress, or null if none. * @return The file descriptor for a shared memory region that contains * the value of the first column in the first row of the result set as a BLOB, * or null if none. * @throws SQLiteException if an error occurs, such as a syntax error * or invalid number of bind arguments. * @throws OperationCanceledException if the operation was canceled. */ public ParcelFileDescriptor executeForBlobFileDescriptor(String sql, Object[] bindArgs, int connectionFlags, CancellationSignal cancellationSignal) { if (sql == null) { throw new IllegalArgumentException("sql must not be null."); } if (executeSpecial(sql, bindArgs, connectionFlags, cancellationSignal)) { return null; } acquireConnection(sql, connectionFlags, cancellationSignal); // might throw try { return mConnection.executeForBlobFileDescriptor(sql, bindArgs, cancellationSignal); // might throw } finally { releaseConnection(); // might throw } }
private int transferFullRestoreData(ParcelFileDescriptor outputFileDescriptor) { ZipInputStream inputStream = restoreState.getInputStream(); OutputStream outputStream = new FileOutputStream(outputFileDescriptor.getFileDescriptor()); byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; int bytesRead = NO_MORE_DATA; try { bytesRead = inputStream.read(buffer); if (bytesRead <= 0) { bytesRead = NO_MORE_DATA; } else { outputStream.write(buffer, 0, bytesRead); } } catch (Exception e) { Log.e(TAG, "Exception while streaming restore data: ", e); return TRANSPORT_ERROR; } finally { if (bytesRead == NO_MORE_DATA) { if (restoreState.getInputFileDescriptor() != null) { IoUtils.closeQuietly(restoreState.getInputFileDescriptor()); } restoreState.setInputFileDescriptor(null); restoreState.setInputStream(null); } IoUtils.closeQuietly(outputFileDescriptor); } return bytesRead; }
private void handleVideo(MediaInfo mVideoInfo) { mCurrentVideoInfo = mVideoInfo; String assetpath = mVideoInfo.getAssetcover(); File srcFile = new File(assetpath); int dotindex = assetpath.lastIndexOf("."); if (dotindex != -1) { String type = assetpath.substring(dotindex, assetpath.length()); String compressPath = mSession.getCompressPath(); if (Build.VERSION.SDK_INT >= 18) { FileOutputStream fos = null; try { mCacheVideoPath = compressPath + (compressPath.endsWith(File.separator) ? "" : File.separator) + "savorVideo" + type; Uri uriForFile = FileProvider.getUriForFile(this, "com.savor.savorphone.fileprovider", srcFile); ContentResolver contentResolver = getContentResolver(); ParcelFileDescriptor pFileDesCripter = contentResolver.openFileDescriptor(uriForFile, "r"); FileDescriptor fileDesCripter = pFileDesCripter.getFileDescriptor(); // MediaTranscoder.getInstance().transcodeVideo(fileDesCripter, mCacheVideoPath, // MediaFormatStrategyPresets.createExportPreset960x540Strategy(), listener); future = MediaTranscoder.getInstance().transcodeVideo(fileDesCripter, mCacheVideoPath, MediaFormatStrategyPresets.createAndroid720pStrategy(8000 * 1000, 128 * 1000, 1), listener); } catch (Exception e) { e.printStackTrace(); handleFileCopy(mVideoInfo, srcFile, type, compressPath); } } else { handleFileCopy(mVideoInfo, srcFile, type, compressPath); } } }