Java Code Examples for java.nio.channels.FileChannel#lock()

The following examples show how to use java.nio.channels.FileChannel#lock() . 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: LockedInputStream.java    From ade with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Opens an input stream and locks the underlying file.
 * Locking is done via the @java.nio.channels.FileLock class.
 * On windows, this is just like a normal input stream.  
 * On Linux and the likes it uses an "fcntl" type lock.
 * REMEMBER TO CLOSE THE INPUT STREAM.
 * @param filename to open
 * @throws FileNotFoundException
 * @throws AdeUsageException
 */
public LockedInputStream(final String filename) throws FileNotFoundException, AdeUsageException {
    m_lock = null;
    m_filename = filename;
    // Get a file channel for the file
    m_raf = new RandomAccessFile(filename, "rw");
    FileChannel channel = m_raf.getChannel();

    // Use the file channel to create a lock on the file.
    // This method blocks until it can retrieve the lock.
    try {
        m_lock = channel.lock();
    } catch (IOException e) {
        throw new AdeUsageException("Failed locking " + filename, e);
    }

}
 
Example 2
Source File: FileManager.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Override
protected synchronized void write(final byte[] bytes, final int offset, final int length,
        final boolean immediateFlush) {
    if (isLocking) {
        try {
            @SuppressWarnings("resource")
            final FileChannel channel = ((FileOutputStream) getOutputStream()).getChannel();
            /*
             * Lock the whole file. This could be optimized to only lock from the current file position. Note that
             * locking may be advisory on some systems and mandatory on others, so locking just from the current
             * position would allow reading on systems where locking is mandatory. Also, Java 6 will throw an
             * exception if the region of the file is already locked by another FileChannel in the same JVM.
             * Hopefully, that will be avoided since every file should have a single file manager - unless two
             * different files strings are configured that somehow map to the same file.
             */
            try (final FileLock lock = channel.lock(0, Long.MAX_VALUE, false)) {
                super.write(bytes, offset, length, immediateFlush);
            }
        } catch (final IOException ex) {
            throw new AppenderLoggingException("Unable to obtain lock on " + getName(), ex);
        }
    } else {
        super.write(bytes, offset, length, immediateFlush);
    }
}
 
Example 3
Source File: CliMain.java    From btrbck with GNU General Public License v3.0 6 votes vote down vote up
private StreamRepository readAndLockRepository() {
	File path = repositoryLocation;
	if (path == null) {
		path = Paths.get("").toFile();
	}
	StreamRepository repo = streamRepositoryService.readRepository(path
			.toPath());
	FileChannel f;
	try {
		if (!repo.getRepositoryLockFile().toFile().exists())
			throw new DisplayException(
					"Lock file not found: is this a stream repository?");
		f = FileChannel.open(repo.getRepositoryLockFile(),
				StandardOpenOption.WRITE);
		repositoryLock = f.lock(0L, Long.MAX_VALUE, false);
	}
	catch (IOException e) {
		throw new RuntimeException("Error while locking repository", e);
	}
	return repo;
}
 
Example 4
Source File: RawDataFileImpl.java    From mzmine2 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Opens the given file as a data points file for this RawDataFileImpl instance. If the file is
 * not empty, the TreeMaps supplied as parameters have to describe the mapping of storage IDs to
 * data points in the file.
 */
public synchronized void openDataPointsFile(File dataPointsFileName) throws IOException {

  if (this.dataPointsFile != null) {
    throw new IOException("Cannot open another data points file, because one is already open");
  }

  this.dataPointsFileName = dataPointsFileName;
  this.dataPointsFile = new RandomAccessFile(dataPointsFileName, "rw");

  // Locks the temporary file so it is not removed when another instance
  // of MZmine is starting. Lock will be automatically released when this
  // instance of MZmine exits. Locking may fail on network-mounted filesystems.
  try {
    FileChannel fileChannel = dataPointsFile.getChannel();
    fileChannel.lock();
  } catch (IOException e) {
    logger.log(Level.WARNING, "Failed to lock the file " + dataPointsFileName, e);
  }

  // Unfortunately, deleteOnExit() doesn't work on Windows, see JDK
  // bug #4171239. We will try to remove the temporary files in a
  // shutdown hook registered in the main.ShutDownHook class
  dataPointsFileName.deleteOnExit();

}
 
