893N/A/*
3261N/A * Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
893N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
893N/A *
893N/A * This code is free software; you can redistribute it and/or modify it
893N/A * under the terms of the GNU General Public License version 2 only, as
893N/A * published by the Free Software Foundation.
893N/A *
893N/A * This code is distributed in the hope that it will be useful, but WITHOUT
893N/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
893N/A * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
893N/A * version 2 for more details (a copy is included in the LICENSE file that
893N/A * accompanied this code).
893N/A *
893N/A * You should have received a copy of the GNU General Public License version
893N/A * 2 along with this work; if not, write to the Free Software Foundation,
893N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
893N/A *
2362N/A * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
2362N/A * or visit www.oracle.com if you need additional information or have any
2362N/A * questions.
893N/A */
893N/A
893N/A
893N/A/* @test
1580N/A * @bug 4607272 6814948 6842687
893N/A * @summary Unit test for AsynchronousFileChannel#lock method
893N/A */
893N/A
893N/Aimport java.net.*;
893N/Aimport java.nio.ByteBuffer;
893N/Aimport java.nio.charset.Charset;
893N/Aimport java.nio.file.*;
893N/Aimport static java.nio.file.StandardOpenOption.*;
893N/Aimport java.nio.channels.*;
893N/Aimport java.io.File;
893N/Aimport java.io.IOException;
893N/Aimport java.io.InputStream;
893N/Aimport java.util.Random;
893N/Aimport java.util.concurrent.*;
893N/A
893N/Apublic class Lock {
893N/A
893N/A static final Random rand = new Random();
893N/A
893N/A public static void main(String[] args) throws Exception {
893N/A if (args.length > 0 && args[0].equals("-lockslave")) {
893N/A int port = Integer.parseInt(args[1]);
893N/A runLockSlave(port);
893N/A System.exit(0);
893N/A }
893N/A
893N/A LockSlaveMirror slave = startLockSlave();
893N/A try {
893N/A
2546N/A // create temporary file
893N/A File blah = File.createTempFile("blah", null);
893N/A blah.deleteOnExit();
893N/A
2546N/A // run tests
893N/A testLockProtocol(blah, slave);
893N/A testAsyncClose(blah, slave);
893N/A
2546N/A // eagerly clean-up
2546N/A blah.delete();
2546N/A
893N/A } finally {
893N/A slave.shutdown();
893N/A }
893N/A }
893N/A
893N/A // test locking protocol
893N/A static void testLockProtocol(File file, LockSlaveMirror slave)
893N/A throws Exception
893N/A {
893N/A FileLock fl;
893N/A
893N/A // slave VM opens file and acquires exclusive lock
893N/A slave.open(file.getPath()).lock();
893N/A
893N/A AsynchronousFileChannel ch = AsynchronousFileChannel
893N/A .open(file.toPath(), READ, WRITE);
893N/A
893N/A // this VM tries to acquire lock
893N/A // (lock should not be acquire until released by slave VM)
893N/A Future<FileLock> result = ch.lock();
893N/A try {
893N/A result.get(2, TimeUnit.SECONDS);
893N/A throw new RuntimeException("Timeout expected");
893N/A } catch (TimeoutException x) {
893N/A }
893N/A
893N/A // slave VM releases lock
893N/A slave.unlock();
893N/A
893N/A // this VM should now acquire lock
893N/A fl = result.get();
893N/A fl.release();
893N/A
893N/A // slave VM acquires lock on range
893N/A slave.lock(0, 10, false);
893N/A
893N/A // this VM acquires lock on non-overlapping range
1580N/A fl = ch.lock(10, 10, false).get();
893N/A fl.release();
893N/A
893N/A // done
893N/A ch.close();
893N/A slave.close();
893N/A }
893N/A
893N/A // test close of channel with outstanding lock operation
893N/A static void testAsyncClose(File file, LockSlaveMirror slave) throws Exception {
893N/A // slave VM opens file and acquires exclusive lock
893N/A slave.open(file.getPath()).lock();
893N/A
893N/A for (int i=0; i<100; i++) {
893N/A AsynchronousFileChannel ch = AsynchronousFileChannel
893N/A .open(file.toPath(), READ, WRITE);
893N/A
893N/A // try to lock file (should not complete because file is locked by slave)
893N/A Future<FileLock> result = ch.lock();
893N/A try {
893N/A result.get(rand.nextInt(100), TimeUnit.MILLISECONDS);
893N/A throw new RuntimeException("Timeout expected");
893N/A } catch (TimeoutException x) {
893N/A }
893N/A
893N/A // close channel with lock operation outstanding
893N/A ch.close();
893N/A
893N/A // operation should complete with AsynchronousCloseException
893N/A try {
893N/A result.get();
893N/A throw new RuntimeException("ExecutionException expected");
893N/A } catch (ExecutionException x) {
893N/A if (!(x.getCause() instanceof AsynchronousCloseException)) {
893N/A x.getCause().printStackTrace();
893N/A throw new RuntimeException("AsynchronousCloseException expected");
893N/A }
893N/A }
893N/A }
893N/A
893N/A slave.close();
893N/A }
893N/A
893N/A // starts a "lock slave" in another process, returning a mirror object to
893N/A // control the slave
893N/A static LockSlaveMirror startLockSlave() throws Exception {
893N/A ServerSocketChannel ssc = ServerSocketChannel.open()
893N/A .bind(new InetSocketAddress(0));
893N/A int port = ((InetSocketAddress)(ssc.getLocalAddress())).getPort();
893N/A
893N/A String sep = FileSystems.getDefault().getSeparator();
893N/A
893N/A String command = System.getProperty("java.home") +
2546N/A sep + "bin" + sep + "java";
2546N/A String testClasses = System.getProperty("test.classes");
2546N/A if (testClasses != null)
2546N/A command += " -cp " + testClasses;
2546N/A command += " Lock -lockslave " + port;
2546N/A
893N/A Process p = Runtime.getRuntime().exec(command);
893N/A IOHandler.handle(p.getInputStream());
893N/A IOHandler.handle(p.getErrorStream());
893N/A
893N/A // wait for slave to connect
893N/A SocketChannel sc = ssc.accept();
893N/A return new LockSlaveMirror(sc);
893N/A }
893N/A
893N/A // commands that the slave understands
893N/A static final String OPEN_CMD = "open";
893N/A static final String CLOSE_CMD = "close";
893N/A static final String LOCK_CMD = "lock";
893N/A static final String UNLOCK_CMD = "unlock";
893N/A static final char TERMINATOR = ';';
893N/A
893N/A // provides a proxy to a "lock slave"
893N/A static class LockSlaveMirror {
893N/A private final SocketChannel sc;
893N/A
893N/A LockSlaveMirror(SocketChannel sc) {
893N/A this.sc = sc;
893N/A }
893N/A
893N/A private void sendCommand(String cmd, String... params)
893N/A throws IOException
893N/A {
893N/A for (String s: params) {
893N/A cmd += " " + s;
893N/A }
893N/A cmd += TERMINATOR;
893N/A
893N/A ByteBuffer buf = Charset.defaultCharset().encode(cmd);
893N/A while (buf.hasRemaining()) {
893N/A sc.write(buf);
893N/A }
893N/A
893N/A // wait for ack
893N/A buf = ByteBuffer.allocate(1);
893N/A int n = sc.read(buf);
893N/A if (n != 1)
893N/A throw new RuntimeException("Reply expected");
893N/A if (buf.get(0) != TERMINATOR)
893N/A throw new RuntimeException("Terminated expected");
893N/A }
893N/A
893N/A LockSlaveMirror open(String file) throws IOException {
893N/A sendCommand(OPEN_CMD, file);
893N/A return this;
893N/A }
893N/A
893N/A void close() throws IOException {
893N/A sendCommand(CLOSE_CMD);
893N/A }
893N/A
893N/A LockSlaveMirror lock() throws IOException {
893N/A sendCommand(LOCK_CMD);
893N/A return this;
893N/A }
893N/A
893N/A
893N/A LockSlaveMirror lock(long position, long size, boolean shared)
893N/A throws IOException
893N/A {
893N/A sendCommand(LOCK_CMD, position + "," + size + "," + shared);
893N/A return this;
893N/A }
893N/A
893N/A LockSlaveMirror unlock() throws IOException {
893N/A sendCommand(UNLOCK_CMD);
893N/A return this;
893N/A }
893N/A
893N/A void shutdown() throws IOException {
893N/A sc.close();
893N/A }
893N/A }
893N/A
893N/A // Helper class to direct process output to the parent System.out
893N/A static class IOHandler implements Runnable {
893N/A private final InputStream in;
893N/A
893N/A IOHandler(InputStream in) {
893N/A this.in = in;
893N/A }
893N/A
893N/A static void handle(InputStream in) {
893N/A IOHandler handler = new IOHandler(in);
893N/A Thread thr = new Thread(handler);
893N/A thr.setDaemon(true);
893N/A thr.start();
893N/A }
893N/A
893N/A public void run() {
893N/A try {
893N/A byte b[] = new byte[100];
893N/A for (;;) {
893N/A int n = in.read(b);
893N/A if (n < 0) return;
893N/A for (int i=0; i<n; i++) {
893N/A System.out.print((char)b[i]);
893N/A }
893N/A }
893N/A } catch (IOException ioe) { }
893N/A }
893N/A }
893N/A
893N/A // slave process that responds to simple commands a socket connection
893N/A static void runLockSlave(int port) throws Exception {
893N/A
893N/A // establish connection to parent
893N/A SocketChannel sc = SocketChannel.open(new InetSocketAddress(port));
893N/A ByteBuffer buf = ByteBuffer.allocateDirect(1024);
893N/A
893N/A FileChannel fc = null;
893N/A FileLock fl = null;
893N/A try {
893N/A for (;;) {
893N/A
893N/A // read command (ends with ";")
893N/A buf.clear();
893N/A int n, last = 0;
893N/A do {
893N/A n = sc.read(buf);
893N/A if (n < 0)
893N/A return;
893N/A if (n == 0)
893N/A throw new AssertionError();
893N/A last += n;
893N/A } while (buf.get(last-1) != TERMINATOR);
893N/A
893N/A // decode into command and optional parameter
893N/A buf.flip();
893N/A String s = Charset.defaultCharset().decode(buf).toString();
893N/A int sp = s.indexOf(" ");
893N/A String cmd = (sp < 0) ? s.substring(0, s.length()-1) :
893N/A s.substring(0, sp);
893N/A String param = (sp < 0) ? "" : s.substring(sp+1, s.length()-1);
893N/A
893N/A // execute
893N/A if (cmd.equals(OPEN_CMD)) {
893N/A if (fc != null)
893N/A throw new RuntimeException("File already open");
893N/A fc = FileChannel.open(Paths.get(param),READ, WRITE);
893N/A }
893N/A if (cmd.equals(CLOSE_CMD)) {
893N/A if (fc == null)
893N/A throw new RuntimeException("No file open");
893N/A fc.close();
893N/A fc = null;
893N/A fl = null;
893N/A }
893N/A if (cmd.equals(LOCK_CMD)) {
893N/A if (fl != null)
893N/A throw new RuntimeException("Already holding lock");
893N/A
893N/A if (param.length() == 0) {
893N/A fl = fc.lock();
893N/A } else {
893N/A String[] values = param.split(",");
893N/A if (values.length != 3)
893N/A throw new RuntimeException("Lock parameter invalid");
893N/A long position = Long.parseLong(values[0]);
893N/A long size = Long.parseLong(values[1]);
893N/A boolean shared = Boolean.parseBoolean(values[2]);
893N/A fl = fc.lock(position, size, shared);
893N/A }
893N/A }
893N/A
893N/A if (cmd.equals(UNLOCK_CMD)) {
893N/A if (fl == null)
893N/A throw new RuntimeException("Not holding lock");
893N/A fl.release();
893N/A fl = null;
893N/A }
893N/A
893N/A // send reply
893N/A byte[] reply = { TERMINATOR };
893N/A n = sc.write(ByteBuffer.wrap(reply));
893N/A }
893N/A
893N/A } finally {
893N/A sc.close();
893N/A if (fc != null) fc.close();
893N/A }
893N/A }
893N/A}