下面列出了怎么用java.io.FileDescriptor的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
super.dump(prefix, fd, writer, args);
if (mTask != null) {
writer.print(prefix); writer.print("mTask="); writer.print(mTask);
writer.print(" waiting="); writer.println(mTask.waiting);
}
if (mCancellingTask != null) {
writer.print(prefix); writer.print("mCancellingTask="); writer.print(mCancellingTask);
writer.print(" waiting="); writer.println(mCancellingTask.waiting);
}
if (mUpdateThrottle != 0) {
writer.print(prefix); writer.print("mUpdateThrottle=");
TimeUtils.formatDuration(mUpdateThrottle, writer);
writer.print(" mLastLoadCompleteTime=");
TimeUtils.formatDuration(mLastLoadCompleteTime,
SystemClock.uptimeMillis(), writer);
writer.println();
}
}
private void protectFileDescriptor(FileDescriptor fd) {
try {
Method getInt = FileDescriptor.class.getDeclaredMethod("getInt$");
int fdint = (Integer) getInt.invoke(fd);
// You can even get more evil by parsing toString() and extract the int from that :)
boolean result = mOpenVPNService.protect(fdint);
if (!result) VpnStatus.logWarning("Could not protect VPN socket");
//ParcelFileDescriptor pfd = ParcelFileDescriptor.fromFd(fdint);
//pfd.close();
NativeUtils.jniclose(fdint);
return;
} catch (NoSuchMethodException | IllegalArgumentException | InvocationTargetException | IllegalAccessException | NullPointerException e) {
VpnStatus.logException("Failed to retrieve fd from socket (" + fd + ")", e);
}
Log.d("Openvpn", "Failed to retrieve fd from socket: " + fd);
}
/**
* Sets the data source (file-path or http/rtsp URL) to use.
*
* @param path the path of the file, or the http/rtsp URL of the stream you want to play
* @param keys AVOption key
* @param values AVOption value
* @throws IllegalStateException if it is called in an invalid state
*/
public void setDataSource(String path, String[] keys, String[] values) throws IOException, IllegalArgumentException, SecurityException, IllegalStateException {
final Uri uri = Uri.parse(path);
if ("file".equals(uri.getScheme())) {
path = uri.getPath();
}
final File file = new File(path);
if (file.exists()) {
FileInputStream is = new FileInputStream(file);
FileDescriptor fd = is.getFD();
setDataSource(fd);
is.close();
} else {
_setDataSource(path, keys, values);
}
}
private static int writeFromNativeBuffer(FileDescriptor fd, ByteBuffer bb,
long position, NativeDispatcher nd)
throws IOException
{
int pos = bb.position();
int lim = bb.limit();
assert (pos <= lim);
int rem = (pos <= lim ? lim - pos : 0);
int written = 0;
if (rem == 0)
return 0;
if (position != -1) {
written = nd.pwrite(fd,
((DirectBuffer)bb).address() + pos,
rem, position);
} else {
written = nd.write(fd, ((DirectBuffer)bb).address() + pos, rem);
}
if (written > 0)
bb.position(pos + written);
return written;
}
public static AsynchronousFileChannel open(FileDescriptor fdo,
boolean reading,
boolean writing,
ThreadPool pool)
throws IOException
{
Iocp iocp;
boolean isDefaultIocp;
if (pool == null) {
iocp = DefaultIocpHolder.defaultIocp;
isDefaultIocp = true;
} else {
iocp = new Iocp(null, pool).start();
isDefaultIocp = false;
}
try {
return new
WindowsAsynchronousFileChannelImpl(fdo, reading, writing, iocp, isDefaultIocp);
} catch (IOException x) {
// error binding to port so need to close it (if created for this channel)
if (!isDefaultIocp)
iocp.implClose();
throw x;
}
}
private static int writeFromNativeBuffer(FileDescriptor fd, ByteBuffer bb,
long position, NativeDispatcher nd)
throws IOException
{
int pos = bb.position();
int lim = bb.limit();
assert (pos <= lim);
int rem = (pos <= lim ? lim - pos : 0);
int written = 0;
if (rem == 0)
return 0;
if (position != -1) {
written = nd.pwrite(fd,
((DirectBuffer)bb).address() + pos,
rem, position);
} else {
written = nd.write(fd, ((DirectBuffer)bb).address() + pos, rem);
}
if (written > 0)
bb.position(pos + written);
return written;
}
private static int writeFromNativeBuffer(FileDescriptor fd, ByteBuffer bb,
long position, NativeDispatcher nd)
throws IOException
{
int pos = bb.position();
int lim = bb.limit();
assert (pos <= lim);
int rem = (pos <= lim ? lim - pos : 0);
int written = 0;
if (rem == 0)
return 0;
if (position != -1) {
written = nd.pwrite(fd,
((DirectBuffer)bb).address() + pos,
rem, position);
} else {
written = nd.write(fd, ((DirectBuffer)bb).address() + pos, rem);
}
if (written > 0)
bb.position(pos + written);
return written;
}
@Override
public SctpChannel branch(Association association)
throws IOException {
synchronized (stateLock) {
checkAssociation(association);
if (!isOpen())
throw new ClosedChannelException();
FileDescriptor bFd = SctpNet.branch(fdVal,
association.associationID());
/* successfully branched, we can now remove it from assoc list */
removeAssociation(association);
return new SctpChannelImpl(provider(), bFd, association);
}
}
@Override
public SctpChannel branch(Association association)
throws IOException {
synchronized (stateLock) {
checkAssociation(association);
if (!isOpen())
throw new ClosedChannelException();
FileDescriptor bFd = SctpNet.branch(fdVal,
association.associationID());
/* successfully branched, we can now remove it from assoc list */
removeAssociation(association);
return new SctpChannelImpl(provider(), bFd, association);
}
}
private int receive(FileDescriptor fd, ByteBuffer dst)
throws IOException
{
int pos = dst.position();
int lim = dst.limit();
assert (pos <= lim);
int rem = (pos <= lim ? lim - pos : 0);
if (dst instanceof DirectBuffer && rem > 0)
return receiveIntoNativeBuffer(fd, dst, rem, pos);
// Substitute a native buffer. If the supplied buffer is empty
// we must instead use a nonempty buffer, otherwise the call
// will not block waiting for a datagram on some platforms.
int newSize = Math.max(rem, 1);
ByteBuffer bb = Util.getTemporaryDirectBuffer(newSize);
try {
int n = receiveIntoNativeBuffer(fd, bb, newSize, 0);
bb.flip();
if (n > 0 && rem > 0)
dst.put(bb);
return n;
} finally {
Util.releaseTemporaryDirectBuffer(bb);
}
}
/**
* Constructor for sockets obtained from branching
*/
public SctpChannelImpl(SelectorProvider provider,
FileDescriptor fd,
Association association)
throws IOException {
super(provider);
this.fd = fd;
this.fdVal = IOUtil.fdVal(fd);
this.state = ChannelState.CONNECTED;
port = (Net.localAddress(fd)).getPort();
if (association != null) { /* branched */
this.association = association;
} else { /* obtained from server channel */
/* Receive COMM_UP */
ByteBuffer buf = Util.getTemporaryDirectBuffer(50);
try {
receive(buf, null, null, true);
} finally {
Util.releaseTemporaryDirectBuffer(buf);
}
}
}
/**
* Invoke prior to connecting an unbound TCP socket.
*/
public static void beforeTcpConnect(FileDescriptor fdObj,
InetAddress address,
int port)
throws IOException
{
provider.implBeforeTcpConnect(fdObj, address, port);
}
public static FileKey create(FileDescriptor fd) {
FileKey fk = new FileKey();
try {
fk.init(fd);
} catch (IOException ioe) {
throw new Error(ioe);
}
return fk;
}
/**
* Invoke prior to binding a TCP socket.
*/
public static void beforeTcpBind(FileDescriptor fdObj,
InetAddress address,
int port)
throws IOException
{
// nothing to do
}
void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
writer.print(prefix); writer.print("mInterface=");
writer.println(mInterface.asBinder());
writer.print(prefix); writer.print("mCallingPackage="); writer.print(mCallingPackage);
writer.print(" mCallingUid="); UserHandle.formatUid(writer, mCallingUid);
writer.println();
writer.print(prefix); writer.print("mCallback=");
writer.println(mCallback.asBinder());
if (mExtras != null) {
writer.print(prefix); writer.print("mExtras=");
writer.println(mExtras);
}
}
@Override // Binder call
protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
final long ident = Binder.clearCallingIdentity();
try {
dumpInternal(pw);
} finally {
Binder.restoreCallingIdentity(ident);
}
}
void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
super.dump(prefix, fd, writer, args);
writer.print(prefix); writer.print("mPrompt="); writer.println(mPrompt);
if (mExtras != null) {
writer.print(prefix); writer.print("mExtras="); writer.println(mExtras);
}
}
public IpSecUdpEncapResponse(int inStatus, int inResourceId, int inPort, FileDescriptor inFd)
throws IOException {
if (inStatus == IpSecManager.Status.OK && inFd == null) {
throw new IllegalArgumentException("Valid status implies FD must be non-null");
}
status = inStatus;
resourceId = inResourceId;
port = inPort;
fileDescriptor = (status == IpSecManager.Status.OK) ? ParcelFileDescriptor.dup(inFd) : null;
}
void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
super.dump(prefix, fd, writer, args);
writer.print(prefix); writer.print("mPrompt=");
writer.println(mPrompt);
if (mOptions != null) {
writer.print(prefix); writer.println("Options:");
for (int i=0; i<mOptions.length; i++) {
VoiceInteractor.PickOptionRequest.Option op = mOptions[i];
writer.print(prefix); writer.print(" #"); writer.print(i); writer.println(":");
writer.print(prefix); writer.print(" mLabel=");
writer.println(op.getLabel());
writer.print(prefix); writer.print(" mIndex=");
writer.println(op.getIndex());
if (op.countSynonyms() > 0) {
writer.print(prefix); writer.println(" Synonyms:");
for (int j=0; j<op.countSynonyms(); j++) {
writer.print(prefix); writer.print(" #"); writer.print(j);
writer.print(": "); writer.println(op.getSynonymAt(j));
}
}
if (op.getExtras() != null) {
writer.print(prefix); writer.print(" mExtras=");
writer.println(op.getExtras());
}
}
}
}
@Override
public void setOption(FileDescriptor fd, SocketOption<?> option, Object value)
throws SocketException
{
throw new UnsupportedOperationException(
"no extended options: " + option.name());
}
/**
* Creates and returns a file lock table for a channel that is connected to
* the a system-wide map of all file locks for the Java virtual machine.
*/
public static FileLockTable newSharedFileLockTable(Channel channel,
FileDescriptor fd)
throws IOException
{
return new SharedFileLockTable(channel, fd);
}
/**
* Print the Loader's state into the given stream.
*
* @param prefix Text to print at the front of each line.
* @param fd The raw file descriptor that the dump is being sent to.
* @param writer A PrintWriter to which the dump is to be set.
* @param args Additional arguments to the dump request.
*/
public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
writer.print(prefix); writer.print("mId="); writer.print(mId);
writer.print(" mListener="); writer.println(mListener);
if (mStarted || mContentChanged || mProcessingChange) {
writer.print(prefix); writer.print("mStarted="); writer.print(mStarted);
writer.print(" mContentChanged="); writer.print(mContentChanged);
writer.print(" mProcessingChange="); writer.println(mProcessingChange);
}
if (mAbandoned || mReset) {
writer.print(prefix); writer.print("mAbandoned="); writer.print(mAbandoned);
writer.print(" mReset="); writer.println(mReset);
}
}
@Override // Binder call
public void onShellCommand(FileDescriptor in, FileDescriptor out,
FileDescriptor err, String[] args, ShellCallback callback,
ResultReceiver resultReceiver) {
final long token = Binder.clearCallingIdentity();
try {
DisplayManagerShellCommand command = new DisplayManagerShellCommand(this);
command.exec(this, in, out, err, args, callback, resultReceiver);
} finally {
Binder.restoreCallingIdentity(token);
}
}
/**
* Accept a connection on a socket.
*
* @implNote Wrap native call to allow instrumentation.
*/
private int accept(FileDescriptor ssfd, FileDescriptor newfd,
InetSocketAddress[] isaa)
throws IOException
{
return accept0(ssfd, newfd, isaa);
}
/**
* Constructs a file channel by opening a file using a dfd/path pair
*/
static FileChannel newFileChannel(int dfd,
UnixPath path,
String pathForPermissionCheck,
Set<? extends OpenOption> options,
int mode)
throws UnixException
{
Flags flags = Flags.toFlags(options);
// default is reading; append => writing
if (!flags.read && !flags.write) {
if (flags.append) {
flags.write = true;
} else {
flags.read = true;
}
}
// validation
if (flags.read && flags.append)
throw new IllegalArgumentException("READ + APPEND not allowed");
if (flags.append && flags.truncateExisting)
throw new IllegalArgumentException("APPEND + TRUNCATE_EXISTING not allowed");
FileDescriptor fdObj = open(dfd, path, pathForPermissionCheck, flags, mode);
return FileChannelImpl.open(fdObj, path.toString(), flags.read, flags.write, flags.append, null);
}
public static void main(String args[]) throws IOException {
// close FileDescriptor.in
(new FileInputStream(FileDescriptor.in)).close();
// get the inherited channel
if (System.inheritedChannel() != null) {
throw new RuntimeException("inherited channel not null - unexpected!");
}
}
FileDescriptor duplicateForMapping(FileDescriptor fd) throws IOException {
// on Windows we need to keep a handle to the file
JavaIOFileDescriptorAccess fdAccess =
SharedSecrets.getJavaIOFileDescriptorAccess();
FileDescriptor result = new FileDescriptor();
long handle = duplicateHandle(fdAccess.getHandle(fd));
fdAccess.setHandle(result, handle);
return result;
}
/**
* 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;
}
}
public static FileKey create(FileDescriptor fd) {
FileKey fk = new FileKey();
try {
fk.init(fd);
} catch (IOException ioe) {
throw new Error(ioe);
}
return fk;
}
InheritedDatagramChannelImpl(SelectorProvider sp,
FileDescriptor fd)
throws IOException
{
super(sp, fd);
}