Basic.java 17.3 KB
Newer Older
1
/*
2
 * Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved.
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code 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 General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
19 20 21
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
22 23 24
 */

/* @test
25
 * @bug 4313887 6838333 7017446
26 27
 * @summary Unit test for java.nio.file.WatchService
 * @library ..
28
 * @run main Basic
29 30 31
 */

import java.nio.file.*;
32
import static java.nio.file.StandardWatchEventKinds.*;
33 34 35 36 37 38 39 40 41 42 43
import java.nio.file.attribute.*;
import java.io.*;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * Unit test for WatchService that exercises all methods in various scenarios.
 */

public class Basic {

44 45 46
    static void checkKey(WatchKey key, Path dir) {
        if (!key.isValid())
            throw new RuntimeException("Key is not valid");
47 48
        if (key.watchable() != dir)
            throw new RuntimeException("Unexpected watchable");
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
    }

    static void takeExpectedKey(WatchService watcher, WatchKey expected) {
        System.out.println("take events...");
        WatchKey key;
        try {
            key = watcher.take();
        } catch (InterruptedException x) {
            // not expected
            throw new RuntimeException(x);
        }
        if (key != expected)
            throw new RuntimeException("removed unexpected key");
    }

    static void checkExpectedEvent(Iterable<WatchEvent<?>> events,
                                   WatchEvent.Kind<?> expectedKind,
                                   Object expectedContext)
    {
        WatchEvent<?> event = events.iterator().next();
        System.out.format("got event: type=%s, count=%d, context=%s\n",
            event.kind(), event.count(), event.context());
        if (event.kind() != expectedKind)
            throw new RuntimeException("unexpected event");
        if (!expectedContext.equals(event.context()))
            throw new RuntimeException("unexpected context");
    }

    /**
     * Simple test of each of the standard events
     */
    static void testEvents(Path dir) throws IOException {
        System.out.println("-- Standard Events --");

        FileSystem fs = FileSystems.getDefault();
        Path name = fs.getPath("foo");

86
        try (WatchService watcher = fs.newWatchService()) {
87 88 89 90 91 92
            // --- ENTRY_CREATE ---

            // register for event
            System.out.format("register %s for ENTRY_CREATE\n", dir);
            WatchKey myKey = dir.register(watcher,
                new WatchEvent.Kind<?>[]{ ENTRY_CREATE });
93
            checkKey(myKey, dir);
94 95 96 97

            // create file
            Path file = dir.resolve("foo");
            System.out.format("create %s\n", file);
98
            Files.createFile(file);
99 100 101 102

            // remove key and check that we got the ENTRY_CREATE event
            takeExpectedKey(watcher, myKey);
            checkExpectedEvent(myKey.pollEvents(),
103
                StandardWatchEventKinds.ENTRY_CREATE, name);
104 105 106 107 108 109 110 111 112 113 114 115 116 117

            System.out.println("reset key");
            if (!myKey.reset())
                throw new RuntimeException("key has been cancalled");

            System.out.println("OKAY");

            // --- ENTRY_DELETE ---

            System.out.format("register %s for ENTRY_DELETE\n", dir);
            WatchKey deleteKey = dir.register(watcher,
                new WatchEvent.Kind<?>[]{ ENTRY_DELETE });
            if (deleteKey != myKey)
                throw new RuntimeException("register did not return existing key");
118
            checkKey(deleteKey, dir);
119 120

            System.out.format("delete %s\n", file);
121
            Files.delete(file);
122 123
            takeExpectedKey(watcher, myKey);
            checkExpectedEvent(myKey.pollEvents(),
124
                StandardWatchEventKinds.ENTRY_DELETE, name);
125 126 127 128 129 130 131 132

            System.out.println("reset key");
            if (!myKey.reset())
                throw new RuntimeException("key has been cancalled");

            System.out.println("OKAY");

            // create the file for the next test
133
            Files.createFile(file);
134 135 136 137 138 139 140 141

            // --- ENTRY_MODIFY ---

            System.out.format("register %s for ENTRY_MODIFY\n", dir);
            WatchKey newKey = dir.register(watcher,
                new WatchEvent.Kind<?>[]{ ENTRY_MODIFY });
            if (newKey != myKey)
                throw new RuntimeException("register did not return existing key");
142
            checkKey(newKey, dir);
143 144

            System.out.format("update: %s\n", file);
145
            try (OutputStream out = Files.newOutputStream(file, StandardOpenOption.APPEND)) {
146 147 148 149 150 151
                out.write("I am a small file".getBytes("UTF-8"));
            }

            // remove key and check that we got the ENTRY_MODIFY event
            takeExpectedKey(watcher, myKey);
            checkExpectedEvent(myKey.pollEvents(),
152
                StandardWatchEventKinds.ENTRY_MODIFY, name);
153 154 155
            System.out.println("OKAY");

            // done
156
            Files.delete(file);
157 158 159 160 161 162 163 164 165
        }
    }

