Example usage for java.nio.channels FileChannel tryLock

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

Introduction

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

Prototype

public final FileLock tryLock() throws IOException 

Source Link

Document

Attempts to acquire an exclusive lock on this channel's file.

Usage

From source file:JNLPAppletLauncher.java

/**
 * Called by the Reaper thread to delete old temp directories
 * Only one of these threads will run per JVM invocation.
 *///from   w w  w .  j ava 2 s . c  o m
private static void deleteOldTempDirs() {
    if (VERBOSE) {
        System.err.println("*** Reaper: deleteOldTempDirs in " + tmpBaseDir.getAbsolutePath());
    }

    // enumerate list of jnl*.lck files, ignore our own jlnNNNN file
    final String ourLockFile = tmpRootPropValue + ".lck";
    FilenameFilter lckFilter = new FilenameFilter() {
        /* @Override */
        public boolean accept(File dir, String name) {
            return name.endsWith(".lck") && !name.equals(ourLockFile);
        }
    };

    // For each file <file>.lck in the list we will first try to lock
    // <file>.tmp if that succeeds then we will try to lock <file>.lck
    // (which should always succeed unless there is a problem). If we can
    // get the lock on both files, then it must be an old installation, and
    // we will delete it.
    String[] fileNames = tmpBaseDir.list(lckFilter);
    if (fileNames != null) {
        for (int i = 0; i < fileNames.length; i++) {
            String lckFileName = fileNames[i];
            String tmpDirName = lckFileName.substring(0, lckFileName.lastIndexOf(".lck"));
            String tmpFileName = tmpDirName + ".tmp";

            File lckFile = new File(tmpBaseDir, lckFileName);
            File tmpFile = new File(tmpBaseDir, tmpFileName);
            File tmpDir = new File(tmpBaseDir, tmpDirName);

            if (lckFile.exists() && tmpFile.exists() && tmpDir.isDirectory()) {
                FileOutputStream tmpOut = null;
                FileChannel tmpChannel = null;
                FileLock tmpLock = null;

                try {
                    tmpOut = new FileOutputStream(tmpFile);
                    tmpChannel = tmpOut.getChannel();
                    tmpLock = tmpChannel.tryLock();
                } catch (Exception ex) {
                    // Ignore exceptions
                    if (DEBUG) {
                        ex.printStackTrace();
                    }
                }

                if (tmpLock != null) {
                    FileOutputStream lckOut = null;
                    FileChannel lckChannel = null;
                    FileLock lckLock = null;

                    try {
                        lckOut = new FileOutputStream(lckFile);
                        lckChannel = lckOut.getChannel();
                        lckLock = lckChannel.tryLock();
                    } catch (Exception ex) {
                        if (DEBUG) {
                            ex.printStackTrace();
                        }
                    }

                    if (lckLock != null) {
                        // Recursively remove the old tmpDir and all of
                        // its contents
                        removeAll(tmpDir);

                        // Close the streams and delete the .lck and .tmp
                        // files. Note that there is a slight race condition
                        // in that another process could open a stream at
                        // the same time we are trying to delete it, which will
                        // prevent deletion, but we won't worry about it, since
                        // the worst that will happen is we might have an
                        // occasional 0-byte .lck or .tmp file left around
                        try {
                            lckOut.close();
                        } catch (IOException ex) {
                        }
                        lckFile.delete();
                        try {
                            tmpOut.close();
                        } catch (IOException ex) {
                        }
                        tmpFile.delete();
                    } else {
                        try {
                            // Close the file and channel for the *.lck file
                            if (lckOut != null) {
                                lckOut.close();
                            }
                            // Close the file/channel and release the lock
                            // on the *.tmp file
                            tmpOut.close();
                            tmpLock.release();
                        } catch (IOException ex) {
                            if (DEBUG) {
                                ex.printStackTrace();
                            }
                        }
                    }
                }
            } else {
                if (VERBOSE) {
                    System.err.println("    Skipping: " + tmpDir.getAbsolutePath());
                }
            }
        }
    }
}

From source file:MyZone.Settings.java

