Package java.nio.channels

Examples of java.nio.channels.FileLock


                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 {


        File uncompressedFile = DiskCache.getFileStandardPolicy(raf.getLocation() + ".uncompress");

        if (uncompressedFile.exists() && uncompressedFile.length() > 0) {
          // see if its locked - another thread is writing it
          FileInputStream fstream = null;
          FileLock lock = null;
          try {
            fstream = new FileInputStream(uncompressedFile);
            //lock = fstream.getChannel().lock(0, 1, true); // wait till its unlocked

            while (true) { // loop waiting for the lock
              try {
                lock = fstream.getChannel().lock(0, 1, true); // wait till its unlocked
                break;

              } catch (OverlappingFileLockException oe) { // not sure why lock() doesnt block
                try {
                  Thread.sleep(100); // msecs
                } catch (InterruptedException e1) {
                  break;
                }
              }
            }

          } finally {
            if (lock != null) lock.release();
            if (fstream != null) fstream.close();
          }
          uraf = new ucar.unidata.io.RandomAccessFile(uncompressedFile.getPath(), "r");

        } else {

   * @return raf of uncompressed file
   * @throws IOException on read error
   */
  private RandomAccessFile uncompress(RandomAccessFile inputRaf, String ufilename) throws IOException {
    RandomAccessFile outputRaf = new RandomAccessFile(ufilename, "rw");
    FileLock lock = null;

    while (true) { // loop waiting for the lock
      try {
        lock = outputRaf.getRandomAccessFile().getChannel().lock(0, 1, false);
        break;

      } catch (OverlappingFileLockException oe) { // not sure why lock() doesnt block
        try {
          Thread.sleep(100); // msecs
        } catch (InterruptedException e1) {
        }
      }
    }

    try {
      inputRaf.seek(0);
      byte[] header = new byte[Level2Record.FILE_HEADER_SIZE];
      inputRaf.read(header);
      outputRaf.write(header);

      boolean eof = false;
      int numCompBytes;
      byte[] ubuff = new byte[40000];
      byte[] obuff = new byte[40000];
      try {
        CBZip2InputStream cbzip2 = new CBZip2InputStream();
        while (!eof) {
          try {
            numCompBytes = inputRaf.readInt();
            if (numCompBytes == -1) {
              if (log.isDebugEnabled()) log.debug("  done: numCompBytes=-1 ");
              break;
            }
          } catch (EOFException ee) {
            log.warn("  got EOFException ");
            break; // assume this is ok
          }

          if (log.isDebugEnabled()) {
            log.debug("reading compressed bytes " + numCompBytes + " input starts at " + inputRaf.getFilePointer() + "; output starts at " + outputRaf.getFilePointer());
          }
          /*
          * For some stupid reason, the last block seems to
          * have the number of bytes negated.  So, we just
          * assume that any negative number (other than -1)
          * is the last block and go on our merry little way.
          */
          if (numCompBytes < 0) {
            if (log.isDebugEnabled()) log.debug("last block?" + numCompBytes);
            numCompBytes = -numCompBytes;
            eof = true;
          }
          byte[] buf = new byte[numCompBytes];
          inputRaf.readFully(buf);
          ByteArrayInputStream bis = new ByteArrayInputStream(buf, 2, numCompBytes - 2);

          //CBZip2InputStream cbzip2 = new CBZip2InputStream(bis);
          cbzip2.setStream(bis);
          int total = 0;
          int nread;
          /*
          while ((nread = cbzip2.read(ubuff)) != -1) {
            dout2.write(ubuff, 0, nread);
            total += nread;
          }
          */
          try {
            while ((nread = cbzip2.read(ubuff)) != -1) {
              if (total + nread > obuff.length) {
                byte[] temp = obuff;
                obuff = new byte[temp.length * 2];
                System.arraycopy(temp, 0, obuff, 0, temp.length);
              }
              System.arraycopy(ubuff, 0, obuff, total, nread);
              total += nread;
            }
            if (obuff.length >= 0) outputRaf.write(obuff, 0, total);
          } catch (BZip2ReadException ioe) {
            log.warn("Nexrad2IOSP.uncompress ", ioe);
          }
          float nrecords = (float) (total / 2432.0);
          if (log.isDebugEnabled())
            log.debug("  unpacked " + total + " num bytes " + nrecords + " records; ouput ends at " + outputRaf.getFilePointer());
        }

      } catch (Exception e) {
        if (outputRaf != null) outputRaf.close();
        outputRaf = null;

        // dont leave bad files around
        File ufile = new File(ufilename);
        if (ufile.exists()) {
          if (!ufile.delete())
            log.warn("failed to delete uncompressed file (IOException)" + ufilename);
        }

        if (e instanceof IOException)
          throw (IOException) e;
        else
          throw new RuntimeException(e);
      }

    } finally {
      if (null != outputRaf) outputRaf.flush();
      if (lock != null) lock.release();
    }

    return outputRaf;
  }

      File infoFile = new File(lockDir, INFO_FILE_NAME);
      File lockedFile = new File(lockDir, LOCK_FILE_NAME);

      RandomAccessFile raf = new RandomAccessFile(lockedFile, "rw");
      try {
        FileLock fileLock = raf.getChannel().lock();
        lock = createLock(raf, fileLock);
        sign(infoFile);
      }
      catch (IOException e) {
        if (lock != null) {

      boolean revokeLock = false;

      File lockedFile = new File(lockDir, LOCK_FILE_NAME);
      RandomAccessFile raf = new RandomAccessFile(lockedFile, "rw");
      try {
        FileLock fileLock = raf.getChannel().tryLock();

        if (fileLock != null) {
          logger.warn("Removing invalid lock {}", getLockedBy());
          fileLock.release();
          revokeLock = true;
        }
      }
      catch (OverlappingFileLockException exc) {
        // lock is still valid

      FileOutputStream fos = new FileOutputStream(cacheFile);
      channel = fos.getChannel();

      // Try acquiring the lock without blocking. This method returns
      // null or throws an exception if the file is already locked.
      FileLock lock;
      try {
        lock = channel.tryLock();
      } catch (OverlappingFileLockException e) {
        // File is already locked in this thread or virtual machine
        return; // give up

    // see if already decompressed, look in cache if need be
    File uncompressedFile = DiskCache.getFileStandardPolicy(uncompressedFilename);
    if (uncompressedFile.exists() && uncompressedFile.length() > 0) {
      // see if its locked - another thread is writing it
      FileInputStream stream = null;
      FileLock lock = null;
      try {
        stream = new FileInputStream(uncompressedFile);
        // obtain the lock
        while (true) { // loop waiting for the lock
          try {
            lock = stream.getChannel().lock(0, 1, true); // wait till its unlocked
            break;

          } catch (OverlappingFileLockException oe) { // not sure why lock() doesnt block
            try {
              Thread.sleep(100); // msecs
            } catch (InterruptedException e1) {
              break;
            }
          }
        }

        if (debugCompress) System.out.println("found uncompressed " + uncompressedFile + " for " + filename);
        return uncompressedFile.getPath();
      } finally {
        if (lock != null) lock.release();
        if (stream != null) stream.close();
      }
    }

    // ok gonna write it
    // make sure compressed file exists
    File file = new File(filename);
    if (!file.exists())
      return null; // bail out  */

    InputStream in = null;
    FileOutputStream fout = new FileOutputStream(uncompressedFile);

    // obtain the lock
    FileLock lock = null;
    while (true) { // loop waiting for the lock
      try {
        lock = fout.getChannel().lock(0, 1, false);
        break;

      } catch (OverlappingFileLockException oe) { // not sure why lock() doesnt block
        try {
          Thread.sleep(100); // msecs
        } catch (InterruptedException e1) {
        }
      }
    }

    try {
      if (suffix.equalsIgnoreCase("Z")) {
        in = new UncompressInputStream(new FileInputStream(filename));
        copy(in, fout, 100000);
        if (debugCompress) System.out.println("uncompressed " + filename + " to " + uncompressedFile);

      } else if (suffix.equalsIgnoreCase("zip")) {
        in = new ZipInputStream(new FileInputStream(filename));
        copy(in, fout, 100000);
        if (debugCompress) System.out.println("unzipped " + filename + " to " + uncompressedFile);

      } else if (suffix.equalsIgnoreCase("bz2")) {
        in = new CBZip2InputStream(new FileInputStream(filename), true);
        copy(in, fout, 100000);
        if (debugCompress) System.out.println("unbzipped " + filename + " to " + uncompressedFile);

      } else if (suffix.equalsIgnoreCase("gzip") || suffix.equalsIgnoreCase("gz")) {

        in = new GZIPInputStream(new FileInputStream(filename));
        copy(in, fout, 100000);

        if (debugCompress) System.out.println("ungzipped " + filename + " to " + uncompressedFile);
      }
    } catch (Exception e) {

      // appears we have to close before we can delete
      if (fout != null) fout.close();
      fout = null;

      // dont leave bad files around
      if (uncompressedFile.exists()) {
        if (!uncompressedFile.delete())
          log.warn("failed to delete uncompressed file (IOException)" + uncompressedFile);
      }
      throw e;

    } finally {
      if (lock != null) lock.release();
      if (in != null) in.close();
      if (fout != null) fout.close();
    }

    return uncompressedFile.getPath();

        // We got an IOException while trying to open the file.
        // Try the next file.
        continue;
    }
    try {
        FileLock fl = fc.tryLock();
        if (fl == null) {
            // We failed to get the lock.  Try next file.
      continue;
        }
        // We got the lock OK.

    final String conMethodName = conClassName + "::doLock";

    // randomFile = new RandomAccessFile(this.strFileName, pstrAccessMode);
    randomFile = new RandomAccessFile(this, pstrAccessMode);
    FileChannel channel = randomFile.getChannel();
    FileLock fleLock = null;
    try {
      fleLock = channel.tryLock();
    }
    catch (OverlappingFileLockException e) {
      flgFileIsLocked = true;

                if (lockType == SqlJetLockType.SHARED
                        || (lockType == SqlJetLockType.EXCLUSIVE && this.lockType.compareTo(SqlJetLockType.PENDING) < 0)) {

                    if (lockType != SqlJetLockType.SHARED) {
            if (lockInfo.sharedLockCount <= 1) {
                          final FileLock sharedLock = locks.remove(SqlJetLockType.SHARED);
                          if(null != sharedLock) {
                            sharedLock.release();
                            lockInfo.sharedLock = null;
                          }
            }
                    }

                    if (!locks.containsKey(SqlJetLockType.PENDING)) {
                        final FileLock pendingLock = fileLockManager.tryLock(PENDING_BYTE, 1,
                                lockType == SqlJetLockType.SHARED);
                        if (null == pendingLock)
                            return false;
                        locks.put(SqlJetLockType.PENDING, pendingLock);
                    }
                }

                /*
                 * If control gets to this point, then actually go ahead and
                 * make operating system calls for the specified lock.
                 */
                if (lockType == SqlJetLockType.SHARED) {

                    /* Now get the read-lock */
                    final FileLock sharedLock = fileLockManager.tryLock(SHARED_FIRST, SHARED_SIZE, true);
                    locks.put(SqlJetLockType.SHARED, sharedLock);

                    /* Drop the temporary PENDING lock */
                    final FileLock pendingLock = locks.get(SqlJetLockType.PENDING);
                    if (null != pendingLock) {
                        pendingLock.release();
                        locks.remove(SqlJetLockType.PENDING);
                    }

                    if (null == sharedLock)
                        return false;

                    this.lockType = SqlJetLockType.SHARED;
                    openCount.numLock++;
                    lockInfo.sharedLockCount = 1;
                    lockInfo.sharedLock = sharedLock;

                } else if (lockType == SqlJetLockType.EXCLUSIVE && lockInfo.sharedLockCount > 1) {
                    /*
                     * We are trying for an exclusive lock but another thread in
                     * this same process is still holding a shared lock.
                     */
                    return false;

                } else {
                    /*
                     * The request was for a RESERVED or EXCLUSIVE lock. It is
                     * assumed that there is a SHARED or greater lock on the
                     * file already.
                     */
                    assert (SqlJetLockType.NONE != this.lockType);

                    switch (lockType) {
                    case RESERVED:
                        final FileLock reservedLock = fileLockManager.tryLock(RESERVED_BYTE, 1, false);
                        if (null == reservedLock)
                            return false;
                        locks.put(SqlJetLockType.RESERVED, reservedLock);
                        break;
                    case EXCLUSIVE:
                        final FileLock exclusiveLock = fileLockManager.tryLock(SHARED_FIRST, SHARED_SIZE, false);
                        if (null == exclusiveLock) {
                            this.lockType = SqlJetLockType.PENDING;
                            lockInfo.lockType = SqlJetLockType.PENDING;
                            return false;
                        }

TOP

Related Classes of java.nio.channels.FileLock

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.