Example 5
Source File: SignalAccount.java    From signal-cli with GNU General Public License v3.0 5 votes vote down vote up
private static Pair<FileChannel, FileLock> openFileChannel(String fileName) throws IOException {
    FileChannel fileChannel = new RandomAccessFile(new File(fileName), "rw").getChannel();
    FileLock lock = fileChannel.tryLock();
    if (lock == null) {
        System.err.println("Config file is in use by another instance, waiting…");
        lock = fileChannel.lock();
        System.err.println("Config file lock acquired.");
    }
    return new Pair<>(fileChannel, lock);
}
 
Example 6
Source File: FileChannelTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
private void useFileChannel() throws IOException {
  File file = File.createTempFile("j2objc", "tmp");
  ChannelGetter channelGetter = new ChannelGetter();

  channelGetter.createChannel(file);
  // The FileOutputStream used to create the channel is released at this point.

  FileChannel channel = channelGetter.get();
  FileLock lock = channel.lock();
  lock.close();
  channel.close();
  assertTrue(file.delete());
}
 
Example 7
Source File: IOUtils.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
/**
 * Why it's synchronized : if the same JVM try to lock file, we got an java.nio.channels.OverlappingFileLockException.
 * So we need to block until the file is totally written.
 */
public static synchronized File exportResourceToTemp(String resource, String tempFileNamePrefix, String tempFileNameExtension) {
    try (InputStream resourceStream = IOUtils.class.getResourceAsStream("/" + resource)) {
        if (resourceStream == null) {
            throw new IllegalStateException(resource + " not found");
        }
        String hash = md5Hash(IOUtils.class.getResourceAsStream("/" + resource));
        File tempFile = new File(System.getProperty("java.io.tmpdir"), tempFileNamePrefix + "-" + hash + tempFileNameExtension);
        if (!tempFile.exists()) {
            try (FileOutputStream out = new FileOutputStream(tempFile)) {
                FileChannel channel = out.getChannel();
                // If multiple JVM start on same compute, they can write in same file
                // and this file will be corrupted.
                try (FileLock ignored = channel.lock()) {
                    if (tempFile.length() == 0) {
                        byte[] buffer = new byte[1024];
                        for (int length; (length = resourceStream.read(buffer)) != -1; ) {
                            out.write(buffer, 0, length);
                        }
                    }
                }
            }
        } else if (!md5Hash(new FileInputStream(tempFile)).equals(hash)) {
            throw new IllegalStateException("Invalid MD5 checksum of " + tempFile + ". Please delete this file.");
        }
        return tempFile;
    } catch (NoSuchAlgorithmException | IOException e) {
        throw new IllegalStateException(e);
    }
}
 
Example 8
Source File: RawDataFileImpl.java    From mzmine3 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Opens the given file as a data points file for this RawDataFileImpl instance. If the file is
 * not empty, the TreeMaps supplied as parameters have to describe the mapping of storage IDs to
 * data points in the file.
 */
public synchronized void openDataPointsFile(File dataPointsFileName) throws IOException {

  if (this.dataPointsFile != null) {
    throw new IOException("Cannot open another data points file, because one is already open");
  }

  this.dataPointsFileName = dataPointsFileName;
  this.dataPointsFile = new RandomAccessFile(dataPointsFileName, "rw");

  // Locks the temporary file so it is not removed when another instance
  // of MZmine is starting. Lock will be automatically released when this
  // instance of MZmine exits. Locking may fail on network-mounted
  // filesystems.
  try {
    FileChannel fileChannel = dataPointsFile.getChannel();
    fileChannel.lock();
  } catch (IOException e) {
    logger.log(Level.WARNING, "Failed to lock the file " + dataPointsFileName, e);
  }

  // Unfortunately, deleteOnExit() doesn't work on Windows, see JDK
  // bug #4171239. We will try to remove the temporary files in a
  // shutdown hook registered in the main.ShutDownHook class
  dataPointsFileName.deleteOnExit();

}
 
