Example usage for java.nio.channels FileLock release

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

Introduction

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

Prototype

public abstract void release() throws IOException;

Source Link

Document

Releases this lock.

Usage

From source file:io.github.eternalbits.compactvd.CompactVD.java

private void copy(File from, int options, File to, String type) throws IOException {
    long mtime = to.lastModified();
    task = DiskImageProgress.COPY;//from w  ww  .  j  a  v  a2  s. com
    File copy = null;
    try (RandomAccessFile check = new RandomAccessFile(from, "r")) { // is file?
        // If writable, source is open in write mode for an exclusive file lock
        String mode = from.canWrite() ? "rw" : "r";
        try (DiskImage image = DiskImages.open(from, mode)) {
            if (type == null)
                type = image.getType();
            try (DiskImage clone = DiskImages.create(type, to, image.getDiskSize())) {
                copy = to; // copy open by DiskImage
                FileLock source = null;
                if (mode.equals("rw"))
                    source = image.tryLock();
                verboseProgress(SEARCHING_SPACE);
                image.addObserver(this, false);
                image.optimize(options);
                image.removeObserver(this);
                if (!isCancelled()) {
                    verboseProgress("Copying " + from.getName() + " to " + to.getName());
                    FileLock fileLock = clone.tryLock();
                    clone.addObserver(this, false);
                    clone.copy(image);
                    clone.removeObserver(this);
                    fileLock.release();
                }
                if (source != null)
                    source.release();
                if (!isCancelled()) {
                    copy = null;
                }
            }
        }
    } finally {
        if (copy != null && copy.isFile())
            copy.delete();
        System.out.println(mtime != to.lastModified()
                ? String.format(IMAGE_CREATED, to.getName(), to.getAbsoluteFile().getParent())
                : IMAGE_NOT_CREATED);
    }
}

From source file:net.modsec.ms.connector.ConnRequestHandler.java

/**
 * Reads the modsecurity configuration file on modsecurity machine.
 * @param json//w w w .ja va  2 s .com
 */
@SuppressWarnings("unchecked")
public static void onReadMSConfig(JSONObject json) {

    log.info("onReadMSConfig called.. : " + json.toJSONString());
    MSConfig serviceCfg = MSConfig.getInstance();

    String fileName = serviceCfg.getConfigMap().get("MSConfigFile");
    InputStream ins;
    BufferedReader br;

    try {

        File file = new File(fileName);
        DataInputStream in;

        @SuppressWarnings("resource")
        FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
        FileLock lock = channel.lock();

        try {

            ins = new FileInputStream(file);
            in = new DataInputStream(ins);
            br = new BufferedReader(new InputStreamReader(in));

            String line = "";

            while ((line = br.readLine()) != null) {

                //log.info("Line :" + line);
                for (ModSecConfigFields field : ModSecConfigFields.values()) {

                    if (line.startsWith(field.toString())) {

                        if (line.trim().split(" ")[0].equals(field.toString())) {
                            json.put(field.toString(), line.trim().split(" ")[1].replace("\"", ""));
                        }

                    }

                }

            }
            log.info("ModSecurity Configurations configurations Loaded ... ");

        } finally {

            lock.release();

        }
        br.close();
        in.close();
        ins.close();

    } catch (FileNotFoundException e1) {

        json.put("status", "1");
        json.put("message", "configuration file not found");
        e1.printStackTrace();

    } catch (IOException | NullPointerException e) {

        json.put("status", "1");
        json.put("message", "configuration file is corrupt");
        e.printStackTrace();

    }

    log.info("Sending Json :" + json.toJSONString());
    ConnectorService.getConnectorProducer().send(json.toJSONString());
    json.clear();

}

From source file:org.sonarsource.sonarlint.core.plugin.DefaultPluginJarExploder.java

