java.io.FileDescriptor#valid ( )源码实例Demo

下面列出了java.io.FileDescriptor#valid ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: android_9.0.0_r45   文件: PinnerService.java
/**
 * 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);
            }
        }
    }
}
 
源代码2 项目: android_9.0.0_r45   文件: SharedMemory.java
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));
}
 
源代码3 项目: j2objc   文件: AbstractPlainDatagramSocketImpl.java
/**
 * 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");
    }
}
 
源代码4 项目: openjdk-jdk9   文件: ExtendedSocketOptions.java
@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);
    }
}
 
源代码5 项目: sdl_java_suite   文件: MultiplexUsbTransport.java
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);
}
 
源代码6 项目: libcommon   文件: BitmapHelper.java
/**
 * ファイルからビットマップを読み込んで指定した幅・高さに最も近い大きさの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;
}
 
源代码7 项目: dttv-android   文件: FileUtils.java
/**
 * 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);
    }
}
 
源代码8 项目: p4ic4idea   文件: ClientMergeState.java
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;
}
 
源代码9 项目: j2objc   文件: NetworkBridge.java
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?
    }
}
 
源代码10 项目: p4ic4idea   文件: ClientMergeState.java
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;
}
 
源代码11 项目: p4ic4idea   文件: ClientMergeState.java
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;
}
 
源代码12 项目: android_9.0.0_r45   文件: VerityUtils.java
/**
 * 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();
        }
    }
}
 
源代码13 项目: Bytecoder   文件: SocketCleanable.java
/**
 * 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));
    }
}
 
源代码14 项目: container   文件: FileBridge.java
public static void closeQuietly(FileDescriptor fd) {

        if (fd != null && fd.valid()) {
            try {
                Os.close(fd);
            } catch (ErrnoException e) {
                e.printStackTrace();
            }
        }
    }
 
源代码15 项目: j2objc   文件: NetworkBridge.java
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);
}
 
源代码16 项目: j2objc   文件: IoUtils.java
/**
 * 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();
    }
}
 
源代码17 项目: dttv-android   文件: FileUtils.java
/**
 * 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());
    }
}
 
源代码18 项目: io   文件: BinaryDataAccessor.java
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)));
    }
}
 
源代码19 项目: FontProvider   文件: FontManager.java
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);
}
 
源代码20 项目: DroidDLNA   文件: MediaMetadataRetriever.java
/**
 * 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());
}