    /**
     * Check that a cancelled key will never be queued
     */
    static void testCancel(Path dir) throws IOException {
        System.out.println("-- Cancel --");

166
        try (WatchService watcher = FileSystems.getDefault().newWatchService()) {
167 168 169 170

            System.out.format("register %s for events\n", dir);
            WatchKey myKey = dir.register(watcher,
                new WatchEvent.Kind<?>[]{ ENTRY_CREATE });
171
            checkKey(myKey, dir);
172 173 174 175 176 177 178

            System.out.println("cancel key");
            myKey.cancel();

            // create a file in the directory
            Path file = dir.resolve("mars");
            System.out.format("create: %s\n", file);
179
            Files.createFile(file);
180 181 182 183 184 185 186 187 188 189 190 191

            // poll for keys - there will be none
            System.out.println("poll...");
            try {
                WatchKey key = watcher.poll(3000, TimeUnit.MILLISECONDS);
                if (key != null)
                    throw new RuntimeException("key should not be queued");
            } catch (InterruptedException x) {
                throw new RuntimeException(x);
            }

            // done
192
            Files.delete(file);
193 194 195 196 197 198 199 200 201 202 203 204

            System.out.println("OKAY");
        }
    }

    /**
     * Check that deleting a registered directory causes the key to be
     * cancelled and queued.
     */
    static void testAutomaticCancel(Path dir) throws IOException {
        System.out.println("-- Automatic Cancel --");

205
        Path subdir = Files.createDirectory(dir.resolve("bar"));
206

207
        try (WatchService watcher = FileSystems.getDefault().newWatchService()) {
208 209 210 211 212 213

            System.out.format("register %s for events\n", subdir);
            WatchKey myKey = subdir.register(watcher,
                new WatchEvent.Kind<?>[]{ ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY });

            System.out.format("delete: %s\n", subdir);
214
            Files.delete(subdir);
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
            takeExpectedKey(watcher, myKey);

            System.out.println("reset key");
            if (myKey.reset())
                throw new RuntimeException("Key was not cancelled");
            if (myKey.isValid())
                throw new RuntimeException("Key is still valid");

            System.out.println("OKAY");

        }
    }

    /**
     * Asynchronous close of watcher causes blocked threads to wakeup
     */
    static void testWakeup(Path dir) throws IOException {
        System.out.println("-- Wakeup Tests --");
        final WatchService watcher = FileSystems.getDefault().newWatchService();
        Runnable r = new Runnable() {
            public void run() {
                try {
                    Thread.sleep(5000);
                    System.out.println("close WatchService...");
                    watcher.close();
                } catch (InterruptedException x) {
                    x.printStackTrace();
                } catch (IOException x) {
                    x.printStackTrace();
                }
            }
        };

        // start thread to close watch service after delay
        new Thread(r).start();

        try {
            System.out.println("take...");
            watcher.take();
            throw new RuntimeException("ClosedWatchServiceException not thrown");
        } catch (InterruptedException x) {
            throw new RuntimeException(x);
        } catch (ClosedWatchServiceException  x) {
            System.out.println("ClosedWatchServiceException thrown");
        }

        System.out.println("OKAY");
    }

    /**
     * Simple test to check exceptions and other cases
     */
    @SuppressWarnings("unchecked")
    static void testExceptions(Path dir) throws IOException {
        System.out.println("-- Exceptions and other simple tests --");

        WatchService watcher = FileSystems.getDefault().newWatchService();
        try {

            // Poll tests

            WatchKey key;
            System.out.println("poll...");
            key = watcher.poll();
            if (key != null)
                throw new RuntimeException("no keys registered");

            System.out.println("poll with timeout...");
            try {
284
                long start = System.nanoTime();
285 286 287
                key = watcher.poll(3000, TimeUnit.MILLISECONDS);
                if (key != null)
                    throw new RuntimeException("no keys registered");
288
                long waited = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start);
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
                if (waited < 2900)
                    throw new RuntimeException("poll was too short");
            } catch (InterruptedException x) {
                throw new RuntimeException(x);
            }

            // IllegalArgumentException
            System.out.println("IllegalArgumentException tests...");
            try {
                dir.register(watcher, new WatchEvent.Kind<?>[]{ } );
                throw new RuntimeException("IllegalArgumentException not thrown");
            } catch (IllegalArgumentException x) {
            }
            try {
                // OVERFLOW is ignored so this is equivalent to the empty set
                dir.register(watcher, new WatchEvent.Kind<?>[]{ OVERFLOW });
                throw new RuntimeException("IllegalArgumentException not thrown");
            } catch (IllegalArgumentException x) {
            }

            // UnsupportedOperationException
            try {
                dir.register(watcher, new WatchEvent.Kind<?>[]{
                             new WatchEvent.Kind<Object>() {
                                @Override public String name() { return "custom"; }
                                @Override public Class<Object> type() { return Object.class; }
                             }});
            } catch (UnsupportedOperationException x) {
            }
            try {
                dir.register(watcher,
                             new WatchEvent.Kind<?>[]{ ENTRY_CREATE },
                             new WatchEvent.Modifier() {
                                 @Override public String name() { return "custom"; }
                             });
                throw new RuntimeException("UnsupportedOperationException not thrown");
            } catch (UnsupportedOperationException x) {
            }

            // NullPointerException
            System.out.println("NullPointerException tests...");
            try {
                dir.register(null, new WatchEvent.Kind<?>[]{ ENTRY_CREATE });
                throw new RuntimeException("NullPointerException not thrown");
            } catch (NullPointerException x) {
            }
            try {
                dir.register(watcher, new WatchEvent.Kind<?>[]{ null });
                throw new RuntimeException("NullPointerException not thrown");
            } catch (NullPointerException x) {
            }
            try {
                dir.register(watcher, new WatchEvent.Kind<?>[]{ ENTRY_CREATE },
                    (WatchEvent.Modifier)null);
                throw new RuntimeException("NullPointerException not thrown");
            } catch (NullPointerException x) {
            }
        } finally {
            watcher.close();
        }