Example 9
Source File: CrossProcessLock.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Create and return a lock that is exclusive across processes. If another process has the lock
 * then this call will block until it is released.
 *
 * @param lockName the lockname is global across all processes of an app
 * @return a CrossProcessLock if success. If the lock failed to acquire (maybe due to disk full or
 *     other unexpected and unsupported permissions) then null will be returned.
 */
static CrossProcessLock acquire(Context appContext, String lockName) {
  FileChannel channel = null;
  FileLock lock = null;
  try {
    File file = new File(appContext.getFilesDir(), lockName);
    channel = new RandomAccessFile(file, "rw").getChannel();
    // Use the file channel to create a lock on the file.
    // This method blocks until it can retrieve the lock.
    lock = channel.lock();
    return new CrossProcessLock(channel, lock);
  } catch (IOException | Error e) {
    // Certain conditions can cause file locking to fail, such as out of disk or bad permissions.
    // In any case, the acquire will fail and return null instead of a held lock.
    // NOTE: In Java 7 & 8, FileKey creation failure might wrap IOException into Error. See
    // https://bugs.openjdk.java.net/browse/JDK-8025619 for details.
    Log.e(TAG, "encountered error while creating and acquiring the lock, ignoring", e);

    // Clean up any dangling resources
    if (lock != null) {
      try {
        lock.release();
      } catch (IOException e2) {
        // nothing to do here
      }
    }
    if (channel != null) {
      try {
        channel.close();
      } catch (IOException e3) {
        // nothing to do here
      }
    }

    return null;
  }
}
 
Example 10
Source File: IOUtil.java    From spring-boot-protocol with Apache License 2.0 5 votes vote down vote up
/**
 * writeFile
 * @param dataIterator data
 * @param targetPath targetPath
 * @param targetFileName targetFileName
 * @param append Whether to concatenate old data
 * @throws IOException IOException
 * @return File
 */
public static File writeFile(Iterator<ByteBuffer> dataIterator, String targetPath, String targetFileName, boolean append) throws IOException {
    if(targetPath == null){
        targetPath = "";
    }
    new File(targetPath).mkdirs();
    File outFile = new File(targetPath.concat(File.separator).concat(targetFileName));
    if(!outFile.exists()){
        outFile.createNewFile();
    }
    FileChannel outChannel = new FileOutputStream(outFile, append).getChannel();
    long writeBeginIndex = append? outChannel.size() : 0L;
    FileLock lock = outChannel.lock(writeBeginIndex, Long.MAX_VALUE - writeBeginIndex, false);
    try{
        while (dataIterator.hasNext()){
            ByteBuffer buffer = dataIterator.next();
            if(buffer == null) {
                continue;
            }
            if(!buffer.hasRemaining()){
                buffer.flip();
            }
            outChannel.write(buffer);
        }
    }finally {
        lock.release();
        outChannel.force(FORCE_META_DATA);
        outChannel.close();
    }
    return outFile;
}
 
Example 11
Source File: Locks.java    From OpenModsLib with MIT License 5 votes vote down vote up
public static SharedLock sharedLock(File file) throws IOException {
	Closer closer = Closer.create();
	try {
		final RandomAccessFile s = closer.register(new RandomAccessFile(file, "rw"));
		final FileChannel ch = closer.register(s.getChannel());

		final FileLock lock = ch.lock(0, Long.MAX_VALUE, true);
		return new SharedLock(file, ch, lock);
	} catch (Throwable t) {
		throw closer.rethrow(t);
	}
}
 
Example 12
Source File: Sharing.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Exercise FileDispatcher close()/preClose()
 */
