List of usage examples for android.os ParcelFileDescriptor parseMode
public static int parseMode(String mode)
From source file:net.sf.fakenames.fddemo.PermissionActivity.java
private String accessPattern(String access) { final int accessMode = ParcelFileDescriptor.parseMode(access); if ((accessMode & ParcelFileDescriptor.MODE_READ_ONLY) == accessMode) { return "read"; }//from w w w .ja v a 2 s . c o m if ((accessMode & ParcelFileDescriptor.MODE_WRITE_ONLY) == accessMode) { return "write"; } return "full"; }
From source file:org.alfresco.mobile.android.application.providers.storage.StorageAccessDocumentsProvider.java
@Override public ParcelFileDescriptor openDocument(String documentId, String mode, CancellationSignal signal) throws FileNotFoundException { // Log.d(TAG, "Open Document : " + documentId); try {/*from ww w .j a v a 2s .co m*/ EncodedQueryUri cUri = new EncodedQueryUri(documentId); checkSession(cUri); Node currentNode = retrieveNode(cUri.id); try { // DocumentId can be an old one stored as "recent doc" // This id might have been updated/changed until the last access // That's why We ALWAYS request the latest version // Log.d(TAG, "retrieve latest version"); currentNode = session.getServiceRegistry().getVersionService() .getLatestVersion((org.alfresco.mobile.android.api.model.Document) currentNode); } catch (AlfrescoServiceException e) { // Specific edge case on old version of Alfresco // the first version number can be 0.1 instead of 1.0 // So we try to find this version instead the default 1.0 String id = NodeRefUtils.getCleanIdentifier(cUri.id); if (session instanceof RepositorySession) { id = NodeRefUtils.createNodeRefByIdentifier(id) + ";0.1"; } currentNode = session.getServiceRegistry().getDocumentFolderService().getNodeByIdentifier(id); currentNode = session.getServiceRegistry().getVersionService() .getLatestVersion((org.alfresco.mobile.android.api.model.Document) currentNode); } nodesIndex.put(NodeRefUtils.getVersionIdentifier(cUri.id), currentNode); nodesIndex.put(NodeRefUtils.getVersionIdentifier(currentNode.getIdentifier()), currentNode); // Check Document has Content if (currentNode.isFolder()) { return null; } // It's a document so let's write the local file! // Store the document inside a temporary folder per account File downloadedFile = null; if (getContext() != null && currentNode != null && session != null) { File folder = AlfrescoStorageManager.getInstance(getContext()).getShareFolder(selectedAccount); if (folder != null) { String extension = MimeTypeManager.getExtension(currentNode.getName()); String name = NodeRefUtils.getVersionIdentifier(currentNode.getIdentifier()); if (!TextUtils.isEmpty(extension)) { name = name.concat(".").concat(extension); } downloadedFile = new File(folder, name); } } // Check the mode final int accessMode = ParcelFileDescriptor.parseMode(mode); final boolean isWrite = (mode.indexOf('w') != -1); // Is Document in cache ? if (downloadedFile != null && downloadedFile.exists() && currentNode.getModifiedAt().getTimeInMillis() < downloadedFile.lastModified()) { // Document available locally return createFileDescriptor((org.alfresco.mobile.android.api.model.Document) currentNode, isWrite, downloadedFile, accessMode); } // Not in cache so let's download the content if it has content ! if (((org.alfresco.mobile.android.api.model.Document) currentNode).getContentStreamLength() != 0) { ContentStream contentStream = session.getServiceRegistry().getDocumentFolderService() .getContentStream((org.alfresco.mobile.android.api.model.Document) currentNode); // Check Stream if (contentStream == null || contentStream.getLength() == 0) { return null; } // Copy the content locally. copyFile(contentStream.getInputStream(), contentStream.getLength(), downloadedFile, signal); } else { downloadedFile.createNewFile(); } if (downloadedFile.exists()) { // Document available locally return createFileDescriptor((org.alfresco.mobile.android.api.model.Document) currentNode, isWrite, downloadedFile, accessMode); } else { return null; } } catch (Exception e) { Log.w(TAG, Log.getStackTraceString(e)); throw new FileNotFoundException("Unable to find this document"); } }
From source file:net.sf.xfd.provider.PublicProvider.java
final void verifyMac(Uri path, String grantMode, String requested) throws FileNotFoundException { if (Process.myUid() == Binder.getCallingUid()) { return;/*from w w w .ja v a2 s . c o m*/ } final int requestedMode = ParcelFileDescriptor.parseMode(requested); final String cookie = path.getQueryParameter(URI_ARG_COOKIE); final String expiry = path.getQueryParameter(URI_ARG_EXPIRY); if (TextUtils.isEmpty(cookie) || TextUtils.isEmpty(expiry)) { throw new FileNotFoundException("Invalid uri: MAC and expiry date are missing"); } final long l; try { l = Long.parseLong(expiry); } catch (NumberFormatException nfe) { throw new FileNotFoundException("Invalid uri: unable to parse expiry date"); } final Key key = getSalt(getContext()); if (key == null) { throw new FileNotFoundException("Unable to verify hash: failed to produce key"); } final int modeInt = ParcelFileDescriptor.parseMode(grantMode); if ((requestedMode & modeInt) != requestedMode) { throw new FileNotFoundException("Requested mode " + requested + " but limited to " + grantMode); } final byte[] encoded; final Mac hash; try { hash = Mac.getInstance("HmacSHA1"); hash.init(key); final byte[] modeBits = new byte[] { (byte) (modeInt >> 24), (byte) (modeInt >> 16), (byte) (modeInt >> 8), (byte) modeInt, }; hash.update(modeBits); final byte[] expiryDate = new byte[] { (byte) (l >> 56), (byte) (l >> 48), (byte) (l >> 40), (byte) (l >> 32), (byte) (l >> 24), (byte) (l >> 16), (byte) (l >> 8), (byte) l, }; hash.update(expiryDate); encoded = hash.doFinal(path.getPath().getBytes()); final String sample = Base64.encodeToString(encoded, URL_SAFE | NO_WRAP | NO_PADDING); if (!cookie.equals(sample)) { throw new FileNotFoundException("Expired uri"); } } catch (NoSuchAlgorithmException e) { throw new FileNotFoundException("Unable to verify hash: missing HmacSHA1"); } catch (InvalidKeyException e) { throw new FileNotFoundException("Unable to verify hash: corrupted key?!"); } }
From source file:net.sf.xfd.provider.PublicProvider.java
@Nullable @Override//from w w w . j av a2 s. com public ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String requestedMode, CancellationSignal signal) throws FileNotFoundException { String path = uri.getPath(); assertAbsolute(path); final int readableMode = ParcelFileDescriptor.parseMode(requestedMode); if (signal != null) { final Thread theThread = Thread.currentThread(); signal.setOnCancelListener(theThread::interrupt); } path = canonString(path); if (!path.equals(uri.getPath())) { uri = uri.buildUpon().path(path).build(); } try { if (!checkAccess(uri, requestedMode)) { return null; } final OS rooted = base.getOS(); if (rooted == null) { throw new FileNotFoundException("Failed to open " + uri.getPath() + ": unable to acquire access"); } int openFlags; if ((readableMode & MODE_READ_ONLY) == readableMode) { openFlags = OS.O_RDONLY; } else if ((readableMode & MODE_WRITE_ONLY) == readableMode) { openFlags = OS.O_WRONLY; } else { openFlags = OS.O_RDWR; } if (signal == null) { openFlags |= NativeBits.O_NONBLOCK; } //noinspection WrongConstant @Fd int fd = rooted.open(path, openFlags, 0); return ParcelFileDescriptor.adoptFd(fd); } catch (IOException e) { throw new FileNotFoundException("Unable to open " + uri.getPath() + ": " + e.getMessage()); } finally { if (signal != null) { signal.setOnCancelListener(null); } Thread.interrupted(); } }
From source file:com.seafile.seadroid2.provider.SeafileProvider.java
/** * Create ParcelFileDescriptor from the given file. * * @param file the file/*from w w w . ja v a 2 s . c om*/ * @param mode the mode the file shoall be opened with. * @return a ParcelFileDescriptor * @throws IOException */ private ParcelFileDescriptor makeParcelFileDescriptor(final DataManager dm, final String repoName, final String repoID, final String parentDir, final File file, final String mode) throws IOException { final int accessMode = ParcelFileDescriptor.parseMode(mode); Handler handler = new Handler(getContext().getMainLooper()); return ParcelFileDescriptor.open(file, accessMode, handler, new ParcelFileDescriptor.OnCloseListener() { @Override public void onClose(final IOException e) { Log.d(DEBUG_TAG, "uploading file: " + repoID + "; " + file.getPath() + "; " + parentDir + "; e=" + e); if (mode.equals("r") || e != null) { return; } ConcurrentAsyncTask.submit(new Runnable() { @Override public void run() { try { dm.uploadFile(repoName, repoID, parentDir, file.getPath(), null, true, false); // update cache for parent dir dm.getDirentsFromServer(repoID, parentDir); } catch (SeafException e1) { Log.d(DEBUG_TAG, "could not upload file: ", e1); } } }); } }); }
From source file:net.sf.xfd.provider.PublicProvider.java
@Override public Uri canonicalize(@NonNull Uri uri) { try {//from w w w . j av a 2 s . c om base.assertAbsolute(uri); String grantMode = uri.getQueryParameter(URI_ARG_MODE); if (TextUtils.isEmpty(grantMode)) { grantMode = "r"; } verifyMac(uri, grantMode, grantMode); final int flags = ParcelFileDescriptor.parseMode(grantMode); final Context context = getContext(); assert context != null; final String packageName = context.getPackageName(); final Uri canon = DocumentsContract.buildDocumentUri(packageName + FileProvider.AUTHORITY_SUFFIX, canonString(uri.getPath())); final int callerUid = Binder.getCallingUid(); if (callerUid != Process.myUid()) { int grantFlags = Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION; if ((flags & ParcelFileDescriptor.MODE_READ_ONLY) == flags) { grantFlags |= Intent.FLAG_GRANT_READ_URI_PERMISSION; } else if ((flags & ParcelFileDescriptor.MODE_WRITE_ONLY) == flags) grantFlags |= Intent.FLAG_GRANT_WRITE_URI_PERMISSION; else { grantFlags |= Intent.FLAG_GRANT_WRITE_URI_PERMISSION; grantFlags |= Intent.FLAG_GRANT_READ_URI_PERMISSION; } final String[] packages; final String caller = getCallingPackage(); if (caller != null) { packages = new String[] { caller }; } else { final PackageManager pm = context.getPackageManager(); packages = pm.getPackagesForUid(callerUid); } if (packages != null) { for (String pkg : packages) { context.grantUriPermission(pkg, canon, grantFlags); } } } return canon; } catch (FileNotFoundException e) { return null; } }
From source file:net.sf.xfd.provider.PublicProvider.java
public static @Nullable Uri publicUri(Context context, CharSequence path, String mode) { // XXX suspect coversion final String pathString = path.toString(); final int modeInt = ParcelFileDescriptor.parseMode(mode); final Key key = getSalt(context); if (key == null) { return null; }/*from w ww.j av a 2 s .c om*/ final Calendar c = Calendar.getInstance(); c.add(Calendar.DATE, 1); final long l = c.getTimeInMillis(); final byte[] encoded; try { final Mac hash = Mac.getInstance("HmacSHA1"); hash.init(key); final byte[] modeBits = new byte[] { (byte) (modeInt >> 24), (byte) (modeInt >> 16), (byte) (modeInt >> 8), (byte) modeInt, }; hash.update(modeBits); final byte[] expiryDate = new byte[] { (byte) (l >> 56), (byte) (l >> 48), (byte) (l >> 40), (byte) (l >> 32), (byte) (l >> 24), (byte) (l >> 16), (byte) (l >> 8), (byte) l, }; hash.update(expiryDate); encoded = hash.doFinal(pathString.getBytes()); } catch (NoSuchAlgorithmException | InvalidKeyException e) { throw new AssertionError("Error while creating a hash: " + e.getMessage(), e); } final String packageName = context.getPackageName(); final Uri.Builder b = new Uri.Builder().scheme(SCHEME_CONTENT).authority(packageName + AUTHORITY_SUFFIX); if (!"r".equals(mode)) { b.appendQueryParameter(URI_ARG_MODE, mode); } return b.path(pathString).appendQueryParameter(URI_ARG_EXPIRY, String.valueOf(l)) .appendQueryParameter(URI_ARG_COOKIE, encodeToString(encoded, URL_SAFE | NO_WRAP | NO_PADDING)) .build(); }
From source file:dev.dworks.apps.anexplorer.provider.ExternalStorageProvider.java
@TargetApi(Build.VERSION_CODES.KITKAT) @Override//from ww w .j a v a 2 s . c o m public ParcelFileDescriptor openDocument(String documentId, String mode, CancellationSignal signal) throws FileNotFoundException { final File file = getFileForDocId(documentId); if (Utils.hasKitKat()) { final int pfdMode = ParcelFileDescriptor.parseMode(mode); if (pfdMode == ParcelFileDescriptor.MODE_READ_ONLY) { return ParcelFileDescriptor.open(file, pfdMode); } else { try { // When finished writing, kick off media scanner return ParcelFileDescriptor.open(file, pfdMode, mHandler, new ParcelFileDescriptor.OnCloseListener() { @Override public void onClose(IOException e) { FileUtils.updateMedia(getContext(), file.getPath()); } }); } catch (IOException e) { throw new FileNotFoundException("Failed to open for writing: " + e); } } } else { return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);//ParcelFileDescriptor.parseMode(mode)); } }
From source file:com.google.android.apps.muzei.provider.MuzeiProvider.java
private ParcelFileDescriptor openFileArtwork(@NonNull final Uri uri, @NonNull final String mode) throws FileNotFoundException { String[] projection = { BaseColumns._ID, MuzeiContract.Artwork.COLUMN_NAME_IMAGE_URI }; final boolean isWriteOperation = mode.contains("w"); final File file; if (!UserManagerCompat.isUserUnlocked(getContext())) { if (isWriteOperation) { Log.w(TAG, "Wallpaper is read only until the user is unlocked"); return null; }//from w ww. jav a2 s . c o m file = DirectBootCacheJobService.getCachedArtwork(getContext()); } else if (!isWriteOperation && MuzeiProvider.uriMatcher.match(uri) == MuzeiProvider.ARTWORK) { // If it isn't a write operation, then we should attempt to find the latest artwork // that does have a cached artwork file. This prevents race conditions where // an external app attempts to load the latest artwork while an art source is inserting a // new artwork Cursor data = queryArtwork(MuzeiContract.Artwork.CONTENT_URI, projection, null, null, null); if (data == null) { return null; } if (!data.moveToFirst()) { if (!getContext().getPackageName().equals(getCallingPackage())) { Log.w(TAG, "You must insert at least one row to read or write artwork"); } return null; } File foundFile = null; while (!data.isAfterLast()) { Uri possibleArtworkUri = ContentUris.withAppendedId(MuzeiContract.Artwork.CONTENT_URI, data.getLong(0)); File possibleFile = getCacheFileForArtworkUri(possibleArtworkUri); if (possibleFile != null && possibleFile.exists()) { foundFile = possibleFile; break; } data.moveToNext(); } file = foundFile; } else { file = getCacheFileForArtworkUri(uri); } if (file == null) { throw new FileNotFoundException("Could not create artwork file"); } if (file.exists() && file.length() > 0 && isWriteOperation) { Context context = getContext(); if (context == null) { return null; } if (!context.getPackageName().equals(getCallingPackage())) { Log.w(TAG, "Writing to an existing artwork file is not allowed: insert a new row"); } cleanupCachedFiles(); return null; } try { return ParcelFileDescriptor.open(file, ParcelFileDescriptor.parseMode(mode), openFileHandler, new ParcelFileDescriptor.OnCloseListener() { @Override public void onClose(final IOException e) { if (isWriteOperation) { if (e != null) { Log.e(TAG, "Error closing " + file + " for " + uri, e); if (file.exists()) { if (!file.delete()) { Log.w(TAG, "Unable to delete " + file); } } } else { // The file was successfully written, notify listeners of the new artwork notifyChange(uri); cleanupCachedFiles(); } } } }); } catch (IOException e) { Log.e(TAG, "Error opening artwork " + uri, e); throw new FileNotFoundException("Error opening artwork " + uri); } }
From source file:android.webkit.cts.WebViewTest.java
public void testPrinting() throws Throwable { if (!NullWebViewUtils.isWebViewAvailable()) { return;//from w w w . j ava 2 s . com } mOnUiThread.loadDataAndWaitForCompletion("<html><head></head>" + "<body>foo</body></html>", "text/html", null); final PrintDocumentAdapter adapter = mOnUiThread.createPrintDocumentAdapter(); printDocumentStart(adapter); PrintAttributes attributes = new PrintAttributes.Builder().setMediaSize(PrintAttributes.MediaSize.ISO_A4) .setResolution(new PrintAttributes.Resolution("foo", "bar", 300, 300)) .setMinMargins(PrintAttributes.Margins.NO_MARGINS).build(); final WebViewCtsActivity activity = getActivity(); final File file = activity.getFileStreamPath(PRINTER_TEST_FILE); final ParcelFileDescriptor descriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.parseMode("w")); final FutureTask<Boolean> result = new FutureTask<Boolean>(new Callable<Boolean>() { public Boolean call() { return true; } }); printDocumentLayout(adapter, null, attributes, new LayoutResultCallback() { // Called on UI thread @Override public void onLayoutFinished(PrintDocumentInfo info, boolean changed) { savePrintedPage(adapter, descriptor, result); } }); try { result.get(TEST_TIMEOUT, TimeUnit.MILLISECONDS); assertTrue(file.length() > 0); FileInputStream in = new FileInputStream(file); byte[] b = new byte[PDF_PREAMBLE.length()]; in.read(b); String preamble = new String(b); assertEquals(PDF_PREAMBLE, preamble); } finally { // close the descriptor, if not closed already. descriptor.close(); file.delete(); } }