        // -- ClosedWatchServiceException --

        System.out.println("ClosedWatchServiceException tests...");

        try {
            watcher.poll();
            throw new RuntimeException("ClosedWatchServiceException not thrown");
        } catch (ClosedWatchServiceException  x) {
        }

        // assume that poll throws exception immediately
361
        long start = System.nanoTime();
362 363 364 365 366 367
        try {
            watcher.poll(10000, TimeUnit.MILLISECONDS);
            throw new RuntimeException("ClosedWatchServiceException not thrown");
        } catch (InterruptedException x) {
            throw new RuntimeException(x);
        } catch (ClosedWatchServiceException  x) {
368
            long waited = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start);
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
            if (waited > 5000)
                throw new RuntimeException("poll was too long");
        }

        try {
            watcher.take();
            throw new RuntimeException("ClosedWatchServiceException not thrown");
        } catch (InterruptedException x) {
            throw new RuntimeException(x);
        } catch (ClosedWatchServiceException  x) {
        }

        try {
            dir.register(watcher, new WatchEvent.Kind<?>[]{ ENTRY_CREATE });
             throw new RuntimeException("ClosedWatchServiceException not thrown");
        } catch (ClosedWatchServiceException  x) {
        }

        System.out.println("OKAY");
    }

    /**
     * Test that directory can be registered with more than one watch service
     * and that events don't interfere with each other
     */
    static void testTwoWatchers(Path dir) throws IOException {
        System.out.println("-- Two watchers test --");

        FileSystem fs = FileSystems.getDefault();
        WatchService watcher1 = fs.newWatchService();
        WatchService watcher2 = fs.newWatchService();
        try {
            Path name1 = fs.getPath("gus1");
            Path name2 = fs.getPath("gus2");

            // create gus1
            Path file1 = dir.resolve(name1);
            System.out.format("create %s\n", file1);
407
            Files.createFile(file1);
408 409 410 411 412 413 414 415 416 417 418 419 420 421

            // register with both watch services (different events)
            System.out.println("register for different events");
            WatchKey key1 = dir.register(watcher1,
                new WatchEvent.Kind<?>[]{ ENTRY_CREATE });
            WatchKey key2 = dir.register(watcher2,
                new WatchEvent.Kind<?>[]{ ENTRY_DELETE });

            if (key1 == key2)
                throw new RuntimeException("keys should be different");

            // create gus2
            Path file2 = dir.resolve(name2);
            System.out.format("create %s\n", file2);
422
            Files.createFile(file2);
423 424 425 426

            // check that key1 got ENTRY_CREATE
            takeExpectedKey(watcher1, key1);
            checkExpectedEvent(key1.pollEvents(),
427
                StandardWatchEventKinds.ENTRY_CREATE, name2);
428 429 430 431 432 433 434

            // check that key2 got zero events
            WatchKey key = watcher2.poll();
            if (key != null)
                throw new RuntimeException("key not expected");

            // delete gus1
435
            Files.delete(file1);
436 437 438 439

            // check that key2 got ENTRY_DELETE
            takeExpectedKey(watcher2, key2);
            checkExpectedEvent(key2.pollEvents(),
440
                StandardWatchEventKinds.ENTRY_DELETE, name1);
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457

            // check that key1 got zero events
            key = watcher1.poll();
            if (key != null)
                throw new RuntimeException("key not expected");

            // reset for next test
            key1.reset();
            key2.reset();

            // change registration with watcher2 so that they are both
            // registered for the same event
            System.out.println("register for same event");
            key2 = dir.register(watcher2, new WatchEvent.Kind<?>[]{ ENTRY_CREATE });

            // create file and key2 should be queued
            System.out.format("create %s\n", file1);
458
            Files.createFile(file1);
459 460
            takeExpectedKey(watcher2, key2);
            checkExpectedEvent(key2.pollEvents(),
461
                StandardWatchEventKinds.ENTRY_CREATE, name1);
462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486

            System.out.println("OKAY");

        } finally {
            watcher2.close();
            watcher1.close();
        }
    }

    public static void main(String[] args) throws IOException {
        Path dir = TestUtil.createTemporaryDirectory();
        try {

            testEvents(dir);
            testCancel(dir);
            testAutomaticCancel(dir);
            testWakeup(dir);
            testExceptions(dir);
            testTwoWatchers(dir);

        } finally {
            TestUtil.removeAll(dir);
        }
    }
}