Java Code Examples for java.io.FileDescriptor#valid()
The following examples show how to use
java.io.FileDescriptor#valid() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PinnerService.java From android_9.0.0_r45 with Apache License 2.0 | 6 votes |
/** * Close FD, swallowing irrelevant errors. */ private static void safeClose(@Nullable FileDescriptor fd) { if (fd != null && fd.valid()) { try { Os.close(fd); } catch (ErrnoException ex) { // Swallow the exception: non-EBADF errors in close(2) // indicate deferred paging write errors, which we // don't care about here. The underlying file // descriptor is always closed. if (ex.errno == OsConstants.EBADF) { throw new AssertionError(ex); } } } }
Example 2
Source File: SharedMemory.java From android_9.0.0_r45 with Apache License 2.0 | 6 votes |
private SharedMemory(FileDescriptor fd) { // This constructor is only used internally so it should be impossible to hit any of the // exceptions unless something goes horribly wrong. if (fd == null) { throw new IllegalArgumentException( "Unable to create SharedMemory from a null FileDescriptor"); } if (!fd.valid()) { throw new IllegalArgumentException( "Unable to create SharedMemory from closed FileDescriptor"); } mFileDescriptor = fd; mSize = nGetSize(mFileDescriptor); if (mSize <= 0) { throw new IllegalArgumentException("FileDescriptor is not a valid ashmem fd"); } mMemoryRegistration = new MemoryRegistration(mSize); mCleaner = Cleaner.create(mFileDescriptor, new Closer(mFileDescriptor, mMemoryRegistration)); }
Example 3
Source File: AbstractPlainDatagramSocketImpl.java From j2objc with Apache License 2.0 | 6 votes |
/** * Creates a datagram socket */ protected synchronized void create() throws SocketException { ResourceManager.beforeUdpCreate(); fd = new FileDescriptor(); try { datagramSocketCreate(); } catch (SocketException ioe) { ResourceManager.afterUdpClose(); fd = null; throw ioe; } if (fd != null && fd.valid()) { guard.open("close"); } }
Example 4
Source File: ExtendedSocketOptions.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
@Override public Object getOption(FileDescriptor fd, SocketOption<?> option) throws SocketException { SecurityManager sm = System.getSecurityManager(); if (sm != null) sm.checkPermission(new NetworkPermission("getOption." + option.name())); if (fd == null || !fd.valid()) throw new SocketException("socket closed"); if (option == SO_FLOW_SLA) { assert flowSupported; SocketFlow flow = SocketFlow.create(); getFlowOption(fd, flow); return flow; } else { throw new InternalError("Unexpected option " + option); } }
Example 5
Source File: ClientMergeState.java From p4ic4idea with Apache License 2.0 | 6 votes |
private boolean checkStream(RpcOutputStream stream) { try { if (stream != null) { FileDescriptor fd = stream.getFD(); if (fd != null) { if (fd.valid()) { return true; } } } } catch (IOException ioexc) { // Ignore for now other than to log it... Log.exception(ioexc); } return false; }
Example 6
Source File: MultiplexUsbTransport.java From sdl_java_suite with BSD 3-Clause "New" or "Revised" License | 6 votes |
public synchronized void start(){ setState(STATE_CONNECTING); FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor(); if(fileDescriptor == null || !fileDescriptor.valid()){ Log.e(TAG, "USB FD was null or not valid,"); setState(STATE_NONE); return; } readerThread = new ReaderThread(fileDescriptor); readerThread.setDaemon(true); writerThread = new WriterThread(fileDescriptor); writerThread.setDaemon(true); readerThread.start(); writerThread.start(); // Send the name of the connected device back to the UI Activity Message msg = handler.obtainMessage(SdlRouterService.MESSAGE_DEVICE_NAME); Bundle bundle = new Bundle(); bundle.putString(DEVICE_NAME, connectedDeviceName); bundle.putString(DEVICE_ADDRESS, connectedDeviceAddress); msg.setData(bundle); handler.sendMessage(msg); setState(STATE_CONNECTED); }
Example 7
Source File: BitmapHelper.java From libcommon with Apache License 2.0 | 6 votes |
/** * ファイルからビットマップを読み込んで指定した幅・高さに最も近い大きさのBitmapとして返す * @param fd * @param requestWidth * @param requestHeight * @return */ @Nullable public static Bitmap asBitmap( final FileDescriptor fd, final int requestWidth, final int requestHeight) { Bitmap bitmap = null; if (fd != null && fd.valid()) { final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; // Bitmapを生成せずにサイズ等の情報だけを取得する BitmapFactory.decodeFileDescriptor(fd, null, options); options.inJustDecodeBounds = false; options.inSampleSize = calcSampleSize(options, requestWidth, requestHeight); bitmap = BitmapFactory.decodeFileDescriptor(fd, null, options); final int orientation = getOrientation(fd); if (orientation != 0) { final Bitmap newBitmap = rotateBitmap(bitmap, orientation); bitmap.recycle(); bitmap = newBitmap; } } return bitmap; }
Example 8
Source File: FileUtils.java From dttv-android with GNU General Public License v3.0 | 6 votes |
/** * Copies bytes from the URL <code>source</code> to a file * <code>destination</code>. The directories up to <code>destination</code> * will be created if they don't already exist. <code>destination</code> * will be overwritten if it already exists. * * @param source the <code>URL</code> to copy bytes from, must not be <code>null</code> * @param destination the non-directory <code>File</code> to write bytes to * (possibly overwriting), must not be <code>null</code> * @throws IOException if <code>source</code> URL cannot be opened * @throws IOException if <code>destination</code> is a directory * @throws IOException if <code>destination</code> cannot be written * @throws IOException if <code>destination</code> needs creating but can't be * @throws IOException if an IO error occurs during copying */ public static void copyURLToFile(URL source, File destination) throws IOException { InputStream input = source.openStream(); try { FileOutputStream output = openOutputStream(destination); try { IOUtils.copy(input, output); FileDescriptor fd = output.getFD(); if(fd.valid()) fd.sync(); } finally { IOUtils.closeQuietly(output); } } finally { IOUtils.closeQuietly(input); } }
Example 9
Source File: ClientMergeState.java From p4ic4idea with Apache License 2.0 | 6 votes |
private boolean checkStream(RpcOutputStream stream) { try { if (stream != null) { FileDescriptor fd = stream.getFD(); if (fd != null) { if (fd.valid()) { return true; } } } } catch (IOException ioexc) { // Ignore for now other than to log it... Log.exception(ioexc); } return false; }
Example 10
Source File: NetworkBridge.java From j2objc with Apache License 2.0 | 6 votes |
public static void closeSocket(FileDescriptor fd) throws IOException { if (!fd.valid()) { // Socket.close doesn't throw if you try to close an already-closed socket. return; } int intFd = fd.getInt$(); fd.setInt$(-1); FileDescriptor oldFd = new FileDescriptor(); oldFd.setInt$(intFd); AsynchronousCloseMonitor.signalBlockedThreads(oldFd); try { Libcore.os.close(oldFd); } catch (ErrnoException errnoException) { // TODO: are there any cases in which we should throw? } }
Example 11
Source File: ClientMergeState.java From p4ic4idea with Apache License 2.0 | 6 votes |
private boolean checkStream(RpcOutputStream stream) { try { if (stream != null) { FileDescriptor fd = stream.getFD(); if (fd != null) { if (fd.valid()) { return true; } } } } catch (IOException ioexc) { // Ignore for now other than to log it... Log.exception(ioexc); } return false; }
Example 12
Source File: BinaryDataAccessor.java From io with Apache License 2.0 | 5 votes |
private void fsyncIfFileOutputStream(OutputStream outputStream) throws IOException { if (outputStream instanceof FileOutputStream) { FileDescriptor desc = ((FileOutputStream) outputStream).getFD(); if (null != desc && desc.valid()) { sync(desc); } } else if (outputStream instanceof FilterOutputStream) { // FilterOutputStream の場合には、"out"field から FileOutputStream を取り出してfsyncする fsyncIfFileOutputStream(getInternalOutputStream(((FilterOutputStream) outputStream))); } }
Example 13
Source File: VerityUtils.java From android_9.0.0_r45 with Apache License 2.0 | 5 votes |
/** * Generates Merkle tree and fsverity metadata. * * @return {@code SetupResult} that contains the {@code EsetupResultCode}, and when success, the * {@code FileDescriptor} to read all the data from. */ public static SetupResult generateApkVeritySetupData(@NonNull String apkPath) { if (DEBUG) Slog.d(TAG, "Trying to install apk verity to " + apkPath); SharedMemory shm = null; try { byte[] signedRootHash = ApkSignatureVerifier.getVerityRootHash(apkPath); if (signedRootHash == null) { if (DEBUG) { Slog.d(TAG, "Skip verity tree generation since there is no root hash"); } return SetupResult.skipped(); } Pair<SharedMemory, Integer> result = generateApkVerityIntoSharedMemory(apkPath, signedRootHash); shm = result.first; int contentSize = result.second; FileDescriptor rfd = shm.getFileDescriptor(); if (rfd == null || !rfd.valid()) { return SetupResult.failed(); } return SetupResult.ok(Os.dup(rfd), contentSize); } catch (IOException | SecurityException | DigestException | NoSuchAlgorithmException | SignatureNotFoundException | ErrnoException e) { Slog.e(TAG, "Failed to set up apk verity: ", e); return SetupResult.failed(); } finally { if (shm != null) { shm.close(); } } }
Example 14
Source File: FileUtils.java From dttv-android with GNU General Public License v3.0 | 5 votes |
/** * Internal copy file method. * * @param srcFile the validated source file, must not be <code>null</code> * @param destFile the validated destination file, must not be <code>null</code> * @param preserveFileDate whether to preserve the file date * @throws IOException if an error occurs */ private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { if (destFile.exists() && destFile.isDirectory()) { throw new IOException("Destination '" + destFile + "' exists but is a directory"); } FileInputStream input = new FileInputStream(srcFile); try { FileOutputStream output = new FileOutputStream(destFile); try { IOUtils.copy(input, output); FileDescriptor fd = output.getFD(); if(fd.valid()) fd.sync(); } finally { IOUtils.closeQuietly(output); } } finally { IOUtils.closeQuietly(input); } if (srcFile.length() != destFile.length()) { throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); } if (preserveFileDate) { destFile.setLastModified(srcFile.lastModified()); } }
Example 15
Source File: IoUtils.java From j2objc with Apache License 2.0 | 5 votes |
/** * Calls close(2) on 'fd'. Also resets the internal int to -1. Does nothing if 'fd' is null * or invalid. */ public static void close(FileDescriptor fd) throws IOException { try { if (fd != null && fd.valid()) { Libcore.os.close(fd); } } catch (ErrnoException errnoException) { throw errnoException.rethrowAsIOException(); } }
Example 16
Source File: NetworkBridge.java From j2objc with Apache License 2.0 | 5 votes |
public static boolean isConnected(FileDescriptor fd, InetAddress inetAddress, int port, int timeoutMs, int remainingTimeoutMs) throws IOException { ErrnoException cause; try { StructPollfd[] pollFds = new StructPollfd[] { new StructPollfd() }; pollFds[0].fd = fd; pollFds[0].events = (short) POLLOUT; int rc = Libcore.os.poll(pollFds, remainingTimeoutMs); if (rc == 0) { return false; // Timeout. } int connectError = NetworkOs.getsockoptInt(fd, SOL_SOCKET, SO_ERROR); if (connectError == 0) { return true; // Success! } throw new ErrnoException("isConnected", connectError); // The connect(2) failed. } catch (ErrnoException errnoException) { if (!fd.valid()) { throw new SocketException("Socket closed"); } if (errnoException.errno == EINTR) { return false; // Punt and ask the caller to try again. } else { cause = errnoException; } } String detail = connectDetail(inetAddress, port, timeoutMs, cause); if (cause.errno == ETIMEDOUT) { throw new SocketTimeoutException(detail, cause); } throw new ConnectException(detail, cause); }
Example 17
Source File: FileBridge.java From container with GNU General Public License v3.0 | 5 votes |
public static void closeQuietly(FileDescriptor fd) { if (fd != null && fd.valid()) { try { Os.close(fd); } catch (ErrnoException e) { e.printStackTrace(); } } }
Example 18
Source File: SocketCleanable.java From Bytecoder with Apache License 2.0 | 5 votes |
/** * Register a socket specific Cleanable with the FileDescriptor * if the FileDescriptor is non-null and the raw fd is != -1. * * @param fdo the FileDescriptor; may be null * @param stream false for datagram socket */ static void register(FileDescriptor fdo, boolean stream) { if (fdo != null && fdo.valid()) { int fd = fdAccess.get(fdo); fdAccess.registerCleanup(fdo, new SocketCleanable(fdo, CleanerFactory.cleaner(), fd, stream)); } }
Example 19
Source File: MediaMetadataRetriever.java From DroidDLNA with GNU General Public License v3.0 | 4 votes |
/** * Sets the data source as a content Uri. Call this method before the rest * of the methods in this class. This method may be time-consuming. * * @param context * the Context to use when resolving the Uri * @param uri * the Content URI of the data you want to play * @throws IllegalArgumentException * if the Uri is invalid * @throws SecurityException * if the Uri cannot be used due to lack of permission. */ public void setDataSource(Context context, Uri uri) throws IllegalArgumentException, SecurityException { if (uri == null) { throw new IllegalArgumentException(); } String scheme = uri.getScheme(); if (scheme == null || scheme.equals("file")) { // 匹配文件 setDataSource(uri.getPath()); return; } AssetFileDescriptor fd = null; try { ContentResolver resolver = context.getContentResolver(); try { fd = resolver.openAssetFileDescriptor(uri, "r");// 读取文件 } catch (FileNotFoundException e) { throw new IllegalArgumentException(); } if (fd == null) { throw new IllegalArgumentException(); } FileDescriptor descriptor = fd.getFileDescriptor(); if (!descriptor.valid()) { throw new IllegalArgumentException(); } // Note: using getDeclaredLength so that our behavior is the same // as previous versions when the content provider is returning // a full file. if (fd.getDeclaredLength() < 0) { setDataSource(descriptor); } else { setDataSource(descriptor, fd.getStartOffset(), fd.getDeclaredLength()); } return; } catch (SecurityException ex) { } finally { try { if (fd != null) { fd.close(); } } catch (IOException ioEx) { } } setDataSource(uri.toString()); }
Example 20
Source File: FontManager.java From FontProvider with MIT License | 4 votes |
public static FileDescriptor getFileDescriptor(Context context, String filename) { MemoryFile mf = sCache.get(filename); if (mf != null) { Log.i(TAG, "MemoryFile " + filename + " is in the cache"); FileDescriptor fd = MemoryFileUtils.getFileDescriptor(mf); if (fd != null && fd.valid()) { return fd; } else { Log.i(TAG, "MemoryFile " + filename + " is not valid?"); } } long time = System.currentTimeMillis(); Log.i(TAG, "loading file " + filename); // built in font? read from asset if (BUILT_IN_FONTS_SIZE.containsKey(filename)) { mf = MemoryFileUtils.fromAsset(context.getAssets(), filename, FILE_SIZE.get(filename)); } // downloadable font? read from file if (mf == null) { File file = ContextUtils.getExternalFile(context, filename); if (file.exists()) { mf = MemoryFileUtils.fromFile(file); if (mf != null) { FILE_SIZE.put(filename, mf.length()); } } } // file not exist? if (mf == null) { Log.w(TAG, "loading " + filename + " failed"); return null; } Log.i(TAG, "loading finished in " + (System.currentTimeMillis() - time) + "ms"); sCache.put(filename, mf); return MemoryFileUtils.getFileDescriptor(mf); }