Search in sources :

Example 46 with FileLock

use of java.nio.channels.FileLock in project android_frameworks_base by crdroidandroid.

the class MiniThumbFile method getMiniThumbFromFile.

/**
     * Gallery app can use this method to retrieve mini-thumbnail. Full size
     * images share the same IDs with their corresponding thumbnails.
     *
     * @param id the ID of the image (same of full size image).
     * @param data the buffer to store mini-thumbnail.
     */
public synchronized byte[] getMiniThumbFromFile(long id, byte[] data) {
    RandomAccessFile r = miniThumbDataFile();
    if (r == null)
        return null;
    long pos = getIndex(id, false);
    if (pos < 0)
        return null;
    pos *= BYTES_PER_MINTHUMB;
    FileLock lock = null;
    try {
        mBuffer.clear();
        lock = mChannel.lock(pos, BYTES_PER_MINTHUMB, true);
        int size = mChannel.read(mBuffer, pos);
        if (size > 1 + 8 + 4) {
            // flag, magic, length
            mBuffer.position(0);
            byte flag = mBuffer.get();
            long magic = mBuffer.getLong();
            int length = mBuffer.getInt();
            if (size >= 1 + 8 + 4 + length && length != 0 && magic != 0 && flag == 1 && data.length >= length) {
                mBuffer.get(data, 0, length);
                return data;
            }
        }
    } catch (IOException ex) {
        Log.w(TAG, "got exception when reading thumbnail id=" + id + ", exception: " + ex);
    } catch (RuntimeException ex) {
        // Other NIO related exception like disk full, read only channel..etc
        Log.e(TAG, "Got exception when reading thumbnail, id = " + id + ", disk full or mount read-only? " + ex.getClass());
    } finally {
        try {
            if (lock != null)
                lock.release();
        } catch (IOException ex) {
        // ignore it.
        }
    }
    return null;
}
Also used : RandomAccessFile(java.io.RandomAccessFile) FileLock(java.nio.channels.FileLock) IOException(java.io.IOException)

Example 47 with FileLock

use of java.nio.channels.FileLock in project ice by JBEI.

the class BlastPlus method rebuildDatabase.

/**
     * Re-builds the blast database, using a lock file to prevent concurrent rebuilds.
     * The lock file has a "life-span" of 1 day after which it is deleted.
     * <p/>
     * Also, a rebuild can be forced even if a lock file exists which is less than a day old
     *
     * @param force set to true to force a rebuild. Use with caution
     * @throws BlastException
     */
public static void rebuildDatabase(boolean force) throws BlastException {
    String blastInstallDir = Utils.getConfigValue(ConfigurationKey.BLAST_INSTALL_DIR);
    if (StringUtils.isEmpty(blastInstallDir)) {
        Logger.warn("Blast install directory not available. Aborting blast rebuild");
        return;
    }
    Path blastDir = Paths.get(blastInstallDir);
    if (!Files.exists(blastDir))
        throw new BlastException("Could not locate Blast installation in " + blastInstallDir);
    String dataDir = Utils.getConfigValue(ConfigurationKey.DATA_DIRECTORY);
    final Path blastFolder = Paths.get(dataDir, BLAST_DB_FOLDER);
    File lockFile = Paths.get(blastFolder.toString(), LOCK_FILE_NAME).toFile();
    if (lockFile.exists()) {
        if (lockFile.lastModified() <= (System.currentTimeMillis() - (1000 * 60 * 60 * 24))) {
            if (!lockFile.delete()) {
                Logger.warn("Could not delete outdated blast lockfile. Delete the following file manually: " + lockFile.getAbsolutePath());
                return;
            }
        } else {
            Logger.info("Blast db locked (lockfile - " + lockFile.getAbsolutePath() + "). Rebuild aborted!");
            return;
        }
    }
    try {
        if (!Files.exists(blastFolder)) {
            Logger.info("Blast folder (" + blastFolder.toString() + ") does not exist. Creating...");
            try {
                Files.createDirectories(blastFolder);
            } catch (Exception e) {
                Logger.warn("Could not create blast folder. Create it manually or all blast runs will fail");
                return;
            }
        }
        if (!force && blastDatabaseExists()) {
            Logger.info("Blast database found in " + blastFolder.toAbsolutePath().toString());
            return;
        }
        if (!lockFile.createNewFile()) {
            Logger.warn("Could not create lock file for blast rebuild");
            return;
        }
        FileOutputStream fos = new FileOutputStream(lockFile);
        try (FileLock lock = fos.getChannel().tryLock()) {
            if (lock == null)
                return;
            Logger.info("Rebuilding blast database");
            rebuildSequenceDatabase(blastDir, blastFolder, false);
            Logger.info("Blast database rebuild complete");
        }
    } catch (OverlappingFileLockException l) {
        Logger.warn("Could not obtain lock file for blast at " + blastFolder.toString());
    } catch (IOException eio) {
        FileUtils.deleteQuietly(lockFile);
        throw new BlastException(eio);
    }
    FileUtils.deleteQuietly(lockFile);
}
Also used : FileLock(java.nio.channels.FileLock) OverlappingFileLockException(java.nio.channels.OverlappingFileLockException) OverlappingFileLockException(java.nio.channels.OverlappingFileLockException) IllegalAlphabetException(org.biojava.bio.symbol.IllegalAlphabetException) IllegalSymbolException(org.biojava.bio.symbol.IllegalSymbolException)