private static void TestMultipleFD() throws Exception {
    RandomAccessFile raf = null;
    FileOutputStream fos = null;
    FileInputStream fis = null;
    FileChannel fc = null;
    FileLock fileLock = null;

    File test1 = new File("test1");
    try {
        raf = new RandomAccessFile(test1, "rw");
        fos = new FileOutputStream(raf.getFD());
        fis = new FileInputStream(raf.getFD());
        fc = raf.getChannel();
        fileLock = fc.lock();
        raf.setLength(0L);
        fos.flush();
        fos.write("TEST".getBytes());
    } finally {
        if (fileLock != null) fileLock.release();
        if (fis != null) fis.close();
        if (fos != null) fos.close();
        if (raf != null) raf.close();
        test1.delete();
    }

    /*
     * Close out in different order to ensure FD is not
     * closed out too early
     */
    File test2 = new File("test2");
    try {
        raf = new RandomAccessFile(test2, "rw");
        fos = new FileOutputStream(raf.getFD());
        fis = new FileInputStream(raf.getFD());
        fc = raf.getChannel();
        fileLock = fc.lock();
        raf.setLength(0L);
        fos.flush();
        fos.write("TEST".getBytes());
    } finally {
        if (fileLock != null) fileLock.release();
        if (raf != null) raf.close();
        if (fos != null) fos.close();
        if (fis != null) fis.close();
        test2.delete();
    }

    // one more time, fos first this time
    File test3 = new File("test3");
    try {
        raf = new RandomAccessFile(test3, "rw");
        fos = new FileOutputStream(raf.getFD());
        fis = new FileInputStream(raf.getFD());
        fc = raf.getChannel();
        fileLock = fc.lock();
        raf.setLength(0L);
        fos.flush();
        fos.write("TEST".getBytes());
    } finally {
        if (fileLock != null) fileLock.release();
        if (fos != null) fos.close();
        if (raf != null) raf.close();
        if (fis != null) fis.close();
        test3.delete();
    }
}
 
Example 13
Source File: Sharing.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Exercise FileDispatcher close()/preClose()
 */
private static void TestMultipleFD() throws Exception {
    RandomAccessFile raf = null;
    FileOutputStream fos = null;
    FileInputStream fis = null;
    FileChannel fc = null;
    FileLock fileLock = null;

    File test1 = new File("test1");
    try {
        raf = new RandomAccessFile(test1, "rw");
        fos = new FileOutputStream(raf.getFD());
        fis = new FileInputStream(raf.getFD());
        fc = raf.getChannel();
        fileLock = fc.lock();
        raf.setLength(0L);
        fos.flush();
        fos.write("TEST".getBytes());
    } finally {
        if (fileLock != null) fileLock.release();
        if (fis != null) fis.close();
        if (fos != null) fos.close();
        if (raf != null) raf.close();
        test1.delete();
    }

    /*
     * Close out in different order to ensure FD is not
     * closed out too early
     */
    File test2 = new File("test2");
    try {
        raf = new RandomAccessFile(test2, "rw");
        fos = new FileOutputStream(raf.getFD());
        fis = new FileInputStream(raf.getFD());
        fc = raf.getChannel();
        fileLock = fc.lock();
        raf.setLength(0L);
        fos.flush();
        fos.write("TEST".getBytes());
    } finally {
        if (fileLock != null) fileLock.release();
        if (raf != null) raf.close();
        if (fos != null) fos.close();
        if (fis != null) fis.close();
        test2.delete();
    }

    // one more time, fos first this time
    File test3 = new File("test3");
    try {
        raf = new RandomAccessFile(test3, "rw");
        fos = new FileOutputStream(raf.getFD());
        fis = new FileInputStream(raf.getFD());
        fc = raf.getChannel();
        fileLock = fc.lock();
        raf.setLength(0L);
        fos.flush();
        fos.write("TEST".getBytes());
    } finally {
        if (fileLock != null) fileLock.release();
        if (fos != null) fos.close();
        if (raf != null) raf.close();
        if (fis != null) fis.close();
        test3.delete();
    }
}
 