private boolean saveXML(String filename, Document dom) {
    File file = null;// w  ww . jav  a  2  s  .  c  om
    FileChannel channel = null;
    FileLock lock = null;
    FileOutputStream toWrite = null;
    try {
        if (!new File(filename).exists()) {
            String dirName = filename.substring(0, filename.lastIndexOf("/"));
            boolean success = (new File(dirName)).mkdirs();
            if (!success && !(new File(dirName)).exists()) {
                return false;
            }
            OutputFormat format = new OutputFormat(dom);
            format.setIndenting(true);
            file = new File(filename);
            toWrite = new FileOutputStream(file, false);
            XMLSerializer serializer = new XMLSerializer(toWrite, format);
            serializer.serialize(dom);
        } else {
            file = new File(filename);
            toWrite = new FileOutputStream(file, false);
            channel = toWrite.getChannel();
            while ((lock = channel.tryLock()) == null) {
                Thread.yield();
            }
            OutputFormat format = new OutputFormat(dom);
            format.setIndenting(true);
            XMLSerializer serializer = new XMLSerializer(toWrite, format);
            serializer.serialize(dom);
            return true;
        }
    } catch (Exception e) {
        if (DEBUG) {
            e.printStackTrace();
        }
        return false;
    } finally {
        try {
            if (lock != null) {
                lock.release();
            }
            if (channel != null) {
                channel.close();
            }
            if (toWrite != null) {
                toWrite.flush();
                toWrite.close();
            }
        } catch (Exception e) {
            if (DEBUG) {
                e.printStackTrace();
            }
            return false;
        }
    }
    return false;
}

From source file:org.apache.axiom.attachments.impl.BufferUtils.java

/**
 * Opimized writing to FileOutputStream using a channel
 * @param is//  w w w. j a va2 s  . co  m
 * @param fos
 * @return false if lock was not aquired
 * @throws IOException
 */
public static boolean inputStream2FileOutputStream(InputStream is, FileOutputStream fos) throws IOException {

    // See if a file channel and lock can be obtained on the FileOutputStream
    FileChannel channel = null;
    FileLock lock = null;
    ByteBuffer bb = null;
    try {
        channel = fos.getChannel();
        if (channel != null) {
            lock = channel.tryLock();
        }
        bb = getTempByteBuffer();
    } catch (Throwable t) {
    }
    if (lock == null || bb == null || !bb.hasArray()) {
        releaseTempByteBuffer(bb);
        return false; // lock could not be set or bb does not have direct array access
    }

    try {

        // Read directly into the ByteBuffer array
        int bytesRead = is.read(bb.array());
        // Continue reading until no bytes are read and no
        // bytes are now available.
        while (bytesRead > 0 || is.available() > 0) {
            if (bytesRead > 0) {
                int written = 0;

                if (bytesRead < BUFFER_LEN) {
                    // If the ByteBuffer is not full, allocate a new one
                    ByteBuffer temp = ByteBuffer.allocate(bytesRead);
                    temp.put(bb.array(), 0, bytesRead);
                    temp.position(0);
                    written = channel.write(temp);
                } else {
                    // Write to channel
                    bb.position(0);
                    written = channel.write(bb);
                    bb.clear();
                }

            }

            // REVIEW: Do we need to ensure that bytesWritten is 
            // the same as the number of bytes sent ?

            bytesRead = is.read(bb.array());
        }
    } finally {
        // Release the lock
        lock.release();
        releaseTempByteBuffer(bb);
    }
    return true;
}

From source file:org.apache.camel.component.file.strategy.FileLockExclusiveReadLockStrategy.java

public boolean acquireExclusiveReadLock(GenericFileOperations<File> operations, GenericFile<File> file,
        Exchange exchange) throws Exception {
    File target = new File(file.getAbsoluteFilePath());

    if (LOG.isTraceEnabled()) {
        LOG.trace("Waiting for exclusive read lock to file: " + target);
    }/* w w  w . j a v a2  s  . co m*/

    try {
        // try to acquire rw lock on the file before we can consume it
        FileChannel channel = new RandomAccessFile(target, "rw").getChannel();

        boolean exclusive = false;
        StopWatch watch = new StopWatch();

        while (!exclusive) {
            // timeout check
            if (timeout > 0) {
                long delta = watch.taken();
                if (delta > timeout) {
                    LOG.warn("Cannot acquire read lock within " + timeout + " millis. Will skip the file: "
                            + target);
                    // we could not get the lock within the timeout period, so return false
                    return false;
                }
            }

            // get the lock using either try lock or not depending on if we are using timeout or not
            try {
                lock = timeout > 0 ? channel.tryLock() : channel.lock();
            } catch (IllegalStateException ex) {
                // Also catch the OverlappingFileLockException here. Do nothing here                    
            }
            if (lock != null) {
                if (LOG.isTraceEnabled()) {
                    LOG.trace("Acquired exclusive read lock: " + lock + " to file: " + target);
                }
                lockFileName = target.getName();
                exclusive = true;
            } else {
                boolean interrupted = sleep();
                if (interrupted) {
                    // we were interrupted while sleeping, we are likely being shutdown so return false
                    return false;
                }
            }
        }
    } catch (IOException e) {
        // must handle IOException as some apps on Windows etc. will still somehow hold a lock to a file
        // such as AntiVirus or MS Office that has special locks for it's supported files
        if (timeout == 0) {
            // if not using timeout, then we cant retry, so rethrow
            throw e;
        }
        if (LOG.isDebugEnabled()) {
            LOG.debug("Cannot acquire read lock. Will try again.", e);
        }
        boolean interrupted = sleep();
        if (interrupted) {
            // we were interrupted while sleeping, we are likely being shutdown so return false
            return false;
        }
    }

    return true;
}

