Example usage for java.nio.channels FileChannel lock

List of usage examples for java.nio.channels FileChannel lock

Introduction

In this page you can find the example usage for java.nio.channels FileChannel lock.

Prototype

public final FileLock lock() throws IOException 

Source Link

Document

Acquires an exclusive lock on this channel's file.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    RandomAccessFile raf = new RandomAccessFile("test.txt", "rw");
    FileChannel fileChannel = raf.getChannel();

    FileLock lock = fileChannel.lock();

}

From source file:MainClass.java

public static void main(String[] args) throws IOException {

    FileInputStream inFile = new FileInputStream(args[0]);
    FileOutputStream outFile = new FileOutputStream(args[1]);

    FileChannel inChannel = inFile.getChannel();
    FileChannel outChannel = outFile.getChannel();

    FileLock outLock = outChannel.lock();
    FileLock inLock = inChannel.lock(0, inChannel.size(), true);

    inChannel.transferTo(0, inChannel.size(), outChannel);

    outLock.release();//from  w  w w.j  ava 2s .  co  m
    inLock.release();

    inChannel.close();
    outChannel.close();
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    File file = new File("filename");
    FileChannel channel = new RandomAccessFile(file, "rw").getChannel();

    FileLock lock = channel.lock();

    lock = channel.tryLock();/*from ww  w . ja  v  a2  s.com*/

    lock.release();

    channel.close();
}

From source file:com.moscona.dataSpace.debug.BadLocks.java

public static void main(String[] args) {
    try {//from www  . ja  v  a  2  s. com
        String lockFile = "C:\\Users\\Admin\\projects\\intellitrade\\tmp\\bad.lock";
        FileUtils.touch(new File(lockFile));
        FileOutputStream stream = new FileOutputStream(lockFile);
        //            FileInputStream stream = new FileInputStream(lockFile);
        FileChannel channel = stream.getChannel();
        //            FileLock lock = channel.lock(0,Long.MAX_VALUE, true);
        FileLock lock = channel.lock();
        stream.write(new UndocumentedJava().pid().getBytes());
        stream.flush();
        long start = System.currentTimeMillis();
        //            while (System.currentTimeMillis()-start < 10000) {
        //                Thread.sleep(500);
        //            }
        lock.release();
        stream.close();
        File f = new File(lockFile);
        System.out.println("Before write: " + FileUtils.readFileToString(f));
        FileUtils.writeStringToFile(f, "written after lock released");
        System.out.println("After write: " + FileUtils.readFileToString(f));
    } catch (Exception e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    }

}

From source file:eu.mhutti1.utils.storage.StorageDeviceUtils.java

private static boolean canWrite(File file) {
    try {/*from   w  w w  .  j  a  va 2s .co m*/
        RandomAccessFile randomAccessFile = new RandomAccessFile(file + "/test.txt", "rw");
        FileChannel fileChannel = randomAccessFile.getChannel();
        FileLock fileLock = fileChannel.lock();
        fileLock.release();
        fileChannel.close();
        randomAccessFile.close();
        return true;
    } catch (Exception ex) {
        return false;
    }
}

From source file:com.amazonaws.services.s3.internal.FileLocks.java

/**
 * Acquires an exclusive lock on the specified file, creating the file as
 * necessary. Caller of this method is responsible to call the
 * {@link #unlock(File)} method to prevent release leakage.
 * /*from   w  ww .  j ava  2 s  .c o m*/
 * @return true if the locking is successful; false otherwise.
 * 
 * @throws FileLockException if we failed to lock the file
 */
public static boolean lock(File file) {
    synchronized (lockedFiles) {
        if (lockedFiles.containsKey(file))
            return false; // already locked
    }
    FileLock lock = null;
    RandomAccessFile raf = null;
    try {
        // Note if the file does not already exist then an attempt will be
        // made to create it because of the use of "rw".
        raf = new RandomAccessFile(file, "rw");
        FileChannel channel = raf.getChannel();
        if (EXTERNAL_LOCK)
            lock = channel.lock();
    } catch (Exception e) {
        IOUtils.closeQuietly(raf, log);
        throw new FileLockException(e);
    }
    final boolean locked;
    synchronized (lockedFiles) {
        RandomAccessFile prev = lockedFiles.put(file, raf);
        if (prev == null) {
            locked = true;
        } else {
            // race condition: some other thread got locked it before this
            locked = false;
            lockedFiles.put(file, prev); // put it back
        }
    }
    if (locked) {
        if (log.isDebugEnabled())
            log.debug("Locked file " + file + " with " + lock);
    } else {
        IOUtils.closeQuietly(raf, log);
    }
    return locked;
}

From source file:org.ow2.proactive.resourcemanager.updater.RMNodeUpdater.java