Example 14
Source File: Sharing.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Exercise FileDispatcher close()/preClose()
 */
private static void TestMultipleFD() throws Exception {
    RandomAccessFile raf = null;
    FileOutputStream fos = null;
    FileInputStream fis = null;
    FileChannel fc = null;
    FileLock fileLock = null;

    File test1 = new File("test1");
    try {
        raf = new RandomAccessFile(test1, "rw");
        fos = new FileOutputStream(raf.getFD());
        fis = new FileInputStream(raf.getFD());
        fc = raf.getChannel();
        fileLock = fc.lock();
        raf.setLength(0L);
        fos.flush();
        fos.write("TEST".getBytes());
    } finally {
        if (fileLock != null) fileLock.release();
        if (fis != null) fis.close();
        if (fos != null) fos.close();
        if (raf != null) raf.close();
        test1.delete();
    }

    /*
     * Close out in different order to ensure FD is not
     * closed out too early
     */
    File test2 = new File("test2");
    try {
        raf = new RandomAccessFile(test2, "rw");
        fos = new FileOutputStream(raf.getFD());
        fis = new FileInputStream(raf.getFD());
        fc = raf.getChannel();
        fileLock = fc.lock();
        raf.setLength(0L);
        fos.flush();
        fos.write("TEST".getBytes());
    } finally {
        if (fileLock != null) fileLock.release();
        if (raf != null) raf.close();
        if (fos != null) fos.close();
        if (fis != null) fis.close();
        test2.delete();
    }

    // one more time, fos first this time
    File test3 = new File("test3");
    try {
        raf = new RandomAccessFile(test3, "rw");
        fos = new FileOutputStream(raf.getFD());
        fis = new FileInputStream(raf.getFD());
        fc = raf.getChannel();
        fileLock = fc.lock();
        raf.setLength(0L);
        fos.flush();
        fos.write("TEST".getBytes());
    } finally {
        if (fileLock != null) fileLock.release();
        if (fos != null) fos.close();
        if (raf != null) raf.close();
        if (fis != null) fis.close();
        test3.delete();
    }
}
 
Example 15
Source File: Sharing.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Exercise FileDispatcher close()/preClose()
 */
private static void TestMultipleFD() throws Exception {
    RandomAccessFile raf = null;
    FileOutputStream fos = null;
    FileInputStream fis = null;
    FileChannel fc = null;
    FileLock fileLock = null;

    File test1 = new File("test1");
    try {
        raf = new RandomAccessFile(test1, "rw");
        fos = new FileOutputStream(raf.getFD());
        fis = new FileInputStream(raf.getFD());
        fc = raf.getChannel();
        fileLock = fc.lock();
        raf.setLength(0L);
        fos.flush();
        fos.write("TEST".getBytes());
    } finally {
        if (fileLock != null) fileLock.release();
        if (fis != null) fis.close();
        if (fos != null) fos.close();
        if (raf != null) raf.close();
        test1.delete();
    }

    /*
     * Close out in different order to ensure FD is not
     * closed out too early
     */
    File test2 = new File("test2");
    try {
        raf = new RandomAccessFile(test2, "rw");
        fos = new FileOutputStream(raf.getFD());
        fis = new FileInputStream(raf.getFD());
        fc = raf.getChannel();
        fileLock = fc.lock();
        raf.setLength(0L);
        fos.flush();
        fos.write("TEST".getBytes());
    } finally {
        if (fileLock != null) fileLock.release();
        if (raf != null) raf.close();
        if (fos != null) fos.close();
        if (fis != null) fis.close();
        test2.delete();
    }

    // one more time, fos first this time
    File test3 = new File("test3");
    try {
        raf = new RandomAccessFile(test3, "rw");
        fos = new FileOutputStream(raf.getFD());
        fis = new FileInputStream(raf.getFD());
        fc = raf.getChannel();
        fileLock = fc.lock();
        raf.setLength(0L);
        fos.flush();
        fos.write("TEST".getBytes());
    } finally {
        if (fileLock != null) fileLock.release();
        if (fos != null) fos.close();
        if (raf != null) raf.close();
        if (fis != null) fis.close();
        test3.delete();
    }
}
 