From source file:org.apache.hadoop.chukwa.inputtools.mdl.LoaderServer.java

public void init() throws IOException {
    String pidLong = ManagementFactory.getRuntimeMXBean().getName();
    String[] items = pidLong.split("@");
    String pid = items[0];/*from w w w . java  2 s  . com*/
    String chukwaPath = System.getProperty("CHUKWA_HOME");
    StringBuffer pidFilesb = new StringBuffer();
    pidFilesb.append(chukwaPath).append("/var/run/").append(name).append(".pid");
    try {
        File pidFile = new File(pidFilesb.toString());

        pidFileOutput = new FileOutputStream(pidFile);
        pidFileOutput.write(pid.getBytes());
        pidFileOutput.flush();
        FileChannel channel = pidFileOutput.getChannel();
        LoaderServer.lock = channel.tryLock();
        if (LoaderServer.lock != null) {
            log.info("Initlization succeeded...");
        } else {
            throw (new IOException());
        }
    } catch (IOException ex) {
        System.out.println("Initializaiton failed: can not write pid file.");
        log.error("Initialization failed...");
        log.error(ex.getMessage());
        System.exit(-1);
        throw ex;

    }

}

From source file:org.apache.hadoop.chukwa.util.PidFile.java

public void init() throws IOException {
    String pidLong = ManagementFactory.getRuntimeMXBean().getName();
    String[] items = pidLong.split("@");
    String pid = items[0];/* ww  w . j  ava  2s .  c  o m*/
    String chukwaPath = System.getProperty("CHUKWA_HOME");
    StringBuffer pidFilesb = new StringBuffer();
    String pidDir = System.getenv("CHUKWA_PID_DIR");
    if (pidDir == null) {
        pidDir = chukwaPath + File.separator + "var" + File.separator + "run";
    }
    pidFilesb.append(pidDir).append(File.separator).append(name).append(".pid");
    try {
        File existsFile = new File(pidDir);
        if (!existsFile.exists()) {
            boolean success = (new File(pidDir)).mkdirs();
            if (!success) {
                throw (new IOException());
            }
        }
        File pidFile = new File(pidFilesb.toString());

        pidFileOutput = new FileOutputStream(pidFile);
        pidFileOutput.write(pid.getBytes());
        pidFileOutput.flush();
        FileChannel channel = pidFileOutput.getChannel();
        PidFile.lock = channel.tryLock();
        if (PidFile.lock != null) {
            log.debug("Initlization succeeded...");
        } else {
            throw (new IOException("Can not get lock on pid file: " + pidFilesb));
        }
    } catch (IOException ex) {
        System.out.println("Initialization failed: can not write pid file to " + pidFilesb);
        log.error("Initialization failed...");
        log.error(ex.getMessage());
        System.exit(-1);
        throw ex;

    }

}

From source file:org.apache.manifoldcf.agents.output.filesystem.FileOutputConnector.java

/** Add (or replace) a document in the output data store using the connector.
 * This method presumes that the connector object has been configured, and it is thus able to communicate with the output data store should that be
 * necessary./*from   w w w  .  j a  v  a  2 s . c  o  m*/
 * The OutputSpecification is *not* provided to this method, because the goal is consistency, and if output is done it must be consistent with the
 * output description, since that was what was partly used to determine if output should be taking place.  So it may be necessary for this method to decode
 * an output description string in order to determine what should be done.
 *@param documentURI is the URI of the document.  The URI is presumed to be the unique identifier which the output data store will use to process
 * and serve the document.  This URI is constructed by the repository connector which fetches the document, and is thus universal across all output connectors.
 *@param outputDescription is the description string that was constructed for this document by the getOutputDescription() method.
 *@param document is the document data to be processed (handed to the output data store).
 *@param authorityNameString is the name of the authority responsible for authorizing any access tokens passed in with the repository document.  May be null.
 *@param activities is the handle to an object that the implementer of an output connector may use to perform operations, such as logging processing activity.
 *@return the document status (accepted or permanently rejected).
 */
