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:com.sqlite.multiread.java

public void run() {
    newSqLiteAdapter.openToRead();/*from  w  ww.  ja  v  a 2 s . co  m*/
    long seconds1 = 0;
    long seconds2 = 0;
    Cursor cur = null;
    Transactions transactions = new Transactions();
    ArrayList<Long> array = new ArrayList<Long>();
    for (int i = 0; i < 10; i++) {
        seconds1 = System.currentTimeMillis();
        //cur = newSqLiteAdapter.queueAll("dammyTable", false, false, false,
        //         false, false, false, true, threadNum);
        seconds2 = System.currentTimeMillis();
        array.add(seconds2 - seconds1);
    }
    //   newSqLiteAdapter.close();
    FileOutputStream fos = null;
    try {
        byte[] data = new String("\nTotal time: " + transactions.average_time(array) / 8 + "ms  Thread Id: "
                + currentThread().getId() + " I Have read " + cur.getCount()).getBytes();

        File file = new File(Environment.getExternalStorageDirectory() + "/Aaa/", "threadsResults.txt");

        FileChannel channel = new RandomAccessFile(file, "rw").getChannel();

        FileLock lock = channel.lock();

        try {
            lock = channel.tryLock();
        } catch (OverlappingFileLockException e) {

        }

        fos = new FileOutputStream(file, true);
        fos.write(data);

        fos.flush();

        lock.release();
        channel.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:org.forgerock.openidm.script.javascript.JavaScriptFactory.java

private Script initializeScript(String name, File source, boolean sharedScope) throws ScriptException {
    initDebugListener();/*  w  w  w .jav a  2s. c om*/
    if (debugInitialised) {
        try {
            FileChannel inChannel = new FileInputStream(source).getChannel();
            FileChannel outChannel = new FileOutputStream(getTargetFile(name)).getChannel();
            FileLock outLock = outChannel.lock();
            FileLock inLock = inChannel.lock(0, inChannel.size(), true);
            inChannel.transferTo(0, inChannel.size(), outChannel);

            outLock.release();
            inLock.release();

            inChannel.close();
            outChannel.close();
        } catch (IOException e) {
            logger.warn("JavaScript source was not updated for {}", name, e);
        }
    }
    return new JavaScript(name, source, sharedScope);
}

From source file:org.forgerock.openidm.script.javascript.JavaScriptFactory.java

private Script initializeScript(String name, String source, boolean sharedScope) throws ScriptException {
    initDebugListener();//from   www  . j a  v a 2  s  . c o m
    if (debugInitialised) {
        try {
            FileChannel outChannel = new FileOutputStream(getTargetFile(name)).getChannel();
            FileLock outLock = outChannel.lock();
            ByteBuffer buf = ByteBuffer.allocate(source.length());
            buf.put(source.getBytes("UTF-8"));
            buf.flip();
            outChannel.write(buf);
            outLock.release();
            outChannel.close();
        } catch (IOException e) {
            logger.warn("JavaScript source was not updated for {}", name, e);
        }
    }
    return new JavaScript(name, source, sharedScope);
}

From source file:csic.ceab.movelab.beepath.Util.java

/**
 * Saves a byte array to the internal storage directory.
 * /* w  w w  .  j a  va  2s. com*/
 * @param context
 *            The application context.
 * @param filename
 *            The file name to use.
 * @param bytes
 *            The byte array to be saved.
 */
public static void saveJSON(Context context, String dir, String fileprefix, String inputString) {
    // String TAG = "Util.saveFile";
    FileOutputStream fos = null;
    FileLock lock = null;

    try {
        byte[] bytes = inputString.getBytes("UTF-8");

        File directory = new File(context.getFilesDir().getAbsolutePath(), dir);

        directory.mkdirs();

        File target = new File(directory, fileprefix + System.currentTimeMillis() + ".txt");
        fos = new FileOutputStream(target);

        lock = fos.getChannel().lock();

        fos.write(bytes);

    } catch (IOException e) {
        // logging exception but doing nothing
        // Log.e(TAG, "Exception " + e);
    } finally {

        if (lock != null) {

            try {
                lock.release();
            } catch (Exception e) {

            }
        }
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException e) {
                // logging exception but doing nothing
                // Log.e(TAG, "Exception " + e);

            }
        }

    }

}