Example 16
Source File: MultiDexExtractor.java    From atlas with Apache License 2.0 4 votes vote down vote up
/**
 * Extracts application secondary dexes into files in the application data
 * directory.
 *
 * @return a list of files that were created. The list may be empty if there
 *         are no secondary dex files. Never return null.
 * @throws IOException if encounters a problem while reading or writing
 *         secondary dex files
 */
static List<? extends File> load(Context context, File sourceApk, File dexDir,
        String prefsKeyPrefix,
        boolean forceReload) throws IOException {
    Log.i(TAG, "MultiDexExtractor.load(" + sourceApk.getPath() + ", " + forceReload + ", " +
            prefsKeyPrefix + ")");

    long currentCrc = getZipCrc(sourceApk);

    // Validity check and extraction must be done only while the lock file has been taken.
    File lockFile = new File(dexDir, LOCK_FILENAME);
    RandomAccessFile lockRaf = new RandomAccessFile(lockFile, "rw");
    FileChannel lockChannel = null;
    FileLock cacheLock = null;
    List<ExtractedDex> files;
    IOException releaseLockException = null;
    try {
        lockChannel = lockRaf.getChannel();
        Log.i(TAG, "Blocking on lock " + lockFile.getPath());
        cacheLock = lockChannel.lock();
        Log.i(TAG, lockFile.getPath() + " locked");

        if (!forceReload && !isModified(context, sourceApk, currentCrc, prefsKeyPrefix)) {
            try {
                files = loadExistingExtractions(context, sourceApk, dexDir, prefsKeyPrefix);
            } catch (IOException ioe) {
                Log.w(TAG, "Failed to reload existing extracted secondary dex files,"
                        + " falling back to fresh extraction", ioe);
                files = performExtractions(sourceApk, dexDir);
                putStoredApkInfo(context, prefsKeyPrefix, getTimeStamp(sourceApk), currentCrc,
                        files);
            }
        } else {
            Log.i(TAG, "Detected that extraction must be performed.");
            files = performExtractions(sourceApk, dexDir);
            putStoredApkInfo(context, prefsKeyPrefix, getTimeStamp(sourceApk), currentCrc,
                    files);
        }
    } finally {
        if (cacheLock != null) {
            try {
                cacheLock.release();
            } catch (IOException e) {
                Log.e(TAG, "Failed to release lock on " + lockFile.getPath());
                // Exception while releasing the lock is bad, we want to report it, but not at
                // the price of overriding any already pending exception.
                releaseLockException = e;
            }
        }
        if (lockChannel != null) {
            closeQuietly(lockChannel);
        }
        closeQuietly(lockRaf);
    }

    if (releaseLockException != null) {
        throw releaseLockException;
    }

    Log.i(TAG, "load found " + files.size() + " secondary dex files");
    return files;
}
 
Example 17
Source File: FileOperations.java    From ph-commons with Apache License 2.0 4 votes vote down vote up
/**
 * Copy the content of the source file to the destination file using
 * {@link FileChannel}. This version seems to fail with UNC paths.
 *
 * @param aSrcFile
 *        Source file. May not be <code>null</code>.
 * @param aDestFile
 *        Destination file. May not be <code>null</code>.
 * @return {@link ESuccess}
 */