@Override
public int addOrReplaceDocumentWithException(String documentURI, VersionContext outputDescription,
        RepositoryDocument document, String authorityNameString, IOutputAddActivity activities)
        throws ManifoldCFException, ServiceInterruption, IOException {
    // Establish a session
    getSession();

    FileOutputConfig config = getConfigParameters(null);

    FileOutputSpecs specs = new FileOutputSpecs(getSpecNode(outputDescription.getSpecification()));
    ;
    StringBuffer path = new StringBuffer();

    String errorCode = "OK";
    String errorDesc = null;

    try {
        /*
          * make file path
          */
        if (specs.getRootPath() != null) {
            path.append(specs.getRootPath());
        }

        // If the path does not yet exist at the root level, it is dangerous to create it.
        File currentPath = new File(path.toString());
        if (!currentPath.exists())
            throw new ManifoldCFException("Root path does not yet exist: '" + currentPath + "'");
        if (!currentPath.isDirectory())
            throw new ManifoldCFException("Root path is not a directory: '" + currentPath + "'");

        String filePath = documentURItoFilePath(documentURI);

        // Build path one level at a time.  This is needed because there may be a collision at
        // every level.
        int index = 0;
        while (true) {
            int currentIndex = filePath.indexOf("/", index);
            if (currentIndex == -1)
                break;
            String dirName = filePath.substring(index, currentIndex);
            File newPath = new File(currentPath, dirName);
            index = currentIndex + 1;
            int suffix = 1;
            while (true) {
                if (newPath.exists() && newPath.isDirectory())
                    break;
                // Try to create it.  If we fail, check if it now exists as a file.
                if (newPath.mkdir())
                    break;
                // Hmm, didn't create.  If it is a file, we suffered a collision, so try again with ".N" as a suffix.
                if (newPath.exists()) {
                    if (newPath.isDirectory())
                        break;
                    newPath = new File(currentPath, dirName + "." + suffix);
                    suffix++;
                } else {
                    errorCode = activities.CREATED_DIRECTORY;
                    errorDesc = "Could not create directory '\"+newPath+\"'.  Permission issue?";
                    throw new ManifoldCFException(errorDesc);
                }
            }
            // Directory successfully created!
            currentPath = newPath;
            // Go on to the next one.
        }

        // Path successfully created.  Now create file.
        FileOutputStream output = null;
        String fileName = filePath.substring(index);
        File outputPath = new File(currentPath, fileName);
        int fileSuffix = 1;
        while (true) {
            try {
                output = new FileOutputStream(outputPath);
                break;
            } catch (FileNotFoundException e) {
                // Figure out why it could not be created.
                if (outputPath.exists() && !outputPath.isFile()) {
                    // try a new file
                    outputPath = new File(currentPath, fileName + "." + fileSuffix);
                    fileSuffix++;
                    continue;
                }
                // Probably some other error
                errorCode = e.getClass().getSimpleName().toUpperCase(Locale.ROOT);
                errorDesc = "Could not create file '" + outputPath + "': " + e.getMessage();
                throw new ManifoldCFException(errorDesc, e);
            }
        }

        try {
            /*
              * lock file
              */
            FileChannel channel = output.getChannel();
            FileLock lock = channel.tryLock();
            if (lock == null) {
                errorCode = ServiceInterruption.class.getSimpleName().toUpperCase(Locale.ROOT);
                errorDesc = "Could not lock file: '" + outputPath + "'";
                throw new ServiceInterruption(errorDesc, null, 1000L, -1L, 10, false);
            }

            try {

                /*
                  * write file
                  */
                InputStream input = document.getBinaryStream();
                byte buf[] = new byte[65536];
                int len;
                while ((len = input.read(buf)) != -1) {
                    output.write(buf, 0, len);
                }
                output.flush();
            } finally {
                // Unlock
                try {
                    if (lock != null) {
                        lock.release();
                    }
                } catch (ClosedChannelException e) {
                }
            }
        } finally {
            try {
                output.close();
            } catch (IOException e) {
            }
        }
    } catch (URISyntaxException e) {
        errorCode = e.getClass().getSimpleName().toUpperCase(Locale.ROOT);
        errorDesc = "Failed to write document due to: " + e.getMessage();
        handleURISyntaxException(e);
        return DOCUMENTSTATUS_REJECTED;
    } catch (FileNotFoundException e) {
        errorCode = e.getClass().getSimpleName().toUpperCase(Locale.ROOT);
        errorDesc = "Failed to write document due to: " + e.getMessage();
        handleFileNotFoundException(e);
        return DOCUMENTSTATUS_REJECTED;
    } catch (SecurityException e) {
        errorCode = e.getClass().getSimpleName().toUpperCase(Locale.ROOT);
        errorDesc = "Failed to write document due to: " + e.getMessage();
        handleSecurityException(e);
        return DOCUMENTSTATUS_REJECTED;
    } catch (IOException e) {
        errorCode = e.getClass().getSimpleName().toUpperCase(Locale.ROOT);
        errorDesc = "Failed to write document due to: " + e.getMessage();
        handleIOException(e);
        return DOCUMENTSTATUS_REJECTED;
    } finally {
        activities.recordActivity(null, INGEST_ACTIVITY, new Long(document.getBinaryLength()), documentURI,
                errorCode, errorDesc);
    }

    return DOCUMENTSTATUS_ACCEPTED;
}