Example 48 with FileLock

use of java.nio.channels.FileLock in project ice by JBEI.

the class BlastPlus method rebuildFeaturesBlastDatabase.

public static void rebuildFeaturesBlastDatabase(String featureFolder) throws IOException {
    String blastInstallDir = Utils.getConfigValue(ConfigurationKey.BLAST_INSTALL_DIR);
    if (StringUtils.isEmpty(blastInstallDir)) {
        Logger.warn("Blast install directory not available. Aborting blast features rebuild");
        return;
    }
    Path blastDir = Paths.get(blastInstallDir);
    if (!Files.exists(blastDir))
        throw new IOException("Could not locate Blast installation in " + blastInstallDir);
    String dataDir = Utils.getConfigValue(ConfigurationKey.DATA_DIRECTORY);
    final Path blastFolder = Paths.get(dataDir, featureFolder);
    File lockFile = Paths.get(blastFolder.toString(), LOCK_FILE_NAME).toFile();
    if (lockFile.exists()) {
        if (lockFile.lastModified() <= (System.currentTimeMillis() - (1000 * 60 * 60 * 24)))
            if (!lockFile.delete()) {
                Logger.warn("Could not delete outdated features blast lockfile. Delete the following file manually: " + lockFile.getAbsolutePath());
            } else {
                Logger.info("Features blast db locked (lockfile - " + lockFile.getAbsolutePath() + "). Rebuild aborted!");
                return;
            }
    }
    try {
        if (!Files.exists(blastFolder)) {
            Logger.info("Features blast folder (" + blastFolder.toString() + ") does not exist. Creating...");
            try {
                Files.createDirectories(blastFolder);
            } catch (Exception e) {
                Logger.warn("Could not create features blast folder. Create it manually or all blast features runs will fail");
                return;
            }
        }
        if (!lockFile.createNewFile()) {
            Logger.warn("Could not create lock file for features blast rebuild");
            return;
        }
        FileOutputStream fos = new FileOutputStream(lockFile);
        try (FileLock lock = fos.getChannel().tryLock()) {
            if (lock == null)
                return;
            Logger.info("Rebuilding features blast database...");
            rebuildSequenceDatabase(blastDir, blastFolder, true);
            Logger.info("Blast features database rebuild complete");
        }
    } catch (OverlappingFileLockException l) {
        Logger.warn("Could not obtain lock file for blast at " + blastFolder.toString());
    } catch (BlastException be) {
        FileUtils.deleteQuietly(lockFile);
        Logger.error(be);
    }
    FileUtils.deleteQuietly(lockFile);
}
Also used : FileLock(java.nio.channels.FileLock) OverlappingFileLockException(java.nio.channels.OverlappingFileLockException) OverlappingFileLockException(java.nio.channels.OverlappingFileLockException) IllegalAlphabetException(org.biojava.bio.symbol.IllegalAlphabetException) IllegalSymbolException(org.biojava.bio.symbol.IllegalSymbolException)