private File unzipFile(File cachedFile) throws IOException {
    String filename = cachedFile.getName();
    File destDir = new File(cachedFile.getParentFile(), filename + "_unzip");
    if (!destDir.exists()) {
        File lockFile = new File(cachedFile.getParentFile(), filename + "_unzip.lock");
        FileOutputStream out = new FileOutputStream(lockFile);
        try {/* ww w  .  ja va  2s.  co  m*/
            FileLock lock = out.getChannel().lock();
            try {
                // Recheck in case of concurrent processes
                if (!destDir.exists()) {
                    Path tempDir = fileCache.createTempDir();
                    ZipUtils.unzip(cachedFile, tempDir.toFile(), newLibFilter());
                    FileUtils.moveDirectory(tempDir.toFile(), destDir);
                }
            } finally {
                lock.release();
            }
        } finally {
            out.close();
            FileUtils.deleteQuietly(lockFile);
        }
    }
    return destDir;
}

From source file:org.sonar.batch.bootstrap.BatchPluginExploder.java

private File unzipFile(File cachedFile) throws IOException {
    String filename = cachedFile.getName();
    File destDir = new File(cachedFile.getParentFile(), filename + "_unzip");
    File lockFile = new File(cachedFile.getParentFile(), filename + "_unzip.lock");
    if (!destDir.exists()) {
        FileOutputStream out = new FileOutputStream(lockFile);
        try {//from   w ww  .j a  v  a 2 s .  com
            java.nio.channels.FileLock lock = out.getChannel().lock();
            try {
                // Recheck in case of concurrent processes
                if (!destDir.exists()) {
                    File tempDir = fileCache.createTempDir();
                    ZipUtils.unzip(cachedFile, tempDir, newLibFilter());
                    FileUtils.moveDirectory(tempDir, destDir);
                }
            } finally {
                lock.release();
            }
        } finally {
            out.close();
            FileUtils.deleteQuietly(lockFile);
        }
    }
    return destDir;
}

From source file:org.sonar.batch.bootstrap.BatchPluginJarExploder.java

private File unzipFile(File cachedFile) throws IOException {
    String filename = cachedFile.getName();
    File destDir = new File(cachedFile.getParentFile(), filename + "_unzip");
    File lockFile = new File(cachedFile.getParentFile(), filename + "_unzip.lock");
    if (!destDir.exists()) {
        FileOutputStream out = new FileOutputStream(lockFile);
        try {/*from w  w  w.  j a  va2s . c  om*/
            java.nio.channels.FileLock lock = out.getChannel().lock();
            try {
                // Recheck in case of concurrent processes
                if (!destDir.exists()) {
                    File tempDir = fileCache.createTempDir();
                    ZipUtils.unzip(cachedFile, tempDir, newLibFilter());
                    FileUtils.moveDirectory(tempDir, destDir);
                }
            } finally {
                lock.release();
            }
        } finally {
            out.close();
            deleteQuietly(lockFile);
        }
    }
    return destDir;
}

From source file:omero.util.TempFileManager.java

/**
 * Returns a platform-specific user-writable temporary directory.
 *
 * First, the value of "OMERO_TEMPDIR" is attempted (if available),
 * then user's home ("user.home") directory, then the global temp director
 * ("java.io.tmpdir").//from w  w  w. j  a  va  2 s .  c om
 *
 * Typical errors for any of the possible temp locations are:
 * <ul>
 * <li>non-existence</li>
 * <li>inability to lock</li>
 * </ul>
 *
 * @see <a href="https://trac.openmicroscopy.org.uk/omero/ticket/1653">ticket:1653</a>
 */