@Nonnull
private static ESuccess _copyFileViaChannel (@Nonnull final File aSrcFile, @Nonnull final File aDestFile)
{
  final FileChannel aSrcChannel = FileChannelHelper.getFileReadChannel (aSrcFile);
  if (aSrcChannel == null)
    return ESuccess.FAILURE;

  try
  {
    final FileChannel aDstChannel = FileChannelHelper.getFileWriteChannel (aDestFile, EAppend.TRUNCATE);
    if (aDstChannel == null)
      return ESuccess.FAILURE;

    try
    {
      FileLock aSrcLock = null;
      FileLock aDestLock = null;
      try
      {
        final long nBytesToRead = aSrcChannel.size ();

        // Shared read lock and exclusive write lock
        aSrcLock = aSrcChannel.lock (0, nBytesToRead, true);
        aDestLock = aDstChannel.lock ();

        // Main copying - the loop version is much quicker than then
        // transferTo with full size!
        long nBytesWritten = 0;
        final long nChunkSize = 1L * CGlobal.BYTES_PER_MEGABYTE;
        while (nBytesWritten < nBytesToRead)
          nBytesWritten += aSrcChannel.transferTo (nBytesWritten, nChunkSize, aDstChannel);

        if (nBytesToRead != nBytesWritten)
        {
          if (LOGGER.isErrorEnabled ())
            LOGGER.error ("Failed to copy file. Meant to read " + nBytesToRead + " bytes but wrote " + nBytesWritten);
          return ESuccess.FAILURE;
        }
        return ESuccess.SUCCESS;
      }
      catch (final IOException ex)
      {
        throw new IllegalStateException ("Failed to copy from " + aSrcFile + " to " + aDestFile, ex);
      }
      finally
      {
        // Unlock
        ChannelHelper.release (aDestLock);
        ChannelHelper.release (aSrcLock);
      }
    }
    finally
    {
      ChannelHelper.close (aDstChannel);
    }
  }
  finally
  {
    ChannelHelper.close (aSrcChannel);
  }
}
 
Example 18
Source File: Sharing.java    From jdk8u-dev-jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Exercise FileDispatcher close()/preClose()
 */
private static void TestMultipleFD() throws Exception {
    RandomAccessFile raf = null;
    FileOutputStream fos = null;
    FileInputStream fis = null;
    FileChannel fc = null;
    FileLock fileLock = null;

    File test1 = new File("test1");
    try {
        raf = new RandomAccessFile(test1, "rw");
        fos = new FileOutputStream(raf.getFD());
        fis = new FileInputStream(raf.getFD());
        fc = raf.getChannel();
        fileLock = fc.lock();
        raf.setLength(0L);
        fos.flush();
        fos.write("TEST".getBytes());
    } finally {
        if (fileLock != null) fileLock.release();
        if (fis != null) fis.close();
        if (fos != null) fos.close();
        if (raf != null) raf.close();
        test1.delete();
    }

    /*
     * Close out in different order to ensure FD is not
     * closed out too early
     */
    File test2 = new File("test2");
    try {
        raf = new RandomAccessFile(test2, "rw");
        fos = new FileOutputStream(raf.getFD());
        fis = new FileInputStream(raf.getFD());
        fc = raf.getChannel();
        fileLock = fc.lock();
        raf.setLength(0L);
        fos.flush();
        fos.write("TEST".getBytes());
    } finally {
        if (fileLock != null) fileLock.release();
        if (raf != null) raf.close();
        if (fos != null) fos.close();
        if (fis != null) fis.close();
        test2.delete();
    }

    // one more time, fos first this time
    File test3 = new File("test3");
    try {
        raf = new RandomAccessFile(test3, "rw");
        fos = new FileOutputStream(raf.getFD());
        fis = new FileInputStream(raf.getFD());
        fc = raf.getChannel();
        fileLock = fc.lock();
        raf.setLength(0L);
        fos.flush();
        fos.write("TEST".getBytes());
    } finally {
        if (fileLock != null) fileLock.release();
        if (fos != null) fos.close();
        if (raf != null) raf.close();
        if (fis != null) fis.close();
        test3.delete();
    }
}
 
Example 19
Source File: Sharing.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Exercise FileDispatcher close()/preClose()
 */
