@Override public void posixFadviseIfPossible(String name, FileDescriptor fd, long offset, long len, int flags) throws NativeIOException { if ((len < 0) || (len > Integer.MAX_VALUE)) { throw new RuntimeException("invalid length of " + len + " passed to posixFadviseIfPossible"); } if ((offset < 0) || (offset > Integer.MAX_VALUE)) { throw new RuntimeException("invalid offset of " + offset + " passed to posixFadviseIfPossible"); } Stats stats = map.get(name); if (stats == null) { stats = new Stats(name); map.put(name, stats); } stats.fadvise((int)offset, (int)len, flags); super.posixFadviseIfPossible(name, fd, offset, len, flags); }
/** * java.io always writes every byte it's asked to, or fails with an error. (That is, unlike * Unix it never just writes as many bytes as happens to be convenient.) */ public static void write(FileDescriptor fd, byte[] bytes, int byteOffset, int byteCount) throws IOException { ArrayUtils.checkOffsetAndCount(bytes.length, byteOffset, byteCount); if (byteCount == 0) { return; } try { while (byteCount > 0) { int bytesWritten = Os.write(fd, bytes, byteOffset, byteCount); byteCount -= bytesWritten; byteOffset += bytesWritten; } } catch (ErrnoException errnoException) { throw new IOException(errnoException); } }
public static String getOwner(FileDescriptor fd) throws IOException { ensureInitialized(); if (Shell.WINDOWS) { String owner = Windows.getOwner(fd); owner = stripDomain(owner); return owner; } else { long uid = POSIX.getUIDforFDOwnerforOwner(fd); CachedUid cUid = uidCache.get(uid); long now = System.currentTimeMillis(); if (cUid != null && (cUid.timestamp + cacheTimeout) > now) { return cUid.username; } String user = POSIX.getUserName(uid); LOG.info("Got UserName " + user + " for UID " + uid + " from the native implementation"); cUid = new CachedUid(user, now); uidCache.put(uid, cUid); return user; } }
/** * fsync OFF. * FileDescriptor#sync() should never be called. * @throws Exception . */ @Test public void testStoreTemporaryBarFile2() throws Exception { boolean fsyncEnabled = PersoniumUnitConfig.getFsyncEnabled(); PersoniumUnitConfig.set(BinaryData.FSYNC_ENABLED, "false"); try { CellEsImpl cell = new CellEsImpl(); cell.setId("hogeCell"); BarFileInstaller bfi = Mockito.spy(new BarFileInstaller(cell, "hogeBox", null, null)); Method method = BarFileInstaller.class.getDeclaredMethod( "storeTemporaryBarFile", new Class<?>[] {InputStream.class}); method.setAccessible(true); //any file method.invoke(bfi, new FileInputStream("pom.xml")); Mockito.verify(bfi, Mockito.never()).sync((FileDescriptor) Mockito.anyObject()); } finally { PersoniumUnitConfig.set(BinaryData.FSYNC_ENABLED, String.valueOf(fsyncEnabled)); } }
@Override protected void dump(final FileDescriptor fd, final PrintWriter fout, final String[] args) { super.dump(fd, fout, args); final Printer p = new PrintWriterPrinter(fout); p.println("LatinIME state :"); p.println(" VersionCode = " + ApplicationUtils.getVersionCode(this)); p.println(" VersionName = " + ApplicationUtils.getVersionName(this)); final Keyboard keyboard = mKeyboardSwitcher.getKeyboard(); final int keyboardMode = keyboard != null ? keyboard.mId.mMode : -1; p.println(" Keyboard mode = " + keyboardMode); final SettingsValues settingsValues = mSettings.getCurrent(); p.println(settingsValues.dump()); p.println(mDictionaryFacilitator.dump(this /* context */)); // TODO: Dump all settings values }
public static Bitmap decodeSampledBitmapFromDescriptor(FileDescriptor fileDescriptor, BitmapSize maxSize, Bitmap.Config config) { final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; options.inPurgeable = true; options.inInputShareable = true; BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options); options.inSampleSize = calculateInSampleSize(options, maxSize.getWidth(), maxSize.getHeight()); options.inJustDecodeBounds = false; if (config != null) { options.inPreferredConfig = config; } try { return BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options); } catch (Throwable e) { LogUtils.e(e.getMessage(), e); return null; } }
public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) { super.dump(prefix, fd, writer, args); writer.print(prefix); writer.print("mUri="); writer.println(this.mUri); writer.print(prefix); writer.print("mProjection="); writer.println(Arrays.toString(this.mProjection)); writer.print(prefix); writer.print("mSelection="); writer.println(this.mSelection); writer.print(prefix); writer.print("mSelectionArgs="); writer.println(Arrays.toString(this.mSelectionArgs)); writer.print(prefix); writer.print("mSortOrder="); writer.println(this.mSortOrder); writer.print(prefix); writer.print("mCursor="); writer.println(this.mCursor); writer.print(prefix); writer.print("mContentChanged="); writer.println(this.mContentChanged); }
@Test (timeout = 30000) public void testOpenWithCreate() throws Exception { if (Path.WINDOWS) { return; } LOG.info("Test creating a file with O_CREAT"); FileDescriptor fd = NativeIO.POSIX.open( new File(TEST_DIR, "testWorkingOpen").getAbsolutePath(), NativeIO.POSIX.O_WRONLY | NativeIO.POSIX.O_CREAT, 0700); assertNotNull(true); assertTrue(fd.valid()); FileOutputStream fos = new FileOutputStream(fd); fos.write("foo".getBytes()); fos.close(); assertFalse(fd.valid()); LOG.info("Test exclusive create"); try { fd = NativeIO.POSIX.open( new File(TEST_DIR, "testWorkingOpen").getAbsolutePath(), NativeIO.POSIX.O_WRONLY | NativeIO.POSIX.O_CREAT | NativeIO.POSIX.O_EXCL, 0700); fail("Was able to create existing file with O_EXCL"); } catch (NativeIOException nioe) { LOG.info("Got expected exception for failed exclusive create", nioe); assertEquals(Errno.EEXIST, nioe.getErrno()); } }
/** * Decode and sample down a bitmap from a file input stream to the requested width and height. * * @param fileDescriptor The file descriptor to read from * @param reqWidth The requested width of the resulting bitmap * @param reqHeight The requested height of the resulting bitmap * @param cache The ImageCache used to find candidate bitmaps for use with inBitmap * @return A bitmap sampled down from the original with the same aspect ratio and dimensions * that are equal to or greater than the requested width and height */ public static Bitmap decodeSampledBitmapFromDescriptor( FileDescriptor fileDescriptor, int reqWidth, int reqHeight, ImageCache cache) { // First decode with inJustDecodeBounds=true to check dimensions final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options); // Calculate inSampleSize options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); // Decode bitmap with inSampleSize set options.inJustDecodeBounds = false; // If we're running on Honeycomb or newer, try to use inBitmap if (Utils.hasHoneycomb()) { addInBitmapOptions(options, cache); } return BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options); }
UnixAsynchronousSocketChannelImpl(Port port, FileDescriptor fd, InetSocketAddress remote) throws IOException { super(port, fd, remote); this.fdVal = IOUtil.fdVal(fd); IOUtil.configureBlocking(fd, false); try { port.register(fdVal, this); } catch (ShutdownChannelGroupException x) { // ShutdownChannelGroupException thrown if we attempt to register a // new channel after the group is shutdown throw new IOException(x); } this.port = port; }
private int sendFromManagedBuffer(FileDescriptor fd, ByteBuffer bb, InetSocketAddress target) throws IOException { int pos = bb.position(); int lim = bb.limit(); assert (pos <= lim); int rem = (pos <= lim ? lim - pos : 0); boolean preferIPv6 = (family != StandardProtocolFamily.INET); int written; try { written = send0(preferIPv6, fd, bb.array(), bb.arrayOffset() + pos, rem, target.getAddress(), target.getPort()); } catch (PortUnreachableException pue) { if (isConnected()) throw pue; written = rem; } if (written > 0) bb.position(pos + written); return written; }
/** * Test that opens and closes a file 10000 times - this would crash with * "Too many open files" if we leaked fds using this access pattern. */ @Test (timeout = 30000) public void testFDDoesntLeak() throws IOException { if (Path.WINDOWS) { return; } for (int i = 0; i < 10000; i++) { FileDescriptor fd = NativeIO.POSIX.open( new File(TEST_DIR, "testNoFdLeak").getAbsolutePath(), O_WRONLY | O_CREAT, 0700); assertNotNull(true); assertTrue(fd.valid()); FileOutputStream fos = new FileOutputStream(fd); fos.write("foo".getBytes()); fos.close(); } }
static cli.System.Net.Sockets.Socket getFD(JNIEnv env, TwoStacksPlainSocketImpl _this) { FileDescriptor fdObj = _this.fd; if (fdObj == NULL) { return null; } return fdObj.getSocket(); }
ServerSocketChannelImpl(SelectorProvider sp, FileDescriptor fd, boolean bound) throws IOException { super(sp); this.fd = fd; this.fdVal = IOUtil.fdVal(fd); this.state = ST_INUSE; if (bound) localAddress = Net.localAddress(fd); }
/** * 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); }
/** * 获取bitmap * * @param fd 文件描述 * @param maxWidth 最大宽度 * @param maxHeight 最大高度 * @return bitmap */ public static Bitmap getBitmap(final FileDescriptor fd, final int maxWidth, final int maxHeight) { if (fd == null) return null; BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFileDescriptor(fd, null, options); options.inSampleSize = calculateInSampleSize(options, maxWidth, maxHeight); options.inJustDecodeBounds = false; return BitmapFactory.decodeFileDescriptor(fd, null, options); }
private WindowsAsynchronousFileChannelImpl(FileDescriptor fdObj, boolean reading, boolean writing, Iocp iocp, boolean isDefaultIocp) throws IOException { super(fdObj, reading, writing, iocp.executor()); this.handle = fdAccess.getHandle(fdObj); this.iocp = iocp; this.isDefaultIocp = isDefaultIocp; this.ioCache = new PendingIoCache(); this.completionKey = iocp.associate(this, handle); }
SocketChannelImpl(SelectorProvider sp, FileDescriptor fd, InetSocketAddress remote) throws IOException { super(sp); this.fd = fd; this.fdVal = IOUtil.fdVal(fd); this.state = ST_CONNECTED; this.localAddress = Net.localAddress(fd); this.remoteAddress = remote; }
static void datagramSocketClose(TwoStacksPlainDatagramSocketImpl _this) { /* * REMIND: PUT A LOCK AROUND THIS CODE */ FileDescriptor fdObj = _this.fd; FileDescriptor fd1Obj = _this.fd1; boolean ipv6_supported = ipv6_available(); cli.System.Net.Sockets.Socket fd = null, fd1 = null; if (IS_NULL(fdObj) && (!ipv6_supported || IS_NULL(fd1Obj))) { return; } if (!IS_NULL(fdObj)) { fd = fdObj.getSocket(); if (fd != null) { fdObj.setSocket(null); NET_SocketClose(fd); } } if (ipv6_supported && fd1Obj != NULL) { fd1 = fd1Obj.getSocket(); if (fd1 == null) { return; } fd1Obj.setSocket(null); NET_SocketClose(fd1); } }
private Unmapper(long address, long size, int cap, FileDescriptor fd) { assert (address != 0); this.address = address; this.size = size; this.cap = cap; this.fd = fd; synchronized (Unmapper.class) { count++; totalSize += size; totalCapacity += cap; } }
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); } }
/** * Invoke this option * * @param option Option. * @param argument Option argument. */ @Override public boolean invoke(String option, String argument) { runnerBase.setOutputFile(FileDescriptor.out); return true; }
/** * Call sync_file_range on the given file descriptor. See the manpage * for this syscall for more information. On systems where this * call is not available, does nothing. * * @throws NativeIOException if there is an error with the syscall */ public static void syncFileRangeIfPossible( FileDescriptor fd, long offset, long nbytes, int flags) throws NativeIOException { if (nativeLoaded && syncFileRangePossible) { try { sync_file_range(fd, offset, nbytes, flags); } catch (UnsupportedOperationException uoe) { syncFileRangePossible = false; } catch (UnsatisfiedLinkError ule) { syncFileRangePossible = false; } } }
private void sendShmSuccessResponse(DomainSocket sock, NewShmInfo shmInfo) throws IOException { DataNodeFaultInjector.get().sendShortCircuitShmResponse(); ShortCircuitShmResponseProto.newBuilder().setStatus(SUCCESS). setId(PBHelper.convert(shmInfo.shmId)).build(). writeDelimitedTo(socketOut); // Send the file descriptor for the shared memory segment. byte buf[] = new byte[] { (byte)0 }; FileDescriptor shmFdArray[] = new FileDescriptor[] { shmInfo.stream.getFD() }; sock.sendFileDescriptors(shmFdArray, buf, 0, buf.length); }
private FileChannelImpl(FileDescriptor fd, String path, boolean readable, boolean writable, boolean append, Object parent) { this.fd = fd; this.readable = readable; this.writable = writable; this.append = append; this.parent = parent; this.path = path; this.nd = new FileDispatcherImpl(append); }
/** * 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; } }
/** * Get a streamable output object. * * @param file File. * @param fd File descriptor. * @param name Name for error, warnings, and documentation. */ private StreamableOutput(File file, FileDescriptor fd, String name) { // Exactly one of file or fd must be set assert (file != null) || (fd != null) : "File and file descriptor are both null (exactly one must be null)"; assert (file == null) || (fd == null) : "Neither file nor file descriptor null (exactly one must be null)"; // Set fields this.file = file; this.fd = fd; this.name = name; return; }
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; }
public static boolean copyFile(Context context, Uri bookUri, String toPath){ try { FileDescriptor fd = context.getContentResolver().openFileDescriptor(bookUri, "r").getFileDescriptor(); InputStream in = new FileInputStream(fd); return copyFile(in, toPath); } catch (IOException e){ e.printStackTrace(); return false; } }
public static void decodeBounds(ThreadPool.JobContext jc, FileDescriptor fd, Options options) { Utils.assertTrue(options != null); options.inJustDecodeBounds = true; jc.setCancelListener(new DecodeCanceller(options)); BitmapFactory.decodeFileDescriptor(fd, null, options); options.inJustDecodeBounds = false; }
@Override public void implBeforeTcpBind(FileDescriptor fdObj, InetAddress address, int port) throws IOException { if (enabled) convertTcpToSdpIfMatch(fdObj, Action.BIND, address, port); }
/** * Report download progress through the database if necessary. */ private void updateProgress(FileDescriptor outFd) throws IOException, StopRequestException { final long now = SystemClock.elapsedRealtime(); final long currentBytes = mInfoDelta.mCurrentBytes; final long sampleDelta = now - mSpeedSampleStart; if (sampleDelta > 500) { final long sampleSpeed = ((currentBytes - mSpeedSampleBytes) * 1000) / sampleDelta; if (mSpeed == 0) { mSpeed = sampleSpeed; } else { mSpeed = ((mSpeed * 3) + sampleSpeed) / 4; } // Only notify once we have a full sample window if (mSpeedSampleStart != 0) { mNotifier.notifyDownloadSpeed(mId, mSpeed); } mSpeedSampleStart = now; mSpeedSampleBytes = currentBytes; } final long bytesDelta = currentBytes - mLastUpdateBytes; final long timeDelta = now - mLastUpdateTime; if (bytesDelta > Constants.MIN_PROGRESS_STEP && timeDelta > Constants.MIN_PROGRESS_TIME) { // fsync() to ensure that current progress has been flushed to disk, // so we can always resume based on latest database information. outFd.sync(); mInfoDelta.writeToDatabaseOrThrow(); mLastUpdateBytes = currentBytes; mLastUpdateTime = now; } }
/** * 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); }
/** * Call posix_fadvise on the given file descriptor. See the manpage * for this syscall for more information. On systems where this * call is not available, does nothing. * * @throws NativeIOException if there is an error with the syscall */ static void posixFadviseIfPossible(String identifier, FileDescriptor fd, long offset, long len, int flags) throws NativeIOException { if (nativeLoaded && fadvisePossible) { try { posix_fadvise(fd, offset, len, flags); } catch (UnsatisfiedLinkError ule) { fadvisePossible = false; } } }
protected AsynchronousFileChannelImpl(FileDescriptor fdObj, boolean reading, boolean writing, ExecutorService executor) { this.fdObj = fdObj; this.reading = reading; this.writing = writing; this.executor = executor; }
static final MappedByteBuffer createDummyMbbInstance(final long nativeBaseAddress) throws RuntimeException { try { final Class<?> cl = Class.forName("java.nio.DirectByteBuffer"); final Constructor<?> ctor = cl.getDeclaredConstructor(int.class, long.class, FileDescriptor.class, Runnable.class); ctor.setAccessible(true); final MappedByteBuffer mbb = (MappedByteBuffer) ctor.newInstance(0, // some junk capacity nativeBaseAddress, null, null); return mbb; } catch (final Exception e) { throw new RuntimeException( "Could not create Dummy MappedByteBuffer instance: " + e.getClass()); } }
@Override final Object attachForeignChannel(final Channel channel, FileDescriptor fd) { int fdVal = IOUtil.fdVal(fd); register(fdVal, new PollableChannel() { public void onEvent(int events, boolean mayInvokeDirect) { } public void close() throws IOException { channel.close(); } }); return Integer.valueOf(fdVal); }