protected File tmpdir() {

    File locktest = null;

    String omerotmp = System.getenv().get("OMERO_TEMPDIR");
    String homeprop = System.getProperty("user.home", null);
    String tempprop = System.getProperty("java.io.tmpdir", null);
    List<String> targets = Arrays.asList(omerotmp, homeprop, tempprop);

    for (String target : targets) {

        if (target == null) {
            continue;
        }

        RandomAccessFile raftest = null;
        try {
            File testdir = new File(target);
            locktest = File.createTempFile("._omero_util_TempFileManager_lock_test", ".tmp", testdir);
            locktest.delete();

            raftest = new RandomAccessFile(locktest, "rw");

            FileLock channeltest = raftest.getChannel().tryLock();
            channeltest.release();
        } catch (Exception e) {
            if ("Operation not permitted".equals(e.getMessage())
                    || "Operation not supported".equals(e.getMessage())) {
                // This is the issue described in ticket:1653
                // To prevent printing the warning, we just continue
                // here.
                log.debug(target + " does not support locking.");
            } else {
                log.warn("Invalid tmp dir: " + target, e);
            }
            continue;
        } finally {
            if (locktest != null && raftest != null) {
                try {
                    raftest.close();
                    locktest.delete();
                } catch (Exception e) {
                    log.warn("Failed to close/delete lock file: " + locktest);
                }
            }
        }

        log.debug("Chose global tmpdir:  " + locktest.getParent());
        break; // Something found!

    }

    if (locktest == null) {
        throw new RuntimeException("Could not find lockable tmp dir");
    }

    File omero = new File(locktest.getParentFile(), "omero");
    File tmp = new File(omero, "tmp");
    return tmp;
}

From source file:org.chimi.s4s.fileservice.FileLockBasedThumbnailCreator.java

@Override
public File create(FileData fileData, Size newSize) throws IOException {
    String thumbnailPath = getThumbnailPath(fileData.getFileId(), newSize);
    File thumbnailFile = new File(thumbnailPath);
    if (thumbnailFile.exists()) {
        // ? ?? /* ww w . j av a 2  s .c o m*/
        return thumbnailFile;
    }
    File lockFile = getLockFile(thumbnailPath);
    FileChannel channel = new RandomAccessFile(lockFile, "rw").getChannel();
    FileLock lock = null;
    try {
        lock = channel.tryLock();
    } catch (OverlappingFileLockException ex) {
    }

    if (lock == null) {
        // ??  , 1  ?? ?? ? ? 
        return createTemporaryThumbnail(thumbnailPath, fileData, newSize);
    }
    try {
        createThumbnail(thumbnailPath, fileData, newSize);
        return thumbnailFile;
    } finally {
        lock.release();
        channel.close();

        // TODO ? ?   
    }
}

From source file:org.sakaiproject.search.index.impl.SegmentInfoImpl.java

/**
 * @param f/*from   ww w .j  av  a2 s  .  c om*/
 * @param message
 */
private void dumpFileInfo(File f, String message) {
    String fileInfo = message + "(" + f.getPath() + "):";
    if (!f.exists()) {
        log.error(fileInfo + " File No longer exists");

    } else {
        log.info(fileInfo + " size=[" + f.length() + "] lastModified=[" + f.lastModified() + "] read=["
                + f.canRead() + "] write=[" + f.canWrite() + "] hidden=[" + f.isHidden() + "]");
        try {
            FileInputStream fin = new FileInputStream(f);
            fin.read(new byte[4096]);
            log.info(fileInfo + " readOk");
            FileLock fl = fin.getChannel().tryLock();
            fl.release();
            fin.close();
            log.info(fileInfo + " lockOk");
        } catch (Exception ex) {
            log.warn(fileInfo + " Lock or Read failed: ", ex);
        }
    }
}

From source file:org.pentaho.di.trans.steps.excelinput.PoiWorkBookTest.java

@Test
public void testResourceFree() throws Exception {
    FileLock lock = null;
    RandomAccessFile randomAccessFile = null;
    try {//from  ww  w.  j a  va 2 s  . c o m
        readData();
        File fileAfterRead = new File("testfiles/sample-file.xlsx");
        randomAccessFile = new RandomAccessFile(fileAfterRead, "rw");
        FileChannel fileChannel = randomAccessFile.getChannel();
        lock = fileChannel.tryLock();
        // check that we could lock file
        assertTrue(lock.isValid());
    } finally {
        if (lock != null) {
            lock.release();
        }
        if (randomAccessFile != null) {
            randomAccessFile.close();
        }
    }
}