private static void TestMultipleFD() throws Exception {
    RandomAccessFile raf = null;
    FileOutputStream fos = null;
    FileInputStream fis = null;
    FileChannel fc = null;
    FileLock fileLock = null;

    File test1 = new File("test1");
    try {
        raf = new RandomAccessFile(test1, "rw");
        fos = new FileOutputStream(raf.getFD());
        fis = new FileInputStream(raf.getFD());
        fc = raf.getChannel();
        fileLock = fc.lock();
        raf.setLength(0L);
        fos.flush();
        fos.write("TEST".getBytes());
    } finally {
        if (fileLock != null) fileLock.release();
        if (fis != null) fis.close();
        if (fos != null) fos.close();
        if (raf != null) raf.close();
        test1.delete();
    }

    /*
     * Close out in different order to ensure FD is not
     * closed out too early
     */
    File test2 = new File("test2");
    try {
        raf = new RandomAccessFile(test2, "rw");
        fos = new FileOutputStream(raf.getFD());
        fis = new FileInputStream(raf.getFD());
        fc = raf.getChannel();
        fileLock = fc.lock();
        raf.setLength(0L);
        fos.flush();
        fos.write("TEST".getBytes());
    } finally {
        if (fileLock != null) fileLock.release();
        if (raf != null) raf.close();
        if (fos != null) fos.close();
        if (fis != null) fis.close();
        test2.delete();
    }

    // one more time, fos first this time
    File test3 = new File("test3");
    try {
        raf = new RandomAccessFile(test3, "rw");
        fos = new FileOutputStream(raf.getFD());
        fis = new FileInputStream(raf.getFD());
        fc = raf.getChannel();
        fileLock = fc.lock();
        raf.setLength(0L);
        fos.flush();
        fos.write("TEST".getBytes());
    } finally {
        if (fileLock != null) fileLock.release();
        if (fos != null) fos.close();
        if (raf != null) raf.close();
        if (fis != null) fis.close();
        test3.delete();
    }
}
 
Example 20
Source File: Sharing.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Exercise FileDispatcher close()/preClose()
 */
private static void TestMultipleFD() throws Exception {
    RandomAccessFile raf = null;
    FileOutputStream fos = null;
    FileInputStream fis = null;
    FileChannel fc = null;
    FileLock fileLock = null;

    File test1 = new File("test1");
    try {
        raf = new RandomAccessFile(test1, "rw");
        fos = new FileOutputStream(raf.getFD());
        fis = new FileInputStream(raf.getFD());
        fc = raf.getChannel();
        fileLock = fc.lock();
        raf.setLength(0L);
        fos.flush();
        fos.write("TEST".getBytes());
    } finally {
        if (fileLock != null) fileLock.release();
        if (fis != null) fis.close();
        if (fos != null) fos.close();
        if (raf != null) raf.close();
        test1.delete();
    }

    /*
     * Close out in different order to ensure FD is not
     * closed out too early
     */
    File test2 = new File("test2");
    try {
        raf = new RandomAccessFile(test2, "rw");
        fos = new FileOutputStream(raf.getFD());
        fis = new FileInputStream(raf.getFD());
        fc = raf.getChannel();
        fileLock = fc.lock();
        raf.setLength(0L);
        fos.flush();
        fos.write("TEST".getBytes());
    } finally {
        if (fileLock != null) fileLock.release();
        if (raf != null) raf.close();
        if (fos != null) fos.close();
        if (fis != null) fis.close();
        test2.delete();
    }

    // one more time, fos first this time
    File test3 = new File("test3");
    try {
        raf = new RandomAccessFile(test3, "rw");
        fos = new FileOutputStream(raf.getFD());
        fis = new FileInputStream(raf.getFD());
        fc = raf.getChannel();
        fileLock = fc.lock();
        raf.setLength(0L);
        fos.flush();
        fos.write("TEST".getBytes());
    } finally {
        if (fileLock != null) fileLock.release();
        if (fos != null) fos.close();
        if (raf != null) raf.close();
        if (fis != null) fis.close();
        test3.delete();
    }
}