From source file:com.adaptris.fs.NioWorkerTest.java

@Test
public void testLockWhileWriting() throws Exception {
    NioWorker worker = createWorker();/*from   w ww  .ja  v  a  2s  .  c  o m*/
    File f = File.createTempFile(this.getClass().getSimpleName(), "");
    f.delete();
    try {
        RandomAccessFile raf = new RandomAccessFile(f, "rwd");
        FileLock lock = raf.getChannel().lock();
        try {
            // Use the write method, because this "bypasses" the file.exists() check
            worker.write(BYTES, f);
            fail();
        } catch (FsException expected) {
            assertEquals(OverlappingFileLockException.class, expected.getCause().getClass());
        }
        lock.release();
        raf.close();
        f.delete();
        worker.put(BYTES, f);
    } finally {
        FileUtils.deleteQuietly(f);
    }
}

From source file:com.edgenius.wiki.service.impl.SitemapServiceImpl.java

private void appendSitemapIndex(String sitemap) throws IOException {
    File sitemapIndexFile = new File(mapResourcesRoot.getFile(), SITEMAP_INDEX_NAME);
    if (!sitemapIndexFile.exists()) {
        //if a new sitemap file
        List<String> lines = new ArrayList<String>();
        lines.add("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
        lines.add("<sitemapindex xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">");
        lines.add("</sitemapindex>");
        FileUtils.writeLines(sitemapIndexFile, lines);
    }/*from w ww .  j a v  a 2s.c  o  m*/

    RandomAccessFile rfile = new RandomAccessFile(sitemapIndexFile, "rw");
    FileChannel channel = rfile.getChannel();

    //this new content will append to end of file before XML end tag
    StringBuilder lines = new StringBuilder();
    lines.append("   <sitemap>\n");
    lines.append("     <loc>" + WebUtil.getHostAppURL() + SITEMAP_URL_CONTEXT + sitemap + "</loc>\n");
    lines.append("     <lastmod>" + TIME_FORMAT.format(new Date()) + " </lastmod>\n");
    lines.append("   </sitemap>\n");
    //the last tag will be overwrite, so append it again to new content. 
    lines.append(SITEMAP_INDEX_TAIL_FLAG);
    byte[] content = lines.toString().getBytes();

    ByteBuffer byteBuf = ByteBuffer.allocate(512);
    // seek first
    int len = 0, headIdx = 0;
    long tailIdx = channel.size() - 512;
    tailIdx = tailIdx < 0 ? 0 : tailIdx;

    long headPos = -1;
    StringBuilder header = new StringBuilder();
    while ((len = channel.read(byteBuf, tailIdx)) > 0) {
        byteBuf.rewind();
        byte[] dst = new byte[len];
        byteBuf.get(dst, 0, len);
        header.append(new String(dst, "UTF8"));
        headIdx = header.indexOf(SITEMAP_INDEX_TAIL_FLAG);
        if (headIdx != -1) {
            headPos = channel.size() - header.substring(headIdx).getBytes().length;
            break;
        }
    }
    FileLock lock = channel.tryLock(headPos, content.length, false);
    try {
        channel.write(ByteBuffer.wrap(content), headPos);
    } finally {
        lock.release();
    }

    channel.force(false);
    rfile.close();

}

From source file:org.apache.geode.test.concurrent.FileBasedCountDownLatch.java

public void countDown() throws IOException {
    try (FileOutputStream out = new FileOutputStream(lockFile)) {
        java.nio.channels.FileLock lock = out.getChannel().lock();

        try {//from w w  w  . jav a2  s.c o m
            String fileContents = FileUtils.readFileToString(dataFile, Charsets.UTF_8);
            int currentValue = Integer.valueOf(fileContents);

            int newValue = currentValue - 1;
            FileUtils.writeStringToFile(dataFile, String.valueOf(newValue), Charsets.UTF_8);

        } finally {
            lock.release();
        }
    }
}

From source file:de.ailis.oneinstance.OneInstance.java

/**
 * Releases the specified lock./*from w w w.j  a  v  a2s .  com*/
 * 
 * @param fileLock
 *            The file lock to release. If null then nothing is done.
 */
private void release(final FileLock fileLock) {
    if (fileLock == null)
        return;
    try {
        fileLock.release();
    } catch (IOException e) {
        LOG.warn("Unable to release lock file: " + e, e);
    }
}

From source file:com.emc.vipr.sync.source.FilesystemSource.java

protected void delete(File file) {
    // Try to lock the file first.  If this fails, the file is
    // probably open for write somewhere.
    // Note that on a mac, you can apparently delete files that
    // someone else has open for writing, and can lock files
    // too./* w  w w  .j a  v  a2 s  .c o  m*/
    // Must make sure to throw exceptions when necessary to flag actual failures as opposed to skipped files.
    if (file.isDirectory()) {
        File metaDir = getMetaFile(file).getParentFile();
        if (metaDir.exists())
            metaDir.delete();
        // Just try and delete dir
        if (!file.delete()) {
            LogMF.warn(l4j, "Failed to delete directory {0}", file);
        }
    } else {
        boolean tryDelete = true;
        if (deleteOlderThan > 0) {
            if (System.currentTimeMillis() - file.lastModified() < deleteOlderThan) {
                LogMF.info(l4j, "not deleting {0}; it is not at least {1} ms old", file, deleteOlderThan);
                tryDelete = false;
            }
        }
        if (deleteCheckScript != null) {
            String[] args = new String[] { deleteCheckScript.getAbsolutePath(), file.getAbsolutePath() };
            try {
                l4j.debug("delete check: " + Arrays.asList(args));
                Process p = Runtime.getRuntime().exec(args);
                while (true) {
                    try {
                        int exitCode = p.exitValue();

                        if (exitCode == 0) {
                            LogMF.debug(l4j, "delete check OK, exit code {0}", exitCode);
                        } else {
                            LogMF.info(l4j, "delete check failed, exit code {0}.  Not deleting file.",
                                    exitCode);
                            tryDelete = false;
                        }
                        break;
                    } catch (IllegalThreadStateException e) {
                        // Ignore.
                    }
                }
            } catch (IOException e) {
                LogMF.info(l4j, "error executing delete check script: {0}.  Not deleting file.", e.toString());
                tryDelete = false;
            }
        }
        RandomAccessFile raf = null;
        if (tryDelete) {
            try {
                raf = new RandomAccessFile(file, "rw");
                FileChannel fc = raf.getChannel();
                FileLock flock = fc.lock();
                // If we got here, we should be good.
                flock.release();
                if (!file.delete()) {
                    throw new RuntimeException(MessageFormat.format("Failed to delete {0}", file));
                }
            } catch (IOException e) {
                throw new RuntimeException(MessageFormat
                        .format("File {0} not deleted, it appears to be open: {1}", file, e.getMessage()));
            } finally {
                if (raf != null) {
                    try {
                        raf.close();
                    } catch (IOException e) {
                        // Ignore.
                    }
                }
            }
        }
    }
}

From source file:fr.acxio.tools.agia.alfresco.ContentFileDeleteWriterTest.java

@Test
public void testWriteCannotDeleteThrowException() throws Exception {
    ContentFileDeleteWriter aWriter = new ContentFileDeleteWriter();
    aWriter.setIgnoreErrors(false);// w  w  w  .  ja  va 2s .  c  o m

    File aOriginFile = new File("src/test/resources/testFiles/content1.pdf");
    File aDestinationFile1 = new File("target/content5.pdf");
    FileCopyUtils.copy(aOriginFile, aDestinationFile1);

    List<NodeList> aData = new ArrayList<NodeList>();
    aData.add(createNodeList(aDestinationFile1.getAbsolutePath()));

    assertTrue(aDestinationFile1.exists());

    FileInputStream aInputStream = new FileInputStream(aDestinationFile1);
    FileLock aLock = aInputStream.getChannel().lock(0L, Long.MAX_VALUE, true); // shared lock

    try {
        aWriter.write(aData);
        assertTrue(aDestinationFile1.exists());
        fail("Must throw an exception");
    } catch (IOException e) {
        // Fall through
    } finally {
        aLock.release();
        aInputStream.close();
    }
}