From source file:it.geosolutions.tools.io.file.IOUtils.java

/**
 * This method is responsible for checking if the input file is still being
 * written or if its available for being parsed.
 * //from w w w  .  j  a va 2  s .c  o  m
 * <p>
 * Specifically this method tries to open up a "rw" channel on the provided
 * input file. If the file is still being written this operation fails with
 * an exception, we therefore catch this exception and sleep for
 * {@value #ATOMIC_WAIT} seconds as defined in the constant
 * {@link #ATOMIC_WAIT}.
 * 
 * <p>
 * If after having waited for {@link MAX_WAITING_TIME_FOR_LOCK} (which is
 * read from the configuration or set to the default value of
 * {@link #DEFAULT_WAITING_TIME}) we have not yet acquired the channel we
 * skip this file but we signal this situation.
 * 
 * NOTE: To make use of mandatory locks, mandatory locking must be enabled
 * both on the file system that contains the file to be locked, and on the
 * file itself. Mandatory locking is enabled on a file system using the
 * "-o mand" option to mount(8), or the MS_MANDLOCK flag for mount(2).
 * Mandatory locking is enabled on a file by disabling group execute
 * permission on the file and enabling the set-group-ID permission bit (see
 * chmod(1) and chmod(2)).
 * 
 * @param caller
 * @param inputFile
 * @param maxwait
 * @return <code>true</code> if the lock has been successfully acquired.
 *         <code>false</code> otherwise
 * @throws InterruptedException
 * @throws IOException
 */
public static boolean acquireLock(Object caller, File inputFile, final long maxwait)
        throws InterruptedException, IOException {

    if (!inputFile.exists())
        return false;// file not exists!

    if (inputFile.isDirectory()) {
        // return inputFile.setReadOnly();
        return true;// cannot lock directory
    }

    // //
    //
    // Acquire an exclusive lock to wait for long
    // writing processes before trying to check on them
    //
    // //
    double sumWait = 0;
    while (true) {
        FileOutputStream outStream = null;
        FileChannel channel = null;
        FileLock lock = null;
        try {
            outStream = new FileOutputStream(inputFile, true);

            // get a rw channel
            channel = outStream.getChannel();
            if (channel != null) {
                // here we could block
                lock = channel.tryLock();
                if (lock != null) {
                    if (LOGGER.isTraceEnabled())
                        LOGGER.trace("File locked successfully");
                    return true;
                }
            }
        } catch (OverlappingFileLockException e) {
            // File is already locked in this thread or virtual machine
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("File is already locked in this thread or virtual machine");
        } catch (Exception e) {
            if (LOGGER.isDebugEnabled())
                LOGGER.debug(e.getLocalizedMessage(), e);
        } finally {

            org.apache.commons.io.IOUtils.closeQuietly(outStream);

            // release the lock
            if (lock != null)
                try {
                    lock.release();
                } catch (Exception e) {
                    // eat me
                }

            if (channel != null)
                try {
                    channel.close();
                } catch (Exception e) {
                    // eat me
                }
        }

        // Sleep for ATOMIC_WAIT milliseconds prior to retry for acquiring
        // the lock
        synchronized (caller) {
            caller.wait(Conf.ATOMIC_WAIT);
        }

        sumWait += Conf.ATOMIC_WAIT;
        if (sumWait > maxwait) {
            if (LOGGER.isWarnEnabled())
                LOGGER.warn("Waiting time beyond maximum specified waiting time, exiting...");
            // Quitting the loop
            break;
        }
    }

    // A time greater than MAX_WAITING_TIME_FOR_LOCK has elapsed and no lock
    // has
    // been acquired. Thus, I need to return false
    return false;
}