public void saveCache(
     JMXInstrumentedCache<K, V> cache, File savedCachePath, Function<K, byte[]> converter)
     throws IOException {
   long start = System.currentTimeMillis();
   String msgSuffix = " " + savedCachePath.getName() + " for " + cfname + " of " + ksname;
   logger.debug("saving" + msgSuffix);
   int count = 0;
   File tmpFile =
       File.createTempFile(savedCachePath.getName(), null, savedCachePath.getParentFile());
   FileOutputStream fout = new FileOutputStream(tmpFile);
   ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(fout));
   FileDescriptor fd = fout.getFD();
   for (K key : cache.getKeySet()) {
     byte[] bytes = converter.apply(key);
     out.writeInt(bytes.length);
     out.write(bytes);
     ++count;
   }
   out.flush();
   fd.sync();
   out.close();
   if (!tmpFile.renameTo(savedCachePath))
     throw new IOException("Unable to rename cache to " + savedCachePath);
   if (logger.isDebugEnabled())
     logger.debug(
         "saved "
             + count
             + " keys in "
             + (System.currentTimeMillis() - start)
             + " ms from"
             + msgSuffix);
 }
 public static ParcelFileDescriptor fromFd(int fd) throws IOException {
   FileDescriptor original = new FileDescriptor();
   original.setInt$(fd);
   try {
     return new ParcelFileDescriptor(Os.dup(original));
   } catch (ErrnoException e) {
     throw e.rethrowAsIOException();
   }
 }
 int truncate(FileDescriptor fd, long size) throws IOException {
     if (append) {
         // HACK in append mode we're not allowed to truncate, so we try to reopen the file and truncate that
         try (FileOutputStream fos = new FileOutputStream(((FileStream)fd.getStream()).get_Name())) {
             fos.getFD().setLength(size);
         }
     } else {
         fd.setLength(size);
     }
     return 0;
 }
 public PlainDatagramSocketImpl(FileDescriptor fd, int localPort) {
   this.fd = fd;
   this.localPort = localPort;
   if (fd.valid()) {
     guard.open("close");
   }
 }
 long read(FileDescriptor fd, ByteBuffer[] bufs, int offset, int length) throws IOException {
     long totalRead = 0;
     try
     {
         for (int i = offset; i < offset + length; i++)
         {
             int size = bufs[i].remaining();
             if (size > 0)
             {
                 int read = IOUtil.read(fd, bufs[i], -1, this, this);
                 if (read < 0)
                 {
                     break;
                 }
                 totalRead += read;
                 if (read < size || fd.available() == 0)
                 {
                     break;
                 }
             }
         }
     }
     catch (IOException x)
     {
         if (totalRead == 0)
         {
             throw x;
         }
     }
     return totalRead;
 }
  /**
   * 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());
  }
 private int connectImpl(InetAddress remote, int remotePort, int trafficClass) throws IOException {
   try {
     if (false) throw new cli.System.Net.Sockets.SocketException();
     if (false) throw new cli.System.ObjectDisposedException("");
     cli.System.Net.IPEndPoint ep =
         new cli.System.Net.IPEndPoint(
             PlainSocketImpl.getAddressFromInetAddress(remote), remotePort);
     if (isBlocking()) {
       fd.getSocket().Connect(ep);
       return 1;
     } else {
       asyncConnect = fd.getSocket().BeginConnect(ep, null, null);
       return IOStatus.UNAVAILABLE;
     }
   } catch (cli.System.Net.Sockets.SocketException x) {
     throw new ConnectException(x.getMessage());
   } catch (cli.System.ObjectDisposedException x1) {
     throw new SocketException("Socket is closed");
   }
 }
 private int checkConnect(FileDescriptor fd, boolean block, boolean ready) throws IOException {
   try {
     if (false) throw new cli.System.Net.Sockets.SocketException();
     if (false) throw new cli.System.ObjectDisposedException("");
     if (block || ready || asyncConnect.get_IsCompleted()) {
       cli.System.IAsyncResult res = asyncConnect;
       asyncConnect = null;
       fd.getSocket().EndConnect(res);
       // work around for blocking issue
       fd.getSocket().set_Blocking(isBlocking());
       return 1;
     } else {
       return IOStatus.UNAVAILABLE;
     }
   } catch (cli.System.Net.Sockets.SocketException x) {
     throw new ConnectException(x.getMessage());
   } catch (cli.System.ObjectDisposedException x1) {
     throw new SocketException("Socket is closed");
   }
 }
  /**
   * Registers a server socket for zygote command connections
   *
   * @throws RuntimeException when open fails
   */
  private static void registerZygoteSocket(String socketName) {
    if (sServerSocket == null) {
      int fileDesc;
      final String fullSocketName = ANDROID_SOCKET_PREFIX + socketName;
      try {
        String env = System.getenv(fullSocketName);
        fileDesc = Integer.parseInt(env);
      } catch (RuntimeException ex) {
        throw new RuntimeException(fullSocketName + " unset or invalid", ex);
      }

      try {
        FileDescriptor fd = new FileDescriptor();
        fd.setInt$(fileDesc);
        sServerSocket = new LocalServerSocket(fd);
      } catch (IOException ex) {
        throw new RuntimeException("Error binding to local socket '" + fileDesc + "'", ex);
      }
    }
  }
 private void closeImpl() throws IOException {
   try {
     if (false) throw new cli.System.Net.Sockets.SocketException();
     if (false) throw new cli.System.ObjectDisposedException("");
     fd.getSocket().Close();
   } catch (cli.System.Net.Sockets.SocketException x) {
     throw PlainSocketImpl.convertSocketExceptionToIOException(x);
   } catch (cli.System.ObjectDisposedException x1) {
     throw new SocketException("Socket is closed");
   }
 }
