Search in sources :

Example 41 with FileLock

use of java.nio.channels.FileLock in project azure-tools-for-java by Microsoft.

the class FileTokenCache method acquireLock.

private FileLock acquireLock(RandomAccessFile raf) throws IOException, InterruptedException {
    // in case of multiprocess file access
    FileLock lock = null;
    int tryCount = 3;
    long sleepSec = 10;
    while (tryCount > 0) {
        try {
            lock = raf.getChannel().tryLock();
            break;
        } catch (OverlappingFileLockException ex) {
            log.log(Level.WARNING, String.format("The file has been locked by another process - waiting %s sec to release [%d attempt(s) left].", sleepSec, tryCount));
            Thread.sleep(sleepSec * 1000);
            tryCount--;
        }
    }
    return lock;
}
Also used : FileLock(java.nio.channels.FileLock) OverlappingFileLockException(java.nio.channels.OverlappingFileLockException)

Example 42 with FileLock

use of java.nio.channels.FileLock in project jdk8u_jdk by JetBrains.

the class Sharing method TestMultipleFD.

/**
     * 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();
    }
}
Also used : FileChannel(java.nio.channels.FileChannel) FileLock(java.nio.channels.FileLock)

Example 43 with FileLock

use of java.nio.channels.FileLock in project ABPlayer by winkstu.

the class MiniThumbFile method saveMiniThumbToFile.

protected synchronized void saveMiniThumbToFile(byte[] data, long id, long magic) throws IOException {
    RandomAccessFile r = miniThumbDataFile();
    if (r == null)
        return;
    long pos = id * BYTES_PER_MINTHUMB;
    FileLock lock = null;
    try {
        if (data != null) {
            if (data.length > BYTES_PER_MINTHUMB - HEADER_SIZE)
                return;
            mBuffer.clear();
            mBuffer.put((byte) 1);
            mBuffer.putLong(magic);
            mBuffer.putInt(data.length);
            mBuffer.put(data);
            mBuffer.flip();
            lock = mChannel.lock(pos, BYTES_PER_MINTHUMB, false);
            mChannel.write(mBuffer, pos);
        }
    } catch (IOException ex) {
        Log.e("couldn't save mini thumbnail data for %d; %s", id, ex.getMessage());
        throw ex;
    } catch (RuntimeException ex) {
        Log.e("couldn't save mini thumbnail data for %d, disk full or mount read-only? %s", id, ex.getClass().toString());
    } finally {
        try {
            if (lock != null)
                lock.release();
        } catch (IOException ex) {
        }
    }
}
Also used : RandomAccessFile(java.io.RandomAccessFile) FileLock(java.nio.channels.FileLock) IOException(java.io.IOException)

Example 44 with FileLock

use of java.nio.channels.FileLock in project intellij-community by JetBrains.

the class FileUtilHeavyTest method testDeleteFail.

@Test
public void testDeleteFail() throws IOException {
    File targetDir = IoTestUtil.createTestDir(myTempDirectory, "failed_delete");
    File file = IoTestUtil.createTestFile(targetDir, "file");
    if (SystemInfo.isWindows) {
        try (RandomAccessFile rw = new RandomAccessFile(file, "rw");
            FileLock ignored = rw.getChannel().tryLock()) {
            assertFalse(FileUtil.delete(file));
        }
    } else {
        assertTrue(targetDir.setWritable(false, false));
        try {
            assertFalse(FileUtil.delete(file));
        } finally {
            assertTrue(targetDir.setWritable(true, true));
        }
    }
}
Also used : RandomAccessFile(java.io.RandomAccessFile) FileLock(java.nio.channels.FileLock) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File) Test(org.junit.Test)

Example 45 with FileLock

use of java.nio.channels.FileLock in project karaf by apache.

the class InstanceHelper method updateInstancePid.

static void updateInstancePid(final File karafHome, final File karafBase, final boolean isStartingInstance) {
    try {
        final String instanceName = System.getProperty("karaf.name");
        final String pid = isStartingInstance ? getPid() : "0";
        if (instanceName != null) {
            String storage = System.getProperty("karaf.instances");
            if (storage == null) {
                throw new Exception("System property 'karaf.instances' is not set. \n" + "This property needs to be set to the full path of the instance.properties file.");
            }
            File storageFile = new File(storage);
            final File propertiesFile = new File(storageFile, "instance.properties");
            if (!propertiesFile.getParentFile().exists()) {
                try {
                    if (!propertiesFile.getParentFile().mkdirs()) {
                        throw new Exception("Unable to create directory " + propertiesFile.getParentFile());
                    }
                } catch (SecurityException se) {
                    throw new Exception(se.getMessage());
                }
            }
            // don't instance.properties if we're stopping and can't acquire lock
            if (!isStartingInstance) {
                boolean proceed = true;
                try (RandomAccessFile raf = new RandomAccessFile(propertiesFile, "rw")) {
                    FileLock lock = raf.getChannel().tryLock();
                    if (lock == null) {
                        proceed = false;
                    } else {
                        lock.release();
                    }
                }
                if (!proceed) {
                    // stopping the child
                    return;
                }
            }
            FileLockUtils.execute(propertiesFile, (TypedProperties props) -> {
                if (props.isEmpty()) {
                    // it's the first instance running, so we consider as root
                    props.put("count", "1");
                    props.put("item.0.name", instanceName);
                    props.put("item.0.loc", karafBase.getAbsolutePath());
                    props.put("item.0.pid", pid);
                    props.put("item.0.root", "true");
                } else {
                    int count = Integer.parseInt(props.get("count").toString());
                    for (int i = 0; i < count; i++) {
                        String name = props.get("item." + i + ".name").toString();
                        if (name.equals(instanceName)) {
                            props.put("item." + i + ".pid", pid);
                            return;
                        }
                    }
                    // it's not found, let assume it's the root instance, so 0
                    props.put("item.0.name", instanceName);
                    props.put("item.0.pid", pid);
                }
            }, true);
        }
    } catch (Exception e) {
        System.err.println("Unable to update instance pid: " + e.getMessage());
    }
}
Also used : RandomAccessFile(java.io.RandomAccessFile) FileLock(java.nio.channels.FileLock) TypedProperties(org.apache.felix.utils.properties.TypedProperties) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File)

Aggregations

FileLock (java.nio.channels.FileLock)134 RandomAccessFile (java.io.RandomAccessFile)71 IOException (java.io.IOException)70 File (java.io.File)46 FileChannel (java.nio.channels.FileChannel)35 OverlappingFileLockException (java.nio.channels.OverlappingFileLockException)24 Test (org.junit.Test)13 FileOutputStream (java.io.FileOutputStream)10 FileInputStream (java.io.FileInputStream)4 ByteBuffer (java.nio.ByteBuffer)4 NonWritableChannelException (java.nio.channels.NonWritableChannelException)4 Path (java.nio.file.Path)4 FileNotFoundException (java.io.FileNotFoundException)3 NonReadableChannelException (java.nio.channels.NonReadableChannelException)3 NoSuchFileException (java.nio.file.NoSuchFileException)3 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)3 Properties (java.util.Properties)3 FileSystemOperationException (com.axway.ats.common.filesystem.FileSystemOperationException)2 AttributeNotSupportedException (com.axway.ats.core.filesystem.exceptions.AttributeNotSupportedException)2 FileDoesNotExistException (com.axway.ats.core.filesystem.exceptions.FileDoesNotExistException)2