private static boolean makeNodeUpToDate() {
    if (System.getProperty(NODE_URL_PROPERTY) != null) {

        String jarUrl = System.getProperty(NODE_URL_PROPERTY);
        String jarFile = SCHEDULER_NODE_JAR;

        if (System.getProperty(NODE_JAR_PROPERTY) != null) {
            jarFile = System.getProperty(NODE_JAR_PROPERTY);
        }/*from w w w  .ja  va 2  s  .  c o  m*/

        if (!isLocalJarUpToDate(jarUrl, jarFile)) {
            System.out.println("Downloading node.jar from " + jarUrl + " to " + jarFile);

            try {
                File destination = new File(jarFile);
                File lockFile = null;
                FileLock lock = null;

                if (destination.exists()) {

                    lockFile = new File(System.getProperty(TMP_DIR_PROPERTY) + "/lock");
                    if (!lockFile.exists()) {
                        lockFile.createNewFile();
                    }

                    System.out.println("Getting the lock on " + lockFile.getAbsoluteFile());
                    FileChannel channel = new RandomAccessFile(lockFile, "rw").getChannel();
                    lock = channel.lock();

                    if (isLocalJarUpToDate(jarUrl, jarFile)) {
                        System.out.println("Another process downloaded node.jar - don't do it anymore");
                        System.out.println("Releasing the lock on " + lockFile.getAbsoluteFile());
                        lock.release();
                        channel.close();

                        return false;
                    }
                }

                FileUtils.copyURLToFile(new URL(jarUrl), destination);
                System.out.println("Download finished");

                if (lock != null && lockFile != null) {
                    System.out.println("Releasing the lock on " + lockFile.getAbsoluteFile());
                    lock.release();
                }

                return true;

            } catch (Exception e) {
                System.err.println("Cannot download node.jar from " + jarUrl);
                e.printStackTrace();
            }
        }
    } else {
        System.out.println(
                "No java property " + NODE_URL_PROPERTY + " specified. Do not check for the new version.");
    }

    return false;
}

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

/**
 * Optimize version of copy method for file channels.
 * //from   w w w. j a va 2 s.c  o  m
 * @param bufferSize
 *            size of the temp buffer to use for this copy.
 * @param source
 *            the source {@link ReadableByteChannel}.
 * @param destination
 *            the destination {@link WritableByteChannel};.
 * @throws IOException
 *             in case something bad happens.
 */
public static void copyFileChannel(int bufferSize, FileChannel source, FileChannel destination)
        throws IOException {

    Objects.notNull(source, destination);
    if (!source.isOpen() || !destination.isOpen())
        throw new IllegalStateException("Source and destination channels must be open.");
    FileLock lock = null;
    try {

        lock = destination.lock();
        final long sourceSize = source.size();
        long pos = 0;
        while (pos < sourceSize) {
            // read and flip
            final long remaining = (sourceSize - pos);
            final int mappedZoneSize = remaining >= bufferSize ? bufferSize : (int) remaining;
            destination.transferFrom(source, pos, mappedZoneSize);
            // update zone
            pos += mappedZoneSize;

        }
    } finally {
        if (lock != null) {
            try {
                lock.release();
            } catch (Throwable t) {
                if (LOGGER.isInfoEnabled())
                    LOGGER.info(t.getLocalizedMessage(), t);
            }
        }

    }
}

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

/**
 * Reads the modsecurity configuration file on modsecurity machine.
 * @param json//from w  ww  .j  av  a 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:net.modsec.ms.connector.ConnRequestHandler.java

/**
 * Writes the modified modsecurity configurations to configuration file.
 * @param json contains modsecurity configurations as json object.
 *//*from   ww w  . ja  v  a 2  s . c om*/
@SuppressWarnings("unchecked")
public static void onWriteMSConfig(JSONObject json) {

    log.info("onWriteMSConfig called.. : " + json.toJSONString());

    MSConfig serviceCfg = MSConfig.getInstance();
    JSONObject jsonResp = new JSONObject();
    String fileName = serviceCfg.getConfigMap().get("MSConfigFile");
    String modifiedStr = "";

    InputStream ins = null;
    FileOutputStream out = null;
    BufferedReader br = null;

    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 = "";
            boolean check;

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

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

                    if (line.startsWith(field.toString())) {
                        if (line.trim().split(" ")[0].equals(field.toString())) {
                            if (json.containsKey(field.toString())) {

                                if (((String) json.get(field.toString())).equals("")
                                        || json.get(field.toString()) == null) {

                                    log.info("---------- Log Empty value ----:"
                                            + (String) json.get(field.toString()));
                                    json.remove(field.toString());
                                    check = false;
                                    continue;

                                } else {

                                    modifiedStr += field.toString() + " " + json.remove(field.toString())
                                            + "\n";
                                    check = false;

                                }

                            }
                        }
                    }

                }

                if (check) {
                    modifiedStr += line + "\n";
                }

            }

            for (ModSecConfigFields field : ModSecConfigFields.values()) {
                if (json.containsKey(field.toString())) {

                    if (json.get(field.toString()) == null
                            || ((String) json.get(field.toString())).equals("")) {

                        log.info("---------- Log Empty value ----:" + (String) json.get(field.toString()));
                        json.remove(field.toString());
                        check = false;
                        continue;

                    } else {
                        modifiedStr += field.toString() + " " + json.remove(field.toString()) + "\n";
                    }

                }

            }

            //modified string writing to modsecurity configurations
            log.info("Writing File :" + modifiedStr);
            out = new FileOutputStream(fileName);
            out.write(modifiedStr.getBytes());

            log.info("ModSecurity Configurations configurations Written ... ");

        } finally {

            lock.release();

        }

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

        //For Restarting modsecurity so that modified configuration can be applied
        JSONObject restartJson = new JSONObject();
        restartJson.put("action", "restart");

        String cmd = serviceCfg.getConfigMap().get("MSRestart");

        executeShScript(cmd, restartJson);

        jsonResp.put("action", "writeMSConfig");
        jsonResp.put("status", "0");
        jsonResp.put("message", "Configurations updated!");

    } catch (FileNotFoundException e1) {

        jsonResp.put("action", "writeMSConfig");
        jsonResp.put("status", "1");
        jsonResp.put("message", "Internal Service is down!");
        e1.printStackTrace();

    } catch (IOException | NullPointerException e) {

        jsonResp.put("action", "writeMSConfig");
        jsonResp.put("status", "0");
        jsonResp.put("message", "Unable to modify configurations. Sorry of inconvenience");
        e.printStackTrace();

    }

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