From source file:org.apache.synapse.config.xml.MultiXMLConfigurationSerializer.java

private boolean isWritable(File file) {
    if (file.isDirectory()) {
        // Further generalize this check
        if (".svn".equals(file.getName())) {
            return true;
        }//from w  ww. j a v  a 2  s  .com

        File[] children = file.listFiles();
        for (File child : children) {
            if (!isWritable(child)) {
                log.warn("File: " + child.getName() + " is not writable");
                return false;
            }
        }

        if (!file.canWrite()) {
            log.warn("Directory: " + file.getName() + " is not writable");
            return false;
        }
        return true;

    } else {
        if (!file.canWrite()) {
            log.warn("File: " + file.getName() + " is not writable");
            return false;
        }

        FileOutputStream fos = null;
        FileLock lock = null;
        boolean writable;

        try {
            fos = new FileOutputStream(file, true);
            FileChannel channel = fos.getChannel();
            lock = channel.tryLock();
        } catch (IOException e) {
            log.warn("Error while attempting to lock the file: " + file.getName(), e);
            writable = false;
        } finally {
            if (lock != null) {
                writable = true;
                try {
                    lock.release();
                } catch (IOException e) {
                    log.warn("Error while releasing the lock on file: " + file.getName(), e);
                    writable = false;
                }
            } else {
                log.warn("Unable to acquire lock on file: " + file.getName());
                writable = false;
            }

            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                log.warn("Error while closing the stream on file: " + file.getName(), e);
                writable = false;
            }
        }
        return writable;
    }
}

From source file:org.fuin.utils4j.Utils4J.java

/**
 * Lock the file./*ww w . j a  v  a2  s  . c o m*/
 * 
 * @param file
 *            File to lock - Cannot be <code>null</code>.
 * @param tryLockMax
 *            Number of tries to lock before throwing an exception.
 * @param tryWaitMillis
 *            Milliseconds to sleep between retries.
 * 
 * @return FileLock.
 * 
 * @throws LockingFailedException
 *             Locking the file failed.
 */
public static FileLock lockRandomAccessFile(final RandomAccessFile file, final int tryLockMax,
        final long tryWaitMillis) throws LockingFailedException {

    checkNotNull("file", file);

    final FileChannel channel = file.getChannel();

    int tryCount = 0;
    while (tryCount < tryLockMax) {
        tryCount++;
        try {
            final FileLock lock = channel.tryLock();
            if (lock != null) {
                return lock;
            }
        } catch (final IOException ex) {
            throw new LockingFailedException("Unexpected I/O-Exception!", ex);
        } catch (final OverlappingFileLockException ex) {
            ignore();
        }
        try {
            Thread.sleep(tryWaitMillis);
        } catch (final InterruptedException ex) {
            throw new LockingFailedException("Unexpected interrupt!", ex);
        }
    }
    throw new LockingFailedException("Number of max tries (" + tryLockMax + ") exceeded!");

}

From source file:org.gtdfree.ApplicationHelper.java

public synchronized static final boolean tryLock(File location) {
    if (location == null) {
        location = getDataFolder();//from  www  .j a v  a  2s. c o m
    }
    if (exclusiveLock != null) {
        return false;
    }
    try {
        FileChannel lock = new RandomAccessFile(new File(location, LOCK_FILE_NAME), "rw").getChannel(); //$NON-NLS-1$
        exclusiveLock = lock.tryLock();
    } catch (Exception e) {
        return false;
    }
    return exclusiveLock != null;
}