Example 49 with FileLock

use of java.nio.channels.FileLock in project dubbo by alibaba.

the class AbstractRegistry method doSaveProperties.

public void doSaveProperties(long version) {
    if (version < lastCacheChanged.get()) {
        return;
    }
    if (file == null) {
        return;
    }
    // Save
    try {
        File lockfile = new File(file.getAbsolutePath() + ".lock");
        if (!lockfile.exists()) {
            lockfile.createNewFile();
        }
        RandomAccessFile raf = new RandomAccessFile(lockfile, "rw");
        try {
            FileChannel channel = raf.getChannel();
            try {
                FileLock lock = channel.tryLock();
                if (lock == null) {
                    throw new IOException("Can not lock the registry cache file " + file.getAbsolutePath() + ", ignore and retry later, maybe multi java process use the file, please config: dubbo.registry.file=xxx.properties");
                }
                // Save
                try {
                    if (!file.exists()) {
                        file.createNewFile();
                    }
                    FileOutputStream outputFile = new FileOutputStream(file);
                    try {
                        properties.store(outputFile, "Dubbo Registry Cache");
                    } finally {
                        outputFile.close();
                    }
                } finally {
                    lock.release();
                }
            } finally {
                channel.close();
            }
        } finally {
            raf.close();
        }
    } catch (Throwable e) {
        if (version < lastCacheChanged.get()) {
            return;
        } else {
            registryCacheExecutor.execute(new SaveProperties(lastCacheChanged.incrementAndGet()));
        }
        logger.warn("Failed to save registry store file, cause: " + e.getMessage(), e);
    }
}
Also used : RandomAccessFile(java.io.RandomAccessFile) FileChannel(java.nio.channels.FileChannel) FileOutputStream(java.io.FileOutputStream) FileLock(java.nio.channels.FileLock) IOException(java.io.IOException) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File)

Example 50 with FileLock

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

the class DiskStoreImpl method closeLockFile.

void closeLockFile() {
    FileLock myfl = this.fl;
    if (myfl != null) {
        try {
            FileChannel fc = myfl.channel();
            if (myfl.isValid()) {
                myfl.release();
            }
            fc.close();
        } catch (IOException ignore) {
        }
        this.fl = null;
    }
    File f = this.lockFile;
    if (f != null) {
        if (f.delete()) {
            if (logger.isDebugEnabled()) {
                logger.debug("Deleted lock file {}", f);
            }
        } else if (f.exists()) {
            if (logger.isDebugEnabled()) {
                logger.debug("Could not delete lock file {}", f);
            }
        }
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Unlocked disk store {}", name);
    }
}
Also used : FileChannel(java.nio.channels.FileChannel) FileLock(java.nio.channels.FileLock) IOException(java.io.IOException) File(java.io.File)

Aggregations

FileLock (java.nio.channels.FileLock)246 IOException (java.io.IOException)127 RandomAccessFile (java.io.RandomAccessFile)99 FileChannel (java.nio.channels.FileChannel)83 File (java.io.File)77 OverlappingFileLockException (java.nio.channels.OverlappingFileLockException)37 FileOutputStream (java.io.FileOutputStream)29 Test (org.junit.Test)19 Path (java.nio.file.Path)16 FileInputStream (java.io.FileInputStream)13 FileNotFoundException (java.io.FileNotFoundException)12 ByteBuffer (java.nio.ByteBuffer)10 InputStream (java.io.InputStream)5 Properties (java.util.Properties)5 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4 NonWritableChannelException (java.nio.channels.NonWritableChannelException)4 NoSuchFileException (java.nio.file.NoSuchFileException)4 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)4 Map (java.util.Map)4 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)3