Example usage for java.nio.channels FileLock channel

List of usage examples for java.nio.channels FileLock channel

Introduction

In this page you can find the example usage for java.nio.channels FileLock channel.

Prototype

Channel channel

To view the source code for java.nio.channels FileLock channel.

Click Source Link

Usage

From source file:com.espirit.moddev.examples.uxbridge.newsdrilldown.jpa.NewsHandler.java

/**
 * Deletes a newsdrilldown from the db./*www .j a va  2  s  .  c o  m*/
 *
 * @param entity The newsdrilldown to delete
 */
public void delete(UXBEntity entity) throws Exception {

    EntityManager em = null;
    EntityTransaction tx = null;
    try {

        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();

        Query query = em.createQuery(new StringBuilder()
                .append("FROM news x WHERE x.fs_id = :fs_id AND x.language = :language").toString());
        query.setParameter("fs_id", Long.parseLong(entity.getUuid()));
        query.setParameter("language", entity.getLanguage());

        if (!query.getResultList().isEmpty()) {
            News art = (News) query.getSingleResult();
            // delete file from filesystem
            URL url = new URL(art.getUrl());
            File file = new File(webpath + url.getPath());
            if (file.exists()) {
                // Try acquiring the lock without blocking. This method returns
                // null or throws an exception if the file is already locked.
                try {
                    FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
                    // Try to lock the file
                    FileLock lock = channel.tryLock();
                    // Delete the file
                    file.delete();
                    // Release the lock
                    lock.release();
                    lock.channel().close();
                } catch (OverlappingFileLockException e) {
                    logger.info("File is already locked in this thread or virtual machine");
                } catch (MalformedURLException e) {
                    logger.info("wrong url", e);
                }
            }
            // remove article from content repository

            em.remove(art);
        }
        tx.commit();
    } catch (Exception e) {
        if (tx != null) {
            tx.setRollbackOnly();
        }
        throw e;
    } finally {
        if (tx != null && tx.isActive()) {
            if (tx.getRollbackOnly()) {
                tx.rollback();
            }
        }
        if (em != null) {
            em.close();
        }
    }
}

From source file:org.apache.flume.channel.file.Log.java

/**
 * Lock storage to provide exclusive access.
 *
 * <p> Locking is not supported by all file systems.
 * E.g., NFS does not consistently support exclusive locks.
 *
 * <p> If locking is supported we guarantee exculsive access to the
 * storage directory. Otherwise, no guarantee is given.
 *
 * @throws IOException if locking fails// w  w w  .j a v a  2 s.  c o m
 */
private void lock(File dir) throws IOException {
    FileLock lock = tryLock(dir);
    if (lock == null) {
        String msg = "Cannot lock " + dir + ". The directory is already locked. " + channelNameDescriptor;
        LOGGER.info(msg);
        throw new IOException(msg);
    }
    FileLock secondLock = tryLock(dir);
    if (secondLock != null) {
        LOGGER.warn("Directory " + dir + " does not support locking");
        secondLock.release();
        secondLock.channel().close();
    }
    locks.put(dir.getAbsolutePath(), lock);
}

From source file:org.apache.flume.channel.file.Log.java

/**
 * Unlock directory.//from w w w. j a v  a 2 s.com
 *
 * @throws IOException
 */
private void unlock(File dir) throws IOException {
    FileLock lock = locks.remove(dir.getAbsolutePath());
    if (lock == null) {
        return;
    }
    lock.release();
    lock.channel().close();
    lock = null;
}

From source file:org.apache.hadoop.dfs.StorageInfo.java

/**
 * Check whether underlying file system supports file locking.
 * /*from   w w  w  . j  a  va2 s . c  o  m*/
 * @return <code>true</code> if exclusive locks are supported or
 *         <code>false</code> otherwise.
 * @throws IOException
 * @see StorageDirectory#lock()
 */
boolean isLockSupported(int idx) throws IOException {
    StorageDirectory sd = storageDirs.get(idx);
    FileLock firstLock = null;
    FileLock secondLock = null;
    try {
        firstLock = sd.lock;
        if (firstLock == null) {
            firstLock = sd.tryLock();
            if (firstLock == null)
                return true;
        }
        secondLock = sd.tryLock();
        if (secondLock == null)
            return true;
    } finally {
        if (firstLock != null && firstLock != sd.lock) {
            firstLock.release();
            firstLock.channel().close();
        }
        if (secondLock != null) {
            secondLock.release();
            secondLock.channel().close();
        }
    }
    return false;
}

From source file:org.apache.hadoop.hdfs.server.common.Storage.java

/**
 * Check whether underlying file system supports file locking.
 * //from  ww  w.  j a v a  2  s.  com
 * @return <code>true</code> if exclusive locks are supported or
 *         <code>false</code> otherwise.
 * @throws IOException
 * @see StorageDirectory#lock()
 */
public boolean isLockSupported(int idx) throws IOException {
    StorageDirectory sd = storageDirs.get(idx);
    FileLock firstLock = null;
    FileLock secondLock = null;
    try {
        firstLock = sd.lock;
        if (firstLock == null) {
            firstLock = sd.tryLock();
            if (firstLock == null)
                return true;
        }
        secondLock = sd.tryLock();
        if (secondLock == null)
            return true;
    } finally {
        if (firstLock != null && firstLock != sd.lock) {
            firstLock.release();
            firstLock.channel().close();
        }
        if (secondLock != null) {
            secondLock.release();
            secondLock.channel().close();
        }
    }
    return false;
}

From source file:org.apache.tez.runtime.library.common.shuffle.Fetcher.java

private void releaseLock(FileLock lock) throws IOException {
    if (lock != null && lock.isValid()) {
        FileChannel lockChannel = lock.channel();
        lock.release();/*  w w  w .j av  a 2 s.c om*/
        lockChannel.close();
    }
}

From source file:org.cyclop.service.common.FileStorage.java

private FileChannel lock(Path histPath, FileChannel channel) throws IOException {
    LOG.debug("Trying to log file: {}", histPath);
    long start = System.currentTimeMillis();
    String lastExMessage = null;/*from   w  ww. j  av  a 2 s .c  om*/
    FileChannel lockChannel = null;
    while (lockChannel == null && System.currentTimeMillis() - start < config.fileStore.lockWaitTimeoutMillis) {
        try {
            FileLock lock = channel.lock();
            lockChannel = lock.channel();
        } catch (FileLockInterruptionException | OverlappingFileLockException e) {
            lockRetryCount.incrementAndGet();
            lastExMessage = e.getMessage();
            LOG.debug("File lock on '{}' cannot be obtained (retrying operation): {}", histPath, lastExMessage);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e1) {
                Thread.interrupted();
            }
        }
    }
    if (lockChannel == null) {
        throw new ServiceException("File lock on '" + histPath + "' cannot be obtained: " + lastExMessage);
    }

    return lockChannel;
}