/*
 * FileOperation__FileLockTest class.
 *
 * Copyright (C) 2007 SATOH Takayuki All Rights Reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */
package ts.util.file;

import java.io.*;
import java.nio.channels.*;

/**
 * ファイルのロックを実行する。
 *
 * @author  佐藤隆之.
 * @version $Revision: 1.1.1.1 $, $Date: 2010-10-16 00:03:47 $
 */
public class FileOperation__FileLockTest
{
  public static void main(String[] args)
  {
    boolean shared = (args[0].equals("shared")) ? true : false;
    File lockedFile = new File(args[1]);
    File runFile = new File(args[2]);

    RandomAccessFile raf = null;
    FileLock lock = null;
    try {
      raf = new RandomAccessFile(lockedFile, shared ? "r" : "rw");
      FileChannel channel = raf.getChannel();
      lock = channel.lock(0, Long.MAX_VALUE, shared);
      System.out.println(lock.isShared() ?
        "Do shared lock on: "  + lockedFile.getName() :
        "Do exclusive lock on: " + lockedFile.getName() );
      System.out.flush();

      while (runFile.exists()) ;
    }
    catch (Exception e) {
      e.printStackTrace(System.out);
    }
    finally {
      if (lock != null) try { lock.release(); } catch (Exception e) {}
      if (raf != null) try { raf.close(); } catch (Exception e) {}
    }

    System.out.println(shared ?
      "Release shared lock on: "  + lockedFile.getName() :
      "Release exclusive lock on: "  + lockedFile.getName() );
    System.out.flush();
  }
}