Exemple #11
0
  /**
   * Get system file descriptor from FileDescriptor object.
   *
   * @param descriptor - FileDescriptor objec to get fd from
   * @return file descriptor, -1 or error
   */
  public static int getfd(FileDescriptor descriptor) {
    Field field = FBUtilities.getProtectedField(descriptor.getClass(), "fd");

    if (field == null) return -1;

    try {
      return field.getInt(descriptor);
    } catch (Exception e) {
      logger.warn("unable to read fd field from FileDescriptor");
    }

    return -1;
  }
Exemple #12
0
 private void testFile(DataOutputStream out) throws IOException {
   File file = new File("test.txt");
   if (file.exists()) {
     file.delete();
   }
   RandomAccessFile write = new RandomAccessFile(file, "rws");
   // RandomAccessFile write = new RandomAccessFile(file, "rwd");
   int fileSize = 10 * 1024 * 1024;
   FileUtils.setLength(write, fileSize);
   write.seek(0);
   int i = 0;
   FileDescriptor fd = write.getFD();
   while (true) {
     if (write.getFilePointer() >= fileSize) {
       break;
     }
     write.writeBytes(i + "\r\n");
     fd.sync();
     out.writeInt(i);
     out.flush();
     i++;
   }
   write.close();
 }
 private static void shutdown(FileDescriptor fd, int how) throws IOException {
   try {
     if (false) throw new cli.System.Net.Sockets.SocketException();
     if (false) throw new cli.System.ObjectDisposedException("");
     fd.getSocket()
         .Shutdown(
             cli.System.Net.Sockets.SocketShutdown.wrap(
                 how == SHUT_RD
                     ? cli.System.Net.Sockets.SocketShutdown.Receive
                     : cli.System.Net.Sockets.SocketShutdown.Send));
   } catch (cli.System.Net.Sockets.SocketException x) {
     throw PlainSocketImpl.convertSocketExceptionToIOException(x);
   } catch (cli.System.ObjectDisposedException x1) {
     throw new SocketException("Socket is closed");
   }
 }
 @cli.System.Security.SecuritySafeCriticalAttribute.Annotation
 void release(FileDescriptor fd, long pos, long size) throws IOException {
     FileStream fs = (FileStream)fd.getStream();
     if (WINDOWS)
     {
         int ERROR_NOT_LOCKED = 158;
         OVERLAPPED o = new OVERLAPPED();
         o.OffsetLow = (int)pos;
         o.OffsetHigh = (int)(pos >> 32);
         int result = UnlockFileEx(fs.get_SafeFileHandle(), 0, (int)size, (int)(size >> 32), o);
         if (result == 0 && Marshal.GetLastWin32Error() != ERROR_NOT_LOCKED)
         {
             throw new IOException("Release failed");
         }
     }
     else
     {
         try
         {
             if (false) throw new cli.System.ArgumentOutOfRangeException();
             if (false) throw new cli.System.IO.IOException();
             if (false) throw new cli.System.ObjectDisposedException("");
             fs.Unlock(pos, size);
         }
         catch (cli.System.IO.IOException x)
         {
             if (!NotLockedHack.isErrorNotLocked(x))
             {
                 throw new IOException(x.getMessage());
             }
         }
         catch (cli.System.ArgumentOutOfRangeException
             | cli.System.ObjectDisposedException x)
         {
             throw new IOException(x.getMessage());
         }
     }
 }
  public void testLocalConnections() throws IOException {
    // create client and server socket
    LocalServerSocket localServerSocket = new LocalServerSocket(mSockAddr);
    LocalSocket clientSocket = new LocalSocket();

    // establish connection between client and server
    LocalSocketAddress locSockAddr = new LocalSocketAddress(mSockAddr);
    assertFalse(clientSocket.isConnected());
    clientSocket.connect(locSockAddr);
    assertTrue(clientSocket.isConnected());
    LocalSocket serverSocket = localServerSocket.accept();

    Credentials credent = clientSocket.getPeerCredentials();
    assertTrue(0 != credent.getPid());

    // send data from client to server
    OutputStream clientOutStream = clientSocket.getOutputStream();
    clientOutStream.write(12);
    InputStream serverInStream = serverSocket.getInputStream();
    assertEquals(12, serverInStream.read());

    // send data from server to client
    OutputStream serverOutStream = serverSocket.getOutputStream();
    serverOutStream.write(3);
    InputStream clientInStream = clientSocket.getInputStream();
    assertEquals(3, clientInStream.read());

    // Test sending and receiving file descriptors
    clientSocket.setFileDescriptorsForSend(new FileDescriptor[] {FileDescriptor.in});
    clientOutStream.write(32);
    assertEquals(32, serverInStream.read());

    FileDescriptor[] out = serverSocket.getAncillaryFileDescriptors();
    assertEquals(1, out.length);
    FileDescriptor fd = clientSocket.getFileDescriptor();
    assertTrue(fd.valid());

    // shutdown input stream of client
    clientSocket.shutdownInput();
    assertEquals(-1, clientInStream.read());

    // shutdown output stream of client
    clientSocket.shutdownOutput();
    try {
      clientOutStream.write(10);
      fail("testLocalSocket shouldn't come to here");
    } catch (IOException e) {
      // expected
    }

    // shutdown input stream of server
    serverSocket.shutdownInput();
    assertEquals(-1, serverInStream.read());

    // shutdown output stream of server
    serverSocket.shutdownOutput();
    try {
      serverOutStream.write(10);
      fail("testLocalSocket shouldn't come to here");
    } catch (IOException e) {
      // expected
    }

    // close client socket
    clientSocket.close();
    try {
      clientInStream.read();
      fail("testLocalSocket shouldn't come to here");
    } catch (IOException e) {
      // expected
    }

    // close server socket
    serverSocket.close();
    try {
      serverInStream.read();
      fail("testLocalSocket shouldn't come to here");
    } catch (IOException e) {
      // expected
    }
  }
 private static FileDescriptor standardStream(int fd) {
   FileDescriptor desc = new FileDescriptor();
   desc.handle = set(fd);
   return desc;
 }
 public void dumpAsync(FileDescriptor fd, String[] args) throws RemoteException {
   fd.addTaint(args[0].getTaint());
 }
 public static ParcelFileDescriptor adoptFd(int fd) {
   FileDescriptor fdesc = new FileDescriptor();
   fdesc.setInt$(fd);
   return new ParcelFileDescriptor(fdesc);
 }
 int force(FileDescriptor fd, boolean metaData) throws IOException {
     fd.sync();
     return 0;
 }
 static void testDescriptorValidity(Closeable fp, FileDescriptor fd) throws IOException {
   System.out.println(fd.valid());
   fp.close();
   System.out.println(fd.valid());
 }
 long size(FileDescriptor fd) throws IOException {
     return fd.length();
 }
 @cli.System.Security.SecuritySafeCriticalAttribute.Annotation
 int lock(FileDescriptor fd, boolean blocking, long pos, long size,
          boolean shared) throws IOException
 {
     FileStream fs = (FileStream)fd.getStream();
     if (WINDOWS)
     {
         int LOCKFILE_FAIL_IMMEDIATELY = 1;
         int LOCKFILE_EXCLUSIVE_LOCK = 2;
         int ERROR_LOCK_VIOLATION = 33;
         int flags = 0;
         OVERLAPPED o = new OVERLAPPED();
         o.OffsetLow = (int)pos;
         o.OffsetHigh = (int)(pos >> 32);
         if (!blocking)
         {
             flags |= LOCKFILE_FAIL_IMMEDIATELY;
         }
         if (!shared)
         {
             flags |= LOCKFILE_EXCLUSIVE_LOCK;
         }
         int result = LockFileEx(fs.get_SafeFileHandle(), flags, 0, (int)size, (int)(size >> 32), o);
         if (result == 0)
         {
             int error = Marshal.GetLastWin32Error();
             if (!blocking && error == ERROR_LOCK_VIOLATION)
             {
                 return NO_LOCK;
             }
             throw new IOException("Lock failed");
         }
         return LOCKED;
     }
     else
     {
         try
         {
             if (false) throw new cli.System.ArgumentOutOfRangeException();
             for (;;)
             {
                 try
                 {
                     if (false) throw new cli.System.IO.IOException();
                     if (false) throw new cli.System.ObjectDisposedException("");
                     fs.Lock(pos, size);
                     return shared ? RET_EX_LOCK : LOCKED;
                 }
                 catch (cli.System.IO.IOException x)
                 {
                     if (!blocking)
                     {
                         return NO_LOCK;
                     }
                     cli.System.Threading.Thread.Sleep(100);
                 }
                 catch (cli.System.ObjectDisposedException x)
                 {
                     throw new IOException(x.getMessage());
                 }
             }
         }
         catch (cli.System.ArgumentOutOfRangeException x)
         {
             throw new IOException(x.getMessage());
         }
     }
 }
 void close(FileDescriptor fd) throws IOException {
     fd.close();
 }
 int write(FileDescriptor fd, byte[] buf, int offset, int length) throws IOException {
     fd.writeBytes(buf, offset, length);
     return length;
 }
 int read(FileDescriptor fd, byte[] buf, int offset, int length) throws IOException {
     return fd.readBytes(buf, offset, length);
 }