Mercurial > hg > release > icedtea8-3.0
changeset 1622:738f5ba2f1fb
Remove org.classpath.icedtea namespace.
2009-02-13 Andrew John Hughes <ahughes@redhat.com>
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/io/File.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/io/FilePermission.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/io/Inputs.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/io/Outputs.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/net/ProtocolFamily.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/net/SocketOption.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/net/StandardProtocolFamily.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/net/StandardSocketOption.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/AsynchronousByteChannel.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/AsynchronousChannel.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/AsynchronousChannelGroup.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/AsynchronousDatagramChannel.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/AsynchronousFileChannel.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/AsynchronousServerSocketChannel.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/AsynchronousSocketChannel.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/Channels.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/CompletionHandler.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/DatagramChannel.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/FileChannel.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/FileLock.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/MembershipKey.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/MulticastChannel.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/NetworkChannel.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/SeekableByteChannel.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/exceptions,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/package-info.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/spi/AsynchronousChannelProvider.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/spi/SelectorProvider.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/spi/package.html,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/AccessDeniedException.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/AccessMode.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/AtomicMoveNotSupportedException.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/ClosedDirectoryStreamException.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/ClosedFileSystemException.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/ClosedWatchServiceException.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/CopyOption.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/DirectoryNotEmptyException.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/DirectoryStream.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/DirectoryStreamFilters.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/FileAction.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/FileAlreadyExistsException.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/FileRef.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/FileStore.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/FileSystem.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/FileSystemAlreadyExistsException.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/FileSystemException.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/FileSystemNotFoundException.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/FileSystems.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/FileTreeWalker.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/FileVisitOption.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/FileVisitResult.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/FileVisitor.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/Files.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/InvalidPathException.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/LinkOption.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/LinkPermission.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/NoSuchFileException.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/NotDirectoryException.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/NotLinkException.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/OpenOption.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/Path.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/PathMatcher.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/Paths.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/ProviderMismatchException.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/ProviderNotFoundException.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/ReadOnlyFileSystemException.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/SecureDirectoryStream.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/SimpleFileVisitor.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/StandardCopyOption.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/StandardOpenOption.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/StandardWatchEventKind.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/WatchEvent.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/WatchKey.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/WatchService.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/Watchable.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/AclEntry.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/AclEntryFlag.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/AclEntryPermission.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/AclEntryType.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/AclFileAttributeView.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/AttributeView.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/Attributes.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/BasicFileAttributeView.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/BasicFileAttributes.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/DosFileAttributeView.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/DosFileAttributes.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/FileAttribute.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/FileAttributeView.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/FileOwnerAttributeView.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/FileStoreAttributeView.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/FileStoreSpaceAttributeView.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/FileStoreSpaceAttributes.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/GroupPrincipal.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/NamedAttributeView.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/PosixFileAttributeView.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/PosixFileAttributes.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/PosixFilePermission.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/PosixFilePermissions.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/UserPrincipal.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/UserPrincipalLookupService.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/UserPrincipalNotFoundException.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/package-info.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/package-info.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/spi/AbstractPath.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/spi/FileSystemProvider.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/spi/FileTypeDetector.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/spi/package-info.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/util/Scanner.java,
* overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/util/concurrent/ScheduledThreadPoolExecutor.java: Moved...
* overlays/nio2/openjdk/jdk/src/share/classes/java/io/File.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/io/FilePermission.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/io/Inputs.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/io/Outputs.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/net/ProtocolFamily.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/net/SocketOption.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/net/StandardProtocolFamily.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/net/StandardSocketOption.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/AsynchronousByteChannel.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/AsynchronousChannel.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/AsynchronousChannelGroup.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/AsynchronousDatagramChannel.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/AsynchronousFileChannel.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/AsynchronousServerSocketChannel.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/AsynchronousSocketChannel.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/Channels.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/CompletionHandler.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/DatagramChannel.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/FileChannel.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/FileLock.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/MembershipKey.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/MulticastChannel.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/NetworkChannel.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/SeekableByteChannel.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/exceptions,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/package-info.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/spi/AsynchronousChannelProvider.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/spi/SelectorProvider.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/spi/package.html,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/AccessDeniedException.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/AccessMode.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/AtomicMoveNotSupportedException.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/ClosedDirectoryStreamException.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/ClosedFileSystemException.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/ClosedWatchServiceException.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/CopyOption.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/DirectoryNotEmptyException.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/DirectoryStream.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/DirectoryStreamFilters.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/FileAction.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/FileAlreadyExistsException.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/FileRef.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/FileStore.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/FileSystem.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/FileSystemAlreadyExistsException.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/FileSystemException.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/FileSystemNotFoundException.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/FileSystems.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/FileTreeWalker.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/FileVisitOption.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/FileVisitResult.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/FileVisitor.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/Files.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/InvalidPathException.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/LinkOption.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/LinkPermission.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/NoSuchFileException.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/NotDirectoryException.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/NotLinkException.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/OpenOption.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/Path.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/PathMatcher.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/Paths.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/ProviderMismatchException.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/ProviderNotFoundException.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/ReadOnlyFileSystemException.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/SecureDirectoryStream.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/SimpleFileVisitor.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/StandardCopyOption.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/StandardOpenOption.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/StandardWatchEventKind.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/WatchEvent.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/WatchKey.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/WatchService.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/Watchable.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/AclEntry.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/AclEntryFlag.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/AclEntryPermission.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/AclEntryType.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/AclFileAttributeView.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/AttributeView.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/Attributes.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/BasicFileAttributeView.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/BasicFileAttributes.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/DosFileAttributeView.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/DosFileAttributes.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/FileAttribute.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/FileAttributeView.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/FileOwnerAttributeView.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/FileStoreAttributeView.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/FileStoreSpaceAttributeView.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/FileStoreSpaceAttributes.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/GroupPrincipal.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/NamedAttributeView.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/PosixFileAttributeView.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/PosixFileAttributes.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/PosixFilePermission.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/PosixFilePermissions.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/UserPrincipal.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/UserPrincipalLookupService.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/UserPrincipalNotFoundException.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/package-info.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/package-info.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/spi/AbstractPath.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/spi/FileSystemProvider.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/spi/FileTypeDetector.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/spi/package-info.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/util/Scanner.java,
* overlays/nio2/openjdk/jdk/src/share/classes/java/util/concurrent/ScheduledThreadPoolExecutor.java: to here.
author | Andrew John Hughes <ahughes@redhat.com> |
---|---|
date | Fri, 13 Feb 2009 20:38:41 +0000 |
parents | 983ed89e8dd3 |
children | 5bda1b46a64f |
files | ChangeLog overlays/nio2/openjdk/jdk/src/share/classes/java/io/File.java overlays/nio2/openjdk/jdk/src/share/classes/java/io/FilePermission.java overlays/nio2/openjdk/jdk/src/share/classes/java/io/Inputs.java overlays/nio2/openjdk/jdk/src/share/classes/java/io/Outputs.java overlays/nio2/openjdk/jdk/src/share/classes/java/net/ProtocolFamily.java overlays/nio2/openjdk/jdk/src/share/classes/java/net/SocketOption.java overlays/nio2/openjdk/jdk/src/share/classes/java/net/StandardProtocolFamily.java overlays/nio2/openjdk/jdk/src/share/classes/java/net/StandardSocketOption.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/AsynchronousByteChannel.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/AsynchronousChannel.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/AsynchronousChannelGroup.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/AsynchronousDatagramChannel.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/AsynchronousFileChannel.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/AsynchronousServerSocketChannel.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/AsynchronousSocketChannel.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/Channels.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/CompletionHandler.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/DatagramChannel.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/FileChannel.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/FileLock.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/MembershipKey.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/MulticastChannel.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/NetworkChannel.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/SeekableByteChannel.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/exceptions overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/package-info.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/spi/AsynchronousChannelProvider.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/spi/SelectorProvider.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/spi/package.html overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/AccessDeniedException.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/AccessMode.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/AtomicMoveNotSupportedException.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/ClosedDirectoryStreamException.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/ClosedFileSystemException.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/ClosedWatchServiceException.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/CopyOption.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/DirectoryNotEmptyException.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/DirectoryStream.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/DirectoryStreamFilters.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/FileAction.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/FileAlreadyExistsException.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/FileRef.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/FileStore.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/FileSystem.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/FileSystemAlreadyExistsException.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/FileSystemException.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/FileSystemNotFoundException.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/FileSystems.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/FileTreeWalker.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/FileVisitOption.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/FileVisitResult.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/FileVisitor.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/Files.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/InvalidPathException.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/LinkOption.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/LinkPermission.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/NoSuchFileException.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/NotDirectoryException.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/NotLinkException.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/OpenOption.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/Path.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/PathMatcher.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/Paths.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/ProviderMismatchException.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/ProviderNotFoundException.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/ReadOnlyFileSystemException.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/SecureDirectoryStream.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/SimpleFileVisitor.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/StandardCopyOption.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/StandardOpenOption.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/StandardWatchEventKind.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/WatchEvent.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/WatchKey.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/WatchService.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/Watchable.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/AclEntry.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/AclEntryFlag.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/AclEntryPermission.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/AclEntryType.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/AclFileAttributeView.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/AttributeView.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/Attributes.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/BasicFileAttributeView.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/BasicFileAttributes.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/DosFileAttributeView.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/DosFileAttributes.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/FileAttribute.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/FileAttributeView.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/FileOwnerAttributeView.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/FileStoreAttributeView.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/FileStoreSpaceAttributeView.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/FileStoreSpaceAttributes.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/GroupPrincipal.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/NamedAttributeView.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/PosixFileAttributeView.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/PosixFileAttributes.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/PosixFilePermission.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/PosixFilePermissions.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/UserPrincipal.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/UserPrincipalLookupService.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/UserPrincipalNotFoundException.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/package-info.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/package-info.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/spi/AbstractPath.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/spi/FileSystemProvider.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/spi/FileTypeDetector.java overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/spi/package-info.java overlays/nio2/openjdk/jdk/src/share/classes/java/util/Scanner.java overlays/nio2/openjdk/jdk/src/share/classes/java/util/concurrent/ScheduledThreadPoolExecutor.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/io/File.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/io/FilePermission.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/io/Inputs.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/io/Outputs.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/net/ProtocolFamily.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/net/SocketOption.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/net/StandardProtocolFamily.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/net/StandardSocketOption.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/AsynchronousByteChannel.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/AsynchronousChannel.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/AsynchronousChannelGroup.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/AsynchronousDatagramChannel.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/AsynchronousFileChannel.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/AsynchronousServerSocketChannel.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/AsynchronousSocketChannel.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/Channels.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/CompletionHandler.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/DatagramChannel.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/FileChannel.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/FileLock.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/MembershipKey.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/MulticastChannel.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/NetworkChannel.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/SeekableByteChannel.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/exceptions overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/package-info.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/spi/AsynchronousChannelProvider.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/spi/SelectorProvider.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/spi/package.html overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/AccessDeniedException.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/AccessMode.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/AtomicMoveNotSupportedException.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/ClosedDirectoryStreamException.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/ClosedFileSystemException.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/ClosedWatchServiceException.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/CopyOption.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/DirectoryNotEmptyException.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/DirectoryStream.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/DirectoryStreamFilters.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/FileAction.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/FileAlreadyExistsException.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/FileRef.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/FileStore.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/FileSystem.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/FileSystemAlreadyExistsException.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/FileSystemException.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/FileSystemNotFoundException.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/FileSystems.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/FileTreeWalker.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/FileVisitOption.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/FileVisitResult.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/FileVisitor.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/Files.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/InvalidPathException.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/LinkOption.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/LinkPermission.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/NoSuchFileException.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/NotDirectoryException.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/NotLinkException.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/OpenOption.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/Path.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/PathMatcher.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/Paths.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/ProviderMismatchException.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/ProviderNotFoundException.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/ReadOnlyFileSystemException.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/SecureDirectoryStream.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/SimpleFileVisitor.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/StandardCopyOption.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/StandardOpenOption.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/StandardWatchEventKind.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/WatchEvent.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/WatchKey.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/WatchService.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/Watchable.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/AclEntry.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/AclEntryFlag.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/AclEntryPermission.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/AclEntryType.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/AclFileAttributeView.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/AttributeView.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/Attributes.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/BasicFileAttributeView.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/BasicFileAttributes.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/DosFileAttributeView.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/DosFileAttributes.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/FileAttribute.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/FileAttributeView.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/FileOwnerAttributeView.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/FileStoreAttributeView.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/FileStoreSpaceAttributeView.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/FileStoreSpaceAttributes.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/GroupPrincipal.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/NamedAttributeView.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/PosixFileAttributeView.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/PosixFileAttributes.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/PosixFilePermission.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/PosixFilePermissions.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/UserPrincipal.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/UserPrincipalLookupService.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/UserPrincipalNotFoundException.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/package-info.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/package-info.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/spi/AbstractPath.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/spi/FileSystemProvider.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/spi/FileTypeDetector.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/spi/package-info.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/util/Scanner.java overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/util/concurrent/ScheduledThreadPoolExecutor.java |
diffstat | 219 files changed, 25077 insertions(+), 24856 deletions(-) [+] |
line wrap: on
line diff
--- a/ChangeLog Fri Feb 13 20:26:58 2009 +0000 +++ b/ChangeLog Fri Feb 13 20:38:41 2009 +0000 @@ -1,3 +1,224 @@ +2009-02-13 Andrew John Hughes <ahughes@redhat.com> + + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/io/File.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/io/FilePermission.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/io/Inputs.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/io/Outputs.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/net/ProtocolFamily.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/net/SocketOption.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/net/StandardProtocolFamily.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/net/StandardSocketOption.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/AsynchronousByteChannel.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/AsynchronousChannel.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/AsynchronousChannelGroup.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/AsynchronousDatagramChannel.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/AsynchronousFileChannel.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/AsynchronousServerSocketChannel.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/AsynchronousSocketChannel.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/Channels.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/CompletionHandler.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/DatagramChannel.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/FileChannel.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/FileLock.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/MembershipKey.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/MulticastChannel.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/NetworkChannel.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/SeekableByteChannel.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/exceptions, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/package-info.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/spi/AsynchronousChannelProvider.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/spi/SelectorProvider.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/spi/package.html, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/AccessDeniedException.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/AccessMode.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/AtomicMoveNotSupportedException.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/ClosedDirectoryStreamException.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/ClosedFileSystemException.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/ClosedWatchServiceException.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/CopyOption.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/DirectoryNotEmptyException.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/DirectoryStream.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/DirectoryStreamFilters.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/FileAction.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/FileAlreadyExistsException.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/FileRef.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/FileStore.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/FileSystem.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/FileSystemAlreadyExistsException.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/FileSystemException.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/FileSystemNotFoundException.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/FileSystems.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/FileTreeWalker.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/FileVisitOption.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/FileVisitResult.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/FileVisitor.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/Files.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/InvalidPathException.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/LinkOption.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/LinkPermission.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/NoSuchFileException.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/NotDirectoryException.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/NotLinkException.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/OpenOption.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/Path.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/PathMatcher.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/Paths.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/ProviderMismatchException.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/ProviderNotFoundException.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/ReadOnlyFileSystemException.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/SecureDirectoryStream.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/SimpleFileVisitor.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/StandardCopyOption.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/StandardOpenOption.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/StandardWatchEventKind.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/WatchEvent.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/WatchKey.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/WatchService.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/Watchable.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/AclEntry.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/AclEntryFlag.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/AclEntryPermission.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/AclEntryType.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/AclFileAttributeView.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/AttributeView.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/Attributes.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/BasicFileAttributeView.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/BasicFileAttributes.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/DosFileAttributeView.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/DosFileAttributes.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/FileAttribute.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/FileAttributeView.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/FileOwnerAttributeView.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/FileStoreAttributeView.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/FileStoreSpaceAttributeView.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/FileStoreSpaceAttributes.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/GroupPrincipal.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/NamedAttributeView.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/PosixFileAttributeView.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/PosixFileAttributes.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/PosixFilePermission.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/PosixFilePermissions.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/UserPrincipal.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/UserPrincipalLookupService.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/UserPrincipalNotFoundException.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/package-info.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/package-info.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/spi/AbstractPath.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/spi/FileSystemProvider.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/spi/FileTypeDetector.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/spi/package-info.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/util/Scanner.java, + * overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/util/concurrent/ScheduledThreadPoolExecutor.java: Moved... + * overlays/nio2/openjdk/jdk/src/share/classes/java/io/File.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/io/FilePermission.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/io/Inputs.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/io/Outputs.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/net/ProtocolFamily.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/net/SocketOption.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/net/StandardProtocolFamily.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/net/StandardSocketOption.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/AsynchronousByteChannel.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/AsynchronousChannel.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/AsynchronousChannelGroup.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/AsynchronousDatagramChannel.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/AsynchronousFileChannel.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/AsynchronousServerSocketChannel.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/AsynchronousSocketChannel.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/Channels.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/CompletionHandler.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/DatagramChannel.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/FileChannel.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/FileLock.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/MembershipKey.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/MulticastChannel.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/NetworkChannel.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/SeekableByteChannel.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/exceptions, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/package-info.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/spi/AsynchronousChannelProvider.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/spi/SelectorProvider.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/spi/package.html, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/AccessDeniedException.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/AccessMode.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/AtomicMoveNotSupportedException.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/ClosedDirectoryStreamException.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/ClosedFileSystemException.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/ClosedWatchServiceException.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/CopyOption.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/DirectoryNotEmptyException.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/DirectoryStream.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/DirectoryStreamFilters.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/FileAction.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/FileAlreadyExistsException.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/FileRef.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/FileStore.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/FileSystem.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/FileSystemAlreadyExistsException.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/FileSystemException.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/FileSystemNotFoundException.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/FileSystems.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/FileTreeWalker.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/FileVisitOption.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/FileVisitResult.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/FileVisitor.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/Files.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/InvalidPathException.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/LinkOption.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/LinkPermission.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/NoSuchFileException.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/NotDirectoryException.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/NotLinkException.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/OpenOption.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/Path.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/PathMatcher.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/Paths.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/ProviderMismatchException.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/ProviderNotFoundException.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/ReadOnlyFileSystemException.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/SecureDirectoryStream.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/SimpleFileVisitor.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/StandardCopyOption.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/StandardOpenOption.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/StandardWatchEventKind.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/WatchEvent.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/WatchKey.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/WatchService.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/Watchable.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/AclEntry.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/AclEntryFlag.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/AclEntryPermission.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/AclEntryType.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/AclFileAttributeView.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/AttributeView.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/Attributes.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/BasicFileAttributeView.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/BasicFileAttributes.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/DosFileAttributeView.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/DosFileAttributes.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/FileAttribute.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/FileAttributeView.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/FileOwnerAttributeView.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/FileStoreAttributeView.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/FileStoreSpaceAttributeView.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/FileStoreSpaceAttributes.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/GroupPrincipal.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/NamedAttributeView.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/PosixFileAttributeView.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/PosixFileAttributes.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/PosixFilePermission.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/PosixFilePermissions.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/UserPrincipal.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/UserPrincipalLookupService.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/UserPrincipalNotFoundException.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/package-info.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/package-info.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/spi/AbstractPath.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/spi/FileSystemProvider.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/spi/FileTypeDetector.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/spi/package-info.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/util/Scanner.java, + * overlays/nio2/openjdk/jdk/src/share/classes/java/util/concurrent/ScheduledThreadPoolExecutor.java: to here. + 2009-02-13 Andrew John Hughes <ahughes@redhat.com> * patches/hotspot/14.0b08/icedtea-format.patch:
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/io/File.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,450 @@ +/* + * Copyright 1994-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.io; + +import java.beans.ConstructorProperties; +import java.net.URI; +import java.net.URL; +import java.net.MalformedURLException; +import java.net.URISyntaxException; + +import java.io.IOException; +import java.io.IOError; + +import java.util.*; +import java.util.concurrent.atomic.AtomicInteger; +import java.security.AccessController; +import java.security.PrivilegedAction; +import sun.security.action.GetPropertyAction; + +import org.classpath.icedtea.java.nio.file.FileAlreadyExistsException; +import org.classpath.icedtea.java.nio.file.FileSystem; +import org.classpath.icedtea.java.nio.file.FileSystems; +import org.classpath.icedtea.java.nio.file.InvalidPathException; +import org.classpath.icedtea.java.nio.file.Path; +import org.classpath.icedtea.java.nio.file.Paths; + +import org.classpath.icedtea.java.nio.file.attribute.FileAttribute; +import org.classpath.icedtea.java.nio.file.attribute.FileAttributeView; +import org.classpath.icedtea.java.nio.file.attribute.PosixFilePermission; +import org.classpath.icedtea.java.nio.file.attribute.PosixFilePermissions; + +import org.classpath.icedtea.misc.SharedSecrets; + +/** + * An abstract representation of file and directory pathnames. + * + * <p> User interfaces and operating systems use system-dependent <em>pathname + * strings</em> to name files and directories. This class presents an + * abstract, system-independent view of hierarchical pathnames. An + * <em>abstract pathname</em> has two components: + * + * <ol> + * <li> An optional system-dependent <em>prefix</em> string, + * such as a disk-drive specifier, <code>"/"</code> for the UNIX root + * directory, or <code>"\\\\"</code> for a Microsoft Windows UNC pathname, and + * <li> A sequence of zero or more string <em>names</em>. + * </ol> + * + * The first name in an abstract pathname may be a directory name or, in the + * case of Microsoft Windows UNC pathnames, a hostname. Each subsequent name + * in an abstract pathname denotes a directory; the last name may denote + * either a directory or a file. The <em>empty</em> abstract pathname has no + * prefix and an empty name sequence. + * + * <p> The conversion of a pathname string to or from an abstract pathname is + * inherently system-dependent. When an abstract pathname is converted into a + * pathname string, each name is separated from the next by a single copy of + * the default <em>separator character</em>. The default name-separator + * character is defined by the system property <code>file.separator</code>, and + * is made available in the public static fields <code>{@link + * #separator}</code> and <code>{@link #separatorChar}</code> of this class. + * When a pathname string is converted into an abstract pathname, the names + * within it may be separated by the default name-separator character or by any + * other name-separator character that is supported by the underlying system. + * + * <p> A pathname, whether abstract or in string form, may be either + * <em>absolute</em> or <em>relative</em>. An absolute pathname is complete in + * that no other information is required in order to locate the file that it + * denotes. A relative pathname, in contrast, must be interpreted in terms of + * information taken from some other pathname. By default the classes in the + * <code>java.io</code> package always resolve relative pathnames against the + * current user directory. This directory is named by the system property + * <code>user.dir</code>, and is typically the directory in which the Java + * virtual machine was invoked. + * + * <p> The <em>parent</em> of an abstract pathname may be obtained by invoking + * the {@link #getParent} method of this class and consists of the pathname's + * prefix and each name in the pathname's name sequence except for the last. + * Each directory's absolute pathname is an ancestor of any <tt>File</tt> + * object with an absolute abstract pathname which begins with the directory's + * absolute pathname. For example, the directory denoted by the abstract + * pathname <tt>"/usr"</tt> is an ancestor of the directory denoted by the + * pathname <tt>"/usr/local/bin"</tt>. + * + * <p> The prefix concept is used to handle root directories on UNIX platforms, + * and drive specifiers, root directories and UNC pathnames on Microsoft Windows platforms, + * as follows: + * + * <ul> + * + * <li> For UNIX platforms, the prefix of an absolute pathname is always + * <code>"/"</code>. Relative pathnames have no prefix. The abstract pathname + * denoting the root directory has the prefix <code>"/"</code> and an empty + * name sequence. + * + * <li> For Microsoft Windows platforms, the prefix of a pathname that contains a drive + * specifier consists of the drive letter followed by <code>":"</code> and + * possibly followed by <code>"\\"</code> if the pathname is absolute. The + * prefix of a UNC pathname is <code>"\\\\"</code>; the hostname and the share + * name are the first two names in the name sequence. A relative pathname that + * does not specify a drive has no prefix. + * + * </ul> + * + * <p> Instances of this class may or may not denote an actual file-system + * object such as a file or a directory. If it does denote such an object + * then that object resides in a <i>partition</i>. A partition is an + * operating system-specific portion of storage for a file system. A single + * storage device (e.g. a physical disk-drive, flash memory, CD-ROM) may + * contain multiple partitions. The object, if any, will reside on the + * partition <a name="partName">named</a> by some ancestor of the absolute + * form of this pathname. + * + * <p> A file system may implement restrictions to certain operations on the + * actual file-system object, such as reading, writing, and executing. These + * restrictions are collectively known as <i>access permissions</i>. The file + * system may have multiple sets of access permissions on a single object. + * For example, one set may apply to the object's <i>owner</i>, and another + * may apply to all other users. The access permissions on an object may + * cause some methods in this class to fail. + * + * <p> Instances of the <code>File</code> class are immutable; that is, once + * created, the abstract pathname represented by a <code>File</code> object + * will never change. + * + * <h4>Interoperability with {@code java.nio.file} package</h4> + * + * <p> {@note new} + * The <a href="../../java/nio/file/package-summary.html">{@code java.nio.file}</a> + * package defines interfaces and classes for the Java virtual machine to access + * files, file attributes, and file systems. This API may be used to overcome + * many of the limitations of the {@code java.io.File} class. + * The {@link #toPath toPath} method may be used to obtain a {@link + * Path} that uses the abstract path represented by a {@code File} object to + * locate a file. The resulting {@code Path} provides more efficient and + * extensive access to file attributes, additional file operations, and I/O + * exceptions to help diagnose errors when an operation on a file fails. + * + * @author unascribed + * @since JDK1.0 + */ + +public class File + extends java.io.File +{ + + /** + * Creates a new <code>File</code> instance by converting the given + * pathname string into an abstract pathname. If the given string is + * the empty string, then the result is the empty abstract pathname. + * + * @param pathname A pathname string + * @throws NullPointerException + * If the <code>pathname</code> argument is <code>null</code> + */ + @ConstructorProperties("path") + public File(String pathname) { + super(pathname); + } + + /* Note: The two-argument File constructors do not interpret an empty + parent abstract pathname as the current user directory. An empty parent + instead causes the child to be resolved against the system-dependent + directory defined by the FileSystem.getDefaultParent method. On Unix + this default is "/", while on Microsoft Windows it is "\\". This is required for + compatibility with the original behavior of this class. */ + + /** + * Creates a new <code>File</code> instance from a parent pathname string + * and a child pathname string. + * + * <p> If <code>parent</code> is <code>null</code> then the new + * <code>File</code> instance is created as if by invoking the + * single-argument <code>File</code> constructor on the given + * <code>child</code> pathname string. + * + * <p> Otherwise the <code>parent</code> pathname string is taken to denote + * a directory, and the <code>child</code> pathname string is taken to + * denote either a directory or a file. If the <code>child</code> pathname + * string is absolute then it is converted into a relative pathname in a + * system-dependent way. If <code>parent</code> is the empty string then + * the new <code>File</code> instance is created by converting + * <code>child</code> into an abstract pathname and resolving the result + * against a system-dependent default directory. Otherwise each pathname + * string is converted into an abstract pathname and the child abstract + * pathname is resolved against the parent. + * + * @param parent The parent pathname string + * @param child The child pathname string + * @throws NullPointerException + * If <code>child</code> is <code>null</code> + */ + public File(String parent, String child) { + super(parent, child); + } + + /** + * Creates a new <code>File</code> instance from a parent abstract + * pathname and a child pathname string. + * + * <p> If <code>parent</code> is <code>null</code> then the new + * <code>File</code> instance is created as if by invoking the + * single-argument <code>File</code> constructor on the given + * <code>child</code> pathname string. + * + * <p> Otherwise the <code>parent</code> abstract pathname is taken to + * denote a directory, and the <code>child</code> pathname string is taken + * to denote either a directory or a file. If the <code>child</code> + * pathname string is absolute then it is converted into a relative + * pathname in a system-dependent way. If <code>parent</code> is the empty + * abstract pathname then the new <code>File</code> instance is created by + * converting <code>child</code> into an abstract pathname and resolving + * the result against a system-dependent default directory. Otherwise each + * pathname string is converted into an abstract pathname and the child + * abstract pathname is resolved against the parent. + * + * @param parent The parent abstract pathname + * @param child The child pathname string + * @throws NullPointerException + * If <code>child</code> is <code>null</code> + */ + public File(File parent, String child) { + super(parent, child); + } + + + + /* -- Temporary files -- */ + + private static class TemporaryDirectory { + private TemporaryDirectory() { } + + static final File valueAsFile = + new File(AccessController.doPrivileged(new GetPropertyAction("java.io.tmpdir"))); + + // file name generation + private static final AtomicInteger counter = + new AtomicInteger(new Random().nextInt() & 0xffff); + static File generateFile(String prefix, String suffix, File dir) { + int n = counter.getAndIncrement(); + return new File(dir, prefix + Integer.toString(n) + suffix); + } + + // default file permissions + static final FileAttribute<Set<PosixFilePermission>> defaultPosixFilePermissions = + PosixFilePermissions.asFileAttribute(EnumSet + .of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE)); + static final boolean isPosix = isPosix(); + static boolean isPosix() { + return AccessController.doPrivileged( + new PrivilegedAction<Boolean>() { + public Boolean run() { + try { + return FileSystems.getDefault().getPath(valueAsFile.getPath()) + .getFileStore().supportsFileAttributeView("posix"); + } catch (IOException e) { + throw new IOError(e); + } + } + }); + } + } + + /** + * {@note new} + * Creates an empty file in the default temporary-file directory, using + * the given prefix and suffix to generate its name. This method is + * equivalent to invoking the {@link #createTempFile(String,String) + * createTempFile(prefix, suffix)} method with the addition that the + * resulting pathname may be requested to be deleted when the Java virtual + * machine terminates, and the initial file attributes to set atomically + * when creating the file may be specified. + * + * <p> When the value of the {@code deleteOnExit} method is {@code true} + * then the resulting file is requested to be deleted when the Java virtual + * machine terminates as if by invoking the {@link #deleteOnExit deleteOnExit} + * method. + * + * <p> The {@code attrs} parameter is an optional array of {@link FileAttribute + * attributes} to set atomically when creating the file. Each attribute is + * identified by its {@link FileAttribute#name name}. If more than one attribute + * of the same name is included in the array then all but the last occurrence + * is ignored. + * + * @param prefix + * The prefix string to be used in generating the file's + * name; must be at least three characters long + * @param suffix + * The suffix string to be used in generating the file's + * name; may be {@code null}, in which case the suffix + * {@code ".tmp"} will be used + * @param deleteOnExit + * {@code true} if the file denoted by resulting pathname be + * deleted when the Java virtual machine terminates + * @param attrs + * An optional list of file attributes to set atomically when creating + * the file + * + * @return An abstract pathname denoting a newly-created empty file + * + * @throws IllegalArgumentException + * If the <code>prefix</code> argument contains fewer than three + * characters + * @throws UnsupportedOperationException + * If the array contains an attribute that cannot be set atomically + * when creating the file + * @throws IOException + * If a file could not be created + * @throws SecurityException + * If a security manager exists and its <code>{@link + * java.lang.SecurityManager#checkWrite(java.lang.String)}</code> + * method does not allow a file to be created. When the {@code + * deleteOnExit} parameter has the value {@code true} then the + * security manager's {@link + * java.lang.SecurityManager#checkDelete(java.lang.String)} is + * invoked to check delete access to the file. + * @since 1.7 + */ + public static File createTempFile(String prefix, + String suffix, + boolean deleteOnExit, + FileAttribute<?>... attrs) + throws IOException + { + if (prefix.length() < 3) + throw new IllegalArgumentException("Prefix string too short"); + suffix = (suffix == null) ? ".tmp" : suffix; + + // special case POSIX environments so that 0600 is used as the file mode + if (TemporaryDirectory.isPosix) { + if (attrs.length == 0) { + // no attributes so use default permissions + attrs = new FileAttribute<?>[1]; + attrs[0] = TemporaryDirectory.defaultPosixFilePermissions; + } else { + // check if posix permissions given; if not use default + boolean hasPermissions = false; + for (int i=0; i<attrs.length; i++) { + if (attrs[i].name().equals("posix:permissions")) { + hasPermissions = true; + break; + } + } + if (!hasPermissions) { + FileAttribute<?>[] copy = new FileAttribute<?>[attrs.length+1]; + System.arraycopy(attrs, 0, copy, 0, attrs.length); + attrs = copy; + attrs[attrs.length-1] = + TemporaryDirectory.defaultPosixFilePermissions; + } + } + } + + // use Path#createFile to create file + SecurityManager sm = System.getSecurityManager(); + for (;;) { + File f = TemporaryDirectory + .generateFile(prefix, suffix, TemporaryDirectory.valueAsFile); + if (sm != null && deleteOnExit) + sm.checkDelete(f.getPath()); + try { + f.toPath().createFile(attrs); + if (deleteOnExit) + SharedSecrets.getJavaIODeleteOnExitAccess().add(f.getPath()); + return f; + } catch (InvalidPathException e) { + // don't reveal temporary directory location + if (sm != null) + throw new IllegalArgumentException("Invalid prefix or suffix"); + throw e; + } catch (SecurityException e) { + // don't reveal temporary directory location + if (sm != null) + throw new SecurityException("Unable to create temporary file"); + throw e; + } catch (FileAlreadyExistsException e) { + // ignore + } + } + } + + // -- Integration with java.nio.file -- + + private volatile transient Path filePath; + + /** + * {@note new} + * Returns a {@link Path java.nio.file.Path} object constructed from the + * this abstract path. The first invocation of this method works as if + * invoking it were equivalent to evaluating the expression: + * <blockquote><pre> + * {@link FileSystems#getDefault FileSystems.getDefault}().{@link FileSystem#getPath getPath}(this.{@link #getPath getPath}()); + * </pre></blockquote> + * Subsequent invocations of this method return the same {@code Path}. + * + * <p> If this abstract pathname is the empty abstract pathname then this + * method returns a {@code Path} that may be used to access to the current + * user directory. + * + * @return A {@code Path} constructed from this abstract path. The resulting + * {@code Path} is associated with the {@link FileSystems#getDefault + * default-filesystem}. + * + * @throws InvalidPathException + * If a {@code Path} object cannot be constructed from the abstract + * path (see {@link java.nio.file.FileSystem#getPath FileSystem.getPath}) + * + * @since 1.7 + */ + public Path toPath() { + if (filePath == null) { + synchronized (this) { + if (filePath == null) { + String path = getPath(); + if (path.length() == 0) { + // assume default file system treats "." as current directory + filePath = Paths.get("."); + } else { + filePath = Paths.get(path); + } + } + } + } + return filePath; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/io/FilePermission.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,852 @@ +/* + * Copyright 1997-2005 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.io; + +import java.security.*; +import java.util.Enumeration; +import java.util.List; +import java.util.ArrayList; +import java.util.Vector; +import java.util.Collections; +import java.io.IOException; +import java.io.ObjectStreamField; +import java.io.ObjectOutputStream; +import java.io.ObjectInputStream; +import java.io.Serializable; +import sun.security.util.SecurityConstants; + +/** + * This class represents access to a file or directory. A FilePermission consists + * of a pathname and a set of actions valid for that pathname. + * <P> + * Pathname is the pathname of the file or directory granted the specified + * actions. A pathname that ends in "/*" (where "/" is + * the file separator character, <code>File.separatorChar</code>) indicates + * all the files and directories contained in that directory. A pathname + * that ends with "/-" indicates (recursively) all files + * and subdirectories contained in that directory. A pathname consisting of + * the special token "<<ALL FILES>>" matches <b>any</b> file. + * <P> + * Note: A pathname consisting of a single "*" indicates all the files + * in the current directory, while a pathname consisting of a single "-" + * indicates all the files in the current directory and + * (recursively) all files and subdirectories contained in the current + * directory. + * <P> + * {@note revised} + * The actions to be granted are passed to the constructor in a string containing + * a list of one or more comma-separated keywords. The possible keywords are + * "read", "write", "execute", "delete", and "readlink". Their meaning is + * defined as follows: + * <P> + * <DL> + * <DT> read <DD> read permission + * <DT> write <DD> write permission + * <DT> execute + * <DD> execute permission. Allows <code>Runtime.exec</code> to + * be called. Corresponds to <code>SecurityManager.checkExec</code>. + * <DT> delete + * <DD> delete permission. Allows <code>File.delete</code> to + * be called. Corresponds to <code>SecurityManager.checkDelete</code>. + * <DT> readlink + * <DD> read link permission. Allows the target of a + * <a href="../nio/file/package-summary.html#links">symbolic link</a> + * to be read by invoking the {@link java.nio.file.Path#readSymbolicLink + * readSymbolicLink } method. + * </DL> + * <P> + * The actions string is converted to lowercase before processing. + * <P> + * Be careful when granting FilePermissions. Think about the implications + * of granting read and especially write access to various files and + * directories. The "<<ALL FILES>>" permission with write action is + * especially dangerous. This grants permission to write to the entire + * file system. One thing this effectively allows is replacement of the + * system binary, including the JVM runtime environment. + * + * <p>Please note: Code can always read a file from the same + * directory it's in (or a subdirectory of that directory); it does not + * need explicit permission to do so. + * + * @see java.security.Permission + * @see java.security.Permissions + * @see java.security.PermissionCollection + * + * + * @author Marianne Mueller + * @author Roland Schemers + * @since 1.2 + * + * @serial exclude + */ + +public final class FilePermission extends Permission implements Serializable { + + /** + * Execute action. + */ + private final static int EXECUTE = 0x1; + /** + * Write action. + */ + private final static int WRITE = 0x2; + /** + * Read action. + */ + private final static int READ = 0x4; + /** + * Delete action. + */ + private final static int DELETE = 0x8; + /** + * Read link action. + */ + private final static int READLINK = 0x10; + + /** + * All actions (read,write,execute,delete,readlink) + */ + private final static int ALL = READ|WRITE|EXECUTE|DELETE|READLINK; + /** + * No actions. + */ + private final static int NONE = 0x0; + + // the actions mask + private transient int mask; + + // does path indicate a directory? (wildcard or recursive) + private transient boolean directory; + + // is it a recursive directory specification? + private transient boolean recursive; + + /** + * the actions string. + * + * @serial + */ + private String actions; // Left null as long as possible, then + // created and re-used in the getAction function. + + // canonicalized dir path. In the case of + // directories, it is the name "/blah/*" or "/blah/-" without + // the last character (the "*" or "-"). + + private transient String cpath; + + // static Strings used by init(int mask) + private static final char RECURSIVE_CHAR = '-'; + private static final char WILD_CHAR = '*'; + +/* + public String toString() + { + StringBuffer sb = new StringBuffer(); + sb.append("***\n"); + sb.append("cpath = "+cpath+"\n"); + sb.append("mask = "+mask+"\n"); + sb.append("actions = "+getActions()+"\n"); + sb.append("directory = "+directory+"\n"); + sb.append("recursive = "+recursive+"\n"); + sb.append("***\n"); + return sb.toString(); + } +*/ + + private static final long serialVersionUID = 7930732926638008763L; + + /** + * initialize a FilePermission object. Common to all constructors. + * Also called during de-serialization. + * + * @param mask the actions mask to use. + * + */ + private void init(int mask) + { + + if ((mask & ALL) != mask) + throw new IllegalArgumentException("invalid actions mask"); + + if (mask == NONE) + throw new IllegalArgumentException("invalid actions mask"); + + if ((cpath = getName()) == null) + throw new NullPointerException("name can't be null"); + + this.mask = mask; + + if (cpath.equals("<<ALL FILES>>")) { + directory = true; + recursive = true; + cpath = ""; + return; + } + + // store only the canonical cpath if possible + cpath = AccessController.doPrivileged(new PrivilegedAction<String>() { + public String run() { + try { + return sun.security.provider.PolicyFile.canonPath(cpath); + } catch (IOException ioe) { + return cpath; + } + } + }); + + int len = cpath.length(); + char last = ((len > 0) ? cpath.charAt(len - 1) : 0); + + if (last == RECURSIVE_CHAR && + cpath.charAt(len - 2) == File.separatorChar) { + directory = true; + recursive = true; + cpath = cpath.substring(0, --len); + } else if (last == WILD_CHAR && + cpath.charAt(len - 2) == File.separatorChar) { + directory = true; + //recursive = false; + cpath = cpath.substring(0, --len); + } else { + // overkill since they are initialized to false, but + // commented out here to remind us... + //directory = false; + //recursive = false; + } + + // XXX: at this point the path should be absolute. die if it isn't? + } + + /** + * Creates a new FilePermission object with the specified actions. + * <i>path</i> is the pathname of a file or directory, and <i>actions</i> + * contains a comma-separated list of the desired actions granted on the + * file or directory. Possible actions are + * "read", "write", "execute", "delete", and "readlink". + * + * <p>A pathname that ends in "/*" (where "/" is + * the file separator character, <code>File.separatorChar</code>) + * indicates all the files and directories contained in that directory. + * A pathname that ends with "/-" indicates (recursively) all files and + * subdirectories contained in that directory. The special pathname + * "<<ALL FILES>>" matches any file. + * + * <p>A pathname consisting of a single "*" indicates all the files + * in the current directory, while a pathname consisting of a single "-" + * indicates all the files in the current directory and + * (recursively) all files and subdirectories contained in the current + * directory. + * + * <p>A pathname containing an empty string represents an empty path. + * + * @param path the pathname of the file/directory. + * @param actions the action string. + * + * @throws IllegalArgumentException + * If actions is <code>null</code>, empty or contains an action + * other than the specified possible actions. + */ + + public FilePermission(String path, String actions) + { + super(path); + init(getMask(actions)); + } + + /** + * Creates a new FilePermission object using an action mask. + * More efficient than the FilePermission(String, String) constructor. + * Can be used from within + * code that needs to create a FilePermission object to pass into the + * <code>implies</code> method. + * + * @param path the pathname of the file/directory. + * @param mask the action mask to use. + */ + + // package private for use by the FilePermissionCollection add method + FilePermission(String path, int mask) + { + super(path); + init(mask); + } + + /** + * Checks if this FilePermission object "implies" the specified permission. + * <P> + * More specifically, this method returns true if:<p> + * <ul> + * <li> <i>p</i> is an instanceof FilePermission,<p> + * <li> <i>p</i>'s actions are a proper subset of this + * object's actions, and <p> + * <li> <i>p</i>'s pathname is implied by this object's + * pathname. For example, "/tmp/*" implies "/tmp/foo", since + * "/tmp/*" encompasses all files in the "/tmp" directory, + * including the one named "foo". + * </ul> + * + * @param p the permission to check against. + * + * @return <code>true</code> if the specified permission is not + * <code>null</code> and is implied by this object, + * <code>false</code> otherwise. + */ + public boolean implies(Permission p) { + if (!(p instanceof FilePermission)) + return false; + + FilePermission that = (FilePermission) p; + + // we get the effective mask. i.e., the "and" of this and that. + // They must be equal to that.mask for implies to return true. + + return ((this.mask & that.mask) == that.mask) && impliesIgnoreMask(that); + } + + /** + * Checks if the Permission's actions are a proper subset of the + * this object's actions. Returns the effective mask iff the + * this FilePermission's path also implies that FilePermission's path. + * + * @param that the FilePermission to check against. + * @param exact return immediately if the masks are not equal + * @return the effective mask + */ + boolean impliesIgnoreMask(FilePermission that) { + if (this.directory) { + if (this.recursive) { + // make sure that.path is longer then path so + // something like /foo/- does not imply /foo + if (that.directory) { + return (that.cpath.length() >= this.cpath.length()) && + that.cpath.startsWith(this.cpath); + } else { + return ((that.cpath.length() > this.cpath.length()) && + that.cpath.startsWith(this.cpath)); + } + } else { + if (that.directory) { + // if the permission passed in is a directory + // specification, make sure that a non-recursive + // permission (i.e., this object) can't imply a recursive + // permission. + if (that.recursive) + return false; + else + return (this.cpath.equals(that.cpath)); + } else { + int last = that.cpath.lastIndexOf(File.separatorChar); + if (last == -1) + return false; + else { + // this.cpath.equals(that.cpath.substring(0, last+1)); + // Use regionMatches to avoid creating new string + return (this.cpath.length() == (last + 1)) && + this.cpath.regionMatches(0, that.cpath, 0, last+1); + } + } + } + } else if (that.directory) { + // if this is NOT recursive/wildcarded, + // do not let it imply a recursive/wildcarded permission + return false; + } else { + return (this.cpath.equals(that.cpath)); + } + } + + /** + * Checks two FilePermission objects for equality. Checks that <i>obj</i> is + * a FilePermission, and has the same pathname and actions as this object. + * <P> + * @param obj the object we are testing for equality with this object. + * @return <code>true</code> if obj is a FilePermission, and has the same + * pathname and actions as this FilePermission object, + * <code>false</code> otherwise. + */ + public boolean equals(Object obj) { + if (obj == this) + return true; + + if (! (obj instanceof FilePermission)) + return false; + + FilePermission that = (FilePermission) obj; + + return (this.mask == that.mask) && + this.cpath.equals(that.cpath) && + (this.directory == that.directory) && + (this.recursive == that.recursive); + } + + /** + * Returns the hash code value for this object. + * + * @return a hash code value for this object. + */ + + public int hashCode() { + return this.cpath.hashCode(); + } + + /** + * Converts an actions String to an actions mask. + * + * @param action the action string. + * @return the actions mask. + */ + private static int getMask(String actions) { + + int mask = NONE; + + // Null action valid? + if (actions == null) { + return mask; + } + // Check against use of constants (used heavily within the JDK) + if (actions == SecurityConstants.FILE_READ_ACTION) { + return READ; + } else if (actions == SecurityConstants.FILE_WRITE_ACTION) { + return WRITE; + } else if (actions == SecurityConstants.FILE_EXECUTE_ACTION) { + return EXECUTE; + } else if (actions == SecurityConstants.FILE_DELETE_ACTION) { + return DELETE; + } else if (actions == SecurityConstants.FILE_READLINK_ACTION) { + return READLINK; + } + + char[] a = actions.toCharArray(); + + int i = a.length - 1; + if (i < 0) + return mask; + + while (i != -1) { + char c; + + // skip whitespace + while ((i!=-1) && ((c = a[i]) == ' ' || + c == '\r' || + c == '\n' || + c == '\f' || + c == '\t')) + i--; + + // check for the known strings + int matchlen; + + if (i >= 3 && (a[i-3] == 'r' || a[i-3] == 'R') && + (a[i-2] == 'e' || a[i-2] == 'E') && + (a[i-1] == 'a' || a[i-1] == 'A') && + (a[i] == 'd' || a[i] == 'D')) + { + matchlen = 4; + mask |= READ; + + } else if (i >= 4 && (a[i-4] == 'w' || a[i-4] == 'W') && + (a[i-3] == 'r' || a[i-3] == 'R') && + (a[i-2] == 'i' || a[i-2] == 'I') && + (a[i-1] == 't' || a[i-1] == 'T') && + (a[i] == 'e' || a[i] == 'E')) + { + matchlen = 5; + mask |= WRITE; + + } else if (i >= 6 && (a[i-6] == 'e' || a[i-6] == 'E') && + (a[i-5] == 'x' || a[i-5] == 'X') && + (a[i-4] == 'e' || a[i-4] == 'E') && + (a[i-3] == 'c' || a[i-3] == 'C') && + (a[i-2] == 'u' || a[i-2] == 'U') && + (a[i-1] == 't' || a[i-1] == 'T') && + (a[i] == 'e' || a[i] == 'E')) + { + matchlen = 7; + mask |= EXECUTE; + + } else if (i >= 5 && (a[i-5] == 'd' || a[i-5] == 'D') && + (a[i-4] == 'e' || a[i-4] == 'E') && + (a[i-3] == 'l' || a[i-3] == 'L') && + (a[i-2] == 'e' || a[i-2] == 'E') && + (a[i-1] == 't' || a[i-1] == 'T') && + (a[i] == 'e' || a[i] == 'E')) + { + matchlen = 6; + mask |= DELETE; + + } else if (i >= 7 && (a[i-7] == 'r' || a[i-7] == 'R') && + (a[i-6] == 'e' || a[i-6] == 'E') && + (a[i-5] == 'a' || a[i-5] == 'A') && + (a[i-4] == 'd' || a[i-4] == 'D') && + (a[i-3] == 'l' || a[i-3] == 'L') && + (a[i-2] == 'i' || a[i-2] == 'I') && + (a[i-1] == 'n' || a[i-1] == 'N') && + (a[i] == 'k' || a[i] == 'K')) + { + matchlen = 8; + mask |= READLINK; + + } else { + // parse error + throw new IllegalArgumentException( + "invalid permission: " + actions); + } + + // make sure we didn't just match the tail of a word + // like "ackbarfaccept". Also, skip to the comma. + boolean seencomma = false; + while (i >= matchlen && !seencomma) { + switch(a[i-matchlen]) { + case ',': + seencomma = true; + /*FALLTHROUGH*/ + case ' ': case '\r': case '\n': + case '\f': case '\t': + break; + default: + throw new IllegalArgumentException( + "invalid permission: " + actions); + } + i--; + } + + // point i at the location of the comma minus one (or -1). + i -= matchlen; + } + + return mask; + } + + /** + * Return the current action mask. Used by the FilePermissionCollection. + * + * @return the actions mask. + */ + + int getMask() { + return mask; + } + + /** + * Return the canonical string representation of the actions. + * Always returns present actions in the following order: + * read, write, execute, delete, readlink. + * + * @return the canonical string representation of the actions. + */ + private static String getActions(int mask) + { + StringBuilder sb = new StringBuilder(); + boolean comma = false; + + if ((mask & READ) == READ) { + comma = true; + sb.append("read"); + } + + if ((mask & WRITE) == WRITE) { + if (comma) sb.append(','); + else comma = true; + sb.append("write"); + } + + if ((mask & EXECUTE) == EXECUTE) { + if (comma) sb.append(','); + else comma = true; + sb.append("execute"); + } + + if ((mask & DELETE) == DELETE) { + if (comma) sb.append(','); + else comma = true; + sb.append("delete"); + } + + if ((mask & READLINK) == READLINK) { + if (comma) sb.append(','); + else comma = true; + sb.append("readlink"); + } + + return sb.toString(); + } + + /** + * Returns the "canonical string representation" of the actions. + * That is, this method always returns present actions in the following order: + * read, write, execute, delete, readlink. For example, if this FilePermission + * object allows both write and read actions, a call to <code>getActions</code> + * will return the string "read,write". + * + * @return the canonical string representation of the actions. + */ + public String getActions() + { + if (actions == null) + actions = getActions(this.mask); + + return actions; + } + + + /** + * Returns a new PermissionCollection object for storing FilePermission + * objects. + * <p> + * FilePermission objects must be stored in a manner that allows them + * to be inserted into the collection in any order, but that also enables the + * PermissionCollection <code>implies</code> + * method to be implemented in an efficient (and consistent) manner. + * + * <p>For example, if you have two FilePermissions: + * <OL> + * <LI> <code>"/tmp/-", "read"</code> + * <LI> <code>"/tmp/scratch/foo", "write"</code> + * </OL> + * + * <p>and you are calling the <code>implies</code> method with the FilePermission: + * + * <pre> + * "/tmp/scratch/foo", "read,write", + * </pre> + * + * then the <code>implies</code> function must + * take into account both the "/tmp/-" and "/tmp/scratch/foo" + * permissions, so the effective permission is "read,write", + * and <code>implies</code> returns true. The "implies" semantics for + * FilePermissions are handled properly by the PermissionCollection object + * returned by this <code>newPermissionCollection</code> method. + * + * @return a new PermissionCollection object suitable for storing + * FilePermissions. + */ + + public PermissionCollection newPermissionCollection() { + return new FilePermissionCollection(); + } + + /** + * WriteObject is called to save the state of the FilePermission + * to a stream. The actions are serialized, and the superclass + * takes care of the name. + */ + private void writeObject(ObjectOutputStream s) + throws IOException + { + // Write out the actions. The superclass takes care of the name + // call getActions to make sure actions field is initialized + if (actions == null) + getActions(); + s.defaultWriteObject(); + } + + /** + * readObject is called to restore the state of the FilePermission from + * a stream. + */ + private void readObject(ObjectInputStream s) + throws IOException, ClassNotFoundException + { + // Read in the actions, then restore everything else by calling init. + s.defaultReadObject(); + init(getMask(actions)); + } +} + +/** + * A FilePermissionCollection stores a set of FilePermission permissions. + * FilePermission objects + * must be stored in a manner that allows them to be inserted in any + * order, but enable the implies function to evaluate the implies + * method. + * For example, if you have two FilePermissions: + * <OL> + * <LI> "/tmp/-", "read" + * <LI> "/tmp/scratch/foo", "write" + * </OL> + * And you are calling the implies function with the FilePermission: + * "/tmp/scratch/foo", "read,write", then the implies function must + * take into account both the /tmp/- and /tmp/scratch/foo + * permissions, so the effective permission is "read,write". + * + * @see java.security.Permission + * @see java.security.Permissions + * @see java.security.PermissionCollection + * + * + * @author Marianne Mueller + * @author Roland Schemers + * + * @serial include + * + */ + +final class FilePermissionCollection extends PermissionCollection +implements Serializable { + + // Not serialized; see serialization section at end of class + private transient List<Permission> perms; + + /** + * Create an empty FilePermissions object. + * + */ + + public FilePermissionCollection() { + perms = new ArrayList<Permission>(); + } + + /** + * Adds a permission to the FilePermissions. The key for the hash is + * permission.path. + * + * @param permission the Permission object to add. + * + * @exception IllegalArgumentException - if the permission is not a + * FilePermission + * + * @exception SecurityException - if this FilePermissionCollection object + * has been marked readonly + */ + + public void add(Permission permission) + { + if (! (permission instanceof FilePermission)) + throw new IllegalArgumentException("invalid permission: "+ + permission); + if (isReadOnly()) + throw new SecurityException( + "attempt to add a Permission to a readonly PermissionCollection"); + + synchronized (this) { + perms.add(permission); + } + } + + /** + * Check and see if this set of permissions implies the permissions + * expressed in "permission". + * + * @param p the Permission object to compare + * + * @return true if "permission" is a proper subset of a permission in + * the set, false if not. + */ + + public boolean implies(Permission permission) + { + if (! (permission instanceof FilePermission)) + return false; + + FilePermission fp = (FilePermission) permission; + + int desired = fp.getMask(); + int effective = 0; + int needed = desired; + + synchronized (this) { + int len = perms.size(); + for (int i = 0; i < len; i++) { + FilePermission x = (FilePermission) perms.get(i); + if (((needed & x.getMask()) != 0) && x.impliesIgnoreMask(fp)) { + effective |= x.getMask(); + if ((effective & desired) == desired) + return true; + needed = (desired ^ effective); + } + } + } + return false; + } + + /** + * Returns an enumeration of all the FilePermission objects in the + * container. + * + * @return an enumeration of all the FilePermission objects. + */ + + public Enumeration elements() { + // Convert Iterator into Enumeration + synchronized (this) { + return Collections.enumeration(perms); + } + } + + private static final long serialVersionUID = 2202956749081564585L; + + // Need to maintain serialization interoperability with earlier releases, + // which had the serializable field: + // private Vector permissions; + + /** + * @serialField permissions java.util.Vector + * A list of FilePermission objects. + */ + private static final ObjectStreamField[] serialPersistentFields = { + new ObjectStreamField("permissions", Vector.class), + }; + + /** + * @serialData "permissions" field (a Vector containing the FilePermissions). + */ + /* + * Writes the contents of the perms field out as a Vector for + * serialization compatibility with earlier releases. + */ + private void writeObject(ObjectOutputStream out) throws IOException { + // Don't call out.defaultWriteObject() + + // Write out Vector + Vector<Permission> permissions = new Vector<Permission>(perms.size()); + synchronized (this) { + permissions.addAll(perms); + } + + ObjectOutputStream.PutField pfields = out.putFields(); + pfields.put("permissions", permissions); + out.writeFields(); + } + + /* + * Reads in a Vector of FilePermissions and saves them in the perms field. + */ + @SuppressWarnings("unchecked") + private void readObject(ObjectInputStream in) throws IOException, + ClassNotFoundException { + // Don't call defaultReadObject() + + // Read in serialized fields + ObjectInputStream.GetField gfields = in.readFields(); + + // Get the one we want + Vector<Permission> permissions = (Vector<Permission>)gfields.get("permissions", null); + perms = new ArrayList<Permission>(permissions.size()); + perms.addAll(permissions); + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/io/Inputs.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,391 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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 conne02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.io; + +import java.io.Closeable; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; + +import java.nio.charset.Charset; +import java.nio.charset.UnsupportedCharsetException; +import java.nio.channels.Channels; + +import java.util.Collections; +import java.util.Arrays; +import java.util.ArrayList; +import java.util.List; + + +import org.classpath.icedtea.java.nio.file.FileRef; + +import org.classpath.icedtea.java.nio.file.attribute.Attributes; + +import org.classpath.icedtea.java.util.Scanner; + +/** + * {@note experimental} + * This class consists exclusively of static methods that operate on input + * sources. + * + * <p> The methods to read lines of text defined by this class recognize the + * following as Unicode line terminators: + * <ul> + * <li> <code>\u000D</code> followed by <code>\u000A</code>, + * CARRIAGE RETURN followed by LINE FEED </li> + * <li> <code>\u000A</code>, LINE FEED </li> + * <li> <code>\u000D</code>, CARRIAGE RETURN </li> + * <li> <code>\u2028</code>, LINE SEPARATOR </li> + * <li> <code>\u2029</code>, PARAGRAPH SEPARATOR </li> + * <li> <code>\u0085</code>, NEXT LINE (NEL)</li> + * </ul> + * + * @since 1.7 + */ + +public final class Inputs { + private Inputs() { } + + // initial buffer size when reading (or writing) + private static final int INITIAL_BUFFER_SIZE = 8192; + + // checks that charset is supported + private static void ensureCharsetIsSupported(String csn) { + if (csn == null) + throw new NullPointerException("'csn' is null"); + if (!Charset.isSupported(csn)) + throw new UnsupportedCharsetException(csn); + } + + /** + * Closes the given data source by invoking its {@link Closeable#close close} + * method. If the {@code close} method throws an {@code IOException} then it + * is silently ignored. If the source is already closed then invoking this + * method has no effect. + * + * <p> This method should not be used to close destinations or output + * streams that may be buffered. An I/O error may occur when flushing + * buffered data. + * + * @param source + * The data source + */ + public static void closeUnchecked(Closeable source) { + try { + source.close(); + } catch (IOException ignore) { } + } + + /** + * Read all bytes from the specified file. When all bytes have been read, or + * an I/O error occurs, then the file is closed. + * + * @param source + * The data source + * + * @return A byte array containing the bytes read from the file + * + * @throws IOException + * If an I/O error occurs + * @throws OutOfMemoryError + * If the required array size is too large + */ + public static byte[] readAllBytes(FileRef source) throws IOException { + long size = Attributes.readBasicFileAttributes(source).size(); + if (size > (long)Integer.MAX_VALUE) + throw new OutOfMemoryError("Required array size too large"); + InputStream in = Channels.newInputStream(source.newByteChannel()); + try { + return implReadAllBytes(in, Math.min((int)size, INITIAL_BUFFER_SIZE)); + } finally { + in.close(); + } + } + + /** + * Read all bytes from the specified file. When all bytes have been read, or + * an I/O error occurs, then the file is closed. + * + * @param source + * The data source + * + * @return A byte array containing the bytes read from the file + * + * @throws IOException + * If an I/O error occurs + * @throws OutOfMemoryError + * If the required array size is too large + */ + public static byte[] readAllBytes(File source) throws IOException { + InputStream in = new FileInputStream(source); + try { + return implReadAllBytes(in, INITIAL_BUFFER_SIZE); + } finally { + in.close(); + } + } + + /** + * Read all bytes from the specified input stream. + * + * <p> <b>Usage Example:</b> + * Suppose we want to open a connection to a resource identified by a URI, + * and read all bytes: + * <pre> + * URI uri = ... + * byte[] content = InputOutput.readAllBytes(uri.toURL().openStream()); + * </pre> + * + * <p> On return, the input stream will be at end of stream. + * + * @param source + * The data source + * + * @return A byte array containing the bytes read from the source + * + * @throws IOException + * If an I/O error occurs + * @throws OutOfMemoryError + * If the required array size is too large + */ + public static byte[] readAllBytes(InputStream source) throws IOException { + return implReadAllBytes(source, INITIAL_BUFFER_SIZE); + } + + private static byte[] implReadAllBytes(InputStream source, int initialSize) + throws IOException + { + byte[] buf = new byte[initialSize]; + int nread = 0; + int rem = buf.length; + int n; + while ((n = source.read(buf, nread, rem)) > 0) { + nread += n; + rem -= n; + if (rem <= 0) { + int newSize = buf.length << 1; + if (newSize <= buf.length) { + if (buf.length == Integer.MAX_VALUE) + throw new OutOfMemoryError("Required array size too large"); + newSize = Integer.MAX_VALUE; + } + rem = newSize - buf.length; + buf = Arrays.copyOf(buf, newSize); + } + } + return (buf.length == nread) ? buf : Arrays.copyOf(buf, nread); + } + + /** + * Read all lines from the specified file. Bytes from the file are + * converted into characters using the specified charset. When all lines + * have been read, or an I/O error occurs, then the file is closed. + * + * @param source + * The data source + * @param csn + * The name of the charset to be used + * + * @throws java.nio.charset.UnsupportedCharsetException + * If no support for the named charset is available + * in this instance of the Java virtual machine + * @throws java.nio.charset.MalformedInputException + * If the file contains a byte sequence that is not legal for the + * charset + * @throws IOException + * If an I/O error occurs + */ + public static List<String> readAllLines(FileRef source, String csn) + throws IOException + { + ensureCharsetIsSupported(csn); + Scanner s = new Scanner(source, csn); + try { + return implReadAllLines(s); + } finally { + s.close(); + } + } + + /** + * Read all lines from the specified file. Bytes from the file are + * converted into characters using the underlying platform's {@linkplain + * java.nio.charset.Charset#defaultCharset() default charset}. When all lines + * have been read, or an I/O error occurs, then the file is closed. + * + * @param source + * The data source + * + * @throws java.nio.charset.MalformedInputException + * If the file contains a byte sequence that is not legal for the + * default charset + * @throws IOException + * If an I/O error occurs + */ + public static List<String> readAllLines(FileRef source) throws IOException { + Scanner s = new Scanner(source); + try { + return implReadAllLines(s); + } finally { + s.close(); + } + } + + /** + * Read all lines from the specified file. Bytes from the file are + * converted into characters using the specified charset. When all lines + * have been read, or an I/O error occurs, then the file is closed. + * + * @param source + * The data source + * @param csn + * The name of the charset to be used + * + * @throws UnsupportedCharsetException + * If no support for the named charset is available + * in this instance of the Java virtual machine + * @throws java.nio.charset.MalformedInputException + * If the file contains a byte sequence that is not legal for the + * charset + * @throws IOException + * If an I/O error occurs + */ + public static List<String> readAllLines(File source, String csn) + throws IOException + { + ensureCharsetIsSupported(csn); + Scanner s = new Scanner(source, csn); + try { + return implReadAllLines(s); + } finally { + s.close(); + } + } + + /** + * Read all lines from the specified file. Bytes from the file are + * converted into characters using the underlying platform's {@linkplain + * Charset#defaultCharset() default charset}. When all lines have been read, + * or an I/O error occurs, then the file is closed. + * + * @param source + * The data source + * @throws java.nio.charset.MalformedInputException + * If the file contains a byte sequence that is not legal for the + * default charset + * @throws IOException + * If an I/O error occurs + */ + public static List<String> readAllLines(File source) throws IOException { + Scanner s = new Scanner(source); + try { + return implReadAllLines(s); + } finally { + s.close(); + } + } + + /** + * Read all lines from the specified input stream. Bytes from the stream are + * converted into characters using the specified charset. + * + * <p> On return, the input stream will be at end of stream. + * + * @param source + * The input stream to read from + * @param csn + * The name of the charset to be used + * + * @throws UnsupportedCharsetException + * If no support for the named charset is available + * in this instance of the Java virtual machine + * @throws java.nio.charset.MalformedInputException + * If a byte sequence that is not legal for the charset is read + * from the input + * @throws IOException + * If an I/O error occurs + */ + public static List<String> readAllLines(InputStream source, String csn) + throws IOException + { + ensureCharsetIsSupported(csn); + return implReadAllLines(new Scanner(source, csn)); + } + + /** + * Read all lines from the specified input stream. Bytes from the stream are + * converted into characters using the underlying platform's {@linkplain + * Charset#defaultCharset() default charset}. + * + * <p> On return, the input stream will be at end of stream. + * + * @param source + * The input stream to read from + * + * @return An unmodifiable list of the lines read from the input stream + * + * @throws java.nio.charset.MalformedInputException + * If a byte sequence that is not legal for the default charset is + * read from the input + * @throws IOException + * If an I/O error occurs + */ + public static List<String> readAllLines(InputStream source) throws IOException { + return implReadAllLines(new Scanner(source)); + } + + /** + * Read all lines from the from the specified source. + * + * <p> On return, the input source will be at end of stream. + * + * @param source + * The input stream to read from + * + * @return An unmodifiable list of the lines read from source + * + * @throws IOException + * If an I/O error occurs + */ + public static List<String> readAllLines(Readable source) throws IOException { + return implReadAllLines(new Scanner(source)); + } + + private static List<String> implReadAllLines(Scanner s) throws IOException { + try { + List<String> result = new ArrayList<String>(); + while (s.hasNextLine()) { + result.add(s.nextLine()); + } + return Collections.unmodifiableList(result); + } finally { + IOException ioe = s.ioException(); + if (ioe != null) + throw ioe; + } + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/io/Outputs.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,362 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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 conne02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.io; + +import java.io.BufferedWriter; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.io.OutputStreamWriter; + +import java.nio.ByteBuffer; +import java.nio.charset.Charset; +import java.nio.charset.UnsupportedCharsetException; +import java.nio.channels.Channels; +import java.nio.channels.WritableByteChannel; +import java.util.Arrays; +import java.util.List; + +import org.classpath.icedtea.java.nio.file.FileRef; + +import static org.classpath.icedtea.java.nio.file.StandardOpenOption.CREATE; +import static org.classpath.icedtea.java.nio.file.StandardOpenOption.TRUNCATE_EXISTING; +import static org.classpath.icedtea.java.nio.file.StandardOpenOption.WRITE; + +/** + * {@note experimental} + * This class consists exclusively of static methods that operate on output + * destinations. + * + * <p> The methods to write lines of text output a line terminator following + * each line. The line terminator that is output is platform line terminated, + * as defined by the {@code line.separator} system property. + * + * @since 1.7 + */ + +public final class Outputs { + private Outputs() { } + + // checks that charset is supported + private static void ensureCharsetIsSupported(String csn) { + if (csn == null) + throw new NullPointerException("'csn' is null"); + if (!Charset.isSupported(csn)) + throw new UnsupportedCharsetException(csn); + } + + /** + * Writes a byte array to a file. The file is created if it does not exist. + * If the file already exists, it is first truncated. + * + * @throws IOException + * If an I/O error occurs + */ + public static void write(FileRef file, byte[] bytes) throws IOException { + write(file, bytes, 0, bytes.length); + } + + /** + * Writes a byte array to a file. The file is created if it does not exist. + * If the file already exists, it is first truncated. + * + * @throws IndexOutOfBoundsException + * If {@code off} or {@code len} is negative, or {@code off+len} + * is greater than the length of the array + * @throws IOException + * If an I/O error occurs + */ + public static void write(FileRef file, byte[] bytes, int off, int len) + throws IOException + { + WritableByteChannel wbc = file.newByteChannel(WRITE, CREATE, TRUNCATE_EXISTING); + try { + int pos = off; + while (pos < len) { + int size = Math.min(len-pos, 8192); + ByteBuffer bb = ByteBuffer.wrap(bytes, pos, size); + int n = wbc.write(bb); + pos += n; + } + } finally { + wbc.close(); + } + } + + /** + * Writes the given lines of text to the specified file. The characters in + * each line are encoded into bytes using the specified charset. When all + * lines have been written, or an I/O error occurs, then the file is closed. + * + * @param file + * The file + * @param lines + * The list of lines to write (in order) + * @param csn + * The name of the charset to be used + * + * @throws java.nio.charset.UnsupportedCharsetException + * If no support for the named charset is available + * in this instance of the Java virtual machine + * @throws java.nio.charset.UnmappableCharacterException + * Where a line contains a character that cannot be mapped to an + * output byte sequence + * @throws IOException + * If an I/O error occurs + */ + public static void writeLines(FileRef file, List<String> lines, String csn) + throws IOException + { + ensureCharsetIsSupported(csn); + WritableByteChannel wbc = file.newByteChannel(WRITE, CREATE, TRUNCATE_EXISTING); + BufferedWriter writer = new BufferedWriter(Channels.newWriter(wbc, csn)); + try { + implWriteLines(writer, lines); + } finally { + writer.close(); + } + } + + /** + * Writes the given lines of text to the specified file. The characters in + * each line are encoded into bytes using the underlying platform's {@linkplain + * Charset#defaultCharset() default charset}. When all lines have been + * written, or an I/O error occurs, then the file is closed. + * + * @param file + * The file + * @param lines + * The list of lines to write (in order) + * + * @throws java.nio.charset.UnmappableCharacterException + * Where a line contains a character that cannot be mapped to an + * output byte sequence + * @throws IOException + * If an I/O error occurs + */ + public static void writeLines(FileRef file, List<String> lines) + throws IOException + { + writeLines(file, lines, Charset.defaultCharset().name()); + } + + /** + * Writes the given lines of text to the specified file. The characters in + * each line are encoded into bytes using the underlying platform's {@linkplain + * Charset#defaultCharset() default charset}. When all lines have been + * written, or an I/O error occurs, then the file is closed. + * + * @param file + * The file + * @param lines + * The array of lines to write (in order) + * + * @throws java.nio.charset.UnmappableCharacterException + * Where a line contains a character that cannot be mapped to an + * output byte sequence + * @throws IOException + * If an I/O error occurs + */ + public static void writeLines(FileRef file, String... lines) + throws IOException + { + writeLines(file, Arrays.asList(lines), Charset.defaultCharset().name()); + } + + /** + * Writes a byte array to a file. The file is created if it does not exist. + * If the file already exists, it is first truncated. + * + * @param file + * The file + * @param bytes + * The byte array to write to the file + * + * @throws IOException + * If an I/O error occurs + */ + public static void write(File file, byte[] bytes) throws IOException { + write(file, bytes, 0, bytes.length); + } + + /** + * Writes a byte array to a file. The file is created if it does not exist. + * If the file already exists, it is first truncated. + * + * @throws IndexOutOfBoundsException + * If {@code off} or {@code len} is negative, or {@code off+len} + * is greater than the length of the array + * @throws IOException + * If an I/O error occurs + */ + public static void write(File file, byte[] bytes, int off, int len) + throws IOException + { + FileOutputStream out = new FileOutputStream(file); + try { + out.write(bytes, off, len); + } finally { + out.close(); + } + } + + /** + * Writes the given lines of text to the specified file. The characters in + * each line are encoded into bytes using the specified charset. When all + * lines have been written, or an I/O error occurs, then the file is closed. + * + * @param file + * The file + * @param lines + * The list of lines to write (in order) + * @param csn + * The name of the charset to be used + * + * @throws java.nio.charset.UnsupportedCharsetException + * If no support for the named charset is available + * in this instance of the Java virtual machine + * @throws java.nio.charset.UnmappableCharacterException + * Where a line contains a character that cannot be mapped to an + * output byte sequence + * @throws IOException + * If an I/O error occurs + */ + public static void writeLines(File file, List<String> lines, String csn) + throws IOException + { + ensureCharsetIsSupported(csn); + FileOutputStream out = new FileOutputStream(file); + BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, csn)); + try { + implWriteLines(writer, lines); + } finally { + writer.close(); + } + } + + /** + * Writes the given lines of text to the specified file. The characters in + * each line are encoded into bytes using the underlying platform's {@linkplain + * Charset#defaultCharset() default charset}. When all lines have been + * written, or an I/O error occurs, then the file is closed. + * + * @param file + * The file + * @param lines + * The list of lines to write (in order) + * + * @throws java.nio.charset.UnmappableCharacterException + * Where a line contains a character that cannot be mapped to an + * output byte sequence + * @throws IOException + * If an I/O error occurs + */ + public static void writeLines(File file, List<String> lines) + throws IOException + { + writeLines(file, lines, Charset.defaultCharset().name()); + } + + /** + * Writes the given lines of text to the specified file. The characters in + * each line are encoded into bytes using the underlying platform's {@linkplain + * Charset#defaultCharset() default charset}. When all lines have been + * written, or an I/O error occurs, then the file is closed. + * + * @param file + * The file + * @param lines + * The array of lines to write (in order) + * + * @throws java.nio.charset.UnmappableCharacterException + * Where a line contains a character that cannot be mapped to an + * output byte sequence + * @throws IOException + * If an I/O error occurs + */ + public static void writeLines(File file, String... lines) + throws IOException + { + writeLines(file, Arrays.asList(lines), Charset.defaultCharset().name()); + } + + /** + * Writes the given lines of text to the specified output stream. The + * characters in each line are encoded into bytes using the specified charset. + * + * @param out + * The output stream + * @param lines + * The list of lines to write (in order) + * @param csn + * The name of the charset to be used + * + * @throws java.nio.charset.UnmappableCharacterException + * Where a line contains a character that cannot be mapped to an + * output byte sequence + * @throws IOException + * If an I/O error occurs + */ + public static void writeLines(OutputStream out, List<String> lines, String csn) + throws IOException + { + BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, csn)); + implWriteLines(writer, lines); + writer.flush(); + } + + /** + * Writes the given lines of text to the specified output stream. The + * characters in each line are encoded into bytes using the underlying + * platform's {@linkplain Charset#defaultCharset() default charset}. + * + * @param out + * The output stream + * @param lines + * The list of lines to write (in order) + * + * @throws java.nio.charset.UnmappableCharacterException + * Where a line contains a character that cannot be mapped to an + * output byte sequence + * @throws IOException + * If an I/O error occurs + */ + public static void writeLines(OutputStream out, List<String> lines) + throws IOException + { + writeLines(out, lines, Charset.defaultCharset().name()); + } + + private static void implWriteLines(BufferedWriter writer, List<String> lines) + throws IOException + { + for (String line: lines) { + writer.write(line); + writer.newLine(); + } + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/net/ProtocolFamily.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,40 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.net; + +/** + * Represents a family of communication protocols. + * + * @since 1.7 + */ + +public interface ProtocolFamily { + /** + * Returns the name of the protocol family. + */ + String name(); +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/net/SocketOption.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,56 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.net; + +/** + * A socket option associated with a socket. + * + * <p> In the {@link java.nio.channels channels} package, the {@link + * java.nio.channels.NetworkChannel} interface defines the {@link + * java.nio.channels.NetworkChannel#setOption(SocketOption,Object) setOption} + * and {@link java.nio.channels.NetworkChannel#getOption(SocketOption) getOption} + * methods to set and query the channel's socket options. + * + * @param <T> The type of the socket option value. + * + * @since 1.7 + * + * @see StandardSocketOption + */ + +public interface SocketOption<T> { + + /** + * Returns the name of the socket option. + */ + String name(); + + /** + * Returns the type of the socket option value. + */ + Class<T> type(); +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/net/StandardProtocolFamily.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,46 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.net; + +/** + * Defines the standard families of communication protocols. + * + * @since 1.7 + */ + +public enum StandardProtocolFamily implements ProtocolFamily { + + /** + * Internet Protocol Version 4 (IPv4) + */ + INET, + + /** + * Internet Protocol Version 6 (IPv6) + */ + INET6 +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/net/StandardSocketOption.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,370 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.net; + +import java.net.NetworkInterface; + +/** + * Defines the <em>standard</em> socket options. + * + * <p> The {@link SocketOption#name name} of each socket option defined by this + * class is its field name. + * + * <p> In this release, the socket options defined here are used by {@link + * java.nio.channels.NetworkChannel network} channels in the {@link + * java.nio.channels channels} package. + * + * @since 1.7 + */ + +public final class StandardSocketOption { + private StandardSocketOption() { } + + // -- SOL_SOCKET -- + + /** + * Allow transmission of broadcast datagrams. + * + * <p> The value of this socket option is a {@code Boolean} that represents + * whether the option is enabled or disabled. The option is specific to + * datagram-oriented sockets sending to {@link java.net.Inet4Address IPv4} + * broadcast addresses. When the socket option is enabled then the socket + * can be used to send <em>broadcast datagrams</em>. + * + * <p> The initial value of this socket option is {@code FALSE}. The socket + * option may be enabled or disabled at any time. Some operating systems may + * require that the Java virtual machine be started with implementation + * specific privileges to enable this option or send broadcast datagrams. + * + * @see <a href="http://www.ietf.org/rfc/rfc919.txt">RFC 929: + * Broadcasting Internet Datagrams</a> + * @see DatagramSocket#setBroadcast + */ + public static final SocketOption<Boolean> SO_BROADCAST = + new StdSocketOption<Boolean>("SO_BROADCAST", Boolean.class); + + /** + * Keep connection alive. + * + * <p> The value of this socket option is a {@code Boolean} that represents + * whether the option is enabled or disabled. When the {@code SO_KEEPALIVE} + * option is enabled the operating system may use a <em>keep-alive</em> + * mechanism to periodically probe the other end of a connection when the + * connection is otherwise idle. The exact semantics of the keep alive + * mechanism is system dependent and therefore unspecified. + * + * <p> The initial value of this socket option is {@code FALSE}. The socket + * option may be enabled or disabled at any time. + * + * @see <a href="http://www.ietf.org/rfc/rfc1122.txt">RFC 1122 + * Requirements for Internet Hosts -- Communication Layers</a> + * @see Socket#setKeepAlive + */ + public static final SocketOption<Boolean> SO_KEEPALIVE = + new StdSocketOption<Boolean>("SO_KEEPALIVE", Boolean.class); + + /** + * The size of the socket send buffer. + * + * <p> The value of this socket option is an {@code Integer} that is the + * size of the socket send buffer in bytes. The socket send buffer is an + * output buffer used by the networking implementation. It may need to be + * increased for high-volume connections. The value of the socket option is + * a <em>hint</em> to the implementation to size the buffer and the actual + * size may differ. The socket option can be queried to retrieve the actual + * size. + * + * <p> For datagram-oriented sockets, the size of the send buffer may limit + * the size of the datagrams that may be sent by the socket. Whether + * datagrams larger than the buffer size are sent or discarded is system + * dependent. + * + * <p> The initial/default size of the socket send buffer and the range of + * allowable values is system dependent although a negative size is not + * allowed. An attempt to set the socket send buffer to larger than its + * maximum size causes it to be set to its maximum size. + * + * <p> An implementation allows this socket option to be set before the + * socket is bound or connected. Whether an implementation allows the + * socket send buffer to be changed after the socket is bound is system + * dependent. + * + * @see Socket#setSendBufferSize + */ + public static final SocketOption<Integer> SO_SNDBUF = + new StdSocketOption<Integer>("SO_SNDBUF", Integer.class); + + + /** + * The size of the socket receive buffer. + * + * <p> The value of this socket option is an {@code Integer} that is the + * size of the socket receive buffer in bytes. The socket receive buffer is + * an input buffer used by the networking implementation. It may need to be + * increased for high-volume connections or decreased to limit the possible + * backlog of incoming data. The value of the socket option is a + * <em>hint</em> to the implementation to size the buffer and the actual + * size may differ. + * + * <p> For datagram-oriented sockets, the size of the receive buffer may + * limit the size of the datagrams that can be received. Whether datagrams + * larger than the buffer size can be received is system dependent. + * Increasing the socket receive buffer may be important for cases where + * datagrams arrive in bursts faster than they can be processed. + * + * <p> In the case of stream-oriented sockets and the TCP/IP protocol, the + * size of the socket receive buffer may be used when advertising the size + * of the TCP receive window to the remote peer. + * + * <p> The initial/default size of the socket receive buffer and the range + * of allowable values is system dependent although a negative size is not + * allowed. An attempt to set the socket receive buffer to larger than its + * maximum size causes it to be set to its maximum size. + * + * <p> An implementation allows this socket option to be set before the + * socket is bound or connected. Whether an implementation allows the + * socket receive buffer to be changed after the socket is bound is system + * dependent. + * + * @see <a href="http://www.ietf.org/rfc/rfc1323.txt">RFC 1323: TCP + * Extensions for High Performance</a> + * @see Socket#setReceiveBufferSize + * @see ServerSocket#setReceiveBufferSize + */ + public static final SocketOption<Integer> SO_RCVBUF = + new StdSocketOption<Integer>("SO_RCVBUF", Integer.class); + + /** + * Re-use address. + * + * <p> The value of this socket option is a {@code Boolean} that represents + * whether the option is enabled or disabled. The exact semantics of this + * socket option are socket type and system dependent. + * + * <p> In the case of stream-oriented sockets, this socket option will + * usually determine whether the socket can be bound to a socket address + * when a previous connection involving that socket address is in the + * <em>TIME_WAIT</em> state. On implementations where the semantics differ, + * and the socket option is not required to be enabled in order to bind the + * socket when a previous connection is in this state, then the + * implementation may choose to ignore this option. + * + * <p> For datagram-oriented sockets the socket option is used to allow + * multiple programs bind to the same address. This option should be enabled + * when the socket is to be used for Internet Protocol (IP) multicasting. + * + * <p> An implementation allows this socket option to be set before the + * socket is bound or connected. Changing the value of this socket option + * after the socket is bound has no effect. The default value of this + * socket option is system dependent. + * + * @see <a href="http://www.ietf.org/rfc/rfc793.txt">RFC 793: Transmission + * Control Protocol</a> + * @see ServerSocket#setReuseAddress + */ + public static final SocketOption<Boolean> SO_REUSEADDR = + new StdSocketOption<Boolean>("SO_REUSEADDR", Boolean.class); + + /** + * Linger on close if data is present. + * + * <p> The value of this socket option is an {@code Integer} that controls + * the action taken when unsent data is queued on the socket and a method + * to close the socket is invoked. If the value of the socket option is zero + * or greater, then it represents a timeout value, in seconds, known as the + * <em>linger interval</em>. The linger interval is the timeout for the + * {@code close} method to block while the operating system attempts to + * transmit the unsent data or it decides that it is unable to transmit the + * data. If the value of the socket option is less than zero then the option + * is disabled. In that case the {@code close} method does not wait until + * unsent data is transmitted; if possible the operating system will transmit + * any unsent data before the connection is closed. + * + * <p> This socket option is intended for use with sockets that are configured + * in {@link java.nio.channels.SelectableChannel#isBlocking() blocking} mode + * only. The behavior of the {@code close} method when this option is + * enabled on a non-blocking socket is not defined. + * + * <p> The initial value of this socket option is a negative value, meaning + * that the option is disabled. The option may be enabled, or the linger + * interval changed, at any time. The maximum value of the linger interval + * is system dependent. Setting the linger interval to a value that is + * greater than its maximum value causes the linger interval to be set to + * its maximum value. + * + * @see Socket#setSoLinger + */ + public static final SocketOption<Integer> SO_LINGER = + new StdSocketOption<Integer>("SO_LINGER", Integer.class); + + + // -- IPPROTO_IP -- + + /** + * The Type of Service (ToS) octet in the Internet Protocol (IP) header. + * + * <p> The value of this socket option is an {@code Integer} representing + * the value of the ToS octet in IP packets sent by sockets to an {@link + * StandardProtocolFamily#INET IPv4} socket. The interpretation of the ToS + * octet is network specific and is not defined by this class. Further + * information on the ToS octet can be found in <a + * href="http://www.ietf.org/rfc/rfc1349.txt">RFC 1349</a> and <a + * href="http://www.ietf.org/rfc/rfc2474.txt">RFC 2474</a>. The value + * of the socket option is a <em>hint</em>. An implementation may ignore the + * value, or ignore specific values. + * + * <p> The initial/default value of the TOS field in the ToS octet is + * implementation specific but will typically be {@code 0}. For + * datagram-oriented sockets the option may be configured at any time after + * the socket has been bound. The new value of the octet is used when sending + * subsequent datagrams. It is system dependent whether this option can be + * queried or changed prior to binding the socket. + * + * <p> The behavior of this socket option on a stream-oriented socket, or an + * {@link StandardProtocolFamily#INET6 IPv6} socket, is not defined in this + * release. + * + * @see DatagramSocket#setTrafficClass + */ + public static final SocketOption<Integer> IP_TOS = + new StdSocketOption<Integer>("IP_TOS", Integer.class); + + /** + * The network interface for Internet Protocol (IP) multicast datagrams. + * + * <p> The value of this socket option is a {@link NetworkInterface} that + * represents the outgoing interface for multicast datagrams sent by the + * datagram-oriented socket. For {@link StandardProtocolFamily#INET6 IPv6} + * sockets then it is system dependent whether setting this option also + * sets the outgoing interface for multlicast datagrams sent to IPv4 + * addresses. + * + * <p> The initial/default value of this socket option may be {@code null} + * to indicate that outgoing interface will be selected by the operating + * system, typically based on the network routing tables. An implementation + * allows this socket option to be set after the socket is bound. Whether + * the socket option can be queried or changed prior to binding the socket + * is system dependent. + * + * @see java.nio.channels.MulticastChannel + * @see MulticastSocket#setInterface + */ + public static final SocketOption<NetworkInterface> IP_MULTICAST_IF = + new StdSocketOption<NetworkInterface>("IP_MULTICAST_IF", NetworkInterface.class); + + /** + * The <em>time-to-live</em> for Internet Protocol (IP) multicast datagrams. + * + * <p> The value of this socket option is an {@code Integer} in the range + * <tt>0 <= value <= 255</tt>. It is used to control + * the scope of multicast datagrams sent by the datagram-oriented socket. + * In the case of an {@link StandardProtocolFamily#INET IPv4} socket + * the option is the time-to-live (TTL) on multicast datagrams sent by the + * socket. Datagrams with a TTL of zero are not transmitted on the network + * but may be delivered locally. In the case of an {@link + * StandardProtocolFamily#INET6 IPv6} socket the option is the + * <em>hop limit</em> which is number of <em>hops</em> that the datagram can + * pass through before expiring on the network. For IPv6 sockets it is + * system dependent whether the option also sets the <em>time-to-live</em> + * on multicast datagrams sent to IPv4 addresses. + * + * <p> The initial/default value of the time-to-live setting is typically + * {@code 1}. An implementation allows this socket option to be set after + * the socket is bound. Whether the socket option can be queried or changed + * prior to binding the socket is system dependent. + * + * @see java.nio.channels.MulticastChannel + * @see MulticastSocket#setTimeToLive + */ + public static final SocketOption<Integer> IP_MULTICAST_TTL = + new StdSocketOption<Integer>("IP_MULTICAST_TTL", Integer.class); + + /** + * Loopback for Internet Protocol (IP) multicast datagrams. + * + * <p> The value of this socket option is a {@code Boolean} that controls + * the <em>loopback</em> of multicast datagrams. The value of the socket + * option represents if the option is enabled or disabled. + * + * <p> The exact semantics of this socket options are system dependent. + * In particular, it is system dependent whether the loopback applies to + * multicast datagrams sent from the socket or received by the socket. + * For {@link StandardProtocolFamily#INET6 IPv6} sockets then it is + * system dependent whether the option also applies to multicast datagrams + * sent to IPv4 addresses. + * + * <p> The initial/default value of this socket option is {@code TRUE}. An + * implementation allows this socket option to be set after the socket is + * bound. Whether the socket option can be queried or changed prior to + * binding the socket is system dependent. + * + * @see java.nio.channels.MulticastChannel + * @see MulticastSocket#setLoopbackMode + */ + public static final SocketOption<Boolean> IP_MULTICAST_LOOP = + new StdSocketOption<Boolean>("IP_MULTICAST_LOOP", Boolean.class); + + + // -- IPPROTO_TCP -- + + /** + * Disable the Nagle algorithm. + * + * <p> The value of this socket option is a {@code Boolean} that represents + * whether the option is enabled or disabled. The socket option is specific to + * stream-oriented sockets using the TCP/IP protocol. TCP/IP uses an algorithm + * known as <em>The Nagle Algorithm</em> to coalesce short segments and + * improve network efficiency. + * + * <p> The default value of this socket option is {@code FALSE}. The + * socket option should only be enabled in cases where it is known that the + * coalescing impacts performance. The socket option may be enabled at any + * time. In other words, the Nagle Algorithm can be disabled. Once the option + * is enabled, it is system dependent whether it can be subsequently + * disabled. If it cannot, then invoking the {@code setOption} method to + * disable the option has no effect. + * + * @see <a href="http://www.ietf.org/rfc/rfc1122.txt">RFC 1122: + * Requirements for Internet Hosts -- Communication Layers</a> + * @see Socket#setTcpNoDelay + */ + public static final SocketOption<Boolean> TCP_NODELAY = + new StdSocketOption<Boolean>("TCP_NODELAY", Boolean.class); + + + private static class StdSocketOption<T> implements SocketOption<T> { + private final String name; + private final Class<T> type; + StdSocketOption(String name, Class<T> type) { + this.name = name; + this.type = type; + } + public String name() { return name; } + public Class<T> type() { return type; } + public String toString() { return name; } + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/AsynchronousByteChannel.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,206 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.channels; + +import java.nio.ByteBuffer; +import java.util.concurrent.Future; + +/** + * An asynchronous channel that can read and write bytes. + * + * <p> Some channels may not allow more than one read to be outstanding at any + * given time. If a thread invokes a read method before a previous read + * operation has completed then a {@link ReadPendingException} will be thrown. + * Similarly, if a write method is invoked before a previous write has completed + * then {@link WritePendingException} is thrown. Whether or not other kinds of + * I/O operations may proceed concurrently with a read operation depends upon + * the type of the channel. + * + * <p> Note that {@link java.nio.ByteBuffer ByteBuffers} are not safe for use by + * multiple concurrent threads. When a read or write operation is initiated then + * care must be taken to ensure that the buffer is not accessed until the + * operation completes. + * + * @see Channels#newInputStream(AsynchronousByteChannel) + * @see Channels#newOutputStream(AsynchronousByteChannel) + * + * @since 1.7 + */ + +public interface AsynchronousByteChannel + extends AsynchronousChannel +{ + /** + * Reads a sequence of bytes from this channel into the given buffer. + * + * <p> This method initiates an operation to read a sequence of bytes from + * this channel into the given buffer. The method returns a {@link Future} + * representing the pending result of the operation. The result of the + * operation, obtained by invoking the {@code Future} 's {@link + * Future#get() get} method, is the number of bytes read or {@code -1} if + * all bytes have been read and the channel has reached end-of-stream. + * + * <p> This method initiates a read operation to read up to <i>r</i> bytes + * from the channel, where <i>r</i> is the number of bytes remaining in the + * buffer, that is, {@code dst.remaining()} at the time that the read is + * attempted. Where <i>r</i> is 0, the read operation completes immediately + * with a result of {@code 0} without initiating an I/O operation. + * + * <p> Suppose that a byte sequence of length <i>n</i> is read, where + * <tt>0</tt> <tt><</tt> <i>n</i> <tt><=</tt> <i>r</i>. + * This byte sequence will be transferred into the buffer so that the first + * byte in the sequence is at index <i>p</i> and the last byte is at index + * <i>p</i> <tt>+</tt> <i>n</i> <tt>-</tt> <tt>1</tt>, + * where <i>p</i> is the buffer's position at the moment the read is + * performed. Upon completion the buffer's position will be equal to + * <i>p</i> <tt>+</tt> <i>n</i>; its limit will not have changed. + * + * <p> Buffers are not safe for use by multiple concurrent threads so care + * should be taken to not to access the buffer until the operaton has completed. + * + * <p> This method may be invoked at any time. Some channel types may not + * allow more than one read to be outstanding at any given time. If a thread + * initiates a read operation before a previous read operation has + * completed then a {@link ReadPendingException} will be thrown. + * + * <p> The <tt>handler</tt> parameter is used to specify a {@link + * CompletionHandler}. When the read operation completes the handler's + * {@link CompletionHandler#completed completed} method is executed. + * + * + * @param dst + * The buffer into which bytes are to be transferred + * @param attachment + * The object to attach to the I/O operation; can be {@code null} + * @param handler + * The completion handler object; can be {@code null} + * + * @return A Future representing the result of the operation + * + * @throws IllegalArgumentException + * If the buffer is read-only + * @throws ReadPendingException + * If the channel does not allow more than one read to be outstanding + * and a previous read has not completed + */ + <A> Future<Integer> read(ByteBuffer dst, + A attachment, + CompletionHandler<Integer,? super A> handler); + + /** + * Reads a sequence of bytes from this channel into the given buffer. + * + * <p> An invocation of this method of the form <tt>c.read(dst)</tt> + * behaves in exactly the same manner as the invocation + * <blockquote><pre> + * c.read(dst, null, null);</pre></blockquote> + * + * @param dst + * The buffer into which bytes are to be transferred + * + * @return A Future representing the result of the operation + * + * @throws IllegalArgumentException + * If the buffer is read-only + * @throws ReadPendingException + * If the channel does not allow more than one read to be outstanding + * and a previous read has not completed + */ + Future<Integer> read(ByteBuffer dst); + + /** + * Writes a sequence of bytes to this channel from the given buffer. + * + * <p> This method initiates an operation to write a sequence of bytes to + * this channel from the given buffer. This method returns a {@link + * Future} representing the pending result of the operation. The result + * of the operation, obtained by invoking the <tt>Future</tt>'s {@link + * Future#get() get} method, is the number of bytes written, possibly zero. + * + * <p> This method initiates a write operation to write up to <i>r</i> bytes + * to the channel, where <i>r</i> is the number of bytes remaining in the + * buffer, that is, {@code src.remaining()} at the moment the write is + * attempted. Where <i>r</i> is 0, the write operation completes immediately + * with a result of {@code 0} without initiating an I/O operation. + * + * <p> Suppose that a byte sequence of length <i>n</i> is written, where + * <tt>0</tt> <tt><</tt> <i>n</i> <tt><=</tt> <i>r</i>. + * This byte sequence will be transferred from the buffer starting at index + * <i>p</i>, where <i>p</i> is the buffer's position at the moment the + * write is performed; the index of the last byte written will be + * <i>p</i> <tt>+</tt> <i>n</i> <tt>-</tt> <tt>1</tt>. + * Upon completion the buffer's position will be equal to + * <i>p</i> <tt>+</tt> <i>n</i>; its limit will not have changed. + * + * <p> Buffers are not safe for use by multiple concurrent threads so care + * should be taken to not to access the buffer until the operaton has completed. + * + * <p> This method may be invoked at any time. Some channel types may not + * allow more than one write to be outstanding at any given time. If a thread + * initiates a write operation before a previous write operation has + * completed then a {@link WritePendingException} will be thrown. + * + * <p> The <tt>handler</tt> parameter is used to specify a {@link + * CompletionHandler}. When the write operation completes the handler's + * {@link CompletionHandler#completed completed} method is executed. + * + * @param src + * The buffer from which bytes are to be retrieved + * @param attachment + * The object to attach to the I/O operation; can be {@code null} + * @param handler + * The completion handler object; can be {@code null} + * + * @return A Future representing the result of the operation + * + * @throws WritePendingException + * If the channel does not allow more than one write to be outstanding + * and a previous write has not completed + */ + <A> Future<Integer> write(ByteBuffer src, + A attachment, + CompletionHandler<Integer,? super A> handler); + + /** + * Writes a sequence of bytes to this channel from the given buffer. + * + * <p> An invocation of this method of the form <tt>c.write(src)</tt> + * behaves in exactly the same manner as the invocation + * <blockquote><pre> + * c.write(src, null, null);</pre></blockquote> + * + * @param src + * The buffer from which bytes are to be retrieved + * + * @return A Future representing the result of the operation + * + * @throws WritePendingException + * If the channel does not allow more than one write to be outstanding + * and a previous write has not completed + */ + Future<Integer> write(ByteBuffer src); +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/AsynchronousChannel.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,118 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.channels; + +import java.io.IOException; +import java.nio.channels.Channel; +import java.util.concurrent.Future; // javadoc + +/** + * A channel that supports asynchronous I/O operations. Asynchronous I/O + * operations will usually take one of two forms: + * + * <ol> + * <li><pre>{@link Future}<V> <em>operation</em>(<em>...</em>)</pre></li> + * <li><pre>Future<V> <em>operation</em>(<em>...</em> A attachment, {@link CompletionHandler}<V,? super A> handler)</pre></li> + * </ol> + * + * where <i>operation</i> is the name of the I/O operation (read or write for + * example), <i>V</i> is the result type of the I/O operation, and <i>A</i> is + * the type of an object attached to the I/O operation to provide context when + * consuming the result. The attachment is important for cases where a + * <em>state-less</em> {@code CompletionHandler} is used to consume the result + * of many I/O operations. + * + * <p> In the first form, the methods defined by the {@link Future Future} + * interface may be used to check if the operation has completed, wait for its + * completion, and to retrieve the result. In the second form, a {@link + * CompletionHandler} is invoked to consume the result of the I/O operation when + * it completes, fails, or is cancelled. + * + * <p> A channel that implements this interface is <em>asynchronously + * closeable</em>: If an I/O operation is outstanding on the channel and the + * channel's {@link #close close} method is invoked, then the I/O operation + * fails with the exception {@link AsynchronousCloseException}. + * + * <p> Asynchronous channels are safe for use by multiple concurrent threads. + * Some channel implementations may support concurrent reading and writing, but + * may not allow more than one read and one write operation to be outstanding at + * any given time. + * + * <h4>Cancellation</h4> + * + * <p> The {@code Future} interface defines the {@link Future#cancel cancel} + * method to cancel execution of a task. + * + * <p> Where the {@code cancel} method is invoked with the {@code + * mayInterruptIfRunning} parameter set to {@code true} then the I/O operation + * may be interrupted by closing the channel. This will cause any other I/O + * operations outstanding on the channel to complete with the exception {@link + * AsynchronousCloseException}. + * + * <p> If a {@code CompletionHandler} is specified when initiating an I/O + * operation, and the {@code cancel} method is invoked to cancel the I/O + * operation before it completes, then the {@code CompletionHandler}'s {@link + * CompletionHandler#cancelled cancelled} method is invoked. + * + * <p> If an implementation of this interface supports a means to cancel I/O + * operations, and where cancellation may leave the channel, or the entity to + * which it is connected, in an inconsistent state, then the channel is put into + * an implementation specific <em>error state</em> that prevents further + * attempts to initiate I/O operations on the channel. For example, if a read + * operation is cancelled but the implementation cannot guarantee that bytes + * have not been read from the channel then it puts the channel into error state + * state; further attempts to initiate a {@code read} operation causes an + * unspecified runtime exception to be thrown. + * + * <p> Where the {@code cancel} method is invoked to cancel read or write + * operations then it recommended that all buffers used in the I/O operations be + * discarded or care taken to ensure that the buffers are not accessed while the + * channel remains open. + * + * @since 1.7 + */ + +public interface AsynchronousChannel + extends Channel +{ + /** + * Closes this channel. + * + * <p> Any outstanding asynchronous operations upon this channel will + * complete with the exception {@link AsynchronousCloseException}. After a + * channel is closed then further attempts to initiate asynchronous I/O + * operations complete immediately with cause {@link ClosedChannelException}. + * + * <p> This method otherwise behaves exactly as specified by the {@link + * Channel} interface. + * + * @throws IOException + * If an I/O error occurs + */ + + void close() throws IOException; +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/AsynchronousChannelGroup.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,317 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.channels; + +import java.io.IOException; +import java.util.concurrent.*; + +import org.classpath.icedtea.java.nio.channels.spi.AsynchronousChannelProvider; + +/** + * A grouping of asynchronous channels for the purpose of resource sharing. + * + * <p> An asynchronous channel group encapsulates the mechanics required to + * handle the completion of I/O operations initiated by {@link AsynchronousChannel + * asynchronous channels} that are bound to the group. A group has an associated + * thread pool to which tasks are submitted to handle I/O events and dispatch to + * {@link CompletionHandler completion-handlers} that consume the result of + * asynchronous operations performed on channels in the group. In addition to + * handling I/O events, the pooled threads may also execute other tasks required + * to support the execution of asynchronous I/O operations. + * + * <p> An asynchronous channel group is created by invoking the {@link + * #withFixedThreadPool withFixedThreadPool} or {@link #withCachedThreadPool + * withCachedThreadPool} methods with the appropriate thread pool. Channels are + * bound to a group by specifying the group when constructing the channel. The + * group <em>takes ownership</em> of the thread pool; termination of the group + * results in the shutdown of the thread pool. + * + * <p> In addition to groups created explicitly, the Java virtual machine + * maintains a system-wide <em>default group</em> that is constructed + * automatically. Asynchronous channels that do not specify a group at + * construction time are bound to the default group. The default group has an + * associated thread pool that creates new threads as needed. The default group + * may be configured by means of system properties defined in the table below. + * Where the {@link java.util.concurrent.ThreadFactory ThreadFactory} for the + * default group is not configured then the pooled threads of the default group + * are {@link Thread#isDaemon daemon} threads. + * + * <table border> + * <tr> + * <th>System property</th> + * <th>Description</th> + * </tr> + * <tr> + * <tr> + * <td> {@code java.nio.channels.DefaultThreadPool.threadFactory} </td> + * <td> The value of this property is taken to be the fully-qualified name + * of a concrete {@link java.util.concurrent.ThreadFactory ThreadFactory} + * class. The class is loaded using the system class loader and instantiated. + * The factory's {@link java.util.concurrent.ThreadFactory#newThread + * newThread} method is invoked to create each thread for the default + * group's thread pool. If the process to load and instantiate the value + * of the property fails then an unspecified error is thrown during the + * construction of the default group. </td> + * </tr> + * <tr> + * <td> {@code java.nio.channels.DefaultThreadPool.initialSize} </td> + * <td> The value of the {@code initialSize} parameter for the default + * group (see {@link #withCachedThreadPool withCachedThreadPool}). + * The value of the property is taken to be the {@code String} + * representation of an {@code Integer} that is the initial size parameter. + * If the value cannot be parsed as an {@code Integer} it causes an + * unspecified error to be thrown during the construction of the default + * group. </td> + * </tr> + * </table> + * + * <a name="threading"><h4>Threading</h4></a> + * + * <p> The completion handler for an I/O operation initiated on a channel bound + * to a group is guaranteed to be invoked by one of the pooled threads in the + * group. This ensures that the completion handler is run by a thread with the + * expected <em>identity</em>. + * + * <p> Where an I/O operation completes immediately, and the initiating thread + * is one of the pooled threads in the group then the completion handler may + * be invoked directly by the initiating thread. To avoid stack overflow, an + * implementation may impose a limit as to the number of activations on the + * thread stack. Some I/O operations may prohibit invoking the completion + * handler directly by the initiating thread (see {@link + * AsynchronousServerSocketChannel#accept(Object,CompletionHandler) accept}). + * + * <a name="shutdown"><h4>Shutdown and Termination</h4></a> + * + * <p> The {@link #shutdown() shutdown} method is used to initiate an <em>orderly + * shutdown</em> of the group. An orderly shutdown marks the group as shutdown; + * further attempts to construct a channel that binds to the group will throw + * {@link ShutdownChannelGroupException}. Whether or not a group is shutdown can + * be tested using the {@link #isShutdown() isShutdown} method. Once shutdown, a + * group <em>terminates</em> when all asynchronous channels that are bound to the + * group are closed, all actively executing completion handlers have run to + * completion, and resources used by the group are released. No attempt is made + * to stop or interrupt threads that are executing completion handlers. The + * {@link #isTerminated() isTerminated} method is used to test if the group has + * terminated, and the {@link #awaitTermination awaitTermination} method can be + * used to block until the group has terminated. + * + * <p> The {@link #shutdownNow() shutdownNow} method can be used to initiate a + * <em>forceful shutdown</em> of the group. In addition to the actions performed + * by an orderly shutdown, the {@code shutdownNow} method closes all open channels + * in the group as if by invoking the {@link AsynchronousChannel#close close} + * method. + * + * @since 1.7 + * + * @see AsynchronousSocketChannel#open + * @see AsynchronousServerSocketChannel#open + */ + +public abstract class AsynchronousChannelGroup { + private final AsynchronousChannelProvider provider; + + /** + * Initialize a new instance of this class. + * + * @param provider + * The asynchronous channel provider for this group + */ + protected AsynchronousChannelGroup(AsynchronousChannelProvider provider) { + this.provider = provider; + } + + /** + * Returns the provider that created this channel group. + * + * @return The provider that created this channel group + */ + public final AsynchronousChannelProvider provider() { + return provider; + } + + /** + * Creates an asynchronous channel group with a fixed thread pool. + * + * <p> The {@code executor} parameter is an {@code ExecutorService} that + * reuses a fixed number of threads operating off a shared unbounded queue. + * At any point, at most {@code nThreads} threads will be active processing + * tasks that are submitted to handle I/O events and dispatch completion + * results for operations initiated on asynchronous channels in the group. + * + * <p> The executor is intended to be used for the exclusive use of the + * resulting asynchronous channel group. Adjusting the maximum allowed + * number of threads or other policy parameters after the channel group is + * created is not recommended. Termination of the group results in the orderly + * {@link ExecutorService#shutdown shutdown} of the executor service. + * Shutting down the executor service by other means results in unspecified + * behavior. + * + * <p> The group is created by invoking the {@link + * AsynchronousChannelProvider#openAsynchronousChannelGroup + * openAsynchronousChannelGroup} method of the system-wide default {@link + * AsynchronousChannelProvider} object. + * + * @param executor + * The thread pool for the resulting group + * @param nThreads + * The number of threads in the pool + * + * @return A new asynchronous channel group + * + * @throws IllegalArgumentException + * If {@code nThreads <= 0} + * @throws IOException + * If an I/O error occurs + * + * @see Executors#newFixedThreadPool + */ + public static AsynchronousChannelGroup withFixedThreadPool(ExecutorService executor, + int nThreads) + throws IOException + { + return AsynchronousChannelProvider.provider() + .openAsynchronousChannelGroup(AsynchronousChannelProvider.ThreadPoolType.FIXED, + executor, + nThreads); + } + + /** + * Creates an asynchronous channel group that creates new threads as needed. + * + * <p> The {@code executor} parameter is an {@code ExecutorService} that + * creates new threads as needed to execute tasks that are submitted to + * handle I/O events and dispatch completion results for operations initiated + * on asynchronous channels in the group. It may reuse previously constructed + * threads when they are available. + * + * <p> The {@code initialSize} parameter may be used by the implementation + * as a <em>hint</em> as to the initial number of tasks it may submit. For + * example, it may be used to indictae the initial number of threads that + * wait on I/O events. + * + * <p> The executor is intended to be used for the exclusive use of the + * resulting asynchronous channel group. Termination of the group results in + * the orderly {@link ExecutorService#shutdown shutdown} of the executor + * service. Shutting down the executor service by other means results in + * unspecified behavior. + * + * <p> The group is created by invoking the {@link + * AsynchronousChannelProvider#openAsynchronousChannelGroup + * openAsynchronousChannelGroup} method of the system-wide default {@link + * AsynchronousChannelProvider} object. + * + * @param executor + * The thread pool for the resulting group + * @param initialSize + * A value {@code >=0} or a negative value for implementation + * specific default + * + * @return A new asynchronous channel group + * + * @throws IOException + * If an I/O error occurs + * + * @see Executors#newCachedThreadPool + */ + public static AsynchronousChannelGroup withCachedThreadPool(ExecutorService executor, + int initialSize) + throws IOException + { + return AsynchronousChannelProvider.provider() + .openAsynchronousChannelGroup(AsynchronousChannelProvider.ThreadPoolType.CACHED, + executor, + initialSize); + } + + /** + * Tells whether or not this asynchronous channel group is shutdown. + * + * @return {@code true} if this asynchronous channel group is shutdown or + * has been marked for shutdown. + */ + public abstract boolean isShutdown(); + + /** + * Tells whether or not this group has terminated. + * + * <p> Where this method returns {@code true}, then the associated has + * also {@link ExecutorService#isTerminated terminated}. + * + * @return {@code true} if this group has terminated + */ + public abstract boolean isTerminated(); + + /** + * Initiates an orderly shutdown of the group. + * + * <p> This method marks the group as shutdown. Further attempts to construct + * channel that binds to this group will throw {@link ShutdownChannelGroupException}. + * The group terminates when all asynchronous channels in the group are + * closed, all actively executing completion handlers have run to completion, + * and all resources have been released. This method has no effect if the + * group is already shutdown. + */ + public abstract void shutdown(); + + /** + * Shuts down the group and closes all open channels in the group. + * + * <p> In addition to the actions performed by the {@link #shutdown() shutdown} + * method, this method invokes the {@link AsynchronousChannel#close close} + * method on all open channels in the group. This method does not attempt to + * stop or interrupt threads that are executing completion handlers. The + * group terminates when all actively executing completion handlers have run + * to completion and all resources have been released. This method may be + * invoked at any time. If some other thread has already invoked it, then + * another invocation will block until the first invocation is complete, + * after which it will return without effect. + * + * @throws IOException + * If an I/O error occurs + */ + public abstract void shutdownNow() throws IOException; + + /** + * Awaits termination of the group. + + * <p> This method blocks until the group has terminated, or the timeout + * occurs, or the current thread is interrupted, whichever happens first. + * + * @param timeout + * The maximum time to wait, or zero or less to not wait + * @param unit + * The time unit of the timeout argument + * + * @return {@code true} if the group has terminated; {@code false} if the + * timeout elapsed before termination + * + * @throws InterruptedException + * If interrupted while waiting + */ + public abstract boolean awaitTermination(long timeout, TimeUnit unit) + throws InterruptedException; +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/AsynchronousDatagramChannel.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,707 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.channels; + +import java.util.concurrent.TimeUnit; +import java.util.concurrent.Future; +import java.io.IOException; +import java.net.SocketAddress; +import java.nio.ByteBuffer; + +import org.classpath.icedtea.java.net.ProtocolFamily; +import org.classpath.icedtea.java.net.SocketOption; + +import org.classpath.icedtea.java.nio.channels.spi.AsynchronousChannelProvider; + +/** + * An asynchronous channel for datagram-oriented sockets. + * + * <p> An asynchronous datagram channel is created by invoking one of the {@link + * #open open} methods defined by this class. It is not possible to create a channel + * for an arbitrary, pre-existing datagram socket. A newly-created asynchronous + * datagram channel is open but not connected. It need not be connected in order + * for the {@link #send send} and {@link #receive receive} methods to be used. + * A datagram channel may be connected, by invoking its {@link #connect connect} + * method, in order to avoid the overhead of the security checks that are otherwise + * performed as part of every send and receive operation when a security manager + * is set. The channel must be connected in order to use the {@link #read read} + * and {@link #write write} methods, since those methods do not accept or return + * socket addresses. Once connected, an asynchronous datagram channel remains + * connected until it is disconnected or closed. + * + * <p> Socket options are configured using the {@link #setOption(SocketOption,Object) + * setOption} method. An asynchronous datagram channel to an Internet Protocol + * (IP) socket supports the following options: + * <blockquote> + * <table border> + * <tr> + * <th>Option Name</th> + * <th>Description</th> + * </tr> + * <tr> + * <td> {@link java.net.StandardSocketOption#SO_SNDBUF SO_SNDBUF} </td> + * <td> The size of the socket send buffer </td> + * </tr> + * <tr> + * <td> {@link java.net.StandardSocketOption#SO_RCVBUF SO_RCVBUF} </td> + * <td> The size of the socket receive buffer </td> + * </tr> + * <tr> + * <td> {@link java.net.StandardSocketOption#SO_REUSEADDR SO_REUSEADDR} </td> + * <td> Re-use address </td> + * </tr> + * <tr> + * <td> {@link java.net.StandardSocketOption#SO_BROADCAST SO_BROADCAST} </td> + * <td> Allow transmission of broadcast datagrams </td> + * </tr> + * <tr> + * <td> {@link java.net.StandardSocketOption#IP_TOS IP_TOS} </td> + * <td> The Type of Service (ToS) octet in the Internet Protocol (IP) header </td> + * </tr> + * <tr> + * <td> {@link java.net.StandardSocketOption#IP_MULTICAST_IF IP_MULTICAST_IF} </td> + * <td> The network interface for Internet Protocol (IP) multicast datagrams </td> + * </tr> + * <tr> + * <td> {@link java.net.StandardSocketOption#IP_MULTICAST_TTL + * IP_MULTICAST_TTL} </td> + * <td> The <em>time-to-live</em> for Internet Protocol (IP) multicast + * datagrams </td> + * </tr> + * <tr> + * <td> {@link java.net.StandardSocketOption#IP_MULTICAST_LOOP + * IP_MULTICAST_LOOP} </td> + * <td> Loopback for Internet Protocol (IP) multicast datagrams </td> + * </tr> + * </table> + * </blockquote> + * Additional (implementation specific) options may also be supported. + * + * <p> <b>Usage Example:</b> + * <pre> + * final AsynchronousDatagramChannel dc = AsynchronousDatagramChannel.open() + * .bind(new InetSocketAddress(4000)); + * + * // print the source address of all packets that we receive + * dc.receive(buffer, buffer, new CompletionHandler<SocketAddress,ByteBuffer>() { + * public void completed(SocketAddress sa, ByteBuffer buffer) { + * try { + * System.out.println(sa); + * + * buffer.clear(); + * dc.receive(buffer, buffer, this); + * } catch (...) { ... } + * } + * public void failed(Throwable exc, ByteBuffer buffer) { + * ... + * } + * public void cancelled(ByteBuffer buffer) { + * ... + * } + * }); + * </pre> + * + * @since 1.7 + */ + +public abstract class AsynchronousDatagramChannel + implements AsynchronousByteChannel, MulticastChannel +{ + private final AsynchronousChannelProvider provider; + + /** + * Initializes a new instance of this class. + */ + protected AsynchronousDatagramChannel(AsynchronousChannelProvider provider) { + this.provider = provider; + } + + /** + * Returns the provider that created this channel. + */ + public final AsynchronousChannelProvider provider() { + return provider; + } + + /** + * Opens an asynchronous datagram channel. + * + * <p> The new channel is created by invoking the {@link + * java.nio.channels.spi.AsynchronousChannelProvider#openAsynchronousDatagramChannel + * openAsynchronousDatagramChannel} method on the {@link + * java.nio.channels.spi.AsynchronousChannelProvider} object that created + * the given group. If the group parameter is <tt>null</tt> then the + * resulting channel is created by the system-wide default provider, and + * bound to the <em>default group</em>. + * + * <p> The <tt>family</tt> parameter is used to specify the {@link ProtocolFamily}. + * If the datagram channel is to be used for Internet Protocol {@link + * MulticastChannel multicasting} then this parameter should correspond to + * the address type of the multicast groups that this channel will join. + * + * @param family + * The protocol family, or <tt>null</tt> to use the default protocol + * family + * @param group + * The group to which the newly constructed channel should be bound, + * or <tt>null</tt> for the default group + * + * @return A new asynchronous datagram channel + * + * @throws UnsupportedOperationException + * If the specified protocol family is not supported. For example, + * suppose the parameter is specified as {@link + * java.net.StandardProtocolFamily#INET6 INET6} but IPv6 is not + * enabled on the platform. + * @throws ShutdownChannelGroupException + * The specified group is shutdown + * @throws IOException + * If an I/O error occurs + */ + public static AsynchronousDatagramChannel open(ProtocolFamily family, + AsynchronousChannelGroup group) + throws IOException + { + AsynchronousChannelProvider provider = (group == null) ? + AsynchronousChannelProvider.provider() : group.provider(); + return provider.openAsynchronousDatagramChannel(family, group); + } + + /** + * Opens an asynchronous datagram channel. + * + * <p> This method returns an asynchronous datagram channel that is + * bound to the <em>default group</em>. This method is equivalent to evaluating + * the expression: + * <blockquote><pre> + * open((ProtocolFamily)null, (AsynchronousChannelGroup)null); + * </pre></blockquote> + * + * @return A new asynchronous datagram channel + * + * @throws IOException + * If an I/O error occurs + */ + public static AsynchronousDatagramChannel open() + throws IOException + { + return open(null, null); + } + + // -- Socket-specific operations -- + + /** + * @throws AlreadyBoundException {@inheritDoc} + * @throws UnsupportedAddressTypeException {@inheritDoc} + * @throws ClosedChannelException {@inheritDoc} + * @throws IOException {@inheritDoc} + * @throws SecurityException + * If a security manager has been installed and its {@link + * SecurityManager#checkListen checkListen} method denies the + * operation + */ + + public abstract AsynchronousDatagramChannel bind(SocketAddress local) + throws IOException; + + /** + * @throws IllegalArgumentException {@inheritDoc} + * @throws ClosedChannelException {@inheritDoc} + * @throws IOException {@inheritDoc} + */ + + public abstract <T> AsynchronousDatagramChannel setOption(SocketOption<T> name, T value) + throws IOException; + + /** + * Returns the remote address to which this channel is connected. + * + * <p> Where the channel is connected to an Internet Protocol socket address + * then the return value from this method is of type {@link + * java.net.InetSocketAddress}. + * + * @return The remote address; {@code null} if the channel's socket is not + * connected + * + * @throws ClosedChannelException + * If the channel is closed + * @throws IOException + * If an I/O error occurs + */ + public abstract SocketAddress getRemoteAddress() throws IOException; + + /** + * Connects this channel's socket. + * + * <p> The channel's socket is configured so that it only receives + * datagrams from, and sends datagrams to, the given remote <i>peer</i> + * address. Once connected, datagrams may not be received from or sent to + * any other address. A datagram socket remains connected until it is + * explicitly disconnected or until it is closed. + * + * <p> This method performs exactly the same security checks as the {@link + * java.net.DatagramSocket#connect connect} method of the {@link + * java.net.DatagramSocket} class. That is, if a security manager has been + * installed then this method verifies that its {@link + * java.lang.SecurityManager#checkAccept checkAccept} and {@link + * java.lang.SecurityManager#checkConnect checkConnect} methods permit + * datagrams to be received from and sent to, respectively, the given + * remote address. + * + * <p> This method may be invoked at any time. Whether it has any effect + * on outstanding read or write operations is implementation specific and + * therefore not specified. + * + * @param remote + * The remote address to which this channel is to be connected + * + * @return This datagram channel + * + * @throws ClosedChannelException + * If this channel is closed + * + * @throws SecurityException + * If a security manager has been installed + * and it does not permit access to the given remote address + * + * @throws IOException + * If some other I/O error occurs + */ + public abstract AsynchronousDatagramChannel connect(SocketAddress remote) + throws IOException; + + /** + * Disconnects this channel's socket. + * + * <p> The channel's socket is configured so that it can receive datagrams + * from, and sends datagrams to, any remote address so long as the security + * manager, if installed, permits it. + * + * <p> This method may be invoked at any time. It will not have any effect + * on read or write operations that are already in progress at the moment + * that it is invoked. + * + * <p> This method may be invoked at any time. Whether it has any effect + * on outstanding read or write operations is implementation specific and + * therefore not specified. + * + * @return This datagram channel + * + * @throws IOException + * If some other I/O error occurs + */ + public abstract AsynchronousDatagramChannel disconnect() throws IOException; + + /** + * Receives a datagram via this channel. + * + * <p> This method initiates the receiving of a datagram, returning a + * <tt>Future</tt> representing the pending result of the operation. + * The <tt>Future</tt>'s {@link Future#get() get} method returns + * the source address of the datagram upon successful completion. + * + * <p> The datagram is transferred into the given byte buffer starting at + * its current position, as if by a regular {@link AsynchronousByteChannel#read + * read} operation. If there are fewer bytes remaining in the buffer + * than are required to hold the datagram then the remainder of the datagram + * is silently discarded. + * + * <p> If a timeout is specified and the timeout elapses before the operation + * completes then the operation completes with the exception {@link + * InterruptedByTimeoutException}. + * + * <p> When a security manager has been installed and the channel is not + * connected, then it verifies that the source's address and port number are + * permitted by the security manager's {@link SecurityManager#checkAccept + * checkAccept} method. The permission check is performed with privileges that + * are restricted by the calling context of this method. If the permission + * check fails then the operation completes with a {@link SecurityException}. + * The overhead of this security check can be avoided by first connecting the + * socket via the {@link #connect connect} method. + * + * @param dst + * The buffer into which the datagram is to be transferred + * @param timeout + * The timeout, or <tt>0L</tt> for no timeout + * @param unit + * The time unit of the <tt>timeout</tt> argument + * @param attachment + * The object to attach to the I/O operation; can be {@code null} + * @param handler + * The handler for consuming the result; can be {@code null} + * + * @return a <tt>Future</tt> object representing the pending result + * + * @throws IllegalArgumentException + * If the timeout is negative or the buffer is read-only + * @throws ShutdownChannelGroupException + * If a handler is specified, and the channel group is shutdown + */ + public abstract <A> Future<SocketAddress> receive(ByteBuffer dst, + long timeout, + TimeUnit unit, + A attachment, + CompletionHandler<SocketAddress,? super A> handler); + + /** + * Receives a datagram via this channel. + * + * <p> This method initiates the receiving of a datagram, returning a + * <tt>Future</tt> representing the pending result of the operation. + * The <tt>Future</tt>'s {@link Future#get() get} method returns + * the source address of the datagram upon successful completion. + * + * <p> This method is equivalent to invoking {@link + * #receive(ByteBuffer,long,TimeUnit,Object,CompletionHandler)} with a + * timeout of <tt>0L</tt>. + * + * @param dst + * The buffer into which the datagram is to be transferred + * @param attachment + * The object to attach to the I/O operation; can be {@code null} + * @param handler + * The handler for consuming the result; can be {@code null} + * + * @return a <tt>Future</tt> object representing the pending result + * + * @throws IllegalArgumentException + * If the buffer is read-only + * @throws ShutdownChannelGroupException + * If a handler is specified, and the channel group is shutdown + */ + public final <A> Future<SocketAddress> receive(ByteBuffer dst, + A attachment, + CompletionHandler<SocketAddress,? super A> handler) + { + return receive(dst, 0L, TimeUnit.MILLISECONDS, attachment, handler); + } + + /** + * Receives a datagram via this channel. + * + * <p> This method initiates the receiving of a datagram, returning a + * <tt>Future</tt> representing the pending result of the operation. + * The <tt>Future</tt>'s {@link Future#get() get} method returns + * the source address of the datagram upon successful completion. + * + * <p> This method is equivalent to invoking {@link + * #receive(ByteBuffer,long,TimeUnit,Object,CompletionHandler)} with a + * timeout of {@code 0L}, and an attachment and completion handler + * of {@code null}. + * + * @param dst + * The buffer into which the datagram is to be transferred + * + * @return a <tt>Future</tt> object representing the pending result + * + * @throws IllegalArgumentException + * If the buffer is read-only + */ + public final <A> Future<SocketAddress> receive(ByteBuffer dst) { + return receive(dst, 0L, TimeUnit.MILLISECONDS, null, null); + } + + /** + * Sends a datagram via this channel. + * + * <p> This method initiates sending of a datagram, returning a + * <tt>Future</tt> representing the pending result of the operation. + * The operation sends the remaining bytes in the given buffer as a single + * datagram to the given target address. The result of the operation, obtained + * by invoking the <tt>Future</tt>'s {@link Future#get() get} + * method, is the number of bytes sent. + * + * <p> The datagram is transferred from the byte buffer as if by a regular + * {@link AsynchronousByteChannel#write write} operation. + * + * <p> If a timeout is specified and the timeout elapses before the operation + * completes then the operation completes with the exception {@link + * InterruptedByTimeoutException}. + * + * <p> If there is a security manager installed and the the channel is not + * connected then this method verifies that the target address and port number + * are permitted by the security manager's {@link SecurityManager#checkConnect + * checkConnect} method. The overhead of this security check can be avoided + * by first connecting the socket via the {@link #connect connect} method. + * + * @param src + * The buffer containing the datagram to be sent + * @param target + * The address to which the datagram is to be sent + * @param timeout + * The timeout, or <tt>0L</tt> for no timeout + * @param unit + * The time unit of the <tt>timeout</tt> argument + * @param attachment + * The object to attach to the I/O operation; can be {@code null} + * @param handler + * The handler for consuming the result; can be {@code null} + * + * @return a <tt>Future</tt> object representing the pending result + * + * @throws UnresolvedAddressException + * If the given remote address is not fully resolved + * @throws UnsupportedAddressTypeException + * If the type of the given remote address is not supported + * @throws IllegalArgumentException + * If the channel's socket is connected and is connected to an + * address that is not equal to {@code target} + * @throws SecurityException + * If a security manager has been installed and it does not permit + * datagrams to be sent to the given address + * @throws ShutdownChannelGroupException + * If a handler is specified, and the channel group is shutdown + */ + public abstract <A> Future<Integer> send(ByteBuffer src, + SocketAddress target, + long timeout, + TimeUnit unit, + A attachment, + CompletionHandler<Integer,? super A> handler); + + /** + * Sends a datagram via this channel. + * + * <p> This method initiates sending of a datagram, returning a + * <tt>Future</tt> representing the pending result of the operation. + * The operation sends the remaining bytes in the given buffer as a single + * datagram to the given target address. The result of the operation, obtained + * by invoking the <tt>Future</tt>'s {@link Future#get() get} + * method, is the number of bytes sent. + * + * <p> This method is equivalent to invoking {@link + * #send(ByteBuffer,SocketAddress,long,TimeUnit,Object,CompletionHandler)} + * with a timeout of <tt>0L</tt>. + * + * @param src + * The buffer containing the datagram to be sent + * @param target + * The address to which the datagram is to be sent + * @param attachment + * The object to attach to the I/O operation; can be {@code null} + * @param handler + * The handler for consuming the result; can be {@code null} + * + * @return a <tt>Future</tt> object representing the pending result + * + * @throws UnresolvedAddressException + * If the given remote address is not fully resolved + * @throws UnsupportedAddressTypeException + * If the type of the given remote address is not supported + * @throws IllegalArgumentException + * If the channel's socket is connected and is connected to an + * address that is not equal to {@code target} + * @throws SecurityException + * If a security manager has been installed and it does not permit + * datagrams to be sent to the given address + * @throws ShutdownChannelGroupException + * If a handler is specified, and the channel group is shutdown + */ + public final <A> Future<Integer> send(ByteBuffer src, + SocketAddress target, + A attachment, + CompletionHandler<Integer,? super A> handler) + { + return send(src, target, 0L, TimeUnit.MILLISECONDS, attachment, handler); + } + + /** + * Sends a datagram via this channel. + * + * <p> This method initiates sending of a datagram, returning a + * <tt>Future</tt> representing the pending result of the operation. + * The operation sends the remaining bytes in the given buffer as a single + * datagram to the given target address. The result of the operation, obtained + * by invoking the <tt>Future</tt>'s {@link Future#get() get} + * method, is the number of bytes sent. + * + * <p> This method is equivalent to invoking {@link + * #send(ByteBuffer,SocketAddress,long,TimeUnit,Object,CompletionHandler)} + * with a timeout of {@code 0L} and an attachment and completion handler + * of {@code null}. + * + * @param src + * The buffer containing the datagram to be sent + * @param target + * The address to which the datagram is to be sent + * + * @return a <tt>Future</tt> object representing the pending result + * + * @throws UnresolvedAddressException + * If the given remote address is not fully resolved + * @throws UnsupportedAddressTypeException + * If the type of the given remote address is not supported + * @throws IllegalArgumentException + * If the channel's socket is connected and is connected to an + * address that is not equal to {@code target} + * @throws SecurityException + * If a security manager has been installed and it does not permit + * datagrams to be sent to the given address + */ + public final Future<Integer> send(ByteBuffer src, SocketAddress target) { + return send(src, target, 0L, TimeUnit.MILLISECONDS, null, null); + } + + /** + * Receives a datagram via this channel. + * + * <p> This method initiates the receiving of a datagram, returning a + * <tt>Future</tt> representing the pending result of the operation. + * The <tt>Future</tt>'s {@link Future#get() get} method returns + * the number of bytes transferred upon successful completion. + * + * <p> This method may only be invoked if this channel is connected, and it + * only accepts datagrams from the peer that the channel is connected too. + * The datagram is transferred into the given byte buffer starting at + * its current position and exactly as specified in the {@link + * AsynchronousByteChannel} interface. If there are fewer bytes + * remaining in the buffer than are required to hold the datagram then the + * remainder of the datagram is silently discarded. + * + * <p> If a timeout is specified and the timeout elapses before the operation + * completes then the operation completes with the exception {@link + * InterruptedByTimeoutException}. + * + * @param dst + * The buffer into which the datagram is to be transferred + * @param timeout + * The timeout, or <tt>0L</tt> for no timeout + * @param unit + * The time unit of the <tt>timeout</tt> argument + * @param attachment + * The object to attach to the I/O operation; can be {@code null} + * @param handler + * The handler for consuming the result; can be {@code null} + * + * @return a <tt>Future</tt> object representing the pending result + * + * @throws IllegalArgumentException + * If the timeout is negative or buffer is read-only + * @throws NotYetConnectedException + * If this channel is not connected + * @throws ShutdownChannelGroupException + * If a handler is specified, and the channel group is shutdown + */ + public abstract <A> Future<Integer> read(ByteBuffer dst, + long timeout, + TimeUnit unit, + A attachment, + CompletionHandler<Integer,? super A> handler); + + /** + * @throws NotYetConnectedException + * If this channel is not connected + * @throws ShutdownChannelGroupException + * If a handler is specified, and the channel group is shutdown + */ + + public final <A> Future<Integer> read(ByteBuffer dst, + A attachment, + CompletionHandler<Integer,? super A> handler) + { + return read(dst, 0L, TimeUnit.MILLISECONDS, attachment, handler); + } + + /** + * @throws NotYetConnectedException + * If this channel is not connected + */ + + public final Future<Integer> read(ByteBuffer dst) { + return read(dst, 0L, TimeUnit.MILLISECONDS, null, null); + } + + /** + * Writes a datagram to this channel. + * + * <p> This method initiates sending of a datagram, returning a + * <tt>Future</tt> representing the pending result of the operation. + * The operation sends the remaining bytes in the given buffer as a single + * datagram. The result of the operation, obtained by invoking the + * <tt>Future</tt>'s {@link Future#get() get} method, is the + * number of bytes sent. + * + * <p> The datagram is transferred from the byte buffer as if by a regular + * {@link AsynchronousByteChannel#write write} operation. + * + * <p> This method may only be invoked if this channel is connected, + * in which case it sends datagrams directly to the socket's peer. Otherwise + * it behaves exactly as specified in the {@link + * AsynchronousByteChannel} interface. + * + * <p> If a timeout is specified and the timeout elapses before the operation + * completes then the operation completes with the exception {@link + * InterruptedByTimeoutException}. + * + * @param src + * The buffer containing the datagram to be sent + * @param timeout + * The timeout, or <tt>0L</tt> for no timeout + * @param unit + * The time unit of the <tt>timeout</tt> argument + * @param attachment + * The object to attach to the I/O operation; can be {@code null} + * @param handler + * The handler for consuming the result; can be {@code null} + * + * @return a <tt>Future</tt> object representing the pending result + * + * @throws IllegalArgumentException + * If the timeout is negative + * @throws NotYetConnectedException + * If this channel is not connected + * @throws ShutdownChannelGroupException + * If a handler is specified, and the channel group is shutdown + */ + public abstract <A> Future<Integer> write(ByteBuffer src, + long timeout, + TimeUnit unit, + A attachment, + CompletionHandler<Integer,? super A> handler); + /** + * @throws NotYetConnectedException + * If this channel is not connected + * @throws ShutdownChannelGroupException + * If a handler is specified, and the channel group is shutdown + */ + + public final <A> Future<Integer> write(ByteBuffer src, + A attachment, + CompletionHandler<Integer,? super A> handler) + { + return write(src, 0L, TimeUnit.MILLISECONDS, attachment, handler); + } + + /** + * @throws NotYetConnectedException + * If this channel is not connected + */ + + public final Future<Integer> write(ByteBuffer src) { + return write(src, 0L, TimeUnit.MILLISECONDS, null, null); + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/AsynchronousFileChannel.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,777 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.channels; + +import java.nio.ByteBuffer; +import java.io.IOException; +import java.util.concurrent.Future; +import java.util.concurrent.ExecutorService; +import java.util.Set; +import java.util.HashSet; +import java.util.Collections; + +import org.classpath.icedtea.java.nio.file.OpenOption; +import org.classpath.icedtea.java.nio.file.Path; +import org.classpath.icedtea.java.nio.file.attribute.FileAttribute; +import org.classpath.icedtea.java.nio.file.spi.FileSystemProvider; + +/** + * An asynchronous channel for reading, writing, and manipulating a file. + * + * <p> An asynchronous file channel is created when a file is opened by invoking + * one of the {@link #open open} methods defined by this class. The file contains + * a variable-length sequence of bytes that can be read and written and whose + * current size can be {@link #size() queried}. The size of the file increases + * when bytes are written beyond its current size; the size of the file decreases + * when it is {@link #truncate truncated}. + * + * <p> An asynchronous file channel does not have a <i>current position</i> + * within the file. Instead, the file position is specified to each read and + * write operation. + * + * <p> In addition to read and write operations, this class defines the + * following operations: </p> + * + * <ul> + * + * <li><p> Updates made to a file may be {@link #force <i>forced + * out</i>} to the underlying storage device, ensuring that data are not + * lost in the event of a system crash. </p></li> + * + * <li><p> A region of a file may be {@link FileLock <i>locked</i>} + * against access by other programs. </p></li> + * + * </ul> + * + * <p> The {@link #read read}, {@link #write write}, and {@link #lock lock} + * methods defined by this class are asynchronous and return a {@link Future} + * to represent the pending result of the operation. This may be used to check + * if the operation has completed, to wait for its completion, and to retrieve + * the result. These method may optionally specify a {@link CompletionHandler} + * that is invoked to consume the result of the I/O operation when it completes. + * + * <p> An {@code AsynchronousFileChannel} is associated with a thread pool to + * which tasks are submitted to handle I/O events and dispatch to completion + * handlers that consume the results of I/O operations on the channel. The + * completion handler for an I/O operation initiated on a channel is guaranteed + * to be invoked by one threads in the thread pool (This ensures that the + * completion handler is run by a thread with the expected <em>identity</em>). + * Where an I/O operation completes immediately, and the initiating thread is + * itself a thread in the thread pool, then the completion handler may be invoked + * directly by the initiating thread. When an {@code AsynchronousFileChannel} is + * created without specifying a thread pool then the channel is associated with + * a system-dependent and default thread pool that may be shared with other + * channels. The default thread pool is configured by the system properties + * defined by the {@link AsynchronousChannelGroup} class. + * + * <p> Channels of this type are safe for use by multiple concurrent threads. The + * {@link Channel#close close} method may be invoked at any time, as specified + * by the {@link Channel} interface. This causes all outstanding asynchronous + * operations on the channel to complete with the exception {@link + * AsynchronousCloseException}. Multiple read and write operations may be + * outstanding at the same time. When multiple read and write operations are + * outstanding then the ordering of the I/O operations, and the order that the + * completion handlers are invoked, is not specified; they are not, in particular, + * guaranteed to execute in the order that the operations were initiated. The + * {@link java.nio.ByteBuffer ByteBuffers} used when reading or writing are not + * safe for use by multiple concurrent I/O operations. Furthermore, after an I/O + * operation is initiated then care should be taken to ensure that the buffer is + * not accessed until after the operation has completed. + * + * <p> As with {@link FileChannel}, the view of a file provided by an instance of + * this class is guaranteed to be consistent with other views of the same file + * provided by other instances in the same program. The view provided by an + * instance of this class may or may not, however, be consistent with the views + * seen by other concurrently-running programs due to caching performed by the + * underlying operating system and delays induced by network-filesystem protocols. + * This is true regardless of the language in which these other programs are + * written, and whether they are running on the same machine or on some other + * machine. The exact nature of any such inconsistencies are system-dependent + * and are therefore unspecified. + * + * @since 1.7 + */ + +public abstract class AsynchronousFileChannel + implements AsynchronousChannel +{ + /** + * Initializes a new instance of this class. + */ + protected AsynchronousFileChannel() { + } + + /** + * Closes this channel. + * + * <p> If this channel is associated with its own thread pool then closing + * the channel causes the thread pool to shutdown after all actively + * executing completion handlers have completed. No attempt is made to stop + * or interrupt actively completion handlers. + * + * <p> This method otherwise behaves exactly as specified by the {@link + * AsynchronousChannel} interface. + * + * @throws IOException {@inheritDoc} + */ + + public abstract void close() throws IOException; + + /** + * Opens or creates a file for reading and/or writing, returning an + * asynchronous file channel to access the file. + * + * <p> The {@code options} parameter determines how the file is opened. + * The {@link StandardOpenOption#READ READ} and {@link StandardOpenOption#WRITE + * WRITE} options determines if the file should be opened for reading and/or + * writing. If neither option is contained in the array then an existing file + * is opened for reading. + * + * <p> In addition to {@code READ} and {@code WRITE}, the following options + * may be present: + * + * <table border=1 cellpadding=5 summary=""> + * <tr> <th>Option</th> <th>Description</th> </tr> + * <tr> + * <td> {@link StandardOpenOption#TRUNCATE_EXISTING TRUNCATE_EXISTING} </td> + * <td> When opening an existing file, the file is first truncated to a + * size of 0 bytes. This option is ignored when the file is opened only + * for reading.</td> + * </tr> + * <tr> + * <td> {@link StandardOpenOption#CREATE_NEW CREATE_NEW} </td> + * <td> If this option is present then a new file is created, failing if + * the file already exists. When creating a file the check for the + * existence of the file and the creation of the file if it does not exist + * is atomic with respect to other file system operations. This option is + * ignored when the file is opened only for reading. </td> + * </tr> + * <tr> + * <td > {@link StandardOpenOption#CREATE CREATE} </td> + * <td> If this option is present then an existing file is opened if it + * exists, otherwise a new file is created. When creating a file the check + * for the existence of the file and the creation of the file if it does + * not exist is atomic with respect to other file system operations. This + * option is ignored if the {@code CREATE_NEW} option is also present or + * the file is opened only for reading. </td> + * </tr> + * <tr> + * <td > {@link StandardOpenOption#DELETE_ON_CLOSE DELETE_ON_CLOSE} </td> + * <td> When this option is present then the implementation makes a + * <em>best effort</em> attempt to delete the file when closed by the + * the {@link #close close} method. If the {@code close} method is not + * invoked then a <em>best effort</em> attempt is made to delete the file + * when the Java virtual machine terminates. </td> + * </tr> + * <tr> + * <td>{@link StandardOpenOption#SPARSE SPARSE} </td> + * <td> When creating a new file this option is a <em>hint</em> that the + * new file will be sparse. This option is ignored when not creating + * a new file. </td> + * </tr> + * <tr> + * <td> {@link StandardOpenOption#SYNC SYNC} </td> + * <td> Requires that every update to the file's content or metadata be + * written synchronously to the underlying storage device. (see <a + * href="../file/package-summary.html#integrity"> Synchronized I/O file + * integrity</a>). </td> + * <tr> + * <tr> + * <td> {@link StandardOpenOption#DSYNC DSYNC} </td> + * <td> Requires that every update to the file's content be written + * synchronously to the underlying storage device. (see <a + * href="../file/package-summary.html#integrity"> Synchronized I/O file + * integrity</a>). </td> + * </tr> + * </table> + * + * <p> An implementation may also support additional options. + * + * <p> The {@code executor} parameter is the {@link ExecutorService} to + * which tasks are submitted to handle I/O events and dispatch completion + * results for operations initiated on resulting channel. + * The nature of these tasks is highly implementation specific and so care + * should be taken when configuring the {@code Executor}. Minimally it + * should support an unbounded work queue and should not run tasks on the + * caller thread of the {@link ExecutorService#execute execute} method. + * {@link #close Closing} the channel results in the orderly {@link + * ExecutorService#shutdown shutdown} of the executor service. Shutting down + * the executor service by other means results in unspecified behavior. + * + * <p> The {@code attrs} parameter is an optional array of file {@link + * FileAttribute file-attributes} to set atomically when creating the file. + * + * <p> The new channel is created by invoking the {@link + * FileSystemProvider#newFileChannel newFileChannel} method on the + * provider that created the {@code Path}. + * + * @param file + * The path of the file to open or create + * @param options + * Options specifying how the file is opened + * @param executor + * The thread pool or {@code null} to associate the channel with + * the default thread pool + * @param attrs + * An optional list of file attributes to set atomically when + * creating the file + * + * @return A new asynchronous file channel + * + * @throws IllegalArgumentException + * If the set contains an invalid combination of options + * @throws UnsupportedOperationException + * If the {@code file} is associated with a provider that does not + * support creating asynchronous file channels, or an unsupported + * open option is specified, or the array contains an attribute that + * cannot be set atomically when creating the file + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * If a security manager is installed and it denies an + * unspecified permission required by the implementation. + * In the case of the default provider, the {@link + * SecurityManager#checkRead(String)} method is invoked to check + * read access if the file is opened for reading. The {@link + * SecurityManager#checkWrite(String)} method is invoked to check + * write access if the file is opened for writing + */ + public static AsynchronousFileChannel open(Path file, + Set<? extends OpenOption> options, + ExecutorService executor, + FileAttribute<?>... attrs) + throws IOException + { + FileSystemProvider provider = file.getFileSystem().provider(); + return provider.newAsynchronousFileChannel(file, options, executor, attrs); + } + + private static final FileAttribute<?>[] NO_ATTRIBUTES = new FileAttribute[0]; + + /** + * Opens or creates a file for reading and/or writing, returning an + * asynchronous file channel to access the file. + * + * <p> An invocation of this method behaves in exactly the same way as the + * invocation + * <pre> + * ch.{@link #open(Path,Set,ExecutorService,FileAttribute[]) open}(file, opts, null, new FileAttribute<?>[0]); + * </pre> + * where {@code opts} is a {@code Set} containing the options specified to + * this method. + * + * <p> The resulting channel is associated with default thread pool to which + * tasks are submitted to handle I/O events and dispatch to completion + * handlers that consume the result of asynchronous operations performed on + * the resulting channel. + * + * @param file + * The path of the file to open or create + * @param options + * Options specifying how the file is opened + * + * @return A new asynchronous file channel + * + * @throws IllegalArgumentException + * If the set contains an invalid combination of options + * @throws UnsupportedOperationException + * If the {@code file} is associated with a provider that does not + * support creating file channels, or an unsupported open option is + * specified + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * If a security manager is installed and it denies an + * unspecified permission required by the implementation. + * In the case of the default provider, the {@link + * SecurityManager#checkRead(String)} method is invoked to check + * read access if the file is opened for reading. The {@link + * SecurityManager#checkWrite(String)} method is invoked to check + * write access if the file is opened for writing + */ + public static AsynchronousFileChannel open(Path file, OpenOption... options) + throws IOException + { + Set<OpenOption> set = new HashSet<OpenOption>(options.length); + Collections.addAll(set, options); + return open(file, set, null, NO_ATTRIBUTES); + } + + /** + * Returns the current size of this channel's file. + * + * @return The current size of this channel's file, measured in bytes + * + * @throws ClosedChannelException + * If this channel is closed + * @throws IOException + * If some other I/O error occurs + */ + public abstract long size() throws IOException; + + /** + * Truncates this channel's file to the given size. + * + * <p> If the given size is less than the file's current size then the file + * is truncated, discarding any bytes beyond the new end of the file. If + * the given size is greater than or equal to the file's current size then + * the file is not modified. </p> + * + * @param size + * The new size, a non-negative byte count + * + * @return This file channel + * + * @throws NonWritableChannelException + * If this channel was not opened for writing + * + * @throws ClosedChannelException + * If this channel is closed + * + * @throws IllegalArgumentException + * If the new size is negative + * + * @throws IOException + * If some other I/O error occurs + */ + public abstract AsynchronousFileChannel truncate(long size) throws IOException; + + /** + * Forces any updates to this channel's file to be written to the storage + * device that contains it. + * + * <p> If this channel's file resides on a local storage device then when + * this method returns it is guaranteed that all changes made to the file + * since this channel was created, or since this method was last invoked, + * will have been written to that device. This is useful for ensuring that + * critical information is not lost in the event of a system crash. + * + * <p> If the file does not reside on a local device then no such guarantee + * is made. + * + * <p> The {@code metaData} parameter can be used to limit the number of + * I/O operations that this method is required to perform. Passing + * {@code false} for this parameter indicates that only updates to the + * file's content need be written to storage; passing {@code true} + * indicates that updates to both the file's content and metadata must be + * written, which generally requires at least one more I/O operation. + * Whether this parameter actually has any effect is dependent upon the + * underlying operating system and is therefore unspecified. + * + * <p> Invoking this method may cause an I/O operation to occur even if the + * channel was only opened for reading. Some operating systems, for + * example, maintain a last-access time as part of a file's metadata, and + * this time is updated whenever the file is read. Whether or not this is + * actually done is system-dependent and is therefore unspecified. + * + * <p> This method is only guaranteed to force changes that were made to + * this channel's file via the methods defined in this class. + * + * @param metaData + * If {@code true} then this method is required to force changes + * to both the file's content and metadata to be written to + * storage; otherwise, it need only force content changes to be + * written + * + * @throws ClosedChannelException + * If this channel is closed + * + * @throws IOException + * If some other I/O error occurs + */ + public abstract void force(boolean metaData) throws IOException; + + /** + * Acquires a lock on the given region of this channel's file. + * + * <p> This method initiates an operation to acquire a lock on the given region + * of this channel's file. The method returns a {@code Future} representing + * the pending result of the operation. Its {@link Future#get() get} + * method returns the {@link FileLock} on successful completion. + * + * <p> The region specified by the {@code position} and {@code size} + * parameters need not be contained within, or even overlap, the actual + * underlying file. Lock regions are fixed in size; if a locked region + * initially contains the end of the file and the file grows beyond the + * region then the new portion of the file will not be covered by the lock. + * If a file is expected to grow in size and a lock on the entire file is + * required then a region starting at zero, and no smaller than the + * expected maximum size of the file, should be locked. The two-argument + * {@link #lock(Object,CompletionHandler)} method simply locks a region + * of size {@link Long#MAX_VALUE}. If a lock that overlaps the requested + * region is already held by this Java virtual machine, or this method has + * been invoked to lock an overlapping region and that operation has not + * completed, then this method throws {@link OverlappingFileLockException}. + * + * <p> Some operating systems do not support a mechanism to acquire a file + * lock in an asynchronous manner. Consequently an implementation may + * acquire the file lock in a background thread or from a task executed by + * a thread in the associated thread pool. If there are many lock operations + * outstanding then it may consume threads in the Java virtual machine for + * indefinite periods. + * + * <p> Some operating systems do not support shared locks, in which case a + * request for a shared lock is automatically converted into a request for + * an exclusive lock. Whether the newly-acquired lock is shared or + * exclusive may be tested by invoking the resulting lock object's {@link + * FileLock#isShared() isShared} method. + * + * <p> File locks are held on behalf of the entire Java virtual machine. + * They are not suitable for controlling access to a file by multiple + * threads within the same virtual machine. + * + * @param position + * The position at which the locked region is to start; must be + * non-negative + * @param size + * The size of the locked region; must be non-negative, and the sum + * {@code position} + {@code size} must be non-negative + * @param shared + * {@code true} to request a shared lock, in which case this + * channel must be open for reading (and possibly writing); + * {@code false} to request an exclusive lock, in which case this + * channel must be open for writing (and possibly reading) + * @param attachment + * The object to attach to the I/O operation; can be {@code null} + * @param handler + * The handler for consuming the result; can be {@code null} + * + * @return a {@code Future} object representing the pending result + * + * @throws OverlappingFileLockException + * If a lock that overlaps the requested region is already held by + * this Java virtual machine, or there is already a pending attempt + * to lock an overlapping region + * @throws IllegalArgumentException + * If the preconditions on the parameters do not hold + * @throws NonReadableChannelException + * If {@code shared} is true this channel but was not opened for reading + * @throws NonWritableChannelException + * If {@code shared} is false but this channel was not opened for writing + * @throws ShutdownChannelGroupException + * If a handler is specified, the channel is closed, and the channel + * was originally created with its own thread pool + */ + public abstract <A> Future<FileLock> lock(long position, + long size, + boolean shared, + A attachment, + CompletionHandler<FileLock,? super A> handler); + + /** + * Acquires an exclusive lock on this channel's file. + * + * <p> This method initiates an operation to acquire an exclusive lock on this + * channel's file. The method returns a {@code Future} representing + * the pending result of the operation. Its {@link Future#get() get} + * method returns the {@link FileLock} on successful completion. + * + * <p> An invocation of this method of the form {@code ch.lock(att,handler)} + * behaves in exactly the same way as the invocation + * <pre> + * ch.{@link #lock(long,long,boolean,Object,CompletionHandler) lock}(0L, Long.MAX_VALUE, false, att, handler) + * </pre> + * + * @param attachment + * The object to attach to the I/O operation; can be {@code null} + * @param handler + * The handler for consuming the result; can be {@code null} + * + * @return a {@code Future} object representing the pending result + * + * @throws OverlappingFileLockException + * If a lock is already held by this Java virtual machine, or there + * is already a pending attempt to lock a region + * @throws NonWritableChannelException + * If this channel was not opened for writing + * @throws ShutdownChannelGroupException + * If a handler is specified, the channel is closed, and the channel + * was originally created with its own thread pool + */ + public final <A> Future<FileLock> lock(A attachment, + CompletionHandler<FileLock,? super A> handler) + { + return lock(0L, Long.MAX_VALUE, false, attachment, handler); + } + + /** + * Acquires an exclusive lock on this channel's file. + * + * <p> This method initiates an operation to acquire an exclusive lock on this + * channel's file. The method returns a {@code Future} representing the + * pending result of the operation. Its {@link Future#get() get} method + * returns the {@link FileLock} on successful completion. + * + * <p> An invocation of this method behaves in exactly the same way as the + * invocation + * <pre> + * ch.{@link #lock(long,long,boolean,Object,CompletionHandler) lock}(0L, Long.MAX_VALUE, false, null, null) + * </pre> + * + * @return A {@code Future} object representing the pending result + * + * @throws OverlappingFileLockException + * If a lock is already held by this Java virtual machine, or there + * is already a pending attempt to lock a region + * @throws NonWritableChannelException + * If this channel was not opened for writing + */ + public final Future<FileLock> lock() { + return lock(0L, Long.MAX_VALUE, false, null, null); + } + + /** + * Attempts to acquire a lock on the given region of this channel's file. + * + * <p> This method does not block. An invocation always returns immediately, + * either having acquired a lock on the requested region or having failed to + * do so. If it fails to acquire a lock because an overlapping lock is held + * by another program then it returns {@code null}. If it fails to acquire + * a lock for any other reason then an appropriate exception is thrown. + * + * @param position + * The position at which the locked region is to start; must be + * non-negative + * + * @param size + * The size of the locked region; must be non-negative, and the sum + * {@code position} + {@code size} must be non-negative + * + * @param shared + * {@code true} to request a shared lock, + * {@code false} to request an exclusive lock + * + * @return A lock object representing the newly-acquired lock, + * or {@code null} if the lock could not be acquired + * because another program holds an overlapping lock + * + * @throws IllegalArgumentException + * If the preconditions on the parameters do not hold + * @throws ClosedChannelException + * If this channel is closed + * @throws OverlappingFileLockException + * If a lock that overlaps the requested region is already held by + * this Java virtual machine, or if another thread is already + * blocked in this method and is attempting to lock an overlapping + * region of the same file + * @throws NonReadableChannelException + * If {@code shared} is true this channel but was not opened for reading + * @throws NonWritableChannelException + * If {@code shared} is false but this channel was not opened for writing + * + * @throws IOException + * If some other I/O error occurs + * + * @see #lock(Object,CompletionHandler) + * @see #lock(long,long,boolean,Object,CompletionHandler) + * @see #tryLock() + */ + public abstract FileLock tryLock(long position, long size, boolean shared) + throws IOException; + + /** + * Attempts to acquire an exclusive lock on this channel's file. + * + * <p> An invocation of this method of the form {@code ch.tryLock()} + * behaves in exactly the same way as the invocation + * + * <pre> + * ch.{@link #tryLock(long,long,boolean) tryLock}(0L, Long.MAX_VALUE, false) </pre> + * + * @return A lock object representing the newly-acquired lock, + * or {@code null} if the lock could not be acquired + * because another program holds an overlapping lock + * + * @throws ClosedChannelException + * If this channel is closed + * @throws OverlappingFileLockException + * If a lock that overlaps the requested region is already held by + * this Java virtual machine, or if another thread is already + * blocked in this method and is attempting to lock an overlapping + * region + * @throws NonWritableChannelException + * If {@code shared} is false but this channel was not opened for writing + * + * @throws IOException + * If some other I/O error occurs + * + * @see #lock(Object,CompletionHandler) + * @see #lock(long,long,boolean,Object,CompletionHandler) + * @see #tryLock(long,long,boolean) + */ + public final FileLock tryLock() throws IOException { + return tryLock(0L, Long.MAX_VALUE, false); + } + + /** + * Reads a sequence of bytes from this channel into the given buffer, + * starting at the given file position. + * + * <p> This method initiates the reading of a sequence of bytes from this + * channel into the given buffer, starting at the given file position. This + * method returns a {@code Future} representing the pending result of the + * operation. The Future's {@link Future#get() get} method returns the + * number of bytes read or {@code -1} if the given position is greater than + * or equal to the file's size at the time that the read is attempted. + * + * <p> This method works in the same manner as the {@link + * AsynchronousByteChannel#read(ByteBuffer,Object,CompletionHandler)} + * method, except that bytes are read starting at the given file position. + * If the given file position is greater than the file's size at the time + * that the read is attempted then no bytes are read. + * + * @param dst + * The buffer into which bytes are to be transferred + * @param position + * The file position at which the transfer is to begin; + * must be non-negative + * @param attachment + * The object to attach to the I/O operation; can be {@code null} + * @param handler + * The handler for consuming the result; can be {@code null} + * + * @return A {@code Future} object representing the pending result + * + * @throws IllegalArgumentException + * If the position is negative or the buffer is read-only + * @throws NonReadableChannelException + * If this channel was not opened for reading + * @throws ShutdownChannelGroupException + * If a handler is specified, the channel is closed, and the channel + * was originally created with its own thread pool + */ + public abstract <A> Future<Integer> read(ByteBuffer dst, + long position, + A attachment, + CompletionHandler<Integer,? super A> handler); + + /** + * Reads a sequence of bytes from this channel into the given buffer, + * starting at the given file position. + * + * <p> This method initiates the reading of a sequence of bytes from this + * channel into the given buffer, starting at the given file position. This + * method returns a {@code Future} representing the pending result of the + * operation. The Future's {@link Future#get() get} method returns the + * number of bytes read or {@code -1} if the given position is greater + * than or equal to the file's size at the time that the read is attempted. + * + * <p> This method is equivalent to invoking {@link + * #read(ByteBuffer,long,Object,CompletionHandler)} with the {@code attachment} + * and handler parameters set to {@code null}. + * + * @param dst + * The buffer into which bytes are to be transferred + * @param position + * The file position at which the transfer is to begin; + * must be non-negative + * + * @return A {@code Future} object representing the pending result + * + * @throws IllegalArgumentException + * If the position is negative or the buffer is read-only + * @throws NonReadableChannelException + * If this channel was not opened for reading + */ + public final Future<Integer> read(ByteBuffer dst, long position) { + return read(dst, position, null, null); + } + + /** + * Writes a sequence of bytes to this channel from the given buffer, starting + * at the given file position. + * + * <p> This method initiates the writing of a sequence of bytes to this channel + * from the given buffer, starting at the given file position. The method + * returns a {@code Future} representing the pending result of the write + * operation. The Future's {@link Future#get() get} method returns the + * number of bytes written. + * + * <p> This method works in the same manner as the {@link + * AsynchronousByteChannel#write(ByteBuffer,Object,CompletionHandler)} + * method, except that bytes are written starting at the given file position. + * If the given position is greater than the file's size, at the time that + * the write is attempted, then the file will be grown to accommodate the new + * bytes; the values of any bytes between the previous end-of-file and the + * newly-written bytes are unspecified. + * + * @param src + * The buffer from which bytes are to be transferred + * @param position + * The file position at which the transfer is to begin; + * must be non-negative + * @param attachment + * The object to attach to the I/O operation; can be {@code null} + * @param handler + * The handler for consuming the result; can be {@code null} + * + * @return A {@code Future} object representing the pending result + * + * @throws IllegalArgumentException + * If the position is negative + * @throws NonWritableChannelException + * If this channel was not opened for writing + * @throws ShutdownChannelGroupException + * If a handler is specified, the channel is closed, and the channel + * was originally created with its own thread pool + */ + public abstract <A> Future<Integer> write(ByteBuffer src, + long position, + A attachment, + CompletionHandler<Integer,? super A> handler); + + /** + * Writes a sequence of bytes to this channel from the given buffer, starting + * at the given file position. + * + * <p> This method initiates the writing of a sequence of bytes to this channel + * from the given buffer, starting at the given file position. The method + * returns a {@code Future} representing the pending result of the write + * operation. The Future's {@link Future#get() get} method returns the + * number of bytes written. + * + * <p> This method is equivalent to invoking {@link + * #write(ByteBuffer,long,Object,CompletionHandler)} with the {@code attachment} + * and handler parameters set to {@code null}. + * + * @param src + * The buffer from which bytes are to be transferred + * @param position + * The file position at which the transfer is to begin; + * must be non-negative + * + * @return A {@code Future} object representing the pending result + * + * @throws IllegalArgumentException + * If the position is negative + * @throws NonWritableChannelException + * If this channel was not opened for writing + */ + public final Future<Integer> write(ByteBuffer src, long position) { + return write(src, position, null, null); + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/AsynchronousServerSocketChannel.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,305 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.channels; + +import java.net.SocketAddress; +import java.util.concurrent.Future; +import java.io.IOException; + +import org.classpath.icedtea.java.net.SocketOption; +import org.classpath.icedtea.java.nio.channels.spi.AsynchronousChannelProvider; + +/** + * An asynchronous channel for stream-oriented listening sockets. + * + * <p> An asynchronous server-socket channel is created by invoking the + * {@link #open open} method of this class. + * A newly-created asynchronous server-socket channel is open but not yet bound. + * It can be bound to a local address and configured to listen for connections + * by invoking the {@link #bind(SocketAddress,int) bind} method. Once bound, + * the {@link #accept(Object,CompletionHandler) accept} method + * is used to initiate the accepting of connections to the channel's socket. + * An attempt to invoke the <tt>accept</tt> method on an unbound channel will + * cause a {@link NotYetBoundException} to be thrown. + * + * <p> Channels of this type are safe for use by multiple concurrent threads + * though at most one accept operation can be outstanding at any time. + * If a thread initiates an accept operation before a previous accept operation + * has completed then an {@link AcceptPendingException} will be thrown. + * + * <p> Socket options are configured using the {@link #setOption(SocketOption,Object) + * setOption} method. Channels of this type support the following options: + * <blockquote> + * <table border> + * <tr> + * <th>Option Name</th> + * <th>Description</th> + * </tr> + * <tr> + * <td> {@link java.net.StandardSocketOption#SO_RCVBUF SO_RCVBUF} </td> + * <td> The size of the socket receive buffer </td> + * </tr> + * <tr> + * <td> {@link java.net.StandardSocketOption#SO_REUSEADDR SO_REUSEADDR} </td> + * <td> Re-use address </td> + * </tr> + * </table> + * </blockquote> + * Additional (implementation specific) options may also be supported. + * + * <p> <b>Usage Example:</b> + * <pre> + * final AsynchronousServerSocketChannel listener = + * AsynchronousServerSocketChannel.open().bind(new InetSocketAddress(5000)); + * + * listener.accept(null, new CompletionHandler<AsynchronousSocketChannel,Void>() { + * public void completed(AsynchronousSocketChannel ch, Void att) { + * // accept the next connection + * listener.accept(null, this); + * + * // handle this connection + * handle(ch); + * } + * public void failed(Throwable exc, Void att) { + * ... + * } + * public void cancelled(Void att) { + * ... + * } + * }); + * </pre> + * + * @since 1.7 + */ + +public abstract class AsynchronousServerSocketChannel + implements AsynchronousChannel, NetworkChannel +{ + private final AsynchronousChannelProvider provider; + + /** + * Initializes a new instance of this class. + */ + protected AsynchronousServerSocketChannel(AsynchronousChannelProvider provider) { + this.provider = provider; + } + + /** + * Returns the provider that created this channel. + */ + public final AsynchronousChannelProvider provider() { + return provider; + } + + /** + * Opens an asynchronous server-socket channel. + * + * <p> The new channel is created by invoking the {@link + * java.nio.channels.spi.AsynchronousChannelProvider#openAsynchronousServerSocketChannel + * openAsynchronousServerSocketChannel} method on the {@link + * java.nio.channels.spi.AsynchronousChannelProvider} object that created + * the given group. If the group parameter is <tt>null</tt> then the + * resulting channel is created by the system-wide default provider, and + * bound to the <em>default group</em>. + * + * @param group + * The group to which the newly constructed channel should be bound, + * or <tt>null</tt> for the default group + * + * @return A new asynchronous server socket channel + * + * @throws ShutdownChannelGroupException + * If the channel group is shutdown + * @throws IOException + * If an I/O error occurs + */ + public static AsynchronousServerSocketChannel open(AsynchronousChannelGroup group) + throws IOException + { + AsynchronousChannelProvider provider = (group == null) ? + AsynchronousChannelProvider.provider() : group.provider(); + return provider.openAsynchronousServerSocketChannel(group); + } + + /** + * Opens an asynchronous server-socket channel. + * + * <p> This method returns an asynchronous server socket channel that is + * bound to the <em>default group</em>. This method is equivalent to evaluating + * the expression: + * <blockquote><pre> + * open((AsynchronousChannelGroup)null); + * </pre></blockquote> + * + * @return A new asynchronous server socket channel + * + * @throws IOException + * If an I/O error occurs + */ + public static AsynchronousServerSocketChannel open() + throws IOException + { + return open(null); + } + + /** + * Binds the channel's socket to a local address and configures the socket to + * listen for connections. + * + * <p> An invocation of this method is equivalent to the following: + * <blockquote><pre> + * bind(local, 0); + * </pre></blockquote> + * + * @param local + * The local address to bind the socket, or <tt>null</tt> to bind + * to an automatically assigned socket address + * + * @return This channel + * + * @throws AlreadyBoundException {@inheritDoc} + * @throws UnsupportedAddressTypeException {@inheritDoc} + * @throws SecurityException {@inheritDoc} + * @throws ClosedChannelException {@inheritDoc} + * @throws IOException {@inheritDoc} + */ + public final AsynchronousServerSocketChannel bind(SocketAddress local) + throws IOException + { + return bind(local, 0); + } + + /** + * Binds the channel's socket to a local address and configures the socket to + * listen for connections. + * + * <p> This method is used to establish an association between the socket and + * a local address. Once an association is established then the socket remains + * bound until the associated channel is closed. + * + * <p> The {@code backlog} parameter is the maximum number of pending + * connections on the socket. Its exact semantics are implementation specific. + * In particular, an implementation may impose a maximum length or may choose + * to ignore the parameter altogther. If the {@code backlog} parameter has + * the value {@code 0}, or a negative value, then an implementation specific + * default is used. + * + * @param local + * The local address to bind the socket, or {@code null} to bind + * to an automatically assigned socket address + * @param backlog + * The maximum number of pending connections + * + * @return This channel + * + * @throws AlreadyBoundException + * If the socket is already bound + * @throws UnsupportedAddressTypeException + * If the type of the given address is not supported + * @throws SecurityException + * If a security manager has been installed and its {@link + * SecurityManager#checkListen checkListen} method denies the operation + * @throws ClosedChannelException + * If the channel is closed + * @throws IOException + * If some other I/O error occurs + */ + public abstract AsynchronousServerSocketChannel bind(SocketAddress local, int backlog) + throws IOException; + + /** + * @throws IllegalArgumentException {@inheritDoc} + * @throws ClosedChannelException {@inheritDoc} + * @throws IOException {@inheritDoc} + */ + public abstract <T> AsynchronousServerSocketChannel setOption(SocketOption<T> name, T value) + throws IOException; + + /** + * Accepts a connection. + * + * <p> This method initiates accepting a connection made to this channel's + * socket, returning a {@link Future} representing the pending result + * of the operation. The {@code Future}'s {@link Future#get() get} + * method will return the {@link AsynchronousSocketChannel} for the new + * connection on successful completion. + * + * <p> When a new connection is accepted then the resulting {@code + * AsynchronousSocketChannel} will be bound to the same {@link + * AsynchronousChannelGroup} as this channel. If the group is {@link + * AsynchronousChannelGroup#isShutdown shutdown} and a connection is accepted, + * then the connection is closed, and the operation completes with an {@code + * IOException} and cause {@link ShutdownChannelGroupException}. + * + * <p> To allow for concurrent handling of new connections, the completion + * handler is not invoked directly by the initiating thread when a new + * connection is accepted immediately (see <a + * href="AsynchronousChannelGroup.html#threading">Threading<a>). + * + * <p> If a security manager has been installed then it verifies that the + * address and port number of the connection's remote endpoint are permitted + * by the security manager's {@link SecurityManager#checkAccept checkAccept} + * method. The permission check is performed with privileges that are restricted + * by the calling context of this method. If the permission check fails then + * the connection is closed and the operation completes with a {@link + * SecurityException}. + * + * @param attachment + * The object to attach to the I/O operation; can be {@code null} + * @param handler + * The handler for consuming the result; can be {@code null} + * + * @return an <tt>Future</tt> object representing the pending result + * + * @throws AcceptPendingException + * If an accept operation is already in progress on this channel + * @throws NotYetBoundException + * If this channel's socket has not yet been bound + * @throws ShutdownChannelGroupException + * If a handler is specified, and the channel group is shutdown + */ + public abstract <A> Future<AsynchronousSocketChannel> + accept(A attachment, CompletionHandler<AsynchronousSocketChannel,? super A> handler); + + /** + * Accepts a connection. + * + * <p> This method is equivalent to invoking {@link + * #accept(Object,CompletionHandler)} with the {@code attachment} + * and {@code handler} parameters set to {@code null}. + * + * @return an <tt>Future</tt> object representing the pending result + * + * @throws AcceptPendingException + * If an accept operation is already in progress on this channel + * @throws NotYetBoundException + * If this channel's socket has not yet been bound + */ + public final Future<AsynchronousSocketChannel> accept() { + return accept(null, null); + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/AsynchronousSocketChannel.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,672 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.channels; + +import java.util.concurrent.TimeUnit; +import java.util.concurrent.Future; +import java.io.IOException; +import java.net.SocketAddress; +import java.nio.ByteBuffer; + +import org.classpath.icedtea.java.net.SocketOption; +import org.classpath.icedtea.java.nio.channels.spi.AsynchronousChannelProvider; + +/** + * An asynchronous channel for stream-oriented connecting sockets. + * + * <p> Asynchronous socket channels are created in one of two ways. A newly-created + * {@code AsynchronousSocketChannel} is created by invoking one of the {@link + * #open open} methods defined by this class. A newly-created channel is open but + * not yet connected. A connected {@code AsynchronousSocketChannel} is created + * when a connection is made to the socket of an {@link AsynchronousServerSocketChannel}. + * It is not possible to create an asynchronous socket channel for an arbitrary, + * pre-existing {@link java.net.Socket socket}. + * + * <p> A newly-created channel is connected by invoking its {@link #connect connect} + * method; once connected, a channel remains connected until it is closed. Whether + * or not a socket channel is connected may be determined by invoking its {@link + * #getRemoteAddress getRemoteAddress} method. An attempt to invoke an I/O + * operation upon an unconnected channel will cause a {@link NotYetConnectedException} + * to be thrown. + * + * <p> Channels of this type are safe for use by multiple concurrent threads. + * They support concurrent reading and writing, though at most one read operation + * and one write operation can be outstanding at any time. + * If a thread initiates a read operation before a previous read operation has + * completed then a {@link ReadPendingException} will be thrown. Similarly, an + * attempt to initiate a write operation before a previous write has completed + * will throw a {@link WritePendingException}. + * + * <p> Socket options are configured using the {@link #setOption(SocketOption,Object) + * setOption} method. Asynchronous socket channels support the following options: + * <blockquote> + * <table border> + * <tr> + * <th>Option Name</th> + * <th>Description</th> + * </tr> + * <tr> + * <td> {@link java.net.StandardSocketOption#SO_SNDBUF SO_SNDBUF} </td> + * <td> The size of the socket send buffer </td> + * </tr> + * <tr> + * <td> {@link java.net.StandardSocketOption#SO_RCVBUF SO_RCVBUF} </td> + * <td> The size of the socket receive buffer </td> + * </tr> + * <tr> + * <td> {@link java.net.StandardSocketOption#SO_KEEPALIVE SO_KEEPALIVE} </td> + * <td> Keep connection alive </td> + * </tr> + * <tr> + * <td> {@link java.net.StandardSocketOption#SO_REUSEADDR SO_REUSEADDR} </td> + * <td> Re-use address </td> + * </tr> + * <tr> + * <td> {@link java.net.StandardSocketOption#TCP_NODELAY TCP_NODELAY} </td> + * <td> Disable the Nagle algorithm </td> + * </tr> + * </table> + * </blockquote> + * Additional (implementation specific) options may also be supported. + * + * <h4>Timeouts</h4> + * + * <p> The {@link #read(ByteBuffer,long,TimeUnit,Object,CompletionHandler) read} + * and {@link #write(ByteBuffer,long,TimeUnit,Object,CompletionHandler) write} + * methods defined by this class allow a timeout to be specified when initiating + * a read or write operation. If the timeout elapses before an operation completes + * then the operation completes with the exception {@link + * InterruptedByTimeoutException}. A timeout may leave the channel, or the + * underlying connection, in an inconsistent state. Where the implementation + * cannot guarantee that bytes have not been read from the channel then it puts + * the channel into an implementation specific <em>error state</em>. A subsequent + * attempt to initiate a {@code read} operation causes an unspecified runtime + * exception to be thrown. Similarly if a {@code write} operation times out and + * the implementation cannot guarantee bytes have not been written to the + * channel then further attempts to {@code write} to the channel cause an + * unspecified runtime exception to be thrown. When a timeout elapses then the + * state of the {@link ByteBuffer}, or the sequence of buffers, for the I/O + * operation is not defined. Buffers should be discarded or at least care must + * be taken to ensure that the buffers are not accessed while the channel remains + * open. + * + * @since 1.7 + */ + +public abstract class AsynchronousSocketChannel + implements AsynchronousByteChannel, NetworkChannel +{ + private final AsynchronousChannelProvider provider; + + /** + * Initializes a new instance of this class. + */ + protected AsynchronousSocketChannel(AsynchronousChannelProvider provider) { + this.provider = provider; + } + + /** + * Returns the provider that created this channel. + */ + public final AsynchronousChannelProvider provider() { + return provider; + } + + /** + * Opens an asynchronous socket channel. + * + * <p> The new channel is created by invoking the {@link + * AsynchronousChannelProvider#openAsynchronousSocketChannel + * openAsynchronousSocketChannel} method on the {@link + * AsynchronousChannelProvider} that created the group. If the group parameter + * is {@code null} then the resulting channel is created by the system-wide + * default provider, and bound to the <em>default group</em>. + * + * @param group + * The group to which the newly constructed channel should be bound, + * or {@code null} for the default group + * + * @return A new asynchronous socket channel + * + * @throws ShutdownChannelGroupException + * If the channel group is shutdown + * @throws IOException + * If an I/O error occurs + */ + public static AsynchronousSocketChannel open(AsynchronousChannelGroup group) + throws IOException + { + AsynchronousChannelProvider provider = (group == null) ? + AsynchronousChannelProvider.provider() : group.provider(); + return provider.openAsynchronousSocketChannel(group); + } + + /** + * Opens an asynchronous socket channel. + * + * <p> This method returns an asynchronous socket channel that is bound to + * the <em>default group</em>.This method is equivalent to evaluating the + * expression: + * <blockquote><pre> + * open((AsynchronousChannelGroup)null); + * </pre></blockquote> + * + * @return A new asynchronous socket channel + * + * @throws IOException + * If an I/O error occurs + */ + public static AsynchronousSocketChannel open() + throws IOException + { + return open(null); + } + + + // -- socket options and related -- + + /** + * @throws ConnectionPendingException + * If a connection operation is already in progress on this channel + * @throws AlreadyBoundException {@inheritDoc} + * @throws UnsupportedAddressTypeException {@inheritDoc} + * @throws ClosedChannelException {@inheritDoc} + * @throws IOException {@inheritDoc} + */ + + public abstract AsynchronousSocketChannel bind(SocketAddress local) + throws IOException; + + /** + * @throws IllegalArgumentException {@inheritDoc} + * @throws ClosedChannelException {@inheritDoc} + * @throws IOException {@inheritDoc} + */ + + public abstract <T> AsynchronousSocketChannel setOption(SocketOption<T> name, T value) + throws IOException; + + /** + * Shutdown the connection for reading without closing the channel. + * + * <p> Once shutdown for reading then further reads on the channel will + * return {@code -1}, the end-of-stream indication. If the input side of the + * connection is already shutdown then invoking this method has no effect. + * The effect on an outstanding read operation is system dependent and + * therefore not specified. The effect, if any, when there is data in the + * socket receive buffer that has not been read, or data arrives subsequently, + * is also system dependent. + * + * @return The channel + * + * @throws NotYetConnectedException + * If this channel is not yet connected + * @throws ClosedChannelException + * If this channel is closed + * @throws IOException + * If some other I/O error occurs + */ + public abstract AsynchronousSocketChannel shutdownInput() throws IOException; + + /** + * Shutdown the connection for writing without closing the channel. + * + * <p> Once shutdown for writing then further attempts to write to the + * channel will throw {@link ClosedChannelException}. If the output side of + * the connection is already shutdown then invoking this method has no + * effect. The effect on an outstanding write operation is system dependent + * and therefore not specified. + * + * @return The channel + * + * @throws NotYetConnectedException + * If this channel is not yet connected + * @throws ClosedChannelException + * If this channel is closed + * @throws IOException + * If some other I/O error occurs + */ + public abstract AsynchronousSocketChannel shutdownOutput() throws IOException; + + // -- state -- + + /** + * Returns the remote address to which this channel's socket is connected. + * + * <p> Where the channel is bound and connected to an Internet Protocol + * socket address then the return value from this method is of type {@link + * java.net.InetSocketAddress}. + * + * @return The remote address; {@code null} if the channel's socket is not + * connected + * + * @throws ClosedChannelException + * If the channel is closed + * @throws IOException + * If an I/O error occurs + */ + public abstract SocketAddress getRemoteAddress() throws IOException; + + // -- asynchronous operations -- + + /** + * Connects this channel. + * + * <p> This method initiates an operation to connect this channel, returning + * a {@code Future} representing the pending result of the operation. If + * the connection is successfully established then the {@code Future}'s + * {@link Future#get() get} method will return {@code null}. If the + * connection cannot be established then the channel is closed. In that case, + * invoking the {@code get} method throws {@link + * java.util.concurrent.ExecutionException} with an {@code IOException} as + * the cause. + * + * <p> This method performs exactly the same security checks as the {@link + * java.net.Socket} class. That is, if a security manager has been + * installed then this method verifies that its {@link + * java.lang.SecurityManager#checkConnect checkConnect} method permits + * connecting to the address and port number of the given remote endpoint. + * + * @param remote + * The remote address to which this channel is to be connected + * @param attachment + * The object to attach to the I/O operation; can be {@code null} + * @param handler + * The handler for consuming the result; can be {@code null} + * + * @return A {@code Future} object representing the pending result + * + * @throws UnresolvedAddressException + * If the given remote address is not fully resolved + * @throws UnsupportedAddressTypeException + * If the type of the given remote address is not supported + * @throws AlreadyConnectedException + * If this channel is already connected + * @throws ConnectionPendingException + * If a connection operation is already in progress on this channel + * @throws ShutdownChannelGroupException + * If a handler is specified, and the channel group is shutdown + * @throws SecurityException + * If a security manager has been installed + * and it does not permit access to the given remote endpoint + * + * @see #getRemoteAddress + */ + public abstract <A> Future<Void> connect(SocketAddress remote, + A attachment, + CompletionHandler<Void,? super A> handler); + + /** + * Connects this channel. + * + * <p> This method is equivalent to invoking {@link + * #connect(SocketAddress,Object,CompletionHandler)} with the {@code attachment} + * and handler parameters set to {@code null}. + * + * @param remote + * The remote address to which this channel is to be connected + * + * @return A {@code Future} object representing the pending result + * + * @throws UnresolvedAddressException + * If the given remote address is not fully resolved + * @throws UnsupportedAddressTypeException + * If the type of the given remote address is not supported + * @throws AlreadyConnectedException + * If this channel is already connected + * @throws ConnectionPendingException + * If a connection operation is already in progress on this channel + * @throws SecurityException + * If a security manager has been installed + * and it does not permit access to the given remote endpoint + */ + public final Future<Void> connect(SocketAddress remote) { + return connect(remote, null, null); + } + + /** + * Reads a sequence of bytes from this channel into the given buffer. + * + * <p> This method initiates the reading of a sequence of bytes from this + * channel into the given buffer, returning a {@code Future} representing + * the pending result of the operation. The {@code Future}'s {@link + * Future#get() get} method returns the number of bytes read or {@code -1} + * if all bytes have been read and channel has reached end-of-stream. + * + * <p> If a timeout is specified and the timeout elapses before the operation + * completes then the operation completes with the exception {@link + * InterruptedByTimeoutException}. Where a timeout occurs, and the + * implementation cannot guarantee that bytes have not been read, or will not + * be read from the channel into the given buffer, then further attempts to + * read from the channel will cause an unspecific runtime exception to be + * thrown. + * + * <p> Otherwise this method works in the same manner as the {@link + * AsynchronousByteChannel#read(ByteBuffer,Object,CompletionHandler)} + * method. + * + * @param dst + * The buffer into which bytes are to be transferred + * @param timeout + * The timeout, or {@code 0L} for no timeout + * @param unit + * The time unit of the {@code timeout} argument + * @param attachment + * The object to attach to the I/O operation; can be {@code null} + * @param handler + * The handler for consuming the result; can be {@code null} + * + * @return A {@code Future} object representing the pending result + * + * @throws IllegalArgumentException + * If the {@code timeout} parameter is negative or the buffer is + * read-only + * @throws ReadPendingException + * If a read operation is already in progress on this channel + * @throws NotYetConnectedException + * If this channel is not yet connected + * @throws ShutdownChannelGroupException + * If a handler is specified, and the channel group is shutdown + */ + public abstract <A> Future<Integer> read(ByteBuffer dst, + long timeout, + TimeUnit unit, + A attachment, + CompletionHandler<Integer,? super A> handler); + + /** + * @throws IllegalArgumentException {@inheritDoc} + * @throws ReadPendingException {@inheritDoc} + * @throws NotYetConnectedException + * If this channel is not yet connected + * @throws ShutdownChannelGroupException + * If a handler is specified, and the channel group is shutdown + */ + + public final <A> Future<Integer> read(ByteBuffer dst, + A attachment, + CompletionHandler<Integer,? super A> handler) + { + return read(dst, 0L, TimeUnit.MILLISECONDS, attachment, handler); + } + + /** + * @throws IllegalArgumentException {@inheritDoc} + * @throws ReadPendingException {@inheritDoc} + * @throws NotYetConnectedException + * If this channel is not yet connected + */ + + public final Future<Integer> read(ByteBuffer dst) { + return read(dst, 0L, TimeUnit.MILLISECONDS, null, null); + } + + /** + * Reads a sequence of bytes from this channel into a subsequence of the + * given buffers. This operation, sometimes called a <em>scattering read</em>, + * is often useful when implementing network protocols that group data into + * segments consisting of one or more fixed-length headers followed by a + * variable-length body. + * + * <p> This method initiates a read of up to <i>r</i> bytes from this channel, + * where <i>r</i> is the total number of bytes remaining in the specified + * subsequence of the given buffer array, that is, + * + * <blockquote><pre> + * dsts[offset].remaining() + * + dsts[offset+1].remaining() + * + ... + dsts[offset+length-1].remaining()</pre></blockquote> + * + * at the moment that the read is attempted. + * + * <p> Suppose that a byte sequence of length <i>n</i> is read, where + * <tt>0</tt> <tt><</tt> <i>n</i> <tt><=</tt> <i>r</i>. + * Up to the first <tt>dsts[offset].remaining()</tt> bytes of this sequence + * are transferred into buffer <tt>dsts[offset]</tt>, up to the next + * <tt>dsts[offset+1].remaining()</tt> bytes are transferred into buffer + * <tt>dsts[offset+1]</tt>, and so forth, until the entire byte sequence + * is transferred into the given buffers. As many bytes as possible are + * transferred into each buffer, hence the final position of each updated + * buffer, except the last updated buffer, is guaranteed to be equal to + * that buffer's limit. The underlying operating system may impose a limit + * on the number of buffers that may be used in an I/O operation. Where the + * number of buffers (with bytes remaining), exceeds this limit, then the + * I/O operation is performed with the maximum number of buffers allowed by + * the operating system. + * + * <p> The return value from this method is a {@code Future} representing + * the pending result of the operation. The {@code Future}'s {@link + * Future#get() get} method returns the number of bytes read or {@code -1L} + * if all bytes have been read and the channel has reached end-of-stream. + * + * <p> If a timeout is specified and the timeout elapses before the operation + * completes then it completes with the exception {@link + * InterruptedByTimeoutException}. Where a timeout occurs, and the + * implementation cannot guarantee that bytes have not been read, or will not + * be read from the channel into the given buffers, then further attempts to + * read from the channel will cause an unspecific runtime exception to be + * thrown. + * + * @param dsts + * The buffers into which bytes are to be transferred + * @param offset + * The offset within the buffer array of the first buffer into which + * bytes are to be transferred; must be non-negative and no larger than + * {@code dsts.length} + * @param length + * The maximum number of buffers to be accessed; must be non-negative + * and no larger than {@code dsts.length - offset} + * @param timeout + * The timeout, or {@code 0L} for no timeout + * @param unit + * The time unit of the {@code timeout} argument + * @param attachment + * The object to attach to the I/O operation; can be {@code null} + * @param handler + * The handler for consuming the result; can be {@code null} + * + * @return A {@code Future} object representing the pending result + * + * @throws IndexOutOfBoundsException + * If the pre-conditions for the {@code offset} and {@code length} + * parameter aren't met + * @throws IllegalArgumentException + * If the {@code timeout} parameter is negative, or a buffer is + * read-only + * @throws ReadPendingException + * If a read operation is already in progress on this channel + * @throws NotYetConnectedException + * If this channel is not yet connected + * @throws ShutdownChannelGroupException + * If a handler is specified, and the channel group is shutdown + */ + public abstract <A> Future<Long> read(ByteBuffer[] dsts, + int offset, + int length, + long timeout, + TimeUnit unit, + A attachment, + CompletionHandler<Long,? super A> handler); + + /** + * Writes a sequence of bytes to this channel from the given buffer. + * + * <p> This method initiates the writing of a sequence of bytes to this channel + * from the given buffer, returning a {@code Future} representing the + * pending result of the operation. The {@code Future}'s {@link Future#get() + * get} method will return the number of bytes written. + * + * <p> If a timeout is specified and the timeout elapses before the operation + * completes then it completes with the exception {@link + * InterruptedByTimeoutException}. Where a timeout occurs, and the + * implementation cannot guarantee that bytes have not been written, or will + * not be written to the channel from the given buffer, then further attempts + * to write to the channel will cause an unspecific runtime exception to be + * thrown. + * + * <p> Otherwise this method works in the same manner as the {@link + * AsynchronousByteChannel#write(ByteBuffer,Object,CompletionHandler)} + * method. + * + * @param src + * The buffer from which bytes are to be retrieved + * @param timeout + * The timeout, or {@code 0L} for no timeout + * @param unit + * The time unit of the {@code timeout} argument + * @param attachment + * The object to attach to the I/O operation; can be {@code null} + * @param handler + * The handler for consuming the result; can be {@code null} + * + * @return A {@code Future} object representing the pending result + * + * @throws IllegalArgumentException + * If the {@code timeout} parameter is negative + * @throws WritePendingException + * If a write operation is already in progress on this channel + * @throws NotYetConnectedException + * If this channel is not yet connected + * @throws ShutdownChannelGroupException + * If a handler is specified, and the channel group is shutdown + */ + public abstract <A> Future<Integer> write(ByteBuffer src, + long timeout, + TimeUnit unit, + A attachment, + CompletionHandler<Integer,? super A> handler); + + /** + * @throws WritePendingException {@inheritDoc} + * @throws NotYetConnectedException + * If this channel is not yet connected + * @throws ShutdownChannelGroupException + * If a handler is specified, and the channel group is shutdown + */ + + public final <A> Future<Integer> write(ByteBuffer src, + A attachment, + CompletionHandler<Integer,? super A> handler) + + { + return write(src, 0L, TimeUnit.MILLISECONDS, attachment, handler); + } + + /** + * @throws WritePendingException {@inheritDoc} + * @throws NotYetConnectedException + * If this channel is not yet connected + */ + + public final Future<Integer> write(ByteBuffer src) { + return write(src, 0L, TimeUnit.MILLISECONDS, null, null); + } + + /** + * Writes a sequence of bytes to this channel from a subsequence of the given + * buffers. This operation, sometimes called a <em>gathering write</em>, is + * often useful when implementing network protocols that group data into + * segments consisting of one or more fixed-length headers followed by a + * variable-length body. + * + * <p> This method initiates a write of up to <i>r</i> bytes to this channel, + * where <i>r</i> is the total number of bytes remaining in the specified + * subsequence of the given buffer array, that is, + * + * <blockquote><pre> + * srcs[offset].remaining() + * + srcs[offset+1].remaining() + * + ... + srcs[offset+length-1].remaining()</pre></blockquote> + * + * at the moment that the write is attempted. + * + * <p> Suppose that a byte sequence of length <i>n</i> is written, where + * <tt>0</tt> <tt><</tt> <i>n</i> <tt><=</tt> <i>r</i>. + * Up to the first <tt>srcs[offset].remaining()</tt> bytes of this sequence + * are written from buffer <tt>srcs[offset]</tt>, up to the next + * <tt>srcs[offset+1].remaining()</tt> bytes are written from buffer + * <tt>srcs[offset+1]</tt>, and so forth, until the entire byte sequence is + * written. As many bytes as possible are written from each buffer, hence + * the final position of each updated buffer, except the last updated + * buffer, is guaranteed to be equal to that buffer's limit. The underlying + * operating system may impose a limit on the number of buffers that may be + * used in an I/O operation. Where the number of buffers (with bytes + * remaining), exceeds this limit, then the I/O operation is performed with + * the maximum number of buffers allowed by the operating system. + * + * <p> The return value from this method is a {@code Future} representing + * the pending result of the operation. The {@code Future}'s {@link + * Future#get() get} method will return the number of bytes written. + * + * <p> If a timeout is specified and the timeout elapses before the operation + * completes then it completes with the exception {@link + * InterruptedByTimeoutException}. Where a timeout occurs, and the + * implementation cannot guarantee that bytes have not been written, or will + * not be written to the channel from the given buffers, then further attempts + * to write to the channel will cause an unspecific runtime exception to be + * thrown. + * + * @param srcs + * The buffers from which bytes are to be retrieved + * @param offset + * The offset within the buffer array of the first buffer from which + * bytes are to be retrieved; must be non-negative and no larger + * than {@code srcs.length} + * @param length + * The maximum number of buffers to be accessed; must be non-negative + * and no larger than {@code srcs.length - offset} + * @param timeout + * The timeout, or {@code 0L} for no timeout + * @param unit + * The time unit of the {@code timeout} argument + * @param attachment + * The object to attach to the I/O operation; can be {@code null} + * @param handler + * The handler for consuming the result; can be {@code null} + * + * @return A {@code Future} object representing the pending result + * + * @throws IndexOutOfBoundsException + * If the pre-conditions for the {@code offset} and {@code length} + * parameter aren't met + * @throws IllegalArgumentException + * If the {@code timeout} parameter is negative + * @throws WritePendingException + * If a write operation is already in progress on this channel + * @throws NotYetConnectedException + * If this channel is not yet connected + * @throws ShutdownChannelGroupException + * If a handler is specified, and the channel group is shutdown + */ + public abstract <A> Future<Long> write(ByteBuffer[] srcs, + int offset, + int length, + long timeout, + TimeUnit unit, + A attachment, + CompletionHandler<Long,? super A> handler); +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/Channels.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,214 @@ +/* + * Copyright 2000-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.channels; + +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.Reader; +import java.io.Writer; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.Charset; +import java.nio.charset.CharsetDecoder; +import java.nio.charset.CharsetEncoder; +import java.nio.charset.UnsupportedCharsetException; +import java.nio.channels.spi.AbstractInterruptibleChannel; +import java.util.concurrent.ExecutionException; +import sun.nio.ch.ChannelInputStream; +import sun.nio.cs.StreamDecoder; +import sun.nio.cs.StreamEncoder; + + +/** + * Utility methods for channels and streams. + * + * <p> This class defines static methods that support the interoperation of the + * stream classes of the <tt>{@link java.io}</tt> package with the channel + * classes of this package. </p> + * + * + * @author Mark Reinhold + * @author Mike McCloskey + * @author JSR-51 Expert Group + * @since 1.4 + */ + +public final class Channels { + + private Channels() { } // No instantiation + + /** + * {@note new} + * Constructs a stream that reads bytes from the given channel. + * + * <p> The stream will not be buffered, and it will not support the {@link + * InputStream#mark mark} or {@link InputStream#reset reset} methods. The + * stream will be safe for access by multiple concurrent threads. Closing + * the stream will in turn cause the channel to be closed. </p> + * + * @param ch + * The channel from which bytes will be read + * + * @return A new input stream + * + * @since 1.7 + */ + public static InputStream newInputStream(final AsynchronousByteChannel ch) { + return new InputStream() { + + private ByteBuffer bb = null; + private byte[] bs = null; // Invoker's previous array + private byte[] b1 = null; + + + public synchronized int read() throws IOException { + if (b1 == null) + b1 = new byte[1]; + int n = this.read(b1); + if (n == 1) + return b1[0] & 0xff; + return -1; + } + + + public synchronized int read(byte[] bs, int off, int len) + throws IOException + { + if ((off < 0) || (off > bs.length) || (len < 0) || + ((off + len) > bs.length) || ((off + len) < 0)) { + throw new IndexOutOfBoundsException(); + } else if (len == 0) + return 0; + + ByteBuffer bb = ((this.bs == bs) + ? this.bb + : ByteBuffer.wrap(bs)); + bb.position(off); + bb.limit(Math.min(off + len, bb.capacity())); + this.bb = bb; + this.bs = bs; + + boolean interrupted = false; + try { + for (;;) { + try { + return ch.read(bb).get(); + } catch (ExecutionException ee) { + throw new IOException(ee.getCause()); + } catch (InterruptedException ie) { + interrupted = true; + } + } + } finally { + if (interrupted) + Thread.currentThread().interrupt(); + } + } + + + public void close() throws IOException { + ch.close(); + } + }; + } + + /** + * {@note new} + * Constructs a stream that writes bytes to the given channel. + * + * <p> The stream will not be buffered. The stream will be safe for access + * by multiple concurrent threads. Closing the stream will in turn cause + * the channel to be closed. </p> + * + * @param ch + * The channel to which bytes will be written + * + * @return A new output stream + * + * @since 1.7 + */ + public static OutputStream newOutputStream(final AsynchronousByteChannel ch) { + return new OutputStream() { + + private ByteBuffer bb = null; + private byte[] bs = null; // Invoker's previous array + private byte[] b1 = null; + + + public synchronized void write(int b) throws IOException { + if (b1 == null) + b1 = new byte[1]; + b1[0] = (byte)b; + this.write(b1); + } + + + public synchronized void write(byte[] bs, int off, int len) + throws IOException + { + if ((off < 0) || (off > bs.length) || (len < 0) || + ((off + len) > bs.length) || ((off + len) < 0)) { + throw new IndexOutOfBoundsException(); + } else if (len == 0) { + return; + } + ByteBuffer bb = ((this.bs == bs) + ? this.bb + : ByteBuffer.wrap(bs)); + bb.limit(Math.min(off + len, bb.capacity())); + bb.position(off); + this.bb = bb; + this.bs = bs; + + boolean interrupted = false; + try { + while (bb.remaining() > 0) { + try { + ch.write(bb).get(); + } catch (ExecutionException ee) { + throw new IOException(ee.getCause()); + } catch (InterruptedException ie) { + interrupted = true; + } + } + } finally { + if (interrupted) + Thread.currentThread().interrupt(); + } + } + + + public void close() throws IOException { + ch.close(); + } + }; + } + + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/CompletionHandler.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,78 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.channels; + +/** + * A handler for consuming the result of an asynchronous I/O operation. + * + * <p> The asynchronous channels defined in this package allow a completion + * handler to be specified to consume the result of an asynchronous operation. + * The {@link #completed completed} method is invoked when the I/O operation + * completes successfully. The {@link #failed failed} method is invoked if the + * I/O operations fails. The {@link #cancelled cancelled} method is invoked when + * the I/O operation is cancelled by invoking the {@link + * java.util.concurrent.Future#cancel cancel} method. The implementations of + * these methods should complete in a timely manner so as to avoid keeping the + * invoking thread from dispatching to other completion handlers. + * + * @param <V> The result type of the I/O operation + * @param <A> The type of the object attached to the I/O operation + * + * @since 1.7 + */ + +public interface CompletionHandler<V,A> { + + /** + * Invoked when an operation has completed. + * + * @param result + * The result of the I/O operation. + * @param attachment + * The object attached to the I/O operation when it was initiated. + */ + void completed(V result, A attachment); + + /** + * Invoked when an operation fails. + * + * @param exc + * The exception + * @param attachment + * The object attached to the I/O operation when it was initiated. + */ + void failed(Throwable exc, A attachment); + + /** + * Invoked when an operation is cancelled by invoking the {@link + * java.util.concurrent.Future#cancel cancel} method. + * + * @param attachment + * The object attached to the I/O operation when it was initiated. + */ + void cancelled(A attachment); +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/DatagramChannel.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,223 @@ +/* + * Copyright 2000-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.channels; + +import java.io.IOException; +import java.net.DatagramSocket; +import java.net.SocketAddress; +import java.nio.ByteBuffer; + +import org.classpath.icedtea.java.net.ProtocolFamily; +import org.classpath.icedtea.java.net.SocketOption; + +import org.classpath.icedtea.java.nio.channels.spi.SelectorProvider; + +/** + * A selectable channel for datagram-oriented sockets. + * + * <p> {@note revised} A datagram channel is created by invoking one of the {@link #open open} methods + * of this class. It is not possible to create a channel for an arbitrary, + * pre-existing datagram socket. A newly-created datagram channel is open but not + * connected. A datagram channel need not be connected in order for the {@link #send + * send} and {@link #receive receive} methods to be used. A datagram channel may be + * connected, by invoking its {@link #connect connect} method, in order to + * avoid the overhead of the security checks are otherwise performed as part of + * every send and receive operation. A datagram channel must be connected in + * order to use the {@link #read(java.nio.ByteBuffer) read} and {@link + * #write(java.nio.ByteBuffer) write} methods, since those methods do not + * accept or return socket addresses. + * + * <p> Once connected, a datagram channel remains connected until it is + * disconnected or closed. Whether or not a datagram channel is connected may + * be determined by invoking its {@link #isConnected isConnected} method. + * + * <p> Socket options are configured using the {@link #setOption(SocketOption,Object) + * setOption} method. A datagram channel to an Internet Protocol socket supports + * the following options: + * <blockquote> + * <table border> + * <tr> + * <th>Option Name</th> + * <th>Description</th> + * </tr> + * <tr> + * <td> {@link java.net.StandardSocketOption#SO_SNDBUF SO_SNDBUF} </td> + * <td> The size of the socket send buffer </td> + * </tr> + * <tr> + * <td> {@link java.net.StandardSocketOption#SO_RCVBUF SO_RCVBUF} </td> + * <td> The size of the socket receive buffer </td> + * </tr> + * <tr> + * <td> {@link java.net.StandardSocketOption#SO_REUSEADDR SO_REUSEADDR} </td> + * <td> Re-use address </td> + * </tr> + * <tr> + * <td> {@link java.net.StandardSocketOption#SO_BROADCAST SO_BROADCAST} </td> + * <td> Allow transmission of broadcast datagrams </td> + * </tr> + * <tr> + * <td> {@link java.net.StandardSocketOption#IP_TOS IP_TOS} </td> + * <td> The Type of Service (ToS) octet in the Internet Protocol (IP) header </td> + * </tr> + * <tr> + * <td> {@link java.net.StandardSocketOption#IP_MULTICAST_IF IP_MULTICAST_IF} </td> + * <td> The network interface for Internet Protocol (IP) multicast datagrams </td> + * </tr> + * <tr> + * <td> {@link java.net.StandardSocketOption#IP_MULTICAST_TTL + * IP_MULTICAST_TTL} </td> + * <td> The <em>time-to-live</em> for Internet Protocol (IP) multicast + * datagrams </td> + * </tr> + * <tr> + * <td> {@link java.net.StandardSocketOption#IP_MULTICAST_LOOP + * IP_MULTICAST_LOOP} </td> + * <td> Loopback for Internet Protocol (IP) multicast datagrams </td> + * </tr> + * </table> + * </blockquote> + * Additional (implementation specific) options may also be supported. + * + * <p> Datagram channels are safe for use by multiple concurrent threads. They + * support concurrent reading and writing, though at most one thread may be + * reading and at most one thread may be writing at any given time. </p> + * + * @author Mark Reinhold + * @author JSR-51 Expert Group + * @since 1.4 + * @updated 1.7 + */ + +public abstract class DatagramChannel + extends java.nio.channels.DatagramChannel + implements MulticastChannel +{ + + /** + * Initializes a new instance of this class. + */ + protected DatagramChannel(SelectorProvider provider) { + super(provider); + } + + /** + * Opens a datagram channel. + * + * <p> The new channel is created by invoking the {@link + * java.nio.channels.spi.SelectorProvider#openDatagramChannel() + * openDatagramChannel} method of the system-wide default {@link + * java.nio.channels.spi.SelectorProvider} object. The channel will not be + * connected. </p> + * + * @return A new datagram channel + * + * @throws IOException + * If an I/O error occurs + */ + public static DatagramChannel open() throws IOException { + return SelectorProvider.provider().openDatagramChannel(); + } + + /** + * Opens a datagram channel. + * + * <p> The {@code family} parameter is used to specify the {@link + * ProtocolFamily}. If the datagram channel is to be used for IP multicasing + * then this should correspond to the address type of the multicast groups + * that this channel will join. + * + * <p> The new channel is created by invoking the {@link + * java.nio.channels.spi.SelectorProvider#openDatagramChannel(ProtocolFamily) + * openDatagramChannel} method of the system-wide default {@link + * java.nio.channels.spi.SelectorProvider} object. The channel will not be + * connected. + * + * @param family + * The protocol family + * + * @return A new datagram channel + * + * @throws UnsupportedOperationException + * If the specified protocol family is not supported. For example, + * suppose the parameter is specified as {@link + * java.net.StandardProtocolFamily#INET6 StandardProtocolFamily.INET6} + * but IPv6 is not enabled on the platform. + * @throws IOException + * If an I/O error occurs + * + * @since 1.7 + */ + public static DatagramChannel open(ProtocolFamily family) throws IOException { + return SelectorProvider.provider().openDatagramChannel(family); + } + + + // -- Socket-specific operations -- + + /** + * @throws AlreadyBoundException {@inheritDoc} + * @throws UnsupportedAddressTypeException {@inheritDoc} + * @throws ClosedChannelException {@inheritDoc} + * @throws IOException {@inheritDoc} + * @throws SecurityException + * If a security manager has been installed and its {@link + * SecurityManager#checkListen checkListen} method denies the + * operation + * + * @since 1.7 + */ + public abstract DatagramChannel bind(SocketAddress local) + throws IOException; + + /** + * @throws IllegalArgumentException {@inheritDoc} + * @throws ClosedChannelException {@inheritDoc} + * @throws IOException {@inheritDoc} + * + * @since 1.7 + */ + public abstract <T> DatagramChannel setOption(SocketOption<T> name, T value) + throws IOException; + + /** + * {@note new} + * Returns the remote address to which this channel's socket is connected. + * + * @return The remote address; {@code null} if the channel's socket is not + * connected + * + * @throws ClosedChannelException + * If the channel is closed + * @throws IOException + * If an I/O error occurs + * + * @since 1.7 + */ + public abstract SocketAddress getRemoteAddress() throws IOException; + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/FileChannel.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,404 @@ +/* + * Copyright 2000-2005 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.channels; + +import java.io.*; +import java.nio.ByteBuffer; +import java.nio.MappedByteBuffer; +import java.nio.channels.GatheringByteChannel; +import java.nio.channels.ReadableByteChannel; +import java.nio.channels.ScatteringByteChannel; +import java.nio.channels.WritableByteChannel; +import java.nio.channels.spi.AbstractInterruptibleChannel; +import java.util.Set; +import java.util.HashSet; +import java.util.Collections; + +import org.classpath.icedtea.java.nio.file.OpenOption; +import org.classpath.icedtea.java.nio.file.Path; +import org.classpath.icedtea.java.nio.file.attribute.FileAttribute; +import org.classpath.icedtea.java.nio.file.spi.FileSystemProvider; + +/** + * A channel for reading, writing, mapping, and manipulating a file. + * + * <p> {@note revised} + * A file channel is a {@link SeekableByteChannel} that is connected to + * a file. It has a current <i>position</i> within its file which can + * be both {@link #position() <i>queried</i>} and {@link #position(long) + * <i>modified</i>}. The file itself contains a variable-length sequence + * of bytes that can be read and written and whose current {@link #size + * <i>size</i>} can be queried. The size of the file increases + * when bytes are written beyond its current size; the size of the file + * decreases when it is {@link #truncate </code><i>truncated</i><code>}. The + * file may also have some associated <i>metadata</i> such as access + * permissions, content type, and last-modification time; this class does not + * define methods for metadata access. + * + * <p> In addition to the familiar read, write, and close operations of byte + * channels, this class defines the following file-specific operations: </p> + * + * <ul> + * + * <li><p> Bytes may be {@link #read(ByteBuffer, long) read} or + * {@link #write(ByteBuffer, long) <i>written</i>} at an absolute + * position in a file in a way that does not affect the channel's current + * position. </p></li> + * + * <li><p> A region of a file may be {@link #map <i>mapped</i>} + * directly into memory; for large files this is often much more efficient + * than invoking the usual <tt>read</tt> or <tt>write</tt> methods. + * </p></li> + * + * <li><p> Updates made to a file may be {@link #force <i>forced + * out</i>} to the underlying storage device, ensuring that data are not + * lost in the event of a system crash. </p></li> + * + * <li><p> Bytes can be transferred from a file {@link #transferTo <i>to + * some other channel</i>}, and {@link #transferFrom <i>vice + * versa</i>}, in a way that can be optimized by many operating systems + * into a very fast transfer directly to or from the filesystem cache. + * </p></li> + * + * <li><p> A region of a file may be {@link FileLock <i>locked</i>} + * against access by other programs. </p></li> + * + * </ul> + * + * <p> File channels are safe for use by multiple concurrent threads. The + * {@link Channel#close close} method may be invoked at any time, as specified + * by the {@link Channel} interface. Only one operation that involves the + * channel's position or can change its file's size may be in progress at any + * given time; attempts to initiate a second such operation while the first is + * still in progress will block until the first operation completes. Other + * operations, in particular those that take an explicit position, may proceed + * concurrently; whether they in fact do so is dependent upon the underlying + * implementation and is therefore unspecified. + * + * <p> The view of a file provided by an instance of this class is guaranteed + * to be consistent with other views of the same file provided by other + * instances in the same program. The view provided by an instance of this + * class may or may not, however, be consistent with the views seen by other + * concurrently-running programs due to caching performed by the underlying + * operating system and delays induced by network-filesystem protocols. This + * is true regardless of the language in which these other programs are + * written, and whether they are running on the same machine or on some other + * machine. The exact nature of any such inconsistencies are system-dependent + * and are therefore unspecified. + * + * <p> A file channel is created by invoking one of the {@link #open open} + * methods defined by this class. A file channel can also be obtained from an + * existing {@link java.io.FileInputStream#getChannel FileInputStream}, {@link + * java.io.FileOutputStream#getChannel FileOutputStream}, or {@link + * java.io.RandomAccessFile#getChannel RandomAccessFile} object by invoking + * that object's <tt>getChannel</tt> method, which returns a file channel that + * is connected to the same underlying file. Where the file channel is obtained + * from an existing stream or random access file then the state of the file + * channel is intimately connected to that of the object whose <tt>getChannel</tt> + * method returned the channel. Changing the channel's position, whether + * explicitly or by reading or writing bytes, will change the file position of + * the originating object, and vice versa. Changing the file's length via the + * file channel will change the length seen via the originating object, and vice + * versa. Changing the file's content by writing bytes will change the content + * seen by the originating object, and vice versa. + * + * <a name="open-mode"></a> <p> At various points this class specifies that an + * instance that is "open for reading," "open for writing," or "open for + * reading and writing" is required. A channel obtained via the {@link + * java.io.FileInputStream#getChannel getChannel} method of a {@link + * java.io.FileInputStream} instance will be open for reading. A channel + * obtained via the {@link java.io.FileOutputStream#getChannel getChannel} + * method of a {@link java.io.FileOutputStream} instance will be open for + * writing. Finally, a channel obtained via the {@link + * java.io.RandomAccessFile#getChannel getChannel} method of a {@link + * java.io.RandomAccessFile} instance will be open for reading if the instance + * was created with mode <tt>"r"</tt> and will be open for reading and writing + * if the instance was created with mode <tt>"rw"</tt>. + * + * <a name="append-mode"></a><p> A file channel that is open for writing may be in + * <i>append mode</i>, for example if it was obtained from a file-output stream + * that was created by invoking the {@link + * java.io.FileOutputStream#FileOutputStream(java.io.File,boolean) + * FileOutputStream(File,boolean)} constructor and passing <tt>true</tt> for + * the second parameter. In this mode each invocation of a relative write + * operation first advances the position to the end of the file and then writes + * the requested data. Whether the advancement of the position and the writing + * of the data are done in a single atomic operation is system-dependent and + * therefore unspecified. + * + * @see java.io.FileInputStream#getChannel() + * @see java.io.FileOutputStream#getChannel() + * @see java.io.RandomAccessFile#getChannel() + * + * @author Mark Reinhold + * @author Mike McCloskey + * @author JSR-51 Expert Group + * @since 1.4 + * @updated 1.7 + */ + +public abstract class FileChannel + extends java.nio.channels.FileChannel + implements SeekableByteChannel +{ + /** + * Initializes a new instance of this class. + */ + protected FileChannel() { } + + /** + * {@note new} + * Opens or creates a file, returning a file channel to access the file. + * + * <p> The {@code options} parameter determines how the file is opened. + * The {@link StandardOpenOption#READ READ} and {@link StandardOpenOption#WRITE + * WRITE} options determine if the file should be opened for reading and/or + * writing. If neither option (or the {@link StandardOpenOption#APPEND APPEND} + * option) is contained in the array then the file is opened for reading. + * By default reading or writing commences at the beginning of the file. + * + * <p> In the addition to {@code READ} and {@code WRITE}, the following + * options may be present: + * + * <table border=1 cellpadding=5 summary=""> + * <tr> <th>Option</th> <th>Description</th> </tr> + * <tr> + * <td> {@link StandardOpenOption#APPEND APPEND} </td> + * <td> If this option is present then the file is opened for writing and + * each invocation of the channel's {@code write} method first advances + * the position to the end of the file and then writes the requested + * data. Whether the advancement of the position and the writing of the + * data are done in a single atomic operation is system-dependent and + * therefore unspecified. This option may not be used in conjunction + * with the {@code READ} or {@code TRUNCATE_EXISTING} options. </td> + * </tr> + * <tr> + * <td> {@link StandardOpenOption#TRUNCATE_EXISTING TRUNCATE_EXISTING} </td> + * <td> If this option is present then the existing file is truncated to + * a size of 0 bytes. This option is ignored when the file is opened only + * for reading. </td> + * </tr> + * <tr> + * <td> {@link StandardOpenOption#CREATE_NEW CREATE_NEW} </td> + * <td> If this option is present then a new file is created, failing if + * the file already exists. When creating a file the check for the + * existence of the file and the creation of the file if it does not exist + * is atomic with respect to other file system operations. This option is + * ignored when the file is opened only for reading. </td> + * </tr> + * <tr> + * <td > {@link StandardOpenOption#CREATE CREATE} </td> + * <td> If this option is present then an existing file is opened if it + * exists, otherwise a new file is created. When creating a file the check + * for the existence of the file and the creation of the file if it does + * not exist is atomic with respect to other file system operations. This + * option is ignored if the {@code CREATE_NEW} option is also present or + * the file is opened only for reading. </td> + * </tr> + * <tr> + * <td > {@link StandardOpenOption#DELETE_ON_CLOSE DELETE_ON_CLOSE} </td> + * <td> When this option is present then the implementation makes a + * <em>best effort</em> attempt to delete the file when closed by the + * the {@link #close close} method. If the {@code close} method is not + * invoked then a <em>best effort</em> attempt is made to delete the file + * when the Java virtual machine terminates. </td> + * </tr> + * <tr> + * <td>{@link StandardOpenOption#SPARSE SPARSE} </td> + * <td> When creating a new file this option is a <em>hint</em> that the + * new file will be sparse. This option is ignored when not creating + * a new file. </td> + * </tr> + * <tr> + * <td> {@link StandardOpenOption#SYNC SYNC} </td> + * <td> Requires that every update to the file's content or metadata be + * written synchronously to the underlying storage device. (see <a + * href="../file/package-summary.html#integrity"> Synchronized I/O file + * integrity</a>). </td> + * <tr> + * <tr> + * <td> {@link StandardOpenOption#DSYNC DSYNC} </td> + * <td> Requires that every update to the file's content be written + * synchronously to the underlying storage device. (see <a + * href="../file/package-summary.html#integrity"> Synchronized I/O file + * integrity</a>). </td> + * </tr> + * </table> + * + * <p> An implementation may also support additional options. + * + * <p> The {@code attrs} parameter is an optional array of file {@link + * FileAttribute file-attributes} to set atomically when creating the file. + * + * <p> The new channel is created by invoking the {@link + * FileSystemProvider#newFileChannel newFileChannel} method on the + * provider that created the {@code Path}. + * + * @param file + * The path of the file to open or create + * @param options + * Options specifying how the file is opened + * @param attrs + * An optional list of file attributes to set atomically when + * creating the file + * + * @return A new file channel + * + * @throws IllegalArgumentException + * If the set contains an invalid combination of options + * @throws UnsupportedOperationException + * If the {@code file} is associated with a provider that does not + * support creating file channels, or an unsupported open option is + * specified, or the array contains an attribute that cannot be set + * atomically when creating the file + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * If a security manager is installed and it denies an + * unspecified permission required by the implementation. + * In the case of the default provider, the {@link + * SecurityManager#checkRead(String)} method is invoked to check + * read access if the file is opened for reading. The {@link + * SecurityManager#checkWrite(String)} method is invoked to check + * write access if the file is opened for writing + * + * @since 1.7 + */ + public static FileChannel open(Path file, + Set<? extends OpenOption> options, + FileAttribute<?>... attrs) + throws IOException + { + FileSystemProvider provider = file.getFileSystem().provider(); + return provider.newFileChannel(file, options, attrs); + } + + private static final FileAttribute<?>[] NO_ATTRIBUTES = new FileAttribute[0]; + + /** + * {@note new} + * Opens or creates a file, returning a file channel to access the file. + * + * <p> An invocation of this method behaves in exactly the same way as the + * invocation + * <pre> + * fc.{@link #open(Path,Set,FileAttribute[]) open}(file, options, new FileAttribute<?>[0]); + * </pre> + * + * @param file + * The path of the file to open or create + * @param options + * Options specifying how the file is opened + * + * @return A new file channel + * + * @throws IllegalArgumentException + * If the set contains an invalid combination of options + * @throws UnsupportedOperationException + * If the {@code file} is associated with a provider that does not + * support creating file channels, or an unsupported open option is + * specified + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * If a security manager is installed and it denies an + * unspecified permission required by the implementation. + * In the case of the default provider, the {@link + * SecurityManager#checkRead(String)} method is invoked to check + * read access if the file is opened for reading. The {@link + * SecurityManager#checkWrite(String)} method is invoked to check + * write access if the file is opened for writing + * + * @since 1.7 + */ + public static FileChannel open(Path file, OpenOption... options) + throws IOException + { + Set<OpenOption> set = new HashSet<OpenOption>(options.length); + Collections.addAll(set, options); + return open(file, set, NO_ATTRIBUTES); + } + + /** + * Sets this channel's file position. + * + * <p> Setting the position to a value that is greater than the file's + * current size is legal but does not change the size of the file. A later + * attempt to read bytes at such a position will immediately return an + * end-of-file indication. A later attempt to write bytes at such a + * position will cause the file to be grown to accommodate the new bytes; + * the values of any bytes between the previous end-of-file and the + * newly-written bytes are unspecified. </p> + * + * @param newPosition + * The new position, a non-negative integer counting + * the number of bytes from the beginning of the file + * + * @return This file channel + * + * @throws ClosedChannelException + * If this channel is closed + * + * @throws IllegalArgumentException + * If the new position is negative + * + * @throws IOException + * If some other I/O error occurs + */ + public abstract FileChannel positionSBC(long newPosition) throws IOException; + + /** + * Truncates this channel's file to the given size. + * + * <p> If the given size is less than the file's current size then the file + * is truncated, discarding any bytes beyond the new end of the file. If + * the given size is greater than or equal to the file's current size then + * the file is not modified. In either case, if this channel's file + * position is greater than the given size then it is set to that size. + * </p> + * + * @param size + * The new size, a non-negative byte count + * + * @return This file channel + * + * @throws NonWritableChannelException + * If this channel was not opened for writing + * + * @throws ClosedChannelException + * If this channel is closed + * + * @throws IllegalArgumentException + * If the new size is negative + * + * @throws IOException + * If some other I/O error occurs + */ + public abstract FileChannel truncateSBC(long size) throws IOException; + + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/FileLock.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,321 @@ +/* + * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.channels; + +import java.io.IOException; + +import java.nio.channels.Channel; + +/** + * A token representing a lock on a region of a file. + * + * <p> A file-lock object is created each time a lock is acquired on a file via + * one of the {@link FileChannel#lock(long,long,boolean) lock} or {@link + * FileChannel#tryLock(long,long,boolean) tryLock} methods of the + * {@link FileChannel} class, or the {@link + * AsynchronousFileChannel#lock(long,long,boolean,Object,CompletionHandler) lock} + * or {@link AsynchronousFileChannel#tryLock(long,long,boolean) tryLock} + * methods of the {@link AsynchronousFileChannel} class. + * + * <p> A file-lock object is initially valid. It remains valid until the lock + * is released by invoking the {@link #release release} method, by closing the + * channel that was used to acquire it, or by the termination of the Java + * virtual machine, whichever comes first. The validity of a lock may be + * tested by invoking its {@link #isValid isValid} method. + * + * <p> A file lock is either <i>exclusive</i> or <i>shared</i>. A shared lock + * prevents other concurrently-running programs from acquiring an overlapping + * exclusive lock, but does allow them to acquire overlapping shared locks. An + * exclusive lock prevents other programs from acquiring an overlapping lock of + * either type. Once it is released, a lock has no further effect on the locks + * that may be acquired by other programs. + * + * <p> Whether a lock is exclusive or shared may be determined by invoking its + * {@link #isShared isShared} method. Some platforms do not support shared + * locks, in which case a request for a shared lock is automatically converted + * into a request for an exclusive lock. + * + * <p> The locks held on a particular file by a single Java virtual machine do + * not overlap. The {@link #overlaps overlaps} method may be used to test + * whether a candidate lock range overlaps an existing lock. + * + * <p> A file-lock object records the file channel upon whose file the lock is + * held, the type and validity of the lock, and the position and size of the + * locked region. Only the validity of a lock is subject to change over time; + * all other aspects of a lock's state are immutable. + * + * <p> File locks are held on behalf of the entire Java virtual machine. + * They are not suitable for controlling access to a file by multiple + * threads within the same virtual machine. + * + * <p> File-lock objects are safe for use by multiple concurrent threads. + * + * + * <a name="pdep"><h4> Platform dependencies </h4></a> + * + * <p> This file-locking API is intended to map directly to the native locking + * facility of the underlying operating system. Thus the locks held on a file + * should be visible to all programs that have access to the file, regardless + * of the language in which those programs are written. + * + * <p> Whether or not a lock actually prevents another program from accessing + * the content of the locked region is system-dependent and therefore + * unspecified. The native file-locking facilities of some systems are merely + * <i>advisory</i>, meaning that programs must cooperatively observe a known + * locking protocol in order to guarantee data integrity. On other systems + * native file locks are <i>mandatory</i>, meaning that if one program locks a + * region of a file then other programs are actually prevented from accessing + * that region in a way that would violate the lock. On yet other systems, + * whether native file locks are advisory or mandatory is configurable on a + * per-file basis. To ensure consistent and correct behavior across platforms, + * it is strongly recommended that the locks provided by this API be used as if + * they were advisory locks. + * + * <p> On some systems, acquiring a mandatory lock on a region of a file + * prevents that region from being {@link java.nio.channels.FileChannel#map + * <i>mapped into memory</i>}, and vice versa. Programs that combine + * locking and mapping should be prepared for this combination to fail. + * + * <p> On some systems, closing a channel releases all locks held by the Java + * virtual machine on the underlying file regardless of whether the locks were + * acquired via that channel or via another channel open on the same file. It + * is strongly recommended that, within a program, a unique channel be used to + * acquire all locks on any given file. + * + * <p> Some network filesystems permit file locking to be used with + * memory-mapped files only when the locked regions are page-aligned and a + * whole multiple of the underlying hardware's page size. Some network + * filesystems do not implement file locks on regions that extend past a + * certain position, often 2<sup>30</sup> or 2<sup>31</sup>. In general, great + * care should be taken when locking files that reside on network filesystems. + * + * + * @author Mark Reinhold + * @author JSR-51 Expert Group + * @since 1.4 + * @updated 1.7 + */ + +public abstract class FileLock { + + private final Channel channel; + private final long position; + private final long size; + private final boolean shared; + + /** + * Initializes a new instance of this class. </p> + * + * @param channel + * The file channel upon whose file this lock is held + * + * @param position + * The position within the file at which the locked region starts; + * must be non-negative + * + * @param size + * The size of the locked region; must be non-negative, and the sum + * <tt>position</tt> + <tt>size</tt> must be non-negative + * + * @param shared + * <tt>true</tt> if this lock is shared, + * <tt>false</tt> if it is exclusive + * + * @throws IllegalArgumentException + * If the preconditions on the parameters do not hold + */ + protected FileLock(FileChannel channel, + long position, long size, boolean shared) + { + if (position < 0) + throw new IllegalArgumentException("Negative position"); + if (size < 0) + throw new IllegalArgumentException("Negative size"); + if (position + size < 0) + throw new IllegalArgumentException("Negative position + size"); + this.channel = channel; + this.position = position; + this.size = size; + this.shared = shared; + } + + /** + * {@note new} Initializes a new instance of this class. + * + * @param channel + * The channel upon whose file this lock is held + * + * @param position + * The position within the file at which the locked region starts; + * must be non-negative + * + * @param size + * The size of the locked region; must be non-negative, and the sum + * <tt>position</tt> + <tt>size</tt> must be non-negative + * + * @param shared + * <tt>true</tt> if this lock is shared, + * <tt>false</tt> if it is exclusive + * + * @throws IllegalArgumentException + * If the preconditions on the parameters do not hold + * + * @since 1.7 + */ + protected FileLock(AsynchronousFileChannel channel, + long position, long size, boolean shared) + { + if (position < 0) + throw new IllegalArgumentException("Negative position"); + if (size < 0) + throw new IllegalArgumentException("Negative size"); + if (position + size < 0) + throw new IllegalArgumentException("Negative position + size"); + this.channel = channel; + this.position = position; + this.size = size; + this.shared = shared; + } + + /** + * {@note revised} + * Returns the file channel upon whose file this lock was acquired. + * + * <p> This method has been superseded by the {@link #acquiredBy acquiredBy} + * method. + * + * @return The file channel, or {@code null} if the file lock was not + * acquired by a file channel. + */ + public final FileChannel channel() { + return (channel instanceof FileChannel) ? (FileChannel)channel : null; + } + + /** + * {@note new} + * Returns the channel upon whose file this lock was acquired. + * + * @return The channel upon whose file this lock was acquired. + * + * @since 1.7 + */ + public Channel acquiredBy() { + return channel; + } + + /** + * Returns the position within the file of the first byte of the locked + * region. + * + * <p> A locked region need not be contained within, or even overlap, the + * actual underlying file, so the value returned by this method may exceed + * the file's current size. </p> + * + * @return The position + */ + public final long position() { + return position; + } + + /** + * Returns the size of the locked region in bytes. + * + * <p> A locked region need not be contained within, or even overlap, the + * actual underlying file, so the value returned by this method may exceed + * the file's current size. </p> + * + * @return The size of the locked region + */ + public final long size() { + return size; + } + + /** + * Tells whether this lock is shared. </p> + * + * @return <tt>true</tt> if lock is shared, + * <tt>false</tt> if it is exclusive + */ + public final boolean isShared() { + return shared; + } + + /** + * Tells whether or not this lock overlaps the given lock range. </p> + * + * @return <tt>true</tt> if, and only if, this lock and the given lock + * range overlap by at least one byte + */ + public final boolean overlaps(long position, long size) { + if (position + size <= this.position) + return false; // That is below this + if (this.position + this.size <= position) + return false; // This is below that + return true; + } + + /** + * Tells whether or not this lock is valid. + * + * <p> A lock object remains valid until it is released or the associated + * file channel is closed, whichever comes first. </p> + * + * @return <tt>true</tt> if, and only if, this lock is valid + */ + public abstract boolean isValid(); + + /** + * Releases this lock. + * + * <p> If this lock object is valid then invoking this method releases the + * lock and renders the object invalid. If this lock object is invalid + * then invoking this method has no effect. </p> + * + * @throws ClosedChannelException + * If the channel that was used to acquire this lock + * is no longer open + * + * @throws IOException + * If an I/O error occurs + */ + public abstract void release() throws IOException; + + /** + * Returns a string describing the range, type, and validity of this lock. + * + * @return A descriptive string + */ + public final String toString() { + return (this.getClass().getName() + + "[" + position + + ":" + size + + " " + (shared ? "shared" : "exclusive") + + " " + (isValid() ? "valid" : "invalid") + + "]"); + } + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/MembershipKey.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,183 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.channels; + +import java.net.InetAddress; +import java.net.NetworkInterface; +import java.io.IOException; + +/** + * A token representing the membership of an Internet Protocol (IP) multicast + * group. + * + * <p> A membership key may represent a membership to receive all datagrams sent + * to the group, or it may be <em>source-specific</em>, meaning that it + * represents a membership that receives only datagrams from a specific source + * address. Whether or not a membership key is source-specific may be determined + * by invoking its {@link #sourceAddress() sourceAddress} method. + * + * <p> A membership key is valid upon creation and remains valid until the + * membership is dropped by invoking the {@link #drop() drop} method, or + * the channel is closed. The validity of the membership key may be tested + * by invoking its {@link #isValid() isValid} method. + * + * <p> Where a membership key is not source-specific and the underlying operation + * system supports source filtering, then the {@link #block block} and {@link + * #unblock unblock} methods can be used to block or unblock multicast datagrams + * from particular source addresses. + * + * @see MulticastChannel + * + * @since 1.7 + */ +public abstract class MembershipKey { + + /** + * Initializes a new instance of this class. + */ + protected MembershipKey() { + } + + /** + * Tells whether or not this membership is valid. + * + * <p> A multicast group membership is valid upon creation and remains + * valid until the membership is dropped by invoking the {@link #drop() drop} + * method, or the channel is closed. + * + * @return {@code true} if this membership key is valid, {@code false} + * otherwise + */ + public abstract boolean isValid(); + + /** + * Drop membership. + * + * <p> If the membership key represents a membership to receive all datagrams + * then the membership is dropped and the channel will no longer receive any + * datagrams sent to the group. If the membership key is source-specific + * then the channel will no longer receive datagrams sent to the group from + * that source address. + * + * <p> After membership is dropped it may still be possible to receive + * datagrams sent to the group. This can arise when datagrams are waiting to + * be received in the socket's receive buffer. After membership is dropped + * then the channel may {@link MulticastChannel#join join} the group again + * in which case a new membership key is returned. + * + * <p> Upon return, this membership object will be {@link #isValid() invalid}. + * If the multicast group membership is already invalid then invoking this + * method has no effect. Once a multicast group membership is invalid, + * it remains invalid forever. + * + * @throws IOException + * If an I/O error occurs + */ + public abstract void drop() throws IOException; + + /** + * Block multicast datagrams from the given source address. + * + * <p> If this membership key is not source-specific, and the underlying + * operating system supports source filtering, then this method blocks + * multicast datagrams from the given source address. If the given source + * address is already blocked then this method has no effect. + * After a source address is blocked it may still be possible to receive + * datagams from that source. This can arise when datagrams are waiting to + * be received in the socket's receive buffer. + * + * @param source + * The source address to block + * + * @return This membership key + * + * @throws IllegalArgumentException + * If the {@code source} parameter is not a unicast address or + * is not the same address type as the multicast group + * @throws IllegalStateException + * If this membership key is source-specific or is no longer valid + * @throws UnsupportedOperationException + * If the underlying operating system does not support source + * filtering + * @throws IOException + * If an I/O error occurs + */ + public abstract MembershipKey block(InetAddress source) throws IOException; + + /** + * Unblock multicast datagrams from the given source address that was + * previously blocked using the {@link #block(InetAddress) block} method. + * + * @param source + * The source address to unblock + * + * @return This membership key + * + * @throws IllegalStateException + * If the given source address is not currently blocked or the + * membership key is no longer valid + * @throws IOException + * If an I/O error occurs + */ + public abstract MembershipKey unblock(InetAddress source) throws IOException; + + /** + * Returns the channel for which this membership key was created. This + * method will continue to return the channel even after the membership + * becomes {@link #isValid invalid}. + * + * @return the channel + */ + public abstract MulticastChannel channel(); + + /** + * Returns the multicast group for which this membership key was created. + * This method will continue to return the group even after the membership + * becomes {@link #isValid invalid}. + * + * @return the multicast group + */ + public abstract InetAddress group(); + + /** + * Returns the network interface for which this membership key was created. + * This method will continue to return the network interface even after the + * membership becomes {@link #isValid invalid}. + * + * @return the network interface + */ + public abstract NetworkInterface networkInterface(); + + /** + * Returns the source address if this membership key is source-specific, + * or {@code null} if this membership is not source-specific. + * + * @return The source address if this membership key is source-specific, + * otherwise {@code null} + */ + public abstract InetAddress sourceAddress(); +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/MulticastChannel.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,216 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.channels; + +import java.net.InetAddress; +import java.net.NetworkInterface; +import java.io.IOException; + +import org.classpath.icedtea.java.net.ProtocolFamily; // javadoc +import org.classpath.icedtea.java.net.StandardProtocolFamily; // javadoc +import org.classpath.icedtea.java.net.StandardSocketOption; // javadoc + +/** + * A network channel that supports Internet Protocol (IP) multicasting. + * + * <p> IP multicasting is the transmission of IP datagrams to members of + * a <em>group</em> that is zero or more hosts identified by a single destination + * address. + * + * <p> In the case of a channel to an {@link StandardProtocolFamily#INET IPv4} socket, + * the underlying operating system supports <a href="http://www.ietf.org/rfc/rfc2236.txt"> + * <i>RFC 2236: Internet Group Management Protocol, Version 2 (IGMPv2)</i></a>. + * It may optionally support source filtering as specified by <a + * href="http://www.ietf.org/rfc/rfc3376.txt"> <i>RFC 3376: Internet Group + * Management Protocol, Version 3 (IGMPv3)</i></a>. + * For channels to an {@link StandardProtocolFamily#INET6 IPv6} socket, the equivalent + * standards are <a href="http://www.ietf.org/rfc/rfc2710.txt"> <i>RFC 2710: + * Multicast Listener Discovery (MLD) for IPv6</i></a> and <a + * href="http://www.ietf.org/rfc/rfc3810.txt"> <i>RFC 3810: Multicast Listener + * Discovery Version 2 (MLDv2) for IPv6</i></a>. + * + * <p> The {@link #join(InetAddress,NetworkInterface)} method is used to + * join a group and receive all multicast datagrams sent to the group. A channel + * may join several multicast groups and may join the same group on several + * {@link NetworkInterface interfaces}. Membership is dropped by invoking the {@link + * MembershipKey#drop drop} method on the returned {@link MembershipKey}. If the + * underlying platform supports source filtering then the {@link MembershipKey#block + * block} and {@link MembershipKey#unblock unblock} methods can be used to block or + * unblock multicast datagrams from particular source addresses. + * + * <p> The {@link #join(InetAddress,NetworkInterface,InetAddress)} method + * is used to begin receiving datagrams sent to a group whose source address matches + * a given source address. This method throws {@link UnsupportedOperationException} + * if the underlying platform does not support source filtering. Membership is + * <em>cumulative</em> and this method may be invoked again with the same group + * and interface to allow receiving datagrams from other source addresses. The + * method returns a {@link MembershipKey} that represents membership to receive + * datagrams from the given source address. Invoking the key's {@link + * MembershipKey#drop drop} method drops membership so that datagrams from the + * source address can no longer be received. + * + * <h4>Platform dependencies</h4> + * + * The multicast implementation is intended to map directly to the native + * multicasting facility. Consequently, the following items should be considered + * when developing an application that receives IP multicast datagrams: + * + * <ol> + * + * <li><p> The creation of the channel should specify the {@link ProtocolFamily} + * that corresponds to the address type of the multicast groups that the channel + * will join. There is no guarantee that a channel to a socket in one protocol + * family can join and receive multicast datagrams when the address of the + * multicast group corresponds to another protocol family. For example, it is + * implementation specific if a channel to an {@link StandardProtocolFamily#INET6 IPv6} + * socket can join an {@link StandardProtocolFamily#INET IPv4} multicast group and receive + * multicast datagrams sent to the group. </p></li> + * + * <li><p> The channel's socket should be bound to the {@link + * InetAddress#isAnyLocalAddress wildcard} address. If the socket is bound to + * a specific address, rather than the wildcard address then it is implementation + * specific if multicast datagrams are received by the socket. </p></li> + * + * <li><p> The {@link StandardSocketOption#SO_REUSEADDR SO_REUSEADDR} option should be + * enabled prior to {@link NetworkChannel#bind binding} the socket. This is + * required to allow multiple members of the group to bind to the same + * address. </p></li> + * + * </ol> + * + * <p> <b>Usage Example:</b> + * <pre> + * // join multicast group on this interface, and also use this + * // interface for outgoing multicast datagrams + * NetworkInterface ni = NetworkInterface.getByName("hme0"); + * + * DatagramChannel dc = DatagramChannel.open(StandardProtocolFamily.INET) + * .setOption(StandardSocketOption.SO_REUSEADDR, true) + * .bind(new InetSocketAddress(5000)) + * .setOption(StandardSocketOption.IP_MULTICAST_IF, ni); + * + * InetAddress group = InetAddress.getByName("225.4.5.6"); + * + * MembershipKey key = dc.join(group, ni); + * </pre> + * + * @since 1.7 + */ + +public interface MulticastChannel + extends NetworkChannel +{ + /** + * Joins a multicast group to begin receiving all datagrams sent to the group, + * returning a membership key. + * + * <p> If this channel is currently a member of the group on the given + * interface to receive all datagrams then the membership key, representing + * that membership, is returned. Otherwise this channel joins the group and + * the resulting new membership key is returned. The resulting membership key + * is not {@link MembershipKey#sourceAddress source-specific}. + * + * <p> A multicast channel may join several multicast groups, including + * the same group on more than one interface. An implementation may impose a + * limit on the number of groups that may be joined at the same time. + * + * @param group + * The multicast address to join + * @param interf + * The network interface on which to join the group + * + * @return The membership key + * + * @throws IllegalArgumentException + * If the group parameter is not a {@link InetAddress#isMulticastAddress + * multicast} address, or the group parameter is an address type + * that is not supported by this channel + * @throws IllegalStateException + * If the channel already has source-specific membership of the + * group on the interface + * @throws UnsupportedOperationException + * If the channel's socket is not an Internet Protocol socket + * @throws ClosedChannelException + * If this channel is closed + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * If a security manager is set, and its + * {@link SecurityManager#checkMulticast(InetAddress) checkMulticast} + * method denies access to the multiast group + */ + MembershipKey join(InetAddress group, NetworkInterface interf) + throws IOException; + + /** + * Joins a multicast group to begin receiving datagrams sent to the group + * from a given source address. + * + * <p> If this channel is currently a member of the group on the given + * interface to receive datagrams from the given source address then the + * membership key, representing that membership, is returned. Otherwise this + * channel joins the group and the resulting new membership key is returned. + * The resulting membership key is {@link MembershipKey#sourceAddress + * source-specific}. + * + * <p> Membership is <em>cumulative</em> and this method may be invoked + * again with the same group and interface to allow receiving datagrams sent + * by other source addresses to the group. + * + * @param group + * The multicast address to join + * @param interf + * The network interface on which to join the group + * @param source + * The source address + * + * @return The membership key + * + * @throws IllegalArgumentException + * If the group parameter is not a {@link + * InetAddress#isMulticastAddress multicast} address, the + * source parameter is not a unicast address, the group + * parameter is an address type that is not supported by this channel, + * or the source parameter is not the same address type as the group + * @throws IllegalStateException + * If the channel is currently a member of the group on the given + * interface to receive all datagrams + * @throws UnsupportedOperationException + * If the channel's socket is not an Internet Protocol socket or + * source filtering is not supported + * @throws ClosedChannelException + * If this channel is closed + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * If a security manager is set, and its + * {@link SecurityManager#checkMulticast(InetAddress) checkMulticast} + * method denies access to the multiast group + */ + MembershipKey join(InetAddress group, NetworkInterface interf, InetAddress source) + throws IOException; +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/NetworkChannel.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,165 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.channels; + +import java.net.SocketAddress; + +import java.nio.channels.Channel; + +import java.util.Set; +import java.io.IOException; + +import org.classpath.icedtea.java.net.SocketOption; + +/** + * A channel to a network socket. + * + * <p> A channel that implements this interface is a channel to a network + * socket. The {@link #bind(SocketAddress) bind} method is used to bind the + * socket to a local {@link SocketAddress address}, the {@link #getLocalAddress() + * getLocalAddress} method returns the address that the socket is bound to, and + * the {@link #setOption(SocketOption,Object) setOption} and {@link + * #getOption(SocketOption) getOption} methods are used to set and query socket + * options. An implementation of this interface should specify the socket options + * that it supports. + * + * <p> The {@link #bind bind} and {@link #setOption setOption} methods that do + * not otherwise have a value to return are specified to return the network + * channel upon which they are invoked. This allows method invocations to be + * chained. Implementations of this interface should specialize the return type + * so that method invocations on the implementation class can be chained. + * + * @since 1.7 + */ + +public interface NetworkChannel + extends Channel +{ + /** + * Binds the channel's socket to a local address. + * + * <p> This method is used to establish an association between the socket and + * a local address. Once an association is established then the socket remains + * bound until the channel is closed. If the {@code local} parameter has the + * value {@code null} then the socket will be bound to an address that is + * assigned automatically. + * + * @param local + * The address to bind the socket, or {@code null} to bind the socket + * to an automatically assigned socket address + * + * @return This channel + * + * @throws AlreadyBoundException + * If the socket is already bound + * @throws UnsupportedAddressTypeException + * If the type of the given address is not supported + * @throws ClosedChannelException + * If the channel is closed + * @throws IOException + * If some other I/O error occurs + * @throws SecurityException + * If a security manager is installed and it denies an unspecified + * permission. An implementation of this interface should specify + * any required permissions. + * + * @see #getLocalAddress + */ + NetworkChannel bind(SocketAddress local) throws IOException; + + /** + * Returns the socket address that this channel's socket is bound to, or + * {@code null} if the socket is not bound. + * + * <p> Where the channel is {@link #bind bound} to an Internet Protocol + * socket address then the return value from this method is of type {@link + * java.net.InetSocketAddress}. + * + * @return The socket address that the socket is bound to, or {@code null} + * if the channel's socket is not bound + * + * @throws ClosedChannelException + * If the channel is closed + * @throws IOException + * If an I/O error occurs + */ + SocketAddress getLocalAddress() throws IOException; + + /** + * Sets the value of a socket option. + * + * @param name + * The socket option + * @param value + * The value of the socket option. A value of {@code null} may be + * a valid value for some socket options. + * + * @return This channel + * + * @throws UnsupportedOperationException + * If the socket option is not supported by this channel + * @throws IllegalArgumentException + * If the value is not a valid value for this socket option + * @throws ClosedChannelException + * If this channel is closed + * @throws IOException + * If an I/O error occurs + * + * @see java.net.StandardSocketOption + */ + <T> NetworkChannel setOption(SocketOption<T> name, T value) throws IOException; + + /** + * Returns the value of a socket option. + * + * @param name + * The socket option + * + * @return The value of the socket option. A value of {@code null} may be + * a valid value for some socket options. + * + * @throws UnsupportedOperationException + * If the socket option is not supported by this channel + * @throws ClosedChannelException + * If this channel is closed + * @throws IOException + * If an I/O error occurs + * + * @see java.net.StandardSocketOption + */ + <T> T getOption(SocketOption<T> name) throws IOException; + + /** + * Returns a set of the socket options supported by this channel. + * + * <p> This method will continue to return the set of options even after the + * channel has been closed. + * + * @return A set of the socket options supported by this channel + */ + Set<SocketOption<?>> supportedOptions(); +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/SeekableByteChannel.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,170 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.channels; + +import java.nio.ByteBuffer; +import java.nio.channels.ByteChannel; +import java.io.IOException; + +/** + * A byte channel that maintains a current <i>position</i> and allows the + * position to be changed. + * + * <p> A seekable byte channel is connected to an entity, typically a file, + * that contains a variable-length sequence of bytes that can be read and + * written. The current position can be {@link #position() <i>queried</i>} and + * {@link #position(long) <i>modified</i>}. The channel also provides access to + * the current <i>size</i> of the entity to which the channel is connected. The + * size increases when bytes are written beyond its current size; the size + * decreases when it is {@link #truncate <i>truncated</i>}. + * + * <p> The {@link #position(long) position} and {@link #truncate truncate} methods + * which do not otherwise have a value to return are specified to return the + * channel upon which they are invoked. This allows method invocations to be + * chained. Implementations of this interface should specialize the return type + * so that method invocations on the implementation class can be chained. + * + * @since 1.7 + * @see java.nio.file.FileRef#newByteChannel + */ + +public interface SeekableByteChannel + extends ByteChannel +{ + /** + * Reads a sequence of bytes from this channel into the given buffer. + * + * <p> Bytes are read starting at this channel's current position, and + * then the position is updated with the number of bytes actually read. + * Otherwise this method behaves exactly as specified in the {@link + * ReadableByteChannel} interface. + */ + + int read(ByteBuffer dst) throws IOException; + + /** + * Writes a sequence of bytes to this channel from the given buffer. + * + * <p> Bytes are written starting at this channel's current position, unless + * the channel is connected to an entity such as a file that is opened with + * the {@link java.nio.file.StandardOpenOption#APPEND APPEND} option, in + * which case the position is first advanced to the end. The entity to which + * the channel is connected is grown, if necessary, to accommodate the + * written bytes, and then the position is updated with the number of bytes + * actually written. Otherwise this method behaves exactly as specified by + * the {@link WritableByteChannel} interface. + */ + + int write(ByteBuffer src) throws IOException; + + /** + * Returns this channel's position. + * + * @return This channel's position, + * a non-negative integer counting the number of bytes + * from the beginning of the entity to the current position + * + * @throws ClosedChannelException + * If this channel is closed + * @throws IOException + * If some other I/O error occurs + */ + long position() throws IOException; + + /** + * Sets this channel's position. + * + * <p> Setting the position to a value that is greater than the current size + * is legal but does not change the size of the entity. A later attempt to + * read bytes at such a position will immediately return an end-of-file + * indication. A later attempt to write bytes at such a position will cause + * the entity to grow to accommodate the new bytes; the values of any bytes + * between the previous end-of-file and the newly-written bytes are + * unspecified. + * + * <p> Setting the channel's position is not recommended when connected to + * an entity, typically a file, that is opened with the {@link + * java.nio.file.StandardOpenOption#APPEND APPEND} option. When opened for + * append, the position is first advanced to the end before writing. + * + * @param newPosition + * The new position, a non-negative integer counting + * the number of bytes from the beginning of the entity + * + * @return This channel + * + * @throws ClosedChannelException + * If this channel is closed + * @throws IllegalArgumentException + * If the new position is negative + * @throws IOException + * If some other I/O error occurs + */ + SeekableByteChannel positionSBC(long newPosition) throws IOException; + + /** + * Returns the current size of entity to which this channel is connected. + * + * @return The current size, measured in bytes + * + * @throws ClosedChannelException + * If this channel is closed + * @throws IOException + * If some other I/O error occurs + */ + long size() throws IOException; + + /** + * Truncates the entity, to which this channel is connected, to the given + * size. + * + * <p> If the given size is less than the current size then the entity is + * truncated, discarding any bytes beyond the new end. If the given size is + * greater than or equal to the current size then the entity is not modified. + * In either case, if the current position is greater than the given size + * then it is set to that size. + * + * <p> An implementation of this interface may prohibit truncation when + * connected to an entity, typically a file, opened with the {@link + * java.nio.file.StandardOpenOption#APPEND APPEND} option. + * + * @param size + * The new size, a non-negative byte count + * + * @return This channel + * + * @throws NonWritableChannelException + * If this channel was not opened for writing + * @throws ClosedChannelException + * If this channel is closed + * @throws IllegalArgumentException + * If the new size is negative + * @throws IOException + * If some other I/O error occurs + */ + SeekableByteChannel truncateSBC(long size) throws IOException; +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/exceptions Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,68 @@ +# +# Copyright 2000-2008 Sun Microsystems, Inc. All Rights Reserved. +# 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. Sun designates this +# particular file as subject to the "Classpath" exception as provided +# by Sun in the LICENSE file that accompanied this code. +# +# 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. +# +# Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, +# CA 95054 USA or visit www.sun.com if you need additional information or +# have any questions. +# + +# Generated exception classes for java.nio.channels + +PACKAGE=org.classpath.icedtea.java.nio.channels +# This year should only change if the generated source is modified. +COPYRIGHT_YEARS=2000-2007 +SINCE=1.7 + +SUPER=java.io.IOException + +gen InterruptedByTimeoutException " + * Checked exception received by a thread when a timeout elapses before an + * asynchronous operation completes." \ + -4268008601014042947L + +SUPER=IllegalArgumentException + +gen IllegalChannelGroupException " + * Unchecked exception thrown when an attempt is made to open a channel + * in a group that was not created by the same provider. " \ + -2495041211157744253L + +SUPER=IllegalStateException + +gen AcceptPendingException " + * Unchecked exception thrown when an attempt is made to initiate an accept + * operation on a channel and a previous accept operation has not completed." \ + 2721339977965416421L + +gen ReadPendingException " + * Unchecked exception thrown when an attempt is made to read from an + * asynchronous socket channel and a previous read has not completed." \ + 1986315242191227217L + +gen WritePendingException " + * Unchecked exception thrown when an attempt is made to write to an + * asynchronous socket channel and a previous write has not completed." \ + 7031871839266032276L + +gen ShutdownChannelGroupException " + * Unchecked exception thrown when an attempt is made to construct a channel in + * a group that is shutdown or the completion handler for an I/O operation + * cannot be invoked because the channel group is shutdown." \ + -3903801676350154157L
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/package-info.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,293 @@ +/* + * Copyright 2001-2008 Sun Microsystems, Inc. All Rights Reserved. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/** + * Defines channels, which represent connections to entities that are capable of + * performing I/O operations, such as files and sockets; defines selectors, for + * multiplexed, non-blocking I/O operations. + * + * <a name="channels"></a> + * + * <blockquote><table cellspacing=1 cellpadding=0 summary="Lists channels and their descriptions"> + * <tr><th><p align="left">Channels</p></th><th><p align="left">Description</p></th></tr> + * <tr><td valign=top><tt><i>{@link java.nio.channels.Channel}</i></tt></td> + * <td>A nexus for I/O operations</td></tr> + * <tr><td valign=top><tt> <i>{@link java.nio.channels.ReadableByteChannel}</i></tt></td> + * <td>Can read into a buffer</td></tr> + * <tr><td valign=top><tt> <i>{@link java.nio.channels.ScatteringByteChannel} </i></tt></td> + * <td>Can read into a sequence of buffers</td></tr> + * <tr><td valign=top><tt> <i>{@link java.nio.channels.WritableByteChannel}</i></tt></td> + * <td>Can write from a buffer</td></tr> + * <tr><td valign=top><tt> <i>{@link java.nio.channels.GatheringByteChannel}</i></tt></td> + * <td>Can write from a sequence of buffers</td></tr> + * <tr><td valign=top><tt> <i>{@link java.nio.channels.ByteChannel}</i></tt></td> + * <td>Can read/write to/from a buffer</td></tr> + * <tr><td valign=top><tt> <i>{@link java.nio.channels.SeekableByteChannel}</i></tt></td> + * <td>A {@code ByteChannel} connected to an entity that contains a variable-length sequence of bytes</td></tr> + * <tr><td valign=top><tt> <i>{@link java.nio.channels.AsynchronousChannel}</i></tt></td> + * <td>Supports asynchronous I/O operations.</td></tr> + * <tr><td valign=top><tt> <i>{@link java.nio.channels.AsynchronousByteChannel}</i></tt></td> + * <td>Can read and write bytes asynchronously</td></tr> + * <tr><td valign=top><tt> <i>{@link java.nio.channels.NetworkChannel}</i></tt></td> + * <td>A channel to a network socket</td></tr> + * <tr><td valign=top><tt> <i>{@link java.nio.channels.MulticastChannel}</i></tt></td> + * <td>Can join Internet Protocol (IP) multicast groups</td></tr> + * <tr><td valign=top><tt>{@link org.classpath.icedtea.java.nio.channels.Channels}</tt></td> + * <td>Utility methods for channel/stream interoperation</td></tr> + * </table></blockquote> + * + * <p> A <i>channel</i> represents an open connection to an entity such as a + * hardware device, a file, a network socket, or a program component that is + * capable of performing one or more distinct I/O operations, for example reading + * or writing. As specified in the {@link java.nio.channels.Channel} interface, + * channels are either open or closed, and they are both <i>asynchronously + * closeable</i> and <i>interruptible</i>. + * + * <p> The {@link java.nio.channels.Channel} interface is extended by several + * other interfaces. + * + * <p> The {@link java.nio.channels.ReadableByteChannel} interface specifies a + * {@link java.nio.channels.ReadableByteChannel#read read} method that reads bytes + * from the channel into a buffer; similarly, the {@link + * java.nio.channels.WritableByteChannel} interface specifies a {@link + * java.nio.channels.WritableByteChannel#write write} method that writes bytes + * from a buffer to the channel. The {@link java.nio.channels.ByteChannel} + * interface unifies these two interfaces for the common case of channels that can + * both read and write bytes. The {@link java.nio.channels.SeekableByteChannel} + * interface extends the {@code ByteChannel} interface with methods to {@link + * java.nio.channels.SeekableByteChannel#position() query} and {@link + * java.nio.channels.SeekableByteChannel#position(long) modify} the channel's + * current position, and its {@link java.nio.channels.SeekableByteChannel#size + * size}. + * + * <p> The {@link java.nio.channels.ScatteringByteChannel} and {@link + * java.nio.channels.GatheringByteChannel} interfaces extend the {@link + * java.nio.channels.ReadableByteChannel} and {@link + * java.nio.channels.WritableByteChannel} interfaces, respectively, adding {@link + * java.nio.channels.ScatteringByteChannel#read read} and {@link + * java.nio.channels.GatheringByteChannel#write write} methods that take a + * sequence of buffers rather than a single buffer. + * + * <p> The {@link java.nio.channels.NetworkChannel} interface specifies methods + * to {@link java.nio.channels.NetworkChannel#bind bind} the channel's socket, + * obtain the address to which the socket is bound, and methods to {@link + * java.nio.channels.NetworkChannel#getOption get} and {@link + * java.nio.channels.NetworkChannel#setOption set} socket options. The {@link + * java.nio.channels.MulticastChannel} interface specifies methods to join + * Internet Protocol (IP) multicast groups. + * + * <p> The {@link org.classpath.icedtea.java.nio.channels.Channels} utility class defines static methods + * that support the interoperation of the stream classes of the <tt>{@link + * java.io}</tt> package with the channel classes of this package. An appropriate + * channel can be constructed from an {@link java.io.InputStream} or an {@link + * java.io.OutputStream}, and conversely an {@link java.io.InputStream} or an + * {@link java.io.OutputStream} can be constructed from a channel. A {@link + * java.io.Reader} can be constructed that uses a given charset to decode bytes + * from a given readable byte channel, and conversely a {@link java.io.Writer} can + * be constructed that uses a given charset to encode characters into bytes and + * write them to a given writable byte channel. + * + * <blockquote><table cellspacing=1 cellpadding=0 summary="Lists file channels and their descriptions"> + * <tr><th><p align="left">File channels</p></th><th><p align="left">Description</p></th></tr> + * <tr><td valign=top><tt>{@link org.classpath.icedtea.java.nio.channels.FileChannel}</tt></td> + * <td>Reads, writes, maps, and manipulates files</td></tr> + * <tr><td valign=top><tt>{@link org.classpath.icedtea.java.nio.channels.FileLock}</tt></td> + * <td>A lock on a (region of a) file</td></tr> + * <tr><td valign=top><tt>{@link java.nio.MappedByteBuffer}/{@link java.nio.MappedBigByteBuffer} </tt></td> + * <td>A direct byte buffer or big byte buffer mapped to a region of a file</td></tr> + * </table></blockquote> + * + * <p> The {@link org.classpath.icedtea.java.nio.channels.FileChannel} class supports the usual + * operations of reading bytes from, and writing bytes to, a channel connected to + * a file, as well as those of querying and modifying the current file position + * and truncating the file to a specific size. It defines methods for acquiring + * locks on the whole file or on a specific region of a file; these methods return + * instances of the {@link org.classpath.icedtea.java.nio.channels.FileLock} class. Finally, it defines + * methods for forcing updates to the file to be written to the storage device that + * contains it, for efficiently transferring bytes between the file and other + * channels, and for mapping a region of the file directly into memory. + * + * <p> A {@code FileChannel} is created by invoking one of its static {@link + * java.nio.channels.FileChannel#open open} methods, or by invoking the {@code + * getChannel} method of a {@link java.io.FileInputStream}, {@link + * java.io.FileOutputStream}, or {@link java.io.RandomAccessFile} to return a + * file channel connected to the same underlying file as the <tt>{@link java.io}</tt> + * class. + * + * <a name="multiplex"></a> + * <blockquote><table cellspacing=1 cellpadding=0 summary="Lists multiplexed, non-blocking channels and their descriptions"> + * <tr><th><p align="left">Multiplexed, non-blocking I/O</p></th><th><p align="left">Description</p></th></tr> + * <tr><td valign=top><tt>{@link java.nio.channels.SelectableChannel}</tt></td> + * <td>A channel that can be multiplexed</td></tr> + * <tr><td valign=top><tt> {@link java.nio.channels.DatagramChannel}</tt></td> + * <td>A channel to a datagram-oriented socket</td></tr> + * <tr><td valign=top><tt> {@link java.nio.channels.Pipe.SinkChannel}</tt></td> + * <td>The write end of a pipe</td></tr> + * <tr><td valign=top><tt> {@link java.nio.channels.Pipe.SourceChannel}</tt></td> + * <td>The read end of a pipe</td></tr> + * <tr><td valign=top><tt> {@link java.nio.channels.ServerSocketChannel} </tt></td> + * <td>A channel to a stream-oriented listening socket</td></tr> + * <tr><td valign=top><tt> {@link java.nio.channels.SocketChannel}</tt></td> + * <td>A channel for a stream-oriented connecting socket</td></tr> + * <tr><td valign=top><tt>{@link java.nio.channels.Selector}</tt></td> + * <td>A multiplexor of selectable channels</td></tr> + * <tr><td valign=top><tt>{@link java.nio.channels.SelectionKey}</tt></td> + * <td>A token representing the registration <br> of a channel + * with a selector</td></tr> + * <tr><td valign=top><tt>{@link java.nio.channels.Pipe}</tt></td> + * <td>Two channels that form a unidirectional pipe</td></tr> + * </table></blockquote> + * + * <p> Multiplexed, non-blocking I/O, which is much more scalable than + * thread-oriented, blocking I/O, is provided by <i>selectors</i>, <i>selectable + * channels</i>, and <i>selection keys</i>. + * + * <p> A <a href="Selector.html"><i>selector</i></a> is a multiplexor of <a + * href="SelectableChannel.html"><i>selectable channels</i></a>, which in turn are + * a special type of channel that can be put into <a + * href="SelectableChannel.html#bm"><i>non-blocking mode</i></a>. To perform + * multiplexed I/O operations, one or more selectable channels are first created, + * put into non-blocking mode, and {@link + * java.nio.channels.SelectableChannel#register <i>registered</i>} + * with a selector. Registering a channel specifies the set of I/O operations + * that will be tested for readiness by the selector, and returns a <a + * href="SelectionKey.html"><i>selection key</i></a> that represents the + * registration. + * + * <p> Once some channels have been registered with a selector, a <a + * href="Selector.html#selop"><i>selection operation</i></a> can be performed in + * order to discover which channels, if any, have become ready to perform one or + * more of the operations in which interest was previously declared. If a channel + * is ready then the key returned when it was registered will be added to the + * selector's <i>selected-key set</i>. The key set, and the keys within it, can + * be examined in order to determine the operations for which each channel is + * ready. From each key one can retrieve the corresponding channel in order to + * perform whatever I/O operations are required. + * + * <p> That a selection key indicates that its channel is ready for some operation + * is a hint, but not a guarantee, that such an operation can be performed by a + * thread without causing the thread to block. It is imperative that code that + * performs multiplexed I/O be written so as to ignore these hints when they prove + * to be incorrect. + * + * <p> This package defines selectable-channel classes corresponding to the {@link + * java.net.DatagramSocket}, {@link java.net.ServerSocket}, and {@link + * java.net.Socket} classes defined in the <tt>{@link java.net}</tt> package. + * Minor changes to these classes have been made in order to support sockets that + * are associated with channels. This package also defines a simple class that + * implements unidirectional pipes. In all cases, a new selectable channel is + * created by invoking the static <tt>open</tt> method of the corresponding class. + * If a channel needs an associated socket then a socket will be created as a side + * effect of this operation. + * + * <p> The implementation of selectors, selectable channels, and selection keys + * can be replaced by "plugging in" an alternative definition or instance of the + * {@link java.nio.channels.spi.SelectorProvider} class defined in the <tt>{@link + * java.nio.channels.spi}</tt> package. It is not expected that many developers + * will actually make use of this facility; it is provided primarily so that + * sophisticated users can take advantage of operating-system-specific + * I/O-multiplexing mechanisms when very high performance is required. + * + * <p> Much of the bookkeeping and synchronization required to implement the + * multiplexed-I/O abstractions is performed by the {@link + * java.nio.channels.spi.AbstractInterruptibleChannel}, {@link + * java.nio.channels.spi.AbstractSelectableChannel}, {@link + * java.nio.channels.spi.AbstractSelectionKey}, and {@link + * java.nio.channels.spi.AbstractSelector} classes in the <tt>{@link + * java.nio.channels.spi}</tt> package. When defining a custom selector provider, + * only the {@link java.nio.channels.spi.AbstractSelector} and {@link + * java.nio.channels.spi.AbstractSelectionKey} classes should be subclassed + * directly; custom channel classes should extend the appropriate {@link + * java.nio.channels.SelectableChannel} subclasses defined in this package. + * + * <a name="async"></a> + * + * <blockquote><table cellspacing=1 cellpadding=0 summary="Lists asynchronous channels and their descriptions"> + * <tr><th><p align="left">Asynchronous I/O</p></th><th><p align="left">Description</p></th></tr> + * <tr><td valign=top><tt>{@link org.classpath.icedtea.java.nio.channels.AsynchronousFileChannel}</tt></td> + * <td>An asynchronous channel for reading, writing, and manipulating a file</td></tr> + * <tr><td valign=top><tt>{@link org.classpath.icedtea.java.nio.channels.AsynchronousSocketChannel}</tt></td> + * <td>An asynchronous channel to a stream-oriented connecting socket</td></tr> + * <tr><td valign=top><tt>{@link org.classpath.icedtea.java.nio.channels.AsynchronousServerSocketChannel} </tt></td> + * <td>An asynchronous channel to a stream-oriented listening socket</td></tr> + * <tr><td valign=top><tt>{@link org.classpath.icedtea.java.nio.channels.AsynchronousDatagramChannel}</tt></td> + * <td>An asynchronous channel to a datagram-oriented socket</td></tr> + * <tr><td valign=top><tt>{@link org.classpath.icedtea.java.nio.channels.CompletionHandler}</tt></td> + * <td>A handler for consuming the result of an asynchronous operation</td></tr> + * <tr><td valign=top><tt>{@link org.classpath.icedtea.java.nio.channels.AsynchronousChannelGroup}</tt></td> + * <td>A grouping of asynchronous channels for the purpose of resource sharing</td></tr> + * </table></blockquote> + * + * <p> {@link org.classpath.icedtea.java.nio.channels.AsynchronousChannel Asynchronous channels} are a + * special type of channel capable of asynchronous I/O operations. Asynchronous + * channels are non-blocking and define methods to initiate asynchronous + * operations, returning a {@link java.util.concurrent.Future} representing the + * pending result of each operation. The {@code Future} can be used to poll or + * wait for the result of the operation. Asynchronous I/O operations can also + * specify a {@link org.classpath.icedtea.java.nio.channels.CompletionHandler} to invoke when the + * operation completes. A completion handler is user provided code that is executed + * to consume the result of I/O operation. + * + * <p> This package defines asynchronous-channel classes that are connected to + * a stream-oriented connecting or listening socket, or a datagram-oriented socket. + * It also defines the {@link org.classpath.icedtea.java.nio.channels.AsynchronousFileChannel} class + * for asynchronous reading, writing, and manipulating a file. As with the {@link + * org.classpath.icedtea.java.nio.channels.FileChannel} it supports operations to truncate the file + * to a specific size, force updates to the file to be written to the storage + * device, or acquire locks on the whole file or on a specific region of the file. + * Unlike the {@code FileChannel} it does not define methods for mapping a + * region of the file directly into memory. Where memory mapped I/O is required, + * then a {@code FileChannel} can be used. + * + * <p> Asynchronous channels are bound to an asynchronous channel group for the + * purpose of resource sharing. A group has an associated {@link + * java.util.concurrent.ExecutorService} to which tasks are submitted to handle + * I/O events and dispatch to completion handlers that consume the result of + * asynchronous operations performed on channels in the group. The group can + * optionally be specified when creating the channel or the channel can be bound + * to a <em>default group</em>. Sophisticated users may wish to create their + * own asynchronous channel groups or configure the {@code ExecutorService} + * that will be used for the default group. + * + * <p> As with selectors, the implementatin of asynchronous channels can be + * replaced by "plugging in" an alternative definition or instance of the {@link + * java.nio.channels.spi.AsynchronousChannelProvider} class defined in the + * <tt>{@link java.nio.channels.spi}</tt> package. It is not expected that many + * developers will actually make use of this facility; it is provided primarily + * so that sophisticated users can take advantage of operating-system-specific + * asynchronous I/O mechanisms when very high performance is required. + * + * <hr width="80%"> + * <p> Unless otherwise noted, passing a <tt>null</tt> argument to a constructor + * or method in any class or interface in this package will cause a {@link + * java.lang.NullPointerException NullPointerException} to be thrown. + * + * @since 1.4 + * @updated 1.7 + * @author Mark Reinhold + * @author JSR-51 Expert Group + */ + +package org.classpath.icedtea.java.nio.channels;
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/spi/AsynchronousChannelProvider.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,284 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.channels.spi; + +import java.nio.channels.*; +import java.io.IOException; +import java.util.Iterator; +import java.util.ServiceLoader; +import java.util.ServiceConfigurationError; +import java.util.concurrent.*; +import java.security.AccessController; +import java.security.PrivilegedAction; + +import org.classpath.icedtea.java.net.ProtocolFamily; + +import org.classpath.icedtea.java.nio.channels.AsynchronousChannelGroup; +import org.classpath.icedtea.java.nio.channels.AsynchronousDatagramChannel; +import org.classpath.icedtea.java.nio.channels.AsynchronousServerSocketChannel; +import org.classpath.icedtea.java.nio.channels.AsynchronousSocketChannel; + +/** + * Service-provider class for asynchronous channels. + * + * <p> An asynchronous channel provider is a concrete subclass of this class that + * has a zero-argument constructor and implements the abstract methods specified + * below. A given invocation of the Java virtual machine maintains a single + * system-wide default provider instance, which is returned by the {@link + * #provider() provider} method. The first invocation of that method will locate + * the default provider as specified below. + * + * <p> All of the methods in this class are safe for use by multiple concurrent + * threads. </p> + * + * @since 1.7 + */ + +public abstract class AsynchronousChannelProvider { + + private static final Object lock = new Object(); + private static AsynchronousChannelProvider provider = null; + + private static Void checkPermission() { + SecurityManager sm = System.getSecurityManager(); + if (sm != null) + sm.checkPermission(new RuntimePermission("asynchronousChannelProvider")); + return null; + } + private AsynchronousChannelProvider(Void ignore) { } + + /** + * Initializes a new instance of this class. + * + * @throws SecurityException + * If a security manager has been installed and it denies + * {@link RuntimePermission}<tt>("asynchronousChannelProvider")</tt> + */ + protected AsynchronousChannelProvider() { + this(checkPermission()); + } + + private static boolean loadProviderFromProperty() { + String cn = System.getProperty("org.classpath.icedtea.java.nio.channels.spi.AsynchronousChannelProvider"); + if (cn == null) + return false; + try { + Class<?> c = Class.forName(cn, true, + ClassLoader.getSystemClassLoader()); + provider = (AsynchronousChannelProvider)c.newInstance(); + return true; + } catch (ClassNotFoundException x) { + throw new ServiceConfigurationError(null, x); + } catch (IllegalAccessException x) { + throw new ServiceConfigurationError(null, x); + } catch (InstantiationException x) { + throw new ServiceConfigurationError(null, x); + } catch (SecurityException x) { + throw new ServiceConfigurationError(null, x); + } + } + + private static boolean loadProviderAsService() { + + ServiceLoader<AsynchronousChannelProvider> sl = + ServiceLoader.load(AsynchronousChannelProvider.class, + ClassLoader.getSystemClassLoader()); + Iterator<AsynchronousChannelProvider> i = sl.iterator(); + for (;;) { + try { + if (!i.hasNext()) + return false; + provider = i.next(); + return true; + } catch (ServiceConfigurationError sce) { + if (sce.getCause() instanceof SecurityException) { + // Ignore the security exception, try the next provider + continue; + } + throw sce; + } + } + } + + /** + * Returns the system-wide default asynchronous channel provider for this + * invocation of the Java virtual machine. + * + * <p> The first invocation of this method locates the default provider + * object as follows: </p> + * + * <ol> + * + * <li><p> If the system property + * <tt>java.nio.channels.spi.AsynchronousChannelProvider</tt> is defined + * then it is taken to be the fully-qualified name of a concrete provider class. + * The class is loaded and instantiated; if this process fails then an + * unspecified error is thrown. </p></li> + * + * <li><p> If a provider class has been installed in a jar file that is + * visible to the system class loader, and that jar file contains a + * provider-configuration file named + * <tt>java.nio.channels.spi.AsynchronousChannelProvider</tt> in the resource + * directory <tt>META-INF/services</tt>, then the first class name + * specified in that file is taken. The class is loaded and + * instantiated; if this process fails then an unspecified error is + * thrown. </p></li> + * + * <li><p> Finally, if no provider has been specified by any of the above + * means then the system-default provider class is instantiated and the + * result is returned. </p></li> + * + * </ol> + * + * <p> Subsequent invocations of this method return the provider that was + * returned by the first invocation. </p> + * + * @return The system-wide default AsynchronousChannel provider + */ + public static AsynchronousChannelProvider provider() { + synchronized (lock) { + if (provider != null) { + return provider; + } + return AccessController + .doPrivileged(new PrivilegedAction<AsynchronousChannelProvider>() { + public AsynchronousChannelProvider run() { + if (loadProviderFromProperty()) + return provider; + if (loadProviderAsService()) + return provider; + provider = sun.nio.ch.DefaultAsynchronousChannelProvider.create(); + return provider; + } + }); + } + } + + /** + * The types of thread pool that an asynchronous channel group can be + * constructed with. + * + * @since 1.7 + */ + public static enum ThreadPoolType { + /** + * Fixed thread pool. + * + * @see Executors#newFixedThreadPool + */ + FIXED, + /** + * Cached thread pool. + * + * @see Executors#newCachedThreadPool + */ + CACHED; + } + + /** + * Constructs a new asynchronous channel group. + * + * @param poolType + * The type of thread pool + * @param executor + * The thread pool + * @param nThreads + * The number of threads or initial size, depending on the thread + * pool type. + * + * @throws IllegalArgumentException + * If the {@code nThreads} parameter is invalid for the thread + * pool type + * @throws IOException + * If an I/O error occurs + */ + public AsynchronousChannelGroup openAsynchronousChannelGroup + (ThreadPoolType poolType, ExecutorService executor, int nThreads) throws IOException + { + return null; + } + + /** + * Opens an asynchronous server-socket channel. + * + * @param group + * The group to which the channel is bound, or {@code null} to + * bind to the default group + * + * @return The new channel + * + * @throws IllegalChannelGroupException + * If the provider that created the group differs from this provider + * @throws ShutdownChannelGroupException + * The group is shutdown + * @throws IOException + * If an I/O error occurs + */ + public abstract AsynchronousServerSocketChannel openAsynchronousServerSocketChannel + (AsynchronousChannelGroup group) throws IOException; + + /** + * Opens an asynchronous socket channel. + * + * @param group + * The group to which the channel is bound, or {@code null} to + * bind to the default group + * + * @return The new channel + * + * @throws IllegalChannelGroupException + * If the provider that created the group differs from this provider + * @throws ShutdownChannelGroupException + * The group is shutdown + * @throws IOException + * If an I/O error occurs + */ + public abstract AsynchronousSocketChannel openAsynchronousSocketChannel + (AsynchronousChannelGroup group) throws IOException; + + /** + * Opens an asynchronous datagram channel. + * + * @param family + * The protocol family, or {@code null} for the default protocol + * family + * @param group + * The group to which the channel is bound, or {@code null} to + * bind to the default group + * + * @return The new channel + * + * @throws IllegalChannelGroupException + * If the provider that created the group differs from this provider + * @throws ShutdownChannelGroupException + * The group is shutdown + * @throws IOException + * If an I/O error occurs + */ + public abstract AsynchronousDatagramChannel openAsynchronousDatagramChannel + (ProtocolFamily family, AsynchronousChannelGroup group) throws IOException; +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/spi/SelectorProvider.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,199 @@ +/* + * Copyright 2000-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.channels.spi; + +import java.io.IOException; + +import java.security.AccessController; +import java.security.PrivilegedAction; + +import java.util.Iterator; +import java.util.ServiceLoader; +import java.util.ServiceConfigurationError; + +import org.classpath.icedtea.java.net.ProtocolFamily; + +import org.classpath.icedtea.java.nio.channels.DatagramChannel; + +/** + * Service-provider class for selectors and selectable channels. + * + * <p> A selector provider is a concrete subclass of this class that has a + * zero-argument constructor and implements the abstract methods specified + * below. A given invocation of the Java virtual machine maintains a single + * system-wide default provider instance, which is returned by the {@link + * #provider() provider} method. The first invocation of that method will locate + * the default provider as specified below. + * + * <p> The system-wide default provider is used by the static <tt>open</tt> + * methods of the {@link java.nio.channels.DatagramChannel#open + * DatagramChannel}, {@link java.nio.channels.Pipe#open Pipe}, {@link + * java.nio.channels.Selector#open Selector}, {@link + * java.nio.channels.ServerSocketChannel#open ServerSocketChannel}, and {@link + * java.nio.channels.SocketChannel#open SocketChannel} classes. It is also + * used by the {@link java.lang.System#inheritedChannel System.inheritedChannel()} + * method. A program may make use of a provider other than the default provider + * by instantiating that provider and then directly invoking the <tt>open</tt> + * methods defined in this class. + * + * <p> All of the methods in this class are safe for use by multiple concurrent + * threads. </p> + * + * + * @author Mark Reinhold + * @author JSR-51 Expert Group + * @since 1.4 + */ + +public abstract class SelectorProvider + extends java.nio.channels.spi.SelectorProvider { + + private static final Object lock = new Object(); + private static SelectorProvider provider = null; + + /** + * Opens a datagram channel. </p> + * + * @return The new channel + */ + public abstract DatagramChannel openDatagramChannel() + throws IOException; + + /** + * {@note new} + * Opens a datagram channel. + * + * @param family + * The protocol family + * + * @return A new datagram channel + * + * @throws UnsupportedOperationException + * If the specified protocol family is not supported + * @throws IOException + * If an I/O error occurs + * + * @since 1.7 + */ + public abstract DatagramChannel openDatagramChannel(ProtocolFamily family) + throws IOException; + + /** + * Returns the system-wide default selector provider for this invocation of + * the Java virtual machine. + * + * <p> The first invocation of this method locates the default provider + * object as follows: </p> + * + * <ol> + * + * <li><p> If the system property + * <tt>java.nio.channels.spi.SelectorProvider</tt> is defined then it is + * taken to be the fully-qualified name of a concrete provider class. + * The class is loaded and instantiated; if this process fails then an + * unspecified error is thrown. </p></li> + * + * <li><p> If a provider class has been installed in a jar file that is + * visible to the system class loader, and that jar file contains a + * provider-configuration file named + * <tt>java.nio.channels.spi.SelectorProvider</tt> in the resource + * directory <tt>META-INF/services</tt>, then the first class name + * specified in that file is taken. The class is loaded and + * instantiated; if this process fails then an unspecified error is + * thrown. </p></li> + * + * <li><p> Finally, if no provider has been specified by any of the above + * means then the system-default provider class is instantiated and the + * result is returned. </p></li> + * + * </ol> + * + * <p> Subsequent invocations of this method return the provider that was + * returned by the first invocation. </p> + * + * @return The system-wide default selector provider + */ + public static SelectorProvider provider() { + synchronized (lock) { + if (provider != null) + return provider; + return AccessController + .doPrivileged(new PrivilegedAction<SelectorProvider>() { + public SelectorProvider run() { + if (loadProviderFromProperty()) + return provider; + if (loadProviderAsService()) + return provider; + provider = sun.nio.ch.DefaultSelectorProvider.create(); + return provider; + } + }); + } + } + + private static boolean loadProviderFromProperty() { + String cn = System.getProperty("org.classpath.icedtea.java.nio.channels.spi.SelectorProvider"); + if (cn == null) + return false; + try { + Class<?> c = Class.forName(cn, true, + ClassLoader.getSystemClassLoader()); + provider = (SelectorProvider)c.newInstance(); + return true; + } catch (ClassNotFoundException x) { + throw new ServiceConfigurationError(null, x); + } catch (IllegalAccessException x) { + throw new ServiceConfigurationError(null, x); + } catch (InstantiationException x) { + throw new ServiceConfigurationError(null, x); + } catch (SecurityException x) { + throw new ServiceConfigurationError(null, x); + } + } + + private static boolean loadProviderAsService() { + + ServiceLoader<SelectorProvider> sl = + ServiceLoader.load(SelectorProvider.class, + ClassLoader.getSystemClassLoader()); + Iterator<SelectorProvider> i = sl.iterator(); + for (;;) { + try { + if (!i.hasNext()) + return false; + provider = i.next(); + return true; + } catch (ServiceConfigurationError sce) { + if (sce.getCause() instanceof SecurityException) { + // Ignore the security exception, try the next provider + continue; + } + throw sce; + } + } + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/channels/spi/package.html Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,46 @@ +<!-- + Copyright 2000-2005 Sun Microsystems, Inc. All Rights Reserved. + Copyright 2009 Red Hat, Inc. + 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. Sun designates this + particular file as subject to the "Classpath" exception as provided + by Sun in the LICENSE file that accompanied this code. + + 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. + + Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + CA 95054 USA or visit www.sun.com if you need additional information or + have any questions. +--> + +<!doctype html public "-//IETF//DTD HTML//EN"> +<html> +<body bgcolor="white"> + +Service-provider classes for the <tt>{@link org.classpath.icedtea.java.nio.channels}</tt> package. + +<p> Only developers who are defining new asynchronous channel providers should need +to make direct use of this package. </p> + +<p> Unless otherwise noted, passing a <tt>null</tt> argument to a constructor +or method in any class or interface in this package will cause a {@link +java.lang.NullPointerException NullPointerException} to be thrown. + + +@since 1.7 +@author Mark Reinhold +@author JSR-51 Expert Group + +</body> +</html>
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/AccessDeniedException.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,69 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file; + +/** + * Checked exception thrown when a file system operation is denied, typically + * due to a file permission or other access check. + * + * <p> This exception is not related to the {@link + * java.security.AccessControlException AccessControlException} or {@link + * SecurityException} thrown by access controllers or security managers when + * access to a file is denied. + * + * @since 1.7 + */ + +public class AccessDeniedException + extends FileSystemException +{ + private static final long serialVersionUID = 4943049599949219617L; + + /** + * Constructs an instance of this class. + * + * @param file + * A string identifying the file or {@code null} if not known. + */ + public AccessDeniedException(String file) { + super(file); + } + + /** + * Constructs an instance of this class. + * + * @param file + * A string identifying the file or {@code null} if not known. + * @param other + * A string identifying the other file or {@code null} if not known. + * @param reason + * A reason message with additional information or {@code null} + */ + public AccessDeniedException(String file, String other, String reason) { + super(file, other, reason); + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/AccessMode.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,50 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file; + +/** + * Defines access modes used to test the accessibility of a file. + * + * @since 1.7 + * + * @see FileRef#checkAccess + */ + +public enum AccessMode { + /** + * Test read access. + */ + READ, + /** + * Test write access. + */ + WRITE, + /** + * Test execute access. + */ + EXECUTE; +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/AtomicMoveNotSupportedException.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,57 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file; + +/** + * Checked exception thrown when a file cannot be moved as an atomic file system + * operation. + * + * @since 1.7 + */ + +public class AtomicMoveNotSupportedException + extends FileSystemException +{ + static final long serialVersionUID = 5402760225333135579L; + + /** + * Constructs an instance of this class. + * + * @param source + * A string identifying the source file or {@code null} if not known. + * @param target + * A string identifying the target file or {@code null} if not known. + * @param reason + * A reason message with additional information + */ + public AtomicMoveNotSupportedException(String source, + String target, + String reason) + { + super(source, target, reason); + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/ClosedDirectoryStreamException.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,46 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file; + +/** + * Unchecked exception thrown when an attempt is made to invoke an operation on + * a directory stream that is closed. + * + * @since 1.7 + */ + +public class ClosedDirectoryStreamException + extends IllegalStateException +{ + static final long serialVersionUID = 4228386650900895400L; + + /** + * Constructs an instance of this class. + */ + public ClosedDirectoryStreamException() { + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/ClosedFileSystemException.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,44 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file; + +/** + * Unchecked exception thrown when an attempt is made to invoke an operation on + * a file and the file system is closed. + */ + +public class ClosedFileSystemException + extends IllegalStateException +{ + static final long serialVersionUID = -8158336077256193488L; + + /** + * Constructs an instance of this class. + */ + public ClosedFileSystemException() { + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/ClosedWatchServiceException.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,44 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file; + +/** + * Unchecked exception thrown when an attempt is made to invoke an operation on + * a watch service that is closed. + */ + +public class ClosedWatchServiceException + extends IllegalStateException +{ + static final long serialVersionUID = 1853336266231677732L; + + /** + * Constructs an instance of this class. + */ + public ClosedWatchServiceException() { + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/CopyOption.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,42 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file; + +/** + * An object that configures how to copy or move a file. + * + * <p> Objects of this type may be used with the {@link Path#copyTo copyTo} and + * {@link Path#moveTo moveTo} methods to configure how a file is copied or moved. + * + * <p> The {@link StandardCopyOption} enumeration type defines the + * <i>standard</i> options. + * + * @since 1.7 + */ + +public interface CopyOption { +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/DirectoryNotEmptyException.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,50 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file; + +/** + * Checked exception thrown when a file system operation fails because a + * directory is not empty. + * + * @since 1.7 + */ + +public class DirectoryNotEmptyException + extends FileSystemException +{ + static final long serialVersionUID = 3056667871802779003L; + + /** + * Constructs an instance of this class. + * + * @param dir + * A string identifying the directory or {@code null} if not known. + */ + public DirectoryNotEmptyException(String dir) { + super(dir); + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/DirectoryStream.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,139 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file; + +import java.util.Iterator; +import java.io.Closeable; + +/** + * An object to iterate over the entries in a directory. A directory stream + * allows for convenient use of the for-each construct: + * <pre> + * Path dir = ... + * DirectoryStream<Path> stream = dir.newDirectoryStream(); + * try { + * for (Path entry: stream) { + * .. + * } + * } finally { + * stream.close(); + * } + * </pre> + * + * <p><b> A {@code DirectoryStream} is not a general-purpose {@code Iterable}. + * While this interface extends {@code Iterable}, the {@code iterator} method + * may only be invoked once to obtain the iterator; a second, or subsequent, + * call to the {@code iterator} method throws {@code IllegalStateException}. </b> + * + * <p> A {@code DirectoryStream} is opened upon creation and is closed by + * invoking the {@link #close close} method. Closing the directory stream + * releases any resources associated with the stream. The {@link + * Files#withDirectory Files.withDirectory} utility method is useful for cases + * where a task is performed on entries in a directory. This method automatically + * closes the directory stream when iteration is complete (or an error occurs). + * Once a directory stream is closed, all further method invocations on the + * iterator throw {@link java.util.concurrent.ConcurrentModificationException} + * with cause {@link ClosedDirectoryStreamException}. + * + * <p> A directory stream is not required to be <i>asynchronously closeable</i>. + * If a thread is blocked on the directory stream's iterator, reading from the + * directory, and another thread invokes the {@code close} method then it may + * require to block until the read operation is complete. + * + * <p> The {@link Iterator#hasNext() hasNext} and {@link Iterator#next() next} + * methods can encounter an I/O error when iterating over the directory in which + * case {@code ConcurrentModificationException} is thrown with cause + * {@link java.io.IOException}. The {@code hasNext} method is guaranteed to + * read-ahead by at least one element. This means that if the {@code hasNext} + * method returns {@code true} and is followed by a call to the {@code next} + * method then it is guaranteed not to fail with a {@code + * ConcurrentModificationException}. + * + * <p> The elements returned by the iterator are in no specific order. Some file + * systems maintain special links to the directory itself and the directory's + * parent directory. Entries representing these links are not returned by the + * iterator. + * + * <p> The iterator's {@link Iterator#remove() remove} method removes the + * directory entry for the last element returned by the iterator, as if by + * invoking the {@link FileRef#delete delete} method. If an I/O error or + * security exception occurs then {@code ConcurrentModificationException} is + * thrown with the cause. + * + * <p> The iterator is <i>weakly consistent</i>. It is thread safe but does not + * freeze the directory while iterating, so it may (or may not) reflect updates + * to the directory that occur after the {@code DirectoryStream} is created. + * + * @param <T> The type of element returned by the iterator + * + * @since 1.7 + * + * @see Path#newDirectoryStream + */ + +public interface DirectoryStream<T> + extends Closeable, Iterable<T> +{ + /** + * An interface that is implemented by objects that decide if a directory + * entry should be accepted or filtered. A {@code Filter} is passed as the + * parameter to the {@link Path#newDirectoryStream(DirectoryStream.Filter) + * newDirectoryStream} method when opening a directory to iterate over the + * entries in the directory. + * + * <p> The {@link DirectoryStreamFilters} class defines factory methods to + * create filters for a number of common usages and also methods to combine + * filters. + * + * @param <T> The type of the directory entry + * + * @since 1.7 + */ + public static interface Filter<T> { + /** + * Decides if the given directory entry should be accept or filtered. + * + * @param entry + * The directory entry to be tested + * + * @return {@code true} if the directory entry should be accepted + */ + boolean accept(T entry); + } + + /** + * Returns the iterator associated with this {@code DirectoryStream}. + * + * @return The iterator associated with this {@code DirectoryStream} + * + * @throws IllegalStateException + * If this directory stream is closed or the iterator has already + * been returned + */ + + Iterator<T> iterator(); +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/DirectoryStreamFilters.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,211 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file; + +import java.io.IOException; +import java.io.IOError; +import sun.nio.fs.MimeType; + +/** + * This class consists exclusively of static methods that construct or combine + * filters. + * + * @since 1.7 + */ + +public final class DirectoryStreamFilters { + private DirectoryStreamFilters() { } + + /** + * Constructs a directory stream filter that filters directory entries by + * their <a href="http://www.ietf.org/rfc/rfc2045.txt">MIME</a> content + * type. The directory stream filter's {@link + * java.nio.file.DirectoryStream.Filter#accept accept} method returns {@code + * true} if the content type of the directory entry can be determined by + * invoking the {@link Files#probeContentType probeContentType} method, and + * the content type matches the given content type. + * + * <p> The {@code type} parameter is the value of a Multipurpose Internet + * Mail Extension (MIME) content type as defined by <a + * href="http://www.ietf.org/rfc/rfc2045.txt"><i>RFC 2045: Multipurpose + * Internet Mail Extensions (MIME) Part One: Format of Internet Message + * Bodies</i></a>. It is parsable according to the grammar in the RFC. Any + * space characters (<code>'\u0020'</code>) surrounding its components are + * ignored. The {@code type} parameter is parsed into its primary and subtype + * components which are used to match the primary and subtype components of + * each directory entry's content type. Parameters are not allowed. The + * primary type matches if it has value {@code '*'} or is equal to the + * primary type of the directory entry's content type without regard to + * case. The subtype matches if has the value {@code '*'} or is equal to the + * subtype of the directory entry's content type without regard to case. If + * both the primary and subtype match then the filter's {@code accept} method + * returns {@code true}. If the content type of a directory entry cannot be + * determined then the entry is filtered. + * + * <p> The {@code accept} method of the resulting directory stream filter + * throws {@link IOError} if the probing of the content type fails by + * throwing an {@link IOException}. Security exceptions are also propogated + * to the caller of the {@code accept} method. + * + * <p> <b>Usage Example:</b> + * Suppose we require to list only the HTML files in a directory. + * <pre> + * DirectoryStream.Filter<FileRef> filter = + * DirectoryStreamFilters.newContentTypeFilter("text/html"); + * </pre> + * + * @param type + * The content type + * + * @return A new directory stream filter + * + * @throws IllegalArgumentException + * If the {@code type} parameter cannot be parsed as a MIME type + * or it has parameters + */ + public static <T extends FileRef> DirectoryStream.Filter<T> + newContentTypeFilter(String type) + { + final MimeType matchType = MimeType.parse(type); + if (matchType.hasParameters()) + throw new IllegalArgumentException("Parameters not allowed"); + return new DirectoryStream.Filter<T>() { + + public boolean accept(T entry) { + String fileType; + try { + fileType = Files.probeContentType(entry); + } catch (IOException x) { + throw new IOError(x); + } + if (fileType != null) { + return matchType.match(fileType); + } + return false; + } + }; + } + + /** + * Returns a directory stream filter that {@link DirectoryStream.Filter#accept + * accepts} a directory entry if the entry is accepted by all of the given + * filters. + * + * <p> This method returns a filter that invokes, in iterator order, the + * {@code accept} method of each of the filters. If {@code false} is returned + * by any of the filters then the directory entry is filtered. If the + * directory entry is not filtered then the resulting filter accepts the + * entry. If the iterator returns zero elements then the resulting filter + * accepts all directory entries. + * + * <p> <b>Usage Example:</b> + * <pre> + * List<DirectoryStream.Filter<? super Path>> filters = ... + * DirectoryStream.Filter<Path> filter = DirectoryStreamFilters.allOf(filters); + * </pre> + * + * @param filters + * The sequence of filters + * + * @return The resulting filter + */ + public static <T> DirectoryStream.Filter<T> + allOf(final Iterable<? extends DirectoryStream.Filter<? super T>> filters) + { + if (filters == null) + throw new NullPointerException("'filters' is null"); + return new DirectoryStream.Filter<T>() { + + public boolean accept(T entry) { + for (DirectoryStream.Filter<? super T> filter: filters) { + if (!filter.accept(entry)) + return false; + } + return true; + } + }; + } + + /** + * Returns a directory stream filter that {@link DirectoryStream.Filter#accept + * accepts} a directory entry if the entry is accepted by one or more of + * the given filters. + * + * <p> This method returns a filter that invokes, in iteration order, the + * {@code accept} method of each of filter. If {@code true} is returned by + * any of the filters then the directory entry is accepted. If none of the + * filters accepts the directory entry then it is filtered. If the iterator + * returns zero elements then the resulting filter filters all directory + * entries. + * + * @param filters + * The sequence of filters + * + * @return The resulting filter + */ + public static <T> DirectoryStream.Filter<T> + anyOf(final Iterable<? extends DirectoryStream.Filter<? super T>> filters) + { + if (filters == null) + throw new NullPointerException("'filters' is null"); + return new DirectoryStream.Filter<T>() { + + public boolean accept(T entry) { + for (DirectoryStream.Filter<? super T> filter: filters) { + if (filter.accept(entry)) + return true; + } + return false; + } + }; + } + + /** + * Returns a directory stream filter that is the <em>complement</em> of the + * given filter. The resulting filter {@link + * java.nio.file.DirectoryStream.Filter#accept accepts} a directory entry + * if filtered by the given filter, and filters any entries that are accepted + * by the given filter. + * + * @param filter + * The given filter + * + * @return The resulting filter that is the complement of the given filter + */ + public static <T> DirectoryStream.Filter<T> + complementOf(final DirectoryStream.Filter<T> filter) + { + if (filter == null) + throw new NullPointerException("'filter' is null"); + return new DirectoryStream.Filter<T>() { + + public boolean accept(T entry) { + return !filter.accept(entry); + } + }; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/FileAction.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,65 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file; + +import java.io.IOException; + +/** + * An interface that is implemented by objects that operate on a file. An + * implementation of this interface is provided to the {@link Files#withDirectory + * withDirectory} utility method so that the file action is {@link #invoke + * invoked} for all accepted entries in the directory, after which, the directory + * is automatically closed. + * + * <p> <b>Usage Example:</b> + * Suppose we require to perform a task on all class files in a directory: + * <pre> + * Path dir = ... + * Files.withDirectory(dir, "*.class", new FileAction<Path>() { + * public void invoke(Path entry) { + * : + * } + * }); + * </pre> + * + * @param <T> The type of file reference + * + * @since 1.7 + */ + +public interface FileAction<T extends FileRef> { + /** + * Invoked for a file. + * + * @param file + * The file + * + * @throws IOException + * If the block terminates due an uncaught I/O exception + */ + void invoke(T file) throws IOException; +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/FileAlreadyExistsException.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,64 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file; + +/** + * Checked exception thrown when an attempt is made to create a file or + * directory and a file of that name already exists. + * + * @since 1.7 + */ + +public class FileAlreadyExistsException + extends FileSystemException +{ + static final long serialVersionUID = 7579540934498831181L; + + /** + * Constructs an instance of this class. + * + * @param file + * A string identifying the file or {@code null} if not known. + */ + public FileAlreadyExistsException(String file) { + super(file); + } + + /** + * Constructs an instance of this class. + * + * @param file + * A string identifying the file or {@code null} if not known. + * @param other + * A string identifying the other file or {@code null} if not known. + * @param reason + * A reason message with additional information or {@code null} + */ + public FileAlreadyExistsException(String file, String other, String reason) { + super(file, other, reason); + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/FileRef.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,425 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file; + +import java.io.IOException; + +import org.classpath.icedtea.java.nio.channels.SeekableByteChannel; + +import org.classpath.icedtea.java.nio.file.attribute.FileAttributeView; + +/** + * A reference to a file. + * + * <p> A {@code FileRef} is an object that locates a file and defines methods to + * access the file. The means by which the file is located depends on the + * implementation. In many cases, a file is located by a {@link Path} but it may + * be located by other means such as a file-system identifier. + * + * <p> This interface defines the following operations: + * <ul> + * <li><p> The {@link #newByteChannel newByteChannel} method + * may be used to open a file and obtain a byte channel for reading or + * writing. </p></li> + * <li><p> The {@link #delete delete} method may be used to delete a file. + * </p></li> + * <li><p> The {@link #checkAccess checkAccess} method may be used to check + * the existence or accessibility of a file. </p></li> + * <li><p> The {@link #isSameFile isSameFile} method may be used to test if + * two file references locate the same file. </p></li> + * <li><p> The {@link #getFileStore getFileStore} method may be used to + * obtain the {@link FileStore} representing the storage where a file is + * located. </p></li> + * </ul> + * + * <p> Access to associated metadata or file attributes requires an appropriate + * {@link FileAttributeView FileAttributeView}. The {@link + * #getFileAttributeView(Class,LinkOption[]) getFileAttributeView(Class,LinkOption[])} + * method may be used to obtain a file attribute view that defines type-safe + * methods to read or update file attributes. The {@link + * #getFileAttributeView(String,LinkOption[]) getFileAttributeView(String,LinkOption[])} + * method may be used to obtain a file attribute view where dynamic access to + * file attributes where required. + * + * <p> A {@code FileRef} is immutable and safe for use by multiple concurrent + * threads. + * + * @since 1.7 + */ + +public interface FileRef { + + /** + * Opens the file referenced by this object, returning a seekable byte + * channel to access the file. + * + * <p> The {@code options} parameter determines how the file is opened. + * The {@link StandardOpenOption#READ READ} and {@link StandardOpenOption#WRITE + * WRITE} options determine if the file should be opened for reading and/or + * writing. If neither option (or the {@link StandardOpenOption#APPEND APPEND} + * option) is contained in the array then the file is opened for reading. + * By default reading or writing commences at the beginning of the file. + * + * <p> In the addition to {@code READ} and {@code WRITE}, the following + * options may be present: + * + * <table border=1 cellpadding=5 summary=""> + * <tr> <th>Option</th> <th>Description</th> </tr> + * <tr> + * <td> {@link StandardOpenOption#APPEND APPEND} </td> + * <td> If this option is present then the file is opened for writing and + * each invocation of the channel's {@code write} method first advances + * the position to the end of the file and then writes the requested + * data. Whether the advancement of the position and the writing of the + * data are done in a single atomic operation is system-dependent and + * therefore unspecified. This option may not be used in conjunction + * with the {@code READ} or {@code TRUNCATE_EXISTING} options. </td> + * </tr> + * <tr> + * <td> {@link StandardOpenOption#TRUNCATE_EXISTING TRUNCATE_EXISTING} </td> + * <td> If this option is present then the existing file is truncated to + * a size of 0 bytes. This option is ignored when the file is opened only + * for reading. </td> + * </tr> + * <tr> + * <td> {@link StandardOpenOption#SYNC SYNC} </td> + * <td> Requires that every update to the file's content or metadata be + * written synchronously to the underlying storage device. (see <a + * href="package-summary.html#integrity"> Synchronized I/O file + * integrity</a>). </td> + * </tr> + * <tr> + * <td> {@link StandardOpenOption#DSYNC DSYNC} </td> + * <td> Requires that every update to the file's content be written + * synchronously to the underlying storage device. (see <a + * href="package-summary.html#integrity"> Synchronized I/O file + * integrity</a>). </td> + * </tr> + * </table> + * + * <p> An implementation of this interface may support additional options + * defined by the {@link StandardOpenOption} enumeration type or other + * implementation specific options. + * + * <p> The {@link java.nio.channels.Channels} utility classes defines methods + * to construct input and output streams where inter-operation with the + * {@link java.io} package is required. + * + * @param options + * Options specifying how the file is opened + * + * @return a new seekable byte channel + * + * @throws IllegalArgumentException + * If an invalid combination of options is specified + * @throws UnsupportedOperationException + * If an unsupported open option is specified + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * In the case of the default provider, and a security manager is + * installed, the {@link SecurityManager#checkRead(String) checkRead} + * method is invoked to check read access to the path if the file is + * opened for reading. The {@link SecurityManager#checkWrite(String) + * checkWrite} method is invoked to check write access to the path + * if the file is opened for writing. + */ + SeekableByteChannel newByteChannel(OpenOption... options) + throws IOException; + + /** + * Returns the {@link FileStore} representing the file store where the file + * referenced by this object is stored. + * + * <p> Once a reference to the {@code FileStore} is obtained it is + * implementation specific if operations on the returned {@code FileStore}, + * or {@link FileStoreAttributeView} objects obtained from it, continue + * to depend on the existence of the file. In particular the behavior is not + * defined for the case that the file is deleted or moved to a different + * file store. + * + * @return The file store where the file is stored + * + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * In the case of the default provider, and a security manager is + * installed, the {@link SecurityManager#checkRead(String) checkRead} + * method is invoked to check read access to the file. + */ + FileStore getFileStore() throws IOException; + + /** + * Checks the existence and optionally the accessibility of the file + * referenced by this object. + * + * <p> This method checks the existence of a file and that this Java virtual + * machine has appropriate privileges that would allow it access the file + * according to all of access modes specified in the {@code modes} parameter + * as follows: + * + * <table border=1 cellpadding=5 summary=""> + * <tr> <th>Value</th> <th>Description</th> </tr> + * <tr> + * <td> {@link AccessMode#READ READ} </td> + * <td> Checks that the file exists and that the Java virtual machine has + * permission to read the file. </td> + * </tr> + * <tr> + * <td> {@link AccessMode#WRITE WRITE} </td> + * <td> Checks that the file exists and that the Java virtual machine has + * permission to write to the file, </td> + * </tr> + * <tr> + * <td> {@link AccessMode#EXECUTE EXECUTE} </td> + * <td> Checks that the file exists and that the Java virtual machine has + * permission to {@link Runtime#exec execute} the file. The semantics + * may differ when checking access to a directory. For example, on UNIX + * systems, checking for {@code EXECUTE} access checks that the Java + * virtual machine has permission to search the directory in order to + * access file or subdirectories. </td> + * </tr> + * </table> + * + * <p> If the {@code modes} parameter is of length zero, then the existence + * of the file is checked. + * + * <p> This method follows symbolic links if the file referenced by this + * object is a symbolic link. Depending on the implementation, this method + * may require to read file permissions, access control lists, or other + * file attributes in order to check the effective access to the file. To + * determine the effective access to a file may require access to several + * attributes and so in some implementations this method may not be atomic + * with respect to other file system operations. Furthermore, as the result + * of this method is immediately outdated, there is no guarantee that a + * subsequence access will succeed (or even that it will access the same + * file). Care should be taken when using this method in security sensitive + * applications. + * + * @param modes + * The access modes to check; may have zero elements + * + * @throws UnsupportedOperationException + * An implementation is required to support checking for + * {@code READ}, {@code WRITE}, and {@code EXECUTE} access. This + * exception is specified to allow for the {@code Access} enum to + * be extended in future releases. + * @throws NoSuchFileException + * If a file does not exist <i>(optional specific exception)</i> + * @throws AccessDeniedException + * The requested access would be denied or the access cannot be + * determined because the Java virtual machine has insufficient + * privileges or other reasons. <i>(optional specific exception)</i> + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * In the case of the default provider, and a security manager is + * installed, the {@link SecurityManager#checkRead(String) checkRead} + * is invoked when checking read access to the file or only the + * existence of the file, the {@link SecurityManager#checkWrite(String) + * checkWrite} is invoked when checking write access to the file, + * and {@link SecurityManager#checkExec(String) checkExec} is invoked + * when checking execute access. + */ + void checkAccess(AccessMode... modes) throws IOException; + + /** + * Returns a file attribute view of a given type. + * + * <p> A file attribute view provides a read-only or updatable view of the + * file attributes that is supports. This method is intended to be used where + * the file attribute view defines type-safe methods to read or update the + * file attributes. The {@code type} parameter is the type of the attribute + * view required and the method returns an instance of that type if + * supported. The {@link BasicFileAttributeView} type supports access to the + * basic attributes of a file. Invoking this method to select a file + * attribute view of that type will always return an instance of that class. + * + * <p> The {@code options} array may be used to indicate how symbolic links + * are handled by the resulting file attribute view for the case that the + * file is a symbolic link. By default, symbolic links are followed. If the + * option {@link LinkOption#NOFOLLOW_LINKS NOFOLLOW_LINKS} is present then + * symbolic links are not followed. This option is ignored by implementations + * that do not support symbolic links. + * + * @param type + * The {@code Class} object corresponding to the file attribute view + * @param options + * Options indicating how symbolic links are handled + * + * @return A file attribute view of the specified type, or {@code null} if + * the attribute view type is not available + * + * @throws UnsupportedOperationException + * If options contains an unsupported option. This exception is + * specified to allow the {@code LinkOption} enum be extended + * in future releases. + * + * @see Attributes#readBasicFileAttributes + */ + <V extends FileAttributeView> V getFileAttributeView(Class<V> type, LinkOption... options); + + /** + * Returns a file attribute view of the given name. + * + * <p> A file attribute view provides a read-only or updatable view of the + * file attributes that is supports. This method is intended to be used where + * <em>dynamic access</em> to the file attributes is required. The {@code + * name} parameter specifies the {@link FileAttributeView#name name} of the + * file attribute view and this method returns an instance of that view if + * supported. The {@link BasicFileAttributeView} type supports access to the + * basic attributes of a file and is name {@code "basic"}. Invoking this + * method to select a file attribute view named {@code "basic"} will always + * return an instance of that class. + * + * <p> The {@code options} array may be used to indicate how symbolic links + * are handled by the resulting file attribute view for the case that the + * file is a symbolic link. By default, symbolic links are followed. If the + * option {@link LinkOption#NOFOLLOW_LINKS NOFOLLOW_LINKS} is present then + * symbolic links are not followed. This option is ignored by implementations + * that do not support symbolic links. + * + * @param name + * The name of the file attribute view + * @param options + * Options indicating how symbolic links are handled + * + * @return A file attribute view of the given name, or {@code null} if + * the attribute view is not available + * + * @throws UnsupportedOperationException + * If options contains an unsupported option. This exception is + * specified to allow the {@code LinkOption} enum be extended + * in future releases. + */ + FileAttributeView getFileAttributeView(String name, LinkOption... options); + + /** + * Tests if the file referenced by this object is the same file referenced + * by another object. + * + * <p> If this {@code FileRef} and the given {@code FileRef} are {@link + * #equals(Object) equal} then this method returns {@code true} without checking + * if the file exists. If the {@code FileRef} and the given {@code FileRef} + * are associated with different providers, or the given {@code FileRef} is + * {@code null} then this method returns {@code false}. Otherwise, this method + * checks if both {@code FileRefs} locate the same file, and depending on the + * implementation, may require to open or access both files. + * + * <p> If the file system and files remain static, then this method implements + * an equivalence relation for non-null {@code FileRefs}. + * <ul> + * <li>It is <i>reflexive</i>: for a non-null {@code FileRef} {@code f}, + * {@code f.isSameFile(f)} should return {@code true}. + * <li>It is <i>symmetric</i>: for two non-null {@code FileRefs} + * {@code f} and {@code g}, {@code f.isSameFile(g)} will equal + * {@code g.isSameFile(f)}. + * <li>It is <i>transitive</i>: for three {@code FileRefs} + * {@code f}, {@code g}, and {@code h}, if {@code f.isSameFile(g)} returns + * {@code true} and {@code g.isSameFile(h)} returns {@code true}, then + * {@code f.isSameFile(h)} will return return {@code true}. + * </ul> + * + * @param other + * The other file reference + * + * @return {@code true} if, and only if, this object and the given object + * locate the same file + * + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * In the case of the default provider, and a security manager is + * installed, the {@link SecurityManager#checkRead(String) checkRead} + * method is invoked to check read access to both files. + * + * @see java.nio.file.attribute.BasicFileAttributes#fileKey + */ + boolean isSameFile(FileRef other) throws IOException; + + /** + * Deletes the file referenced by this object. + * + * <p> An implementation may require to examine the file to determine if the + * file is a directory. Consequently this method may not be atomic with respect + * to other file system operations. If the file is a symbolic-link then the + * link is deleted and not the final target of the link. + * + * <p> If the file is a directory then the directory must be empty. In some + * implementations a directory has entries for special files or links that + * are created when the directory is created. In such implementations a + * directory is considered empty when only the special entries exist. + * + * <p> On some operating systems it may not be possible to remove a file when + * it is open and in use by this Java virtual machine or other programs. + * + * @throws NoSuchFileException + * If the file does not exist <i>(optional specific exception)</i> + * @throws DirectoryNotEmptyException + * If the file is a directory and could not otherwise be deleted + * because the directory is not empty <i>(optional specific + * exception)</i> + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * In the case of the default provider, and a security manager is + * installed, the {@link SecurityManager#checkDelete(String)} method + * is invoked to check delete access to the file + */ + void delete() throws IOException; + + /** + * Tests this object for equality with another object. + * + * <p> If the given object is not a {@code FileRef} then this method + * immediately returns {@code false}. + * + * <p> For two file references to be considered equal requires that they + * are both the same type of {@code FileRef} and encapsulate components + * to locate the same file. This method does not access the file system and + * the file may not exist. + * + * <p> This method satisfies the general contract of the {@link + * java.lang.Object#equals(Object) Object.equals} method. </p> + * + * @param ob The object to which this object is to be compared + * + * @return {@code true} if, and only if, the given object is a {@code FileRef} + * that is identical to this {@code FileRef} + * + * @see #isSameFile + */ + boolean equals(Object ob); + + /** + * Returns the hash-code value for this object. + * + * <p> This method satisfies the general contract of the + * {@link java.lang.Object#hashCode() Object.hashCode} method. + */ + int hashCode(); +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/FileStore.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,173 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file; + +import java.util.Set; + +import org.classpath.icedtea.java.nio.file.attribute.FileAttributeView; +import org.classpath.icedtea.java.nio.file.attribute.FileStoreAttributeView; + +/** + * Storage for files. A {@code FileStore} represents a storage pool, device, + * partition, volume, concrete file system or other implementation specific means + * of file storage. The {@code FileStore} for where a file is stored is obtained + * by invoking the {@link FileRef#getFileStore getFileStore} method, or all file + * stores can be enumerated by invoking the {@link FileSystem#getFileStores + * getFileStores} method. + * + * <p> In addition to the methods defined by this class, a file store may support + * one or more {@link FileStoreAttributeView FileStoreAttributeView} classes + * that provide a read-only or updatable view of a set of file store attributes. + * File stores associated with the default provider support the {@link + * FileStoreSpaceAttributeView} to read the space related attributes of the + * file store. + * + * @since 1.7 + */ + +public abstract class FileStore { + + /** + * Initializes a new instance of this class. + */ + protected FileStore() { + } + + /** + * Returns the name of this file store. The format of the name is highly + * implementation specific. It will typically be the name of the storage + * pool or volume. + * + * <p> The string returned by this method may differ from the string + * returned by the {@link Object#toString() toString} method. + * + * @return The name of this file store + */ + public abstract String name(); + + /** + * Returns the <em>type</em> of this file store. The format of the string + * returned by this method is highly implementation specific. It may + * indicate, for example, the format used or if the file store is local + * or remote. + * + * @return A string representing the type of this file store + */ + public abstract String type(); + + /** + * Tells whether this file store is read-only. A file store is read-only if + * it does not support write operations or other changes to files. Any + * attempt to create a file, open an existing file for writing etc. causes + * an {@code IOException} to be thrown. + * + * @return {@code true} if, and only if, this file store is read-only + */ + public abstract boolean isReadOnly(); + + /** + * Tells whether or not this file store supports the file attributes + * identified by the given file attribute view. + * + * <p> Invoking this method to test if the file store supports {@link + * BasicFileAttributeView} will always return {@code true}. In the case of + * the default provider, this method cannot guarantee to give the correct + * result when the file store is not a local storage device. The reasons for + * this are implementation specific and therefore unspecified. + * + * @param type + * The file attribute view type + * + * @return {@code true} if, and only if, the file attribute view is + * supported + */ + public abstract boolean supportsFileAttributeView(Class<? extends FileAttributeView> type); + + /** + * Tells whether or not this file store supports the file attributes + * identified by the given file attribute view. + * + * <p> Invoking this method to test if the file store supports {@link + * BasicFileAttributeView}, identified by the name "{@code basic}" will + * always return {@code true}. In the case of the default provider, this + * method cannot guarantee to give the correct result when the file store is + * not a local storage device. The reasons for this are implementation + * specific and therefore unspecified. + * + * @param name + * The {@link FileAttributeView#name name} of file attribute view + * + * @return {@code true} if, and only if, the file attribute view is + * supported + */ + public abstract boolean supportsFileAttributeView(String name); + + /** + * Returns a {@code FileStoreAttributeView} of the given type. + * + * <p> This method is intended to be used where the file store attribute + * view defines type-safe methods to read or update the file store attributes. + * The {@code type} parameter is the type of the attribute view required and + * the method returns an instance of that type if supported. + * + * <p> For {@code FileStore} objects created by the default provider, then + * the file stores support the {@link FileStoreSpaceAttributeView} that + * provides access to space attributes. In that case invoking this method + * with a parameter value of {@code FileStoreSpaceAttributeView.class} will + * always return an instance of that class. + * + * @param type + * The {@code Class} object corresponding to the attribute view + * + * @return A file store attribute view of the specified type or + * {@code null} if the attribute view is not available + */ + public abstract <V extends FileStoreAttributeView> V + getFileStoreAttributeView(Class<V> type); + + /** + * Returns a {@code FileStoreAttributeView} of the given name. + * + * <p> This method is intended to be used where <em>dynamic access</em> to + * file store attributes is required. The {@code name} parameter specifies + * the {@link FileAttributeView#name name} of the file store attribute view + * and this method returns an instance of that view if supported. + * + * <p> For {@code FileStore} objects created by the default provider, then + * the file stores support the {@link FileStoreSpaceAttributeView} that + * provides access to space attributes. In that case invoking this method + * with a parameter value of {@code "space"} will always return an instance + * of that class. + * + * @param name + * The name of the attribute view + * + * @return A file store attribute view of the given name, or {@code null} + * if the attribute view is not available + */ + public abstract FileStoreAttributeView getFileStoreAttributeView(String name); +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/FileSystem.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,426 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file; + +import java.util.Set; +import java.io.Closeable; +import java.io.IOException; + +import org.classpath.icedtea.java.nio.file.attribute.UserPrincipalLookupService; + +import org.classpath.icedtea.java.nio.file.spi.FileSystemProvider; + +/** + * Provides an interface to a file system and is the factory for objects to + * access files and other objects in the file system. + * + * <p> The default file system, obtained by invoking the {@link FileSystems#getDefault + * FileSystems.getDefault} method, provides access to the file system that is + * accessible to the Java virtual machine. The {@link FileSystems} class defines + * methods to create file systems that provide access to other types of file + * systems. + * + * <p> A file system is the factory for several types of objects: + * + * <ul> + * <li><p> The {@link #getPath getPath} method converts a system dependent + * <em>path string</em>, returning a {@link Path} object that may be used + * to locate and access a file. </p></li> + * <li><p> The {@link #getNameMatcher getNameMatcher} method is used + * to create a {@link PathMatcher} that performs match operations on + * file names. </p></li> + * <li><p> The {@link #getFileStores getFileStores} method returns an iterator + * over the underlying {@link FileStore file-stores}. </p></li> + * <li><p> The {@link #getUserPrincipalLookupService getUserPrincipalLookupService} + * method returns the {@link UserPrincipalLookupService} to lookup users or + * groups by name. </p></li> + * <li><p> The {@link #newWatchService newWatchService} method creates a + * {@link WatchService} that may be used to watch objects for changes and + * events. </p></li> + * </ul> + * + * <p> File systems vary greatly. In some cases the file system is a single + * hierarchy of files with one top-level root directory. In other cases it may + * have several distinct file hierarchies, each with its own top-level root + * directory. The {@link #getRootDirectories getRootDirectories} method may be + * used to iterate over the root directories in the file system. A file system + * is typically composed of one or more underlying {@link FileStore file-stores} + * that provide the storage for the files. Theses file stores can also vary in + * the features they support, and the file attributes or <em>meta-data</em> that + * they associate with files. + * + * <p> A file system is open upon creation and can be closed by invoking its + * {@link #close() close} method. Once closed, any further attempt to access + * objects in the file system cause {@link ClosedFileSystemException} to be + * thrown. File systems created by the default {@link FileSystemProvider provider} + * cannot be closed. + * + * <p> A {@code FileSystem} can provide read-only or read-write access to the + * file system. Whether or not a file system provides read-only access is + * established when the {@code FileSystem} is created and can be tested by invoking + * its {@link #isReadOnly() isReadOnly} method. Attempts to write to file stores + * by means of an object associated with a read-only file system throws {@link + * ReadOnlyFileSystemException}. + * + * <p> File systems are safe for use by multiple concurrent threads. The {@link + * #close close} method may be invoked at any time to close a file system but + * whether a file system is <i>asynchronously closeable</i> is provider specific + * and therefore unspecified. In other words, if a thread is accessing an + * object in a file system, and another thread invokes the {@code close} method + * then it may require to block until the first operation is complete. Closing + * a file system causes all open channels, watch services, and other {@link + * Closeable closeable} objects associated with the file system to be closed. + * + * @since 1.7 + */ + +public abstract class FileSystem + implements Closeable +{ + /** + * Initializes a new instance of this class. + */ + protected FileSystem() { + } + + /** + * Returns the provider that created this file system. + * + * @return The provider that created this file system. + */ + public abstract FileSystemProvider provider(); + + /** + * Closes this file system. + * + * <p> After a file system is closed then all subsequent access to the file + * system, either by methods defined by this class or on objects associated + * with this file system, throw {@link ClosedFileSystemException}. If the + * file system is already closed then invoking this method has no effect. + * + * <p> Closing a file system will close all open {@link + * java.nio.channels.Channel channels}, {@link DirectoryStream directory-streams}, + * {@link WatchService watch-service}, and other closeable objects associated + * with this file system. The {@link FileSystems#getDefault default} file + * system cannot be closed. + * + * @throws IOException + * If an I/O error occurs + * @throws UnsupportedOperationException + * Thrown in the case of the default file system + */ + + public abstract void close() throws IOException; + + /** + * Tells whether or not this file system is open. + * + * <p> File systems created by the default provider are always open. + * + * @return {@code true} if, and only if, this file system is open + */ + public abstract boolean isOpen(); + + /** + * Tells whether or not this file system allows only read-only access to + * its file stores. + * + * @return {@code true} if, and only if, this file system provides + * read-only access + */ + public abstract boolean isReadOnly(); + + /** + * Returns the name separator, represented as a string. + * + * <p> The name separator is used to separate names in a path string. An + * implementation may support multiple name separators in which case this + * method returns an implementation specific <em>default</em> name separator. + * This separator is used when creating path strings by invoking the {@link + * Path#toString() toString()} method. + * + * <p> In the case of the default provider, this method returns the same + * separator as {@link java.io.File#separator}. + * + * @return The name separator + */ + public abstract String getSeparator(); + + /** + * Returns an object to iterate over the paths of the root directories. + * + * <p> A file system provides access to a file store that may be composed + * of a number of distinct file hierarchies, each with its own top-level + * root directory. Unless denied by the security manager, each element in + * the returned iterator corresponds to the root directory of a distinct + * file hierarchy. The order of the elements is not defined. The file + * hierarchies may change during the lifetime of the Java virtual machine. + * For example, in some implementations, the insertion of removable media + * may result in the creation of a new file hierarchy with its own + * top-level directory. + * + * <p> When a security manager is installed, it is invoked to check access + * to the each root directory. If denied, the root directory is not returned + * by the iterator. In the case of the default provider, the {@link + * SecurityManager#checkRead(String)} method is invoked to check read access + * to each root directory. It is system dependent if the permission checks + * are done when the iterator is obtained or during iteration. + * + * @return An object to iterate over the root directories + */ + public abstract Iterable<Path> getRootDirectories(); + + /** + * Returns an object to iterate over the underlying file stores. + * + * <p> The elements of the returned iterator are the {@link + * FileStore FileStores} for this file system. The order of the elements is + * not defined and the file stores may change during the lifetime of the + * Java virtual machine. When an I/O error occurs, perhaps because a file + * store is not accessible, then it is not returned by the iterator. + * + * <p> When a security manager is installed, it is invoked to check access + * to each file store. If denied, the file store is not returned by the + * iterator. In the case of the default provider, the {@link + * SecurityManager#checkRead(String)} method is invoked to check read access + * to the file store's <em>top-most</em> directory. It is system dependent + * if the permission checks are done when the iterator is obtained or during + * iteration. + * + * <p> <b>Usage Example:</b> + * Suppose we want to print the space usage for all file stores: + * <pre> + * for (FileStore store: FileSystems.getDefault().getFileStores()) { + * FileStoreSpaceAttributes attrs = Attributes.readFileStoreSpaceAttributes(store); + * long total = attrs.totalSpace() / 1024; + * long used = (attrs.totalSpace() - attrs.unallocatedSpace()) / 1024; + * long avail = attrs.usableSpace() / 1024; + * System.out.format("%-20s %12d %12d %12d%n", store, total, used, avail); + * } + * </pre> + * + * @return An object to iterate over the backing file stores + */ + public abstract Iterable<FileStore> getFileStores(); + + /** + * Returns the set of the {@link FileAttributeView#name names} of the file + * attribute views supported by this {@code FileSystem}. + * + * <p> The {@link BasicFileAttributeView} is required to be supported and + * therefore the set contains at least one element, "basic". + * + * <p> The {@link FileStore#supportsFileAttributeView(String) + * supportsFileAttributeView(String)} method may be used to test if an + * underlying {@link FileStore} supports the file attributes identified by a + * file attribute view. + * + * @return An unmodifiable set of the names of the supported file attribute + * views + */ + public abstract Set<String> supportedFileAttributeViews(); + + /** + * Converts a path string to a {@code Path}. + * + * <p> The parsing and conversion to a path object is inherently + * implementation dependent. In the simplest case, the path string is rejected, + * and {@link InvalidPathException} thrown, if the path string contains + * characters that cannot be converted to characters that are <em>legal</em> + * to the file store. For example, on UNIX systems, the NUL (\u0000) + * character is not allowed to be present in a path. An implementation may + * choose to reject path strings that contain names that are longer than those + * allowed by any file store, and where an implementation supports a complex + * path syntax, it may choose to reject path strings that are <em>badly + * formed</em>. + * + * <p> In the case of the default provider, path strings are parsed based + * on the definition of paths at the platform or virtual file system level. + * For example, an operating system may not allow specific characters to be + * present in a file name, but a specific underlying file store may impose + * different or additional restrictions on the set of legal + * characters. + * + * <p> This method throws {@link InvalidPathException} when the path string + * cannot be converted to a path. Where possible, and where applicable, + * the exception is created with an {@link InvalidPathException#getIndex + * index} value indicating the first position in the {@code path} parameter + * that caused the path string to be rejected. + * + * <p> Invoking this method with an empty path string throws + * {@code InvalidPathException}. + * + * @param path + * The path string + * + * @return A {@code Path} object + * + * @throws InvalidPathException + * If the path string cannot be converted + */ + public abstract Path getPath(String path); + + /** + * Returns a {@code PathMatcher} that performs match operations on file + * {@link Path#getName names} by interpreting a given pattern. + * + * <p> The {@code syntax} parameter identifies the syntax. This method + * supports the "{@code glob}" and "{@code regex}" syntaxes, and may + * support others. The value of the syntax component is compared without + * regard to case. + * + * <p> When the syntax is "{@code glob}" then the {@code String} + * representation of the file name is matched using a limited pattern + * language that resembles regular expressions but with a simpler syntax. + * For example: + * + * <blockquote> + * <table border="0"> + * <tr> + * <td>{@code *.java}</td> + * <td>Matches file names ending in {@code .java}</td> + * </tr> + * <tr> + * <td>{@code *.*}</td> + * <td>Matches file names containing a dot</td> + * </tr> + * <tr> + * <tr> + * <td>{@code *.{java,class}}</td> + * <td>Matches file names ending with {@code .java} or {@code .class}</td> + * </tr> + * <tr> + * <td>{@code foo.?}</td> + * <td>Matches file names starting with {@code foo.} and a single + * character extension</td> + * </tr> + * </table> + * </blockquote> + * + * <p> The following rules are used to interprete glob patterns: + * + * <p> <ul> + * <li><p> The {@code *} character matches zero or more {@link Character + * characters}. </p></li> + * + * <li><p> The {@code ?} character matches exactly one character. </p></li> + * + * <li><p> The backslash character ({@code \}) is used to escape characters + * that would otherwise be interpreted as special characters. The expression + * {@code \\} matches a single backslash and "\{" matches a left brace + * for example. </p></li> + * + * <li><p> The {@code [ ]} characters are a <i>bracket expression</i> and + * match a single character that is contained within the brackets. For + * example, {@code [abc]} matches {@code "a"}, {@code "b"}, or {@code "c"}. + * The hyphen ({@code -}) may be used to specify a range so {@code [a-z]} + * specifies a range that matches from {@code "a"} to {@code "z"} (inclusive). + * These forms can be mixed so [abce-g] matches {@code "a"}, {@code "b"}, + * {@code "c"}, {@code "e"}, {@code "f"} or {@code "g"}. If the character + * after the {@code [} is a {@code !} then it is used for negation so {@code + * [!a-c]} matches any character except {@code "a"}, {@code "b"}, or {@code + * "c"}. + * <p> Within a bracket expression the {@code *}, {@code ?} and {@code \} + * characters match themselves. The ({@code -}) character matches itself if + * it is the first character within the brackets, or the first character + * after the {@code !} if negating.</p></li> + * + * <li><p> The {@code { }} characters are a group of subpatterns, where + * the group matches if any subpattern in the group matches. The {@code ","} + * character is used to separate the subpatterns. Groups cannot be nested. + * </p></li> + * + * <li><p>All other characters match themselves in an implementation + * dependent manner. </p></li> + * </ul> + * + * <p> When the syntax is "{@code regex}" then the pattern component is a + * regular expression as defined by the {@link java.util.regex.Pattern} + * class. + * + * <p> For both the glob and regex syntaxes then whether matching is case + * sensitive, and other matching details, are implementation-dependent. + * + * <p> The {@code PathMatcher} returned by this method matches on the {@link + * Path#getName name} component of a {@code Path}. If the {@link + * PathMatcher#matches matches} method is invoked with a {@code Path} that + * does not have a {@code name} component then it returns {@code false}. + * + * @param syntax + * The pattern syntax + * @param pattern + * The pattern + * + * @return A file name matcher that matches file names against the pattern + * + * @throws java.util.regex.PatternSyntaxException + * If the pattern is invalid + * @throws UnsupportedOperationException + * If the pattern syntax is not known to the implementation + * + * @see Path#newDirectoryStream(String) + */ + public abstract PathMatcher getNameMatcher(String syntax, String pattern); + + /** + * Returns the {@code UserPrincipalLookupService} for this file system + * <i>(optional operation)</i>. The resulting lookup service may be used to + * lookup user or group names. + * + * <p> <b>Usage Example:</b> + * Suppose we want to make "joe" the owner of a file: + * <pre> + * Path file = ... + * UserPrincipal joe = file.getFileSystem().getUserPrincipalLookupService() + * .lookupPrincipalByName("joe"); + * Attributes.setOwner(file, joe); + * </pre> + * + * @throws UnsupportedOperationException + * If this {@code FileSystem} does not does have a lookup service + * + * @return The {@code UserPrincipalLookupService} for this file system + */ + public abstract UserPrincipalLookupService getUserPrincipalLookupService(); + + /** + * Constructs a new {@link WatchService} <i>(optional operation)</i>. + * + * <p> This method constructs a new watch service that may be used to watch + * registered objects for changes and events. + * + * @return a new watch service + * + * @throws UnsupportedOperationException + * If this {@code FileSystem} does not support watching file system + * objects for changes and events. This exception is not thrown + * by {@code FileSystems} created by the default provider. + * @throws IOException + * If an I/O error occurs + */ + public abstract WatchService newWatchService() throws IOException; +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/FileSystemAlreadyExistsException.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,54 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file; + +/** + * Runtime exception thrown an attempt is made to create a file system that + * already exists. + */ + +public class FileSystemAlreadyExistsException + extends RuntimeException +{ + static final long serialVersionUID = -5438419127181131148L; + + /** + * Constructs an instance of this class. + */ + public FileSystemAlreadyExistsException() { + } + + /** + * Constructs an instance of this class. + * + * @param msg + * The detail message + */ + public FileSystemAlreadyExistsException(String msg) { + super(msg); + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/FileSystemException.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,126 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file; + +import java.io.IOException; + +/** + * Thrown when a file system operation fails on one or two files. This class is + * the general class for file system exceptions. + * + * @since 1.7 + */ + +public class FileSystemException + extends IOException +{ + static final long serialVersionUID = -3055425747967319812L; + + private final String file; + private final String other; + + /** + * Constructs an instance of this class. This constructor should be used + * when an operation involving one file fails and there isn't any additional + * information to explain the reason. + * + * @param file + * A string identifying the file or {@code null} if not known. + */ + public FileSystemException(String file) { + super((String)null); + this.file = file; + this.other = null; + } + + /** + * Constructs an instance of this class. This constructor should be used + * when an operation involving two files fails, or there is additional + * information to explain the reason. + * + * @param file + * A string identifying the file or {@code null} if not known. + * @param other + * A string identifying the other file or {@code null} if there + * isn't another file or if not known + * @param reason + * A reason message with additional information or {@code null} + */ + public FileSystemException(String file, String other, String reason) { + super(reason); + this.file = file; + this.other = other; + } + + /** + * Returns the file used to create this exception. + * + * @return The file (can be {@code null}) + */ + public String getFile() { + return file; + } + + /** + * Returns the other file used to create this exception. + * + * @return The other file (can be {@code null}) + */ + public String getOtherFile() { + return other; + } + + /** + * Returns the string explaining why the file system operation failed. + * + * @return The string explaining why the file system operation failed + */ + public String getReason() { + return super.getMessage(); + } + + /** + * Returns the detail message string. + */ + + public String getMessage() { + if (file == null && other == null) + return getReason(); + StringBuilder sb = new StringBuilder(); + if (file != null) + sb.append(file); + if (other != null) { + sb.append(" -> "); + sb.append(other); + } + if (getReason() != null) { + sb.append(": "); + sb.append(getReason()); + } + return sb.toString(); + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/FileSystemNotFoundException.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,53 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file; + +/** + * Runtime exception thrown when a file system cannot be found. + */ + +public class FileSystemNotFoundException + extends RuntimeException +{ + static final long serialVersionUID = 7999581764446402397L; + + /** + * Constructs an instance of this class. + */ + public FileSystemNotFoundException() { + } + + /** + * Constructs an instance of this class. + * + * @param msg + * The detail message + */ + public FileSystemNotFoundException(String msg) { + super(msg); + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/FileSystems.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,415 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file; + +import java.net.URI; +import java.io.IOException; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.util.*; +import java.lang.reflect.Constructor; + +import org.classpath.icedtea.java.nio.file.spi.FileSystemProvider; + +/** + * Factory methods for file systems. This class defines the {@link #getDefault + * getDefault} method to get the default file system and factory methods to + * construct other types of file systems. + * + * <p> The first invocation of any of the methods defined by this class causes + * the default {@link FileSystemProvider provider} to be loaded. The default + * provider, identified by the URI scheme "file", creates the {@link FileSystem} + * that provides access to the file systems accessible to the Java virtual + * machine. If the process of loading or initializing the default provider fails + * then an unspecified error is thrown. + * + * <p> The first invocation of the {@link FileSystemProvider#installedProviders + * installedProviders} method, by way of invoking any of the {@code + * newFileSystem} methods defined by this class, locates and loads all + * installed file system providers. Installed providers are loaded using the + * service-provider loading facility defined by the {@link ServiceLoader} class. + * Installed providers are loaded using the system class loader. If the + * system class loader cannot be found then the extension class loader is used; + * if there is no extension class loader then the bootstrap class loader is used. + * Providers are typically installed by placing them in a JAR file on the + * application class path or in the extension directory, the JAR file contains a + * provider-configuration file named {@code java.nio.file.spi.FileSystemProvider} + * in the resource directory {@code META-INF/services}, and the file lists one or + * more fully-qualified names of concrete subclass of {@link FileSystemProvider} + * that have a zero argument constructor. + * The ordering that installed providers are located is implementation specific. + * If a provider is instantiated and its {@link FileSystemProvider#getScheme() + * getScheme} returns the same URI scheme of a provider that was previously + * instantiated then the most recently instantiated duplicate is discarded. URI + * schemes are compared without regard to case. During construction a provider + * may safely access files associated with the default provider but care needs + * to be taken to avoid circular loading of other installed providers. If + * circular loading of installed providers is detected then an unspecified error + * is thrown. + * + * <p> This class also defines factory methods that allow a {@link ClassLoader} + * to be specified when locating a provider. As with installed providers, the + * provider classes are identified by placing the provider configuration file + * in the resource directory {@code META-INF/services}. + * + * <p> If a thread initiates the loading of the installed file system providers + * and another thread invokes a method that also attempts to load the providers + * then the method will block until the loading completes. + * + * @since 1.7 + */ + +public final class FileSystems { + private FileSystems() { + } + + // lazy initialization of default file system + private static class LazyInitialization { + static final FileSystem defaultFileSystem = defaultFileSystem(); + + // returns default file system + private static FileSystem defaultFileSystem() { + // load default provider + FileSystemProvider provider = AccessController + .doPrivileged(new PrivilegedAction<FileSystemProvider>() { + public FileSystemProvider run() { + return getDefaultProvider(); + } + }); + + // return file system + return provider.getFileSystem(URI.create("file:///")); + } + + // returns default provider + private static FileSystemProvider getDefaultProvider() { + FileSystemProvider provider = sun.nio.fs.DefaultFileSystemProvider.create(); + + // if the property java.nio.file.spi.DefaultFileSystemProvider is + // set then its value is the name of the default provider (or a list) + String propValue = System + .getProperty("java.nio.file.spi.DefaultFileSystemProvider"); + if (propValue != null) { + for (String cn: propValue.split(",")) { + try { + Class<?> c = Class + .forName(cn, true, ClassLoader.getSystemClassLoader()); + Constructor<?> ctor = c + .getDeclaredConstructor(FileSystemProvider.class); + provider = (FileSystemProvider)ctor.newInstance(provider); + + // must be "file" + if (!provider.getScheme().equals("file")) + throw new Error("Default provider must use scheme 'file'"); + + } catch (Exception x) { + throw new Error(x); + } + } + } + return provider; + } + } + + /** + * Returns the default {@code FileSystem}. The default file system creates + * objects that provide access to the file systems accessible to the Java + * virtual machine. The <em>working directory</em> of the file system is + * the current user directory, named by the system property {@code user.dir}. + * This allows for interoperability with the {@link java.io.File java.io.File} + * class. + * + * <p> The first invocation of any of the methods defined by this class + * locates the default {@link FileSystemProvider provider} object. Where the + * system property {@code java.nio.file.spi.DefaultFileSystemProvider} is + * not defined then the default provider is a system-default provider that + * is invoked to create the default file system. + * + * <p> If the system property {@code java.nio.file.spi.DefaultFileSystemProvider} + * is defined then it is taken to be a list of one or more fully-qualified + * names of concrete provider classes identified by the URI scheme + * {@code "file"}. Where the property is a list of more than one name then + * the names are separated by a comma. Each class is loaded, using the system + * class loader, and instantiated by invoking a one argument constructor + * whose formal parameter type is {@code FileSystemProvider}. The providers + * are loaded and instantiated in the order they are listed in the property. + * If this process fails or a provider's scheme is not equal to {@code "file"} + * then an unspecified error is thrown. URI schemes are normally compared + * without regard to case but for the default provider, the scheme is + * required to be {@code "file"}. The first provider class is instantiated + * by invoking it with a reference to the system-default provider. + * The second provider class is instantiated by invoking it with a reference + * to the first provider instance. The third provider class is instantiated + * by invoking it with a reference to the second instance, and so on. The + * last provider to be instantiated becomes the default provider; its {@code + * getFileSystem} method is invoked with the URI {@code "file:///"} to create + * the default file system. + * + * <p> Subsequent invocations of this method return the file system that was + * returned by the first invocation. + * + * @return the default file system + */ + public static FileSystem getDefault() { + return LazyInitialization.defaultFileSystem; + } + + /** + * Returns a reference to an existing {@code FileSystem}. + * + * <p> This method iterates over the {@link FileSystemProvider#installedProviders() + * installed} providers to locate the provider that is identified by the URI + * {@link URI#getScheme scheme} of the given URI. URI schemes are compared + * without regard to case. The exact form of the URI is highly provider + * dependent. If found, the provider's {@link FileSystemProvider#getFileSystem + * getFileSystem} method is invoked to obtain a reference to the {@code + * FileSystem}. + * + * <p> Once a file system created by this provider is {@link FileSystem#close + * closed} it is provider-dependent if this method returns a reference to + * the closed file system or throws {@link FileSystemNotFoundException}. + * If the provider allows a new file system to be created with the same URI + * as a file system it previously created then this method throws the + * exception if invoked after the file system is closed (and before a new + * instance is created by the {@link #newFileSystem newFileSystem} method). + * + * <p> If a security manager is installed then a provider implementation + * may require to check a permission before returning a reference to an + * existing file system. In the case of the {@link FileSystems#getDefault + * default} file system, no permission check is required. + * + * @throws IllegalArgumentException + * If the pre-conditions for the {@code uri} parameter aren't met + * @throws FileSystemNotFoundException + * If the file system, identified by the URI, does not exist + * @throws ProviderNotFoundException + * If a provider supporting the URI scheme is not installed + * @throws SecurityException + * If a security manager is installed and it denies an unspecified + * permission. + */ + public static FileSystem getFileSystem(URI uri) { + String scheme = uri.getScheme(); + for (FileSystemProvider provider: FileSystemProvider.installedProviders()) { + if (scheme.equalsIgnoreCase(provider.getScheme())) { + return provider.getFileSystem(uri); + } + } + throw new ProviderNotFoundException("Provider \"" + scheme + "\" not found"); + } + + /** + * Constructs a new file system that is identified by a {@link URI} + * + * <p> This method iterates over the {@link FileSystemProvider#installedProviders() + * installed} providers to locate the provider that is identified by the URI + * {@link URI#getScheme scheme} of the given URI. URI schemes are compared + * without regard to case. The exact form of the URI is highly provider + * dependent. If found, the provider's {@link FileSystemProvider#newFileSystem(URI,Map) + * newFileSystem(URI,Map)} method is invoked to construct the new file system. + * + * <p> Once a file system is {@link FileSystem#close closed} it is + * provider-dependent if the provider allows a new file system to be created + * with the same URI as a file system it previously created. + * + * <p> <b>Usage Example:</b> + * Suppose there is a provider identified by the scheme {@code "memory"} + * installed: + * <pre> + * Map<String,String> env = new HashMap<String,String>(); + * env.put("capacity", "16G"); + * env.put("blockSize", "4k"); + * FileSystem fs = FileSystems.newFileSystem(URI.create("memory:///?name=logfs"), env); + * </pre> + * + * @param uri + * The URI identifying the file system + * @param env + * A map of provider specific properties to configure the file system; + * may be empty + * + * @return A new file system + * + * @throws IllegalArgumentException + * If the pre-conditions for the {@code uri} parameter aren't met, + * or the {@code env} parameter does not contain properties required + * by the provider, or a property value is invalid + * @throws FileSystemAlreadyExistsException + * If the file system has already been created + * @throws ProviderNotFoundException + * If a provider supporting the URI scheme is not installed + * @throws IOException + * An I/O error occurs creating the file system + * @throws SecurityException + * If a security manager is installed and it denies an unspecified + * permission required by the file system provider implementation + */ + public static FileSystem newFileSystem(URI uri, Map<String,?> env) + throws IOException + { + return newFileSystem(uri, env, null); + } + + /** + * Constructs a new file system that is identified by a {@link URI} + * + * <p> This method first attempts to locate an installed provider in exactly + * the same manner as the {@link #newFileSystem(URI,Map) newFileSystem(URI,Map)} + * method. If none of the installed providers support the URI scheme then an + * attempt is made to locate the provider using the given class loader. If a + * provider supporting the URI scheme is located then its {@link + * FileSystemProvider#newFileSystem(URI,Map) newFileSystem(URI,Map)} is + * invoked to construct the new file system. + * + * @param uri + * The URI identifying the file system + * @param env + * A map of provider specific properties to configure the file system; + * may be empty + * @param loader + * The class loader to locate the provider or {@code null} to only + * attempt to locate an installed provider + * + * @return A new file system + * + * @throws IllegalArgumentException + * If the pre-conditions for the {@code uri} parameter aren't met, + * or the {@code env} parameter does not contain properties required + * by the provider, or a property value is invalid + * @throws FileSystemAlreadyExistsException + * If the URI scheme identifies an installed provider and the file + * system has already been created + * @throws ProviderNotFoundException + * If a provider supporting the URI scheme is not found + * @throws ServiceConfigurationError + * When an error occurs while loading a service provider + * @throws IOException + * An I/O error occurs creating the file system + * @throws SecurityException + * If a security manager is installed and it denies an unspecified + * permission required by the file system provider implementation + */ + public static FileSystem newFileSystem(URI uri, Map<String,?> env, ClassLoader loader) + throws IOException + { + String scheme = uri.getScheme(); + + // check installed providers + for (FileSystemProvider provider: FileSystemProvider.installedProviders()) { + if (scheme.equalsIgnoreCase(provider.getScheme())) { + return provider.newFileSystem(uri, env); + } + } + + // if not found, use service-provider loading facility + if (loader != null) { + ServiceLoader<FileSystemProvider> sl = ServiceLoader + .load(FileSystemProvider.class, loader); + for (FileSystemProvider provider: sl) { + if (scheme.equalsIgnoreCase(provider.getScheme())) { + return provider.newFileSystem(uri, env); + } + } + } + + throw new ProviderNotFoundException("Provider \"" + scheme + "\" not found"); + } + + /** + * Constructs a new {@code FileSystem} to access the contents of a file as a + * file system. + * + * <p> This method makes use of specialized providers that create pseudo file + * systems where the contents of one or more files is treated as a file + * system. The {@code file} parameter is a reference to an existing file + * and the {@code env} parameter is a map of provider specific properties to + * configure the file system. + * + * <p> This method iterates over the {@link FileSystemProvider#installedProviders() + * installed} providers. It invokes, in turn, each provider's {@link + * FileSystemProvider#newFileSystem(FileRef,Map) newFileSystem(FileRef,Map)} method. + * If a provider returns a file system then the iteration terminates + * and the file system is returned. If none of the installed providers return + * a {@code FileSystem} then an attempt is made to locate the provider using + * the given class loader. If a provider returns a file system then the lookup + * terminates and the file system is returned. + * + * @param file + * A reference to a file + * @param env + * A map of provider specific properties to configure the file system; + * may be empty + * @param loader + * The class loader to locate the provider or {@code null} to only + * attempt to locate an installed provider + * + * @return A new file system + * + * @throws IllegalArgumentException + * If the {@code env} parameter does not contain properties required + * by the provider, or a property value is invalid + * @throws ProviderNotFoundException + * If a provider supporting this file type cannot be located + * @throws ServiceConfigurationError + * When an error occurs while loading a service provider + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * If a security manager is installed and it denies an unspecified + * permission. + */ + public static FileSystem newFileSystem(FileRef file, + Map<String,?> env, + ClassLoader loader) + throws IOException + { + if (file == null) + throw new NullPointerException(); + + // check installed providers + for (FileSystemProvider provider: FileSystemProvider.installedProviders()) { + try { + return provider.newFileSystem(file, env); + } catch (UnsupportedOperationException uoe) { + } + } + + // if not found, use service-provider loading facility + if (loader != null) { + ServiceLoader<FileSystemProvider> sl = ServiceLoader + .load(FileSystemProvider.class, loader); + for (FileSystemProvider provider: sl) { + try { + return provider.newFileSystem(file, env); + } catch (UnsupportedOperationException uoe) { + } + } + } + + throw new ProviderNotFoundException("Provider not found"); + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/FileTreeWalker.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,247 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file; + +import java.io.IOException; +import java.util.*; + +import org.classpath.icedtea.java.nio.file.attribute.Attributes; +import org.classpath.icedtea.java.nio.file.attribute.BasicFileAttributes; + +/** + * Simple file tree walker that works in a similar manner to nftw(3C). + * + * @see Files#walkFileTree + */ + +class FileTreeWalker { + private final boolean followLinks; + private final boolean detectCycles; + private final LinkOption[] linkOptions; + private final FileVisitor<? super Path> visitor; + + FileTreeWalker(Set<FileVisitOption> options, FileVisitor<? super Path> visitor) { + boolean fl = false; + boolean dc = false; + for (FileVisitOption option: options) { + switch (option) { + case FOLLOW_LINKS : fl = true; break; + case DETECT_CYCLES : dc = true; break; + default: + if (option == null) + throw new NullPointerException("Visit options contains 'null'"); + throw new AssertionError("Should not get here"); + } + } + this.followLinks = fl; + this.detectCycles = fl | dc; + this.linkOptions = (fl) ? new LinkOption[0] : + new LinkOption[] { LinkOption.NOFOLLOW_LINKS }; + this.visitor = visitor; + } + + /** + * Walk file tree starting at the given file + */ + void walk(Path start, int maxDepth) { + FileVisitResult result = walk(start, + maxDepth, + new ArrayList<AncestorDirectory>()); + if (result == null) { + throw new NullPointerException("Visitor returned 'null'"); + } + } + + /** + * @param file + * The directory to visit + * @param path + * list of directories that is relative path from starting file + * @param depth + * Depth remaining + * @param ancestors + * use when cycle detection is enabled + */ + private FileVisitResult walk(Path file, + int depth, + List<AncestorDirectory> ancestors) + { + // depth check + if (depth-- < 0) + return FileVisitResult.CONTINUE; + + BasicFileAttributes attrs = null; + IOException exc = null; + + // attempt to get attributes of file. If fails and we are following + // links then a link target might not exist so get attributes of link + try { + try { + attrs = Attributes.readBasicFileAttributes(file, linkOptions); + } catch (IOException x1) { + if (followLinks) { + try { + attrs = Attributes + .readBasicFileAttributes(file, LinkOption.NOFOLLOW_LINKS); + } catch (IOException x2) { + exc = x2; + } + } else { + exc = x1; + } + } + } catch (SecurityException x) { + return FileVisitResult.CONTINUE; + } + + // unable to get attributes of file + if (exc != null) { + return visitor.visitFileFailed(file, exc); + } + + // file is not a directory so invoke visitFile method + if (!attrs.isDirectory()) { + return visitor.visitFile(file, attrs); + } + + // check for cycles + if (detectCycles) { + Object key = attrs.fileKey(); + + // if this directory and ancestor has a file key then we compare + // them; otherwise we use less efficient isSameFile test. + for (AncestorDirectory ancestor: ancestors) { + Object ancestorKey = ancestor.fileKey(); + if (key != null && ancestorKey != null) { + if (key.equals(ancestorKey)) { + // cycle detected + return visitor.visitFile(file, attrs); + } + } else { + try { + if (file.isSameFile(ancestor.file())) { + // cycle detected + return visitor.visitFile(file, attrs); + } + } catch (IOException x) { + // ignore + } catch (SecurityException x) { + // ignore + } + } + } + + ancestors.add(new AncestorDirectory(file, key)); + } + + // visit directory + try { + DirectoryStream<Path> stream = null; + FileVisitResult result; + + // open the directory + try { + stream = file.newDirectoryStream(); + } catch (IOException x) { + return visitor.preVisitDirectoryFailed(file, x); + } catch (SecurityException x) { + // ignore, as per spec + return FileVisitResult.CONTINUE; + } + + // the exception notified to the postVisitDirectory method + IOException ioe = null; + + // invoke preVisitDirectory and then visit each entry + try { + result = visitor.preVisitDirectory(file); + if (result != FileVisitResult.CONTINUE) { + return result; + } + + // if an I/O occurs during iteration then a CME is thrown. We + // need to distinguish this from a CME thrown by the visitor. + boolean inAction = false; + + try { + for (Path entry: stream) { + inAction = true; + result = walk(entry, depth, ancestors); + inAction = false; + + // returning null will cause NPE to be thrown + if (result == null || result == FileVisitResult.TERMINATE) + return result; + + // skip remaining siblings in this directory + if (result == FileVisitResult.SKIP_SIBLINGS) + break; + } + } catch (ConcurrentModificationException x) { + // if CME thrown because the iteration failed then remember + // the IOException so that it is notified to postVisitDirectory + if (!inAction) { + // iteration failed + Throwable t = x.getCause(); + if (t instanceof IOException) + ioe = (IOException)t; + } + if (ioe == null) + throw x; + } + } finally { + try { + stream.close(); + } catch (IOException x) { } + } + + // invoke postVisitDirectory last + return visitor.postVisitDirectory(file, ioe); + + } finally { + // remove key from trail if doing cycle detection + if (detectCycles) { + ancestors.remove(ancestors.size()-1); + } + } + } + + private static class AncestorDirectory { + private final FileRef dir; + private final Object key; + AncestorDirectory(FileRef dir, Object key) { + this.dir = dir; + this.key = key; + } + FileRef file() { + return dir; + } + Object fileKey() { + return key; + } + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/FileVisitOption.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,46 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file; + +/** + * Defines the file tree traversal options. + * + * @since 1.7 + * + * @see Files#walkFileTree + */ + +public enum FileVisitOption { + /** + * Follow symbolic links. + */ + FOLLOW_LINKS, + /** + * Detect cycles in the file tree. + */ + DETECT_CYCLES; +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/FileVisitResult.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,63 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file; + +/** + * The result type of a {@link FileVisitor FileVisitor}. + * + * @since 1.7 + * + * @see Files#walkFileTree + */ + +public enum FileVisitResult { + /** + * Continue. When returned from a {@link FileVisitor#preVisitDirectory + * preVisitDirectory} method then the entries in the directory should also + * be visited. + */ + CONTINUE, + /** + * Terminate. + */ + TERMINATE, + /** + * Continue without visiting the entries in this directory. This result + * is only meaningful when returned from the {@link + * FileVisitor#preVisitDirectory preVisitDirectory} method; otherwise + * this result type is the same as returning {@link #CONTINUE}. + */ + SKIP_SUBTREE, + /** + * Continue without visiting the <em>siblings</em> of this file or directory. + * If returned from the {@link FileVisitor#preVisitDirectory + * preVisitDirectory} method then the entries in the directory are also + * skipped and the {@link FileVisitor#postVisitDirectory postVisitDirectory} + * method is not invoked. + */ + SKIP_SIBLINGS; +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/FileVisitor.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,177 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file; + +import java.io.IOException; + +import org.classpath.icedtea.java.nio.file.attribute.BasicFileAttributes; + +/** + * A visitor of files. An implementation of this interface is provided to the + * {@link Files#walkFileTree walkFileTree} utility method to visit each file + * in a tree. + * + * <p> <b>Usage Examples:</b> + * Suppose we want to delete a file tree. In that case, each directory should + * be deleted after the entries in the directory are deleted. + * <pre> + * Path start = ... + * Files.walkFileTree(start, new SimpleFileVisitor<Path>() { + * @Override + * public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { + * try { + * file.delete(false); + * } catch (IOException exc) { + * // failed to delete + * } + * return FileVisitResult.CONTINUE; + * } + * @Override + * public FileVisitResult postVisitDirectory(Path dir, IOException e) { + * if (e == null) { + * try { + * dir.delete(false); + * } catch (IOException exc) { + * // failed to delete + * } + * } else { + * // directory iteration failed + * } + * return FileVisitResult.CONTINUE; + * } + * }); + * </pre> + * <p> Furthermore, suppose we want to copy a file tree rooted at a source + * directory to a target location. In that case, symbolic links should be + * followed and the target directory should be created before the entries in + * the directory are copied. + * <pre> + * final Path source = ... + * final Path target = ... + * + * Files.walkFileTree(source, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, + * new SimpleFileVisitor<Path>() { + * @Override + * public FileVisitResult preVisitDirectory(Path dir) { + * try { + * dir.copyTo(target.resolve(source.relativize(dir))); + * } catch (FileAlreadyExistsException e) { + * // ignore + * } catch (IOException e) { + * // copy failed, skip rest of directory and descendants + * return SKIP_SUBTREE; + * } + * return CONTINUE; + * } + * @Override + * public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { + * try { + * file.copyTo(target.resolve(source.relativize(file))); + * } catch (IOException e) { + * // copy failed + * } + * return CONTINUE; + * } + * }); + * </pre> + * + * @since 1.7 + */ + +public interface FileVisitor<T extends FileRef> { + + /** + * Invoked for a directory before entries in the directory are visited. + * + * <p> If this method returns {@link FileVisitResult#CONTINUE CONTINUE}, + * then entries in the directory are visited. If this method returns {@link + * FileVisitResult#SKIP_SUBTREE SKIP_SUBTREE} or {@link + * FileVisitResult#SKIP_SIBLINGS SKIP_SIBLINGS} then entries in the + * directory (and any descendants) will not be visited. + * + * @param dir + * A reference to the directory + * + * @return the visit result + */ + FileVisitResult preVisitDirectory(T dir); + + /** + * Invoked for a directory that could not be opened. + * + * @param dir + * A reference to the directory + * @param exc + * The I/O exception thrown from the attempt to open the directory + * + * @return the visit result + */ + FileVisitResult preVisitDirectoryFailed(T dir, IOException exc); + + /** + * Invoked for a file in a directory. + * + * @param file + * A reference to the file + * @param attrs + * The file's basic attributes + * + * @return the visit result + */ + FileVisitResult visitFile(T file, BasicFileAttributes attrs); + + /** + * Invoked for a file when its basic file attributes could not be read. + * + * @param file + * A reference to the file + * @param exc + * The I/O exception thrown from the attempt to read the file + * attributes + * + * @return the visit result + */ + FileVisitResult visitFileFailed(T file, IOException exc); + + /** + * Invoked for a directory after entries in the directory, and all of their + * descendants, have been visited. This method is also invoked when iteration + * of the directory completes prematurely (by a {@link #visitFile visitFile} + * method returning {@link FileVisitResult#SKIP_SIBLINGS SKIP_SIBLINGS}, + * or an I/O error when iterating over the directory). + * + * @param dir + * A reference to the directory + * @param exc + * {@code null} if the iteration of the directory completes without + * an error; otherwise the I/O exception that caused the iteration + * of the directory to complete prematurely + * + * @return the visit result + */ + FileVisitResult postVisitDirectory(T dir, IOException exc); +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/Files.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,405 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file; + +import java.io.IOException; +import java.util.*; +import java.security.AccessController; +import java.security.PrivilegedAction; + +import org.classpath.icedtea.java.nio.file.spi.FileTypeDetector; + +/** + * Utility methods for files and directories. + * + * @since 1.7 + */ + +public final class Files { + private Files() { } + + // lazy loading of default and installed file type detectors + private static class LazyInitialization { + static final FileTypeDetector defaultFileTypeDetector = + sun.nio.fs.DefaultFileTypeDetector.create(); + static final List<FileTypeDetector> installeDetectors = + loadInstalledDetectors(); + + // loads all installed file type detectors + private static List<FileTypeDetector> loadInstalledDetectors() { + return AccessController + .doPrivileged(new PrivilegedAction<List<FileTypeDetector>>() { + public List<FileTypeDetector> run() { + List<FileTypeDetector> list = new ArrayList<FileTypeDetector>(); + ServiceLoader<FileTypeDetector> loader = ServiceLoader + .load(FileTypeDetector.class, ClassLoader.getSystemClassLoader()); + for (FileTypeDetector detector: loader) { + list.add(detector); + } + return list; + }}); + } + } + + /** + * Probes the content type of a file. + * + * <p> This method uses the installed {@link FileTypeDetector} implementations + * to probe the given file to determine its content type. Each file type + * detector's {@link FileTypeDetector#probeContentType probeContentType} is + * invoked, in turn, to probe the file type. If the file is recognized then + * the content type is returned. If the file is not recognized by any of the + * installed file type detectors then a system-default file type detector is + * invoked to guess the content type. + * + * <p> A given invocation of the Java virtual machine maintains a system-wide + * list of file type detectors. Installed file type detectors are loaded + * using the service-provider loading facility defined by the {@link ServiceLoader} + * class. Installed file type detectors are loaded using the system class + * loader. If the system class loader cannot be found then the extension class + * loader is used; If the extension class loader cannot be found then the + * bootstrap class loader is used. File type detectors are typically installed + * by placing them in a JAR file on the application class path or in the + * extension directory, the JAR file contains a provider-configuration file + * named {@code java.nio.file.spi.FileTypeDetector} in the resource directory + * {@code META-INF/services}, and the file lists one or more fully-qualified + * names of concrete subclass of {@code FileTypeDetector } that have a zero + * argument constructor. If the process of locating or instantiating the + * installed file type detectors fails then an unspecified error is thrown. + * The ordering that installed providers are located is implementation + * specific. + * + * <p> The return value of this method is the string form of the value of a + * Multipurpose Internet Mail Extension (MIME) content type as + * defined by <a href="http://www.ietf.org/rfc/rfc2045.txt"><i>RFC 2045: + * Multipurpose Internet Mail Extensions (MIME) Part One: Format of Internet + * Message Bodies</i></a>. The string is guaranteed to be parsable according + * to the grammar in the RFC. + * + * @param file + * The file reference + * + * @return The content type of the file, or {@code null} if the content + * type cannot be determined + * + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * If a security manager is installed and it denies an unspecified + * permission required by a file type detector implementation. + * + * @see DirectoryStreamFilters#newContentTypeFilter + */ + public static String probeContentType(FileRef file) + throws IOException + { + // try installed file type detectors + for (FileTypeDetector detector: LazyInitialization.installeDetectors) { + String result = detector.probeContentType(file); + if (result != null) + return result; + } + + // fallback to default + return LazyInitialization.defaultFileTypeDetector.probeContentType(file); + } + + /** + * Invokes a {@link FileAction} for each entry in a directory accepted + * by a given {@link java.nio.file.DirectoryStream.Filter filter}. + * + * <p> This method opens the given directory and invokes the file action's + * {@link FileAction#invoke invoke} method for each entry accepted by the + * filter. When iteration is completed then the directory is closed. If the + * {@link DirectoryStream#close close} method throws an {@code IOException} + * then it is silently ignored. + * + * <p> If the {@code FileAction}'s {@code invoke} method terminates due + * to an uncaught {@link IOException}, {@code Error} or {@code RuntimeException} + * then the exception is propagated by this method after closing the + * directory. + * + * @param dir + * The directory + * @param filter + * The filter, or {@code null} to accept all entries + * @param action + * The {@code FileAction} to invoke for each accepted entry + * + * @throws NotDirectoryException + * If the {@code dir} parameter is not a directory <i>(optional + * specific exception)</i> + * @throws IOException + * If an I/O error occurs or the {@code invoke} method terminates + * due to an uncaught {@code IOException} + * @throws SecurityException + * In the case of the default provider, the {@link + * SecurityManager#checkRead(String) checkRead} method is invoked + * to check read access to the directory. + */ + public static void withDirectory(Path dir, + DirectoryStream.Filter<? super Path> filter, + FileAction<? super Path> action) + throws IOException + { + // explicit null check required in case directory is empty + if (action == null) + throw new NullPointerException(); + + DirectoryStream<Path> stream = dir.newDirectoryStream(filter); + try { + // set to true when invoking the action so as to distinguish a + // CME thrown by the iteration from a CME thrown by the invoke + boolean inAction = false; + try { + for (Path entry: stream) { + inAction = true; + action.invoke(entry); + inAction = false; + } + } catch (ConcurrentModificationException cme) { + if (!inAction) { + Throwable cause = cme.getCause(); + if (cause instanceof IOException) + throw (IOException)cause; + } + throw cme; + } + } finally { + try { + stream.close(); + } catch (IOException x) { } + } + } + + /** + * Invokes a {@link FileAction} for each entry in a directory with a + * file name that matches a given pattern. + * + * <p> This method opens the given directory and invokes the file action's + * {@link FileAction#invoke invoke} method for each entry that matches the + * given pattern. When iteration is completed then the directory is closed. + * If the {@link DirectoryStream#close close} method throws an {@code + * IOException} then it is silently ignored. + * + * <p> If the {@code FileAction}'s {@code invoke} method terminates due + * to an uncaught {@link IOException}, {@code Error} or {@code RuntimeException} + * then the exception is propagated by this method after closing the + * directory. + * + * <p> The globbing pattern language supported by this method is as + * specified by the {@link FileSystem#getNameMatcher getNameMatcher} method. + * + * @param dir + * The directory + * @param glob + * The globbing pattern + * @param action + * The {@code FileAction} to invoke for each entry + * + * @throws NotDirectoryException + * If the {@code dir} parameter is not a directory <i>(optional + * specific exception)</i> + * @throws IOException + * If an I/O error occurs or the {@code invoke} method terminates + * due to an uncaught {@code IOException} + * @throws SecurityException + * In the case of the default provider, the {@link + * SecurityManager#checkRead(String) checkRead} method is invoked + * to check read access to the directory. + */ + public static void withDirectory(Path dir, + String glob, + FileAction<? super Path> action) + throws IOException + { + final PathMatcher matcher = dir.getFileSystem().getNameMatcher("glob", glob); + DirectoryStream.Filter<Path> filter = new DirectoryStream.Filter<Path>() { + + public boolean accept(Path entry) { + return matcher.matches(entry.getName()); + } + }; + withDirectory(dir, filter, action); + } + + /** + * Invokes a {@link FileAction} for all entries in a directory. + * + * <p> This method works as if invoking it were equivalent to evaluating the + * expression: + * <blockquote><pre> + * withDirectory(dir, "*", action) + * </pre></blockquote> + * + * @param dir + * The directory + * @param action + * The {@code FileAction} to invoke for each entry + * + * @throws NotDirectoryException + * If the {@code dir} parameter is not a directory <i>(optional + * specific exception)</i> + * @throws IOException + * If an I/O error occurs or the {@code invoke} method terminates + * due to an uncaught {@code IOException} + * @throws SecurityException + * In the case of the default provider, the {@link + * SecurityManager#checkRead(String) checkRead} method is invoked + * to check read access to the directory. + */ + public static void withDirectory(Path dir, FileAction<? super Path> action) + throws IOException + { + withDirectory(dir, "*", action); + } + + /** + * Walks a file tree. + * + * <p> This method walks a file tree rooted at a given starting file. The + * file tree traversal is <em>depth-first</em> with the given {@link + * FileVisitor} invoked for each file encountered. File tree traversal + * completes when all accessible files in the tree have been visited, a + * visitor returns a result of {@link FileVisitResult#TERMINATE TERMINATE}, + * or the visitor terminates due to an uncaught {@code Error} or {@code + * RuntimeException}. + * + * <p> For each file encountered this method attempts to gets its {@link + * java.nio.file.attribute.BasicFileAttributes}. If the file is not a + * directory then the {@link FileVisitor#visitFile visitFile} method is + * invoked with the file attributes. If the file attributes cannot be read, + * due to an I/O exception, then the {@link FileVisitor#visitFileFailed + * visitFileFailed} method is invoked with the I/O exception. + * + * <p> Where the file is a directory, this method attempts to open it by + * invoking its {@link Path#newDirectoryStream newDirectoryStream} method. + * Where the directory could not be opened, due to an {@code IOException}, + * then the {@link FileVisitor#preVisitDirectoryFailed preVisitDirectoryFailed} + * method is invoked with the I/O exception, after which, the file tree walk + * continues, by default, at the next <em>sibling</em> of the directory. + * + * <p> Where the directory is opened successfully, then the entries in the + * directory, and their <em>descendants</em> are visited. When all entries + * have been visited, or an I/O error occurs during iteration of the + * directory, then the directory is closed and the visitor's {@link + * FileVisitor#postVisitDirectory postVisitDirectory} method is invoked. + * The file tree walk then continues, by default, at the next <em>sibling</em> + * of the directory. + * + * <p> By default, symbolic links are not automatically followed by this + * method. If the {@code options} parameter contains the {@link + * FileVisitOption#FOLLOW_LINKS FOLLOW_LINKS} option then symbolic links are + * followed. When following links, and the attributes of the target cannot + * be read, then this method attempts to get the {@code BasicFileAttributes} + * of the link. If they can be read then the {@code visitFile} method is + * invoked with the attributes of the link (otherwise the {@code visitFileFailed} + * method is invoked as specified above). + * + * <p> If the {@code options} parameter contains the {@link + * FileVisitOption#DETECT_CYCLES DETECT_CYCLES} or {@link + * FileVisitOption#FOLLOW_LINKS FOLLOW_LINKS} options then this method keeps + * track of directories visited so that cycles can be detected. A cycle + * arises when there is an entry in a directory that is an ancestor of the + * directory. Cycle detection is done by recording the {@link + * java.nio.file.attribute.BasicFileAttributes#fileKey file-key} of directories, + * or if file keys are not available, by invoking the {@link FileRef#isSameFile + * isSameFile} method to test if a directory is the same file as an + * ancestor. When a cycle is detected the {@link FileVisitor#visitFile + * visitFile} is invoked with the attributes of the directory. The {@link + * java.nio.file.attribute.BasicFileAttributes#isDirectory isDirectory} + * method may be used to test if the file is a directory and that a cycle is + * detected. The {@code preVisitDirectory} and {@code postVisitDirectory} + * methods are not invoked. + * + * <p> The {@code maxDepth} parameter is the maximum number of levels of + * directories to visit. A value of {@code 0} means that only the starting + * file is visited, unless denied by the security manager. A value of + * {@link Integer#MAX_VALUE MAX_VALUE} may be used to indicate that all + * levels should be visited. + * + * <p> If a visitor returns a result of {@code null} then {@code + * NullPointerException} is thrown. + * + * <p> When a security manager is installed and it denies access to a file + * (or directory), then it is ignored and the visitor is not invoked for + * that file (or directory). + * + * @param start + * The starting file + * @param options + * Options to configure the traversal + * @param maxDepth + * The maximum number of directory levels to visit + * @param visitor + * The file visitor to invoke for each file + * + * @throws IllegalArgumentException + * If the {@code maxDepth} parameter is negative + * @throws SecurityException + * If the security manager denies access to the starting file. + * In the case of the default provider, the {@link + * SecurityManager#checkRead(String) checkRead} method is invoked + * to check read access to the directory. + */ + public static void walkFileTree(Path start, + Set<FileVisitOption> options, + int maxDepth, + FileVisitor<? super Path> visitor) + { + if (maxDepth < 0) + throw new IllegalArgumentException("'maxDepth' is negative"); + new FileTreeWalker(options, visitor).walk(start, Integer.MAX_VALUE); + } + + /** + * Walks a file tree. + * + * <p> This method works as if invoking it were equivalent to evaluating the + * expression: + * <blockquote><pre> + * walkFileTree(start, EnumSet.noneOf(FileVisitOption.class), Integer.MAX_VALUE, visitor) + * </pre></blockquote> + * + * @param start + * The starting file + * @param visitor + * The file visitor to invoke for each file + * + * @throws SecurityException + * If the security manager denies access to the starting file. + * In the case of the default provider, the {@link + * SecurityManager#checkRead(String) checkRead} method is invoked + * to check read access to the directory. + */ + public static void walkFileTree(Path start, FileVisitor<? super Path> visitor) { + walkFileTree(start, + EnumSet.noneOf(FileVisitOption.class), + Integer.MAX_VALUE, + visitor); + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/InvalidPathException.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,131 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file; + +/** + * Unchecked exception thrown when path string cannot be converted into a + * {@link Path} because the path string contains invalid characters, or + * the path string is invalid for other file system specific reasons. + */ + +public class InvalidPathException + extends IllegalArgumentException +{ + static final long serialVersionUID = 4355821422286746137L; + + private String input; + private int index; + + /** + * Constructs an instance from the given input string, reason, and error + * index. + * + * @param input The input string + * @param reason A string explaining why the input was rejected + * @param index The index at which the error occurred, + * or <tt>-1</tt> if the index is not known + * + * @throws NullPointerException + * If either the input or reason strings are <tt>null</tt> + * + * @throws IllegalArgumentException + * If the error index is less than <tt>-1</tt> + */ + public InvalidPathException(String input, String reason, int index) { + super(reason); + if ((input == null) || (reason == null)) + throw new NullPointerException(); + if (index < -1) + throw new IllegalArgumentException(); + this.input = input; + this.index = index; + } + + /** + * Constructs an instance from the given input string and reason. The + * resulting object will have an error index of <tt>-1</tt>. + * + * @param input The input string + * @param reason A string explaining why the input was rejected + * + * @throws NullPointerException + * If either the input or reason strings are <tt>null</tt> + */ + public InvalidPathException(String input, String reason) { + this(input, reason, -1); + } + + /** + * Returns the input string. + * + * @return The input string + */ + public String getInput() { + return input; + } + + /** + * Returns a string explaining why the input string was rejected. + * + * @return The reason string + */ + public String getReason() { + return super.getMessage(); + } + + /** + * Returns an index into the input string of the position at which the + * error occurred, or <tt>-1</tt> if this position is not known. + * + * @return The error index + */ + public int getIndex() { + return index; + } + + /** + * Returns a string describing the error. The resulting string + * consists of the reason string followed by a colon character + * (<tt>':'</tt>), a space, and the input string. If the error index is + * defined then the string <tt>" at index "</tt> followed by the index, in + * decimal, is inserted after the reason string and before the colon + * character. + * + * @return A string describing the error + */ + public String getMessage() { + StringBuffer sb = new StringBuffer(); + sb.append(getReason()); + if (index > -1) { + sb.append(" at index "); + sb.append(index); + } + sb.append(": "); + sb.append(input); + return sb.toString(); + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/LinkOption.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,44 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file; + +/** + * Defines the options as to how symbolic links are handled. + * + * @since 1.7 + */ + +public enum LinkOption implements OpenOption, CopyOption { + /** + * Do not follow symbolic links. + * + * @see FileRef#getFileAttributeView(Class,LinkOption[]) + * @see Path#copyTo + * @see SecureDirectoryStream#newByteChannel + */ + NOFOLLOW_LINKS; +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/LinkPermission.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,108 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file; + +import java.security.BasicPermission; + +/** + * The {@code Permission} class for link creation operations. + * + * <p> The following table provides a summary description of what the permission + * allows, and discusses the risks of granting code the permission. + * + * <table border=1 cellpadding=5 + * summary="Table shows permission target name, what the permission allows, and associated risks"> + * <tr> + * <th>Permission Target Name</th> + * <th>What the Permission Allows</th> + * <th>Risks of Allowing this Permission</th> + * </tr> + * <tr> + * <td>hard</td> + * <td> Ability to add an existing file to a directory. This is sometimes + * known as creating a link, or hard link. </td> + * <td> Extreme care should be taken when granting this permission. It allows + * linking to any file or directory in the file system thus allowing the + * attacker to access to all files. </td> + * </tr> + * <tr> + * <td>symbolic</td> + * <td> Ability to create symbolic links. </td> + * <td> Extreme care should be taken when granting this permission. It allows + * linking to any file or directory in the file system thus allowing the + * attacker to access to all files. </td> + * </tr> + * </table> + * + * @since 1.7 + * + * @see Path#createLink + * @see Path#createSymbolicLink + */ +public final class LinkPermission extends BasicPermission { + static final long serialVersionUID = -1441492453772213220L; + + private void checkName(String name) { + if (!name.equals("hard") && !name.equals("symbolic")) { + throw new IllegalArgumentException("name: " + name); + } + } + + /** + * Constructs a {@code LinkPermission} with the specified name. + * + * @param name + * The name of the permission. It must be "hard" or "symbolic". + * + * @throws IllegalArgumentException + * If name is empty or invalid. + */ + public LinkPermission(String name) { + super(name); + checkName(name); + } + + /** + * Constructs a {@code LinkPermission} with the specified name. + * + * @param name + * The name of the permission; must be "hard" or "symbolic". + * @param actions + * The actions for the permission; must be the empty string or + * {@code null} + * + * @throws IllegalArgumentException + * If name is empty or invalid. + */ + public LinkPermission(String name, String actions) { + super(name); + checkName(name); + if (actions != null && actions.length() > 0) { + throw new IllegalArgumentException("actions: " + actions); + } + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/NoSuchFileException.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,64 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file; + +/** + * Checked exception thrown when an attempt is made to access a file that does + * not exist. + * + * @since 1.7 + */ + +public class NoSuchFileException + extends FileSystemException +{ + static final long serialVersionUID = -1390291775875351931L; + + /** + * Constructs an instance of this class. + * + * @param file + * A string identifying the file or {@code null} if not known. + */ + public NoSuchFileException(String file) { + super(file); + } + + /** + * Constructs an instance of this class. + * + * @param file + * A string identifying the file or {@code null} if not known. + * @param other + * A string identifying the other file or {@code null} if not known. + * @param reason + * A reason message with additional information or {@code null} + */ + public NoSuchFileException(String file, String other, String reason) { + super(file, other, reason); + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/NotDirectoryException.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,50 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file; + +/** + * Checked exception thrown when a file system operation, intended for a + * directory, fails because the file is not a directory. + * + * @since 1.7 + */ + +public class NotDirectoryException + extends FileSystemException +{ + private static final long serialVersionUID = -9011457427178200199L; + + /** + * Constructs an instance of this class. + * + * @param file + * A string identifying the file or {@code null} if not known. + */ + public NotDirectoryException(String file) { + super(file); + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/NotLinkException.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,64 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file; + +/** + * Checked exception thrown when a file system operation fails because a file + * is not a link. + * + * @since 1.7 + */ + +public class NotLinkException + extends FileSystemException +{ + static final long serialVersionUID = -388655596416518021L; + + /** + * Constructs an instance of this class. + * + * @param file + * A string identifying the file or {@code null} if not known. + */ + public NotLinkException(String file) { + super(file); + } + + /** + * Constructs an instance of this class. + * + * @param file + * A string identifying the file or {@code null} if not known. + * @param other + * A string identifying the other file or {@code null} if not known. + * @param reason + * A reason message with additional information or {@code null} + */ + public NotLinkException(String file, String other, String reason) { + super(file, other, reason); + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/OpenOption.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,46 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file; + +/** + * An object that configures how to open or create a file. + * + * <p> Objects of this type are used by methods such as {@link + * Path#newOutputStream(OpenOption[]) newOutputStream}, {@link + * FileRef#newByteChannel newByteChannel}, {@link + * java.nio.channels.FileChannel#open FileChannel.open}, and {@link + * java.nio.channels.AsynchronousFileChannel#open AsynchronousFileChannel.open} + * when opening or creating a file. + * + * <p> The {@link StandardOpenOption} enumeration type defines the + * <i>standard</i> options. + * + * @since 1.7 + */ + +public interface OpenOption { +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/Path.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,1575 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file; + +import java.nio.channels.*; +import java.io.*; +import java.net.URI; +import java.util.*; + +import org.classpath.icedtea.java.nio.channels.SeekableByteChannel; + +import org.classpath.icedtea.java.nio.file.attribute.FileAttribute; + +/** + * A file reference that locates a file using a system dependent path. The file + * is not required to exist. + * + * <p> On many platforms a <em>path</em> is the means to locate and access files + * in a file system. A path is hierarchical and composed of a sequence of + * directory names separated by a special separator or delimiter. + * + * <h4>Path operations</h4> + * + * <p> A system dependent path represented by this class is conceptually a + * sequence of name elements and optionally a <em>root component</em>. The name + * that is <em>farthest</em> from the root of the directory hierarchy is the + * name of a file or directory. The other elements are directory names. The root + * component typically identifies a file system hierarchy. A {@code Path} can + * represent a root, a root and a sequence of names, or simply one or more name + * elements. It defines the {@link #getName() getName}, {@link #getParent + * getParent}, {@link #getRoot getRoot}, and {@link #subpath subpath} methods + * to access the components or a subsequence of its name elements. + * + * <p> In addition to accessing the components of a path, a {@code Path} also + * defines {@link #resolve(Path) resolve} and {@link #relativize relativize} + * operations. Paths can also be {@link #compareTo compared}, and tested + * against each using using the {@link #startsWith startsWith} and {@link + * #endsWith endWith} methods. + * + * <h4>File operations</h4> + * + * <p> A {@code Path} is either <em>absolute</em> or <em>relative</em>. An + * absolute path is complete in that does not need to be combined with another + * path in order to locate a file. All operations on relative paths are first + * resolved against a file system's default directory as if by invoking the + * {@link #toAbsolutePath toAbsolutePath} method. + * + * <p> In addition to the operations defined by the {@link FileRef} interface, + * this class defines the following operations: + * + * <ul> + * <li><p> Files may be {@link #createFile(FileAttribute[]) created}, or + * directories may be {@link #createDirectory(FileAttribute[]) created}. + * </p></li> + * <li><p> Directories can be {@link #newDirectoryStream opened} so as to + * iterate over the entries in the directory. </p></li> + * <li><p> Files can be {@link #copyTo(Path,CopyOption[]) copied} or + * {@link #moveTo(Path,CopyOption[]) moved}. </p></li> + * <li><p> Symbolic-links may be {@link #createSymbolicLink created}, or the + * target of a link may be {@link #readSymbolicLink read}. </p></li> + * <li><p> {@link #newInputStream InputStream} or {@link #newOutputStream + * OutputStream} streams can be created to allow for interoperation with the + * <a href="../../../java/io/package-summary.html">{@code java.io}</a> package + * where required. </li></p> + * <li><p> The {@link #toRealPath real} path of an existing file may be + * obtained. </li></p> + * </ul> + * + * <p> This class implements {@link Watchable} interface so that a directory + * located by a path can be {@link #register registered} with a {@link WatchService}. + * and entries in the directory watched. + * + * <h4>File attributes</h4> + * + * The <a href="attribute/package-summary.html">{@code java.nio.file.attribute}</a> + * package provides access to file attributes or <em>meta-data</em> associated + * with files. The {@link Attributes Attributes} class defines methods that + * operate on or return file attributes. For example, the file type, size, + * timestamps, and other <em>basic</em> meta-data is obtained, in bulk, by + * invoking the {@link Attributes#readBasicFileAttributes + * Attributes.readBasicFileAttributes} method: + * <pre> + * Path file = ... + * BasicFileAttributes attrs = Attributes.readBasicFileAttributes(file); + * </pre> + * + * <a name="interop"><h4>Interoperability</h4></a> + * + * <p> Paths created by file systems associated with the default {@link + * java.nio.file.spi.FileSystemProvider provider} are generally interoperable + * with the {@link java.io.File java.io.File} class. Paths created by other + * providers are unlikely to be interoperable with the abstract path names + * represented by {@code java.io.File}. The {@link java.io.File#toPath + * File.toPath} method may be used to obtain a {@code Path} from the abstract + * path name represented by a {@code java.io.File java.io.File} object. The + * resulting {@code Path} can be used to operate on the same file as the {@code + * java.io.File} object. + * + * <p> Path objects created by file system's associated with the default + * provider are interoperable with objects created by other file systems created + * by the same provider. Path objects created by file systems associated with + * other providers may not be interoperable with other file systems created by + * the same provider. The reasons for this are provider specific. + * + * <h4>Concurrency</h4></a> + * + * <p> Instances of this class are immutable and safe for use by multiple concurrent + * threads. + * + * @since 1.7 + */ + +public abstract class Path + implements FileRef, Comparable<Path>, Iterable<Path>, Watchable +{ + /** + * Initializes a new instance of this class. + */ + protected Path() { } + + /** + * Returns the file system that created this object. + * + * @return The file system that created this object + */ + public abstract FileSystem getFileSystem(); + + /** + * Tells whether or not this path is absolute. + * + * <p> An absolute path is complete in that it doesn't need to be + * combined with other path information in order to locate a file. + * + * @return {@code true} if, and only if, this path is absolute + */ + public abstract boolean isAbsolute(); + + /** + * Returns the root component of this path as a {@code Path} object, + * or {@code null} if this path does not have a root component. + * + * @return A path representing the root component of this path, + * or {@code null} + */ + public abstract Path getRoot(); + + /** + * Returns the name of the file or directory denoted by this path. The + * file name is the <em>farthest</em> element from the root in the directory + * hierarchy. + * + * @return A path representing the name of the file or directory, or + * {@code null} if this path has zero elements + */ + public abstract Path getName(); + + /** + * Returns the <em>parent path</em>, or {@code null} if this path does not + * have a parent. + * + * <p> The parent of this path object consists of this path's root + * component, if any, and each element in the path except for the + * <em>farthest</em> from the root in the directory hierarchy. This method + * does not access the file system; the path or its parent may not exist. + * Furthermore, this method does not eliminate special names such as "." + * and ".." that may be used in some implementations. On UNIX for example, + * the parent of "{@code /a/b/c}" is "{@code /a/b}", and the parent of + * {@code "x/y/.}" is "{@code x/y}". This method may be used with the {@link + * #normalize normalize} method, to eliminate redundant names, for cases where + * <em>shell-like</em> navigation is required. + * + * <p> If this path has one or more elements, and no root component, then + * this method is equivalent to evaluating the expression: + * <blockquote><pre> + * subpath(0, getNameCount()-1); + * </pre></blockquote> + * + * @return A path representing the path's parent + */ + public abstract Path getParent(); + + /** + * Returns the number of name elements in the path. + * + * @return The number of elements in the path, or {@code 0} if this path + * only represents a root component + */ + public abstract int getNameCount(); + + /** + * Returns a name element of this path. + * + * <p> The {@code index} parameter is the index of the name element to return. + * The element that is <em>closest</em> to the root in the directory hierarchy + * has index {@code 0}. The element that is <em>farthest</em> from the root + * has index {@link #getNameCount count}{@code -1}. + * + * @param index + * The index of the element + * + * @return The name element + * + * @throws IllegalArgumentException + * If {@code index} is negative, {@code index} is greater than or + * equal to the number of elements, or this path has zero name + * elements. + */ + public abstract Path getName(int index); + + /** + * Returns a relative {@code Path} that is a subsequence of the name + * elements of this path. + * + * <p> The {@code beginIndex} and {@code endIndex} parameters specify the + * subsequence of name elements. The name that is <em>closest</em> to the root + * in the directory hierarchy has index {@code 0}. The name that is + * <em>farthest</em> from the root has index {@link #getNameCount + * count}{@code -1}. The returned {@code Path} object has the name elements + * that begin at {@code beginIndex} and extend to the element at index {@code + * endIndex-1}. + * + * @param beginIndex + * The index of the first element, inclusive + * @param endIndex + * The index of the last element, exclusive + * + * @return A new {@code Path} object that is a subsequence of the name + * elements in this {@code Path} + * + * @throws IllegalArgumentException + * If {@code beginIndex} is negative, or greater than or equal to + * the number of elements. If {@code endIndex} is less than or + * equal to {@code beginIndex}, or larger than the number of elements. + */ + public abstract Path subpath(int beginIndex, int endIndex); + + /** + * Tests if this path starts with the given path. + * + * <p> This path <em>starts</em> with the given path if this path's root + * component <em>starts</em> with the root component of the given path, + * and this path starts with the same name elements as the given path. + * If the given path has more name elements than this path then {@code false} + * is returned. + * + * <p> Whether or not the root component of this path starts with the root + * component of the given path is file system specific. If this path does + * not have a root component and the given path has a root component then + * this path does not start with the given path. + * + * @param other + * The given path + * + * @return {@code true} if this path starts with the given path; otherwise + * {@code false} + */ + public abstract boolean startsWith(Path other); + + /** + * Tests if this path ends with the given path. + * + * <p> If the given path has <em>N</em> elements, and no root component, + * and this path has <em>N</em> or more elements, then this path ends with + * the given path if the last <em>N</em> elements of each path, starting at + * the element farthest from the root, are equal. + * + * <p> If the given path has a root component then this path ends with the + * given path if the root component of this path <em>ends with</em> the root + * component of the given path, and the corresponding elements of both paths + * are equal. Whether or not the root component of this path ends with the + * root component of the given path is file system specific. If this path + * does not have a root component and the given path has a root component + * then this path does not end with the given path. + * + * @param other + * The given path + * + * @return {@code true} if this path ends with the given path; otherwise + * {@code false} + */ + public abstract boolean endsWith(Path other); + + /** + * Returns a path that is this path with redundant name elements eliminated. + * + * <p> The precise definition of this method is implementation dependent but + * in general it derives from this path, a path that does not contain + * <em>redundant</em> name elements. In many file systems, the "{@code .}" + * and "{@code ..}" are special names used to indicate the current directory + * and parent directory. In such file systems all occurrences of "{@code .}" + * are considered redundant. If a "{@code ..}" is preceded by a + * non-"{@code ..}" name then both names are considered redundant (the + * process to identify such names is repeated until is it no longer + * applicable). + * + * <p> This method does not access the file system; the path may not locate + * a file that exists. Eliminating "{@code ..}" and a preceding name from a + * path may result in the path that locates a different file than the original + * path. This can arise when the preceding name is a symbolic link. + * + * @return The resulting path, or this path if it does not contain + * redundant name elements, or {@code null} if this path does not + * have a root component and all name elements are redundant. + * + * @see #getParent + * @see #toRealPath + */ + public abstract Path normalize(); + + // -- resolution and relativization -- + + /** + * Resolve the given path against this path. + * + * <p> If the {@code other} parameter is an {@link #isAbsolute() absolute} + * path then this method trivially returns {@code other}. If {@code other} + * is {@code null} then this path is returned. Otherwise this method + * considers this path to be a directory and resolves the given path + * against this path. In the simplest case, the given path does not have + * a {@link #getRoot root} component, in which case this method <em>joins</em> + * the given path to this path and returns a resulting path that {@link + * #endsWith ends} with the given path. Where the given path has a root + * component then resolution is highly implementation dependent and therefore + * unspecified. + * + * @param other + * The path to resolve against this path; can be {@code null} + * + * @return The resulting path + * + * @see #relativize + */ + public abstract Path resolve(Path other); + + /** + * Converts a given path string to a {@code Path} and resolves it against + * this {@code Path} in exactly the manner specified by the {@link + * #resolve(Path) resolve} method. + * + * @param other + * The path string to resolve against this path + * + * @return The resulting path + * + * @throws InvalidPathException + * If the path string cannot be converted to a Path. + * + * @see FileSystem#getPath + */ + public abstract Path resolve(String other); + + /** + * Constructs a relative path between this path and a given path. + * + * <p> Relativization is the inverse of {@link #resolve(Path) resolution}. + * This method attempts to construct a {@link #isAbsolute relative} path + * that when {@link #resolve(Path) resolved} against this path, yields a + * path that locates the same file as the given path. For example, on UNIX, + * if this path is {@code "/a/b"} and the given path is {@code "/a/b/c/d"} + * then the resulting relative path would be {@code "c/d"}. Where this + * path and the given path do not have a {@link #getRoot root} component, + * then a relative path can be constructed. A relative path cannot be + * constructed if only one of the paths have a root component. Where both + * paths have a root component then it is implementation dependent if a + * relative path can be constructed. If this path and the given path are + * {@link #equals equal} then {@code null} is returned. + * + * <p> For any two paths <i>p</i> and <i>q</i>, where <i>q</i> does not have + * a root component, + * <blockquote> + * <i>p</i><tt>.relativize(</tt><i>p</i><tt>.resolve(</tt><i>q</i><tt>)).equals(</tt><i>q</i><tt>)</tt> + * </blockquote> + * + * <p> When symbolic-links are supported, then whether the resulting path, + * when resolved against this path, yields a path that can be used to locate + * the {@link #isSameFile same} file as {@code other} is implementation + * dependent. For example, if this path is {@code "/a/b"} and the given + * path is {@code "/a/x"} then the resulting relative path may be {@code + * "../x"}. If {@code "b"} is a symbolic-link then is implementation + * dependent if {@code "a/b/../x"} would locate the same file as {@code "/a/x"}. + * + * @param other + * The resulting path + * + * @return The resulting relative path, or {@code null} if both paths are + * equal + * + * @throws IllegalArgumentException + * If {@code other} is not a {@code Path} that can be relativized + * against this path + */ + public abstract Path relativize(Path other); + + // -- file operations -- + + /** + * Deletes the file located by this path. + * + * <p> The {@code failIfNotExists} parameter determines how the method + * behaves when the file does not exist. When {@code true}, and the file + * does not exist, then the method fails. When {@code false} then the method + * does not fail. + * + * <p> As with the {@link FileRef#delete delete()} method, an implementation + * may require to examine the file to determine if the file is a directory. + * Consequently this method may not be atomic with respect to other file + * system operations. If the file is a symbolic-link then the link is + * deleted and not the final target of the link. + * + * <p> If the file is a directory then the directory must be empty. In some + * implementations a directory has entries for special files or links that + * are created when the directory is created. In such implementations a + * directory is considered empty when only the special entries exist. + * + * <p> On some operating systems it may not be possible to remove a file when + * it is open and in use by this Java virtual machine or other programs. + * + * @param failIfNotExists + * {@code true} if the method should fail when the file does not + * exist + * + * @throws NoSuchFileException + * If the value of the {@code failIfNotExists} is {@code true} and + * the file does not exist <i>(optional specific exception)</i> + * @throws DirectoryNotEmptyException + * If the file is a directory and could not otherwise be deleted + * because the directory is not empty <i>(optional specific + * exception)</i> + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * In the case of the default provider, and a security manager is + * installed, the {@link SecurityManager#checkDelete(String)} method + * is invoked to check delete access to the file + */ + public abstract void delete(boolean failIfNotExists) throws IOException; + + /** + * Creates a symbolic link to a target <i>(optional operation)</i>. + * + * <p> The {@code target} parameter is the target of the link. It may be an + * {@link Path#isAbsolute absolute} or relative path and may not exist. When + * the target is a relative path then file system operations on the resulting + * link are relative to the path of the link. + * + * <p> The {@code attrs} parameter is an optional array of {@link FileAttribute + * attributes} to set atomically when creating the link. Each attribute is + * identified by its {@link FileAttribute#name name}. If more than one attribute + * of the same name is included in the array then all but the last occurrence + * is ignored. + * + * <p> Where symbolic links are supported, but the underlying {@link FileStore} + * does not support symbolic links, then this may fail with an {@link + * IOException}. Additionally, some operating systems may require that the + * Java virtual machine be started with implementation specific privileges to + * create symbolic links, in which case this method may throw {@code IOException}. + * + * @param target + * The target of the link + * @param attrs + * The array of attributes to set atomically when creating the + * symbolic link + * + * @return this path + * + * @throws UnsupportedOperationException + * If the implementation does not support symbolic links or the + * array contains an attribute that cannot be set atomically when + * creating the symbolic link + * @throws FileAlreadyExistsException + * If a file with the name already exists <i>(optional specific + * exception)</i> + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * In the case of the the default provider, and a security manager + * is installed, it denies {@link LinkPermission}<tt>("symbolic")</tt> + * or its {@link SecurityManager#checkWrite(String) checkWrite} + * method denies write access to the path of the symbolic link. + */ + public abstract Path createSymbolicLink(Path target, FileAttribute<?>... attrs) + throws IOException; + + /** + * Creates a new link (directory entry) for an existing file <i>(optional + * operation)</i>. + * + * <p> This path locates the directory entry to create. The {@code existing} + * parameter is the path to an existing file. This method creates a new + * directory entry for the file so that it can be accessed using this path. + * On some file systems this is known as creating a "hard link". Whether the + * file attributes are maintained for the file or for each directory entry + * is file system specific and therefore not specified. Typically, a file + * system requires that all links (directory entries) for a file be on the + * same file system. Furthermore, on some platforms, the Java virtual machine + * may require to be started with implementation specific privileges to + * create hard links or to create links to directories. + * + * @param existing + * A reference to an existing file + * + * @return this path + * + * @throws UnsupportedOperationException + * If the implementation does not support adding an existing file + * to a directory + * @throws FileAlreadyExistsException + * If the entry could not otherwise be created because a file of + * that name already exists <i>(optional specific exception)</i> + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * In the case of the the default provider, and a security manager + * is installed, it denies {@link LinkPermission}<tt>("hard")</tt> + * or its {@link SecurityManager#checkWrite(String) checkWrite} + * method denies write access to both this path and the path of the + * existing file + * + * @see BasicFileAttributes#linkCount + */ + public abstract Path createLink(Path existing) throws IOException; + + /** + * Reads the target of a symbolic link <i>(optional operation)</i>. + * + * <p> If the file system supports <a href="package-summary.html#links">symbolic + * links</a> then this method is used read the target of the link, failing + * if the file is not a link. The target of the link need not exist. The + * returned {@code Path} object will be associated with the same file + * system as this {@code Path}. + * + * @return A {@code Path} object representing the target of the link + * + * @throws UnsupportedOperationException + * If the implementation does not support symbolic links + * @throws NotLinkException + * If the target could otherwise not be read because the file + * is not a link <i>(optional specific exception)</i> + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * In the case of the the default provider, and a security manager + * is installed, it checks that {@code FilePermission} has been + * granted with the "{@code readlink}" action to read the link. + */ + public abstract Path readSymbolicLink() throws IOException; + + /** + * Returns a URI to represent this path. + * + * <p> This method constructs a hierarchical {@link URI} that is absolute + * with a non-empty path component. Its {@link URI#getScheme() scheme} is + * equal to the URI scheme that identifies the provider. The exact form of + * the other URI components is highly provider dependent. In particular, it + * is implementation dependent if its query, fragment, and authority + * components are defined or undefined. + * + * <p> For the default provider the {@link URI#getPath() path} component + * will represent the {@link #toAbsolutePath absolute} path; the query, + * fragment components are undefined. Whether the authority component is + * defined or not is implementation dependent. There is no guarantee that + * the {@code URI} may be used to construct a {@link java.io.File java.io.File}. + * In particular, if this path represents a Universal Naming Convention (UNC) + * path, then the UNC server name may be encoded in the authority component + * of the resulting URI. In the case of the default provider, and the file + * exists, and it can be determined that the file is a directory, then the + * resulting {@code URI} will end with a slash. + * + * <p> The default provider provides a similar <em>round-trip</em> guarantee + * to the {@link java.io.File} class. For a given {@code Path} <i>p</i> it + * is guaranteed that + * <blockquote><tt> + * {@link Paths#get(URI) Paths.get}(</tt><i>p</i><tt>.toUri()).equals(</tt><i>p</i> + * <tt>.{@link #toAbsolutePath() toAbsolutePath}())</tt> + * </blockquote> + * so long as the original {@code Path}, the {@code URI}, and the new {@code + * Path} are all created in (possibly different invocations of) the same + * Java virtual machine. Whether other providers make any guarantees is + * provider specific and therefore unspecified. + * + * <p> When a file system is constructed to access the contents of a file + * as a file system then it is highly implementation specific if the returned + * URI represents the given path in the file system or it represents a + * <em>compound</em> URI that encodes the URI of the enclosing file system. + * A format for compound URIs is not defined in this release; such a scheme + * may be added in a future release. + * + * @return An absolute, hierarchical URI with a non-empty path component + * + * @throws IOError + * If an I/O error occurs obtaining the absolute path, or where a + * file system is constructed to access the contents of a file as + * a file system, the URI of the enclosing file system cannot be + * obtained. + * + * @throws SecurityException + * In the case of the the default provider, and a security manager + * is installed, the {@link #toAbsolutePath toAbsolutePath} method + * throws a security exception. + */ + public abstract URI toUri(); + + /** + * Returns a {@code Path} object representing the absolute path of this + * path. + * + * <p> If this path is already {@link Path#isAbsolute absolute} then this + * method simply returns this path. Otherwise, this method resolves the path + * in an implementation dependent manner, typically by resolving the path + * against a file system default directory. Depending on the implementation, + * this method may throw an I/O error if the file system is not accessible. + * + * @return A {@code Path} object representing the absolute path + * + * @throws IOError + * If an I/O error occurs + * @throws SecurityException + * In the case of the the default provider, and a security manager + * is installed, its {@link SecurityManager#checkPropertyAccess(String) + * checkPropertyAccess} method is invoked to check access to the + * system property {@code user.dir} + */ + public abstract Path toAbsolutePath(); + + /** + * Returns the <em>real</em> path of an existing file. + * + * <p> The precise definition of this method is implementation dependent but + * in general it derives from this path, an {@link #isAbsolute absolute} + * path that locates the {@link #isSameFile same} file as this path, but + * with name elements that represent the actual name of the directories + * and the file. For example, where filename comparisons on a file system + * are case insensitive then the name elements represent the names in their + * actual case. Additionally, the resulting path has redundant name + * elements removed. + * + * <p> If this path is relative then its absolute path is first obtained, + * as if by invoking the {@link #toAbsolutePath toAbsolutePath} method. + * + * <p> The {@code resolveLinks} parameter specifies if symbolic links + * should be resolved. This parameter is ignored when symbolic links are + * not supported. Where supported, and the parameter has the value {@code + * true} then symbolic links are resolved to their final target. Where the + * parameter has the value {@code false} then this method does not resolve + * symbolic links. Some implementations allow special names such as + * "{@code ..}" to refer to the parent directory. When deriving the <em>real + * path</em>, and a "{@code ..}" (or equivalent) is preceded by a + * non-"{@code ..}" name then an implementation will typically causes both + * names to be removed. When not resolving symbolic links and the preceding + * name is a symbolic link then the names are only removed if it guaranteed + * that the resulting path will locate the same file as this path. + * + * @return An absolute path represent the <em>real</em> path of the file + * located by this object + * + * @throws IOException + * If the file does not exist or an I/O error occurs + * @throws SecurityException + * In the case of the the default provider, and a security manager + * is installed, its {@link SecurityManager#checkRead(String) checkRead} + * method is invoked to check read access to the file, and where + * this path is not absolute, its {@link SecurityManager#checkPropertyAccess(String) + * checkPropertyAccess} method is invoked to check access to the + * system property {@code user.dir} + */ + public abstract Path toRealPath(boolean resolveLinks) throws IOException; + + /** + * Copy the file located by this path to a target location. + * + * <p> This method copies the file located by this {@code Path} to the + * target location with the {@code options} parameter specifying how the + * copy is performed. By default, the copy fails if the target file already + * exists, except if the source and target are the {@link #isSameFile same} + * file, in which case this method has no effect. File attributes are not + * required to be copied to the target file. If symbolic links are supported, + * and the file is a link, then the final target of the link is copied. If + * the file is a directory then it creates an empty directory in the target + * location (entries in the directory are not copied). This method can be + * used with the {@link Files#walkFileTree Files.walkFileTree} utility + * method to copy a directory and all entries in the directory, or an entire + * <i>file-tree</i> where required. + * + * <p> The {@code options} parameter is an array of options and may contain + * any of the following: + * + * <table border=1 cellpadding=5 summary=""> + * <tr> <th>Option</th> <th>Description</th> </tr> + * <tr> + * <td> {@link StandardCopyOption#REPLACE_EXISTING REPLACE_EXISTING} </td> + * <td> If the target file exists, then the target file is replaced if it + * is not a non-empty directory. If the target file exists and is a + * symbolic-link then the symbolic-link is replaced (not the target of + * the link. </td> + * </tr> + * <tr> + * <td> {@link StandardCopyOption#COPY_ATTRIBUTES COPY_ATTRIBUTES} </td> + * <td> Attempts to copy the file attributes associated with this file to + * the target file. The exact file attributes that are copied is platform + * and file system dependent and therefore unspecified. Minimally, the + * {@link BasicFileAttributes#lastModifiedTime last-modified-time} is + * copied to the target file. </td> + * </tr> + * <tr> + * <td> {@link LinkOption#NOFOLLOW_LINKS NOFOLLOW_LINKS} </td> + * <td> Symbolic-links are not followed. If the file, located by this path, + * is a symbolic-link then the link is copied rather than the target of + * the link. It is implementation specific if file attributes can be + * copied to the new link. In other words, the {@code COPY_ATTRIBUTES} + * option may be ignored when copying a link. </td> + * </tr> + * </table> + * + * <p> An implementation of this interface may support additional + * implementation specific options. + * + * <p> Copying a file is not an atomic operation. If an {@link IOException} + * is thrown then it possible that the target file is incomplete or some of + * its file attributes have not been copied from the source file. When the + * {@code REPLACE_EXISTING} option is specified and the target file exists, + * then the target file is replaced. The check for the existence of the file + * and the creation of the new file may not be atomic with respect to other + * file system activities. + * + * @param target + * The target location + * @param options + * Options specifying how the copy should be done + * + * @return The target + * + * @throws UnsupportedOperationException + * If the array contains a copy option that is not supported + * @throws FileAlreadyExistsException + * The target file exists and cannot be replaced because the + * {@code REPLACE_EXISTING} option is not specified, or the target + * file is a non-empty directory <i>(optional specific exception)</i> + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * In the case of the default provider, and a security manager is + * installed, the {@link SecurityManager#checkRead(String) checkRead} + * method is invoked to check read access to the source file, the + * {@link SecurityManager#checkWrite(String) checkWrite} is invoked + * to check write access to the target file. If a symbolic link is + * copied the security manager is invoked to check {@link + * LinkPermission}{@code ("symbolic")}. + */ + public abstract Path copyTo(Path target, CopyOption... options) + throws IOException; + + /** + * Move or rename the file located by this path to a target location. + * + * <p> By default, this method attempts to move the file to the target + * location, failing if the target file exists except if the source and + * target are the {@link #isSameFile same} file, in which case this method + * has no effect. If the file is a symbolic link then the link is moved and + * not the target of the link. This method may be invoked to move an empty + * directory. In some implementations a directory has entries for special + * files or links that are created when the directory is created. In such + * implementations a directory is considered empty when only the special + * entries exist. When invoked to move a directory that is not empty then the + * directory is moved if it does not require moving the entries in the directory. + * For example, renaming a directory on the same {@link FileStore} will usually + * not require moving the entries in the directory. When moving a directory + * requires that its entries be moved then this method fails (by throwing + * an {@code IOException}). To move a <i>file tree</i> may involve copying + * rather than moving directories and this can be done using the {@link + * #copyTo copyTo} method in conjunction with the {@link + * Files#walkFileTree Files.walkFileTree} utility method. + * + * <p> The {@code options} parameter is an array of options and may contain + * any of the following: + * + * <table border=1 cellpadding=5 summary=""> + * <tr> <th>Option</th> <th>Description</th> </tr> + * <tr> + * <td> {@link StandardCopyOption#REPLACE_EXISTING REPLACE_EXISTING} </td> + * <td> If the target file exists, then the target file is replaced if it + * is not a non-empty directory. If the target file exists and is a + * symbolic-link then the symbolic-link is replaced and not the target of + * the link. </td> + * </tr> + * <tr> + * <td> {@link StandardCopyOption#ATOMIC_MOVE ATOMIC_MOVE} </td> + * <td> The move is performed as an atomic file system operation and all + * other options are ignored. If the target file exists then it is + * implementation specific if the existing file is replaced or this method + * fails by throwing an {@link IOException}. If the move cannot be + * performed as an atomic file system operation then {@link + * AtomicMoveNotSupportedException} is thrown. This can arise, for + * example, when the target location is on a different {@code FileStore} + * and would require that the file be copied, or target location is + * associated with a different provider to this object. </td> + * </table> + * + * <p> An implementation of this interface may support additional + * implementation specific options. + * + * <p> Where the move requires that the file be copied then the {@link + * BasicFileAttributes#lastModifiedTime last-modified-time} is copied to the + * new file. An implementation may also attempt to copy other file + * attributes but is not required to fail if the file attributes cannot be + * copied. When the move is performed as a non-atomic operation, and a {@code + * IOException} is thrown, then the state of the files is not defined. The + * original file and the target file may both exist, the target file may be + * incomplete or some of its file attributes may not been copied from the + * original file. + * + * @param target + * The target location + * @param options + * Options specifying how the move should be done + * + * @return The target + * + * @throws UnsupportedOperationException + * If the array contains a copy option that is not supported + * @throws FileAlreadyExistsException + * The target file exists and cannot be replaced because the + * {@code REPLACE_EXISTING} option is not specified, or the target + * file is a non-empty directory + * @throws AtomicMoveNotSupportedException + * The options array contains the {@code ATOMIC_MOVE} option but + * the file cannot be moved as an atomic file system operation. + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * In the case of the default provider, and a security manager is + * installed, the {@link SecurityManager#checkWrite(String) checkWrite} + * method is invoked to check write access to both the source and + * target file. + */ + public abstract Path moveTo(Path target, CopyOption... options) + throws IOException; + + /** + * Opens the directory referenced by this object, returning a {@code + * DirectoryStream} to iterate over all entries in the directory. The + * elements returned by the directory stream's {@link DirectoryStream#iterator + * iterator} are of type {@code Path}, each one representing an entry in the + * directory. The {@code Path} objects are obtained as if by {@link + * #resolve(Path) resolving} the name of the directory entry against this + * path. + * + * <p> The directory stream's {@code close} method should be invoked after + * iteration is completed so as to free any resources held for the open + * directory. The {@link Files#withDirectory Files.withDirectory} utility + * method is useful for cases where a task is performed on each accepted + * entry in a directory. This method closes the directory when iteration is + * complete (or an error occurs). + * + * <p> When an implementation supports operations on entries in the + * directory that execute in a race-free manner then the returned directory + * stream is a {@link SecureDirectoryStream}. + * + * @return A new and open {@code DirectoryStream} object + * + * @throws NotDirectoryException + * If the file could not otherwise be opened because it is not + * a directory <i>(optional specific exception)</i> + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * In the case of the default provider, and a security manager is + * installed, the {@link SecurityManager#checkRead(String) checkRead} + * method is invoked to check read access to the directory. + */ + public abstract DirectoryStream<Path> newDirectoryStream() + throws IOException; + + /** + * Opens the directory referenced by this object, returning a {@code + * DirectoryStream} to iterate over the entries in the directory. The + * elements returned by the directory stream's {@link DirectoryStream#iterator + * iterator} are of type {@code Path}, each one representing an entry in the + * directory. The {@code Path} objects are obtained as if by {@link + * #resolve(Path) resolving} the name of the directory entry against this + * path. The entries returned by the iterator are filtered by matching the + * {@code String} representation of their file names against the given + * <em>globbing</em> pattern. + * + * <p> For example, suppose we want to iterate over the files ending with + * ".java" in a directory: + * <pre> + * Path dir = ... + * DirectoryStream<Path> stream = dir.newDirectoryStream("*.java"); + * </pre> + * + * <p> The globbing pattern is specified by the {@link + * FileSystem#getNameMatcher getNameMatcher} method. + * + * <p> The directory stream's {@code close} method should be invoked after + * iteration is completed so as to free any resources held for the open + * directory. + * + * <p> When an implementation supports operations on entries in the + * directory that execute in a race-free manner then the returned directory + * stream is a {@link SecureDirectoryStream}. + * + * @param glob + * The glob pattern + * + * @return A new and open {@code DirectoryStream} object + * + * @throws java.util.regex.PatternSyntaxException + * If the pattern is invalid + * @throws UnsupportedOperationException + * If the pattern syntax is not known to the implementation + * @throws NotDirectoryException + * If the file could not otherwise be opened because it is not + * a directory <i>(optional specific exception)</i> + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * In the case of the default provider, and a security manager is + * installed, the {@link SecurityManager#checkRead(String) checkRead} + * method is invoked to check read access to the directory. + */ + public abstract DirectoryStream<Path> newDirectoryStream(String glob) + throws IOException; + + /** + * Opens the directory referenced by this object, returning a {@code + * DirectoryStream} to iterate over the entries in the directory. The + * elements returned by the directory stream's {@link DirectoryStream#iterator + * iterator} are of type {@code Path}, each one representing an entry in the + * directory. The {@code Path} objects are obtained as if by {@link + * #resolve(Path) resolving} the name of the directory entry against this + * path. The entries returned by the iterator are filtered by the given + * {@link DirectoryStream.Filter filter}. The {@link DirectoryStreamFilters} + * class defines factory methods that create useful filters. + * + * <p> The directory stream's {@code close} method should be invoked after + * iteration is completed so as to free any resources held for the open + * directory. The {@link Files#withDirectory Files.withDirectory} utility + * method is useful for cases where a task is performed on each accepted + * entry in a directory. This method closes the directory when iteration is + * complete (or an error occurs). + * + * <p> When an implementation supports operations on entries in the + * directory that execute in a race-free manner then the returned directory + * stream is a {@link SecureDirectoryStream}. + * + * <p> <b>Usage Example:</b> + * Suppose we want to iterate over the files in a directory that are + * larger than 8K. + * <pre> + * DirectoryStream.Filter<Path> filter = new DirectoryStream.Filter<Path>() { + * public boolean accept(Path file) { + * try { + * long size = Attributes.readBasicFileAttributes(file).size(); + * return (size > 8192L); + * } catch (IOException e) { + * // failed to get size + * return false; + * } + * } + * }; + * Path dir = ... + * DirectoryStream<Path> stream = dir.newDirectoryStream(filter); + * </pre> + * @param filter + * The directory stream filter + * + * @return A new and open {@code DirectoryStream} object + * + * @throws NotDirectoryException + * If the file could not otherwise be opened because it is not + * a directory <i>(optional specific exception)</i> + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * In the case of the default provider, and a security manager is + * installed, the {@link SecurityManager#checkRead(String) checkRead} + * method is invoked to check read access to the directory. + */ + public abstract DirectoryStream<Path> newDirectoryStream(DirectoryStream.Filter<? super Path> filter) + throws IOException; + + /** + * Creates a new and empty file, failing if the file already exists. + * + * <p> This {@code Path} locates the file to create. The check for the + * existence of the file and the creation of the new file if it does not + * exist are a single operation that is atomic with respect to all other + * filesystem activities that might affect the directory. + * + * <p> The {@code attrs} parameter is an optional array of {@link FileAttribute + * file-attributes} to set atomically when creating the file. Each attribute + * is identified by its {@link FileAttribute#name name}. If more than one + * attribute of the same name is included in the array then all but the last + * occurrence is ignored. + * + * @param attrs + * An optional list of file attributes to set atomically when + * creating the file + * + * @return This path + * + * @throws UnsupportedOperationException + * If the array contains an attribute that cannot be set atomically + * when creating the file + * @throws FileAlreadyExistsException + * If a file of that name already exists + * <i>(optional specific exception)</i> + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * In the case of the default provider, and a security manager is + * installed, the {@link SecurityManager#checkWrite(String) checkWrite} + * method is invoked to check write access to the new file. + */ + public abstract Path createFile(FileAttribute<?>... attrs) throws IOException; + + /** + * Creates a new directory. + * + * <p> This {@code Path} locates the directory to create. The check for the + * existence of the file and the creation of the directory if it does not + * exist are a single operation that is atomic with respect to all other + * filesystem activities that might affect the directory. + * + * <p> The {@code attrs} parameter is an optional array of {@link FileAttribute + * file-attributes} to set atomically when creating the directory. Each + * file attribute is identified by its {@link FileAttribute#name name}. If + * more than one attribute of the same name is included in the array then all + * but the last occurrence is ignored. + * + * @param attrs + * An optional list of file attributes to set atomically when + * creating the directory + * + * @return This path + * + * @throws UnsupportedOperationException + * If the array contains an attribute that cannot be set atomically + * when creating the directory + * @throws FileAlreadyExistsException + * If a directory could not otherwise be created because a file of + * that name already exists <i>(optional specific exception)</i> + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * In the case of the default provider, and a security manager is + * installed, the {@link SecurityManager#checkWrite(String) checkWrite} + * method is invoked to check write access to the new directory. + */ + public abstract Path createDirectory(FileAttribute<?>... attrs) + throws IOException; + + /** + * Opens or creates a file, returning a seekable byte channel to access the + * file. + * + * <p> The {@code options} parameter determines how the file is opened. + * The {@link StandardOpenOption#READ READ} and {@link StandardOpenOption#WRITE WRITE} + * options determine if the file should be opened for reading and/or writing. + * If neither option (or the {@link StandardOpenOption#APPEND APPEND} + * option) is contained in the array then the file is opened for reading. + * By default reading or writing commences at the beginning of the file. + * + * <p> In the addition to {@code READ} and {@code WRITE}, the following + * options may be present: + * + * <table border=1 cellpadding=5 summary=""> + * <tr> <th>Option</th> <th>Description</th> </tr> + * <tr> + * <td> {@link StandardOpenOption#APPEND APPEND} </td> + * <td> If this option is present then the file is opened for writing and + * each invocation of the channel's {@code write} method first advances + * the position to the end of the file and then writes the requested + * data. Whether the advancement of the position and the writing of the + * data are done in a single atomic operation is system-dependent and + * therefore unspecified. This option may not be used in conjunction + * with the {@code READ} or {@code TRUNCATE_EXISTING} options. </td> + * </tr> + * <tr> + * <td> {@link StandardOpenOption#TRUNCATE_EXISTING TRUNCATE_EXISTING} </td> + * <td> If this option is present then the existing file is truncated to + * a size of 0 bytes. This option is ignored when the file is opened only + * for reading. </td> + * </tr> + * <tr> + * <td> {@link StandardOpenOption#CREATE_NEW CREATE_NEW} </td> + * <td> If this option is present then a new file is created, failing if + * the file already exists or is a symbolic link. When creating a file the + * check for the existence of the file and the creation of the file if it + * does not exist is atomic with respect to other file system operations. + * This option is ignored when the file is opened only for reading. </td> + * </tr> + * <tr> + * <td > {@link StandardOpenOption#CREATE CREATE} </td> + * <td> If this option is present then an existing file is opened if it + * exists, otherwise a new file is created. This option is ignored if the + * {@code CREATE_NEW} option is also present or the file is opened only + * for reading. </td> + * </tr> + * <tr> + * <td > {@link StandardOpenOption#DELETE_ON_CLOSE DELETE_ON_CLOSE} </td> + * <td> When this option is present then the implementation makes a + * <em>best effort</em> attempt to delete the file when closed by the + * {@link SeekableByteChannel#close close} method. If the {@code close} + * method is not invoked then a <em>best effort</em> attempt is made to + * delete the file when the Java virtual machine terminates. </td> + * </tr> + * <tr> + * <td>{@link StandardOpenOption#SPARSE SPARSE} </td> + * <td> When creating a new file this option is a <em>hint</em> that the + * new file will be sparse. This option is ignored when not creating + * a new file. </td> + * </tr> + * <tr> + * <td> {@link StandardOpenOption#SYNC SYNC} </td> + * <td> Requires that every update to the file's content or metadata be + * written synchronously to the underlying storage device. (see <a + * href="package-summary.html#integrity"> Synchronized I/O file + * integrity</a>). </td> + * <tr> + * <tr> + * <td> {@link StandardOpenOption#DSYNC DSYNC} </td> + * <td> Requires that every update to the file's content be written + * synchronously to the underlying storage device. (see <a + * href="package-summary.html#integrity"> Synchronized I/O file + * integrity</a>). </td> + * </tr> + * </table> + * + * <p> An implementation may also support additional implementation specific + * options. + * + * <p> The {@code attrs} parameter is an optional array of file {@link + * FileAttribute file-attributes} to set atomically when a new file is created. + * + * <p> In the case of the default provider, the returned seekable byte channel + * is a {@link FileChannel}. + * + * <p> <b>Usage Examples:</b> + * <pre> + * Path file = ... + * + * // open file for reading + * ReadableByteChannel rbc = file.newByteChannel(EnumSet.of(READ))); + * + * // open file for writing to the end of an existing file, creating + * // the file if it doesn't already exist + * WritableByteChannel wbc = file.newByteChannel(EnumSet.of(CREATE,APPEND)); + * + * // create file with initial permissions, opening it for both reading and writing + * FileAttribute<Set<PosixFilePermission>> perms = ... + * SeekableByteChannel sbc = file.newByteChannel(EnumSet.of(CREATE_NEW,READ,WRITE), perms); + * </pre> + * + * @param options + * Options specifying how the file is opened + * @param attrs + * An optional list of file attributes to set atomically when + * creating the file + * + * @return a new seekable byte channel + * + * @throws IllegalArgumentException + * If the set contains an invalid combination of options + * @throws UnsupportedOperationException + * If an unsupported open option is specified or the array contains + * attributes that cannot be set atomically when creating the file + * @throws FileAlreadyExistsException + * If a file of that name already exists and the {@link + * StandardOpenOption#CREATE_NEW CREATE_NEW} option is specified + * <i>(optional specific exception)</i> + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * In the case of the default provider, and a security manager is + * installed, the {@link SecurityManager#checkRead(String) checkRead} + * method is invoked to check read access to the path if the file is + * opened for reading. The {@link SecurityManager#checkWrite(String) + * checkWrite} method is invoked to check write access to the path + * if the file is opened for writing. + */ + public abstract SeekableByteChannel newByteChannel(Set<? extends OpenOption> options, + FileAttribute<?>... attrs) + throws IOException; + + /** + * Opens or creates a file, returning a seekable byte channel to access the + * file. + * + * <p> This method extends the options defined by the {@code FileRef} + * interface and to the options specified by the {@link + * #newByteChannel(Set,FileAttribute[]) newByteChannel} method + * except that the options are specified by an array. In the case of the + * default provider, the returned seekable byte channel is a {@link + * FileChannel}. + * + * @param options + * Options specifying how the file is opened + * + * @return a new seekable byte channel + * + * @throws IllegalArgumentException + * If the set contains an invalid combination of options + * @throws UnsupportedOperationException + * If an unsupported open option is specified + * @throws FileAlreadyExistsException + * If a file of that name already exists and the {@link + * StandardOpenOption#CREATE_NEW CREATE_NEW} option is specified + * <i>(optional specific exception)</i> + * @throws IOException {@inheritDoc} + * @throws SecurityException {@inheritDoc} + */ + + public abstract SeekableByteChannel newByteChannel(OpenOption... options) + throws IOException; + + /** + * Opens the file located by this path for reading, returning an input + * stream to read bytes from the file. The stream will not be buffered, and + * is not required to support the {@link InputStream#mark mark} or {@link + * InputStream#reset reset} methods. The stream will be safe for access by + * multiple concurrent threads. Reading commences at the beginning of the file. + * + * @return An input stream to read bytes from the file + * + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * In the case of the default provider, and a security manager is + * installed, the {@link SecurityManager#checkRead(String) checkRead} + * method is invoked to check read access to the file. + */ + public abstract InputStream newInputStream() throws IOException; + + /** + * Opens or creates the file located by this path for writing, returning an + * output stream to write bytes to the file. + * + * <p> This method opens or creates a file in exactly the manner specified + * by the {@link Path#newByteChannel(Set,FileAttribute[]) newByteChannel} + * method except that the {@link StandardOpenOption#READ READ} option may not + * be present in the array of open options. If no open options are present + * then this method creates a new file for writing or truncates an existing + * file. + * + * <p> The resulting stream will not be buffered. The stream will be safe + * for access by multiple concurrent threads. + * + * <p> <b>Usage Example:</b> + * Suppose we wish to open a log file for writing so that we append to the + * file if it already exists, or create it when it doesn't exist. + * <pre> + * Path logfile = ... + * OutputStream out = new BufferedOutputStream(logfile.newOutputStream(CREATE, APPEND)); + * </pre> + * + * @param options + * Options specifying how the file is opened + * + * @return a new seekable byte channel + * + * @throws IllegalArgumentException + * If {@code options} contains an invalid combination of options + * @throws UnsupportedOperationException + * If an unsupported open option is specified + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * In the case of the default provider, and a security manager is + * installed, the {@link SecurityManager#checkWrite(String) checkWrite} + * method is invoked to check write access to the file. + */ + public abstract OutputStream newOutputStream(OpenOption... options) + throws IOException; + + /** + * Opens or creates the file located by this path for writing, returning an + * output stream to write bytes to the file. + * + * <p> This method opens or creates a file in exactly the manner specified + * by the {@link Path#newByteChannel(Set,FileAttribute[]) newByteChannel} + * method except that {@code options} parameter may not contain the {@link + * StandardOpenOption#READ READ} option. If no open options are present + * then this method creates a new file for writing or truncates an existing + * file. + * + * <p> The resulting stream will not be buffered. The stream will be safe + * for access by multiple concurrent threads. + * + * @param options + * Options specifying how the file is opened + * @param attrs + * An optional list of file attributes to set atomically when + * creating the file + * + * @return A new output stream + * + * @throws IllegalArgumentException + * If the set contains an invalid combination of options + * @throws UnsupportedOperationException + * If an unsupported open option is specified or the array contains + * attributes that cannot be set atomically when creating the file + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * In the case of the default provider, and a security manager is + * installed, the {@link SecurityManager#checkWrite(String) checkWrite} + * method is invoked to check write access to the file. + */ + public abstract OutputStream newOutputStream(Set<? extends OpenOption> options, + FileAttribute<?>... attrs) + throws IOException; + + /** + * Tells whether or not the file located by this object is considered + * <em>hidden</em>. The exact definition of hidden is platform or provider + * dependent. On UNIX for example a file is considered to be hidden if its + * name begins with a period character ('.'). On Windows a file is + * considered hidden if it isn't a directory and the DOS {@link + * DosFileAttributes#isHidden hidden} attribute is set. + * + * <p> Depending on the implementation this method may require to access + * the file system to determine if the file is considered hidden. + * + * @return {@code true} if the file is considered hidden + * + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * In the case of the default provider, and a security manager is + * installed, the {@link SecurityManager#checkRead(String) checkRead} + * method is invoked to check read access to the file. + */ + public abstract boolean isHidden() throws IOException; + + /** + * Tests whether the file located by this path exists. + * + * <p> This convenience method is intended for cases where it is required to + * take action when it can be confirmed that a file exists. This method simply + * invokes the {@link #checkAccess checkAccess} method to check if the file + * exists. If the {@code checkAccess} method succeeds then this method returns + * {@code true}, otherwise if an {@code IOException} is thrown (because the + * file doesn't exist or cannot be accessed by this Java virtual machine) + * then {@code false} is returned. + * + * <p> Note that the result of this method is immediately outdated. If this + * method indicates the file exists then there is no guarantee that a + * subsequence access will succeed. Care should be taken when using this + * method in security sensitive applications. + * + * @return {@code true} if the file exists; {@code false} if the file does + * not exist or its existence cannot be determined. + * + * @throws SecurityException + * In the case of the default provider, the {@link + * SecurityManager#checkRead(String)} is invoked to check + * read access to the file. + * + * @see #notExists + */ + public abstract boolean exists(); + + /** + * Tests whether the file located by this path does not exist. + * + * <p> This convenience method is intended for cases where it is required to + * take action when it can be confirmed that a file does not exist. This + * method invokes the {@link #checkAccess checkAccess} method to check if the + * file exists. If the file does not exist then {@code true} is returned, + * otherwise the file exists or cannot be accessed by this Java virtual + * machine and {@code false} is returned. + * + * <p> Note that this method is not the complement of the {@link #exists + * exists} method. Where it is not possible to determine if a file exists + * or not then both methods return {@code false}. As with the {@code exists} + * method, the result of this method is immediately outdated. If this + * method indicates the file does exist then there is no guarantee that a + * subsequence attempt to create the file will succeed. Care should be taken + * when using this method in security sensitive applications. + * + * @return {@code true} if the file does not exist; {@code false} if the + * file exists or its existence cannot be determined. + * + * @throws SecurityException + * In the case of the default provider, the {@link + * SecurityManager#checkRead(String)} is invoked to check + * read access to the file. + */ + public abstract boolean notExists(); + + // -- watchable -- + + /** + * Registers the file located by this path with a watch service. + * + * <p> In this release, this path locates a directory that exists. The + * directory is registered with the watch service so that entries in the + * directory can be watched. The {@code events} parameter is an array of + * events to register and may contain the following events: + * <ul> + * <li>{@link StandardWatchEventKind#ENTRY_CREATE ENTRY_CREATE} - + * entry created or moved into the directory</li> + * <li>{@link StandardWatchEventKind#ENTRY_DELETE ENTRY_DELETE} - + * entry deleted or moved out of the directory</li> + * <li>{@link StandardWatchEventKind#ENTRY_MODIFY ENTRY_MODIFY} - + * entry in directory was modified</li> + * </ul> + * + * <p> The {@link WatchEvent#context context} for these events is the + * relative path between the directory located by this path, and the path + * that locates the directory entry that is created, deleted, or modified. + * + * <p> The set of events may include additional implementation specific + * event that are not defined by the enum {@link StandardWatchEventKind} + * + * <p> The {@code modifiers} parameter is an array of <em>modifiers</em> + * that qualify how the directory is registered. This release does not + * define any <em>standard</em> modifiers. The array may contain + * implementation specific modifiers. + * + * <p> Where a file is registered with a watch service by means of a symbolic + * link then it is implementation specific if the watch continues to depend + * on the existence of the link after it is registered. + * + * <p> <b>Usage Example:</b> + * Suppose we wish register a directory for entry create, delete, and modify + * events: + * <pre> + * Path dir = ... + * WatchService watcher = ... + * + * WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY); + * </pre> + * + * @param watcher + * The watch service to which this object is to be registered + * @param events + * The events for which this object should be registered + * @param modifiers + * The modifiers, if any, that modify how the object is registered + * + * @return A key representing the registration of this object with the + * given watch service + * + * @throws UnsupportedOperationException + * If unsupported events or modifiers are specified + * @throws IllegalArgumentException + * If an invalid combination of events or modifiers is specified + * @throws ClosedWatchServiceException + * If the watch service is closed + * @throws NotDirectoryException + * If the file is registered to watch the entries in a directory + * and the file is not a directory <i>(optional specific exception)</i> + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * In the case of the default provider, and a security manager is + * installed, the {@link SecurityManager#checkRead(String) checkRead} + * method is invoked to check read access to the file. + */ + + public abstract WatchKey register(WatchService watcher, + WatchEvent.Kind<?>[] events, + WatchEvent.Modifier... modifiers) + throws IOException; + + // -- Iterable -- + + /** + * Returns an iterator over the name elements of this path. + * + * <p> The first element returned by the iterator represents the name + * element that is closest to the root in the directory hierarchy, the + * second element is the next closest, and so on. The last element returned + * is the name of the file or directory denoted by this path. The {@link + * #getRoot root} component, if present, is not returned by the iterator. + * + * @return An iterator over the name elements of this path. + */ + + public abstract Iterator<Path> iterator(); + + // -- compareTo/equals/hashCode -- + + /** + * Compares two abstract paths lexicographically. The ordering defined by + * this method is provider specific, and in the case of the default + * provider, platform specific. This method does not access the file system + * and neither file is required to exist. + * + * @param other The path compared to this path. + * + * @return Zero if the argument is {@link #equals equal} to this path, a + * value less than zero if this path is lexicographically less than + * the argument, or a value greater than zero if this path is + * lexicographically greater than the argument + */ + + public abstract int compareTo(Path other); + + /** + * Tests this path for equality with the given object. + * + * <p> If the given object is not a Path, or is a Path associated with a + * different provider, then this method immediately returns {@code false}. + * + * <p> Whether or not two path are equal depends on the file system + * implementation. In some cases the paths are compared without regard + * to case, and others are case sensitive. This method does not access the + * file system and the file is not required to exist. + * + * <p> This method satisfies the general contract of the {@link + * java.lang.Object#equals(Object) Object.equals} method. </p> + * + * @param ob + * The object to which this object is to be compared + * + * @return {@code true} if, and only if, the given object is a {@code Path} + * that is identical to this {@code Path} + */ + + public abstract boolean equals(Object ob); + + /** + * Computes a hash code for this path. + * + * <p> The hash code is based upon the components of the path, and + * satisfies the general contract of the {@link Object#hashCode + * Object.hashCode} method. + * + * @return The hash-code value for this Path + */ + + public abstract int hashCode(); + + /** + * Returns the string representation of this path. + * + * <p> If this path was created by converting a path string using the + * {@link FileSystem#getPath getPath} method then the path string returned + * by this method may differ from the original String used to create the path. + * + * <p> The returned path string uses the default name {@link + * FileSystem#getSeparator separator} to separate names in the path. + * + * @return The string representation of this path + */ + + public abstract String toString(); +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/PathMatcher.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,50 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file; + +/** + * An interface that is implemented by objects that perform match operations on + * paths. + * + * @since 1.7 + * + * @see FileSystem#getNameMatcher + * @see Path#newDirectoryStream(String) + */ + +public interface PathMatcher { + /** + * Tells if given path matches this matcher's pattern. + * + * @param path + * The path to match + * + * @return {@code true} if, and only if, the path matches this + * matcher's pattern + */ + boolean matches(Path path); +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/Paths.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,126 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file; + +import java.net.URI; +import java.util.Iterator; + +import org.classpath.icedtea.java.nio.file.spi.FileSystemProvider; + +/** + * This class consists exclusively of static methods that return a {@link Path} + * by converting a path string or {@link URI}. + * + * @since 1.7 + */ + +public class Paths { + private Paths() { } + + /** + * Constructs a {@code Path} by converting the given path string. + * + * <p> The {@code Path} is obtained by invoking the {@link FileSystem#getPath + * getPath} method of the {@link FileSystems#getDefault default} {@link + * FileSystem}. + * + * @param path + * The path string to convert + * + * @return The resulting {@code Path} + * + * @throws InvalidPathException + * If the path string cannot be converted to a {@code Path} + * + * @see FileSystem#getPath + */ + public static Path get(String path) { + return FileSystems.getDefault().getPath(path); + } + + /** + * Converts the given URI to a {@link Path} object. + * + * <p> This method iterates over the {@link FileSystemProvider#installedProviders() + * installed} providers to locate the provider that is identified by the + * URI {@link URI#getScheme scheme} of the given URI. URI schemes are + * compared without regard to case. If the provider is found then its {@link + * FileSystemProvider#getPath getPath} method is invoked to convert the + * URI. + * + * <p> In the case of the default provider, identified by the URI scheme + * "file", the given URI has a non-empty path component, and undefined query + * and fragment components. Whether the authority component may be present + * is platform specific. The returned {@code Path} is associated with the + * {@link FileSystems#getDefault default} file system. + * + * <p> The default provider provides a similar <em>round-trip</em> guarantee + * to the {@link java.io.File} class. For a given {@code Path} <i>p</i> it + * is guaranteed that + * <blockquote><tt> + * Paths.get(</tt><i>p</i><tt>.{@link Path#toUri() toUri}()).equals(</tt> + * <i>p</i><tt>.{@link Path#toAbsolutePath() toAbsolutePath}())</tt> + * </blockquote> + * so long as the original {@code Path}, the {@code URI}, and the new {@code + * Path} are all created in (possibly different invocations of) the same + * Java virtual machine. Whether other providers make any guarantees is + * provider specific and therefore unspecified. + * + * @param uri + * The URI to convert + * + * @return The resulting {@code Path} + * + * @throws IllegalArgumentException + * If preconditions on the {@code uri} parameter do not hold. The + * format of the URI is provider specific. + * @throws FileSystemNotFoundException + * If the file system identified by the URI does not exist or the + * provider identified by the URI's scheme component is not installed + * @throws SecurityException + * If a security manager is installed and it denies an unspecified + * permission to access the file system + */ + public static Path get(URI uri) { + String scheme = uri.getScheme(); + if (scheme == null) + throw new IllegalArgumentException("Missing scheme"); + + // check for default provider to avoid loading of installed providers + if (scheme.equalsIgnoreCase("file")) + return FileSystems.getDefault().provider().getPath(uri); + + // try to find provider + for (FileSystemProvider provider: FileSystemProvider.installedProviders()) { + if (provider.getScheme().equalsIgnoreCase(scheme)) { + return provider.getPath(uri); + } + } + + throw new FileSystemNotFoundException("Provider \"" + scheme + "\" not installed"); + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/ProviderMismatchException.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,54 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file; + +/** + * Unchecked exception thrown when an attempt is made to invoke a method on an + * object created by one file system provider with a parameter created by a + * different file system provider. + */ +public class ProviderMismatchException + extends java.lang.IllegalArgumentException +{ + static final long serialVersionUID = 4990847485741612530L; + + /** + * Constructs an instance of this class. + */ + public ProviderMismatchException() { + } + + /** + * Constructs an instance of this class. + * + * @param msg + * The detail message + */ + public ProviderMismatchException(String msg) { + super(msg); + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/ProviderNotFoundException.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,53 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file; + +/** + * Runtime exception thrown a provider of the required type cannot be found. + */ + +public class ProviderNotFoundException + extends RuntimeException +{ + static final long serialVersionUID = -1880012509822920354L; + + /** + * Constructs an instance of this class. + */ + public ProviderNotFoundException() { + } + + /** + * Constructs an instance of this class. + * + * @param msg + * The detail message + */ + public ProviderNotFoundException(String msg) { + super(msg); + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/ReadOnlyFileSystemException.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,44 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file; + +/** + * Unchecked exception thrown when an attempt is made to update an object in a + * file system that is accessed through a read-only {@code FileSystem}. + */ + +public class ReadOnlyFileSystemException + extends UnsupportedOperationException +{ + static final long serialVersionUID = -6822409595617487197L; + + /** + * Constructs an instance of this class. + */ + public ReadOnlyFileSystemException() { + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/SecureDirectoryStream.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,327 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classname" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ +package org.classpath.icedtea.java.nio.file; + +import java.util.Set; +import java.io.IOException; + +import org.classpath.icedtea.java.nio.channels.SeekableByteChannel; +import org.classpath.icedtea.java.nio.file.attribute.FileAttribute; +import org.classpath.icedtea.java.nio.file.attribute.FileAttributeView; + +/** + * A {@code DirectoryStream} that defines operations on files that are located + * relative to an open directory. A {@code SecureDirectoryStream} is intended + * for use by sophisticated or security sensitive applications requiring to + * traverse file trees or otherwise operate on directories in a race-free manner. + * Race conditions can arise when a sequence of file operations cannot be + * carried out in isolation. Each of the file operations defined by this + * interface specify a relative {@link Path}. All access to the file is relative + * to the open directory irrespective of if the directory is moved or replaced + * by an attacker while the directory is open. A {@code SecureDirectoryStream} + * may also be used as a virtual <em>working directory</em>. + * + * <p> A {@code SecureDirectoryStream} requires corresponding support from the + * underlying operating system. Where an implementation supports this features + * then the {@code DirectoryStream} returned by the {@link Path#newDirectoryStream + * newDirectoryStream} method will be a {@code SecureDirectoryStream} and must + * be cast to that type in order to invoke the methods defined by this interface. + * + * <p> As specified by {@code DirectoryStream}, the iterator's {@link + * java.util.Iterator#remove() remove} method removes the directory entry for + * the last element returned by the iterator. In the case of a {@code + * SecureDirectoryStream} the {@code remove} method behaves as if by invoking + * the {@link #deleteFile deleteFile} or {@link #deleteDirectory deleteDirectory} + * methods defined by this interface. The {@code remove} may require to examine + * the file to determine if the file is a directory, and consequently, it may + * not be atomic with respect to other file system operations. + * + * <p> In the case of the default {@link java.nio.file.spi.FileSystemProvider + * provider}, and a security manager is set, then the permission checks are + * performed using the path obtained by resolving the given relative path + * against the <i>original path</i> of the directory (irrespective of if the + * directory is moved since it was opened). + * + * @since 1.7 + */ + +public abstract class SecureDirectoryStream + implements DirectoryStream<Path> +{ + /** + * Initialize a new instance of this class. + */ + protected SecureDirectoryStream() { } + + /** + * Opens the directory identified by the given path, returning a {@code + * SecureDirectoryStream} to iterate over the entries in the directory. + * + * <p> This method works in exactly the manner specified by the {@link + * Path#newDirectoryStream newDirectoryStream} method for the case that + * the {@code path} parameter is an {@link Path#isAbsolute absolute} path. + * When the parameter is a relative path then the directory to open is + * relative to this open directory. The {@code followLinks} parameter + * determines if links should be followed. If this parameter is {@code + * false} and the file is a symbolic link then this method fails (by + * throwing an I/O exception). + * + * <p> The new directory stream, once created, is not dependent upon the + * directory stream used to create it. Closing this directory stream has no + * effect upon newly created directory stream. + * + * @param path + * The path to the directory to open + * @param followLinks + * {@code true} if the links should be followed + * @param filter + * The directory stream filter or {@code null}. + * + * @return A new and open {@code SecureDirectoryStream} object + * + * @throws ClosedDirectoryStreamException + * If the directory stream is closed + * @throws NotDirectoryException + * If the file could not otherwise be opened because it is not + * a directory <i>(optional specific exception)</i> + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * In the case of the default provider, and a security manager is + * installed, the {@link SecurityManager#checkRead(String) checkRead} + * method is invoked to check read access to the directory. + */ + public abstract SecureDirectoryStream newDirectoryStream(Path path, + boolean followLinks, + DirectoryStream.Filter<? super Path> filter) + throws IOException; + + /** + * Opens or creates a file in this directory, returning a seekable byte + * channel to access the file. + * + * <p> This method works in exactly the manner specified by the {@link + * Path#newByteChannel Path.newByteChannel} method for the + * case that the {@code path} parameter is an {@link Path#isAbsolute absolute} + * path. When the parameter is a relative path then the file to open or + * create is relative to this open directory. In addition to the options + * defined by the {@code Path.newByteChannel} method, the {@link + * LinkOption#NOFOLLOW_LINKS NOFOLLOW_LINKS} option may be used to + * ensure that this method fails if the file is a symbolic link. + * + * <p> The channel, once created, is not dependent upon the directory stream + * used to create it. Closing this directory stream has no effect upon the + * channel. + * + * @param path + * The path of the file to open open or create + * @param options + * Options specifying how the file is opened + * @param attrs + * An optional list of attributes to set atomically when creating + * the file + * + * @throws ClosedDirectoryStreamException + * If the directory stream is closed + * @throws IllegalArgumentException + * If the set contains an invalid combination of options + * @throws UnsupportedOperationException + * If an unsupported open option is specified or the array contains + * attributes that cannot be set atomically when creating the file + * @throws FileAlreadyExistsException + * If a file of that name already exists and the {@link + * StandardOpenOption#CREATE_NEW CREATE_NEW} option is specified + * <i>(optional specific exception)</i> + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * In the case of the default provider, and a security manager is + * installed, the {@link SecurityManager#checkRead(String) checkRead} + * method is invoked to check read access to the path if the file + * is opened for reading. The {@link SecurityManager#checkWrite(String) + * checkWrite} method is invoked to check write access to the path + * if the file is opened for writing. + */ + public abstract SeekableByteChannel newByteChannel(Path path, + Set<? extends OpenOption> options, + FileAttribute<?>... attrs) + throws IOException; + + /** + * Deletes a file. + * + * <p> Unlike the {@link FileRef#delete delete()} method, this method + * does not first examine the file to determine if the file is a directory. + * Whether a directory is deleted by this method is system dependent and + * therefore not specified. If the file is a symbolic-link then the link is + * deleted (not the final target of the link). When the parameter is a + * relative path then the file to delete is relative to this open directory. + * + * @param path + * The path of the file to delete + * + * @throws ClosedDirectoryStreamException + * If the directory stream is closed + * @throws NoSuchFileException + * If the the file does not exist <i>(optional specific exception)</i> + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * In the case of the default provider, and a security manager is + * installed, the {@link SecurityManager#checkDelete(String) checkDelete} + * method is invoked to check delete access to the file + */ + public abstract void deleteFile(Path path) throws IOException; + + /** + * Deletes a directory. + * + * <p> Unlike the {@link FileRef#delete delete()} method, this method + * does not first examine the file to determine if the file is a directory. + * Whether non-directories are deleted by this method is system dependent and + * therefore not specified. When the parameter is a relative path then the + * directory to delete is relative to this open directory. + * + * @param path + * The path of the directory to delete + * + * @throws ClosedDirectoryStreamException + * If the directory stream is closed + * @throws NoSuchFileException + * If the the directory does not exist <i>(optional specific exception)</i> + * @throws DirectoryNotEmptyException + * If the directory could not otherwise be deleted because it is + * not empty <i>(optional specific exception)</i> + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * In the case of the default provider, and a security manager is + * installed, the {@link SecurityManager#checkDelete(String) checkDelete} + * method is invoked to check delete access to the directory + */ + public abstract void deleteDirectory(Path path) throws IOException; + + /** + * Move a file from this directory to another directory. + * + * <p> This method works in a similar manner to {@link Path#moveTo moveTo} + * method when the {@link StandardCopyOption#ATOMIC_MOVE ATOMIC_MOVE} option + * is specified. That is, this method moves a file as an atomic file system + * operation. If the {@code srcpath} parameter is an {@link Path#isAbsolute + * absolute} path then it locates the source file. If the parameter is a + * relative path then it is located relative to this open directory. If + * the {@code targetpath} parameter is absolute then it locates the target + * file (the {@code targetdir} parameter is ignored). If the parameter is + * a relative path it is located relative to the open directory identified + * by the {@code targetdir} parameter. In all cases, if the target file + * exists then it is implementation specific if it is replaced or this + * method fails. + * + * @param srcpath + * The name of the file to move + * @param targetdir + * The destination directory + * @param targetpath + * The name to give the file in the destination directory + * + * @throws ClosedDirectoryStreamException + * If this or the target directory stream is closed + * @throws FileAlreadyExistsException + * The file already exists in the target directory and cannot + * be replaced <i>(optional specific exception)</i> + * @throws AtomicMoveNotSupportedException + * The file cannot be moved as an atomic file system operation + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * In the case of the default provider, and a security manager is + * installed, the {@link SecurityManager#checkWrite(String) checkWrite} + * method is invoked to check write access to both the source and + * target file. + */ + public abstract void move(Path srcpath, SecureDirectoryStream targetdir, Path targetpath) + throws IOException; + + /** + * Returns a new file attribute view to access the file attributes of this + * directory. + * + * <p> The resulting file attribute view can be used to read or update the + * attributes of this (open) directory. The {@code type} parameter specifies + * the type of the attribute view and the method returns an instance of that + * type if supported. Invoking this method to obtain a {@link + * BasicFileAttributeView} always returns an instance of that class that is + * bound to this open directory. + * + * <p> The state of resulting file attribute view is intimately connected + * to this directory stream. Once the directory stream is {@link #close closed}, + * then all methods to read or update attributes will throw {@link + * ClosedDirectoryStreamException ClosedDirectoryStreamException}. + * + * @param type + * The {@code Class} object corresponding to the file attribute view + * + * @return A new file attribute view of the specified type bound to + * this directory stream, or {@code null} if the attribute view + * type is not available + */ + public abstract <V extends FileAttributeView> V getFileAttributeView(Class<V> type); + + /** + * Returns a new file attribute view to access the file attributes of a file + * in this directory. + * + * <p> The resulting file attribute view can be used to read or update the + * attributes of file in this directory. The {@code type} parameter specifies + * the type of the attribute view and the method returns an instance of that + * type if supported. Invoking this method to obtain a {@link + * BasicFileAttributeView} always returns an instance of that class that is + * bound to the file in the directory. + * + * <p> The state of resulting file attribute view is intimately connected + * to this directory stream. Once the directory stream {@link #close closed}, + * then all methods to read or update attributes will throw {@link + * ClosedDirectoryStreamException ClosedDirectoryStreamException}. The + * file is not required to exist at the time that the file attribute view + * is created but methods to read or update attributes of the file will + * fail when invoked and the file does not exist. + * + * @param path + * The path of the file + * @param type + * The {@code Class} object corresponding to the file attribute view + * @param options + * Options indicating how symbolic links are handled + * + * @return A new file attribute view of the specified type bound to a + * this directory stream, or {@code null} if the attribute view + * type is not available + * + */ + public abstract <V extends FileAttributeView> V getFileAttributeView(Path path, + Class<V> type, + LinkOption... options); +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/SimpleFileVisitor.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,123 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file; + +import java.io.IOException; +import java.io.IOError; + +import org.classpath.icedtea.java.nio.file.attribute.BasicFileAttributes; + +/** + * A simple visitor of files with default behavior to visit all files and to + * re-throw I/O errors. + * + * <p> Methods in this class may be overridden subject to their general contract. + * + * @param <T> The type of reference to the files + * + * @since 1.7 + */ + +public class SimpleFileVisitor<T extends FileRef> implements FileVisitor<T> { + /** + * Initializes a new instance of this class. + */ + protected SimpleFileVisitor() { + } + + /** + * Invoked for a directory before entries in the directory are visited. + * + * <p> Unless overridden, this method returns {@link FileVisitResult#CONTINUE + * CONTINUE}. + */ + + public FileVisitResult preVisitDirectory(T dir) { + return FileVisitResult.CONTINUE; + } + + /** + * Invoked for a directory that could not be opened. + * + * <p> Unless overridden, this method throws {@link IOError} with the I/O + * exception as cause. + * + * @throws IOError + * With the I/O exception thrown when the attempt to open the + * directory failed + */ + + public FileVisitResult preVisitDirectoryFailed(T dir, IOException exc) { + throw new IOError(exc); + } + + /** + * Invoked for a file in a directory. + * + * <p> Unless overridden, this method returns {@link FileVisitResult#CONTINUE + * CONTINUE}. + */ + + public FileVisitResult visitFile(T file, BasicFileAttributes attrs) { + return FileVisitResult.CONTINUE; + } + + /** + * Invoked for a file when its basic file attributes could not be read. + * + * <p> Unless overridden, this method throws {@link IOError} with the I/O + * exception as cause. + * + * @throws IOError + * With the I/O exception thrown when the attempt to read the file + * attributes failed + */ + + public FileVisitResult visitFileFailed(T file, IOException exc) { + throw new IOError(exc); + } + + /** + * Invoked for a directory after entries in the directory, and all of their + * descendants, have been visited. + * + * <p> Unless overridden, this method returns {@link FileVisitResult#CONTINUE + * CONTINUE} if the directory iteration completes without an I/O exception; + * otherwise this method throws {@link IOError} with the I/O exception as + * cause. + * + * @throws IOError + * If iteration of the directory completed prematurely due to an + * I/O error + */ + + public FileVisitResult postVisitDirectory(T dir, IOException exc) { + if (exc != null) + throw new IOError(exc); + return FileVisitResult.CONTINUE; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/StandardCopyOption.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,48 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file; + +/** + * Defines the standard copy options. + * + * @since 1.7 + */ + +public enum StandardCopyOption implements CopyOption { + /** + * Replace an existing file if it exists. + */ + REPLACE_EXISTING, + /** + * Copy attributes to the new file. + */ + COPY_ATTRIBUTES, + /** + * Move the file as an atomic file system operation. + */ + ATOMIC_MOVE; +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/StandardOpenOption.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,126 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file; + +/** + * Defines the standard open options. + * + * @since 1.7 + */ + +public enum StandardOpenOption implements OpenOption { + /** + * Open for read access. + */ + READ, + + /** + * Open for write access. + */ + WRITE, + + /** + * If the file is opened for {@link #WRITE} access then bytes will be written + * to the end of the file rather than the beginning. + * + * <p> If the file is opened for write access by other programs, then it + * is file system specific if writing to the end of the file is atomic. + */ + APPEND, + + /** + * If the file already exists and it is opened for {@link #WRITE} + * access, then its length is truncated to 0. This option is ignored + * if the file is opened only for {@link #READ} access. + */ + TRUNCATE_EXISTING, + + /** + * Create a new file if it does not exist. + * This option is ignored if the {@link #CREATE_NEW} option is also set. + * The check for the existence of the file and the creation of the file + * if it does not exist is atomic with respect to other file system + * operations. + */ + CREATE, + + /** + * Create a new file, failing if the file already exists. + * The check for the existence of the file and the creation of the file + * if it does not exist is atomic with respect to other file system + * operations. + */ + CREATE_NEW, + + /** + * Delete on close. When this option is present then the implementation + * makes a <em>best effort</em> attempt to delete the file when the closed + * by the appropriate {@code close} method. If the {@code close} method is + * not invoked then a <em>best effort</em> attempt is made to delete the + * file when the Java virtual machine terminates (either normally, as + * defined by the Java Language Specification, or where possible, abnormally). + * This option is primarily intended for use with <em>work files</em> that + * are used solely by a single instance of the Java virtual machine. This + * option is not recommended for use when opening files that are open + * concurrently by other entities. Many of the details as to when and how + * the file is deleted are implementation specific and therefore not + * specified. In particular, an implementation may be unable to guarantee + * that it deletes the expected file when replaced by an attacker while the + * file is open. Consequently, security sensitive applications should take + * care when using this option. + * + * <p> For security reasons, this option may imply the {@link + * LinkOption#NOFOLLOW_LINKS} option. In other words, if the option is present + * when opening an existing file that is a symbolic link then it may fail + * (by throwing {@link java.io.IOException}). + */ + DELETE_ON_CLOSE, + + /** + * Sparse file. When used with the {@link #CREATE_NEW} option then this + * option provides a <em>hint</em> that the new file will be sparse. The + * option is ignored when the file system does not support the creation of + * sparse files. + */ + SPARSE, + + /** + * Requires that every update to the file's content or metadata be written + * synchronously to the underlying storage device. + * + * @see <a href="package-summary.html#integrity">Synchronized I/O file integrity</a> + */ + SYNC, + + /** + * Requires that every update to the file's content be written + * synchronously to the underlying storage device. + * + * @see <a href="package-summary.html#integrity">Synchronized I/O file integrity</a> + */ + DSYNC; +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/StandardWatchEventKind.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,95 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file; + +/** + * Defines the <em>standard</em> event kinds. + * + * @since 1.7 + */ + +public class StandardWatchEventKind { + private StandardWatchEventKind() { } + + /** + * A special event to indicate that events may have been lost or + * discarded. + * + * <p> The {@link WatchEvent#context context} for this event is + * implementation specific and may be {@code null}. The event {@link + * WatchEvent#count count} may be greater than {@code 1}. + * + * @see WatchService + */ + public static final WatchEvent.Kind<Void> OVERFLOW = + new StdWatchEventKind<Void>("OVERFLOW", Void.class); + + /** + * Directory entry created. + * + * <p> When a directory is registered for this event then the {@link WatchKey} + * is queued when it is observed that an entry is created in the directory + * or renamed into the directory. The event {@link WatchEvent#count count} + * for this event is always {@code 1}. + */ + public static final WatchEvent.Kind<Path> ENTRY_CREATE = + new StdWatchEventKind<Path>("ENTRY_CREATE", Path.class); + + /** + * Directory entry deleted. + * + * <p> When a directory is registered for this event then the {@link WatchKey} + * is queued when it is observed that an entry is deleted or renamed out of + * the directory. The event {@link WatchEvent#count count} for this event + * is always {@code 1}. + */ + public static final WatchEvent.Kind<Path> ENTRY_DELETE = + new StdWatchEventKind<Path>("ENTRY_DELETE", Path.class); + + /** + * Directory entry modified. + * + * <p> When a directory is registered for this event then the {@link WatchKey} + * is queued when it is observed that an entry in the directory has been + * modified. The event {@link WatchEvent#count count} for this event is + * {@code 1} or greater. + */ + public static final WatchEvent.Kind<Path> ENTRY_MODIFY = + new StdWatchEventKind<Path>("ENTRY_MODIFY", Path.class); + + private static class StdWatchEventKind<T> implements WatchEvent.Kind<T> { + private final String name; + private final Class<T> type; + StdWatchEventKind(String name, Class<T> type) { + this.name = name; + this.type = type; + } + public String name() { return name; } + public Class<T> type() { return type; } + public String toString() { return name; } + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/WatchEvent.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,117 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file; + +/** + * An event or a repeated event for an object that is registered with a {@link + * WatchService}. + * + * <p> An event is classified by its {@link #kind() kind} and has a {@link + * #count() count} to indicate the number of times that the event has been + * observed. This allows for efficient representation of repeated events. The + * {@link #context() context} method returns any context associated with + * the event. In the case of a repeated event then the context is the same for + * all events. + * + * <p> Watch events are immutable and safe for use by multiple concurrent + * threads. + * + * @param <T> The type of the context object associated with the event + * + * @since 1.7 + */ + +public abstract class WatchEvent<T> { + + /** + * An event kind, for the purposes of identification. + * + * @since 1.7 + * @see StandardWatchEventKind + */ + public static interface Kind<T> { + /** + * Returns the name of the event kind. + */ + String name(); + + /** + * Returns the type of the {@link WatchEvent#context context} value. + */ + Class<T> type(); + } + + /** + * Initializes a new instance of this class. + */ + protected WatchEvent() { } + + /** + * An event modifier that qualifies how a {@link Watchable} is registered + * with a {@link WatchService}. + * + * <p> This release does not define any <em>standard</em> modifiers. + * + * @since 1.7 + * @see Watchable#register + */ + public static interface Modifier { + /** + * Returns the name of the modifier. + */ + String name(); + } + + /** + * Returns the event kind. + * + * @return The event kind + */ + public abstract Kind<T> kind(); + + /** + * Returns the event count. If the event count is greater than {@code 1} + * then this is a repeated event. + * + * @return The event count + */ + public abstract int count(); + + /** + * Returns the context for the event. + * + * <p> In the case of {@link StandardWatchEventKind#ENTRY_CREATE ENTRY_CREATE}, + * {@link StandardWatchEventKind#ENTRY_DELETE ENTRY_DELETE}, and {@link + * StandardWatchEventKind#ENTRY_MODIFY ENTRY_MODIFY} events the context is + * a {@code Path} that is the {@link Path#relativize relative} path between + * the directory registered with the watch service, and the entry that is + * created, deleted, or modified. + * + * @return The event context; may be {@code null} + */ + public abstract T context(); +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/WatchKey.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,138 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file; + +import java.util.List; + +/** + * A key representing the registration of an object with a {@link WatchService}. + * + * <p> A watch key is created when a {@link Watchable Watchable} object is + * registered with a watch service. The key remains {@link #isValid valid} until: + * <ol> + * <li> It is cancelled, explicitly, by invoking its {@link #cancel cancel} + * method, or</li> + * <li> Cancelled implicitly, because the object is no longer accessible, + * or </li> + * <li> By {@link WatchService#close closing} the watch service. </li> + * </ol> + * + * <p> A watch key has a state. When initially created the key is said to be + * <em>ready</em>. When an event is detected then the key is <em>signalled</em> + * and queued so that it can be retrieved by invoking the watch service's {@link + * WatchService#poll() poll} or {@link WatchService#take() take} methods. Once + * signalled, a key remains in this state until its {@link #reset reset} method + * is invoked to return the key to the ready state. Events detected while the + * key is in the signalled state are queued but do not cause the key to be + * re-queued for retrieval from the watch service. Events are retrieved by + * invoking the key's {@link #pollEvents pollEvents} method. This method + * retrieves and removes all events accumulated for the object. When initially + * created, a watch key has no pending events. Typically events are retrieved + * when the key is in the signalled state leading to the following idiom: + * + * <pre> + * for (;;) { + * // retrieve key + * WatchKey key = watcher.take(); + * + * // process events + * for (WatchEvent<?> event: key.pollEvents()) { + * : + * } + * + * // reset the key + * boolean valid = key.reset(); + * if (!valid) { + * // object no longer registered + * } + * } + * </pre> + * + * <p> Watch keys are safe for use by multiple concurrent threads. Where there + * are several threads retrieving signalled keys from a watch service then care + * should be taken to ensure that the {@code reset} method is only invoked after + * the events for the object have been processed. This ensures that one thread + * is processing the events for an object at any time. + * + * @since 1.7 + */ + +public abstract class WatchKey { + /** + * Initializes a new instance of this class. + */ + protected WatchKey() { } + + /** + * Tells whether or not this watch key is valid. + * + * <p> A watch key is valid upon creation and remains until it is cancelled, + * or its watch service is closed. + * + * @return {@code true} if, and only if, this watch key is valid + */ + public abstract boolean isValid(); + + /** + * Retrieves and removes all pending events for this watch key, returning + * a {@code List} of the events that were retrieved. + * + * <p> Note that this method does not wait if there are no events pending. + * + * @return The list of the events retrieved + */ + public abstract List<WatchEvent<?>> pollEvents(); + + /** + * Resets this watch key. + * + * <p> If this watch key has been cancelled or this watch key is already in + * the ready state then invoking this method has no effect. Otherwise + * if there are pending events for the object then this watch key is + * immediately re-queued to the watch service. If there are no pending + * events then the watch key is put into the ready state and will remain in + * that state until an event is detected or the watch key is cancelled. + * + * @return {@code true} if the watch key is valid and has been reset; + * {@code false} if the watch key could not be reset because it is + * no longer {@link #isValid valid} + */ + public abstract boolean reset(); + + /** + * Cancels the registration with the watch service. Upon return the watch key + * will be invalid. If the watch key is enqueued, waiting to be retrieved + * from the watch service, then it will remain in the queue until it is + * removed. Pending events, if any, remain pending and may be retrieved by + * invoking the {@link #pollEvents pollEvents} method event after the key is + * cancelled. + * + * <p> If this watch key has already been cancelled then invoking this + * method has no effect. Once cancelled, a watch key remains forever invalid. + */ + public abstract void cancel(); +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/WatchService.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,179 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file; + +import java.io.Closeable; +import java.io.IOException; +import java.util.concurrent.TimeUnit; + +/** + * A watch service that <em>watches</em> registered objects for changes and + * events. For example a file manager may use a watch service to monitor a + * directory for changes so that it can update its display of the list of files + * when files are created or deleted. + * + * <p> A {@link Watchable} object is registered with a watch service by invoking + * its {@link Watchable#register register} method, returning a {@link WatchKey} + * to represent the registration. When an event for an object is detected the + * key is <em>signalled</em>, and if not currently signalled, it is queued to + * the watch service so that it can be retrieved by consumers that invoke the + * {@link #poll() poll} or {@link #take() take} methods to retrieve keys + * and process events. Once the events have been processed the consumer + * invokes the key's {@link WatchKey#reset reset} method to reset the key which + * allows the key to be signalled and re-queued with further events. + * + * <p> Registration with a watch service is cancelled by invoking the key's + * {@link WatchKey#cancel cancel} method. A key that is queued at the time that + * it is cancelled remains in the queue until it is retrieved. Depending on the + * object, a key may be cancelled automatically. For example, suppose a + * directory is watched and the watch service detects that it has been deleted + * or its file system is no longer accessible. When a key is cancelled in this + * manner it is signalled and queued, if not currently signalled. To ensure + * that the consumer is notified the return value from the {@code reset} + * method indicates if the key is valid. + * + * <p> A watch service is safe for use by multiple concurrent consumers. To + * ensure that only one consumer processes the events for a particular object at + * any time then care should be taken to ensure that the key's {@code reset} + * method is only invoked after its events have been processed. The {@link + * #close close} method may be invoked at any time to close the service causing + * any threads waiting to retrieve keys, to throw {@code + * ClosedWatchServiceException}. + * + * <p> File systems may report events faster than they can be retrieved or + * processed and an implementation may impose an unspecified limit on the number + * of events that it may accumulate. Where an implementation <em>knowingly</em> + * discards events then it arranges for the key's {@link WatchKey#pollEvents + * pollEvents} method to return an element with an event type of {@link + * StandardWatchEventKind#OVERFLOW OVERFLOW}. This event can be used by the + * consumer as a trigger to re-examine the state of the object. + * + * <p> When an event is reported to indicate that a file in a watched directory + * has been modified then there is no guarantee that the program (or programs) + * that have modified the file have completed. Care should be taken to coordinate + * access with other programs that may be updating the file. + * The {@link java.nio.channels.FileChannel FileChannel} class defines methods + * to lock regions of a file against access by other programs. + * + * <h4>Platform dependencies</h4> + * + * <p> The implementation that observes events from the file system is intended + * to map directly on to the native file event notification facility where + * available, or to use a primitive mechanism, such as polling, when a native + * facility is not available. Consequently, many of the details on how events + * are detected, their timeliness, and whether their ordering is preserved are + * highly implementation specific. For example, when a file in a watched + * directory is modified then it may result in a single {@link + * StandardWatchEventKind#ENTRY_MODIFY ENTRY_MODIFY} event in some + * implementations but several events in other implementations. Short-lived + * files (meaning files that are deleted very quickly after they are created) + * may not be detected by primitive implementations that periodically poll the + * file system to detect changes. + * + * <p> If a watched file is not located on a local storage device then it is + * implementation specific if changes to the file can be detected. In particular, + * it is not required that changes to files carried out on remote systems be + * detected. + * + * @since 1.7 + * + * @see FileSystem#newWatchService + */ + +public abstract class WatchService + implements Closeable +{ + /** + * Initializes a new instance of this class. + */ + protected WatchService() { } + + /** + * Closes this watch service. + * + * <p> If a thread is currently blocked in the {@link #take take} or {@link + * #poll(long,TimeUnit) poll} methods waiting for a key to be queued then + * it immediately receives a {@link ClosedWatchServiceException}. Any + * valid keys associated with this watch service are {@link WatchKey#isValid + * invalidated}. + * + * <p> After a watch service is closed, any further attempt to invoke + * operations upon it will throw {@link ClosedWatchServiceException}. + * If this watch service is already closed then invoking this method + * has no effect. + * + * @throws IOException + * If an I/O error occurs + */ + + public abstract void close() throws IOException; + + /** + * Retrieves and removes the next watch key, or {@code null} if none are + * present. + * + * @return The next watch key, or {@code null} + * + * @throws ClosedWatchServiceException + * If this watch service is closed + */ + public abstract WatchKey poll(); + + /** + * Retrieves and removes the next watch key, waiting if necessary up to the + * specified wait time if none are yet present. + * + * @param timeout + * how to wait before giving up, in units of unit + * @param unit + * a {@code TimeUnit} determining how to interpret the timeout + * parameter + * + * @return The next watch key, or {@code null} + * + * @throws ClosedWatchServiceException + * If this watch service is closed, or it is closed while waiting + * for the next key + * @throws InterruptedException + * If interrupted while waiting + */ + public abstract WatchKey poll(long timeout, TimeUnit unit) + throws InterruptedException; + + /** + * Retrieves and removes next watch key waiting if none are yet present. + * + * @return The next watch key + * + * @throws ClosedWatchServiceException + * If this watch service is closed, or it is closed while waiting + * for the next key + * @throws InterruptedException + * If interrupted while waiting + */ + public abstract WatchKey take() throws InterruptedException; +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/Watchable.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,128 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file; + +import java.io.IOException; + +/** + * An object that may be registered with a watch service so that it can be + * <em>watched</em> for changes and events. + * + * <p> This interface defines the {@link #register register} method to register + * the object with a {@link WatchService} returning a {@link WatchKey} to + * represent the registration. An object may be registered with more than one + * watch service. Registration with a watch service is cancelled by invoking the + * key's {@link WatchKey#cancel cancel} method. + * + * @since 1.7 + * + * @see Path#register + */ + +public interface Watchable { + + /** + * Registers an object with a watch service. + * + * <p> If the file system object identified by this object is currently + * registered with the watch service then the watch key, representing that + * registration, is returned after changing the event set or modifiers to + * those specified by the {@code events} and {@code modifiers} parameters. + * Changing the event set does not cause pending events for the object to be + * discarded. Objects are automatically registered for the {@link + * StandardWatchEventKind#OVERFLOW OVERFLOW} event. This event is not + * required to be present in the array of events. + * + * <p> Otherwise the file system object has not yet been registered with the + * given watch service, so it is registered and the resulting new key is + * returned. + * + * <p> Implementations of this interface should specify the events they + * support. + * + * @param watcher + * The watch service to which this object is to be registered + * @param events + * The events for which this object should be registered + * @param modifiers + * The modifiers, if any, that modify how the object is registered + * + * @return A key representing the registration of this object with the + * given watch service + * + * @throws UnsupportedOperationException + * If unsupported events or modifiers are specified + * @throws IllegalArgumentException + * If an invalid of combination of events are modifiers are specified + * @throws ClosedWatchServiceException + * If the watch service is closed + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * If a security manager is installed and it denies an unspecified + * permission required to monitor this object. Implementations of + * this interface should specify the permission checks. + */ + WatchKey register(WatchService watcher, + WatchEvent.Kind<?>[] events, + WatchEvent.Modifier... modifiers) + throws IOException; + + + /** + * Registers an object with a watch service. + * + * <p> An invocation of this method behaves in exactly the same way as the + * invocation + * <pre> + * watchable.{@link #register(WatchService,WatchEvent.Kind[],WatchEvent.Modifier[]) register}(watcher, events, new WatchEvent.Modifier[0]); + * </pre> + * + * @param watcher + * The watch service to which this object is to be registered + * @param events + * The events for which this object should be registered + * + * @return A key representing the registration of this object with the + * given watch service + * + * @throws UnsupportedOperationException + * If unsupported events are specified + * @throws IllegalArgumentException + * If an invalid of combination of events are specified + * @throws ClosedWatchServiceException + * If the watch service is closed + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * If a security manager is installed and it denies an unspecified + * permission required to monitor this object. Implementations of + * this interface should specify the permission checks. + */ + WatchKey register(WatchService watcher, WatchEvent.Kind<?>... events) + throws IOException; +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/AclEntry.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,395 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file.attribute; + +import java.util.*; + +/** + * An entry in an access control list (ACL). + * + * <p> The ACL entry represented by this class is based on the ACL model + * specified in <a href="http://www.ietf.org/rfc/rfc3530.txt"><i>RFC 3530: + * Network File System (NFS) version 4 Protocol</i></a>. Each entry has four + * components as follows: + * + * <ol> + * <li><p> The {@link #type() type} component determines if the entry + * grants or denies access. </p></li> + * + * <li><p> The {@link #principal() principal} component, sometimes called the + * "who" component, is a {@link UserPrincipal} corresponding to the identity + * that the entry grants or denies access + * </p></li> + * + * <li><p> The {@link #permissions permissions} component is a set of + * {@link AclEntryPermission permissions} + * </p></li> + * + * <li><p> The {@link #flags flags} component is a set of {@link AclEntryFlag + * flags} to indicate how entries are inherited and propagated </p></li> + * </ol> + * + * <p> ACL entries are created using an associated {@link Builder} object by + * invoking its {@link Builder#build build} method. + * + * <p> ACL entries are immutable and are safe for use by multiple concurrent + * threads. + * + * @since 1.7 + */ + +public final class AclEntry { + + private final AclEntryType type; + private final UserPrincipal who; + private final Set<AclEntryPermission> perms; + private final Set<AclEntryFlag> flags; + + // cached hash code + private volatile int hash; + + // private constructor + private AclEntry(AclEntryType type, + UserPrincipal who, + Set<AclEntryPermission> perms, + Set<AclEntryFlag> flags) + { + this.type = type; + this.who = who; + this.perms = perms; + this.flags = flags; + } + + /** + * A builder of {@link AclEntry} objects. + * + * <p> A {@code Builder} object is obtained by invoking one of the {@link + * AclEntry#newBuilder newBuilder} methods defined by the {@code AclEntry} + * class. + * + * <p> Builder objects are mutable and are not safe for use by multiple + * concurrent threads without appropriate synchronization. + * + * @since 1.7 + */ + public static final class Builder { + private AclEntryType type; + private UserPrincipal who; + private Set<AclEntryPermission> perms; + private Set<AclEntryFlag> flags; + + private Builder(AclEntryType type, + UserPrincipal who, + Set<AclEntryPermission> perms, + Set<AclEntryFlag> flags) + { + assert perms != null && flags != null; + this.type = type; + this.who = who; + this.perms = perms; + this.flags = flags; + } + + /** + * Constructs an {@link AclEntry} from the components of this builder. + * The type and who components are required to have been set in order + * to construct an {@code AclEntry}. + * + * @return A new ACL entry + * + * @throws IllegalStateException + * If the type or who component have not been set. + */ + public AclEntry build() { + if (type == null) + throw new IllegalStateException("Missing type component"); + if (who == null) + throw new IllegalStateException("Missing who component"); + return new AclEntry(type, who, perms, flags); + } + + /** + * Sets the type component of this builder. + * + * @return This builder + */ + public Builder setType(AclEntryType type) { + if (type == null) + throw new NullPointerException(); + this.type = type; + return this; + } + + /** + * Sets the principal component of this builder. + * + * @return This builder + */ + public Builder setPrincipal(UserPrincipal who) { + if (who == null) + throw new NullPointerException(); + this.who = who; + return this; + } + + // check set only contains elements of the given type + private static void checkSet(Set<?> set, Class<?> type) { + for (Object e: set) { + if (e == null) + throw new NullPointerException(); + type.cast(e); + } + } + + /** + * Sets the permissions component of this builder. On return, the + * permissions component of this builder is a copy of the given set. + * + * @return This builder + * + * @throws ClassCastException + * If the sets contains elements that are not of type {@code + * AclEntryPermission} + */ + public Builder setPermissions(Set<AclEntryPermission> perms) { + // copy and check for erroneous elements + perms = new HashSet<AclEntryPermission>(perms); + checkSet(perms, AclEntryPermission.class); + this.perms = perms; + return this; + } + + /** + * Sets the permissions component of this builder. On return, the + * permissions component of this builder is a copy of the permissions in + * the given array. + * + * @return This builder + */ + public Builder setPermissions(AclEntryPermission... perms) { + Set<AclEntryPermission> set = + new HashSet<AclEntryPermission>(perms.length); + // copy and check for null elements + for (AclEntryPermission p: perms) { + if (p == null) + throw new NullPointerException(); + set.add(p); + } + this.perms = set; + return this; + } + + /** + * Sets the flags component of this builder. On return, the flags + * component of this builder is a copy of the given set. + * + * @return This builder + * + * @throws ClassCastException + * If the sets contains elements that are not of type {@code + * AclEntryFlag} + */ + public Builder setFlags(Set<AclEntryFlag> flags) { + // copy and check for erroneous elements + flags = new HashSet<AclEntryFlag>(flags); + checkSet(flags, AclEntryFlag.class); + this.flags = flags; + return this; + } + + /** + * Sets the flags component of this builder. On return, the flags + * component of this builder is a copy of the flags in the given + * array. + * + * @return This builder + */ + public Builder setFlags(AclEntryFlag... flags) { + Set<AclEntryFlag> set = new HashSet<AclEntryFlag>(flags.length); + // copy and check for null elements + for (AclEntryFlag f: flags) { + if (f == null) + throw new NullPointerException(); + set.add(f); + } + this.flags = set; + return this; + } + } + + /** + * Constructs a new builder. The initial value of the type and who + * components is {@code null}. The initial value of the permissions and + * flags components is the empty set. + * + * @return A new builder + */ + public static Builder newBuilder() { + Set<AclEntryPermission> perms = Collections.emptySet(); + Set<AclEntryFlag> flags = Collections.emptySet(); + return new Builder(null, null, perms, flags); + } + + /** + * Constructs a new builder with the components of an existing ACL entry. + * + * @param entry + * An ACL entry + * + * @return A new builder + */ + public static Builder newBuilder(AclEntry entry) { + return new Builder(entry.type, entry.who, entry.perms, entry.flags); + } + + /** + * Returns the ACL entry type. + */ + public AclEntryType type() { + return type; + } + + /** + * Returns the principal component. + */ + public UserPrincipal principal() { + return who; + } + + /** + * Returns a copy of the permissions component. + * + * <p> The returned set is a modifiable copy of the permissions. + */ + public Set<AclEntryPermission> permissions() { + return new HashSet<AclEntryPermission>(perms); + } + + /** + * Returns a copy of the flags component. + * + * <p> The returned set is a modifiable copy of the flags. + */ + public Set<AclEntryFlag> flags() { + return new HashSet<AclEntryFlag>(flags); + } + + /** + * Compares the specified object with this ACL entry for equality. + * + * <p> If the given object is not an {@code AclEntry} then this method + * immediately returns {@code false}. + * + * <p> For two ACL entries to be considered equals requires that they are + * both the same type, their who components are equal, their permissions + * components are equal, and their flags components are equal. + * + * <p> This method satisfies the general contract of the {@link + * java.lang.Object#equals(Object) Object.equals} method. </p> + * + * @param ob The object to which this object is to be compared + * + * @return {@code true} if, and only if, the given object is an AclEntry that + * is identical to this AclEntry + */ + + public boolean equals(Object ob) { + if (ob == this) + return true; + if (ob == null || !(ob instanceof AclEntry)) + return false; + AclEntry other = (AclEntry)ob; + if (this.type != other.type) + return false; + if (!this.who.equals(other.who)) + return false; + if (!this.perms.equals(other.perms)) + return false; + if (!this.flags.equals(other.flags)) + return false; + return true; + } + + private static int hash(int h, Object o) { + return h * 127 + o.hashCode(); + } + + /** + * Returns the hash-code value for this ACL entry. + * + * <p> This method satisfies the general contract of the {@link + * Object#hashCode method}. + */ + + public int hashCode() { + // return cached hash if available + if (hash != 0) + return hash; + int h = type.hashCode(); + h = hash(h, who); + h = hash(h, perms); + h = hash(h, flags); + hash = h; + return hash; + } + + /** + * Returns the string representation of this ACL entry. + * + * @return The string representation of this entry + */ + + public String toString() { + StringBuilder sb = new StringBuilder(); + + // who + sb.append(who.getName()); + sb.append(':'); + + // permissions + for (AclEntryPermission perm: perms) { + sb.append(perm.name()); + sb.append('/'); + } + sb.setLength(sb.length()-1); // drop final slash + sb.append(':'); + + // flags + if (!flags.isEmpty()) { + for (AclEntryFlag flag: flags) { + sb.append(flag.name()); + sb.append('/'); + } + sb.setLength(sb.length()-1); // drop final slash + sb.append(':'); + } + + // type + sb.append(type.name()); + return sb.toString(); + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/AclEntryFlag.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,66 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file.attribute; + +/** + * Defines the flags for used by the flags component of an ACL {@link AclEntry + * entry}. + * + * <p> In this release, this class does not define flags related to {@link + * AclEntryType#AUDIT} and {@link AclEntryType#ALARM} entry types. + * + * @since 1.7 + */ + +public enum AclEntryFlag { + + /** + * Can be placed on a directory and indicates that the ACL entry should be + * added to each new non-directory file created. + */ + FILE_INHERIT, + + /** + * Can be placed on a directory and indicates that the ACL entry should be + * added to each new directory created. + */ + DIRECTORY_INHERIT, + + /** + * Can be placed on a directory to indicate that the ACL entry should not + * be placed on the newly created directory which is inheritable by + * subdirectories of the created directory. + */ + NO_PROPAGATE_INHERIT, + + /** + * Can be placed on a directory but does not apply to the directory, + * only to newly created files/directories as specified by the + * {@link #FILE_INHERIT} and {@link #DIRECTORY_INHERIT} flags. + */ + INHERIT_ONLY; +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/AclEntryPermission.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,131 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file.attribute; + +/** + * Defines the permissions for use with the permissions component of an ACL + * {@link AclEntry entry}. + * + * @since 1.7 + */ + +public enum AclEntryPermission { + + /** + * Permission to read the data of the file. + */ + READ_DATA, + + /** + * Permission to modify the file's data. + */ + WRITE_DATA, + + /** + * Permission to append data to a file. + */ + APPEND_DATA, + + /** + * Permission to read the named attributes of a file. + * + * <p> <a href="http://www.ietf.org/rfc/rfc3530.txt">RFC 3530: Network + * File System (NFS) version 4 Protocol</a> defines <em>named attributes</em> + * as opaque files associated with a file in the file system. + */ + READ_NAMED_ATTRS, + + /** + * Permission to write the named attributes of a file. + * + * <p> <a href="http://www.ietf.org/rfc/rfc3530.txt">RFC 3530: Network + * File System (NFS) version 4 Protocol</a> defines <em>named attributes</em> + * as opaque files associated with a file in the file system. + */ + WRITE_NAMED_ATTRS, + + /** + * Permission to execute a file. + */ + EXECUTE, + + /** + * Permission to delete a file or directory within a directory. + */ + DELETE_CHILD, + + /** + * The ability to read (non-acl) file attributes. + */ + READ_ATTRIBUTES, + + /** + * The ability to write (non-acl) file attributes. + */ + WRITE_ATTRIBUTES, + + /** + * Permission to delete the file. + */ + DELETE, + + /** + * Permission to read the ACL attribute. + */ + READ_ACL, + + /** + * Permission to write the ACL attribute. + */ + WRITE_ACL, + + /** + * Permission to change the owner. + */ + WRITE_OWNER, + + /** + * Permission to access file locally at the server with synchronous reads + * and writes. + */ + SYNCHRONIZE; + + /** + * Permission to list the entries of a directory (equal to {@link #READ_DATA}) + */ + public static final AclEntryPermission LIST_DIRECTORY = READ_DATA; + + /** + * Permission to add a new file to a directory (equal to {@link #WRITE_DATA}) + */ + public static final AclEntryPermission ADD_FILE = WRITE_DATA; + + /** + * Permission to create a subdirectory to a directory (equal to {@link #APPEND_DATA}) + */ + public static final AclEntryPermission ADD_SUBDIRECTORY = APPEND_DATA; +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/AclEntryType.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,57 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file.attribute; + +/** + * A typesafe enumeration of the access control entry types. + * + * @since 1.7 + */ + +public enum AclEntryType { + /** + * Explicitly grants access to a file or directory. + */ + ALLOW, + + /** + * Explicitly denies access to a file or directory. + */ + DENY, + + /** + * Log, in a system dependent way, the access specified in the + * permissions component of the ACL entry. + */ + AUDIT, + + /** + * Generate an alarm, in a system dependent way, the access specified in the + * permissions component of the ACL entry. + */ + ALARM +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/AclFileAttributeView.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,211 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file.attribute; + +import java.util.List; +import java.io.IOException; + +/** + * A file attribute view that supports reading or updating a file's Access + * Control Lists (ACL) or file owner attributes. + * + * <p> ACLs are used to specify access rights to file system objects. An ACL is + * an ordered list of {@link AclEntry access-control-entries}, each specifying a + * {@link UserPrincipal} and the level of access for that user principal. This + * file attribute view defines the {@link #getAcl() getAcl}, and {@link + * #setAcl(List) setAcl} methods to read and write ACLs based on the ACL + * model specified in <a href="http://www.ietf.org/rfc/rfc3530.txt"><i>RFC 3530: + * Network File System (NFS) version 4 Protocol</i></a>. This file attribute view + * is intended for file system implementations that support the NFSv4 ACL model + * or have a <em>well-defined</em> mapping between the NFSv4 ACL model and the ACL + * model used by the file system. The details of such mapping are implementation + * dependent and are therefore unspecified. + * + * <p> This class also extends {@code FileOwnerAttributeView} so as to define + * methods to get and set the file owner. + * + * <p> When a file system provides access to a set of {@link FileStore + * file-systems} that are not homogeneous then only some of the file systems may + * support ACLs. The {@link FileStore#supportsFileAttributeView + * supportsFileAttributeView} method can be used to test if a file system + * supports ACLs. + * + * <a name="interop"><h4>Interoperability</h4></a> + * + * RFC 3530 allows for special user identities to be used on platforms that + * support the POSIX defined access permissions. The special user identities + * are "{@code OWNER@}", "{@code GROUP@}", and "{@code EVERYONE@}". When both + * the {@code AclFileAttributeView} and the {@link PosixFileAttributeView} + * are supported then these special user identities may be included in ACL {@link + * AclEntry entries} that are read or written. The file system's {@link + * UserPrincipalLookupService} may be used to obtain a {@link UserPrincipal} + * to represent these special identities by invoking the {@link + * UserPrincipalLookupService#lookupPrincipalByName lookupPrincipalByName} + * method. + * + * <p> <b>Usage Example:</b> + * Suppose we wish to add an entry to an existing ACL to grant "joe" access: + * <pre> + * // lookup "joe" + * UserPrincipal joe = file.getFileSystem().getUserPrincipalLookupService() + * .lookupPrincipalByName("joe"); + * + * // get view + * AclFileAttributeView view = file.newFileAttributeView(AclFileAttributeView.class); + * + * // create ACE to give "joe" read access + * AclEntry entry = AclEntry.newBuilder() + * .setType(AclEntryType.ALLOW) + * .setPrincipal(joe) + * .setPermissions(AclEntryPermission.READ_DATA, AclEntryPermission.READ_ATTRIBUTES) + * .build(); + * + * // read ACL, insert ACE, re-write ACL + * List<AclEntry> acl = view.getAcl(); + * acl.add(0, entry); // insert before any DENY entries + * view.setAcl(acl); + * </pre> + * + * <h4> Dynamic Access </h4> + * <p> Where dynamic access to file attributes is required, the attributes + * supported by this attribute view are as follows: + * <blockquote> + * <table border="1" cellpadding="8"> + * <tr> + * <th> Name </th> + * <th> Type </th> + * </tr> + * <tr> + * <td> "acl" </td> + * <td> {@link List}<{@link AclEntry}> </td> + * </tr> + * <tr> + * <td> "owner" </td> + * <td> {@link UserPrincipal} </td> + * </tr> + * </table> + * </blockquote> + * + * <p> The {@link #getAttribute getAttribute} or {@link #readAttributes + * readAttributes} methods may be used to read the ACL or owner attributes as if + * by invoking the {@link #getAcl getAcl} or {@link #getOwner getOwner} methods. + * + * <p> The {@link #setAttribute setAttribute} method may be used to update the + * ACL or owner attributes as if by invoking the {@link #setAcl setAcl} or {@link + * #setOwner setOwner} methods. + * + * <h4> Setting the ACL when creating a file </h4> + * + * <p> Implementations supporting this attribute view may also support setting + * the initial ACL when creating a file or directory. The initial ACL + * may be provided to methods such as {@link Path#createFile createFile} or {@link + * Path#createDirectory createDirectory} as an {@link FileAttribute} with {@link + * FileAttribute#name name} {@code "acl:acl"} and a {@link FileAttribute#value + * value} that is the list of {@code AclEntry} objects. + * + * <p> Where an implementation supports an ACL model that differs from the NFSv4 + * defined ACL model then setting the initial ACL when creating the file must + * translate the ACL to the model supported by the file system. Methods that + * create a file should reject (by throwing {@link IOException IOException}) + * any attempt to create a file that would be less secure as a result of the + * translation. + * + * @since 1.7 + * @see Attributes#getAcl + * @see Attributes#setAcl + */ + +public interface AclFileAttributeView + extends FileOwnerAttributeView +{ + /** + * Returns the name of the attribute view. Attribute views of this type + * have the name {@code "acl"}. + */ + + String name(); + + /** + * Reads the access control list. + * + * <p> When the file system uses an ACL model that differs from the NFSv4 + * defined ACL model, then this method returns an ACL that is the translation + * of the ACL to the NFSv4 ACL model. + * + * <p> The returned list is modifiable so as to facilitate changes to the + * existing ACL. The {@link #setAcl setAcl} method is used to update + * the file's ACL attribute. + * + * @return An ordered list of {@link AclEntry entries} representing the + * ACL + * + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * In the case of the default provider, a security manager is + * installed, and it denies {@link RuntimePermission}<tt>("accessUserInformation")</tt> + * or its {@link SecurityManager#checkRead(String) checkRead} method + * denies read access to the file. + */ + List<AclEntry> getAcl() throws IOException; + + /** + * Updates (replace) the access control list. + * + * <p> Where the file system supports Access Control Lists, and it uses an + * ACL model that differs from the NFSv4 defined ACL model, then this method + * must translate the ACL to the model supported by the file system. This + * method should reject (by throwing {@link IOException IOException}) any + * attempt to write an ACL that would appear to make the file more secure + * than would be the case if the ACL were updated. Where an implementation + * does not support a mapping of {@link AclEntryType#AUDIT} or {@link + * AclEntryType#ALARM} entries, then this method ignores these entries when + * writing the ACL. + * + * <p> If an ACL entry contains a {@link AclEntry#principal user-principal} + * that is not associated with the same provider as this attribute view then + * {@link ProviderMismatchException} is thrown. Additional validation, if + * any, is implementation dependent. + * + * <p> If the file system supports other security related file attributes + * (such as a file {@link PosixFileAttributes#permissions + * access-permissions} for example), the updating the access control list + * may also cause these security related attributes to be updated. + * + * @param acl + * The new access control list + * + * @throws IOException + * If an I/O error occurs or the ACL is invalid + * @throws SecurityException + * In the case of the default provider, a security manager is + * installed, it denies {@link RuntimePermission}<tt>("accessUserInformation")</tt> + * or its {@link SecurityManager#checkWrite(String) checkWrite} + * method denies write access to the file. + */ + void setAcl(List<AclEntry> acl) throws IOException; +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/AttributeView.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,119 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file.attribute; + +import java.util.*; +import java.io.IOException; + +/** + * An object that provides a read-only or updatable <em>view</em> of non-opaque + * values associated with an object in a filesystem. This interface is extended + * or implemented by specific attribute views that define the attributes + * supported by the view. A specific attribute view will typically define + * type-safe methods to read or update the attributes that it supports. It also + * provides <em>dynamic access</em> where the {@link #readAttributes + * readAttributes}, {@link #getAttribute getAttribute} and {@link #setAttribute + * setAttributs} methods are used to access the attributes by names defined + * by the attribute view. Implementations must ensure that the attribute names + * do not contain the colon (':') or comma (',') characters. + * + * @since 1.7 + */ + +public interface AttributeView { + /** + * Returns the name of the attribute view. + */ + String name(); + + /** + * Reads the value of an attribute. + * + * @param attribute + * The attribute name (case sensitive) + * + * @return The value of the attribute, or {@code null} if the attribute is + * not supported + * + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * If a security manager is set and it denies access + */ + Object getAttribute(String attribute) throws IOException; + + /** + * Sets/updates the value of an attribute. + * + * @param attribute + * The attribute name (case sensitive) + * @param value + * The attribute value + * + * @throws UnsupportedOperationException + * If the attribute is not supported or this attribute view does + * not support updating the value of the attribute + * @throws IllegalArgumentException + * If the attribute value is of the correct type but has an + * inappropriate value + * @throws ClassCastException + * If the attribute value is not of the expected type or is a + * collection containing elements that are not of the expected + * type + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * If a security manager is set and it denies access + */ + void setAttribute(String attribute, Object value) throws IOException; + + /** + * Reads all, or a subset, of the attributes supported by this file attribute + * view. + * + * <p> The {@code first} and {@code rest} parameters are the names of the + * attributes to read. If any of the parameters has the value {@code "*"} + * then all attributes are read. Attributes that are not supported are + * ignored and will not be present in the returned map. It is implementation + * specific if all attributes are read as an atomic operation with respect + * to other file system operations. + * + * @param first + * The name of an attribute to read (case sensitive) + * @param rest + * The names of others attributes to read (case sensitive) + * + * @return An unmodifiable map of the attributes; may be empty. Its keys are + * the attribute names, its values are the attribute values + * + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * If a security manager is set and it denies access + */ + Map<String,?> readAttributes(String first, String... rest) throws IOException; +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/Attributes.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,714 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file.attribute; + +import java.io.IOException; +import java.util.*; +import java.util.concurrent.TimeUnit; + +import org.classpath.icedtea.java.nio.file.FileRef; +import org.classpath.icedtea.java.nio.file.FileStore; +import org.classpath.icedtea.java.nio.file.LinkOption; + +/** + * This class consists exclusively of static methods that operate on or return + * the attributes of files or file stores. These methods provide for convenient + * use of the {@link AttributeView attribute-views} defined in this package. + * + * @since 1.7 + */ + +public final class Attributes { + private Attributes() { + } + + /** + * Splits the given attribute name into the name of an attribute view and + * the attribute. If the attribute view is not identified then it assumed + * to be "basic". + */ + private static String[] split(String attribute) { + String[] s = new String[2]; + int pos = attribute.indexOf(':'); + if (pos == -1) { + s[0] = "basic"; + s[1] = attribute; + } else { + s[0] = attribute.substring(0, pos++); + s[1] = (pos == attribute.length()) ? "" : attribute.substring(pos); + } + return s; + } + + /** + * Sets the value of a file attribute. + * + * <p> The {@code attribute} parameter identifies the attribute to be set + * and takes the form: + * <blockquote> + * [<i>view-name</i><b>:</b>]<i>attribute-name</i> + * </blockquote> + * where square brackets [...] delineate an optional component and the + * character {@code ':'} stands for itself. + * + * <p> <i>view-name</i> is the {@link FileAttributeView#name name} of a {@link + * FileAttributeView} that identifies a set of file attributes. If not + * specified then it defaults to {@code "basic"}, the name of the file + * attribute view that identifies the basic set of file attributes common to + * many file systems. <i>attribute-name</i> is the name of the attribute + * within the set. + * + * <p> <b>Usage Example:</b> + * Suppose we want to set the DOS "hidden" attribute: + * <pre> + * Attributes.setAttribute(file, "dos:hidden", true); + * </pre> + * + * @param file + * A file reference that locates the file + * @param attribute + * The attribute to set + * @param value + * The attribute value + * + * @throws UnsupportedOperationException + * If the attribute view is not available or it does not + * support updating the attribute + * @throws IllegalArgumentException + * If the attribute value is of the correct type but has an + * inappropriate value + * @throws ClassCastException + * If the attribute value is not of the expected type or is a + * collection containing elements that are not of the expected + * type + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * In the case of the default provider, and a security manager is + * installed, its {@link SecurityManager#checkWrite(String) checkWrite} + * method denies write access to the file. If this method is invoked + * to set security sensitive attributes then the security manager + * may be invoked to check for additional permissions. + */ + public static void setAttribute(FileRef file, String attribute, Object value) + throws IOException + { + String[] s = split(attribute); + FileAttributeView view = file.getFileAttributeView(s[0]); + if (view == null) + throw new UnsupportedOperationException("View '" + s[0] + "' not available"); + view.setAttribute(s[1], value); + } + + /** + * Reads the value of a file attribute. + * + * <p> The {@code attribute} parameter identifies the attribute to be read + * and takes the form: + * <blockquote> + * [<i>view-name</i><b>:</b>]<i>attribute-name</i> + * </blockquote> + * where square brackets [...] delineate an optional component and the + * character {@code ':'} stands for itself. + * + * <p> <i>view-name</i> is the {@link FileAttributeView#name name} of a {@link + * FileAttributeView} that identifies a set of file attributes. If not + * specified then it defaults to {@code "basic"}, the name of the file + * attribute view that identifies the basic set of file attributes common to + * many file systems. <i>attribute-name</i> is the name of the attribute. + * + * <p> The {@code options} array may be used to indicate how symbolic links + * are handled for the case that the file is a symbolic link. By default, + * symbolic links are followed and the file attribute of the final target + * of the link is read. If the option {@link LinkOption#NOFOLLOW_LINKS + * NOFOLLOW_LINKS} is present then symbolic links are not followed and so + * the method returns the file attribute of the symbolic link. + * + * <p> <b>Usage Example:</b> + * Suppose we require the user ID of the file owner on a system that + * supports a "{@code unix}" view: + * <pre> + * int uid = (Integer)Attributes.getAttribute(file, "unix:uid"); + * </pre> + * + * @param file + * A file reference that locates the file + * @param attribute + * The attribute to read + * @param options + * Options indicating how symbolic links are handled + * + * @return The attribute value, or {@code null} if the attribute view + * is not available or it does not support reading the attribute + * + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * In the case of the default provider, and a security manager is + * installed, its {@link SecurityManager#checkRead(String) checkRead} + * method denies read access to the file. If this method is invoked + * to read security sensitive attributes then the security manager + * may be invoked to check for additional permissions. + */ + public static Object getAttribute(FileRef file, + String attribute, + LinkOption... options) + throws IOException + { + String[] s = split(attribute); + FileAttributeView view = file.getFileAttributeView(s[0], options); + if (view != null) + return view.getAttribute(s[1]); + // view not available + return null; + } + + /** + * Reads a set of file attributes as a bulk operation. + * + * <p> The {@code attributes} parameter identifies the attributes to be read + * and takes the form: + * <blockquote> + * [<i>view-name</i><b>:</b>]<i>attribute-list</i> + * </blockquote> + * where square brackets [...] delineate an optional component and the + * character {@code ':'} stands for itself. + * + * <p> <i>view-name</i> is the {@link FileAttributeView#name name} of a {@link + * FileAttributeView} that identifies a set of file attributes. If not + * specified then it defaults to {@code "basic"}, the name of the file + * attribute view that identifies the basic set of file attributes common to + * many file systems. + * + * <p> The <i>attribute-list</i> component is a comma separated list of + * zero or more names of attributes to read. If the list contains the value + * {@code "*"} then all attributes are read. Attributes that are not supported + * are ignored and will not be present in the returned map. It is + * implementation specific if all attributes are read as an atomic operation + * with respect to other file system operations. + * + * <p> The following examples demonstrate possible values for the {@code + * attributes} parameter: + * + * <blockquote> + * <table border="0"> + * <tr> + * <td> {@code "*"} </td> + * <td> Read all {@link BasicFileAttributes basic-file-attributes}. </td> + * </tr> + * <tr> + * <td> {@code "size,lastModifiedTime,lastAccessTime"} </td> + * <td> Reads the file size, last modified time, and last access time + * attributes. </td> + * </tr> + * <tr> + * <td> {@code "posix:*"} </td> + * <td> Read all {@link PosixFileAttributes POSIX-file-attributes}.. </td> + * </tr> + * <tr> + * <td> {@code "posix:permissions,owner,size"} </td> + * <td> Reads the POSX file permissions, owner, and file size. </td> + * </tr> + * </table> + * </blockquote> + * + * <p> The {@code options} array may be used to indicate how symbolic links + * are handled for the case that the file is a symbolic link. By default, + * symbolic links are followed and the file attributes of the final target + * of the link are read. If the option {@link LinkOption#NOFOLLOW_LINKS + * NOFOLLOW_LINKS} is present then symbolic links are not followed and so + * the method returns the file attributes of the symbolic link. + * + * @param file + * A file reference that locates the file + * @param attributes + * The attributes to read + * @param options + * Options indicating how symbolic links are handled + * + * @return A map of the attributes returned; may be empty. The map's keys + * are the attribute names, its values are the attribute values + * + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * In the case of the default provider, and a security manager is + * installed, its {@link SecurityManager#checkRead(String) checkRead} + * method denies read access to the file. If this method is invoked + * to read security sensitive attributes then the security manager + * may be invoke to check for additional permissions. + */ + public static Map<String,?> readAttributes(FileRef file, + String attributes, + LinkOption... options) + throws IOException + { + String[] s = split(attributes); + FileAttributeView view = file.getFileAttributeView(s[0], options); + if (view != null) { + // further split attributes into the first and rest. + String[] names = s[1].split(","); + int rem = names.length-1; + String first = names[0]; + String[] rest = new String[rem]; + if (rem > 0) System.arraycopy(names, 1, rest, 0, rem); + + return view.readAttributes(first, rest); + } + // view not available + return Collections.emptyMap(); + } + + /** + * Reads the basic file attributes of a file. + * + * <p> The {@code options} array may be used to indicate how symbolic links + * are handled for the case that the file is a symbolic link. By default, + * symbolic links are followed and the file attributes of the final target + * of the link are read. If the option {@link LinkOption#NOFOLLOW_LINKS + * NOFOLLOW_LINKS} is present then symbolic links are not followed and so + * the method returns the file attributes of the symbolic link. This option + * should be used where there is a need to determine if a file is a + * symbolic link: + * <pre> + * boolean isSymbolicLink = Attributes.readBasicFileAttributes(file, NOFOLLOW_LINKS).isSymbolicLink(); + * </pre> + * + * <p> It is implementation specific if all file attributes are read as an + * atomic operation with respect to other file system operations. + * + * @param file + * A file reference that locates the file + * @param options + * Options indicating how symbolic links are handled + * + * @return The basic file attributes + * + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * In the case of the default provider, the security manager's {@link + * SecurityManager#checkRead(String) checkRead} method is invoked + * to check read access to file + * + * @see BasicFileAttributeView#readAttributes + */ + public static BasicFileAttributes readBasicFileAttributes(FileRef file, + LinkOption... options) + throws IOException + { + return file.getFileAttributeView(BasicFileAttributeView.class, options) + .readAttributes(); + } + + /** + * Reads the POSIX file attributes of a file. + * + * <p> The {@code file} parameter locates a file that supports the {@link + * PosixFileAttributeView}. This file attribute view provides access to a + * subset of the file attributes commonly associated with files on file + * systems used by operating systems that implement the Portable Operating + * System Interface (POSIX) family of standards. It is implementation + * specific if all file attributes are read as an atomic operation with + * respect to other file system operations. + * + * <p> The {@code options} array may be used to indicate how symbolic links + * are handled for the case that the file is a symbolic link. By default, + * symbolic links are followed and the file attributes of the final target + * of the link are read. If the option {@link LinkOption#NOFOLLOW_LINKS + * NOFOLLOW_LINKS} is present then symbolic links are not followed and so + * the method returns the file attributes of the symbolic link. + * + * @param file + * A file reference that locates the file + * @param options + * Options indicating how symbolic links are handled + * + * @return The POSIX file attributes + * + * @throws UnsupportedOperationException + * If the {@code PosixFileAttributeView} is not available + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * In the case of the default provider, and a security manager is + * installed, it denies {@link RuntimePermission}<tt>("accessUserInformation")</tt> + * or its {@link SecurityManager#checkRead(String) checkRead} method + * denies read access to the file. + * + * @see PosixFileAttributeView#readAttributes + */ + public static PosixFileAttributes readPosixFileAttributes(FileRef file, + LinkOption... options) + throws IOException + { + PosixFileAttributeView view = + file.getFileAttributeView(PosixFileAttributeView.class, options); + if (view == null) + throw new UnsupportedOperationException(); + return view.readAttributes(); + } + + /** + * Reads the DOS file attributes of a file. + * + * <p> The {@code file} parameter locates a file that supports the {@link + * DosFileAttributeView}. This file attribute view provides access to + * legacy "DOS" attributes supported by the file systems such as File + * Allocation Table (FAT), commonly used in <em>consumer devices</em>. It is + * implementation specific if all file attributes are read as an atomic + * operation with respect to other file system operations. + * + * <p> The {@code options} array may be used to indicate how symbolic links + * are handled for the case that the file is a symbolic link. By default, + * symbolic links are followed and the file attributes of the final target + * of the link are read. If the option {@link LinkOption#NOFOLLOW_LINKS + * NOFOLLOW_LINKS} is present then symbolic links are not followed and so + * the method returns the file attributes of the symbolic link. + * + * @param file + * A file reference that locates the file + * @param options + * Options indicating how symbolic links are handled + * + * @return The DOS file attributes + * + * @throws UnsupportedOperationException + * If the {@code DosFileAttributeView} is not available + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * In the case of the default provider, the security manager's {@link + * SecurityManager#checkRead(String) checkRead} method is invoked + * to check read access to file + * + * @see DosFileAttributeView#readAttributes + */ + public static DosFileAttributes readDosFileAttributes(FileRef file, + LinkOption... options) + throws IOException + { + DosFileAttributeView view = + file.getFileAttributeView(DosFileAttributeView.class, options); + if (view == null) + throw new UnsupportedOperationException(); + return view.readAttributes(); + } + + /** + * Returns the owner of a file. + * + * <p> The {@code file} parameter locates a file that supports the {@link + * FileOwnerAttributeView}. This file attribute view provides access to + * a file attribute that is the owner of the file. + * + * @param file + * A file reference that locates the file + * + * @return A user principal representing the owner of the file + * + * @throws UnsupportedOperationException + * If the {@code FileOwnerAttributeView} is not available + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * In the case of the default provider, and a security manager is + * installed, it denies {@link RuntimePermission}<tt>("accessUserInformation")</tt> + * or its {@link SecurityManager#checkRead(String) checkRead} method + * denies read access to the file. + * + * @see FileOwnerAttributeView#getOwner + */ + public static UserPrincipal getOwner(FileRef file) throws IOException { + FileOwnerAttributeView view = + file.getFileAttributeView(FileOwnerAttributeView.class); + if (view == null) + throw new UnsupportedOperationException(); + return view.getOwner(); + } + + /** + * Updates the file owner. + * + * <p> The {@code file} parameter locates a file that supports the {@link + * FileOwnerAttributeView}. This file attribute view provides access to + * a file attribute that is the owner of the file. + * + * @param file + * A file reference that locates the file + * @param owner + * The new file owner + * + * @throws UnsupportedOperationException + * If the {@code FileOwnerAttributeView} is not available + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * In the case of the default provider, and a security manager is + * installed, it denies {@link RuntimePermission}<tt>("accessUserInformation")</tt> + * or its {@link SecurityManager#checkWrite(String) checkWrite} + * method denies write access to the file. + * + * @see FileOwnerAttributeView#setOwner + */ + public static void setOwner(FileRef file, UserPrincipal owner) + throws IOException + { + FileOwnerAttributeView view = + file.getFileAttributeView(FileOwnerAttributeView.class); + if (view == null) + throw new UnsupportedOperationException(); + view.setOwner(owner); + } + + /** + * Reads a file's Access Control List (ACL). + * + * <p> The {@code file} parameter locates a file that supports the {@link + * AclFileAttributeView}. This file attribute view provides access to ACLs + * based on the ACL model specified in + * <a href="http://www.ietf.org/rfc/rfc3530.txt"><i>RFC 3530</i></a>. + * + * @param file + * A file reference that locates the file + * + * @return An ordered list of {@link AclEntry entries} representing the + * ACL. The returned list is modifiable. + * + * @throws UnsupportedOperationException + * If the {@code AclAttributeView} is not available + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * In the case of the default provider, and a security manager is + * installed, it denies {@link RuntimePermission}<tt>("accessUserInformation")</tt> + * or its {@link SecurityManager#checkRead(String) checkRead} method + * denies read access to the file. + * + * @see AclFileAttributeView#getAcl + */ + public static List<AclEntry> getAcl(FileRef file) throws IOException { + AclFileAttributeView view = + file.getFileAttributeView(AclFileAttributeView.class); + if (view == null) + throw new UnsupportedOperationException(); + return view.getAcl(); + } + + /** + * Updates a file's Access Control List (ACL). + * + * <p> The {@code file} parameter locates a file that supports the {@link + * AclFileAttributeView}. This file attribute view provides access to ACLs + * based on the ACL model specified in + * <a href="http://www.ietf.org/rfc/rfc3530.txt"><i>RFC 3530</i></a>. + * + * @param file + * A file reference that locates the file + * @param acl + * The new file ACL + * + * @throws UnsupportedOperationException + * If the {@code AclFileAttributeView} is not available + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * In the case of the default provider, and a security manager is + * installed, it denies {@link RuntimePermission}<tt>("accessUserInformation")</tt> + * or its {@link SecurityManager#checkWrite(String) checkWrite} + * method denies write access to the file. + * + * @see AclFileAttributeView#setAcl + */ + public static void setAcl(FileRef file, List<AclEntry> acl) + throws IOException + { + AclFileAttributeView view = + file.getFileAttributeView(AclFileAttributeView.class); + if (view == null) + throw new UnsupportedOperationException(); + view.setAcl(acl); + } + + /** + * Updates the value of a file's last modified time attribute. + * + * <p> The time value is measured since the epoch + * (00:00:00 GMT, January 1, 1970) and is converted to the precision supported + * by the file system. Converting from finer to coarser granularities result + * in precision loss. + * + * <p> If the file system does not support a last modified time attribute then + * this method has no effect. + * + * @param file + * A file reference that locates the file + * + * @param lastModifiedTime + * The new last modified time, or {@code -1L} to update it to + * the current time + * @param unit + * A {@code TimeUnit} determining how to interpret the + * {@code lastModifiedTime} parameter + * + * @throws IllegalArgumentException + * If the {@code lastModifiedime} parameter is a negative value other + * than {@code -1L} + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * In the case of the default provider, the security manager's {@link + * SecurityManager#checkWrite(String) checkWrite} method is invoked + * to check write access to file + * + * @see BasicFileAttributeView#setTimes + */ + public static void setLastModifiedTime(FileRef file, + long lastModifiedTime, + TimeUnit unit) + throws IOException + { + file.getFileAttributeView(BasicFileAttributeView.class) + .setTimes(lastModifiedTime, null, null, unit); + } + + /** + * Updates the value of a file's last access time attribute. + * + * <p> The time value is measured since the epoch + * (00:00:00 GMT, January 1, 1970) and is converted to the precision supported + * by the file system. Converting from finer to coarser granularities result + * in precision loss. + * + * <p> If the file system does not support a last access time attribute then + * this method has no effect. + * + * @param lastAccessTime + * The new last access time, or {@code -1L} to update it to + * the current time + * @param unit + * A {@code TimeUnit} determining how to interpret the + * {@code lastModifiedTime} parameter + * + * @throws IllegalArgumentException + * If the {@code lastAccessTime} parameter is a negative value other + * than {@code -1L} + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * In the case of the default provider, the security manager's {@link + * SecurityManager#checkWrite(String) checkWrite} method is invoked + * to check write access to file + * + * @see BasicFileAttributeView#setTimes + */ + public static void setLastAccessTime(FileRef file, + long lastAccessTime, + TimeUnit unit) + throws IOException + { + file.getFileAttributeView(BasicFileAttributeView.class) + .setTimes(null, lastAccessTime, null, unit); + } + + /** + * Sets a file's POSIX permissions. + * + * <p> The {@code file} parameter is a reference to an existing file. It + * supports the {@link PosixFileAttributeView} that provides access to file + * attributes commonly associated with files on file systems used by + * operating systems that implement the Portable Operating System Interface + * (POSIX) family of standards. + * + * @param file + * A file reference that locates the file + * @param perms + * The new set of permissions + * + * @throws UnsupportedOperationException + * If {@code PosixFileAttributeView} is not available + * @throws ClassCastException + * If the sets contains elements that are not of type {@code + * PosixFilePermission} + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * In the case of the default provider, and a security manager is + * installed, it denies {@link RuntimePermission}<tt>("accessUserInformation")</tt> + * or its {@link SecurityManager#checkWrite(String) checkWrite} + * method denies write access to the file. + * + * @see PosixFileAttributeView#setPermissions + */ + public static void setPosixFilePermissions(FileRef file, + Set<PosixFilePermission> perms) + throws IOException + { + PosixFileAttributeView view = + file.getFileAttributeView(PosixFileAttributeView.class); + if (view == null) + throw new UnsupportedOperationException(); + view.setPermissions(perms); + } + + /** + * Reads the space attributes of a file store. + * + * <p> The {@code store} parameter is a file store that supports the + * {@link FileStoreSpaceAttributeView} providing access to the space related + * attributes of the file store. It is implementation specific if all attributes + * are read as an atomic operation with respect to other file system operations. + * + * @param store + * The file store + * + * @return The file store space attributes + * + * @throws UnsupportedOperationException + * If the file store space attribute view is not supported + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * In the case of the default provider, and a security manager is + * installed, its {@link SecurityManager#checkRead(String) checkRead} + * method is invoked to check read access to the file used to {@link + * FileRef#getFileStore obtain} access to the file + * store, and in addition it checks {@link RuntimePermission}<tt> + * ("getFileStoreAttributes")</tt> + * + * @see FileStoreSpaceAttributeView#readAttributes() + */ + public static FileStoreSpaceAttributes readFileStoreSpaceAttributes(FileStore store) + throws IOException + { + FileStoreSpaceAttributeView view = + store.getFileStoreAttributeView(FileStoreSpaceAttributeView.class); + if (view == null) + throw new UnsupportedOperationException(); + return view.readAttributes(); + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/BasicFileAttributeView.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,185 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file.attribute; + +import java.util.concurrent.TimeUnit; +import java.io.IOException; + +/** + * A file attribute view that provides a view of a <em>basic set</em> of file + * attributes common to many file systems. The basic set of file attributes + * consist of <em>mandatory</em> and <em>optional</em> file attributes as + * defined by the {@link BasicFileAttributes} interface. + + * <p> The file attributes are retrieved from the file system as a <em>bulk + * operation</em> by invoking the {@link #readAttributes() readAttributes} method. + * This class also defines the {@link #setTimes setTimes} method to update the + * file's time attributes. + * + * <p> Where dynamic access to file attributes is required, the attributes + * supported by this attribute view have the following names and types: + * <blockquote> + * <table border="1" cellpadding="8"> + * <tr> + * <th> Name </th> + * <th> Type </th> + * </tr> + * <tr> + * <td> "lastModifiedTime" </td> + * <td> {@link Long} </td> + * </tr> + * <tr> + * <td> "lastAccessTime" </td> + * <td> {@link Long} </td> + * </tr> + * <tr> + * <td> "creationTime" </td> + * <td> {@link Long} </td> + * </tr> + * <tr> + * <td> "resolution" </td> + * <td> {@link java.util.concurrent.TimeUnit} </td> + * </tr> + * <tr> + * <td> "size" </td> + * <td> {@link Long} </td> + * </tr> + * <tr> + * <td> "isRegularFile" </td> + * <td> {@link Boolean} </td> + * </tr> + * <tr> + * <td> "isDirectory" </td> + * <td> {@link Boolean} </td> + * </tr> + * <tr> + * <td> "isSymbolicLink" </td> + * <td> {@link Boolean} </td> + * </tr> + * <tr> + * <td> "isOther" </td> + * <td> {@link Boolean} </td> + * </tr> + * <tr> + * <td> "linkCount" </td> + * <td> {@link Integer} </td> + * </tr> + * <tr> + * <td> "fileKey" </td> + * <td> {@link Object} </td> + * </tr> + * </table> + * </blockquote> + * + * <p> The {@link #getAttribute getAttribute} or {@link + * #readAttributes(String,String[]) readAttributes(String,String[])} methods may + * be used to read any of these attributes as if by invoking the {@link + * #readAttributes() readAttributes()} method. + * + * <p> The {@link #setAttribute setAttribute} method may be used to update the + * file's last modified time, last access time or create time attributes as if + * by invoking the {@link #setTimes setTimes} method. In that case, the time + * value is interpreted in {@link TimeUnit#MILLISECONDS milliseconds} and + * converted to the precision supported by the file system. + * + * @since 1.7 + * @see Attributes + */ + +public interface BasicFileAttributeView + extends FileAttributeView +{ + /** + * Returns the name of the attribute view. Attribute views of this type + * have the name {@code "basic"}. + */ + + String name(); + + /** + * Reads the basic file attributes as a bulk operation. + * + * <p> It is implementation specific if all file attributes are read as an + * atomic operation with respect to other file system operations. + * + * @return The file attributes + * + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * In the case of the default provider, a security manager is + * installed, its {@link SecurityManager#checkRead(String) checkRead} + * method is invoked to check read access to the file + */ + BasicFileAttributes readAttributes() throws IOException; + + /** + * Updates any or all of the file's last modified time, last access time, + * and create time attributes. + * + * <p> This method updates the file's timestamp attributes. The values are + * measured since the epoch (00:00:00 GMT, January 1, 1970) and converted to + * the precision supported by the file system. Converting from finer to + * coarser granularities result in precision loss. + * + * <p> If any of the {@code lastModifiedTime}, {@code lastAccessTime}, + * or {@code createTime} parameters has the value {@code null} then the + * corresponding timestamp is not changed. An implementation may require to + * read the existing values of the file attributes when only some, but not + * all, of the timestamp attributes are updated. Consequently, this method + * may not be an atomic operation with respect to other file system + * operations. If all of the {@code lastModifiedTime}, {@code + * lastAccessTime} and {@code createTime} parameters are {@code null} then + * this method has no effect. + * + * @param lastModifiedTime + * The new last modified time, or {@code -1L} to update it to + * the current time, or {@code null} to not change the attribute + * @param lastAccessTime + * The last access time, or {@code -1L} to update it to + * the current time, or {@code null} to not change the attribute. + * @param createTime + * The file's create time, or {@code -1L} to update it to + * the current time, or {@code null} to not change the attribute + * @param unit + * A {@code TimeUnit} determining how to interpret the time values + * + * @throws IllegalArgumentException + * If any of the parameters is a negative value other than {@code + * -1L} + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * In the case of the default provider, a security manager is + * installed, its {@link SecurityManager#checkWrite(String) checkWrite} + * method is invoked to check write access to the file + */ + void setTimes(Long lastModifiedTime, + Long lastAccessTime, + Long createTime, + TimeUnit unit) throws IOException; +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/BasicFileAttributes.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,164 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file.attribute; + +import java.util.concurrent.TimeUnit; + +/** + * Basic attributes associated with a file in a file system. + * + * <p> Basic file attributes are attributes that are common to many file systems + * and consist of mandatory and optional file attributes as defined by this + * interface. + * + * <p> <b>Usage Example:</b> + * <pre> + * FileRef file = ... + * BasicFileAttributes attrs = Attributes.readBasicFileAttributes(file); + * </pre> + * + * @since 1.7 + * + * @see BasicFileAttributeView + */ + +public interface BasicFileAttributes { + + /** + * Returns the time of last modification. + * + * <p> The {@link #resolution() resolution} method returns the {@link TimeUnit} + * to interpret the return value of this method. + * + * @return A <code>long</code> value representing the time the file was + * last modified since the epoch (00:00:00 GMT, January 1, 1970), + * or {@code -1L} if the attribute is not supported. + */ + long lastModifiedTime(); + + /** + * Returns the time of last access if supported. + * + * <p> The {@link #resolution() resolution} method returns the {@link TimeUnit} + * to interpret the return value of this method. + * + * @return A <code>long</code> value representing the time of last access + * since the epoch (00:00:00 GMT, January 1, 1970), or {@code -1L} + * if the attribute is not supported. + */ + long lastAccessTime(); + + /** + * Returns the creation time if supported. The creation time is the time + * that the file was created. + * + * <p> The {@link #resolution() resolution} method returns the {@link TimeUnit} + * to interpret the return value of this method. + * + * @return A <code>long</code> value representing the time the file was + * created since the epoch (00:00:00 GMT, January 1, 1970), or + * {@code -1L} if the attribute is not supported. + */ + long creationTime(); + + /** + * Returns the {@link TimeUnit} required to interpret the time of last + * modification, time of last access, and creation time. + * + * @return The {@code TimeUnit} required to interpret the file time stamps + */ + TimeUnit resolution(); + + /** + * Tells whether the file is a regular file with opaque content. + */ + boolean isRegularFile(); + + /** + * Tells whether the file is a directory. + */ + boolean isDirectory(); + + /** + * Tells whether the file is a symbolic-link. + */ + boolean isSymbolicLink(); + + /** + * Tells whether the file is something other than a regular file, directory, + * or link. + */ + boolean isOther(); + + /** + * Returns the size of the file (in bytes). The size may differ from the + * actual size on the file system due to compression, support for sparse + * files, or other reasons. The size of files that are not {@link + * #isRegularFile regular} files is implementation specific and + * therefore unspecified. + * + * @return The file size, in bytes + */ + long size(); + + /** + * Returns the number of <em>links</em> to this file. + * + * <p> On file systems where the same file may be in several directories then + * the link count is the number of directory entries for the file. The return + * value is {@code 1} on file systems that only allow a file to have a + * single name in a single directory. + * + * @see java.nio.file.Path#createLink + */ + int linkCount(); + + /** + * Returns an object that uniquely identifies the given file, or {@code + * null} if a file key is not available. On some platforms or file systems + * it is possible to use an identifier, or a combination of identifiers to + * uniquely identify a file. Such identifiers are important for operations + * such as file tree traversal in file systems that support <a + * href="../package-summary.html#links">symbolic links</a> or file systems + * that allow a file to be an entry in more than one directory. On UNIX file + * systems, for example, the <em>device ID</em> and <em>inode</em> are + * commonly used for such purposes. + * + * <p> The file key returned by this method can only be guaranteed to be + * unique if the file system and files remain static. Whether a file system + * re-use identifiers after a file is deleted is implementation dependent and + * therefore unspecified. + * + * <p> File keys returned by this method can be compared for equality and are + * suitable for use in collections. If the file system and files remain static, + * and two files are the {@link java.nio.file.FileRef#isSameFile same} with + * non-{@code null} file keys, then their file keys are equal. + * + * @see java.nio.file.Files#walkFileTree + */ + Object fileKey(); +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/DosFileAttributeView.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,180 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file.attribute; + +import java.io.IOException; + +/** + * A file attribute view that provides a view of the legacy "DOS" file attributes. + * These attributes are supported by file systems such as the File Allocation + * Table (FAT) format commonly used in <em>consumer devices</em>. + * + * <p> A {@code DosFileAttributeView} is a {@link BasicFileAttributeView} that + * additionally supports access to the set of DOS attribute flags that are used + * to indicate if the file is read-only, hidden, a system file, or archived. + * + * <p> Where dynamic access to file attributes is required, the attributes + * supported by this attribute view are as defined by {@code + * BasicFileAttributeView}, and in addition, the following attributes are + * supported: + * <blockquote> + * <table border="1" cellpadding="8"> + * <tr> + * <th> Name </th> + * <th> Type </th> + * </tr> + * <tr> + * <td> readonly </td> + * <td> {@link Boolean} </td> + * </tr> + * <tr> + * <td> hidden </td> + * <td> {@link Boolean} </td> + * </tr> + * <tr> + * <td> system </td> + * <td> {@link Boolean} </td> + * </tr> + * <tr> + * <td> archive </td> + * <td> {@link Boolean} </td> + * </tr> + * </table> + * </blockquote> + * + * <p> The {@link #getAttribute getAttribute} or {@link #readAttributes(String,String[]) + * readAttributes(String,String[])} methods may be used to read any of these + * attributes, or any of the attributes defined by {@link BasicFileAttributeView} + * as if by invoking the {@link #readAttributes readAttributes()} method. + * + * <p> The {@link #setAttribute setAttribute} method may be used to update the + * file's last modified time, last access time or create time attributes as + * defined by {@link BasicFileAttributeView}. It may also be used to update + * the DOS attributes as if by invoking the {@link #setReadOnly setReadOnly}, + * {@link #setHidden setHidden}, {@link #setSystem setSystem}, and {@link + * #setArchive setArchive} methods respectively. + * + * @since 1.7 + */ + +public interface DosFileAttributeView + extends BasicFileAttributeView +{ + /** + * Returns the name of the attribute view. Attribute views of this type + * have the name {@code "dos"}. + */ + + String name(); + + /** + * @throws IOException {@inheritDoc} + * @throws SecurityException {@inheritDoc} + */ + + DosFileAttributes readAttributes() throws IOException; + + /** + * Updates the value of the read-only attribute. + * + * <p> It is implementation specific if the attribute can be updated as an + * atomic operation with respect to other file system operations. An + * implementation may, for example, require to read the existing value of + * the DOS attribute in order to update this attribute. + * + * @param value + * The new value of the attribute + * + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * In the case of the default, and a security manager is installed, + * its {@link SecurityManager#checkWrite(String) checkWrite} method + * is invoked to check write access to the file + */ + void setReadOnly(boolean value) throws IOException; + + /** + * Updates the value of the hidden attribute. + * + * <p> It is implementation specific if the attribute can be updated as an + * atomic operation with respect to other file system operations. An + * implementation may, for example, require to read the existing value of + * the DOS attribute in order to update this attribute. + * + * @param value + * The new value of the attribute + * + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * In the case of the default, and a security manager is installed, + * its {@link SecurityManager#checkWrite(String) checkWrite} method + * is invoked to check write access to the file + */ + void setHidden(boolean value) throws IOException; + + /** + * Updates the value of the system attribute. + * + * <p> It is implementation specific if the attribute can be updated as an + * atomic operation with respect to other file system operations. An + * implementation may, for example, require to read the existing value of + * the DOS attribute in order to update this attribute. + * + * @param value + * The new value of the attribute + * + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * In the case of the default, and a security manager is installed, + * its {@link SecurityManager#checkWrite(String) checkWrite} method + * is invoked to check write access to the file + */ + void setSystem(boolean value) throws IOException; + + /** + * Updates the value of the archive attribute. + * + * <p> It is implementation specific if the attribute can be updated as an + * atomic operation with respect to other file system operations. An + * implementation may, for example, require to read the existing value of + * the DOS attribute in order to update this attribute. + * + * @param value + * The new value of the attribute + * + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * In the case of the default, and a security manager is installed, + * its {@link SecurityManager#checkWrite(String) checkWrite} method + * is invoked to check write access to the file + */ + void setArchive(boolean value) throws IOException; +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/DosFileAttributes.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,85 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file.attribute; + +/** + * File attributes associated with a file in a file system that supports + * legacy "DOS" attributes. + * + * <p> The DOS attributes of a file are retrieved using a {@link + * DosFileAttributeView} by invoking its {@link DosFileAttributeView#readAttributes + * readAttributes} method. + * + * @since 1.7 + * + * @see Attributes#readDosFileAttributes + */ + +public interface DosFileAttributes + extends BasicFileAttributes +{ + /** + * Returns the value of the read-only attribute. + * + * <p> This attribute is often used as a simple access control mechanism + * to prevent files from being deleted or updated. Whether the file system + * or platform does any enforcement to prevent <em>read-only</em> files + * from being updated is implementation specific. + * + * @return The value of the read-only attribute. + */ + boolean isReadOnly(); + + /** + * Returns the value of the hidden attribute. + * + * <p> This attribute is often used to indicate if the file is visible to + * users. + * + * @return The value of the hidden attribute. + */ + boolean isHidden(); + + /** + * Returns the value of the archive attribute. + * + * <p> This attribute is typically used by backup programs. + * + * @return The value of the archive attribute. + */ + boolean isArchive(); + + /** + * Returns the value of the system attribute. + * + * <p> This attribute is often used to indicate that the file is a component + * of the operating system. + * + * @return The value of the system attribute. + */ + boolean isSystem(); +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/FileAttribute.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,51 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file.attribute; + +/** + * An object that encapsulates the value of a file attribute that can be set + * atomically when creating a new file or directory by invoking the {@link + * java.nio.file.Path#createFile createFile} or {@link + * java.nio.file.Path#createDirectory createDirectory} methods. + * + * @param <T> The type of the file attribute value + * + * @since 1.7 + * @see PosixFilePermissions#asFileAttribute + */ + +public interface FileAttribute<T> { + /** + * Returns the attribute name. + */ + String name(); + + /** + * Returns the attribute value. + */ + T value(); +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/FileAttributeView.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,44 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file.attribute; + +/** + * An attribute view that is a read-only or updatable view of non-opaque + * values associated with a file in a filesystem. This interface is extended or + * implemented by specific file attribute views that define methods to read + * and/or update the attributes of a file. + * + * @since 1.7 + * + * @see java.nio.file.FileRef#getFileAttributeView(Class,java.nio.file.LinkOption[]) + * @see java.nio.file.FileRef#getFileAttributeView(String,java.nio.file.LinkOption[]) + */ + +public interface FileAttributeView + extends AttributeView +{ +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/FileOwnerAttributeView.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,102 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file.attribute; + +import java.io.IOException; + +/** + * A file attribute view that supports reading or updating the owner of a file. + * This file attribute view is intended for file system implementations that + * support a file attribute that represents an identity that is the owner of + * the file. Often the owner of a file is the identity of the entity that + * created the file. + * + * <p> The {@link #getOwner getOwner} or {@link #setOwner setOwner} methods may + * be used to read or update the owner of the file. + * + * <p> Where dynamic access to file attributes is required, the owner attribute + * is identified by the name {@code "owner"}, and the value of the attribute is + * a {@link UserPrincipal}. The {@link #readAttributes readAttributes}, {@link + * #getAttribute getAttribute} and {@link #setAttribute setAttributes} methods + * may be used to read or update the file owner. + * + * @since 1.7 + */ + +public interface FileOwnerAttributeView + extends FileAttributeView +{ + /** + * Returns the name of the attribute view. Attribute views of this type + * have the name {@code "owner"}. + */ + + String name(); + + /** + * Read the file owner. + * + * <p> It it implementation specific if the file owner can be a {@link + * GroupPrincipal group}. + * + * @return the file owner + * + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * In the case of the default provider, a security manager is + * installed, and it denies {@link + * RuntimePermission}<tt>("accessUserInformation")</tt> or its + * {@link SecurityManager#checkRead(String) checkRead} method + * denies read access to the file. + */ + UserPrincipal getOwner() throws IOException; + + /** + * Updates the file owner. + * + * <p> It it implementation specific if the file owner can be a {@link + * GroupPrincipal group}. To ensure consistent and correct behavior + * across platforms it is recommended that this method should only be used + * to set the file owner to a user principal that is not a group. + * + * @param owner + * The new file owner + * + * @throws IOException + * If an I/O error occurs, or the {@code owner} parameter is a + * group and this implementation does not support setting the owner + * to a group + * @throws SecurityException + * In the case of the default provider, a security manager is + * installed, and it denies {@link + * RuntimePermission}<tt>("accessUserInformation")</tt> or its + * {@link SecurityManager#checkWrite(String) checkWrite} method + * denies write access to the file. + */ + void setOwner(UserPrincipal owner) throws IOException; +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/FileStoreAttributeView.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,39 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file.attribute; + +/** + * An attribute view that is a read-only or updatable view of the attributes of + * a {@link java.nio.file.FileStore}. + * + * @since 1.7 + */ + +public interface FileStoreAttributeView + extends AttributeView +{ +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/FileStoreSpaceAttributeView.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,94 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file.attribute; + +import java.util.Map; +import java.io.IOException; + +/** + * A file store attribute view that supports reading of space attributes. + * + * <p> Where dynamic access to file attributes is required, the attributes + * supported by this attribute view have the following names and types: + * <blockquote> + * <table border="1" cellpadding="8"> + * <tr> + * <th> Name </th> + * <th> Type </th> + * </tr> + * <tr> + * <td> "totalSpace" </td> + * <td> {@link Long} </td> + * </tr> + * <tr> + * <td> "usableSpace" </td> + * <td> {@link Long} </td> + * </tr> + * <tr> + * <td> "unallocatedSpace" </td> + * <td> {@link Long} </td> + * </tr> + * </table> + * </blockquote> + * <p> The {@link #getAttribute getAttribute} or {@link #readAttributes + * readAttributes(String,String[])} methods may be used to read any of these + * attributes as if by invoking the {@link #readAttributes readAttributes()} + * method. + * + * @since 1.7 + */ + +public interface FileStoreSpaceAttributeView + extends FileStoreAttributeView +{ + /** + * Returns the name of the attribute view. Attribute views of this type + * have the name {@code "space"}. + */ + + String name(); + + /** + * Reads the disk space attributes as a bulk operation. + * + * <p> It is file system specific if all attributes are read as an + * atomic operation with respect to other file system operations. + * + * @return The disk space attributes + * + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * In the case of the default provider, and a security manager is + * installed, its {@link SecurityManager#checkRead(String) checkRead} + * method is invoked to check read access to the file used to {@link + * FileRef#getFileStore obtain} access to the file + * system, and in addition it checks {@link RuntimePermission}<tt> + * ("getFileStoreAttributes")</tt> + */ + FileStoreSpaceAttributes readAttributes() throws IOException; +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/FileStoreSpaceAttributes.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,67 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file.attribute; + +/** + * Space related attributes of a file store. + * + * @since 1.7 + * + * @see Attributes#readFileStoreSpaceAttributes + */ + +public interface FileStoreSpaceAttributes { + /** + * Returns the size, in bytes, of the file store. + */ + long totalSpace(); + + /** + * Returns the number of bytes available to this Java virtual machine on the + * file store. + * + * <p> The returned number of available bytes is a hint, but not a + * guarantee, that it is possible to use most or any of these bytes. The + * number of usable bytes is most likely to be accurate immediately + * after the space attributes are obtained. It is likely to be made inaccurate + * by any external I/O operations including those made on the system outside + * of this Java virtual machine. + */ + long usableSpace(); + + /** + * Returns the number of unallocated bytes in the file store. + * + * <p> The returned number of unallocated bytes is a hint, but not a + * guarantee, that it is possible to use most or any of these bytes. The + * number of unallocated bytes is most likely to be accurate immediately + * after the space attributes are obtained. It is likely to be + * made inaccurate by any external I/O operations including those made on + * the system outside of this virtual machine. + */ + long unallocatedSpace(); +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/GroupPrincipal.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,43 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file.attribute; + +/** + * A {@code UserPrincipal} representing a <em>group identity</em>, used to + * determine access rights to objects in a file system. The exact definition of + * a group is implementation specific, but typically, it represents an identity + * created for administrative purposes so as to determine the access rights for + * the members of the group. Whether an entity can be a member of multiple + * groups, and whether groups can be nested, are implementation specified and + * therefore not specified. + * + * @since 1.7 + * + * @see UserPrincipalLookupService#lookupPrincipalByGroupName + */ + +public interface GroupPrincipal extends UserPrincipal { }
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/NamedAttributeView.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,231 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file.attribute; + +import java.nio.ByteBuffer; +import java.util.List; +import java.io.IOException; + +/** + * A file attribute view that provides a view of a file's user-defined + * attributes, sometimes known as <em>extended attributes</em>. Named attributes + * are used to store metadata with a file that is not meaningful to the file + * system. It is primarily intended for file system implementations that support + * such a capability directly but may be emulated. The details of such emulation + * are highly implementation specific and therefore not specified. + * + * <p> This {@code FileAttributeView} provides a view of a file's named + * attributes as a set of name/value pairs, where the attribute name is + * represented by a {@code String}. An implementation may require to encode and + * decode from the platform or file system representation when accessing the + * attribute. The value has opaque content. This attribute view defines the + * {@link #read read} and {@link #write write} methods to read the value into + * or write from a {@link ByteBuffer}. This {@code FileAttributeView} is not + * intended for use where the size of an attribute value is larger than {@link + * Integer#MAX_VALUE}. + * + * <p> Named attributes may be used in some implementations to store security + * related attributes so consequently, in the case of the default provider at + * least, all methods that access named attributes require the + * {@code RuntimePermission("accessNamedAttributes")} permission when a + * security manager is installed. + * + * <p> The {@link java.nio.file.FileStore#supportsFileAttributeView + * supportsFileAttributeView} method may be used to test if a specific {@link + * java.nio.file.FileStore FileStore} supports the storage of named attributes. + * + * <p> Where dynamic access to file attributes is required, the {@link + * #getAttribute getAttribute} or {@link #readAttributes(String,String[]) + * readAttributes(String,String[])} methods may be used to read the attribute + * value. The attribute value is returned as a byte array (byte[]). The {@link + * #setAttribute setAttribute} method may be used to write the value of a + * user-defined/named attribute from a buffer (as if by invoking the {@link + * #write write} method), or byte array (byte[]). + * + * @since 1.7 + */ + +public interface NamedAttributeView + extends FileAttributeView +{ + /** + * Returns the name of this attribute view. Attribute views of this type + * have the name {@code "xattr"}. + */ + + String name(); + + /** + * Returns a list containing the names of the user-defined/named + * attributes. + * + * @return An unmodifiable list continaing the names of the file's + * user-defined/named attributes + * + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * In the case of the default provider, a security manager is + * installed, and it denies {@link + * RuntimePermission}<tt>("accessNamedAttributes")</tt> + * or its {@link SecurityManager#checkRead(String) checkRead} method + * denies read access to the file. + */ + List<String> list() throws IOException; + + /** + * Returns the size of the value of a user-defined/named attribute. + * + * @param name + * The attribute name + * + * @return The size of the attribute value, in bytes. + * + * @throws ArithmeticException + * If the size of the attribute is larger than {@link Integer#MAX_VALUE} + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * In the case of the default provider, a security manager is + * installed, and it denies {@link + * RuntimePermission}<tt>("accessNamedAttributes")</tt> + * or its {@link SecurityManager#checkRead(String) checkRead} method + * denies read access to the file. + */ + int size(String name) throws IOException; + + /** + * Read the value of a user-defined/named attribute into a buffer. + * + * <p> This method reads the value of the attribute into the given buffer + * as a sequence of bytes, failing if the number of bytes remaining in + * the buffer is insufficient to read the complete attribute value. The + * number of bytes transferred into the buffer is {@code n}, where {@code n} + * is the size of the attribute value. The first byte in the sequence is at + * index {@code p} and the last byte is at index {@code p + n - 1}, where + * {@code p} is the buffer's position. Upon return the buffer's position + * will be equal to {@code p + n}; its limit will not have changed. + * + * <p> <b>Usage Example:</b> + * Suppose we want to read a file's MIME type that is stored as a named + * attribute: + * <pre> + * NamedAttributeView view = file.getFileAttributeView(NamedAttributeView.class); + * String name = "user.mimetype"; + * ByteBuffer buf = ByteBuffer.allocate(view.size(name)); + * view.read(name, buf); + * buf.flip(); + * String value = Charset.defaultCharset().decode(buf).toString(); + * </pre> + * + * @param name + * The attribute name + * @param dst + * The destination buffer + * + * @return The number of bytes read, possibly zero + * + * @throws IllegalArgumentException + * If the destination buffer is read-only + * @throws IOException + * If an I/O error occurs or there is insufficient space in the + * destination buffer for the attribute value + * @throws SecurityException + * In the case of the default provider, a security manager is + * installed, and it denies {@link + * RuntimePermission}<tt>("accessNamedAttributes")</tt> + * or its {@link SecurityManager#checkRead(String) checkRead} method + * denies read access to the file. + * + * @see #size + */ + int read(String name, ByteBuffer dst) throws IOException; + + /** + * Writes the value of a user-defined/named attribute from a buffer. + * + * <p> This method writes the value of the attribute from a given buffer as + * a sequence of bytes. The size of the value to transfer is {@code r}, + * where {@code r} is the number of bytes remaining in the buffer, that is + * {@code src.remaining()}. The sequence of bytes is transferred from the + * buffer starting at index {@code p}, where {@code p} is the buffer's + * position. Upon return, the buffer's position will be equal to {@code + * p + n}, where {@code n} is the number of bytes transferred; its limit + * will not have changed. + * + * <p> If an attribute of the given name already exists then its value is + * replaced. If the attribute does not exist then it is created. If it + * implementation specific if a test to check for the existence of the + * attribute and the creation of attribute are atomic with repect to other + * file system activities. + * + * <p> Where there is insufficient space to store the attribute, or the + * attribute name or value exceed an implementation specific maximum size + * then an {@code IOException} is thrown. + * + * <p> <b>Usage Example:</b> + * Suppose we want to write a file's MIME type as a named attribute: + * <pre> + * NamedAttributeView view = file.getFileAttributeView(NamedAttributeView.class); + * view.write("user.mimetype", Charset.defaultCharset().encode("text/html")); + * </pre> + * + * @param name + * The attribute name + * @param src + * The buffer containing the attribute value + * + * @return The number of bytes written, possibly zero + * + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * In the case of the default provider, a security manager is + * installed, and it denies {@link + * RuntimePermission}<tt>("accessNamedAttributes")</tt> + * or its {@link SecurityManager#checkWrite(String) checkWrite} + * method denies write access to the file. + */ + int write(String name, ByteBuffer src) throws IOException; + + /** + * Deletes a user-defined/named attribute. + * + * @param name + * The attribute name + * + * @throws IOException + * If an I/O error occurs or the attribute does not exist + * @throws SecurityException + * In the case of the default provider, a security manager is + * installed, and it denies {@link + * RuntimePermission}<tt>("accessNamedAttributes")</tt> + * or its {@link SecurityManager#checkWrite(String) checkWrite} + * method denies write access to the file. + */ + void delete(String name) throws IOException; +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/PosixFileAttributeView.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,196 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file.attribute; + +import java.util.Set; +import java.io.IOException; + +/** + * A file attribute view that provides a view of the file attributes commonly + * associated with files on file systems used by operating systems that implement + * the Portable Operating System Interface (POSIX) family of standards. + * + * <p> Operating systems that implement the <a href="http://www.opengroup.org"> + * POSIX</a> family of standards commonly use file systems that have a + * file <em>owner</em>, <em>group-owner</em>, and related <em>access + * permissions</em>. This file attribute view provides read and write access + * to these attributes. + * + * <p> The {@link #readAttributes() readAttributes} method is used to read the + * file's attributes. The file {@link PosixFileAttributes#owner() owner} is + * represented by a {@link UserPrincipal} that is the identity of the file owner + * for the purposes of access control. The {@link PosixFileAttributes#group() + * group-owner}, represented by a {@link GroupPrincipal}, is the identity of the + * group owner, where a group is an identity created for administrative purposes + * so as to determine the access rights for the members of the group. + * + * <p> The {@link PosixFileAttributes#permissions() permissions} attribute is a + * set of access permissions. This file attribute view provides access to the nine + * permission defined by the {@link PosixFilePermission} class. + * These nine permission bits determine the <em>read</em>, <em>write</em>, and + * <em>execute</em> access for the file owner, group, and others (others + * meaning identities other than the owner and members of the group). Some + * operating systems and file systems may provide additional permission bits + * but access to these other bits is not defined by this class in this release. + * + * <p> <b>Usage Example:</b> + * Suppose we need to print out the owner and access permissions of a file: + * <pre> + * FileRef file = ... + * PosixFileAttributes attrs = file.newFileAttributeView(PosixFileAttributeView.class) + * .readAttributes(); + * System.out.format("%s %s%n", + * atts.owner().getName(), + * PosixFilePermissions.toString(attrs.permissions())); + * </pre> + * + * <h4> Dynamic Access </h4> + * <p> Where dynamic access to file attributes is required, the attributes + * supported by this attribute view are as defined by {@link + * BasicFileAttributeView} and {@link FileOwnerAttributeView}, and in addition, + * the following attributes are supported: + * <blockquote> + * <table border="1" cellpadding="8"> + * <tr> + * <th> Name </th> + * <th> Type </th> + * </tr> + * <tr> + * <td> "permissions" </td> + * <td> {@link Set}<{@link PosixFilePermission}> </td> + * </tr> + * <tr> + * <td> "group" </td> + * <td> {@link GroupPrincipal} </td> + * </tr> + * </table> + * </blockquote> + * + * <p> The {@link #getAttribute getAttribute} or {@link + * #readAttributes(String,String[]) readAttributes(String,String[])} methods may + * be used to read any of these attributes, or any of the attributes defined by + * {@link BasicFileAttributeView} as if by invoking the {@link #readAttributes + * readAttributes()} method. + * + * <p> The {@link #setAttribute setAttribute} method may be used to update the + * file's last modified time, last access time or create time attributes as + * defined by {@link BasicFileAttributeView}. It may also be used to update + * the permissions, owner, or group-owner as if by invoking the {@link + * #setPermissions setPermissions}, {@link #setOwner setOwner}, and {@link + * #setGroup setGroup} methods respectively. + * + * <h4> Setting Initial Permissions </h4> + * <p> Implementations supporting this attribute view may also support setting + * the initial permissions when creating a file or directory. The + * initial permissions are provided to the {@link Path#createFile createFile} + * or {@link Path#createDirectory createDirectory} methods as a {@link + * FileAttribute} with {@link FileAttribute#name name} {@code "posix:permissions"} + * and a {@link FileAttribute#value value} that is the set of permissions. The + * following example uses the {@link PosixFilePermissions#asFileAttribute + * asFileAttribute} method to construct a {@code FileAttribute} when creating a + * file: + * + * <pre> + * Path path = ... + * Set<PosixFilePermission> perms = + * EnumSet.of(OWNER_READ, OWNER_WRITE, OWNER_EXECUTE, GROUP_READ); + * path.createFile(PosixFilePermissions.asFileAttribute(perms)); + * </pre> + * + * <p> When the access permissions are set at file creation time then the actual + * value of the permissions may differ that the value of the attribute object. + * The reasons for this are implementation specific. On UNIX systems, for + * example, a process has a <em>umask</em> that impacts the permission bits + * of newly created files. Where an implementation supports the setting of + * the access permissions, and the underlying file system supports access + * permissions, then it is required that the value of the actual access + * permissions will be equal or less than the value of the attribute + * provided to the {@link java.nio.file.Path#createFile createFile} or + * {@link java.nio.file.Path#createDirectory createDirectory} methods. In + * other words, the file may be more secure than requested. + * + * @since 1.7 + * + * @see Attributes#readPosixFileAttributes + */ + +public interface PosixFileAttributeView + extends BasicFileAttributeView, FileOwnerAttributeView +{ + /** + * Returns the name of the attribute view. Attribute views of this type + * have the name {@code "posix"}. + */ + + String name(); + + /** + * @throws IOException {@inheritDoc} + * @throws SecurityException + * In the case of the default provider, a security manager is + * installed, and it denies {@link RuntimePermission}<tt>("accessUserInformation")</tt> + * or its {@link SecurityManager#checkRead(String) checkRead} method + * denies read access to the file. + */ + + PosixFileAttributes readAttributes() throws IOException; + + /** + * Updates the file permissions. + * + * @param perms + * The new set of permissions + * + * @throws ClassCastException + * If the sets contains elements that are not of type {@code + * PosixFilePermission} + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * In the case of the default provider, a security manager is + * installed, and it denies {@link RuntimePermission}<tt>("accessUserInformation")</tt> + * or its {@link SecurityManager#checkWrite(String) checkWrite} + * method denies write access to the file. + */ + void setPermissions(Set<PosixFilePermission> perms) throws IOException; + + /** + * Updates the file group-owner. + * + * @param group + * The new file group-owner + + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * In the case of the default provider, and a security manager is + * installed, it denies {@link RuntimePermission}<tt>("accessUserInformation")</tt> + * or its {@link SecurityManager#checkWrite(String) checkWrite} + * method denies write access to the file. + */ + void setGroup(GroupPrincipal group) throws IOException; +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/PosixFileAttributes.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,78 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file.attribute; + +import java.util.Set; + +/** + * File attributes associated with files on file systems used by operating systems + * that implement the Portable Operating System Interface (POSIX) family of + * standards. + * + * <p> The POSIX attributes of a file are retrieved using a {@link + * PosixFileAttributeView} by invoking its {@link + * PosixFileAttributeView#readAttributes readAttributes} method. + * + * @since 1.7 + * + * @see Attributes#readPosixFileAttributes + */ + +public interface PosixFileAttributes + extends BasicFileAttributes +{ + /** + * Returns the owner of the file. + * + * @return The file owner + * + * @see PosixFileAttributeView#setOwner + */ + UserPrincipal owner(); + + /** + * Returns the group owner of the file. + * + * @return The file group owner + * + * @see PosixFileAttributeView#setGroup + */ + GroupPrincipal group(); + + /** + * Returns the permissions of the file. The file permissions are returned + * as a set of {@link PosixFilePermission} elements. The returned set is a + * copy of the file permissions and is modifiable. This allows the result + * to be modified and passed to the {@link PosixFileAttributeView#setPermissions + * setPermissions} method to update the file's permissions. + * + * @return The file permissions + * + * @see PosixFileAttributeView#setPermissions + */ + Set<PosixFilePermission> permissions(); +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/PosixFilePermission.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,87 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file.attribute; + +import java.util.*; + +/** + * Defines the bits for use with the {@link PosixFileAttributes#permissions() + * permissions} attribute. + * + * <p> The {@link PosixFileAttributes} class defines method methods for + * manipulating {@link Set sets} of permissions. + * + * @since 1.7 + */ + +public enum PosixFilePermission { + + /** + * Read permission, owner. + */ + OWNER_READ, + + /** + * Write permission, owner. + */ + OWNER_WRITE, + + /** + * Execute/search permission, owner. + */ + OWNER_EXECUTE, + + /** + * Read permission, group. + */ + GROUP_READ, + + /** + * Write permission, group. + */ + GROUP_WRITE, + + /** + * Execute/search permission, group. + */ + GROUP_EXECUTE, + + /** + * Read permission, others. + */ + OTHERS_READ, + + /** + * Write permission, others. + */ + OTHERS_WRITE, + + /** + * Execute/search permission, others. + */ + OTHERS_EXECUTE; +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/PosixFilePermissions.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,190 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file.attribute; + +import java.util.*; + +import static org.classpath.icedtea.java.nio.file.attribute.PosixFilePermission.OWNER_READ; +import static org.classpath.icedtea.java.nio.file.attribute.PosixFilePermission.OWNER_WRITE; +import static org.classpath.icedtea.java.nio.file.attribute.PosixFilePermission.OWNER_EXECUTE; +import static org.classpath.icedtea.java.nio.file.attribute.PosixFilePermission.GROUP_READ; +import static org.classpath.icedtea.java.nio.file.attribute.PosixFilePermission.GROUP_WRITE; +import static org.classpath.icedtea.java.nio.file.attribute.PosixFilePermission.GROUP_EXECUTE; +import static org.classpath.icedtea.java.nio.file.attribute.PosixFilePermission.OTHERS_READ; +import static org.classpath.icedtea.java.nio.file.attribute.PosixFilePermission.OTHERS_WRITE; +import static org.classpath.icedtea.java.nio.file.attribute.PosixFilePermission.OTHERS_EXECUTE; + +/** + * This class consists exclusively of static methods that operate on sets of + * {@link PosixFilePermission} objects. + * + * @since 1.7 + */ + +public class PosixFilePermissions { + private PosixFilePermissions() { } + + // Write string representation of permission bits to {@code sb}. + private static void writeBits(StringBuilder sb, boolean r, boolean w, boolean x) { + if (r) { + sb.append('r'); + } else { + sb.append('-'); + } + if (w) { + sb.append('w'); + } else { + sb.append('-'); + } + if (x) { + sb.append('x'); + } else { + sb.append('-'); + } + } + + /** + * Returns the {@code String} representation of a set of permissions. + * + * <p> If the set contains {@code null} or elements that are not of type + * {@code PosixFilePermission} then these elements are ignored. + * + * @param perms + * The set of permissions + * + * @return The string representation of the permission set + * + * @see #fromString + */ + public static String toString(Set<PosixFilePermission> perms) { + StringBuilder sb = new StringBuilder(9); + writeBits(sb, perms.contains(OWNER_READ), perms.contains(OWNER_WRITE), + perms.contains(OWNER_EXECUTE)); + writeBits(sb, perms.contains(GROUP_READ), perms.contains(GROUP_WRITE), + perms.contains(GROUP_EXECUTE)); + writeBits(sb, perms.contains(OTHERS_READ), perms.contains(OTHERS_WRITE), + perms.contains(OTHERS_EXECUTE)); + return sb.toString(); + } + + private static boolean isSet(char c, char setValue) { + if (c == setValue) + return true; + if (c == '-') + return false; + throw new IllegalArgumentException("Invalid mode"); + } + private static boolean isR(char c) { return isSet(c, 'r'); } + private static boolean isW(char c) { return isSet(c, 'w'); } + private static boolean isX(char c) { return isSet(c, 'x'); } + + /** + * Returns the set of permissions corresponding to a given {@code String} + * representation. + * + * <p> The {@code perms} parameter is a {@code String} representing the + * permissions. It has 9 characters that are interpreted as three sets of + * three. The first set refers to the owner's permissions; the next to the + * group permissions and the last to others. Within each set, the first + * character is {@code 'r'} to indicate permission to read, the second + * character is {@code 'w'} to indicate permission to write, and the third + * character is {@code 'x'} for execute permission. Where a permission is + * not set then the corresponding character is set to {@code '-'}. + * + * <p> <b>Usage Example:</b> + * Suppose we require the set of permissions that indicate the owner has read, + * write, and execute permissions, the group has read and execute permissions + * and others have none. + * <pre> + * Set<PosixFilePermission> perms = PosixFilePermissions.fromString("rwxr-x---"); + * </pre> + * + * @param perms + * String representing a set of permissions + * + * @return The resulting set of permissions + * + * @throws IllegalArgumentException + * If the string cannot be converted to a set of permissions + * + * @see #toString(Set) + */ + public static Set<PosixFilePermission> fromString(String perms) { + if (perms.length() != 9) + throw new IllegalArgumentException("Invalid mode"); + Set<PosixFilePermission> result = new HashSet<PosixFilePermission>(); + if (isR(perms.charAt(0))) result.add(OWNER_READ); + if (isW(perms.charAt(1))) result.add(OWNER_WRITE); + if (isX(perms.charAt(2))) result.add(OWNER_EXECUTE); + if (isR(perms.charAt(3))) result.add(GROUP_READ); + if (isW(perms.charAt(4))) result.add(GROUP_WRITE); + if (isX(perms.charAt(5))) result.add(GROUP_EXECUTE); + if (isR(perms.charAt(6))) result.add(OTHERS_READ); + if (isW(perms.charAt(7))) result.add(OTHERS_WRITE); + if (isX(perms.charAt(8))) result.add(OTHERS_EXECUTE); + return result; + } + + /** + * Creates a {@link FileAttribute}, encapsulating a copy of the given file + * permissions, suitable for passing to the {@link java.nio.file.Path#createFile + * createFile} or {@link java.nio.file.Path#createDirectory createDirectory} + * methods. + * + * @param perms + * The set of permissions + * + * @return An attribute encapsulating the given file permissions with + * {@link FileAttribute#name name} {@code "posix:permissions"} + * + * @throws ClassCastException + * If the sets contains elements that are not of type {@code + * PosixFilePermission} + */ + public static FileAttribute<Set<PosixFilePermission>> + asFileAttribute(Set<PosixFilePermission> perms) + { + // copy set and check for nulls (CCE will be thrown if an element is not + // a PosixFilePermission) + perms = new HashSet<PosixFilePermission>(perms); + for (PosixFilePermission p: perms) { + if (p == null) + throw new NullPointerException(); + } + final Set<PosixFilePermission> value = perms; + return new FileAttribute<Set<PosixFilePermission>>() { + + public String name() { + return "posix:permissions"; + } + + public Set<PosixFilePermission> value() { + return Collections.unmodifiableSet(value); + } + }; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/UserPrincipal.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,55 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file.attribute; + +import java.security.Principal; + +/** + * A {@code Principal} representing an identity used to determine access rights + * to objects in a file system. + * + * <p> On many platforms and file systems an entity requires appropriate access + * rights or permissions in order to access objects in a file system. The + * access rights are generally performed by checking the identity of the entity. + * For example, on implementations that use Access Control Lists (ACLs) to + * enforce privilege separation then a file in the file system may have an + * associated ACL that determine the access rights of identities specified in the + * ACL. + * + * <p> A {@code UserPrincipal} object is an abstract representation of an + * identity. It has a {@link #getName() name} that is typically the username or + * account name that it represents. User principal objects may be obtained using + * a {@link UserPrincipalLookupService}, or returned by {@link + * FileAttributeView} implementations that provide access to identity related + * attributes. For example, the {@link AclFileAttributeView} and {@link + * PosixFileAttributeView} provide access to a file's {@link + * PosixFileAttributes#owner owner}. + * + * @since 1.7 + */ + +public interface UserPrincipal extends Principal { }
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/UserPrincipalLookupService.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,105 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file.attribute; + +import java.io.IOException; + +/** + * An object to lookup user and group principals by name. A {@link UserPrincipal} + * represents an identity that may be used to determine access rights to objects + * in a file system. A {@link GroupPrincipal} represents a <em>group identity</em>. + * A {@code UserPrincipalLookupService} defines methods to lookup identities by + * name or group name (which are typically user or account names). Whether names + * and group names are case sensitive or not depends on the implementation. + * The exact definition of a group is implementation specific but typically a + * group represents an identity created for administrative purposes so as to + * determine the access rights for the members of the group. In particular it is + * implementation specific if the <em>namespace</em> for names and groups is the + * same or is distinct. To ensure consistent and correct behavior across + * platforms it is recommended that this API be used as if the namespaces are + * distinct. In other words, the {@link #lookupPrincipalByName + * lookupPrincipalByName} should be used to lookup users, and {@link + * #lookupPrincipalByGroupName lookupPrincipalByGroupName} should be used to + * lookup groups. + * + * @since 1.7 + * + * @see java.nio.file.FileSystem#getUserPrincipalLookupService + */ + +public abstract class UserPrincipalLookupService { + + /** + * Initializes a new instance of this class. + */ + protected UserPrincipalLookupService() { + } + + /** + * Lookup a user principal by name. + * + * @param name + * The string representation of the user principal to lookup + * + * @return A user principal + * + * @throws UserPrincipalNotFoundException + * The principal does not exist + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * In the case of the default provider, and a security manager is + * installed, it checks {@link RuntimePermission}<tt>("lookupUserInformation")</tt> + */ + public abstract UserPrincipal lookupPrincipalByName(String name) + throws IOException; + + /** + * Lookup a group principal by group name. + * + * <p> Where an implementation does not support any notion of group then + * this method always throws {@link UserPrincipalNotFoundException}. Where + * the namespace for user accounts and groups is the same, then this method + * is identical to invoking {@link #lookupPrincipalByName + * lookupPrincipalByName}. + * + * @param group + * The string representation of the group to lookup + * + * @return A user principal. + * + * @throws UserPrincipalNotFoundException + * The principal does not exist or is not a group + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * In the case of the default provider, and a security manager is + * installed, it checks {@link RuntimePermission}<tt>("lookupUserInformation")</tt> + */ + public abstract GroupPrincipal lookupPrincipalByGroupName(String group) + throws IOException; +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/UserPrincipalNotFoundException.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,65 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file.attribute; + +import java.io.IOException; + +/** + * Checked exception thrown when a lookup of {@link UserPrincipal} fails because + * the principal does not exist. + * + * @since 1.7 + */ + +public class UserPrincipalNotFoundException + extends IOException +{ + static final long serialVersionUID = -5369283889045833024L; + + private final String name; + + /** + * Constructs an instance of this class. + * + * @param name + * The principal name; may be {@code null} + */ + public UserPrincipalNotFoundException(String name) { + super(); + this.name = name; + } + + /** + * Returns the user principal name if this exception was created with the + * user principal name that was not found, otherwise <tt>null</tt>. + * + * @return The user principal name or {@code null} + */ + public String getName() { + return name; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/attribute/package-info.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,120 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/** + * Interfaces and classes providing access to file and file system attributes. + * + * <blockquote><table cellspacing=1 cellpadding=0 summary="Attribute views"> + * <tr><th><p align="left">Attribute views</p></th><th><p align="left">Description</p></th></tr> + * <tr><td valign=top><tt><i>{@link org.classpath.icedtea.java.nio.file.attribute.AttributeView}</i></tt></td> + * <td>Can read or update non-opaque values associated with objects in a file system</td></tr> + * <tr><td valign=top><tt> <i>{@link org.classpath.icedtea.java.nio.file.attribute.FileAttributeView}</i></tt></td> + * <td>Can read or update file attributes</td></tr> + * <tr><td valign=top><tt> <i>{@link org.classpath.icedtea.java.nio.file.attribute.BasicFileAttributeView} </i></tt></td> + * <td>Can read or update a basic set of file attributes</td></tr> + * <tr><td valign=top><tt> <i>{@link org.classpath.icedtea.java.nio.file.attribute.PosixFileAttributeView} </i></tt></td> + * <td>Can read or update POSIX defined file attributes</td></tr> + * <tr><td valign=top><tt> <i>{@link org.classpath.icedtea.java.nio.file.attribute.DosFileAttributeView} </i></tt></td> + * <td>Can read or update FAT file attributes</td></tr> + * <tr><td valign=top><tt>  <i>{@link org.classpath.icedtea.java.nio.file.attribute.FileOwnerAttributeView} </i></tt></td> + * <td>Can read or update the owner of a file</td></tr> + * <tr><td valign=top><tt> <i>{@link org.classpath.icedtea.java.nio.file.attribute.AclFileAttributeView} </i></tt></td> + * <td>Can read or update Access Control Lists</td></tr> + * <tr><td valign=top><tt> <i>{@link org.classpath.icedtea.java.nio.file.attribute.NamedAttributeView} </i></tt></td> + * <td>Can read or update Named Attributes</td></tr> + * <tr><td valign=top><tt> <i>{@link org.classpath.icedtea.java.nio.file.attribute.FileStoreAttributeView}</i></tt></td> + * <td>Can read or update file system attributes</td></tr> + * <tr><td valign=top><tt> <i>{@link org.classpath.icedtea.java.nio.file.attribute.FileStoreSpaceAttributeView} </i></tt></td> + * <td>Can read file system <em>space usage</em> related attributes</td></tr> + * </table></blockquote> + * + * <p> An attribute view provides a read-only or updatable view of the non-opaque + * values, or <em>metadata</em>, associated with objects in a file system. + * The {@link org.classpath.icedtea.java.nio.file.attribute.FileAttributeView} interface is + * extended by several other interfaces that that views to specific sets of file + * attributes. {@code FileAttributeViews} are selected by invoking the {@link + * org.classpath.icedtea.java.nio.file.FileRef#getFileAttributeView} method with a + * <em>type-token</em> to identify the required view. Views can also be identified + * by name. The {@link org.classpath.icedtea.java.nio.file.attribute.FileStoreAttributeView} interface + * provides access to file store attributes. A {@code FileStoreAttributeView} of + * a given type is obtained by invoking the {@link + * org.classpath.icedtea.java.nio.file.FileStore#getFileStoreAttributeView} method. + * + * <p> The {@link org.classpath.icedtea.java.nio.file.attribute.BasicFileAttributeView} + * class defines methods to read and update a <em>basic</em> set of file + * attributes that are common to many file systems. + * + * <p> The {@link org.classpath.icedtea.java.nio.file.attribute.PosixFileAttributeView} + * interface extends {@code BasicFileAttributeView} by defining methods + * to access the file attributes commonly used by file systems and operating systems + * that implement the Portable Operating System Interface (POSIX) family of + * standards. + * + * <p> The {@link org.classpath.icedtea.java.nio.file.attribute.DosFileAttributeView} + * class extends {@code BasicFileAttributeView} by defining methods to + * access the legacy "DOS" file attributes supported on file systems such as File + * Allocation Tabl (FAT), commonly used in consumer devices. + * + * <p> The {@link org.classpath.icedtea.java.nio.file.attribute.AclFileAttributeView} + * class defines methods to read and write the Access Control List (ACL) + * file attribute. The ACL model used by this file attribute view is based + * on the model defined by <a href="http://www.ietf.org/rfc/rfc3530.txt"> + * <i>RFC 3530: Network File System (NFS) version 4 Protocol</i></a>. + * + * <p> The {@link org.classpath.icedtea.java.nio.file.attribute.FileStoreSpaceAttributeView} class + * defines methods to read file system space usage related attributes of a file system. + * + * <p> The {@link org.classpath.icedtea.java.nio.file.attribute.Attributes} utility class defines + * static methods to access file or file system attribute using the above + * attribute views. + * + * <p> In addition to attribute views, this package also defines classes and + * interfaces that are used when accessing attributes: + * + * <ul> + * + * <p><li> The {@link org.classpath.icedtea.java.nio.file.attribute.UserPrincipal} and + * {@link org.classpath.icedtea.java.nio.file.attribute.GroupPrincipal} interfaces represent an + * identity or group identity. </li> + * + * <p><li> The {@link org.classpath.icedtea.java.nio.file.attribute.UserPrincipalLookupService} + * interface defines methods to lookup user or group principals. </li> + * + * <p><li> The {@link org.classpath.icedtea.java.nio.file.attribute.Attribute} interface + * represents the value of an attribute for cases where the attribute value is + * require to be set atomically when creating an object in the file system. </li> + * + * </ul> + * + * + * <p> Unless otherwise noted, passing a <tt>null</tt> argument to a constructor + * or method in any class or interface in this package will cause a {@link + * java.lang.NullPointerException NullPointerException} to be thrown. + * + * @since 1.7 + */ + +package org.classpath.icedtea.java.nio.file.attribute;
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/package-info.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,116 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/** + * Define interfaces and classes for the Java virtual machine to access files, + * file attributes, and file systems. + * + * <p> The org.classpath.icedtea.java.nio.file package defines classes to access files and file + * systems. The API to access file and file system attributes is defined in the + * {@link org.classpath.icedtea.java.nio.file.attribute} package. The {@link org.classpath.icedtea.java.nio.file.spi} + * package is used by service provider implementors wishing to extend the + * platform default provider, or to construct other provider implementations. + * + * <a name="links"><h3>Symbolic Links</h3></a> + * Many operating systems and file systems support <em>symbolic links</em>. + * A symbolic link is a special file that serves as a reference to another file. + * For the most part, symbolic links are transparent to applications and + * operations on symbolic links are automatically redirected to the <em>target</em> + * of the link. Exceptions to this are when a symbolic link is deleted or + * renamed/moved in which case the link is deleted or removed rather than the + * target of the link. This package includes support for symbolic links where + * implementations provide these semantics. File systems may support other types + * that are semantically close but support for these other types of links is + * not included in this package. + * + * <a name="interop"><h3>Interoperability</h3></a> + * The {@link org.classpath.icedtea.java.io.File} class defines the {@link org.classpath.icedtea.java.io.File#toPath + * toPath} method to construct a {@link org.classpath.icedtea.java.nio.file.Path} by converting + * the abstract path represented by the {@code org.classpath.icedtea.java.io.File} object. The resulting + * {@code Path} can be used to operate on the same file as the {@code File} + * object. The {@code Path} specification provides further information + * on the <a href="Path.html#interop">interoperability</a> between {@code Path} + * and {@code org.classpath.icedtea.java.io.File} objects. + * + * <h3>Visibility</h3> + * The view of the files and file system provided by classes in this package are + * guaranteed to be consistent with other views provided by other instances in the + * same Java virtual machine. The view may or may not, however, be consistent with + * the view of the file system as seen by other concurrently running programs due + * to caching performed by the underlying operating system and delays induced by + * network-filesystem protocols. This is true regardless of the language in which + * these other programs are written, and whether they are running on the same machine + * or on some other machine. The exact nature of any such inconsistencies are + * system-dependent and are therefore unspecified. + * + * <a name="integrity"><h3>Synchronized I/O File Integrity</h3></a> + * The {@link org.classpath.icedtea.java.nio.file.StandardOpenOption#SYNC SYNC} and {@link + * org.classpath.icedtea.java.nio.file.StandardOpenOption#DSYNC DSYNC} options are used when opening a file + * to require that updates to the file are written synchronously to the underlying + * storage device. In the case of the default provider, and the file resides on + * a local storage device, and the {@link java.nio.channels.SeekableByteChannel + * seekable} channel is connected to a file that was opened with one of these + * options, then an invocation of the {@link + * java.nio.channels.WritableByteChannel#write(java.nio.ByteBuffer) write} + * method is only guaranteed to return when all changes made to the file + * by that invocation have been written to the device. These options are useful + * for ensuring that critical information is not lost in the event of a system + * crash. If the file does not reside on a local device then no such guarantee + * is made. Whether this guarantee is possible with other {@link + * org.classpath.icedtea.java.nio.file.spi.FileSystemProvider provider} implementations is provider + * specific. + * + * <h3>General Exceptions</h3> + * Unless otherwise noted, passing a {@code null} argument to a constructor + * or method of any class or interface in this package will cause a {@link + * java.lang.NullPointerException NullPointerException} to be thrown. Additionally, + * invoking a method with a collection containing a {@code null} element will + * cause a {@code NullPointerException}, unless otherwise specified. + * + * <p> Unless otherwise noted, methods that attempt to access the file system + * will throw {@link org.classpath.icedtea.java.nio.file.ClosedFileSystemException} when invoked on + * objects associated with a {@link org.classpath.icedtea.java.nio.file.FileSystem} that has been + * {@link org.classpath.icedtea.java.nio.file.FileSystem#close closed}. Additionally, any methods + * that attempt write access to a file system will throw {@link + * org.classpath.icedtea.java.nio.file.ReadOnlyFileSystemException} when invoked on an object associated + * with a {@link org.classpath.icedtea.java.nio.file.FileSystem} that only provides read-only access. + * + * <p> Unless otherwise noted, invoking a method of any class or interface in + * this package created by one {@link org.classpath.icedtea.java.nio.file.spi.FileSystemProvider + * provider} with a parameter that is an object created by another provider, + * will throw {@link org.classpath.icedtea.java.nio.file.ProviderMismatchException}. + * + * <h3>Optional Specific Exceptions</h3> + * Most of the methods defined by classes in this package that access the + * file system specify that {@link java.io.IOException} be thrown when an I/O + * error occurs. In some cases, these methods define specific I/O exceptions + * for common cases. These exceptions, noted as <i>optional specific exceptions</i>, + * are thrown by the implementation where it can detect the specific error. + * Where the specific error cannot be detected then the more general {@code + * IOException} is thrown. + * + * @since 1.7 + */ +package org.classpath.icedtea.java.nio.file;
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/spi/AbstractPath.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,542 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file.spi; + +import java.nio.channels.*; +import java.nio.ByteBuffer; +import java.io.*; +import java.util.*; + +import org.classpath.icedtea.java.nio.channels.SeekableByteChannel; + +import org.classpath.icedtea.java.nio.file.AtomicMoveNotSupportedException; +import org.classpath.icedtea.java.nio.file.CopyOption; +import org.classpath.icedtea.java.nio.file.DirectoryStream; +import org.classpath.icedtea.java.nio.file.FileRef; +import org.classpath.icedtea.java.nio.file.LinkOption; +import org.classpath.icedtea.java.nio.file.NoSuchFileException; +import org.classpath.icedtea.java.nio.file.OpenOption; +import org.classpath.icedtea.java.nio.file.Path; +import org.classpath.icedtea.java.nio.file.PathMatcher; +import org.classpath.icedtea.java.nio.file.StandardOpenOption; +import org.classpath.icedtea.java.nio.file.StandardCopyOption; +import org.classpath.icedtea.java.nio.file.WatchEvent; +import org.classpath.icedtea.java.nio.file.WatchKey; +import org.classpath.icedtea.java.nio.file.WatchService; + +import org.classpath.icedtea.java.nio.file.attribute.Attributes; +import org.classpath.icedtea.java.nio.file.attribute.BasicFileAttributes; +import org.classpath.icedtea.java.nio.file.attribute.BasicFileAttributeView; +import org.classpath.icedtea.java.nio.file.attribute.FileAttribute; + +/** + * Base implementation class for a {@code Path}. + * + * <p> This class is intended to be extended by provider implementors. It + * implements, or provides default implementations for several of the methods + * defined by the {@code Path} class. It implements the {@link #copyTo copyTo} + * and {@link #moveTo moveTo} methods for the case that the source and target + * are not associated with the same provider. + * + * @since 1.7 + */ + +public abstract class AbstractPath extends Path { + + /** + * Initializes a new instance of this class. + */ + protected AbstractPath() { } + + /** + * @throws NoSuchFileException {@inheritDoc} + * @throws DirectoryNotEmptyException {@inheritDoc} + * @throws IOException {@inheritDoc} + * @throws SecurityException {@inheritDoc} + */ + + public final void delete() throws IOException { + delete(true); + } + + /** + * @throws IllegalArgumentException {@inheritDoc} + * @throws FileAlreadyExistsException {@inheritDoc} + * @throws IOException {@inheritDoc} + * @throws SecurityException {@inheritDoc} + */ + + public final Path createFile(FileAttribute<?>... attrs) + throws IOException + { + EnumSet<StandardOpenOption> options = + EnumSet.of(StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE); + SeekableByteChannel sbc = newByteChannel(options, attrs); + try { + sbc.close(); + } catch (IOException x) { + // ignore + } + return this; + } + + /** + * @throws IllegalArgumentException {@inheritDoc} + * @throws FileAlreadyExistsException {@inheritDoc} + * @throws IOException {@inheritDoc} + * @throws SecurityException {@inheritDoc} + */ + + public final SeekableByteChannel newByteChannel(OpenOption... options) + throws IOException + { + Set<OpenOption> set = new HashSet<OpenOption>(options.length); + Collections.addAll(set, options); + return newByteChannel(set); + } + + /** + * Opens the file located by this path for reading, returning an input + * stream to read bytes from the file. + * + * <p> This method returns an {@code InputStream} that is constructed by + * invoking the {@link java.nio.channels.Channels#newInputStream + * Channels.newInputStream} method. It may be overridden where a more + * efficient implementation is available. + * + * @throws IOException {@inheritDoc} + * @throws SecurityException {@inheritDoc} + */ + + public InputStream newInputStream() throws IOException { + return Channels.newInputStream(newByteChannel(StandardOpenOption.READ)); + } + + /** + * Opens or creates the file located by this path for writing, returning an + * output stream to write bytes to the file. + * + * <p> This method returns an {@code OutputStream} that is constructed by + * invoking the {@link java.nio.channels.Channels#newOutputStream + * Channels.newOutputStream} method. It may be overridden where a more + * efficient implementation is available. + * + * @throws IllegalArgumentException {@inheritDoc} + * @throws IOException {@inheritDoc} + * @throws SecurityException {@inheritDoc} + */ + + public OutputStream newOutputStream(OpenOption... options) throws IOException { + + int len = options.length; + Set<OpenOption> opts = new HashSet<OpenOption>(len + 3); + if (len == 0) { + opts.add(StandardOpenOption.CREATE); + opts.add(StandardOpenOption.TRUNCATE_EXISTING); + } else { + for (OpenOption opt: options) { + if (opt == StandardOpenOption.READ) + throw new IllegalArgumentException("READ not allowed"); + opts.add(opt); + } + } + opts.add(StandardOpenOption.WRITE); + return Channels.newOutputStream(newByteChannel(opts)); + } + + /** + * Opens or creates the file located by this path for writing, returning an + * output stream to write bytes to the file. + * + * <p> This method returns an {@code OutputStream} that is constructed by + * invoking the {@link java.nio.channels.Channels#newOutputStream + * Channels.newOutputStream} method. It may be overridden where a more + * efficient implementation is available. + * + * @throws IllegalArgumentException {@inheritDoc} + * @throws IOException {@inheritDoc} + * @throws SecurityException {@inheritDoc} + */ + + public OutputStream newOutputStream(Set<? extends OpenOption> options, + FileAttribute<?>... attrs) + throws IOException + { + Set<OpenOption> opts = new HashSet<OpenOption>(options); + if (opts.isEmpty()) { + opts.add(StandardOpenOption.CREATE); + opts.add(StandardOpenOption.TRUNCATE_EXISTING); + } else { + if (opts.contains(StandardOpenOption.READ)) + throw new IllegalArgumentException("READ not allowed"); + } + opts.add(StandardOpenOption.WRITE); + return Channels.newOutputStream(newByteChannel(opts, attrs)); + } + + /** + * @throws NotDirectoryException {@inheritDoc} + * @throws IOException {@inheritDoc} + * @throws SecurityException {@inheritDoc} + */ + + public final DirectoryStream<Path> newDirectoryStream() throws IOException { + return newDirectoryStream(acceptAllFilter); + } + private static final DirectoryStream.Filter<Path> acceptAllFilter = + new DirectoryStream.Filter<Path>() { + public boolean accept(Path entry) { return true; } + }; + + /** + * Opens the directory referenced by this object, returning a {@code + * DirectoryStream} to iterate over the entries in the directory. The + * entries are filtered by matching the {@code String} representation of + * their file names against a given pattern. + * + * <p> This method constructs a {@link PathMatcher} by invoking the + * file system's {@link java.nio.file.FileSystem#getNameMatcher + * getNameMatcher} method. This method may be overridden where a more + * efficient implementation is available. + * + * @throws java.util.regex.PatternSyntaxException {@inheritDoc} + * @throws UnsupportedOperationException {@inheritDoc} + * @throws NotDirectoryException {@inheritDoc} + * @throws IOException {@inheritDoc} + * @throws SecurityException {@inheritDoc} + */ + + public DirectoryStream<Path> newDirectoryStream(String glob) + throws IOException + { + // avoid creating a matcher if all entries are required. + if (glob.equals("*")) + return newDirectoryStream(); + + // create a matcher and return a filter that uses it. + final PathMatcher matcher = getFileSystem().getNameMatcher("glob", glob); + DirectoryStream.Filter<Path> filter = new DirectoryStream.Filter<Path>() { + + public boolean accept(Path entry) { + return matcher.matches(entry.getName()); + } + }; + return newDirectoryStream(filter); + } + + + public final boolean exists() { + try { + checkAccess(); + return true; + } catch (IOException x) { + // unable to determine if file exists + } + return false; + } + + + public final boolean notExists() { + try { + checkAccess(); + return false; + } catch (NoSuchFileException x) { + // file confirmed not to exist + return true; + } catch (IOException x) { + return false; + } + } + + + public final WatchKey register(WatchService watcher, WatchEvent.Kind<?>... events) + throws IOException + { + return register(watcher, events, NO_MODIFIERS); + } + private static final WatchEvent.Modifier[] NO_MODIFIERS = new WatchEvent.Modifier[0]; + + /** + * Copy the file located by this path to a target location. + * + * <p> This method is invoked by the {@link #copyTo copyTo} method for + * the case that this {@code Path} and the target {@code Path} are + * associated with the same provider. + * + * @param target + * The target location + * @param options + * Options specifying how the copy should be done + * + * @throws IllegalArgumentException + * If an invalid option is specified + * @throws FileAlreadyExistsException + * The target file exists and cannot be replaced because the + * {@code REPLACE_EXISTING} option is not specified, or the target + * file is a non-empty directory <i>(optional specific exception)</i> + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * In the case of the default provider, and a security manager is + * installed, the {@link SecurityManager#checkRead(String) checkRead} + * method is invoked to check read access to the source file, the + * {@link SecurityManager#checkWrite(String) checkWrite} is invoked + * to check write access to the target file. If a symbolic link is + * copied the security manager is invoked to check {@link + * LinkPermission}{@code ("symbolic")}. + */ + protected abstract void implCopyTo(Path target, CopyOption... options) + throws IOException; + + /** + * Move the file located by this path to a target location. + * + * <p> This method is invoked by the {@link #moveTo moveTo} method for + * the case that this {@code Path} and the target {@code Path} are + * associated with the same provider. + * + * @param target + * The target location + * @param options + * Options specifying how the move should be done + * + * @throws IllegalArgumentException + * If an invalid option is specified + * @throws FileAlreadyExistsException + * The target file exists and cannot be replaced because the + * {@code REPLACE_EXISTING} option is not specified, or the target + * file is a non-empty directory + * @throws AtomicMoveNotSupportedException + * The options array contains the {@code ATOMIC_MOVE} option but + * the file cannot be moved as an atomic file system operation. + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * In the case of the default provider, and a security manager is + * installed, the {@link SecurityManager#checkWrite(String) checkWrite} + * method is invoked to check write access to both the source and + * target file. + */ + protected abstract void implMoveTo(Path target, CopyOption... options) + throws IOException; + + /** + * Copy the file located by this path to a target location. + * + * <p> If this path is associated with the same {@link FileSystemProvider + * provider} as the {@code target} then the {@link #implCopyTo implCopyTo} + * method is invoked to copy the file. Otherwise, this method attempts to + * copy the file to the target location in a manner that may be less + * efficient than would be the case that target is associated with the same + * provider as this path. + * + * @throws IllegalArgumentException {@inheritDoc} + * @throws FileAlreadyExistsException {@inheritDoc} + * @throws IOException {@inheritDoc} + * @throws SecurityException {@inheritDoc} + */ + + public final Path copyTo(Path target, CopyOption... options) + throws IOException + { + if ((getFileSystem().provider() == target.getFileSystem().provider())) { + implCopyTo(target, options); + } else { + xProviderCopyTo(target, options); + } + return target; + } + + /** + * Move or rename the file located by this path to a target location. + * + * <p> If this path is associated with the same {@link FileSystemProvider + * provider} as the {@code target} then the {@link #implCopyTo implMoveTo} + * method is invoked to move the file. Otherwise, this method attempts to + * copy the file to the target location and delete the source file. This + * implementation may be less efficient than would be the case that + * target is associated with the same provider as this path. + * + * @throws IllegalArgumentException {@inheritDoc} + * @throws FileAlreadyExistsException {@inheritDoc} + * @throws IOException {@inheritDoc} + * @throws SecurityException {@inheritDoc} + */ + + public final Path moveTo(Path target, CopyOption... options) + throws IOException + { + if ((getFileSystem().provider() == target.getFileSystem().provider())) { + implMoveTo(target, options); + } else { + // different providers so copy + delete + xProviderCopyTo(target, convertMoveToCopyOptions(options)); + delete(false); + } + return target; + } + + /** + * Converts the given array of options for moving a file to options suitable + * for copying the file when a move is implemented as copy + delete. + */ + private static CopyOption[] convertMoveToCopyOptions(CopyOption... options) + throws AtomicMoveNotSupportedException + { + int len = options.length; + CopyOption[] newOptions = new CopyOption[len+2]; + for (int i=0; i<len; i++) { + CopyOption option = options[i]; + if (option == StandardCopyOption.ATOMIC_MOVE) { + throw new AtomicMoveNotSupportedException(null, null, + "Atomic move between providers is not supported"); + } + newOptions[i] = option; + } + newOptions[len] = LinkOption.NOFOLLOW_LINKS; + newOptions[len+1] = StandardCopyOption.COPY_ATTRIBUTES; + return newOptions; + } + + /** + * Parses the arguments for a file copy operation. + */ + private static class CopyOptions { + boolean replaceExisting = false; + boolean copyAttributes = false; + boolean followLinks = true; + + private CopyOptions() { } + + static CopyOptions parse(CopyOption... options) { + CopyOptions result = new CopyOptions(); + for (CopyOption option: options) { + if (option == StandardCopyOption.REPLACE_EXISTING) { + result.replaceExisting = true; + continue; + } + if (option == LinkOption.NOFOLLOW_LINKS) { + result.followLinks = false; + continue; + } + if (option == StandardCopyOption.COPY_ATTRIBUTES) { + result.copyAttributes = true; + continue; + } + if (option == null) + throw new NullPointerException(); + throw new IllegalArgumentException("'" + option + + "' is not a valid copy option"); + } + return result; + } + } + + /** + * Simple cross-provider copy where the target is a Path. + */ + private void xProviderCopyTo(Path target, CopyOption... options) + throws IOException + { + CopyOptions opts = CopyOptions.parse(options); + LinkOption[] linkOptions = (opts.followLinks) ? new LinkOption[0] : + new LinkOption[] { LinkOption.NOFOLLOW_LINKS }; + + // attributes of source file + BasicFileAttributes attrs = Attributes + .readBasicFileAttributes(this, linkOptions); + if (attrs.isSymbolicLink()) + throw new IOException("Copying of symbolic links not supported"); + + // delete target file + if (opts.replaceExisting) + target.delete(false); + + // create directory or file + if (attrs.isDirectory()) { + target.createDirectory(); + } else { + target.createFile(); + xProviderCopyRegularFileTo(target); + } + + // copy basic attributes to target + if (opts.copyAttributes) { + BasicFileAttributeView view = target + .getFileAttributeView(BasicFileAttributeView.class, linkOptions); + try { + view.setTimes(attrs.lastModifiedTime(), + attrs.lastAccessTime(), + attrs.creationTime(), + attrs.resolution()); + } catch (IOException x) { + // rollback + try { + target.delete(false); + } catch (IOException ignore) { } + throw x; + } + } + } + + + /** + * Simple copy of regular file to a target file that exists. + */ + private void xProviderCopyRegularFileTo(FileRef target) + throws IOException + { + ReadableByteChannel rbc = newByteChannel(); + try { + // open target file for writing + SeekableByteChannel sbc = target + .newByteChannel(StandardOpenOption.WRITE); + + // simple copy loop + try { + ByteBuffer buf = ByteBuffer.wrap(new byte[8192]); + int n = 0; + for (;;) { + n = rbc.read(buf); + if (n < 0) + break; + assert n > 0; + buf.flip(); + while (buf.hasRemaining()) { + sbc.write(buf); + } + buf.rewind(); + } + + } finally { + sbc.close(); + } + } finally { + rbc.close(); + } + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/spi/FileSystemProvider.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,441 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file.spi; + +import java.net.URI; +import java.util.*; +import java.util.concurrent.ExecutorService; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.io.IOException; + +import org.classpath.icedtea.java.nio.channels.AsynchronousFileChannel; +import org.classpath.icedtea.java.nio.channels.FileChannel; +import org.classpath.icedtea.java.nio.file.FileRef; +import org.classpath.icedtea.java.nio.file.FileSystem; +import org.classpath.icedtea.java.nio.file.FileSystems; +import org.classpath.icedtea.java.nio.file.OpenOption; +import org.classpath.icedtea.java.nio.file.Path; +import org.classpath.icedtea.java.nio.file.attribute.FileAttribute; + +/** + * Service-provider class for file systems. + * + * <p> A file system provider is a concrete implementation of this class that + * implements the abstract methods defined by this class. A provider is + * identified by a {@code URI} {@link #getScheme() scheme}. The default provider + * is identified by the URI scheme "file". It creates the {@link FileSystem} that + * provides access to the file systems accessible to the Java virtual machine. + * The {@link FileSystems} class defines how file system providers are located + * and loaded. The default provider is typically a system-default provider but + * may be overridden if the system property {@code + * java.nio.file.spi.DefaultFileSystemProvider} is set. In that case, the + * provider has a one argument constructor whose formal parameter type is {@code + * FileSystemProvider}. All other providers have a zero argument constructor + * that initializes the provider. + * + * <p> A provider is a factory for one or more {@link FileSystem} instances. Each + * file system is identified by a {@code URI} where the URI's scheme matches + * the provider's {@link #getScheme scheme}. The default file system, for example, + * is identified by the URI {@code "file:///"}. A memory-based file system, + * for example, may be identified by a URI such as {@code "memory:///?name=logfs"}. + * The {@link #newFileSystem newFileSystem} method may be used to create a file + * system, and the {@link #getFileSystem getFileSystem} method may be used to + * obtain a reference to an existing file system created by the provider. Where + * a provider is the factory for a single file system then it is provider dependent + * if the file system is created when the provider is initialized, or later when + * the {@code newFileSystem} method is invoked. In the case of the default + * provider, the {@code FileSystem} is created when the provider is initialized. + * + * <p> In addition to file systems, a provider is also a factory for {@link + * FileChannel} and {@link AsynchronousFileChannel} channels. The {@link + * #newFileChannel newFileChannel} and {@link #newAsynchronousFileChannel + * AsynchronousFileChannel} methods are defined to open or create files, returning + * a channel to access the file. These methods are invoked by static factory + * methods defined in the {@link java.nio.channels} package. + * + * <p> All of the methods in this class are safe for use by multiple concurrent + * threads. + * + * @since 1.7 + */ + +public abstract class FileSystemProvider { + // lock using when loading providers + private static final Object lock = new Object(); + + // installed providers + private static volatile List<FileSystemProvider> installedProviders; + + // used to avoid recursive loading of instaled providers + private static boolean loadingProviders = false; + + private static Void checkPermission() { + SecurityManager sm = System.getSecurityManager(); + if (sm != null) + sm.checkPermission(new RuntimePermission("fileSystemProvider")); + return null; + } + private FileSystemProvider(Void ignore) { } + + /** + * Initializes a new instance of this class. + * + * <p> During construction a provider may safely access files associated + * with the default provider but care needs to be taken to avoid circular + * loading of other installed providers. If circular loading of installed + * providers is detected then an unspecified error is thrown. + * + * @throws SecurityException + * If a security manager has been installed and it denies + * {@link RuntimePermission}<tt>("fileSystemProvider")</tt> + */ + protected FileSystemProvider() { + this(checkPermission()); + } + + // loads all installed providers + private static List<FileSystemProvider> loadInstalledProviders() { + List<FileSystemProvider> list = new ArrayList<FileSystemProvider>(); + + ServiceLoader<FileSystemProvider> sl = ServiceLoader + .load(FileSystemProvider.class, ClassLoader.getSystemClassLoader()); + + // ServiceConfigurationError may be throw here + for (FileSystemProvider provider: sl) { + String scheme = provider.getScheme(); + + // add to list if the provider is not "file" and isn't a duplicate + if (!scheme.equalsIgnoreCase("file")) { + boolean found = false; + for (FileSystemProvider p: list) { + if (p.getScheme().equalsIgnoreCase(scheme)) { + found = true; + break; + } + } + if (!found) { + list.add(provider); + } + } + } + return list; + } + + /** + * Returns a list of the installed file system providers. + * + * <p> The first invocation of this method causes the default provider to be + * initialized (if not already initialized) and loads any other installed + * providers as described by the {@link FileSystems} class. + * + * @return An unmodifiable list of the installed file system providers. The + * list contains at least one element, that is the default file + * system provider + * + * @throws ServiceConfigurationError + * When an error occurs while loading a service provider + */ + public static List<FileSystemProvider> installedProviders() { + if (installedProviders == null) { + // ensure default provider is initialized + FileSystemProvider defaultProvider = FileSystems.getDefault().provider(); + + synchronized (lock) { + if (installedProviders == null) { + if (loadingProviders) { + throw new Error("Circular loading of installed providers detected"); + } + loadingProviders = true; + + List<FileSystemProvider> list = AccessController + .doPrivileged(new PrivilegedAction<List<FileSystemProvider>>() { + + public List<FileSystemProvider> run() { + return loadInstalledProviders(); + }}); + + // insert the default provider at the start of the list + list.add(0, defaultProvider); + + installedProviders = Collections.unmodifiableList(list); + } + } + } + return installedProviders; + } + + /** + * Returns the URI scheme that identifies this provider. + * + * @return The URI scheme + */ + public abstract String getScheme(); + + /** + * Constructs a new {@code FileSystem} object identified by a URI. This + * method is invoked by the {@link FileSystems#newFileSystem(URI,Map)} + * method to open a new file system identified by a URI. + * + * <p> The {@code uri} parameter is an absolute, hierarchical URI, with a + * scheme equal (without regard to case) to the scheme supported by this + * provider. The exact form of the URI is highly provider dependent. The + * {@code env} parameter is a map of provider specific properties to configure + * the file system. + * + * <p> This method throws {@link FileSystemAlreadyExistsException} if the + * file system already exists because it was previously created by an + * invocation of this method. Once a file system is {@link FileSystem#close + * closed} it is provider-dependent if the provider allows a new file system + * to be created with the same URI as a file system it previously created. + * + * @param uri + * URI reference + * @param env + * A map of provider specific properties to configure the file system; + * may be empty + * + * @return A new file system + * + * @throws IllegalArgumentException + * If the pre-conditions for the {@code uri} parameter aren't met, + * or the {@code env} parameter does not contain properties required + * by the provider, or a property value is invalid + * @throws IOException + * An I/O error occurs creating the file system + * @throws SecurityException + * If a security manager is installed and it denies an unspecified + * permission required by the file system provider implementation + * @throws FileSystemAlreadyExistsException + * If the file system has already been created + */ + public abstract FileSystem newFileSystem(URI uri, Map<String,?> env) + throws IOException; + + /** + * Returns an existing {@code FileSystem} created by this provider. + * + * <p> This method returns a reference to a {@code FileSystem} that was + * created by invoking the {@link #newFileSystem(URI,Map) newFileSystem(URI,Map)} + * method. File systems created the {@link #newFileSystem(FileRef,Map) + * newFileSystem(FileRef,Map)} method are not returned by this method. + * The file system is identified by its {@code URI}. Its exact form + * is highly provider dependent. In the case of the default provider the URI's + * path component is {@code "/"} and the authority, query and fragment components + * are undefined (Undefined components are represented by {@code null}). + * + * <p> Once a file system created by this provider is {@link FileSystem#close + * closed} it is provider-dependent if this method returns a reference to + * the closed file system or throws {@link FileSystemNotFoundException}. + * If the provider allows a new file system to be created with the same URI + * as a file system it previously created then this method throws the + * exception if invoked after the file system is closed (and before a new + * instance is created by the {@link #newFileSystem newFileSystem} method). + * + * <p> If a security manager is installed then a provider implementation + * may require to check a permission before returning a reference to an + * existing file system. In the case of the {@link FileSystems#getDefault + * default} file system, no permission check is required. + * + * @param uri + * URI reference + * + * @return The file system + * + * @throws IllegalArgumentException + * If the pre-conditions for the {@code uri} parameter aren't met + * @throws FileSystemNotFoundException + * If the file system does not exist + * @throws SecurityException + * If a security manager is installed and it denies an unspecified + * permission. + */ + public abstract FileSystem getFileSystem(URI uri); + + /** + * Return a {@code Path} object by converting the given {@link URI}. + * + * <p> The exact form of the URI is file system provider dependent. In the + * case of the default provider, the URI scheme is {@code "file"} and the + * given URI has a non-empty path component, and undefined query, and + * fragment components. The resulting {@code Path} is associated with the + * default {@link FileSystems#getDefault default} {@code FileSystem}. + * + * <p> If a security manager is installed then a provider implementation + * may require to check a permission. In the case of the {@link + * FileSystems#getDefault default} file system, no permission check is + * required. + * + * @param uri + * The URI to convert + * + * @throws IllegalArgumentException + * If the URI scheme does not identify this provider or other + * preconditions on the uri parameter do not hold + * @throws FileSystemNotFoundException + * The file system, identified by the URI, does not exist + * @throws SecurityException + * If a security manager is installed and it denies an unspecified + * permission. + */ + public abstract Path getPath(URI uri); + + /** + * Constructs a new {@code FileSystem} to access the contents of a file as a + * file system. + * + * <p> This method is intended for specialized providers of pseudo file + * systems where the contents of one or more files is treated as a file + * system. The {@code file} parameter is a reference to an existing file + * and the {@code env} parameter is a map of provider specific properties to + * configure the file system. + * + * <p> If this provider does not support the creation of such file systems + * or if the provider does not recognize the file type of the given file then + * it throws {@code UnsupportedOperationException}. The default implementation + * of this method throws {@code UnsupportedOperationException}. + * + * @param file + * The file + * @param env + * A map of provider specific properties to configure the file system; + * may be empty + * + * @return A new file system + * + * @throws UnsupportedOperationException + * If this provider does not support access to the contents as a + * file system or it does not recognize the file type of the + * given file + * @throws IllegalArgumentException + * If the {@code env} parameter does not contain properties required + * by the provider, or a property value is invalid + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * If a security manager is installed and it denies an unspecified + * permission. + */ + public FileSystem newFileSystem(FileRef file, Map<String,?> env) + throws IOException + { + throw new UnsupportedOperationException(); + } + + /** + * Opens or creates a file for reading and/or writing, returning a file + * channel to access the file. + * + * <p> This method is invoked by the {@link FileChannel#open(Path,Set,FileAttribute[]) + * FileChannel.open} method to open a file channel. A provider that does not + * support all the features required to construct a file channel throws + * {@code UnsupportedOperationException}. The default provider is required + * to support the creation of file channels. When not overridden, the + * default implementation throws {@code UnsupportedOperationException}. + * + * @param path + * The path of the file to open or create + * @param options + * Options specifying how the file is opened + * @param attrs + * An optional list of file attributes to set atomically when + * creating the file + * + * @return A new file channel + * + * @throws IllegalArgumentException + * If the set contains an invalid combination of options + * @throws UnsupportedOperationException + * If this provider that does not support creating file channels, + * or an unsupported open option or file attribute is specified + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * In the case of the default file system, the {@link + * SecurityManager#checkRead(String)} method is invoked to check + * read access if the file is opened for reading. The {@link + * SecurityManager#checkWrite(String)} method is invoked to check + * write access if the file is opened for writing + */ + public FileChannel newFileChannel(Path path, + Set<? extends OpenOption> options, + FileAttribute<?>... attrs) + throws IOException + { + throw new UnsupportedOperationException(); + } + + /** + * Opens or creates a file for reading and/or writing, returning an + * asynchronous file channel to access the file. + * + * <p> This method is invoked by the {@link + * AsynchronousFileChannel#open(Path,Set,ExecutorService,FileAttribute[]) + * AsynchronousFileChannel.open} method to open an asynchronous file channel. + * A provider that does not support all the features required to construct + * an asynchronous file channel throws {@code UnsupportedOperationException}. + * The default provider is required to support the creation of asynchronous + * file channels. When not overridden, the default implementation of this + * method throws {@code UnsupportedOperationException}. + * + * @param path + * The path of the file to open or create + * @param options + * Options specifying how the file is opened + * @param executor + * The thread pool or {@code null} to associate the channel with + * the default thread pool + * @param attrs + * An optional list of file attributes to set atomically when + * creating the file + * + * @return A new asynchronous file channel + * + * @throws IllegalArgumentException + * If the set contains an invalid combination of options + * @throws UnsupportedOperationException + * If this provider that does not support creating asynchronous file + * channels, or an unsupported open option or file attribute is + * specified + * @throws IOException + * If an I/O error occurs + * @throws SecurityException + * In the case of the default file system, the {@link + * SecurityManager#checkRead(String)} method is invoked to check + * read access if the file is opened for reading. The {@link + * SecurityManager#checkWrite(String)} method is invoked to check + * write access if the file is opened for writing + */ + public AsynchronousFileChannel newAsynchronousFileChannel(Path path, + Set<? extends OpenOption> options, + ExecutorService executor, + FileAttribute<?>... attrs) + throws IOException + { + throw new UnsupportedOperationException(); + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/spi/FileTypeDetector.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,102 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.nio.file.spi; + +import java.io.IOException; + +import org.classpath.icedtea.java.nio.file.FileRef; + +/** + * A file type detector for probing a file to guess its file type. + * + * <p> A file type detector is a concrete implementation of this class, has a + * zero-argument constructor, and implements the abstract methods specified + * below. + * + * <p> The means by which a file type detector determines the file type is + * highly implementation specific. A simple implementation might examine the + * <em>file extension</em> (a convention used in some platforms) and map it to + * a file type. In other cases, the file type may be stored as a file <a + * href="../attribute/package-summary.html"> attribute</a> or the bytes in a + * file may be examined to guess its file type. + * + * @see java.nio.file.Files#probeContentType(FileRef) + * + * @since 1.7 + */ + +public abstract class FileTypeDetector { + + /** + * Initializes a new instance of this class. + * + * @throws SecurityException + * If a security manager has been installed and it denies + * {@link RuntimePermission}<tt>("fileTypeDetector")</tt> + */ + protected FileTypeDetector() { + SecurityManager sm = System.getSecurityManager(); + if (sm != null) + sm.checkPermission(new RuntimePermission("fileTypeDetector")); + } + + /** + * Probes the given file to guess its content type. + * + * <p> The means by which this method determines the file type is highly + * implementation specific. It may simply examine the file name, it may use + * a file <a href="../attribute/package-summary.html">attribute</a>, + * or it may examines bytes in the file. + * + * <p> The probe result is the string form of the value of a + * Multipurpose Internet Mail Extension (MIME) content type as + * defined by <a href="http://www.ietf.org/rfc/rfc2045.txt"><i>RFC 2045: + * Multipurpose Internet Mail Extensions (MIME) Part One: Format of Internet + * Message Bodies</i></a>. The string must be parsable according to the + * grammar in the RFC 2045. + * + * @param file + * The file to probe + * + * @return The content type or {@code null} if the file type is not + * recognized + * + * @throws IOException + * An I/O error occurs + * @throws SecurityException + * If the implementation requires to access the file, and a + * security manager is installed, and it denies an unspecified + * permission required by a file system provider implementation. + * If the file reference is associated with the default file system + * provider then the {@link SecurityManager#checkRead(String)} method + * is invoked to check read access to the file. + * + * @see java.nio.file.Files#probeContentType + */ + public abstract String probeContentType(FileRef file) + throws IOException; +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/nio/file/spi/package-info.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,39 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/** + * Service-provider classes for the <tt>{@link org.classpath.icedtea.java.nio.file}</tt> package. + * + * <p> Only developers who are defining new file system providers or file type + * detectors should need to make direct use of this package. </p> + * + * <p> Unless otherwise noted, passing a <tt>null</tt> argument to a constructor + * or method in any class or interface in this package will cause a {@link + * java.lang.NullPointerException NullPointerException} to be thrown. + * + * @since 1.7 + */ + +package org.classpath.icedtea.java.nio.file.spi;
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/util/Scanner.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,2657 @@ +/* + * Copyright 2003-2006 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Red Hat, Inc. + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package org.classpath.icedtea.java.util; + +import java.util.regex.*; +import java.io.*; +import java.math.*; +import java.nio.*; +import java.nio.channels.*; +import java.nio.charset.*; +import java.text.*; +import java.util.InputMismatchException; +import java.util.Iterator; +import java.util.Locale; +import java.util.NoSuchElementException; +import sun.misc.LRUCache; + +import org.classpath.icedtea.java.nio.file.FileRef; + +/** + * A simple text scanner which can parse primitive types and strings using + * regular expressions. + * + * <p>A <code>Scanner</code> breaks its input into tokens using a + * delimiter pattern, which by default matches whitespace. The resulting + * tokens may then be converted into values of different types using the + * various <tt>next</tt> methods. + * + * <p>For example, this code allows a user to read a number from + * <tt>System.in</tt>: + * <blockquote><pre> + * Scanner sc = new Scanner(System.in); + * int i = sc.nextInt(); + * </pre></blockquote> + * + * <p>As another example, this code allows <code>long</code> types to be + * assigned from entries in a file <code>myNumbers</code>: + * <blockquote><pre> + * Scanner sc = new Scanner(new File("myNumbers")); + * while (sc.hasNextLong()) { + * long aLong = sc.nextLong(); + * }</pre></blockquote> + * + * <p>The scanner can also use delimiters other than whitespace. This + * example reads several items in from a string: + *<blockquote><pre> + * String input = "1 fish 2 fish red fish blue fish"; + * Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*"); + * System.out.println(s.nextInt()); + * System.out.println(s.nextInt()); + * System.out.println(s.next()); + * System.out.println(s.next()); + * s.close(); </pre></blockquote> + * <p> + * prints the following output: + * <blockquote><pre> + * 1 + * 2 + * red + * blue </pre></blockquote> + * + * <p>The same output can be generated with this code, which uses a regular + * expression to parse all four tokens at once: + *<blockquote><pre> + * String input = "1 fish 2 fish red fish blue fish"; + * Scanner s = new Scanner(input); + * s.findInLine("(\\d+) fish (\\d+) fish (\\w+) fish (\\w+)"); + * MatchResult result = s.match(); + * for (int i=1; i<=result.groupCount(); i++) + * System.out.println(result.group(i)); + * s.close(); </pre></blockquote> + * + * <p>The <a name="default-delimiter">default whitespace delimiter</a> used + * by a scanner is as recognized by {@link java.lang.Character}.{@link + * java.lang.Character#isWhitespace(char) isWhitespace}. The {@link #reset} + * method will reset the value of the scanner's delimiter to the default + * whitespace delimiter regardless of whether it was previously changed. + * + * <p>A scanning operation may block waiting for input. + * + * <p>The {@link #next} and {@link #hasNext} methods and their + * primitive-type companion methods (such as {@link #nextInt} and + * {@link #hasNextInt}) first skip any input that matches the delimiter + * pattern, and then attempt to return the next token. Both <tt>hasNext</tt> + * and <tt>next</tt> methods may block waiting for further input. Whether a + * <tt>hasNext</tt> method blocks has no connection to whether or not its + * associated <tt>next</tt> method will block. + * + * <p> The {@link #findInLine}, {@link #findWithinHorizon}, and {@link #skip} + * methods operate independently of the delimiter pattern. These methods will + * attempt to match the specified pattern with no regard to delimiters in the + * input and thus can be used in special circumstances where delimiters are + * not relevant. These methods may block waiting for more input. + * + * <p>When a scanner throws an {@link InputMismatchException}, the scanner + * will not pass the token that caused the exception, so that it may be + * retrieved or skipped via some other method. + * + * <p>Depending upon the type of delimiting pattern, empty tokens may be + * returned. For example, the pattern <tt>"\\s+"</tt> will return no empty + * tokens since it matches multiple instances of the delimiter. The delimiting + * pattern <tt>"\\s"</tt> could return empty tokens since it only passes one + * space at a time. + * + * <p> A scanner can read text from any object which implements the {@link + * java.lang.Readable} interface. If an invocation of the underlying + * readable's {@link java.lang.Readable#read} method throws an {@link + * java.io.IOException} then the scanner assumes that the end of the input + * has been reached. The most recent <tt>IOException</tt> thrown by the + * underlying readable can be retrieved via the {@link #ioException} method. + * + * <p>When a <code>Scanner</code> is closed, it will close its input source + * if the source implements the {@link java.io.Closeable} interface. + * + * <p>A <code>Scanner</code> is not safe for multithreaded use without + * external synchronization. + * + * <p>Unless otherwise mentioned, passing a <code>null</code> parameter into + * any method of a <code>Scanner</code> will cause a + * <code>NullPointerException</code> to be thrown. + * + * <p>A scanner will default to interpreting numbers as decimal unless a + * different radix has been set by using the {@link #useRadix} method. The + * {@link #reset} method will reset the value of the scanner's radix to + * <code>10</code> regardless of whether it was previously changed. + * + * <a name="localized-numbers"> + * <h4> Localized numbers </h4> + * + * <p> An instance of this class is capable of scanning numbers in the standard + * formats as well as in the formats of the scanner's locale. A scanner's + * <a name="initial-locale">initial locale </a>is the value returned by the {@link + * java.util.Locale#getDefault} method; it may be changed via the {@link + * #useLocale} method. The {@link #reset} method will reset the value of the + * scanner's locale to the initial locale regardless of whether it was + * previously changed. + * + * <p>The localized formats are defined in terms of the following parameters, + * which for a particular locale are taken from that locale's {@link + * java.text.DecimalFormat DecimalFormat} object, <tt>df</tt>, and its and + * {@link java.text.DecimalFormatSymbols DecimalFormatSymbols} object, + * <tt>dfs</tt>. + * + * <blockquote><table> + * <tr><td valign="top"><i>LocalGroupSeparator </i></td> + * <td valign="top">The character used to separate thousands groups, + * <i>i.e.,</i> <tt>dfs.</tt>{@link + * java.text.DecimalFormatSymbols#getGroupingSeparator + * getGroupingSeparator()}</td></tr> + * <tr><td valign="top"><i>LocalDecimalSeparator </i></td> + * <td valign="top">The character used for the decimal point, + * <i>i.e.,</i> <tt>dfs.</tt>{@link + * java.text.DecimalFormatSymbols#getDecimalSeparator + * getDecimalSeparator()}</td></tr> + * <tr><td valign="top"><i>LocalPositivePrefix </i></td> + * <td valign="top">The string that appears before a positive number (may + * be empty), <i>i.e.,</i> <tt>df.</tt>{@link + * java.text.DecimalFormat#getPositivePrefix + * getPositivePrefix()}</td></tr> + * <tr><td valign="top"><i>LocalPositiveSuffix </i></td> + * <td valign="top">The string that appears after a positive number (may be + * empty), <i>i.e.,</i> <tt>df.</tt>{@link + * java.text.DecimalFormat#getPositiveSuffix + * getPositiveSuffix()}</td></tr> + * <tr><td valign="top"><i>LocalNegativePrefix </i></td> + * <td valign="top">The string that appears before a negative number (may + * be empty), <i>i.e.,</i> <tt>df.</tt>{@link + * java.text.DecimalFormat#getNegativePrefix + * getNegativePrefix()}</td></tr> + * <tr><td valign="top"><i>LocalNegativeSuffix </i></td> + * <td valign="top">The string that appears after a negative number (may be + * empty), <i>i.e.,</i> <tt>df.</tt>{@link + * java.text.DecimalFormat#getNegativeSuffix + * getNegativeSuffix()}</td></tr> + * <tr><td valign="top"><i>LocalNaN </i></td> + * <td valign="top">The string that represents not-a-number for + * floating-point values, + * <i>i.e.,</i> <tt>dfs.</tt>{@link + * java.text.DecimalFormatSymbols#getNaN + * getNaN()}</td></tr> + * <tr><td valign="top"><i>LocalInfinity </i></td> + * <td valign="top">The string that represents infinity for floating-point + * values, <i>i.e.,</i> <tt>dfs.</tt>{@link + * java.text.DecimalFormatSymbols#getInfinity + * getInfinity()}</td></tr> + * </table></blockquote> + * + * <a name="number-syntax"> + * <h4> Number syntax </h4> + * + * <p> The strings that can be parsed as numbers by an instance of this class + * are specified in terms of the following regular-expression grammar, where + * Rmax is the highest digit in the radix being used (for example, Rmax is 9 + * in base 10). + * + * <p> + * <table cellspacing=0 cellpadding=0 align=center> + * + * <tr><td valign=top align=right><i>NonASCIIDigit</i> ::</td> + * <td valign=top>= A non-ASCII character c for which + * {@link java.lang.Character#isDigit Character.isDigit}<tt>(c)</tt> + * returns true</td></tr> + * + * <tr><td> </td></tr> + * + * <tr><td align=right><i>Non0Digit</i> ::</td> + * <td><tt>= [1-</tt><i>Rmax</i><tt>] | </tt><i>NonASCIIDigit</i></td></tr> + * + * <tr><td> </td></tr> + * + * <tr><td align=right><i>Digit</i> ::</td> + * <td><tt>= [0-</tt><i>Rmax</i><tt>] | </tt><i>NonASCIIDigit</i></td></tr> + * + * <tr><td> </td></tr> + * + * <tr><td valign=top align=right><i>GroupedNumeral</i> ::</td> + * <td valign=top> + * <table cellpadding=0 cellspacing=0> + * <tr><td><tt>= ( </tt></td> + * <td><i>Non0Digit</i><tt> + * </tt><i>Digit</i><tt>? + * </tt><i>Digit</i><tt>?</tt></td></tr> + * <tr><td></td> + * <td><tt>( </tt><i>LocalGroupSeparator</i><tt> + * </tt><i>Digit</i><tt> + * </tt><i>Digit</i><tt> + * </tt><i>Digit</i><tt> )+ )</tt></td></tr> + * </table></td></tr> + * + * <tr><td> </td></tr> + * + * <tr><td align=right><i>Numeral</i> ::</td> + * <td><tt>= ( ( </tt><i>Digit</i><tt>+ ) + * | </tt><i>GroupedNumeral</i><tt> )</tt></td></tr> + * + * <tr><td> </td></tr> + * + * <tr><td valign=top align=right> + * <a name="Integer-regex"><i>Integer</i> ::</td> + * <td valign=top><tt>= ( [-+]? ( </tt><i>Numeral</i><tt> + * ) )</tt></td></tr> + * <tr><td></td> + * <td><tt>| </tt><i>LocalPositivePrefix</i><tt> </tt><i>Numeral</i><tt> + * </tt><i>LocalPositiveSuffix</i></td></tr> + * <tr><td></td> + * <td><tt>| </tt><i>LocalNegativePrefix</i><tt> </tt><i>Numeral</i><tt> + * </tt><i>LocalNegativeSuffix</i></td></tr> + * + * <tr><td> </td></tr> + * + * <tr><td align=right><i>DecimalNumeral</i> ::</td> + * <td><tt>= </tt><i>Numeral</i></td></tr> + * <tr><td></td> + * <td><tt>| </tt><i>Numeral</i><tt> + * </tt><i>LocalDecimalSeparator</i><tt> + * </tt><i>Digit</i><tt>*</tt></td></tr> + * <tr><td></td> + * <td><tt>| </tt><i>LocalDecimalSeparator</i><tt> + * </tt><i>Digit</i><tt>+</tt></td></tr> + * + * <tr><td> </td></tr> + * + * <tr><td align=right><i>Exponent</i> ::</td> + * <td><tt>= ( [eE] [+-]? </tt><i>Digit</i><tt>+ )</tt></td></tr> + * + * <tr><td> </td></tr> + * + * <tr><td align=right> + * <a name="Decimal-regex"><i>Decimal</i> ::</td> + * <td><tt>= ( [-+]? </tt><i>DecimalNumeral</i><tt> + * </tt><i>Exponent</i><tt>? )</tt></td></tr> + * <tr><td></td> + * <td><tt>| </tt><i>LocalPositivePrefix</i><tt> + * </tt><i>DecimalNumeral</i><tt> + * </tt><i>LocalPositiveSuffix</i> + * </tt><i>Exponent</i><tt>?</td></tr> + * <tr><td></td> + * <td><tt>| </tt><i>LocalNegativePrefix</i><tt> + * </tt><i>DecimalNumeral</i><tt> + * </tt><i>LocalNegativeSuffix</i> + * </tt><i>Exponent</i><tt>?</td></tr> + * + * <tr><td> </td></tr> + * + * <tr><td align=right><i>HexFloat</i> ::</td> + * <td><tt>= [-+]? 0[xX][0-9a-fA-F]*\.[0-9a-fA-F]+ + * ([pP][-+]?[0-9]+)?</tt></td></tr> + * + * <tr><td> </td></tr> + * + * <tr><td align=right><i>NonNumber</i> ::</td> + * <td valign=top><tt>= NaN + * | </tt><i>LocalNan</i><tt> + * | Infinity + * | </tt><i>LocalInfinity</i></td></tr> + * + * <tr><td> </td></tr> + * + * <tr><td align=right><i>SignedNonNumber</i> ::</td> + * <td><tt>= ( [-+]? </tt><i>NonNumber</i><tt> )</tt></td></tr> + * <tr><td></td> + * <td><tt>| </tt><i>LocalPositivePrefix</i><tt> + * </tt><i>NonNumber</i><tt> + * </tt><i>LocalPositiveSuffix</i></td></tr> + * <tr><td></td> + * <td><tt>| </tt><i>LocalNegativePrefix</i><tt> + * </tt><i>NonNumber</i><tt> + * </tt><i>LocalNegativeSuffix</i></td></tr> + * + * <tr><td> </td></tr> + * + * <tr><td valign=top align=right> + * <a name="Float-regex"><i>Float</i> ::</td> + * <td valign=top><tt>= </tt><i>Decimal</i><tt></td></tr> + * <tr><td></td> + * <td><tt>| </tt><i>HexFloat</i><tt></td></tr> + * <tr><td></td> + * <td><tt>| </tt><i>SignedNonNumber</i><tt></td></tr> + * + * </table> + * </center> + * + * <p> Whitespace is not significant in the above regular expressions. + * + * @since 1.5 + */ +public final class Scanner implements Iterator<String> { + + // Internal buffer used to hold input + private CharBuffer buf; + + // Size of internal character buffer + private static final int BUFFER_SIZE = 1024; // change to 1024; + + // The index into the buffer currently held by the Scanner + private int position; + + // Internal matcher used for finding delimiters + private Matcher matcher; + + // Pattern used to delimit tokens + private Pattern delimPattern; + + // Pattern found in last hasNext operation + private Pattern hasNextPattern; + + // Position after last hasNext operation + private int hasNextPosition; + + // Result after last hasNext operation + private String hasNextResult; + + // The input source + private Readable source; + + // Boolean is true if source is done + private boolean sourceClosed = false; + + // Boolean indicating more input is required + private boolean needInput = false; + + // Boolean indicating if a delim has been skipped this operation + private boolean skipped = false; + + // A store of a position that the scanner may fall back to + private int savedScannerPosition = -1; + + // A cache of the last primitive type scanned + private Object typeCache = null; + + // Boolean indicating if a match result is available + private boolean matchValid = false; + + // Boolean indicating if this scanner has been closed + private boolean closed = false; + + // The current radix used by this scanner + private int radix = 10; + + // The default radix for this scanner + private int defaultRadix = 10; + + // The locale used by this scanner + private Locale locale = null; + + // A cache of the last few recently used Patterns + private LRUCache<String,Pattern> patternCache = + new LRUCache<String,Pattern>(7) { + protected Pattern create(String s) { + return Pattern.compile(s); + } + protected boolean hasName(Pattern p, String s) { + return p.pattern().equals(s); + } + }; + + // A holder of the last IOException encountered + private IOException lastException; + + // A pattern for java whitespace + private static Pattern WHITESPACE_PATTERN = Pattern.compile( + "\\p{javaWhitespace}+"); + + // A pattern for any token + private static Pattern FIND_ANY_PATTERN = Pattern.compile("(?s).*"); + + // A pattern for non-ASCII digits + private static Pattern NON_ASCII_DIGIT = Pattern.compile( + "[\\p{javaDigit}&&[^0-9]]"); + + // Fields and methods to support scanning primitive types + + /** + * Locale dependent values used to scan numbers + */ + private String groupSeparator = "\\,"; + private String decimalSeparator = "\\."; + private String nanString = "NaN"; + private String infinityString = "Infinity"; + private String positivePrefix = ""; + private String negativePrefix = "\\-"; + private String positiveSuffix = ""; + private String negativeSuffix = ""; + + /** + * Fields and an accessor method to match booleans + */ + private static volatile Pattern boolPattern; + private static final String BOOLEAN_PATTERN = "true|false"; + private static Pattern boolPattern() { + Pattern bp = boolPattern; + if (bp == null) + boolPattern = bp = Pattern.compile(BOOLEAN_PATTERN, + Pattern.CASE_INSENSITIVE); + return bp; + } + + /** + * Fields and methods to match bytes, shorts, ints, and longs + */ + private Pattern integerPattern; + private String digits = "0123456789abcdefghijklmnopqrstuvwxyz"; + private String non0Digit = "[\\p{javaDigit}&&[^0]]"; + private int SIMPLE_GROUP_INDEX = 5; + private String buildIntegerPatternString() { + String radixDigits = digits.substring(0, radix); + // \\p{javaDigit} is not guaranteed to be appropriate + // here but what can we do? The final authority will be + // whatever parse method is invoked, so ultimately the + // Scanner will do the right thing + String digit = "((?i)["+radixDigits+"]|\\p{javaDigit})"; + String groupedNumeral = "("+non0Digit+digit+"?"+digit+"?("+ + groupSeparator+digit+digit+digit+")+)"; + // digit++ is the possessive form which is necessary for reducing + // backtracking that would otherwise cause unacceptable performance + String numeral = "(("+ digit+"++)|"+groupedNumeral+")"; + String javaStyleInteger = "([-+]?(" + numeral + "))"; + String negativeInteger = negativePrefix + numeral + negativeSuffix; + String positiveInteger = positivePrefix + numeral + positiveSuffix; + return "("+ javaStyleInteger + ")|(" + + positiveInteger + ")|(" + + negativeInteger + ")"; + } + private Pattern integerPattern() { + if (integerPattern == null) { + integerPattern = patternCache.forName(buildIntegerPatternString()); + } + return integerPattern; + } + + /** + * Fields and an accessor method to match line separators + */ + private static volatile Pattern separatorPattern; + private static volatile Pattern linePattern; + private static final String LINE_SEPARATOR_PATTERN = + "\r\n|[\n\r\u2028\u2029\u0085]"; + private static final String LINE_PATTERN = ".*("+LINE_SEPARATOR_PATTERN+")|.+$"; + + private static Pattern separatorPattern() { + Pattern sp = separatorPattern; + if (sp == null) + separatorPattern = sp = Pattern.compile(LINE_SEPARATOR_PATTERN); + return sp; + } + + private static Pattern linePattern() { + Pattern lp = linePattern; + if (lp == null) + linePattern = lp = Pattern.compile(LINE_PATTERN); + return lp; + } + + /** + * Fields and methods to match floats and doubles + */ + private Pattern floatPattern; + private Pattern decimalPattern; + private void buildFloatAndDecimalPattern() { + // \\p{javaDigit} may not be perfect, see above + String digit = "([0-9]|(\\p{javaDigit}))"; + String exponent = "([eE][+-]?"+digit+"+)?"; + String groupedNumeral = "("+non0Digit+digit+"?"+digit+"?("+ + groupSeparator+digit+digit+digit+")+)"; + // Once again digit++ is used for performance, as above + String numeral = "(("+digit+"++)|"+groupedNumeral+")"; + String decimalNumeral = "("+numeral+"|"+numeral + + decimalSeparator + digit + "*+|"+ decimalSeparator + + digit + "++)"; + String nonNumber = "(NaN|"+nanString+"|Infinity|"+ + infinityString+")"; + String positiveFloat = "(" + positivePrefix + decimalNumeral + + positiveSuffix + exponent + ")"; + String negativeFloat = "(" + negativePrefix + decimalNumeral + + negativeSuffix + exponent + ")"; + String decimal = "(([-+]?" + decimalNumeral + exponent + ")|"+ + positiveFloat + "|" + negativeFloat + ")"; + String hexFloat = + "[-+]?0[xX][0-9a-fA-F]*\\.[0-9a-fA-F]+([pP][-+]?[0-9]+)?"; + String positiveNonNumber = "(" + positivePrefix + nonNumber + + positiveSuffix + ")"; + String negativeNonNumber = "(" + negativePrefix + nonNumber + + negativeSuffix + ")"; + String signedNonNumber = "(([-+]?"+nonNumber+")|" + + positiveNonNumber + "|" + + negativeNonNumber + ")"; + floatPattern = Pattern.compile(decimal + "|" + hexFloat + "|" + + signedNonNumber); + decimalPattern = Pattern.compile(decimal); + } + private Pattern floatPattern() { + if (floatPattern == null) { + buildFloatAndDecimalPattern(); + } + return floatPattern; + } + private Pattern decimalPattern() { + if (decimalPattern == null) { + buildFloatAndDecimalPattern(); + } + return decimalPattern; + } + + // Constructors + + /** + * Constructs a <code>Scanner</code> that returns values scanned + * from the specified source delimited by the specified pattern. + * + * @param source A character source implementing the Readable interface + * @param pattern A delimiting pattern + * @return A scanner with the specified source and pattern + */ + private Scanner(Readable source, Pattern pattern) { + if (source == null) + throw new NullPointerException("source"); + if (pattern == null) + throw new NullPointerException("pattern"); + this.source = source; + delimPattern = pattern; + buf = CharBuffer.allocate(BUFFER_SIZE); + buf.limit(0); + matcher = delimPattern.matcher(buf); + matcher.useTransparentBounds(true); + matcher.useAnchoringBounds(false); + useLocale(Locale.getDefault()); + } + + /** + * Constructs a new <code>Scanner</code> that produces values scanned + * from the specified source. + * + * @param source A character source implementing the {@link Readable} + * interface + */ + public Scanner(Readable source) { + this(source, WHITESPACE_PATTERN); + } + + /** + * Constructs a new <code>Scanner</code> that produces values scanned + * from the specified input stream. Bytes from the stream are converted + * into characters using the underlying platform's + * {@linkplain java.nio.charset.Charset#defaultCharset() default charset}. + * + * @param source An input stream to be scanned + */ + public Scanner(InputStream source) { + this(new InputStreamReader(source), WHITESPACE_PATTERN); + } + + /** + * Constructs a new <code>Scanner</code> that produces values scanned + * from the specified input stream. Bytes from the stream are converted + * into characters using the specified charset. + * + * @param source An input stream to be scanned + * @param charsetName The encoding type used to convert bytes from the + * stream into characters to be scanned + * @throws IllegalArgumentException if the specified character set + * does not exist + */ + public Scanner(InputStream source, String charsetName) { + this(makeReadable(source, charsetName), WHITESPACE_PATTERN); + } + + private static Readable makeReadable(InputStream source, + String charsetName) + { + if (source == null) + throw new NullPointerException("source"); + InputStreamReader isr = null; + try { + isr = new InputStreamReader(source, charsetName); + } catch (UnsupportedEncodingException uee) { + IllegalArgumentException iae = new IllegalArgumentException(); + iae.initCause(uee); + throw iae; + } + return isr; + } + + /** + * Constructs a new <code>Scanner</code> that produces values scanned + * from the specified file. Bytes from the file are converted into + * characters using the underlying platform's + * {@linkplain java.nio.charset.Charset#defaultCharset() default charset}. + * + * @param source A file to be scanned + * @throws FileNotFoundException if source is not found + */ + public Scanner(File source) + throws FileNotFoundException + { + this((ReadableByteChannel)(new FileInputStream(source).getChannel())); + } + + /** + * Constructs a new <code>Scanner</code> that produces values scanned + * from the specified file. Bytes from the file are converted into + * characters using the specified charset. + * + * @param source A file to be scanned + * @param charsetName The encoding type used to convert bytes from the file + * into characters to be scanned + * @throws FileNotFoundException if source is not found + * @throws IllegalArgumentException if the specified encoding is + * not found + */ + public Scanner(File source, String charsetName) + throws FileNotFoundException + { + this((ReadableByteChannel)(new FileInputStream(source).getChannel()), + charsetName); + } + + /** + * {@note new} + * Constructs a new <code>Scanner</code> that produces values scanned + * from the specified file. Bytes from the file are converted into + * characters using the underlying platform's + * {@linkplain java.nio.charset.Charset#defaultCharset() default charset}. + * + * @param source + * A file to be scanned + * @throws IOException + * if an I/O error occurs opening source + * + * @since 1.7 + */ + public Scanner(FileRef source) + throws IOException + { + this(source.newByteChannel()); + } + + /** + * {@note new} + * Constructs a new <code>Scanner</code> that produces values scanned + * from the specified file. Bytes from the file are converted into + * characters using the specified charset. + * + * @param source + * A file to be scanned + * @param charsetName + * The encoding type used to convert bytes from the file + * into characters to be scanned + * @throws IOException + * if an I/O error occurs opening source + * @throws IllegalArgumentException + * if the specified encoding is not found + * @since 1.7 + */ + public Scanner(FileRef source, String charsetName) + throws IOException + { + this(source.newByteChannel(), charsetName); + } + + /** + * Constructs a new <code>Scanner</code> that produces values scanned + * from the specified string. + * + * @param source A string to scan + */ + public Scanner(String source) { + this(new StringReader(source), WHITESPACE_PATTERN); + } + + /** + * Constructs a new <code>Scanner</code> that produces values scanned + * from the specified channel. Bytes from the source are converted into + * characters using the underlying platform's + * {@linkplain java.nio.charset.Charset#defaultCharset() default charset}. + * + * @param source A channel to scan + */ + public Scanner(ReadableByteChannel source) { + this(makeReadable(source), WHITESPACE_PATTERN); + } + + private static Readable makeReadable(ReadableByteChannel source) { + if (source == null) + throw new NullPointerException("source"); + String defaultCharsetName = + java.nio.charset.Charset.defaultCharset().name(); + return Channels.newReader(source, + java.nio.charset.Charset.defaultCharset().name()); + } + + /** + * Constructs a new <code>Scanner</code> that produces values scanned + * from the specified channel. Bytes from the source are converted into + * characters using the specified charset. + * + * @param source A channel to scan + * @param charsetName The encoding type used to convert bytes from the + * channel into characters to be scanned + * @throws IllegalArgumentException if the specified character set + * does not exist + */ + public Scanner(ReadableByteChannel source, String charsetName) { + this(makeReadable(source, charsetName), WHITESPACE_PATTERN); + } + + private static Readable makeReadable(ReadableByteChannel source, + String charsetName) + { + if (source == null) + throw new NullPointerException("source"); + if (!Charset.isSupported(charsetName)) + throw new IllegalArgumentException(charsetName); + return Channels.newReader(source, charsetName); + } + + // Private primitives used to support scanning + + private void saveState() { + savedScannerPosition = position; + } + + private void revertState() { + this.position = savedScannerPosition; + savedScannerPosition = -1; + skipped = false; + } + + private boolean revertState(boolean b) { + this.position = savedScannerPosition; + savedScannerPosition = -1; + skipped = false; + return b; + } + + private void cacheResult() { + hasNextResult = matcher.group(); + hasNextPosition = matcher.end(); + hasNextPattern = matcher.pattern(); + } + + private void cacheResult(String result) { + hasNextResult = result; + hasNextPosition = matcher.end(); + hasNextPattern = matcher.pattern(); + } + + // Clears both regular cache and type cache + private void clearCaches() { + hasNextPattern = null; + typeCache = null; + } + + // Also clears both the regular cache and the type cache + private String getCachedResult() { + position = hasNextPosition; + hasNextPattern = null; + typeCache = null; + return hasNextResult; + } + + // Also clears both the regular cache and the type cache + private void useTypeCache() { + if (closed) + throw new IllegalStateException("Scanner closed"); + position = hasNextPosition; + hasNextPattern = null; + typeCache = null; + } + + // Tries to read more input. May block. + private void readInput() { + if (buf.limit() == buf.capacity()) + makeSpace(); + + // Prepare to receive data + int p = buf.position(); + buf.position(buf.limit()); + buf.limit(buf.capacity()); + + int n = 0; + try { + n = source.read(buf); + } catch (IOException ioe) { + lastException = ioe; + n = -1; + } + + if (n == -1) { + sourceClosed = true; + needInput = false; + } + + if (n > 0) + needInput = false; + + // Restore current position and limit for reading + buf.limit(buf.position()); + buf.position(p); + } + + // After this method is called there will either be an exception + // or else there will be space in the buffer + private boolean makeSpace() { + clearCaches(); + int offset = savedScannerPosition == -1 ? + position : savedScannerPosition; + buf.position(offset); + // Gain space by compacting buffer + if (offset > 0) { + buf.compact(); + translateSavedIndexes(offset); + position -= offset; + buf.flip(); + return true; + } + // Gain space by growing buffer + int newSize = buf.capacity() * 2; + CharBuffer newBuf = CharBuffer.allocate(newSize); + newBuf.put(buf); + newBuf.flip(); + translateSavedIndexes(offset); + position -= offset; + buf = newBuf; + matcher.reset(buf); + return true; + } + + // When a buffer compaction/reallocation occurs the saved indexes must + // be modified appropriately + private void translateSavedIndexes(int offset) { + if (savedScannerPosition != -1) + savedScannerPosition -= offset; + } + + // If we are at the end of input then NoSuchElement; + // If there is still input left then InputMismatch + private void throwFor() { + skipped = false; + if ((sourceClosed) && (position == buf.limit())) + throw new NoSuchElementException(); + else + throw new InputMismatchException(); + } + + // Returns true if a complete token or partial token is in the buffer. + // It is not necessary to find a complete token since a partial token + // means that there will be another token with or without more input. + private boolean hasTokenInBuffer() { + matchValid = false; + matcher.usePattern(delimPattern); + matcher.region(position, buf.limit()); + + // Skip delims first + if (matcher.lookingAt()) + position = matcher.end(); + + // If we are sitting at the end, no more tokens in buffer + if (position == buf.limit()) + return false; + + return true; + } + + /* + * Returns a "complete token" that matches the specified pattern + * + * A token is complete if surrounded by delims; a partial token + * is prefixed by delims but not postfixed by them + * + * The position is advanced to the end of that complete token + * + * Pattern == null means accept any token at all + * + * Triple return: + * 1. valid string means it was found + * 2. null with needInput=false means we won't ever find it + * 3. null with needInput=true means try again after readInput + */ + private String getCompleteTokenInBuffer(Pattern pattern) { + matchValid = false; + + // Skip delims first + matcher.usePattern(delimPattern); + if (!skipped) { // Enforcing only one skip of leading delims + matcher.region(position, buf.limit()); + if (matcher.lookingAt()) { + // If more input could extend the delimiters then we must wait + // for more input + if (matcher.hitEnd() && !sourceClosed) { + needInput = true; + return null; + } + // The delims were whole and the matcher should skip them + skipped = true; + position = matcher.end(); + } + } + + // If we are sitting at the end, no more tokens in buffer + if (position == buf.limit()) { + if (sourceClosed) + return null; + needInput = true; + return null; + } + + // Must look for next delims. Simply attempting to match the + // pattern at this point may find a match but it might not be + // the first longest match because of missing input, or it might + // match a partial token instead of the whole thing. + + // Then look for next delims + matcher.region(position, buf.limit()); + boolean foundNextDelim = matcher.find(); + if (foundNextDelim && (matcher.end() == position)) { + // Zero length delimiter match; we should find the next one + // using the automatic advance past a zero length match; + // Otherwise we have just found the same one we just skipped + foundNextDelim = matcher.find(); + } + if (foundNextDelim) { + // In the rare case that more input could cause the match + // to be lost and there is more input coming we must wait + // for more input. Note that hitting the end is okay as long + // as the match cannot go away. It is the beginning of the + // next delims we want to be sure about, we don't care if + // they potentially extend further. + if (matcher.requireEnd() && !sourceClosed) { + needInput = true; + return null; + } + int tokenEnd = matcher.start(); + // There is a complete token. + if (pattern == null) { + // Must continue with match to provide valid MatchResult + pattern = FIND_ANY_PATTERN; + } + // Attempt to match against the desired pattern + matcher.usePattern(pattern); + matcher.region(position, tokenEnd); + if (matcher.matches()) { + String s = matcher.group(); + position = matcher.end(); + return s; + } else { // Complete token but it does not match + return null; + } + } + + // If we can't find the next delims but no more input is coming, + // then we can treat the remainder as a whole token + if (sourceClosed) { + if (pattern == null) { + // Must continue with match to provide valid MatchResult + pattern = FIND_ANY_PATTERN; + } + // Last token; Match the pattern here or throw + matcher.usePattern(pattern); + matcher.region(position, buf.limit()); + if (matcher.matches()) { + String s = matcher.group(); + position = matcher.end(); + return s; + } + // Last piece does not match + return null; + } + + // There is a partial token in the buffer; must read more + // to complete it + needInput = true; + return null; + } + + // Finds the specified pattern in the buffer up to horizon. + // Returns a match for the specified input pattern. + private String findPatternInBuffer(Pattern pattern, int horizon) { + matchValid = false; + matcher.usePattern(pattern); + int bufferLimit = buf.limit(); + int horizonLimit = -1; + int searchLimit = bufferLimit; + if (horizon > 0) { + horizonLimit = position + horizon; + if (horizonLimit < bufferLimit) + searchLimit = horizonLimit; + } + matcher.region(position, searchLimit); + if (matcher.find()) { + if (matcher.hitEnd() && (!sourceClosed)) { + // The match may be longer if didn't hit horizon or real end + if (searchLimit != horizonLimit) { + // Hit an artificial end; try to extend the match + needInput = true; + return null; + } + // The match could go away depending on what is next + if ((searchLimit == horizonLimit) && matcher.requireEnd()) { + // Rare case: we hit the end of input and it happens + // that it is at the horizon and the end of input is + // required for the match. + needInput = true; + return null; + } + } + // Did not hit end, or hit real end, or hit horizon + position = matcher.end(); + return matcher.group(); + } + + if (sourceClosed) + return null; + + // If there is no specified horizon, or if we have not searched + // to the specified horizon yet, get more input + if ((horizon == 0) || (searchLimit != horizonLimit)) + needInput = true; + return null; + } + + // Returns a match for the specified input pattern anchored at + // the current position + private String matchPatternInBuffer(Pattern pattern) { + matchValid = false; + matcher.usePattern(pattern); + matcher.region(position, buf.limit()); + if (matcher.lookingAt()) { + if (matcher.hitEnd() && (!sourceClosed)) { + // Get more input and try again + needInput = true; + return null; + } + position = matcher.end(); + return matcher.group(); + } + + if (sourceClosed) + return null; + + // Read more to find pattern + needInput = true; + return null; + } + + // Throws if the scanner is closed + private void ensureOpen() { + if (closed) + throw new IllegalStateException("Scanner closed"); + } + + // Public methods + + /** + * Closes this scanner. + * + * <p> If this scanner has not yet been closed then if its underlying + * {@linkplain java.lang.Readable readable} also implements the {@link + * java.io.Closeable} interface then the readable's <tt>close</tt> method + * will be invoked. If this scanner is already closed then invoking this + * method will have no effect. + * + * <p>Attempting to perform search operations after a scanner has + * been closed will result in an {@link IllegalStateException}. + * + */ + public void close() { + if (closed) + return; + if (source instanceof Closeable) { + try { + ((Closeable)source).close(); + } catch (IOException ioe) { + lastException = ioe; + } + } + sourceClosed = true; + source = null; + closed = true; + } + + /** + * Returns the <code>IOException</code> last thrown by this + * <code>Scanner</code>'s underlying <code>Readable</code>. This method + * returns <code>null</code> if no such exception exists. + * + * @return the last exception thrown by this scanner's readable + */ + public IOException ioException() { + return lastException; + } + + /** + * Returns the <code>Pattern</code> this <code>Scanner</code> is currently + * using to match delimiters. + * + * @return this scanner's delimiting pattern. + */ + public Pattern delimiter() { + return delimPattern; + } + + /** + * Sets this scanner's delimiting pattern to the specified pattern. + * + * @param pattern A delimiting pattern + * @return this scanner + */ + public Scanner useDelimiter(Pattern pattern) { + delimPattern = pattern; + return this; + } + + /** + * Sets this scanner's delimiting pattern to a pattern constructed from + * the specified <code>String</code>. + * + * <p> An invocation of this method of the form + * <tt>useDelimiter(pattern)</tt> behaves in exactly the same way as the + * invocation <tt>useDelimiter(Pattern.compile(pattern))</tt>. + * + * <p> Invoking the {@link #reset} method will set the scanner's delimiter + * to the <a href= "#default-delimiter">default</a>. + * + * @param pattern A string specifying a delimiting pattern + * @return this scanner + */ + public Scanner useDelimiter(String pattern) { + delimPattern = patternCache.forName(pattern); + return this; + } + + /** + * Returns this scanner's locale. + * + * <p>A scanner's locale affects many elements of its default + * primitive matching regular expressions; see + * <a href= "#localized-numbers">localized numbers</a> above. + * + * @return this scanner's locale + */ + public Locale locale() { + return this.locale; + } + + /** + * Sets this scanner's locale to the specified locale. + * + * <p>A scanner's locale affects many elements of its default + * primitive matching regular expressions; see + * <a href= "#localized-numbers">localized numbers</a> above. + * + * <p>Invoking the {@link #reset} method will set the scanner's locale to + * the <a href= "#initial-locale">initial locale</a>. + * + * @param locale A string specifying the locale to use + * @return this scanner + */ + public Scanner useLocale(Locale locale) { + if (locale.equals(this.locale)) + return this; + + this.locale = locale; + DecimalFormat df = + (DecimalFormat)NumberFormat.getNumberInstance(locale); + DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(locale); + + // These must be literalized to avoid collision with regex + // metacharacters such as dot or parenthesis + groupSeparator = "\\" + dfs.getGroupingSeparator(); + decimalSeparator = "\\" + dfs.getDecimalSeparator(); + + // Quoting the nonzero length locale-specific things + // to avoid potential conflict with metacharacters + nanString = "\\Q" + dfs.getNaN() + "\\E"; + infinityString = "\\Q" + dfs.getInfinity() + "\\E"; + positivePrefix = df.getPositivePrefix(); + if (positivePrefix.length() > 0) + positivePrefix = "\\Q" + positivePrefix + "\\E"; + negativePrefix = df.getNegativePrefix(); + if (negativePrefix.length() > 0) + negativePrefix = "\\Q" + negativePrefix + "\\E"; + positiveSuffix = df.getPositiveSuffix(); + if (positiveSuffix.length() > 0) + positiveSuffix = "\\Q" + positiveSuffix + "\\E"; + negativeSuffix = df.getNegativeSuffix(); + if (negativeSuffix.length() > 0) + negativeSuffix = "\\Q" + negativeSuffix + "\\E"; + + // Force rebuilding and recompilation of locale dependent + // primitive patterns + integerPattern = null; + floatPattern = null; + + return this; + } + + /** + * Returns this scanner's default radix. + * + * <p>A scanner's radix affects elements of its default + * number matching regular expressions; see + * <a href= "#localized-numbers">localized numbers</a> above. + * + * @return the default radix of this scanner + */ + public int radix() { + return this.defaultRadix; + } + + /** + * Sets this scanner's default radix to the specified radix. + * + * <p>A scanner's radix affects elements of its default + * number matching regular expressions; see + * <a href= "#localized-numbers">localized numbers</a> above. + * + * <p>If the radix is less than <code>Character.MIN_RADIX</code> + * or greater than <code>Character.MAX_RADIX</code>, then an + * <code>IllegalArgumentException</code> is thrown. + * + * <p>Invoking the {@link #reset} method will set the scanner's radix to + * <code>10</code>. + * + * @param radix The radix to use when scanning numbers + * @return this scanner + * @throws IllegalArgumentException if radix is out of range + */ + public Scanner useRadix(int radix) { + if ((radix < Character.MIN_RADIX) || (radix > Character.MAX_RADIX)) + throw new IllegalArgumentException("radix:"+radix); + + if (this.defaultRadix == radix) + return this; + this.defaultRadix = radix; + // Force rebuilding and recompilation of radix dependent patterns + integerPattern = null; + return this; + } + + // The next operation should occur in the specified radix but + // the default is left untouched. + private void setRadix(int radix) { + if (this.radix != radix) { + // Force rebuilding and recompilation of radix dependent patterns + integerPattern = null; + this.radix = radix; + } + } + + /** + * Returns the match result of the last scanning operation performed + * by this scanner. This method throws <code>IllegalStateException</code> + * if no match has been performed, or if the last match was + * not successful. + * + * <p>The various <code>next</code>methods of <code>Scanner</code> + * make a match result available if they complete without throwing an + * exception. For instance, after an invocation of the {@link #nextInt} + * method that returned an int, this method returns a + * <code>MatchResult</code> for the search of the + * <a href="#Integer-regex"><i>Integer</i></a> regular expression + * defined above. Similarly the {@link #findInLine}, + * {@link #findWithinHorizon}, and {@link #skip} methods will make a + * match available if they succeed. + * + * @return a match result for the last match operation + * @throws IllegalStateException If no match result is available + */ + public MatchResult match() { + if (!matchValid) + throw new IllegalStateException("No match result available"); + return matcher.toMatchResult(); + } + + /** + * <p>Returns the string representation of this <code>Scanner</code>. The + * string representation of a <code>Scanner</code> contains information + * that may be useful for debugging. The exact format is unspecified. + * + * @return The string representation of this scanner + */ + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("java.util.Scanner"); + sb.append("[delimiters=" + delimPattern + "]"); + sb.append("[position=" + position + "]"); + sb.append("[match valid=" + matchValid + "]"); + sb.append("[need input=" + needInput + "]"); + sb.append("[source closed=" + sourceClosed + "]"); + sb.append("[skipped=" + skipped + "]"); + sb.append("[group separator=" + groupSeparator + "]"); + sb.append("[decimal separator=" + decimalSeparator + "]"); + sb.append("[positive prefix=" + positivePrefix + "]"); + sb.append("[negative prefix=" + negativePrefix + "]"); + sb.append("[positive suffix=" + positiveSuffix + "]"); + sb.append("[negative suffix=" + negativeSuffix + "]"); + sb.append("[NaN string=" + nanString + "]"); + sb.append("[infinity string=" + infinityString + "]"); + return sb.toString(); + } + + /** + * Returns true if this scanner has another token in its input. + * This method may block while waiting for input to scan. + * The scanner does not advance past any input. + * + * @return true if and only if this scanner has another token + * @throws IllegalStateException if this scanner is closed + * @see java.util.Iterator + */ + public boolean hasNext() { + ensureOpen(); + saveState(); + while (!sourceClosed) { + if (hasTokenInBuffer()) + return revertState(true); + readInput(); + } + boolean result = hasTokenInBuffer(); + return revertState(result); + } + + /** + * Finds and returns the next complete token from this scanner. + * A complete token is preceded and followed by input that matches + * the delimiter pattern. This method may block while waiting for input + * to scan, even if a previous invocation of {@link #hasNext} returned + * <code>true</code>. + * + * @return the next token + * @throws NoSuchElementException if no more tokens are available + * @throws IllegalStateException if this scanner is closed + * @see java.util.Iterator + */ + public String next() { + ensureOpen(); + clearCaches(); + + while (true) { + String token = getCompleteTokenInBuffer(null); + if (token != null) { + matchValid = true; + skipped = false; + return token; + } + if (needInput) + readInput(); + else + throwFor(); + } + } + + /** + * The remove operation is not supported by this implementation of + * <code>Iterator</code>. + * + * @throws UnsupportedOperationException if this method is invoked. + * @see java.util.Iterator + */ + public void remove() { + throw new UnsupportedOperationException(); + } + + /** + * Returns true if the next token matches the pattern constructed from the + * specified string. The scanner does not advance past any input. + * + * <p> An invocation of this method of the form <tt>hasNext(pattern)</tt> + * behaves in exactly the same way as the invocation + * <tt>hasNext(Pattern.compile(pattern))</tt>. + * + * @param pattern a string specifying the pattern to scan + * @return true if and only if this scanner has another token matching + * the specified pattern + * @throws IllegalStateException if this scanner is closed + */ + public boolean hasNext(String pattern) { + return hasNext(patternCache.forName(pattern)); + } + + /** + * Returns the next token if it matches the pattern constructed from the + * specified string. If the match is successful, the scanner advances + * past the input that matched the pattern. + * + * <p> An invocation of this method of the form <tt>next(pattern)</tt> + * behaves in exactly the same way as the invocation + * <tt>next(Pattern.compile(pattern))</tt>. + * + * @param pattern a string specifying the pattern to scan + * @return the next token + * @throws NoSuchElementException if no such tokens are available + * @throws IllegalStateException if this scanner is closed + */ + public String next(String pattern) { + return next(patternCache.forName(pattern)); + } + + /** + * Returns true if the next complete token matches the specified pattern. + * A complete token is prefixed and postfixed by input that matches + * the delimiter pattern. This method may block while waiting for input. + * The scanner does not advance past any input. + * + * @param pattern the pattern to scan for + * @return true if and only if this scanner has another token matching + * the specified pattern + * @throws IllegalStateException if this scanner is closed + */ + public boolean hasNext(Pattern pattern) { + ensureOpen(); + if (pattern == null) + throw new NullPointerException(); + hasNextPattern = null; + saveState(); + + while (true) { + if (getCompleteTokenInBuffer(pattern) != null) { + matchValid = true; + cacheResult(); + return revertState(true); + } + if (needInput) + readInput(); + else + return revertState(false); + } + } + + /** + * Returns the next token if it matches the specified pattern. This + * method may block while waiting for input to scan, even if a previous + * invocation of {@link #hasNext(Pattern)} returned <code>true</code>. + * If the match is successful, the scanner advances past the input that + * matched the pattern. + * + * @param pattern the pattern to scan for + * @return the next token + * @throws NoSuchElementException if no more tokens are available + * @throws IllegalStateException if this scanner is closed + */ + public String next(Pattern pattern) { + ensureOpen(); + if (pattern == null) + throw new NullPointerException(); + + // Did we already find this pattern? + if (hasNextPattern == pattern) + return getCachedResult(); + clearCaches(); + + // Search for the pattern + while (true) { + String token = getCompleteTokenInBuffer(pattern); + if (token != null) { + matchValid = true; + skipped = false; + return token; + } + if (needInput) + readInput(); + else + throwFor(); + } + } + + /** + * Returns true if there is another line in the input of this scanner. + * This method may block while waiting for input. The scanner does not + * advance past any input. + * + * @return true if and only if this scanner has another line of input + * @throws IllegalStateException if this scanner is closed + */ + public boolean hasNextLine() { + saveState(); + + String result = findWithinHorizon(linePattern(), 0); + if (result != null) { + MatchResult mr = this.match(); + String lineSep = mr.group(1); + if (lineSep != null) { + result = result.substring(0, result.length() - + lineSep.length()); + cacheResult(result); + + } else { + cacheResult(); + } + } + revertState(); + return (result != null); + } + + /** + * Advances this scanner past the current line and returns the input + * that was skipped. + * + * This method returns the rest of the current line, excluding any line + * separator at the end. The position is set to the beginning of the next + * line. + * + * <p>Since this method continues to search through the input looking + * for a line separator, it may buffer all of the input searching for + * the line to skip if no line separators are present. + * + * @return the line that was skipped + * @throws NoSuchElementException if no line was found + * @throws IllegalStateException if this scanner is closed + */ + public String nextLine() { + if (hasNextPattern == linePattern()) + return getCachedResult(); + clearCaches(); + + String result = findWithinHorizon(linePattern, 0); + if (result == null) + throw new NoSuchElementException("No line found"); + MatchResult mr = this.match(); + String lineSep = mr.group(1); + if (lineSep != null) + result = result.substring(0, result.length() - lineSep.length()); + if (result == null) + throw new NoSuchElementException(); + else + return result; + } + + // Public methods that ignore delimiters + + /** + * Attempts to find the next occurrence of a pattern constructed from the + * specified string, ignoring delimiters. + * + * <p>An invocation of this method of the form <tt>findInLine(pattern)</tt> + * behaves in exactly the same way as the invocation + * <tt>findInLine(Pattern.compile(pattern))</tt>. + * + * @param pattern a string specifying the pattern to search for + * @return the text that matched the specified pattern + * @throws IllegalStateException if this scanner is closed + */ + public String findInLine(String pattern) { + return findInLine(patternCache.forName(pattern)); + } + + /** + * Attempts to find the next occurrence of the specified pattern ignoring + * delimiters. If the pattern is found before the next line separator, the + * scanner advances past the input that matched and returns the string that + * matched the pattern. + * If no such pattern is detected in the input up to the next line + * separator, then <code>null</code> is returned and the scanner's + * position is unchanged. This method may block waiting for input that + * matches the pattern. + * + * <p>Since this method continues to search through the input looking + * for the specified pattern, it may buffer all of the input searching for + * the desired token if no line separators are present. + * + * @param pattern the pattern to scan for + * @return the text that matched the specified pattern + * @throws IllegalStateException if this scanner is closed + */ + public String findInLine(Pattern pattern) { + ensureOpen(); + if (pattern == null) + throw new NullPointerException(); + clearCaches(); + // Expand buffer to include the next newline or end of input + int endPosition = 0; + saveState(); + while (true) { + String token = findPatternInBuffer(separatorPattern(), 0); + if (token != null) { + endPosition = matcher.start(); + break; // up to next newline + } + if (needInput) { + readInput(); + } else { + endPosition = buf.limit(); + break; // up to end of input + } + } + revertState(); + int horizonForLine = endPosition - position; + // If there is nothing between the current pos and the next + // newline simply return null, invoking findWithinHorizon + // with "horizon=0" will scan beyond the line bound. + if (horizonForLine == 0) + return null; + // Search for the pattern + return findWithinHorizon(pattern, horizonForLine); + } + + /** + * Attempts to find the next occurrence of a pattern constructed from the + * specified string, ignoring delimiters. + * + * <p>An invocation of this method of the form + * <tt>findWithinHorizon(pattern)</tt> behaves in exactly the same way as + * the invocation + * <tt>findWithinHorizon(Pattern.compile(pattern, horizon))</tt>. + * + * @param pattern a string specifying the pattern to search for + * @return the text that matched the specified pattern + * @throws IllegalStateException if this scanner is closed + * @throws IllegalArgumentException if horizon is negative + */ + public String findWithinHorizon(String pattern, int horizon) { + return findWithinHorizon(patternCache.forName(pattern), horizon); + } + + /** + * Attempts to find the next occurrence of the specified pattern. + * + * <p>This method searches through the input up to the specified + * search horizon, ignoring delimiters. If the pattern is found the + * scanner advances past the input that matched and returns the string + * that matched the pattern. If no such pattern is detected then the + * null is returned and the scanner's position remains unchanged. This + * method may block waiting for input that matches the pattern. + * + * <p>A scanner will never search more than <code>horizon</code> code + * points beyond its current position. Note that a match may be clipped + * by the horizon; that is, an arbitrary match result may have been + * different if the horizon had been larger. The scanner treats the + * horizon as a transparent, non-anchoring bound (see {@link + * Matcher#useTransparentBounds} and {@link Matcher#useAnchoringBounds}). + * + * <p>If horizon is <code>0</code>, then the horizon is ignored and + * this method continues to search through the input looking for the + * specified pattern without bound. In this case it may buffer all of + * the input searching for the pattern. + * + * <p>If horizon is negative, then an IllegalArgumentException is + * thrown. + * + * @param pattern the pattern to scan for + * @return the text that matched the specified pattern + * @throws IllegalStateException if this scanner is closed + * @throws IllegalArgumentException if horizon is negative + */ + public String findWithinHorizon(Pattern pattern, int horizon) { + ensureOpen(); + if (pattern == null) + throw new NullPointerException(); + if (horizon < 0) + throw new IllegalArgumentException("horizon < 0"); + clearCaches(); + + // Search for the pattern + while (true) { + String token = findPatternInBuffer(pattern, horizon); + if (token != null) { + matchValid = true; + return token; + } + if (needInput) + readInput(); + else + break; // up to end of input + } + return null; + } + + /** + * Skips input that matches the specified pattern, ignoring delimiters. + * This method will skip input if an anchored match of the specified + * pattern succeeds. + * + * <p>If a match to the specified pattern is not found at the + * current position, then no input is skipped and a + * <tt>NoSuchElementException</tt> is thrown. + * + * <p>Since this method seeks to match the specified pattern starting at + * the scanner's current position, patterns that can match a lot of + * input (".*", for example) may cause the scanner to buffer a large + * amount of input. + * + * <p>Note that it is possible to skip something without risking a + * <code>NoSuchElementException</code> by using a pattern that can + * match nothing, e.g., <code>sc.skip("[ \t]*")</code>. + * + * @param pattern a string specifying the pattern to skip over + * @return this scanner + * @throws NoSuchElementException if the specified pattern is not found + * @throws IllegalStateException if this scanner is closed + */ + public Scanner skip(Pattern pattern) { + ensureOpen(); + if (pattern == null) + throw new NullPointerException(); + clearCaches(); + + // Search for the pattern + while (true) { + String token = matchPatternInBuffer(pattern); + if (token != null) { + matchValid = true; + position = matcher.end(); + return this; + } + if (needInput) + readInput(); + else + throw new NoSuchElementException(); + } + } + + /** + * Skips input that matches a pattern constructed from the specified + * string. + * + * <p> An invocation of this method of the form <tt>skip(pattern)</tt> + * behaves in exactly the same way as the invocation + * <tt>skip(Pattern.compile(pattern))</tt>. + * + * @param pattern a string specifying the pattern to skip over + * @return this scanner + * @throws IllegalStateException if this scanner is closed + */ + public Scanner skip(String pattern) { + return skip(patternCache.forName(pattern)); + } + + // Convenience methods for scanning primitives + + /** + * Returns true if the next token in this scanner's input can be + * interpreted as a boolean value using a case insensitive pattern + * created from the string "true|false". The scanner does not + * advance past the input that matched. + * + * @return true if and only if this scanner's next token is a valid + * boolean value + * @throws IllegalStateException if this scanner is closed + */ + public boolean hasNextBoolean() { + return hasNext(boolPattern()); + } + + /** + * Scans the next token of the input into a boolean value and returns + * that value. This method will throw <code>InputMismatchException</code> + * if the next token cannot be translated into a valid boolean value. + * If the match is successful, the scanner advances past the input that + * matched. + * + * @return the boolean scanned from the input + * @throws InputMismatchException if the next token is not a valid boolean + * @throws NoSuchElementException if input is exhausted + * @throws IllegalStateException if this scanner is closed + */ + public boolean nextBoolean() { + clearCaches(); + return Boolean.parseBoolean(next(boolPattern())); + } + + /** + * Returns true if the next token in this scanner's input can be + * interpreted as a byte value in the default radix using the + * {@link #nextByte} method. The scanner does not advance past any input. + * + * @return true if and only if this scanner's next token is a valid + * byte value + * @throws IllegalStateException if this scanner is closed + */ + public boolean hasNextByte() { + return hasNextByte(defaultRadix); + } + + /** + * Returns true if the next token in this scanner's input can be + * interpreted as a byte value in the specified radix using the + * {@link #nextByte} method. The scanner does not advance past any input. + * + * @param radix the radix used to interpret the token as a byte value + * @return true if and only if this scanner's next token is a valid + * byte value + * @throws IllegalStateException if this scanner is closed + */ + public boolean hasNextByte(int radix) { + setRadix(radix); + boolean result = hasNext(integerPattern()); + if (result) { // Cache it + try { + String s = (matcher.group(SIMPLE_GROUP_INDEX) == null) ? + processIntegerToken(hasNextResult) : + hasNextResult; + typeCache = Byte.parseByte(s, radix); + } catch (NumberFormatException nfe) { + result = false; + } + } + return result; + } + + /** + * Scans the next token of the input as a <tt>byte</tt>. + * + * <p> An invocation of this method of the form + * <tt>nextByte()</tt> behaves in exactly the same way as the + * invocation <tt>nextByte(radix)</tt>, where <code>radix</code> + * is the default radix of this scanner. + * + * @return the <tt>byte</tt> scanned from the input + * @throws InputMismatchException + * if the next token does not match the <i>Integer</i> + * regular expression, or is out of range + * @throws NoSuchElementException if input is exhausted + * @throws IllegalStateException if this scanner is closed + */ + public byte nextByte() { + return nextByte(defaultRadix); + } + + /** + * Scans the next token of the input as a <tt>byte</tt>. + * This method will throw <code>InputMismatchException</code> + * if the next token cannot be translated into a valid byte value as + * described below. If the translation is successful, the scanner advances + * past the input that matched. + * + * <p> If the next token matches the <a + * href="#Integer-regex"><i>Integer</i></a> regular expression defined + * above then the token is converted into a <tt>byte</tt> value as if by + * removing all locale specific prefixes, group separators, and locale + * specific suffixes, then mapping non-ASCII digits into ASCII + * digits via {@link Character#digit Character.digit}, prepending a + * negative sign (-) if the locale specific negative prefixes and suffixes + * were present, and passing the resulting string to + * {@link Byte#parseByte(String, int) Byte.parseByte} with the + * specified radix. + * + * @param radix the radix used to interpret the token as a byte value + * @return the <tt>byte</tt> scanned from the input + * @throws InputMismatchException + * if the next token does not match the <i>Integer</i> + * regular expression, or is out of range + * @throws NoSuchElementException if input is exhausted + * @throws IllegalStateException if this scanner is closed + */ + public byte nextByte(int radix) { + // Check cached result + if ((typeCache != null) && (typeCache instanceof Byte) + && this.radix == radix) { + byte val = ((Byte)typeCache).byteValue(); + useTypeCache(); + return val; + } + setRadix(radix); + clearCaches(); + // Search for next byte + try { + String s = next(integerPattern()); + if (matcher.group(SIMPLE_GROUP_INDEX) == null) + s = processIntegerToken(s); + return Byte.parseByte(s, radix); + } catch (NumberFormatException nfe) { + position = matcher.start(); // don't skip bad token + throw new InputMismatchException(nfe.getMessage()); + } + } + + /** + * Returns true if the next token in this scanner's input can be + * interpreted as a short value in the default radix using the + * {@link #nextShort} method. The scanner does not advance past any input. + * + * @return true if and only if this scanner's next token is a valid + * short value in the default radix + * @throws IllegalStateException if this scanner is closed + */ + public boolean hasNextShort() { + return hasNextShort(defaultRadix); + } + + /** + * Returns true if the next token in this scanner's input can be + * interpreted as a short value in the specified radix using the + * {@link #nextShort} method. The scanner does not advance past any input. + * + * @param radix the radix used to interpret the token as a short value + * @return true if and only if this scanner's next token is a valid + * short value in the specified radix + * @throws IllegalStateException if this scanner is closed + */ + public boolean hasNextShort(int radix) { + setRadix(radix); + boolean result = hasNext(integerPattern()); + if (result) { // Cache it + try { + String s = (matcher.group(SIMPLE_GROUP_INDEX) == null) ? + processIntegerToken(hasNextResult) : + hasNextResult; + typeCache = Short.parseShort(s, radix); + } catch (NumberFormatException nfe) { + result = false; + } + } + return result; + } + + /** + * Scans the next token of the input as a <tt>short</tt>. + * + * <p> An invocation of this method of the form + * <tt>nextShort()</tt> behaves in exactly the same way as the + * invocation <tt>nextShort(radix)</tt>, where <code>radix</code> + * is the default radix of this scanner. + * + * @return the <tt>short</tt> scanned from the input + * @throws InputMismatchException + * if the next token does not match the <i>Integer</i> + * regular expression, or is out of range + * @throws NoSuchElementException if input is exhausted + * @throws IllegalStateException if this scanner is closed + */ + public short nextShort() { + return nextShort(defaultRadix); + } + + /** + * Scans the next token of the input as a <tt>short</tt>. + * This method will throw <code>InputMismatchException</code> + * if the next token cannot be translated into a valid short value as + * described below. If the translation is successful, the scanner advances + * past the input that matched. + * + * <p> If the next token matches the <a + * href="#Integer-regex"><i>Integer</i></a> regular expression defined + * above then the token is converted into a <tt>short</tt> value as if by + * removing all locale specific prefixes, group separators, and locale + * specific suffixes, then mapping non-ASCII digits into ASCII + * digits via {@link Character#digit Character.digit}, prepending a + * negative sign (-) if the locale specific negative prefixes and suffixes + * were present, and passing the resulting string to + * {@link Short#parseShort(String, int) Short.parseShort} with the + * specified radix. + * + * @param radix the radix used to interpret the token as a short value + * @return the <tt>short</tt> scanned from the input + * @throws InputMismatchException + * if the next token does not match the <i>Integer</i> + * regular expression, or is out of range + * @throws NoSuchElementException if input is exhausted + * @throws IllegalStateException if this scanner is closed + */ + public short nextShort(int radix) { + // Check cached result + if ((typeCache != null) && (typeCache instanceof Short) + && this.radix == radix) { + short val = ((Short)typeCache).shortValue(); + useTypeCache(); + return val; + } + setRadix(radix); + clearCaches(); + // Search for next short + try { + String s = next(integerPattern()); + if (matcher.group(SIMPLE_GROUP_INDEX) == null) + s = processIntegerToken(s); + return Short.parseShort(s, radix); + } catch (NumberFormatException nfe) { + position = matcher.start(); // don't skip bad token + throw new InputMismatchException(nfe.getMessage()); + } + } + + /** + * Returns true if the next token in this scanner's input can be + * interpreted as an int value in the default radix using the + * {@link #nextInt} method. The scanner does not advance past any input. + * + * @return true if and only if this scanner's next token is a valid + * int value + * @throws IllegalStateException if this scanner is closed + */ + public boolean hasNextInt() { + return hasNextInt(defaultRadix); + } + + /** + * Returns true if the next token in this scanner's input can be + * interpreted as an int value in the specified radix using the + * {@link #nextInt} method. The scanner does not advance past any input. + * + * @param radix the radix used to interpret the token as an int value + * @return true if and only if this scanner's next token is a valid + * int value + * @throws IllegalStateException if this scanner is closed + */ + public boolean hasNextInt(int radix) { + setRadix(radix); + boolean result = hasNext(integerPattern()); + if (result) { // Cache it + try { + String s = (matcher.group(SIMPLE_GROUP_INDEX) == null) ? + processIntegerToken(hasNextResult) : + hasNextResult; + typeCache = Integer.parseInt(s, radix); + } catch (NumberFormatException nfe) { + result = false; + } + } + return result; + } + + /** + * The integer token must be stripped of prefixes, group separators, + * and suffixes, non ascii digits must be converted into ascii digits + * before parse will accept it. + */ + private String processIntegerToken(String token) { + String result = token.replaceAll(""+groupSeparator, ""); + boolean isNegative = false; + int preLen = negativePrefix.length(); + if ((preLen > 0) && result.startsWith(negativePrefix)) { + isNegative = true; + result = result.substring(preLen); + } + int sufLen = negativeSuffix.length(); + if ((sufLen > 0) && result.endsWith(negativeSuffix)) { + isNegative = true; + result = result.substring(result.length() - sufLen, + result.length()); + } + if (isNegative) + result = "-" + result; + return result; + } + + /** + * Scans the next token of the input as an <tt>int</tt>. + * + * <p> An invocation of this method of the form + * <tt>nextInt()</tt> behaves in exactly the same way as the + * invocation <tt>nextInt(radix)</tt>, where <code>radix</code> + * is the default radix of this scanner. + * + * @return the <tt>int</tt> scanned from the input + * @throws InputMismatchException + * if the next token does not match the <i>Integer</i> + * regular expression, or is out of range + * @throws NoSuchElementException if input is exhausted + * @throws IllegalStateException if this scanner is closed + */ + public int nextInt() { + return nextInt(defaultRadix); + } + + /** + * Scans the next token of the input as an <tt>int</tt>. + * This method will throw <code>InputMismatchException</code> + * if the next token cannot be translated into a valid int value as + * described below. If the translation is successful, the scanner advances + * past the input that matched. + * + * <p> If the next token matches the <a + * href="#Integer-regex"><i>Integer</i></a> regular expression defined + * above then the token is converted into an <tt>int</tt> value as if by + * removing all locale specific prefixes, group separators, and locale + * specific suffixes, then mapping non-ASCII digits into ASCII + * digits via {@link Character#digit Character.digit}, prepending a + * negative sign (-) if the locale specific negative prefixes and suffixes + * were present, and passing the resulting string to + * {@link Integer#parseInt(String, int) Integer.parseInt} with the + * specified radix. + * + * @param radix the radix used to interpret the token as an int value + * @return the <tt>int</tt> scanned from the input + * @throws InputMismatchException + * if the next token does not match the <i>Integer</i> + * regular expression, or is out of range + * @throws NoSuchElementException if input is exhausted + * @throws IllegalStateException if this scanner is closed + */ + public int nextInt(int radix) { + // Check cached result + if ((typeCache != null) && (typeCache instanceof Integer) + && this.radix == radix) { + int val = ((Integer)typeCache).intValue(); + useTypeCache(); + return val; + } + setRadix(radix); + clearCaches(); + // Search for next int + try { + String s = next(integerPattern()); + if (matcher.group(SIMPLE_GROUP_INDEX) == null) + s = processIntegerToken(s); + return Integer.parseInt(s, radix); + } catch (NumberFormatException nfe) { + position = matcher.start(); // don't skip bad token + throw new InputMismatchException(nfe.getMessage()); + } + } + + /** + * Returns true if the next token in this scanner's input can be + * interpreted as a long value in the default radix using the + * {@link #nextLong} method. The scanner does not advance past any input. + * + * @return true if and only if this scanner's next token is a valid + * long value + * @throws IllegalStateException if this scanner is closed + */ + public boolean hasNextLong() { + return hasNextLong(defaultRadix); + } + + /** + * Returns true if the next token in this scanner's input can be + * interpreted as a long value in the specified radix using the + * {@link #nextLong} method. The scanner does not advance past any input. + * + * @param radix the radix used to interpret the token as a long value + * @return true if and only if this scanner's next token is a valid + * long value + * @throws IllegalStateException if this scanner is closed + */ + public boolean hasNextLong(int radix) { + setRadix(radix); + boolean result = hasNext(integerPattern()); + if (result) { // Cache it + try { + String s = (matcher.group(SIMPLE_GROUP_INDEX) == null) ? + processIntegerToken(hasNextResult) : + hasNextResult; + typeCache = Long.parseLong(s, radix); + } catch (NumberFormatException nfe) { + result = false; + } + } + return result; + } + + /** + * Scans the next token of the input as a <tt>long</tt>. + * + * <p> An invocation of this method of the form + * <tt>nextLong()</tt> behaves in exactly the same way as the + * invocation <tt>nextLong(radix)</tt>, where <code>radix</code> + * is the default radix of this scanner. + * + * @return the <tt>long</tt> scanned from the input + * @throws InputMismatchException + * if the next token does not match the <i>Integer</i> + * regular expression, or is out of range + * @throws NoSuchElementException if input is exhausted + * @throws IllegalStateException if this scanner is closed + */ + public long nextLong() { + return nextLong(defaultRadix); + } + + /** + * Scans the next token of the input as a <tt>long</tt>. + * This method will throw <code>InputMismatchException</code> + * if the next token cannot be translated into a valid long value as + * described below. If the translation is successful, the scanner advances + * past the input that matched. + * + * <p> If the next token matches the <a + * href="#Integer-regex"><i>Integer</i></a> regular expression defined + * above then the token is converted into a <tt>long</tt> value as if by + * removing all locale specific prefixes, group separators, and locale + * specific suffixes, then mapping non-ASCII digits into ASCII + * digits via {@link Character#digit Character.digit}, prepending a + * negative sign (-) if the locale specific negative prefixes and suffixes + * were present, and passing the resulting string to + * {@link Long#parseLong(String, int) Long.parseLong} with the + * specified radix. + * + * @param radix the radix used to interpret the token as an int value + * @return the <tt>long</tt> scanned from the input + * @throws InputMismatchException + * if the next token does not match the <i>Integer</i> + * regular expression, or is out of range + * @throws NoSuchElementException if input is exhausted + * @throws IllegalStateException if this scanner is closed + */ + public long nextLong(int radix) { + // Check cached result + if ((typeCache != null) && (typeCache instanceof Long) + && this.radix == radix) { + long val = ((Long)typeCache).longValue(); + useTypeCache(); + return val; + } + setRadix(radix); + clearCaches(); + try { + String s = next(integerPattern()); + if (matcher.group(SIMPLE_GROUP_INDEX) == null) + s = processIntegerToken(s); + return Long.parseLong(s, radix); + } catch (NumberFormatException nfe) { + position = matcher.start(); // don't skip bad token + throw new InputMismatchException(nfe.getMessage()); + } + } + + /** + * The float token must be stripped of prefixes, group separators, + * and suffixes, non ascii digits must be converted into ascii digits + * before parseFloat will accept it. + * + * If there are non-ascii digits in the token these digits must + * be processed before the token is passed to parseFloat. + */ + private String processFloatToken(String token) { + String result = token.replaceAll(groupSeparator, ""); + if (!decimalSeparator.equals("\\.")) + result = result.replaceAll(decimalSeparator, "."); + boolean isNegative = false; + int preLen = negativePrefix.length(); + if ((preLen > 0) && result.startsWith(negativePrefix)) { + isNegative = true; + result = result.substring(preLen); + } + int sufLen = negativeSuffix.length(); + if ((sufLen > 0) && result.endsWith(negativeSuffix)) { + isNegative = true; + result = result.substring(result.length() - sufLen, + result.length()); + } + if (result.equals(nanString)) + result = "NaN"; + if (result.equals(infinityString)) + result = "Infinity"; + if (isNegative) + result = "-" + result; + + // Translate non-ASCII digits + Matcher m = NON_ASCII_DIGIT.matcher(result); + if (m.find()) { + StringBuilder inASCII = new StringBuilder(); + for (int i=0; i<result.length(); i++) { + char nextChar = result.charAt(i); + if (Character.isDigit(nextChar)) { + int d = Character.digit(nextChar, 10); + if (d != -1) + inASCII.append(d); + else + inASCII.append(nextChar); + } else { + inASCII.append(nextChar); + } + } + result = inASCII.toString(); + } + + return result; + } + + /** + * Returns true if the next token in this scanner's input can be + * interpreted as a float value using the {@link #nextFloat} + * method. The scanner does not advance past any input. + * + * @return true if and only if this scanner's next token is a valid + * float value + * @throws IllegalStateException if this scanner is closed + */ + public boolean hasNextFloat() { + setRadix(10); + boolean result = hasNext(floatPattern()); + if (result) { // Cache it + try { + String s = processFloatToken(hasNextResult); + typeCache = Float.valueOf(Float.parseFloat(s)); + } catch (NumberFormatException nfe) { + result = false; + } + } + return result; + } + + /** + * Scans the next token of the input as a <tt>float</tt>. + * This method will throw <code>InputMismatchException</code> + * if the next token cannot be translated into a valid float value as + * described below. If the translation is successful, the scanner advances + * past the input that matched. + * + * <p> If the next token matches the <a + * href="#Float-regex"><i>Float</i></a> regular expression defined above + * then the token is converted into a <tt>float</tt> value as if by + * removing all locale specific prefixes, group separators, and locale + * specific suffixes, then mapping non-ASCII digits into ASCII + * digits via {@link Character#digit Character.digit}, prepending a + * negative sign (-) if the locale specific negative prefixes and suffixes + * were present, and passing the resulting string to + * {@link Float#parseFloat Float.parseFloat}. If the token matches + * the localized NaN or infinity strings, then either "Nan" or "Infinity" + * is passed to {@link Float#parseFloat(String) Float.parseFloat} as + * appropriate. + * + * @return the <tt>float</tt> scanned from the input + * @throws InputMismatchException + * if the next token does not match the <i>Float</i> + * regular expression, or is out of range + * @throws NoSuchElementException if input is exhausted + * @throws IllegalStateException if this scanner is closed + */ + public float nextFloat() { + // Check cached result + if ((typeCache != null) && (typeCache instanceof Float)) { + float val = ((Float)typeCache).floatValue(); + useTypeCache(); + return val; + } + setRadix(10); + clearCaches(); + try { + return Float.parseFloat(processFloatToken(next(floatPattern()))); + } catch (NumberFormatException nfe) { + position = matcher.start(); // don't skip bad token + throw new InputMismatchException(nfe.getMessage()); + } + } + + /** + * Returns true if the next token in this scanner's input can be + * interpreted as a double value using the {@link #nextDouble} + * method. The scanner does not advance past any input. + * + * @return true if and only if this scanner's next token is a valid + * double value + * @throws IllegalStateException if this scanner is closed + */ + public boolean hasNextDouble() { + setRadix(10); + boolean result = hasNext(floatPattern()); + if (result) { // Cache it + try { + String s = processFloatToken(hasNextResult); + typeCache = Double.valueOf(Double.parseDouble(s)); + } catch (NumberFormatException nfe) { + result = false; + } + } + return result; + } + + /** + * Scans the next token of the input as a <tt>double</tt>. + * This method will throw <code>InputMismatchException</code> + * if the next token cannot be translated into a valid double value. + * If the translation is successful, the scanner advances past the input + * that matched. + * + * <p> If the next token matches the <a + * href="#Float-regex"><i>Float</i></a> regular expression defined above + * then the token is converted into a <tt>double</tt> value as if by + * removing all locale specific prefixes, group separators, and locale + * specific suffixes, then mapping non-ASCII digits into ASCII + * digits via {@link Character#digit Character.digit}, prepending a + * negative sign (-) if the locale specific negative prefixes and suffixes + * were present, and passing the resulting string to + * {@link Double#parseDouble Double.parseDouble}. If the token matches + * the localized NaN or infinity strings, then either "Nan" or "Infinity" + * is passed to {@link Double#parseDouble(String) Double.parseDouble} as + * appropriate. + * + * @return the <tt>double</tt> scanned from the input + * @throws InputMismatchException + * if the next token does not match the <i>Float</i> + * regular expression, or is out of range + * @throws NoSuchElementException if the input is exhausted + * @throws IllegalStateException if this scanner is closed + */ + public double nextDouble() { + // Check cached result + if ((typeCache != null) && (typeCache instanceof Double)) { + double val = ((Double)typeCache).doubleValue(); + useTypeCache(); + return val; + } + setRadix(10); + clearCaches(); + // Search for next float + try { + return Double.parseDouble(processFloatToken(next(floatPattern()))); + } catch (NumberFormatException nfe) { + position = matcher.start(); // don't skip bad token + throw new InputMismatchException(nfe.getMessage()); + } + } + + // Convenience methods for scanning multi precision numbers + + /** + * Returns true if the next token in this scanner's input can be + * interpreted as a <code>BigInteger</code> in the default radix using the + * {@link #nextBigInteger} method. The scanner does not advance past any + * input. + * + * @return true if and only if this scanner's next token is a valid + * <code>BigInteger</code> + * @throws IllegalStateException if this scanner is closed + */ + public boolean hasNextBigInteger() { + return hasNextBigInteger(defaultRadix); + } + + /** + * Returns true if the next token in this scanner's input can be + * interpreted as a <code>BigInteger</code> in the specified radix using + * the {@link #nextBigInteger} method. The scanner does not advance past + * any input. + * + * @param radix the radix used to interpret the token as an integer + * @return true if and only if this scanner's next token is a valid + * <code>BigInteger</code> + * @throws IllegalStateException if this scanner is closed + */ + public boolean hasNextBigInteger(int radix) { + setRadix(radix); + boolean result = hasNext(integerPattern()); + if (result) { // Cache it + try { + String s = (matcher.group(SIMPLE_GROUP_INDEX) == null) ? + processIntegerToken(hasNextResult) : + hasNextResult; + typeCache = new BigInteger(s, radix); + } catch (NumberFormatException nfe) { + result = false; + } + } + return result; + } + + /** + * Scans the next token of the input as a {@link java.math.BigInteger + * BigInteger}. + * + * <p> An invocation of this method of the form + * <tt>nextBigInteger()</tt> behaves in exactly the same way as the + * invocation <tt>nextBigInteger(radix)</tt>, where <code>radix</code> + * is the default radix of this scanner. + * + * @return the <tt>BigInteger</tt> scanned from the input + * @throws InputMismatchException + * if the next token does not match the <i>Integer</i> + * regular expression, or is out of range + * @throws NoSuchElementException if the input is exhausted + * @throws IllegalStateException if this scanner is closed + */ + public BigInteger nextBigInteger() { + return nextBigInteger(defaultRadix); + } + + /** + * Scans the next token of the input as a {@link java.math.BigInteger + * BigInteger}. + * + * <p> If the next token matches the <a + * href="#Integer-regex"><i>Integer</i></a> regular expression defined + * above then the token is converted into a <tt>BigInteger</tt> value as if + * by removing all group separators, mapping non-ASCII digits into ASCII + * digits via the {@link Character#digit Character.digit}, and passing the + * resulting string to the {@link + * java.math.BigInteger#BigInteger(java.lang.String) + * BigInteger(String, int)} constructor with the specified radix. + * + * @param radix the radix used to interpret the token + * @return the <tt>BigInteger</tt> scanned from the input + * @throws InputMismatchException + * if the next token does not match the <i>Integer</i> + * regular expression, or is out of range + * @throws NoSuchElementException if the input is exhausted + * @throws IllegalStateException if this scanner is closed + */ + public BigInteger nextBigInteger(int radix) { + // Check cached result + if ((typeCache != null) && (typeCache instanceof BigInteger) + && this.radix == radix) { + BigInteger val = (BigInteger)typeCache; + useTypeCache(); + return val; + } + setRadix(radix); + clearCaches(); + // Search for next int + try { + String s = next(integerPattern()); + if (matcher.group(SIMPLE_GROUP_INDEX) == null) + s = processIntegerToken(s); + return new BigInteger(s, radix); + } catch (NumberFormatException nfe) { + position = matcher.start(); // don't skip bad token + throw new InputMismatchException(nfe.getMessage()); + } + } + + /** + * Returns true if the next token in this scanner's input can be + * interpreted as a <code>BigDecimal</code> using the + * {@link #nextBigDecimal} method. The scanner does not advance past any + * input. + * + * @return true if and only if this scanner's next token is a valid + * <code>BigDecimal</code> + * @throws IllegalStateException if this scanner is closed + */ + public boolean hasNextBigDecimal() { + setRadix(10); + boolean result = hasNext(decimalPattern()); + if (result) { // Cache it + try { + String s = processFloatToken(hasNextResult); + typeCache = new BigDecimal(s); + } catch (NumberFormatException nfe) { + result = false; + } + } + return result; + } + + /** + * Scans the next token of the input as a {@link java.math.BigDecimal + * BigDecimal}. + * + * <p> If the next token matches the <a + * href="#Decimal-regex"><i>Decimal</i></a> regular expression defined + * above then the token is converted into a <tt>BigDecimal</tt> value as if + * by removing all group separators, mapping non-ASCII digits into ASCII + * digits via the {@link Character#digit Character.digit}, and passing the + * resulting string to the {@link + * java.math.BigDecimal#BigDecimal(java.lang.String) BigDecimal(String)} + * constructor. + * + * @return the <tt>BigDecimal</tt> scanned from the input + * @throws InputMismatchException + * if the next token does not match the <i>Decimal</i> + * regular expression, or is out of range + * @throws NoSuchElementException if the input is exhausted + * @throws IllegalStateException if this scanner is closed + */ + public BigDecimal nextBigDecimal() { + // Check cached result + if ((typeCache != null) && (typeCache instanceof BigDecimal)) { + BigDecimal val = (BigDecimal)typeCache; + useTypeCache(); + return val; + } + setRadix(10); + clearCaches(); + // Search for next float + try { + String s = processFloatToken(next(decimalPattern())); + return new BigDecimal(s); + } catch (NumberFormatException nfe) { + position = matcher.start(); // don't skip bad token + throw new InputMismatchException(nfe.getMessage()); + } + } + + /** + * Resets this scanner. + * + * <p> Resetting a scanner discards all of its explicit state + * information which may have been changed by invocations of {@link + * #useDelimiter}, {@link #useLocale}, or {@link #useRadix}. + * + * <p> An invocation of this method of the form + * <tt>scanner.reset()</tt> behaves in exactly the same way as the + * invocation + * + * <blockquote><pre> + * scanner.useDelimiter("\\p{javaWhitespace}+") + * .useLocale(Locale.getDefault()) + * .useRadix(10); + * </pre></blockquote> + * + * @return this scanner + * + * @since 1.6 + */ + public Scanner reset() { + delimPattern = WHITESPACE_PATTERN; + useLocale(Locale.getDefault()); + useRadix(10); + clearCaches(); + return this; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/overlays/nio2/openjdk/jdk/src/share/classes/java/util/concurrent/ScheduledThreadPoolExecutor.java Fri Feb 13 20:38:41 2009 +0000 @@ -0,0 +1,1371 @@ +/* + * 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * This file is available under and governed by the GNU General Public + * License version 2 only, as published by the Free Software Foundation. + * However, the following notice accompanied the original version of this + * file: + * + * Written by Doug Lea with assistance from members of JCP JSR-166 + * Expert Group and released to the public domain, as explained at + * http://creativecommons.org/licenses/publicdomain + */ + +package org.classpath.icedtea.java.util.concurrent; + +import java.util.*; + +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.Callable; +import java.util.concurrent.Delayed; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.FutureTask; +import java.util.concurrent.RejectedExecutionHandler; +import java.util.concurrent.RunnableScheduledFuture; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.ThreadPoolExecutor; + +import java.util.concurrent.atomic.*; +import java.util.concurrent.locks.*; + +import org.classpath.icedtea.misc.JavaUtilConcurrentThreadPoolExecutorAccess; +import org.classpath.icedtea.misc.SharedSecrets; + +/** + * A {@link ThreadPoolExecutor} that can additionally schedule + * commands to run after a given delay, or to execute + * periodically. This class is preferable to {@link java.util.Timer} + * when multiple worker threads are needed, or when the additional + * flexibility or capabilities of {@link ThreadPoolExecutor} (which + * this class extends) are required. + * + * <p>Delayed tasks execute no sooner than they are enabled, but + * without any real-time guarantees about when, after they are + * enabled, they will commence. Tasks scheduled for exactly the same + * execution time are enabled in first-in-first-out (FIFO) order of + * submission. + * + * <p>When a submitted task is cancelled before it is run, execution + * is suppressed. By default, such a cancelled task is not + * automatically removed from the work queue until its delay + * elapses. While this enables further inspection and monitoring, it + * may also cause unbounded retention of cancelled tasks. To avoid + * this, set {@link #setRemoveOnCancelPolicy} to {@code true}, which + * causes tasks to be immediately removed from the work queue at + * time of cancellation. + * + * <p>While this class inherits from {@link ThreadPoolExecutor}, a few + * of the inherited tuning methods are not useful for it. In + * particular, because it acts as a fixed-sized pool using + * {@code corePoolSize} threads and an unbounded queue, adjustments + * to {@code maximumPoolSize} have no useful effect. Additionally, it + * is almost never a good idea to set {@code corePoolSize} to zero or + * use {@code allowCoreThreadTimeOut} because this may leave the pool + * without threads to handle tasks once they become eligible to run. + * + * <p><b>Extension notes:</b> This class overrides the + * {@link ThreadPoolExecutor#execute execute} and + * {@link AbstractExecutorService#submit(Runnable) submit} + * methods to generate internal {@link ScheduledFuture} objects to + * control per-task delays and scheduling. To preserve + * functionality, any further overrides of these methods in + * subclasses must invoke superclass versions, which effectively + * disables additional task customization. However, this class + * provides alternative protected extension method + * {@code decorateTask} (one version each for {@code Runnable} and + * {@code Callable}) that can be used to customize the concrete task + * types used to execute commands entered via {@code execute}, + * {@code submit}, {@code schedule}, {@code scheduleAtFixedRate}, + * and {@code scheduleWithFixedDelay}. By default, a + * {@code ScheduledThreadPoolExecutor} uses a task type extending + * {@link FutureTask}. However, this may be modified or replaced using + * subclasses of the form: + * + * <pre> {@code + * public class CustomScheduledExecutor extends ScheduledThreadPoolExecutor { + * + * static class CustomTask<V> implements RunnableScheduledFuture<V> { ... } + * + * protected <V> RunnableScheduledFuture<V> decorateTask( + * Runnable r, RunnableScheduledFuture<V> task) { + * return new CustomTask<V>(r, task); + * } + * + * protected <V> RunnableScheduledFuture<V> decorateTask( + * Callable<V> c, RunnableScheduledFuture<V> task) { + * return new CustomTask<V>(c, task); + * } + * // ... add constructors, etc. + * }}</pre> + * + * @since 1.5 + * @author Doug Lea + */ +public class ScheduledThreadPoolExecutor + extends ThreadPoolExecutor + implements ScheduledExecutorService { + + /* + * This class specializes ThreadPoolExecutor implementation by + * + * 1. Using a custom task type, ScheduledFutureTask for + * tasks, even those that don't require scheduling (i.e., + * those submitted using ExecutorService execute, not + * ScheduledExecutorService methods) which are treated as + * delayed tasks with a delay of zero. + * + * 2. Using a custom queue (DelayedWorkQueue), a variant of + * unbounded DelayQueue. The lack of capacity constraint and + * the fact that corePoolSize and maximumPoolSize are + * effectively identical simplifies some execution mechanics + * (see delayedExecute) compared to ThreadPoolExecutor. + * + * 3. Supporting optional run-after-shutdown parameters, which + * leads to overrides of shutdown methods to remove and cancel + * tasks that should NOT be run after shutdown, as well as + * different recheck logic when task (re)submission overlaps + * with a shutdown. + * + * 4. Task decoration methods to allow interception and + * instrumentation, which are needed because subclasses cannot + * otherwise override submit methods to get this effect. These + * don't have any impact on pool control logic though. + */ + + /** + * False if should cancel/suppress periodic tasks on shutdown. + */ + private volatile boolean continueExistingPeriodicTasksAfterShutdown; + + /** + * False if should cancel non-periodic tasks on shutdown. + */ + private volatile boolean executeExistingDelayedTasksAfterShutdown = true; + + /** + * True if ScheduledFutureTask.cancel should remove from queue + */ + private volatile boolean removeOnCancel = false; + + /** + * Sequence number to break scheduling ties, and in turn to + * guarantee FIFO order among tied entries. + */ + private static final AtomicLong sequencer = new AtomicLong(0); + + /** + * Returns current nanosecond time. + */ + final long now() { + return System.nanoTime(); + } + + private class ScheduledFutureTask<V> + extends FutureTask<V> implements RunnableScheduledFuture<V> { + + /** Sequence number to break ties FIFO */ + private final long sequenceNumber; + + /** The time the task is enabled to execute in nanoTime units */ + private long time; + + /** + * Period in nanoseconds for repeating tasks. A positive + * value indicates fixed-rate execution. A negative value + * indicates fixed-delay execution. A value of 0 indicates a + * non-repeating task. + */ + private final long period; + + /** The actual task to be re-enqueued by reExecutePeriodic */ + RunnableScheduledFuture<V> outerTask = this; + + /** + * Index into delay queue, to support faster cancellation. + */ + int heapIndex; + + /** + * Creates a one-shot action with given nanoTime-based trigger time. + */ + ScheduledFutureTask(Runnable r, V result, long ns) { + super(r, result); + this.time = ns; + this.period = 0; + this.sequenceNumber = sequencer.getAndIncrement(); + } + + /** + * Creates a periodic action with given nano time and period. + */ + ScheduledFutureTask(Runnable r, V result, long ns, long period) { + super(r, result); + this.time = ns; + this.period = period; + this.sequenceNumber = sequencer.getAndIncrement(); + } + + /** + * Creates a one-shot action with given nanoTime-based trigger. + */ + ScheduledFutureTask(Callable<V> callable, long ns) { + super(callable); + this.time = ns; + this.period = 0; + this.sequenceNumber = sequencer.getAndIncrement(); + } + + public long getDelay(TimeUnit unit) { + return unit.convert(time - now(), TimeUnit.NANOSECONDS); + } + + public int compareTo(Delayed other) { + if (other == this) // compare zero ONLY if same object + return 0; + if (other instanceof ScheduledFutureTask) { + ScheduledFutureTask<?> x = (ScheduledFutureTask<?>)other; + long diff = time - x.time; + if (diff < 0) + return -1; + else if (diff > 0) + return 1; + else if (sequenceNumber < x.sequenceNumber) + return -1; + else + return 1; + } + long d = (getDelay(TimeUnit.NANOSECONDS) - + other.getDelay(TimeUnit.NANOSECONDS)); + return (d == 0) ? 0 : ((d < 0) ? -1 : 1); + } + + /** + * Returns true if this is a periodic (not a one-shot) action. + * + * @return true if periodic + */ + public boolean isPeriodic() { + return period != 0; + } + + /** + * Sets the next time to run for a periodic task. + */ + private void setNextRunTime() { + long p = period; + if (p > 0) + time += p; + else + time = triggerTime(-p); + } + + public boolean cancel(boolean mayInterruptIfRunning) { + boolean cancelled = super.cancel(mayInterruptIfRunning); + if (cancelled && removeOnCancel && heapIndex >= 0) + remove(this); + return cancelled; + } + + /** + * Overrides FutureTask version so as to reset/requeue if periodic. + */ + public void run() { + boolean periodic = isPeriodic(); + if (!canRunInCurrentRunState(periodic)) + cancel(false); + else if (!periodic) + ScheduledFutureTask.super.run(); + else if (ScheduledFutureTask.super.runAndReset()) { + setNextRunTime(); + reExecutePeriodic(outerTask); + } + } + } + + /** + * Returns true if can run a task given current run state + * and run-after-shutdown parameters. + * + * @param periodic true if this task periodic, false if delayed + */ + boolean canRunInCurrentRunState(boolean periodic) { + return isRunningOrShutdownSTPE(periodic ? + continueExistingPeriodicTasksAfterShutdown : + executeExistingDelayedTasksAfterShutdown); + } + + /** + * Main execution method for delayed or periodic tasks. If pool + * is shut down, rejects the task. Otherwise adds task to queue + * and starts a thread, if necessary, to run it. (We cannot + * prestart the thread to run the task because the task (probably) + * shouldn't be run yet,) If the pool is shut down while the task + * is being added, cancel and remove it if required by state and + * run-after-shutdown parameters. + * + * @param task the task + */ + private void delayedExecute(RunnableScheduledFuture<?> task) { + if (isShutdown()) + rejectSTPE(task); + else { + super.getQueue().add(task); + if (isShutdown() && + !canRunInCurrentRunState(task.isPeriodic()) && + remove(task)) + task.cancel(false); + else + prestartCoreThread(); + } + } + + /** + * Requeues a periodic task unless current run state precludes it. + * Same idea as delayedExecute except drops task rather than rejecting. + * + * @param task the task + */ + void reExecutePeriodic(RunnableScheduledFuture<?> task) { + if (canRunInCurrentRunState(true)) { + super.getQueue().add(task); + if (!canRunInCurrentRunState(true) && remove(task)) + task.cancel(false); + else + prestartCoreThread(); + } + } + + /** + * Cancels and clears the queue of all tasks that should not be run + * due to shutdown policy. Invoked within super.shutdown. + */ + void onShutdown() { + BlockingQueue<Runnable> q = super.getQueue(); + boolean keepDelayed = + getExecuteExistingDelayedTasksAfterShutdownPolicy(); + boolean keepPeriodic = + getContinueExistingPeriodicTasksAfterShutdownPolicy(); + if (!keepDelayed && !keepPeriodic) + q.clear(); + else { + // Traverse snapshot to avoid iterator exceptions + for (Object e : q.toArray()) { + if (e instanceof RunnableScheduledFuture) { + RunnableScheduledFuture<?> t = + (RunnableScheduledFuture<?>)e; + if ((t.isPeriodic() ? !keepPeriodic : !keepDelayed) || + t.isCancelled()) { // also remove if already cancelled + if (q.remove(t)) + t.cancel(false); + } + } + } + } + tryTerminateSTPE(); + } + + /** + * Modifies or replaces the task used to execute a runnable. + * This method can be used to override the concrete + * class used for managing internal tasks. + * The default implementation simply returns the given task. + * + * @param runnable the submitted Runnable + * @param task the task created to execute the runnable + * @return a task that can execute the runnable + * @since 1.6 + */ + protected <V> RunnableScheduledFuture<V> decorateTask( + Runnable runnable, RunnableScheduledFuture<V> task) { + return task; + } + + /** + * Modifies or replaces the task used to execute a callable. + * This method can be used to override the concrete + * class used for managing internal tasks. + * The default implementation simply returns the given task. + * + * @param callable the submitted Callable + * @param task the task created to execute the callable + * @return a task that can execute the callable + * @since 1.6 + */ + protected <V> RunnableScheduledFuture<V> decorateTask( + Callable<V> callable, RunnableScheduledFuture<V> task) { + return task; + } + + /** + * Creates a new {@code ScheduledThreadPoolExecutor} with the + * given core pool size. + * + * @param corePoolSize the number of threads to keep in the pool, even + * if they are idle, unless {@code allowCoreThreadTimeOut} is set + * @throws IllegalArgumentException if {@code corePoolSize < 0} + */ + public ScheduledThreadPoolExecutor(int corePoolSize) { + super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS, + new DelayedWorkQueue()); + } + + /** + * Creates a new {@code ScheduledThreadPoolExecutor} with the + * given initial parameters. + * + * @param corePoolSize the number of threads to keep in the pool, even + * if they are idle, unless {@code allowCoreThreadTimeOut} is set + * @param threadFactory the factory to use when the executor + * creates a new thread + * @throws IllegalArgumentException if {@code corePoolSize < 0} + * @throws NullPointerException if {@code threadFactory} is null + */ + public ScheduledThreadPoolExecutor(int corePoolSize, + ThreadFactory threadFactory) { + super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS, + new DelayedWorkQueue(), threadFactory); + } + + /** + * Creates a new ScheduledThreadPoolExecutor with the given + * initial parameters. + * + * @param corePoolSize the number of threads to keep in the pool, even + * if they are idle, unless {@code allowCoreThreadTimeOut} is set + * @param handler the handler to use when execution is blocked + * because the thread bounds and queue capacities are reached + * @throws IllegalArgumentException if {@code corePoolSize < 0} + * @throws NullPointerException if {@code handler} is null + */ + public ScheduledThreadPoolExecutor(int corePoolSize, + RejectedExecutionHandler handler) { + super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS, + new DelayedWorkQueue(), handler); + } + + /** + * Creates a new ScheduledThreadPoolExecutor with the given + * initial parameters. + * + * @param corePoolSize the number of threads to keep in the pool, even + * if they are idle, unless {@code allowCoreThreadTimeOut} is set + * @param threadFactory the factory to use when the executor + * creates a new thread + * @param handler the handler to use when execution is blocked + * because the thread bounds and queue capacities are reached + * @throws IllegalArgumentException if {@code corePoolSize < 0} + * @throws NullPointerException if {@code threadFactory} or + * {@code handler} is null + */ + public ScheduledThreadPoolExecutor(int corePoolSize, + ThreadFactory threadFactory, + RejectedExecutionHandler handler) { + super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS, + new DelayedWorkQueue(), threadFactory, handler); + } + + /** + * Returns the trigger time of a delayed action. + */ + private long triggerTime(long delay, TimeUnit unit) { + return triggerTime(unit.toNanos((delay < 0) ? 0 : delay)); + } + + /** + * Returns the trigger time of a delayed action. + */ + long triggerTime(long delay) { + return now() + + ((delay < (Long.MAX_VALUE >> 1)) ? delay : overflowFree(delay)); + } + + /** + * Constrains the values of all delays in the queue to be within + * Long.MAX_VALUE of each other, to avoid overflow in compareTo. + * This may occur if a task is eligible to be dequeued, but has + * not yet been, while some other task is added with a delay of + * Long.MAX_VALUE. + */ + private long overflowFree(long delay) { + Delayed head = (Delayed) super.getQueue().peek(); + if (head != null) { + long headDelay = head.getDelay(TimeUnit.NANOSECONDS); + if (headDelay < 0 && (delay - headDelay < 0)) + delay = Long.MAX_VALUE + headDelay; + } + return delay; + } + + /** + * @throws RejectedExecutionException {@inheritDoc} + * @throws NullPointerException {@inheritDoc} + */ + public ScheduledFuture<?> schedule(Runnable command, + long delay, + TimeUnit unit) { + if (command == null || unit == null) + throw new NullPointerException(); + RunnableScheduledFuture<?> t = decorateTask(command, + new ScheduledFutureTask<Void>(command, null, + triggerTime(delay, unit))); + delayedExecute(t); + return t; + } + + /** + * @throws RejectedExecutionException {@inheritDoc} + * @throws NullPointerException {@inheritDoc} + */ + public <V> ScheduledFuture<V> schedule(Callable<V> callable, + long delay, + TimeUnit unit) { + if (callable == null || unit == null) + throw new NullPointerException(); + RunnableScheduledFuture<V> t = decorateTask(callable, + new ScheduledFutureTask<V>(callable, + triggerTime(delay, unit))); + delayedExecute(t); + return t; + } + + /** + * @throws RejectedExecutionException {@inheritDoc} + * @throws NullPointerException {@inheritDoc} + * @throws IllegalArgumentException {@inheritDoc} + */ + public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, + long initialDelay, + long period, + TimeUnit unit) { + if (command == null || unit == null) + throw new NullPointerException(); + if (period <= 0) + throw new IllegalArgumentException(); + ScheduledFutureTask<Void> sft = + new ScheduledFutureTask<Void>(command, + null, + triggerTime(initialDelay, unit), + unit.toNanos(period)); + RunnableScheduledFuture<Void> t = decorateTask(command, sft); + sft.outerTask = t; + delayedExecute(t); + return t; + } + + /** + * @throws RejectedExecutionException {@inheritDoc} + * @throws NullPointerException {@inheritDoc} + * @throws IllegalArgumentException {@inheritDoc} + */ + public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, + long initialDelay, + long delay, + TimeUnit unit) { + if (command == null || unit == null) + throw new NullPointerException(); + if (delay <= 0) + throw new IllegalArgumentException(); + ScheduledFutureTask<Void> sft = + new ScheduledFutureTask<Void>(command, + null, + triggerTime(initialDelay, unit), + unit.toNanos(-delay)); + RunnableScheduledFuture<Void> t = decorateTask(command, sft); + sft.outerTask = t; + delayedExecute(t); + return t; + } + + /** + * Executes {@code command} with zero required delay. + * This has effect equivalent to + * {@link #schedule(Runnable,long,TimeUnit) schedule(command, 0, anyUnit)}. + * Note that inspections of the queue and of the list returned by + * {@code shutdownNow} will access the zero-delayed + * {@link ScheduledFuture}, not the {@code command} itself. + * + * <p>A consequence of the use of {@code ScheduledFuture} objects is + * that {@link ThreadPoolExecutor#afterExecute afterExecute} is always + * called with a null second {@code Throwable} argument, even if the + * {@code command} terminated abruptly. Instead, the {@code Throwable} + * thrown by such a task can be obtained via {@link Future#get}. + * + * @throws RejectedExecutionException at discretion of + * {@code RejectedExecutionHandler}, if the task + * cannot be accepted for execution because the + * executor has been shut down + * @throws NullPointerException {@inheritDoc} + */ + public void execute(Runnable command) { + schedule(command, 0, TimeUnit.NANOSECONDS); + } + + // Override AbstractExecutorService methods + + /** + * @throws RejectedExecutionException {@inheritDoc} + * @throws NullPointerException {@inheritDoc} + */ + public Future<?> submit(Runnable task) { + return schedule(task, 0, TimeUnit.NANOSECONDS); + } + + /** + * @throws RejectedExecutionException {@inheritDoc} + * @throws NullPointerException {@inheritDoc} + */ + public <T> Future<T> submit(Runnable task, T result) { + return schedule(Executors.callable(task, result), + 0, TimeUnit.NANOSECONDS); + } + + /** + * @throws RejectedExecutionException {@inheritDoc} + * @throws NullPointerException {@inheritDoc} + */ + public <T> Future<T> submit(Callable<T> task) { + return schedule(task, 0, TimeUnit.NANOSECONDS); + } + + /** + * Sets the policy on whether to continue executing existing + * periodic tasks even when this executor has been {@code shutdown}. + * In this case, these tasks will only terminate upon + * {@code shutdownNow} or after setting the policy to + * {@code false} when already shutdown. + * This value is by default {@code false}. + * + * @param value if {@code true}, continue after shutdown, else don't. + * @see #getContinueExistingPeriodicTasksAfterShutdownPolicy + */ + public void setContinueExistingPeriodicTasksAfterShutdownPolicy(boolean value) { + continueExistingPeriodicTasksAfterShutdown = value; + if (!value && isShutdown()) + onShutdown(); + } + + /** + * Gets the policy on whether to continue executing existing + * periodic tasks even when this executor has been {@code shutdown}. + * In this case, these tasks will only terminate upon + * {@code shutdownNow} or after setting the policy to + * {@code false} when already shutdown. + * This value is by default {@code false}. + * + * @return {@code true} if will continue after shutdown + * @see #setContinueExistingPeriodicTasksAfterShutdownPolicy + */ + public boolean getContinueExistingPeriodicTasksAfterShutdownPolicy() { + return continueExistingPeriodicTasksAfterShutdown; + } + + /** + * Sets the policy on whether to execute existing delayed + * tasks even when this executor has been {@code shutdown}. + * In this case, these tasks will only terminate upon + * {@code shutdownNow}, or after setting the policy to + * {@code false} when already shutdown. + * This value is by default {@code true}. + * + * @param value if {@code true}, execute after shutdown, else don't. + * @see #getExecuteExistingDelayedTasksAfterShutdownPolicy + */ + public void setExecuteExistingDelayedTasksAfterShutdownPolicy(boolean value) { + executeExistingDelayedTasksAfterShutdown = value; + if (!value && isShutdown()) + onShutdown(); + } + + /** + * Gets the policy on whether to execute existing delayed + * tasks even when this executor has been {@code shutdown}. + * In this case, these tasks will only terminate upon + * {@code shutdownNow}, or after setting the policy to + * {@code false} when already shutdown. + * This value is by default {@code true}. + * + * @return {@code true} if will execute after shutdown + * @see #setExecuteExistingDelayedTasksAfterShutdownPolicy + */ + public boolean getExecuteExistingDelayedTasksAfterShutdownPolicy() { + return executeExistingDelayedTasksAfterShutdown; + } + + /** + * Sets the policy on whether cancelled tasks should be immediately + * removed from the work queue at time of cancellation. This value is + * by default {@code false}. + * + * @param value if {@code true}, remove on cancellation, else don't + * @see #getRemoveOnCancelPolicy + * @since 1.7 + */ + public void setRemoveOnCancelPolicy(boolean value) { + removeOnCancel = value; + } + + /** + * Gets the policy on whether cancelled tasks should be immediately + * removed from the work queue at time of cancellation. This value is + * by default {@code false}. + * + * @return {@code true} if cancelled tasks are immediately removed + * from the queue + * @see #setRemoveOnCancelPolicy + * @since 1.7 + */ + public boolean getRemoveOnCancelPolicy() { + return removeOnCancel; + } + + /** + * Initiates an orderly shutdown in which previously submitted + * tasks are executed, but no new tasks will be accepted. + * Invocation has no additional effect if already shut down. + * + * <p>This method does not wait for previously submitted tasks to + * complete execution. Use {@link #awaitTermination awaitTermination} + * to do that. + * + * <p>If the {@code ExecuteExistingDelayedTasksAfterShutdownPolicy} + * has been set {@code false}, existing delayed tasks whose delays + * have not yet elapsed are cancelled. And unless the {@code + * ContinueExistingPeriodicTasksAfterShutdownPolicy} has been set + * {@code true}, future executions of existing periodic tasks will + * be cancelled. + * + * @throws SecurityException {@inheritDoc} + */ + public void shutdown() { + super.shutdown(); + } + + /** + * Attempts to stop all actively executing tasks, halts the + * processing of waiting tasks, and returns a list of the tasks + * that were awaiting execution. + * + * <p>This method does not wait for actively executing tasks to + * terminate. Use {@link #awaitTermination awaitTermination} to + * do that. + * + * <p>There are no guarantees beyond best-effort attempts to stop + * processing actively executing tasks. This implementation + * cancels tasks via {@link Thread#interrupt}, so any task that + * fails to respond to interrupts may never terminate. + * + * @return list of tasks that never commenced execution. + * Each element of this list is a {@link ScheduledFuture}, + * including those tasks submitted using {@code execute}, + * which are for scheduling purposes used as the basis of a + * zero-delay {@code ScheduledFuture}. + * @throws SecurityException {@inheritDoc} + */ + public List<Runnable> shutdownNow() { + return super.shutdownNow(); + } + + /** + * Returns the task queue used by this executor. Each element of + * this queue is a {@link ScheduledFuture}, including those + * tasks submitted using {@code execute} which are for scheduling + * purposes used as the basis of a zero-delay + * {@code ScheduledFuture}. Iteration over this queue is + * <em>not</em> guaranteed to traverse tasks in the order in + * which they will execute. + * + * @return the task queue + */ + public BlockingQueue<Runnable> getQueue() { + return super.getQueue(); + } + + /** + * Specialized delay queue. To mesh with TPE declarations, this + * class must be declared as a BlockingQueue<Runnable> even though + * it can only hold RunnableScheduledFutures. + */ + static class DelayedWorkQueue extends AbstractQueue<Runnable> + implements BlockingQueue<Runnable> { + + /* + * A DelayedWorkQueue is based on a heap-based data structure + * like those in DelayQueue and PriorityQueue, except that + * every ScheduledFutureTask also records its index into the + * heap array. This eliminates the need to find a task upon + * cancellation, greatly speeding up removal (down from O(n) + * to O(log n)), and reducing garbage retention that would + * otherwise occur by waiting for the element to rise to top + * before clearing. But because the queue may also hold + * RunnableScheduledFutures that are not ScheduledFutureTasks, + * we are not guaranteed to have such indices available, in + * which case we fall back to linear search. (We expect that + * most tasks will not be decorated, and that the faster cases + * will be much more common.) + * + * All heap operations must record index changes -- mainly + * within siftUp and siftDown. Upon removal, a task's + * heapIndex is set to -1. Note that ScheduledFutureTasks can + * appear at most once in the queue (this need not be true for + * other kinds of tasks or work queues), so are uniquely + * identified by heapIndex. + */ + + private static final int INITIAL_CAPACITY = 16; + private RunnableScheduledFuture[] queue = + new RunnableScheduledFuture[INITIAL_CAPACITY]; + private final ReentrantLock lock = new ReentrantLock(); + private int size = 0; + + /** + * Thread designated to wait for the task at the head of the + * queue. This variant of the Leader-Follower pattern + * (http://www.cs.wustl.edu/~schmidt/POSA/POSA2/) serves to + * minimize unnecessary timed waiting. When a thread becomes + * the leader, it waits only for the next delay to elapse, but + * other threads await indefinitely. The leader thread must + * signal some other thread before returning from take() or + * poll(...), unless some other thread becomes leader in the + * interim. Whenever the head of the queue is replaced with a + * task with an earlier expiration time, the leader field is + * invalidated by being reset to null, and some waiting + * thread, but not necessarily the current leader, is + * signalled. So waiting threads must be prepared to acquire + * and lose leadership while waiting. + */ + private Thread leader = null; + + /** + * Condition signalled when a newer task becomes available at the + * head of the queue or a new thread may need to become leader. + */ + private final Condition available = lock.newCondition(); + + /** + * Set f's heapIndex if it is a ScheduledFutureTask. + */ + private void setIndex(RunnableScheduledFuture f, int idx) { + if (f instanceof ScheduledFutureTask) + ((ScheduledFutureTask)f).heapIndex = idx; + } + + /** + * Sift element added at bottom up to its heap-ordered spot. + * Call only when holding lock. + */ + private void siftUp(int k, RunnableScheduledFuture key) { + while (k > 0) { + int parent = (k - 1) >>> 1; + RunnableScheduledFuture e = queue[parent]; + if (key.compareTo(e) >= 0) + break; + queue[k] = e; + setIndex(e, k); + k = parent; + } + queue[k] = key; + setIndex(key, k); + } + + /** + * Sift element added at top down to its heap-ordered spot. + * Call only when holding lock. + */ + private void siftDown(int k, RunnableScheduledFuture key) { + int half = size >>> 1; + while (k < half) { + int child = (k << 1) + 1; + RunnableScheduledFuture c = queue[child]; + int right = child + 1; + if (right < size && c.compareTo(queue[right]) > 0) + c = queue[child = right]; + if (key.compareTo(c) <= 0) + break; + queue[k] = c; + setIndex(c, k); + k = child; + } + queue[k] = key; + setIndex(key, k); + } + + /** + * Resize the heap array. Call only when holding lock. + */ + private void grow() { + int oldCapacity = queue.length; + int newCapacity = oldCapacity + (oldCapacity >> 1); // grow 50% + if (newCapacity < 0) // overflow + newCapacity = Integer.MAX_VALUE; + queue = Arrays.copyOf(queue, newCapacity); + } + + /** + * Find index of given object, or -1 if absent + */ + private int indexOf(Object x) { + if (x != null) { + if (x instanceof ScheduledFutureTask) { + int i = ((ScheduledFutureTask) x).heapIndex; + // Sanity check; x could conceivably be a + // ScheduledFutureTask from some other pool. + if (i >= 0 && i < size && queue[i] == x) + return i; + } else { + for (int i = 0; i < size; i++) + if (x.equals(queue[i])) + return i; + } + } + return -1; + } + + public boolean contains(Object x) { + final ReentrantLock lock = this.lock; + lock.lock(); + try { + return indexOf(x) != -1; + } finally { + lock.unlock(); + } + } + + public boolean remove(Object x) { + final ReentrantLock lock = this.lock; + lock.lock(); + try { + int i = indexOf(x); + if (i < 0) + return false; + + setIndex(queue[i], -1); + int s = --size; + RunnableScheduledFuture replacement = queue[s]; + queue[s] = null; + if (s != i) { + siftDown(i, replacement); + if (queue[i] == replacement) + siftUp(i, replacement); + } + return true; + } finally { + lock.unlock(); + } + } + + public int size() { + final ReentrantLock lock = this.lock; + lock.lock(); + try { + return size; + } finally { + lock.unlock(); + } + } + + public boolean isEmpty() { + return size() == 0; + } + + public int remainingCapacity() { + return Integer.MAX_VALUE; + } + + public RunnableScheduledFuture peek() { + final ReentrantLock lock = this.lock; + lock.lock(); + try { + return queue[0]; + } finally { + lock.unlock(); + } + } + + public boolean offer(Runnable x) { + if (x == null) + throw new NullPointerException(); + RunnableScheduledFuture e = (RunnableScheduledFuture)x; + final ReentrantLock lock = this.lock; + lock.lock(); + try { + int i = size; + if (i >= queue.length) + grow(); + size = i + 1; + if (i == 0) { + queue[0] = e; + setIndex(e, 0); + } else { + siftUp(i, e); + } + if (queue[0] == e) { + leader = null; + available.signal(); + } + } finally { + lock.unlock(); + } + return true; + } + + public void put(Runnable e) { + offer(e); + } + + public boolean add(Runnable e) { + return offer(e); + } + + public boolean offer(Runnable e, long timeout, TimeUnit unit) { + return offer(e); + } + + /** + * Performs common bookkeeping for poll and take: Replaces + * first element with last and sifts it down. Call only when + * holding lock. + * @param f the task to remove and return + */ + private RunnableScheduledFuture finishPoll(RunnableScheduledFuture f) { + int s = --size; + RunnableScheduledFuture x = queue[s]; + queue[s] = null; + if (s != 0) + siftDown(0, x); + setIndex(f, -1); + return f; + } + + public RunnableScheduledFuture poll() { + final ReentrantLock lock = this.lock; + lock.lock(); + try { + RunnableScheduledFuture first = queue[0]; + if (first == null || first.getDelay(TimeUnit.NANOSECONDS) > 0) + return null; + else + return finishPoll(first); + } finally { + lock.unlock(); + } + } + + public RunnableScheduledFuture take() throws InterruptedException { + final ReentrantLock lock = this.lock; + lock.lockInterruptibly(); + try { + for (;;) { + RunnableScheduledFuture first = queue[0]; + if (first == null) + available.await(); + else { + long delay = first.getDelay(TimeUnit.NANOSECONDS); + if (delay <= 0) + return finishPoll(first); + else if (leader != null) + available.await(); + else { + Thread thisThread = Thread.currentThread(); + leader = thisThread; + try { + available.awaitNanos(delay); + } finally { + if (leader == thisThread) + leader = null; + } + } + } + } + } finally { + if (leader == null && queue[0] != null) + available.signal(); + lock.unlock(); + } + } + + public RunnableScheduledFuture poll(long timeout, TimeUnit unit) + throws InterruptedException { + long nanos = unit.toNanos(timeout); + final ReentrantLock lock = this.lock; + lock.lockInterruptibly(); + try { + for (;;) { + RunnableScheduledFuture first = queue[0]; + if (first == null) { + if (nanos <= 0) + return null; + else + nanos = available.awaitNanos(nanos); + } else { + long delay = first.getDelay(TimeUnit.NANOSECONDS); + if (delay <= 0) + return finishPoll(first); + if (nanos <= 0) + return null; + if (nanos < delay || leader != null) + nanos = available.awaitNanos(nanos); + else { + Thread thisThread = Thread.currentThread(); + leader = thisThread; + try { + long timeLeft = available.awaitNanos(delay); + nanos -= delay - timeLeft; + } finally { + if (leader == thisThread) + leader = null; + } + } + } + } + } finally { + if (leader == null && queue[0] != null) + available.signal(); + lock.unlock(); + } + } + + public void clear() { + final ReentrantLock lock = this.lock; + lock.lock(); + try { + for (int i = 0; i < size; i++) { + RunnableScheduledFuture t = queue[i]; + if (t != null) { + queue[i] = null; + setIndex(t, -1); + } + } + size = 0; + } finally { + lock.unlock(); + } + } + + /** + * Return and remove first element only if it is expired. + * Used only by drainTo. Call only when holding lock. + */ + private RunnableScheduledFuture pollExpired() { + RunnableScheduledFuture first = queue[0]; + if (first == null || first.getDelay(TimeUnit.NANOSECONDS) > 0) + return null; + return finishPoll(first); + } + + public int drainTo(Collection<? super Runnable> c) { + if (c == null) + throw new NullPointerException(); + if (c == this) + throw new IllegalArgumentException(); + final ReentrantLock lock = this.lock; + lock.lock(); + try { + RunnableScheduledFuture first; + int n = 0; + while ((first = pollExpired()) != null) { + c.add(first); + ++n; + } + return n; + } finally { + lock.unlock(); + } + } + + public int drainTo(Collection<? super Runnable> c, int maxElements) { + if (c == null) + throw new NullPointerException(); + if (c == this) + throw new IllegalArgumentException(); + if (maxElements <= 0) + return 0; + final ReentrantLock lock = this.lock; + lock.lock(); + try { + RunnableScheduledFuture first; + int n = 0; + while (n < maxElements && (first = pollExpired()) != null) { + c.add(first); + ++n; + } + return n; + } finally { + lock.unlock(); + } + } + + public Object[] toArray() { + final ReentrantLock lock = this.lock; + lock.lock(); + try { + return Arrays.copyOf(queue, size, Object[].class); + } finally { + lock.unlock(); + } + } + + @SuppressWarnings("unchecked") + public <T> T[] toArray(T[] a) { + final ReentrantLock lock = this.lock; + lock.lock(); + try { + if (a.length < size) + return (T[]) Arrays.copyOf(queue, size, a.getClass()); + System.arraycopy(queue, 0, a, 0, size); + if (a.length > size) + a[size] = null; + return a; + } finally { + lock.unlock(); + } + } + + public Iterator<Runnable> iterator() { + return new Itr(Arrays.copyOf(queue, size)); + } + + /** + * Snapshot iterator that works off copy of underlying q array. + */ + private class Itr implements Iterator<Runnable> { + final RunnableScheduledFuture[] array; + int cursor = 0; // index of next element to return + int lastRet = -1; // index of last element, or -1 if no such + + Itr(RunnableScheduledFuture[] array) { + this.array = array; + } + + public boolean hasNext() { + return cursor < array.length; + } + + public Runnable next() { + if (cursor >= array.length) + throw new NoSuchElementException(); + lastRet = cursor; + return array[cursor++]; + } + + public void remove() { + if (lastRet < 0) + throw new IllegalStateException(); + DelayedWorkQueue.this.remove(array[lastRet]); + lastRet = -1; + } + } + } + + // Duplicated package-private methods from ThreadPoolExecutor + + private static final int COUNT_BITS = Integer.SIZE - 3; + private static final int CAPACITY = (1 << COUNT_BITS) - 1; + private static final int RUNNING = -1 << COUNT_BITS; + private static final int SHUTDOWN = 0 << COUNT_BITS; + private static final int TIDYING = 2 << COUNT_BITS; + private static final int TERMINATED = 3 << COUNT_BITS; + + // Packing and unpacking ctl + private static int runStateOf(int c) { return c & ~CAPACITY; } + private static int workerCountOf(int c) { return c & CAPACITY; } + private static int ctlOf(int rs, int wc) { return rs | wc; } + + private static final boolean ONLY_ONE = true; + + /** + * Transitions to TERMINATED state if either (SHUTDOWN and pool + * and queue empty) or (STOP and pool empty). If otherwise + * eligible to terminate but workerCount is nonzero, interrupts an + * idle worker to ensure that shutdown signals propagate. This + * method must be called following any action that might make + * termination possible -- reducing worker count or removing tasks + * from the queue during shutdown. The method is non-private to + * allow access from ScheduledThreadPoolExecutor. + */ + private final void tryTerminateSTPE() { + final JavaUtilConcurrentThreadPoolExecutorAccess juctpea = + SharedSecrets.getJavaUtilConcurrentThreadPoolExecutorAccess(); + final AtomicInteger ctl = juctpea.getCtl(this); + for (;;) { + int c = ctl.get(); + if (isRunning(c) || + runStateAtLeast(c, TIDYING) || + (runStateOf(c) == SHUTDOWN && ! juctpea.isWorkQueueEmpty(this))) + return; + if (workerCountOf(c) != 0) { // Eligible to terminate + juctpea.interruptIdleWorkers(this, ONLY_ONE); + return; + } + + juctpea.lockMainLock(this); + try { + if (ctl.compareAndSet(c, ctlOf(TIDYING, 0))) { + try { + terminated(); + } finally { + ctl.set(ctlOf(TERMINATED, 0)); + juctpea.signalAll(this); + } + return; + } + } finally { + juctpea.unlockMainLock(this); + } + // else retry on failed CAS + } + } + + /** + * State check needed by ScheduledThreadPoolExecutor to + * enable running tasks during shutdown. + * + * @param shutdownOK true if should return true if SHUTDOWN + */ + private final boolean isRunningOrShutdownSTPE(boolean shutdownOK) { + int rs = runStateOf(SharedSecrets.getJavaUtilConcurrentThreadPoolExecutorAccess().getCtl(this).get()); + return rs == RUNNING || (rs == SHUTDOWN && shutdownOK); + } + + /** + * Invokes the rejected execution handler for the given command. + * Package-protected for use by ScheduledThreadPoolExecutor. + */ + private final void rejectSTPE(Runnable command) { + SharedSecrets.getJavaUtilConcurrentThreadPoolExecutorAccess().rejectedExecution(command, this); + } + + private static boolean isRunning(int c) { + return c < SHUTDOWN; + } + + private static boolean runStateAtLeast(int c, int s) { + return c >= s; + } + +}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/io/File.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,450 +0,0 @@ -/* - * Copyright 1994-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.io; - -import java.beans.ConstructorProperties; -import java.net.URI; -import java.net.URL; -import java.net.MalformedURLException; -import java.net.URISyntaxException; - -import java.io.IOException; -import java.io.IOError; - -import java.util.*; -import java.util.concurrent.atomic.AtomicInteger; -import java.security.AccessController; -import java.security.PrivilegedAction; -import sun.security.action.GetPropertyAction; - -import org.classpath.icedtea.java.nio.file.FileAlreadyExistsException; -import org.classpath.icedtea.java.nio.file.FileSystem; -import org.classpath.icedtea.java.nio.file.FileSystems; -import org.classpath.icedtea.java.nio.file.InvalidPathException; -import org.classpath.icedtea.java.nio.file.Path; -import org.classpath.icedtea.java.nio.file.Paths; - -import org.classpath.icedtea.java.nio.file.attribute.FileAttribute; -import org.classpath.icedtea.java.nio.file.attribute.FileAttributeView; -import org.classpath.icedtea.java.nio.file.attribute.PosixFilePermission; -import org.classpath.icedtea.java.nio.file.attribute.PosixFilePermissions; - -import org.classpath.icedtea.misc.SharedSecrets; - -/** - * An abstract representation of file and directory pathnames. - * - * <p> User interfaces and operating systems use system-dependent <em>pathname - * strings</em> to name files and directories. This class presents an - * abstract, system-independent view of hierarchical pathnames. An - * <em>abstract pathname</em> has two components: - * - * <ol> - * <li> An optional system-dependent <em>prefix</em> string, - * such as a disk-drive specifier, <code>"/"</code> for the UNIX root - * directory, or <code>"\\\\"</code> for a Microsoft Windows UNC pathname, and - * <li> A sequence of zero or more string <em>names</em>. - * </ol> - * - * The first name in an abstract pathname may be a directory name or, in the - * case of Microsoft Windows UNC pathnames, a hostname. Each subsequent name - * in an abstract pathname denotes a directory; the last name may denote - * either a directory or a file. The <em>empty</em> abstract pathname has no - * prefix and an empty name sequence. - * - * <p> The conversion of a pathname string to or from an abstract pathname is - * inherently system-dependent. When an abstract pathname is converted into a - * pathname string, each name is separated from the next by a single copy of - * the default <em>separator character</em>. The default name-separator - * character is defined by the system property <code>file.separator</code>, and - * is made available in the public static fields <code>{@link - * #separator}</code> and <code>{@link #separatorChar}</code> of this class. - * When a pathname string is converted into an abstract pathname, the names - * within it may be separated by the default name-separator character or by any - * other name-separator character that is supported by the underlying system. - * - * <p> A pathname, whether abstract or in string form, may be either - * <em>absolute</em> or <em>relative</em>. An absolute pathname is complete in - * that no other information is required in order to locate the file that it - * denotes. A relative pathname, in contrast, must be interpreted in terms of - * information taken from some other pathname. By default the classes in the - * <code>java.io</code> package always resolve relative pathnames against the - * current user directory. This directory is named by the system property - * <code>user.dir</code>, and is typically the directory in which the Java - * virtual machine was invoked. - * - * <p> The <em>parent</em> of an abstract pathname may be obtained by invoking - * the {@link #getParent} method of this class and consists of the pathname's - * prefix and each name in the pathname's name sequence except for the last. - * Each directory's absolute pathname is an ancestor of any <tt>File</tt> - * object with an absolute abstract pathname which begins with the directory's - * absolute pathname. For example, the directory denoted by the abstract - * pathname <tt>"/usr"</tt> is an ancestor of the directory denoted by the - * pathname <tt>"/usr/local/bin"</tt>. - * - * <p> The prefix concept is used to handle root directories on UNIX platforms, - * and drive specifiers, root directories and UNC pathnames on Microsoft Windows platforms, - * as follows: - * - * <ul> - * - * <li> For UNIX platforms, the prefix of an absolute pathname is always - * <code>"/"</code>. Relative pathnames have no prefix. The abstract pathname - * denoting the root directory has the prefix <code>"/"</code> and an empty - * name sequence. - * - * <li> For Microsoft Windows platforms, the prefix of a pathname that contains a drive - * specifier consists of the drive letter followed by <code>":"</code> and - * possibly followed by <code>"\\"</code> if the pathname is absolute. The - * prefix of a UNC pathname is <code>"\\\\"</code>; the hostname and the share - * name are the first two names in the name sequence. A relative pathname that - * does not specify a drive has no prefix. - * - * </ul> - * - * <p> Instances of this class may or may not denote an actual file-system - * object such as a file or a directory. If it does denote such an object - * then that object resides in a <i>partition</i>. A partition is an - * operating system-specific portion of storage for a file system. A single - * storage device (e.g. a physical disk-drive, flash memory, CD-ROM) may - * contain multiple partitions. The object, if any, will reside on the - * partition <a name="partName">named</a> by some ancestor of the absolute - * form of this pathname. - * - * <p> A file system may implement restrictions to certain operations on the - * actual file-system object, such as reading, writing, and executing. These - * restrictions are collectively known as <i>access permissions</i>. The file - * system may have multiple sets of access permissions on a single object. - * For example, one set may apply to the object's <i>owner</i>, and another - * may apply to all other users. The access permissions on an object may - * cause some methods in this class to fail. - * - * <p> Instances of the <code>File</code> class are immutable; that is, once - * created, the abstract pathname represented by a <code>File</code> object - * will never change. - * - * <h4>Interoperability with {@code java.nio.file} package</h4> - * - * <p> {@note new} - * The <a href="../../java/nio/file/package-summary.html">{@code java.nio.file}</a> - * package defines interfaces and classes for the Java virtual machine to access - * files, file attributes, and file systems. This API may be used to overcome - * many of the limitations of the {@code java.io.File} class. - * The {@link #toPath toPath} method may be used to obtain a {@link - * Path} that uses the abstract path represented by a {@code File} object to - * locate a file. The resulting {@code Path} provides more efficient and - * extensive access to file attributes, additional file operations, and I/O - * exceptions to help diagnose errors when an operation on a file fails. - * - * @author unascribed - * @since JDK1.0 - */ - -public class File - extends java.io.File -{ - - /** - * Creates a new <code>File</code> instance by converting the given - * pathname string into an abstract pathname. If the given string is - * the empty string, then the result is the empty abstract pathname. - * - * @param pathname A pathname string - * @throws NullPointerException - * If the <code>pathname</code> argument is <code>null</code> - */ - @ConstructorProperties("path") - public File(String pathname) { - super(pathname); - } - - /* Note: The two-argument File constructors do not interpret an empty - parent abstract pathname as the current user directory. An empty parent - instead causes the child to be resolved against the system-dependent - directory defined by the FileSystem.getDefaultParent method. On Unix - this default is "/", while on Microsoft Windows it is "\\". This is required for - compatibility with the original behavior of this class. */ - - /** - * Creates a new <code>File</code> instance from a parent pathname string - * and a child pathname string. - * - * <p> If <code>parent</code> is <code>null</code> then the new - * <code>File</code> instance is created as if by invoking the - * single-argument <code>File</code> constructor on the given - * <code>child</code> pathname string. - * - * <p> Otherwise the <code>parent</code> pathname string is taken to denote - * a directory, and the <code>child</code> pathname string is taken to - * denote either a directory or a file. If the <code>child</code> pathname - * string is absolute then it is converted into a relative pathname in a - * system-dependent way. If <code>parent</code> is the empty string then - * the new <code>File</code> instance is created by converting - * <code>child</code> into an abstract pathname and resolving the result - * against a system-dependent default directory. Otherwise each pathname - * string is converted into an abstract pathname and the child abstract - * pathname is resolved against the parent. - * - * @param parent The parent pathname string - * @param child The child pathname string - * @throws NullPointerException - * If <code>child</code> is <code>null</code> - */ - public File(String parent, String child) { - super(parent, child); - } - - /** - * Creates a new <code>File</code> instance from a parent abstract - * pathname and a child pathname string. - * - * <p> If <code>parent</code> is <code>null</code> then the new - * <code>File</code> instance is created as if by invoking the - * single-argument <code>File</code> constructor on the given - * <code>child</code> pathname string. - * - * <p> Otherwise the <code>parent</code> abstract pathname is taken to - * denote a directory, and the <code>child</code> pathname string is taken - * to denote either a directory or a file. If the <code>child</code> - * pathname string is absolute then it is converted into a relative - * pathname in a system-dependent way. If <code>parent</code> is the empty - * abstract pathname then the new <code>File</code> instance is created by - * converting <code>child</code> into an abstract pathname and resolving - * the result against a system-dependent default directory. Otherwise each - * pathname string is converted into an abstract pathname and the child - * abstract pathname is resolved against the parent. - * - * @param parent The parent abstract pathname - * @param child The child pathname string - * @throws NullPointerException - * If <code>child</code> is <code>null</code> - */ - public File(File parent, String child) { - super(parent, child); - } - - - - /* -- Temporary files -- */ - - private static class TemporaryDirectory { - private TemporaryDirectory() { } - - static final File valueAsFile = - new File(AccessController.doPrivileged(new GetPropertyAction("java.io.tmpdir"))); - - // file name generation - private static final AtomicInteger counter = - new AtomicInteger(new Random().nextInt() & 0xffff); - static File generateFile(String prefix, String suffix, File dir) { - int n = counter.getAndIncrement(); - return new File(dir, prefix + Integer.toString(n) + suffix); - } - - // default file permissions - static final FileAttribute<Set<PosixFilePermission>> defaultPosixFilePermissions = - PosixFilePermissions.asFileAttribute(EnumSet - .of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE)); - static final boolean isPosix = isPosix(); - static boolean isPosix() { - return AccessController.doPrivileged( - new PrivilegedAction<Boolean>() { - public Boolean run() { - try { - return FileSystems.getDefault().getPath(valueAsFile.getPath()) - .getFileStore().supportsFileAttributeView("posix"); - } catch (IOException e) { - throw new IOError(e); - } - } - }); - } - } - - /** - * {@note new} - * Creates an empty file in the default temporary-file directory, using - * the given prefix and suffix to generate its name. This method is - * equivalent to invoking the {@link #createTempFile(String,String) - * createTempFile(prefix, suffix)} method with the addition that the - * resulting pathname may be requested to be deleted when the Java virtual - * machine terminates, and the initial file attributes to set atomically - * when creating the file may be specified. - * - * <p> When the value of the {@code deleteOnExit} method is {@code true} - * then the resulting file is requested to be deleted when the Java virtual - * machine terminates as if by invoking the {@link #deleteOnExit deleteOnExit} - * method. - * - * <p> The {@code attrs} parameter is an optional array of {@link FileAttribute - * attributes} to set atomically when creating the file. Each attribute is - * identified by its {@link FileAttribute#name name}. If more than one attribute - * of the same name is included in the array then all but the last occurrence - * is ignored. - * - * @param prefix - * The prefix string to be used in generating the file's - * name; must be at least three characters long - * @param suffix - * The suffix string to be used in generating the file's - * name; may be {@code null}, in which case the suffix - * {@code ".tmp"} will be used - * @param deleteOnExit - * {@code true} if the file denoted by resulting pathname be - * deleted when the Java virtual machine terminates - * @param attrs - * An optional list of file attributes to set atomically when creating - * the file - * - * @return An abstract pathname denoting a newly-created empty file - * - * @throws IllegalArgumentException - * If the <code>prefix</code> argument contains fewer than three - * characters - * @throws UnsupportedOperationException - * If the array contains an attribute that cannot be set atomically - * when creating the file - * @throws IOException - * If a file could not be created - * @throws SecurityException - * If a security manager exists and its <code>{@link - * java.lang.SecurityManager#checkWrite(java.lang.String)}</code> - * method does not allow a file to be created. When the {@code - * deleteOnExit} parameter has the value {@code true} then the - * security manager's {@link - * java.lang.SecurityManager#checkDelete(java.lang.String)} is - * invoked to check delete access to the file. - * @since 1.7 - */ - public static File createTempFile(String prefix, - String suffix, - boolean deleteOnExit, - FileAttribute<?>... attrs) - throws IOException - { - if (prefix.length() < 3) - throw new IllegalArgumentException("Prefix string too short"); - suffix = (suffix == null) ? ".tmp" : suffix; - - // special case POSIX environments so that 0600 is used as the file mode - if (TemporaryDirectory.isPosix) { - if (attrs.length == 0) { - // no attributes so use default permissions - attrs = new FileAttribute<?>[1]; - attrs[0] = TemporaryDirectory.defaultPosixFilePermissions; - } else { - // check if posix permissions given; if not use default - boolean hasPermissions = false; - for (int i=0; i<attrs.length; i++) { - if (attrs[i].name().equals("posix:permissions")) { - hasPermissions = true; - break; - } - } - if (!hasPermissions) { - FileAttribute<?>[] copy = new FileAttribute<?>[attrs.length+1]; - System.arraycopy(attrs, 0, copy, 0, attrs.length); - attrs = copy; - attrs[attrs.length-1] = - TemporaryDirectory.defaultPosixFilePermissions; - } - } - } - - // use Path#createFile to create file - SecurityManager sm = System.getSecurityManager(); - for (;;) { - File f = TemporaryDirectory - .generateFile(prefix, suffix, TemporaryDirectory.valueAsFile); - if (sm != null && deleteOnExit) - sm.checkDelete(f.getPath()); - try { - f.toPath().createFile(attrs); - if (deleteOnExit) - SharedSecrets.getJavaIODeleteOnExitAccess().add(f.getPath()); - return f; - } catch (InvalidPathException e) { - // don't reveal temporary directory location - if (sm != null) - throw new IllegalArgumentException("Invalid prefix or suffix"); - throw e; - } catch (SecurityException e) { - // don't reveal temporary directory location - if (sm != null) - throw new SecurityException("Unable to create temporary file"); - throw e; - } catch (FileAlreadyExistsException e) { - // ignore - } - } - } - - // -- Integration with java.nio.file -- - - private volatile transient Path filePath; - - /** - * {@note new} - * Returns a {@link Path java.nio.file.Path} object constructed from the - * this abstract path. The first invocation of this method works as if - * invoking it were equivalent to evaluating the expression: - * <blockquote><pre> - * {@link FileSystems#getDefault FileSystems.getDefault}().{@link FileSystem#getPath getPath}(this.{@link #getPath getPath}()); - * </pre></blockquote> - * Subsequent invocations of this method return the same {@code Path}. - * - * <p> If this abstract pathname is the empty abstract pathname then this - * method returns a {@code Path} that may be used to access to the current - * user directory. - * - * @return A {@code Path} constructed from this abstract path. The resulting - * {@code Path} is associated with the {@link FileSystems#getDefault - * default-filesystem}. - * - * @throws InvalidPathException - * If a {@code Path} object cannot be constructed from the abstract - * path (see {@link java.nio.file.FileSystem#getPath FileSystem.getPath}) - * - * @since 1.7 - */ - public Path toPath() { - if (filePath == null) { - synchronized (this) { - if (filePath == null) { - String path = getPath(); - if (path.length() == 0) { - // assume default file system treats "." as current directory - filePath = Paths.get("."); - } else { - filePath = Paths.get(path); - } - } - } - } - return filePath; - } -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/io/FilePermission.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,852 +0,0 @@ -/* - * Copyright 1997-2005 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.io; - -import java.security.*; -import java.util.Enumeration; -import java.util.List; -import java.util.ArrayList; -import java.util.Vector; -import java.util.Collections; -import java.io.IOException; -import java.io.ObjectStreamField; -import java.io.ObjectOutputStream; -import java.io.ObjectInputStream; -import java.io.Serializable; -import sun.security.util.SecurityConstants; - -/** - * This class represents access to a file or directory. A FilePermission consists - * of a pathname and a set of actions valid for that pathname. - * <P> - * Pathname is the pathname of the file or directory granted the specified - * actions. A pathname that ends in "/*" (where "/" is - * the file separator character, <code>File.separatorChar</code>) indicates - * all the files and directories contained in that directory. A pathname - * that ends with "/-" indicates (recursively) all files - * and subdirectories contained in that directory. A pathname consisting of - * the special token "<<ALL FILES>>" matches <b>any</b> file. - * <P> - * Note: A pathname consisting of a single "*" indicates all the files - * in the current directory, while a pathname consisting of a single "-" - * indicates all the files in the current directory and - * (recursively) all files and subdirectories contained in the current - * directory. - * <P> - * {@note revised} - * The actions to be granted are passed to the constructor in a string containing - * a list of one or more comma-separated keywords. The possible keywords are - * "read", "write", "execute", "delete", and "readlink". Their meaning is - * defined as follows: - * <P> - * <DL> - * <DT> read <DD> read permission - * <DT> write <DD> write permission - * <DT> execute - * <DD> execute permission. Allows <code>Runtime.exec</code> to - * be called. Corresponds to <code>SecurityManager.checkExec</code>. - * <DT> delete - * <DD> delete permission. Allows <code>File.delete</code> to - * be called. Corresponds to <code>SecurityManager.checkDelete</code>. - * <DT> readlink - * <DD> read link permission. Allows the target of a - * <a href="../nio/file/package-summary.html#links">symbolic link</a> - * to be read by invoking the {@link java.nio.file.Path#readSymbolicLink - * readSymbolicLink } method. - * </DL> - * <P> - * The actions string is converted to lowercase before processing. - * <P> - * Be careful when granting FilePermissions. Think about the implications - * of granting read and especially write access to various files and - * directories. The "<<ALL FILES>>" permission with write action is - * especially dangerous. This grants permission to write to the entire - * file system. One thing this effectively allows is replacement of the - * system binary, including the JVM runtime environment. - * - * <p>Please note: Code can always read a file from the same - * directory it's in (or a subdirectory of that directory); it does not - * need explicit permission to do so. - * - * @see java.security.Permission - * @see java.security.Permissions - * @see java.security.PermissionCollection - * - * - * @author Marianne Mueller - * @author Roland Schemers - * @since 1.2 - * - * @serial exclude - */ - -public final class FilePermission extends Permission implements Serializable { - - /** - * Execute action. - */ - private final static int EXECUTE = 0x1; - /** - * Write action. - */ - private final static int WRITE = 0x2; - /** - * Read action. - */ - private final static int READ = 0x4; - /** - * Delete action. - */ - private final static int DELETE = 0x8; - /** - * Read link action. - */ - private final static int READLINK = 0x10; - - /** - * All actions (read,write,execute,delete,readlink) - */ - private final static int ALL = READ|WRITE|EXECUTE|DELETE|READLINK; - /** - * No actions. - */ - private final static int NONE = 0x0; - - // the actions mask - private transient int mask; - - // does path indicate a directory? (wildcard or recursive) - private transient boolean directory; - - // is it a recursive directory specification? - private transient boolean recursive; - - /** - * the actions string. - * - * @serial - */ - private String actions; // Left null as long as possible, then - // created and re-used in the getAction function. - - // canonicalized dir path. In the case of - // directories, it is the name "/blah/*" or "/blah/-" without - // the last character (the "*" or "-"). - - private transient String cpath; - - // static Strings used by init(int mask) - private static final char RECURSIVE_CHAR = '-'; - private static final char WILD_CHAR = '*'; - -/* - public String toString() - { - StringBuffer sb = new StringBuffer(); - sb.append("***\n"); - sb.append("cpath = "+cpath+"\n"); - sb.append("mask = "+mask+"\n"); - sb.append("actions = "+getActions()+"\n"); - sb.append("directory = "+directory+"\n"); - sb.append("recursive = "+recursive+"\n"); - sb.append("***\n"); - return sb.toString(); - } -*/ - - private static final long serialVersionUID = 7930732926638008763L; - - /** - * initialize a FilePermission object. Common to all constructors. - * Also called during de-serialization. - * - * @param mask the actions mask to use. - * - */ - private void init(int mask) - { - - if ((mask & ALL) != mask) - throw new IllegalArgumentException("invalid actions mask"); - - if (mask == NONE) - throw new IllegalArgumentException("invalid actions mask"); - - if ((cpath = getName()) == null) - throw new NullPointerException("name can't be null"); - - this.mask = mask; - - if (cpath.equals("<<ALL FILES>>")) { - directory = true; - recursive = true; - cpath = ""; - return; - } - - // store only the canonical cpath if possible - cpath = AccessController.doPrivileged(new PrivilegedAction<String>() { - public String run() { - try { - return sun.security.provider.PolicyFile.canonPath(cpath); - } catch (IOException ioe) { - return cpath; - } - } - }); - - int len = cpath.length(); - char last = ((len > 0) ? cpath.charAt(len - 1) : 0); - - if (last == RECURSIVE_CHAR && - cpath.charAt(len - 2) == File.separatorChar) { - directory = true; - recursive = true; - cpath = cpath.substring(0, --len); - } else if (last == WILD_CHAR && - cpath.charAt(len - 2) == File.separatorChar) { - directory = true; - //recursive = false; - cpath = cpath.substring(0, --len); - } else { - // overkill since they are initialized to false, but - // commented out here to remind us... - //directory = false; - //recursive = false; - } - - // XXX: at this point the path should be absolute. die if it isn't? - } - - /** - * Creates a new FilePermission object with the specified actions. - * <i>path</i> is the pathname of a file or directory, and <i>actions</i> - * contains a comma-separated list of the desired actions granted on the - * file or directory. Possible actions are - * "read", "write", "execute", "delete", and "readlink". - * - * <p>A pathname that ends in "/*" (where "/" is - * the file separator character, <code>File.separatorChar</code>) - * indicates all the files and directories contained in that directory. - * A pathname that ends with "/-" indicates (recursively) all files and - * subdirectories contained in that directory. The special pathname - * "<<ALL FILES>>" matches any file. - * - * <p>A pathname consisting of a single "*" indicates all the files - * in the current directory, while a pathname consisting of a single "-" - * indicates all the files in the current directory and - * (recursively) all files and subdirectories contained in the current - * directory. - * - * <p>A pathname containing an empty string represents an empty path. - * - * @param path the pathname of the file/directory. - * @param actions the action string. - * - * @throws IllegalArgumentException - * If actions is <code>null</code>, empty or contains an action - * other than the specified possible actions. - */ - - public FilePermission(String path, String actions) - { - super(path); - init(getMask(actions)); - } - - /** - * Creates a new FilePermission object using an action mask. - * More efficient than the FilePermission(String, String) constructor. - * Can be used from within - * code that needs to create a FilePermission object to pass into the - * <code>implies</code> method. - * - * @param path the pathname of the file/directory. - * @param mask the action mask to use. - */ - - // package private for use by the FilePermissionCollection add method - FilePermission(String path, int mask) - { - super(path); - init(mask); - } - - /** - * Checks if this FilePermission object "implies" the specified permission. - * <P> - * More specifically, this method returns true if:<p> - * <ul> - * <li> <i>p</i> is an instanceof FilePermission,<p> - * <li> <i>p</i>'s actions are a proper subset of this - * object's actions, and <p> - * <li> <i>p</i>'s pathname is implied by this object's - * pathname. For example, "/tmp/*" implies "/tmp/foo", since - * "/tmp/*" encompasses all files in the "/tmp" directory, - * including the one named "foo". - * </ul> - * - * @param p the permission to check against. - * - * @return <code>true</code> if the specified permission is not - * <code>null</code> and is implied by this object, - * <code>false</code> otherwise. - */ - public boolean implies(Permission p) { - if (!(p instanceof FilePermission)) - return false; - - FilePermission that = (FilePermission) p; - - // we get the effective mask. i.e., the "and" of this and that. - // They must be equal to that.mask for implies to return true. - - return ((this.mask & that.mask) == that.mask) && impliesIgnoreMask(that); - } - - /** - * Checks if the Permission's actions are a proper subset of the - * this object's actions. Returns the effective mask iff the - * this FilePermission's path also implies that FilePermission's path. - * - * @param that the FilePermission to check against. - * @param exact return immediately if the masks are not equal - * @return the effective mask - */ - boolean impliesIgnoreMask(FilePermission that) { - if (this.directory) { - if (this.recursive) { - // make sure that.path is longer then path so - // something like /foo/- does not imply /foo - if (that.directory) { - return (that.cpath.length() >= this.cpath.length()) && - that.cpath.startsWith(this.cpath); - } else { - return ((that.cpath.length() > this.cpath.length()) && - that.cpath.startsWith(this.cpath)); - } - } else { - if (that.directory) { - // if the permission passed in is a directory - // specification, make sure that a non-recursive - // permission (i.e., this object) can't imply a recursive - // permission. - if (that.recursive) - return false; - else - return (this.cpath.equals(that.cpath)); - } else { - int last = that.cpath.lastIndexOf(File.separatorChar); - if (last == -1) - return false; - else { - // this.cpath.equals(that.cpath.substring(0, last+1)); - // Use regionMatches to avoid creating new string - return (this.cpath.length() == (last + 1)) && - this.cpath.regionMatches(0, that.cpath, 0, last+1); - } - } - } - } else if (that.directory) { - // if this is NOT recursive/wildcarded, - // do not let it imply a recursive/wildcarded permission - return false; - } else { - return (this.cpath.equals(that.cpath)); - } - } - - /** - * Checks two FilePermission objects for equality. Checks that <i>obj</i> is - * a FilePermission, and has the same pathname and actions as this object. - * <P> - * @param obj the object we are testing for equality with this object. - * @return <code>true</code> if obj is a FilePermission, and has the same - * pathname and actions as this FilePermission object, - * <code>false</code> otherwise. - */ - public boolean equals(Object obj) { - if (obj == this) - return true; - - if (! (obj instanceof FilePermission)) - return false; - - FilePermission that = (FilePermission) obj; - - return (this.mask == that.mask) && - this.cpath.equals(that.cpath) && - (this.directory == that.directory) && - (this.recursive == that.recursive); - } - - /** - * Returns the hash code value for this object. - * - * @return a hash code value for this object. - */ - - public int hashCode() { - return this.cpath.hashCode(); - } - - /** - * Converts an actions String to an actions mask. - * - * @param action the action string. - * @return the actions mask. - */ - private static int getMask(String actions) { - - int mask = NONE; - - // Null action valid? - if (actions == null) { - return mask; - } - // Check against use of constants (used heavily within the JDK) - if (actions == SecurityConstants.FILE_READ_ACTION) { - return READ; - } else if (actions == SecurityConstants.FILE_WRITE_ACTION) { - return WRITE; - } else if (actions == SecurityConstants.FILE_EXECUTE_ACTION) { - return EXECUTE; - } else if (actions == SecurityConstants.FILE_DELETE_ACTION) { - return DELETE; - } else if (actions == SecurityConstants.FILE_READLINK_ACTION) { - return READLINK; - } - - char[] a = actions.toCharArray(); - - int i = a.length - 1; - if (i < 0) - return mask; - - while (i != -1) { - char c; - - // skip whitespace - while ((i!=-1) && ((c = a[i]) == ' ' || - c == '\r' || - c == '\n' || - c == '\f' || - c == '\t')) - i--; - - // check for the known strings - int matchlen; - - if (i >= 3 && (a[i-3] == 'r' || a[i-3] == 'R') && - (a[i-2] == 'e' || a[i-2] == 'E') && - (a[i-1] == 'a' || a[i-1] == 'A') && - (a[i] == 'd' || a[i] == 'D')) - { - matchlen = 4; - mask |= READ; - - } else if (i >= 4 && (a[i-4] == 'w' || a[i-4] == 'W') && - (a[i-3] == 'r' || a[i-3] == 'R') && - (a[i-2] == 'i' || a[i-2] == 'I') && - (a[i-1] == 't' || a[i-1] == 'T') && - (a[i] == 'e' || a[i] == 'E')) - { - matchlen = 5; - mask |= WRITE; - - } else if (i >= 6 && (a[i-6] == 'e' || a[i-6] == 'E') && - (a[i-5] == 'x' || a[i-5] == 'X') && - (a[i-4] == 'e' || a[i-4] == 'E') && - (a[i-3] == 'c' || a[i-3] == 'C') && - (a[i-2] == 'u' || a[i-2] == 'U') && - (a[i-1] == 't' || a[i-1] == 'T') && - (a[i] == 'e' || a[i] == 'E')) - { - matchlen = 7; - mask |= EXECUTE; - - } else if (i >= 5 && (a[i-5] == 'd' || a[i-5] == 'D') && - (a[i-4] == 'e' || a[i-4] == 'E') && - (a[i-3] == 'l' || a[i-3] == 'L') && - (a[i-2] == 'e' || a[i-2] == 'E') && - (a[i-1] == 't' || a[i-1] == 'T') && - (a[i] == 'e' || a[i] == 'E')) - { - matchlen = 6; - mask |= DELETE; - - } else if (i >= 7 && (a[i-7] == 'r' || a[i-7] == 'R') && - (a[i-6] == 'e' || a[i-6] == 'E') && - (a[i-5] == 'a' || a[i-5] == 'A') && - (a[i-4] == 'd' || a[i-4] == 'D') && - (a[i-3] == 'l' || a[i-3] == 'L') && - (a[i-2] == 'i' || a[i-2] == 'I') && - (a[i-1] == 'n' || a[i-1] == 'N') && - (a[i] == 'k' || a[i] == 'K')) - { - matchlen = 8; - mask |= READLINK; - - } else { - // parse error - throw new IllegalArgumentException( - "invalid permission: " + actions); - } - - // make sure we didn't just match the tail of a word - // like "ackbarfaccept". Also, skip to the comma. - boolean seencomma = false; - while (i >= matchlen && !seencomma) { - switch(a[i-matchlen]) { - case ',': - seencomma = true; - /*FALLTHROUGH*/ - case ' ': case '\r': case '\n': - case '\f': case '\t': - break; - default: - throw new IllegalArgumentException( - "invalid permission: " + actions); - } - i--; - } - - // point i at the location of the comma minus one (or -1). - i -= matchlen; - } - - return mask; - } - - /** - * Return the current action mask. Used by the FilePermissionCollection. - * - * @return the actions mask. - */ - - int getMask() { - return mask; - } - - /** - * Return the canonical string representation of the actions. - * Always returns present actions in the following order: - * read, write, execute, delete, readlink. - * - * @return the canonical string representation of the actions. - */ - private static String getActions(int mask) - { - StringBuilder sb = new StringBuilder(); - boolean comma = false; - - if ((mask & READ) == READ) { - comma = true; - sb.append("read"); - } - - if ((mask & WRITE) == WRITE) { - if (comma) sb.append(','); - else comma = true; - sb.append("write"); - } - - if ((mask & EXECUTE) == EXECUTE) { - if (comma) sb.append(','); - else comma = true; - sb.append("execute"); - } - - if ((mask & DELETE) == DELETE) { - if (comma) sb.append(','); - else comma = true; - sb.append("delete"); - } - - if ((mask & READLINK) == READLINK) { - if (comma) sb.append(','); - else comma = true; - sb.append("readlink"); - } - - return sb.toString(); - } - - /** - * Returns the "canonical string representation" of the actions. - * That is, this method always returns present actions in the following order: - * read, write, execute, delete, readlink. For example, if this FilePermission - * object allows both write and read actions, a call to <code>getActions</code> - * will return the string "read,write". - * - * @return the canonical string representation of the actions. - */ - public String getActions() - { - if (actions == null) - actions = getActions(this.mask); - - return actions; - } - - - /** - * Returns a new PermissionCollection object for storing FilePermission - * objects. - * <p> - * FilePermission objects must be stored in a manner that allows them - * to be inserted into the collection in any order, but that also enables the - * PermissionCollection <code>implies</code> - * method to be implemented in an efficient (and consistent) manner. - * - * <p>For example, if you have two FilePermissions: - * <OL> - * <LI> <code>"/tmp/-", "read"</code> - * <LI> <code>"/tmp/scratch/foo", "write"</code> - * </OL> - * - * <p>and you are calling the <code>implies</code> method with the FilePermission: - * - * <pre> - * "/tmp/scratch/foo", "read,write", - * </pre> - * - * then the <code>implies</code> function must - * take into account both the "/tmp/-" and "/tmp/scratch/foo" - * permissions, so the effective permission is "read,write", - * and <code>implies</code> returns true. The "implies" semantics for - * FilePermissions are handled properly by the PermissionCollection object - * returned by this <code>newPermissionCollection</code> method. - * - * @return a new PermissionCollection object suitable for storing - * FilePermissions. - */ - - public PermissionCollection newPermissionCollection() { - return new FilePermissionCollection(); - } - - /** - * WriteObject is called to save the state of the FilePermission - * to a stream. The actions are serialized, and the superclass - * takes care of the name. - */ - private void writeObject(ObjectOutputStream s) - throws IOException - { - // Write out the actions. The superclass takes care of the name - // call getActions to make sure actions field is initialized - if (actions == null) - getActions(); - s.defaultWriteObject(); - } - - /** - * readObject is called to restore the state of the FilePermission from - * a stream. - */ - private void readObject(ObjectInputStream s) - throws IOException, ClassNotFoundException - { - // Read in the actions, then restore everything else by calling init. - s.defaultReadObject(); - init(getMask(actions)); - } -} - -/** - * A FilePermissionCollection stores a set of FilePermission permissions. - * FilePermission objects - * must be stored in a manner that allows them to be inserted in any - * order, but enable the implies function to evaluate the implies - * method. - * For example, if you have two FilePermissions: - * <OL> - * <LI> "/tmp/-", "read" - * <LI> "/tmp/scratch/foo", "write" - * </OL> - * And you are calling the implies function with the FilePermission: - * "/tmp/scratch/foo", "read,write", then the implies function must - * take into account both the /tmp/- and /tmp/scratch/foo - * permissions, so the effective permission is "read,write". - * - * @see java.security.Permission - * @see java.security.Permissions - * @see java.security.PermissionCollection - * - * - * @author Marianne Mueller - * @author Roland Schemers - * - * @serial include - * - */ - -final class FilePermissionCollection extends PermissionCollection -implements Serializable { - - // Not serialized; see serialization section at end of class - private transient List<Permission> perms; - - /** - * Create an empty FilePermissions object. - * - */ - - public FilePermissionCollection() { - perms = new ArrayList<Permission>(); - } - - /** - * Adds a permission to the FilePermissions. The key for the hash is - * permission.path. - * - * @param permission the Permission object to add. - * - * @exception IllegalArgumentException - if the permission is not a - * FilePermission - * - * @exception SecurityException - if this FilePermissionCollection object - * has been marked readonly - */ - - public void add(Permission permission) - { - if (! (permission instanceof FilePermission)) - throw new IllegalArgumentException("invalid permission: "+ - permission); - if (isReadOnly()) - throw new SecurityException( - "attempt to add a Permission to a readonly PermissionCollection"); - - synchronized (this) { - perms.add(permission); - } - } - - /** - * Check and see if this set of permissions implies the permissions - * expressed in "permission". - * - * @param p the Permission object to compare - * - * @return true if "permission" is a proper subset of a permission in - * the set, false if not. - */ - - public boolean implies(Permission permission) - { - if (! (permission instanceof FilePermission)) - return false; - - FilePermission fp = (FilePermission) permission; - - int desired = fp.getMask(); - int effective = 0; - int needed = desired; - - synchronized (this) { - int len = perms.size(); - for (int i = 0; i < len; i++) { - FilePermission x = (FilePermission) perms.get(i); - if (((needed & x.getMask()) != 0) && x.impliesIgnoreMask(fp)) { - effective |= x.getMask(); - if ((effective & desired) == desired) - return true; - needed = (desired ^ effective); - } - } - } - return false; - } - - /** - * Returns an enumeration of all the FilePermission objects in the - * container. - * - * @return an enumeration of all the FilePermission objects. - */ - - public Enumeration elements() { - // Convert Iterator into Enumeration - synchronized (this) { - return Collections.enumeration(perms); - } - } - - private static final long serialVersionUID = 2202956749081564585L; - - // Need to maintain serialization interoperability with earlier releases, - // which had the serializable field: - // private Vector permissions; - - /** - * @serialField permissions java.util.Vector - * A list of FilePermission objects. - */ - private static final ObjectStreamField[] serialPersistentFields = { - new ObjectStreamField("permissions", Vector.class), - }; - - /** - * @serialData "permissions" field (a Vector containing the FilePermissions). - */ - /* - * Writes the contents of the perms field out as a Vector for - * serialization compatibility with earlier releases. - */ - private void writeObject(ObjectOutputStream out) throws IOException { - // Don't call out.defaultWriteObject() - - // Write out Vector - Vector<Permission> permissions = new Vector<Permission>(perms.size()); - synchronized (this) { - permissions.addAll(perms); - } - - ObjectOutputStream.PutField pfields = out.putFields(); - pfields.put("permissions", permissions); - out.writeFields(); - } - - /* - * Reads in a Vector of FilePermissions and saves them in the perms field. - */ - @SuppressWarnings("unchecked") - private void readObject(ObjectInputStream in) throws IOException, - ClassNotFoundException { - // Don't call defaultReadObject() - - // Read in serialized fields - ObjectInputStream.GetField gfields = in.readFields(); - - // Get the one we want - Vector<Permission> permissions = (Vector<Permission>)gfields.get("permissions", null); - perms = new ArrayList<Permission>(permissions.size()); - perms.addAll(permissions); - } -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/io/Inputs.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,391 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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 conne02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.io; - -import java.io.Closeable; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; - -import java.nio.charset.Charset; -import java.nio.charset.UnsupportedCharsetException; -import java.nio.channels.Channels; - -import java.util.Collections; -import java.util.Arrays; -import java.util.ArrayList; -import java.util.List; - - -import org.classpath.icedtea.java.nio.file.FileRef; - -import org.classpath.icedtea.java.nio.file.attribute.Attributes; - -import org.classpath.icedtea.java.util.Scanner; - -/** - * {@note experimental} - * This class consists exclusively of static methods that operate on input - * sources. - * - * <p> The methods to read lines of text defined by this class recognize the - * following as Unicode line terminators: - * <ul> - * <li> <code>\u000D</code> followed by <code>\u000A</code>, - * CARRIAGE RETURN followed by LINE FEED </li> - * <li> <code>\u000A</code>, LINE FEED </li> - * <li> <code>\u000D</code>, CARRIAGE RETURN </li> - * <li> <code>\u2028</code>, LINE SEPARATOR </li> - * <li> <code>\u2029</code>, PARAGRAPH SEPARATOR </li> - * <li> <code>\u0085</code>, NEXT LINE (NEL)</li> - * </ul> - * - * @since 1.7 - */ - -public final class Inputs { - private Inputs() { } - - // initial buffer size when reading (or writing) - private static final int INITIAL_BUFFER_SIZE = 8192; - - // checks that charset is supported - private static void ensureCharsetIsSupported(String csn) { - if (csn == null) - throw new NullPointerException("'csn' is null"); - if (!Charset.isSupported(csn)) - throw new UnsupportedCharsetException(csn); - } - - /** - * Closes the given data source by invoking its {@link Closeable#close close} - * method. If the {@code close} method throws an {@code IOException} then it - * is silently ignored. If the source is already closed then invoking this - * method has no effect. - * - * <p> This method should not be used to close destinations or output - * streams that may be buffered. An I/O error may occur when flushing - * buffered data. - * - * @param source - * The data source - */ - public static void closeUnchecked(Closeable source) { - try { - source.close(); - } catch (IOException ignore) { } - } - - /** - * Read all bytes from the specified file. When all bytes have been read, or - * an I/O error occurs, then the file is closed. - * - * @param source - * The data source - * - * @return A byte array containing the bytes read from the file - * - * @throws IOException - * If an I/O error occurs - * @throws OutOfMemoryError - * If the required array size is too large - */ - public static byte[] readAllBytes(FileRef source) throws IOException { - long size = Attributes.readBasicFileAttributes(source).size(); - if (size > (long)Integer.MAX_VALUE) - throw new OutOfMemoryError("Required array size too large"); - InputStream in = Channels.newInputStream(source.newByteChannel()); - try { - return implReadAllBytes(in, Math.min((int)size, INITIAL_BUFFER_SIZE)); - } finally { - in.close(); - } - } - - /** - * Read all bytes from the specified file. When all bytes have been read, or - * an I/O error occurs, then the file is closed. - * - * @param source - * The data source - * - * @return A byte array containing the bytes read from the file - * - * @throws IOException - * If an I/O error occurs - * @throws OutOfMemoryError - * If the required array size is too large - */ - public static byte[] readAllBytes(File source) throws IOException { - InputStream in = new FileInputStream(source); - try { - return implReadAllBytes(in, INITIAL_BUFFER_SIZE); - } finally { - in.close(); - } - } - - /** - * Read all bytes from the specified input stream. - * - * <p> <b>Usage Example:</b> - * Suppose we want to open a connection to a resource identified by a URI, - * and read all bytes: - * <pre> - * URI uri = ... - * byte[] content = InputOutput.readAllBytes(uri.toURL().openStream()); - * </pre> - * - * <p> On return, the input stream will be at end of stream. - * - * @param source - * The data source - * - * @return A byte array containing the bytes read from the source - * - * @throws IOException - * If an I/O error occurs - * @throws OutOfMemoryError - * If the required array size is too large - */ - public static byte[] readAllBytes(InputStream source) throws IOException { - return implReadAllBytes(source, INITIAL_BUFFER_SIZE); - } - - private static byte[] implReadAllBytes(InputStream source, int initialSize) - throws IOException - { - byte[] buf = new byte[initialSize]; - int nread = 0; - int rem = buf.length; - int n; - while ((n = source.read(buf, nread, rem)) > 0) { - nread += n; - rem -= n; - if (rem <= 0) { - int newSize = buf.length << 1; - if (newSize <= buf.length) { - if (buf.length == Integer.MAX_VALUE) - throw new OutOfMemoryError("Required array size too large"); - newSize = Integer.MAX_VALUE; - } - rem = newSize - buf.length; - buf = Arrays.copyOf(buf, newSize); - } - } - return (buf.length == nread) ? buf : Arrays.copyOf(buf, nread); - } - - /** - * Read all lines from the specified file. Bytes from the file are - * converted into characters using the specified charset. When all lines - * have been read, or an I/O error occurs, then the file is closed. - * - * @param source - * The data source - * @param csn - * The name of the charset to be used - * - * @throws java.nio.charset.UnsupportedCharsetException - * If no support for the named charset is available - * in this instance of the Java virtual machine - * @throws java.nio.charset.MalformedInputException - * If the file contains a byte sequence that is not legal for the - * charset - * @throws IOException - * If an I/O error occurs - */ - public static List<String> readAllLines(FileRef source, String csn) - throws IOException - { - ensureCharsetIsSupported(csn); - Scanner s = new Scanner(source, csn); - try { - return implReadAllLines(s); - } finally { - s.close(); - } - } - - /** - * Read all lines from the specified file. Bytes from the file are - * converted into characters using the underlying platform's {@linkplain - * java.nio.charset.Charset#defaultCharset() default charset}. When all lines - * have been read, or an I/O error occurs, then the file is closed. - * - * @param source - * The data source - * - * @throws java.nio.charset.MalformedInputException - * If the file contains a byte sequence that is not legal for the - * default charset - * @throws IOException - * If an I/O error occurs - */ - public static List<String> readAllLines(FileRef source) throws IOException { - Scanner s = new Scanner(source); - try { - return implReadAllLines(s); - } finally { - s.close(); - } - } - - /** - * Read all lines from the specified file. Bytes from the file are - * converted into characters using the specified charset. When all lines - * have been read, or an I/O error occurs, then the file is closed. - * - * @param source - * The data source - * @param csn - * The name of the charset to be used - * - * @throws UnsupportedCharsetException - * If no support for the named charset is available - * in this instance of the Java virtual machine - * @throws java.nio.charset.MalformedInputException - * If the file contains a byte sequence that is not legal for the - * charset - * @throws IOException - * If an I/O error occurs - */ - public static List<String> readAllLines(File source, String csn) - throws IOException - { - ensureCharsetIsSupported(csn); - Scanner s = new Scanner(source, csn); - try { - return implReadAllLines(s); - } finally { - s.close(); - } - } - - /** - * Read all lines from the specified file. Bytes from the file are - * converted into characters using the underlying platform's {@linkplain - * Charset#defaultCharset() default charset}. When all lines have been read, - * or an I/O error occurs, then the file is closed. - * - * @param source - * The data source - * @throws java.nio.charset.MalformedInputException - * If the file contains a byte sequence that is not legal for the - * default charset - * @throws IOException - * If an I/O error occurs - */ - public static List<String> readAllLines(File source) throws IOException { - Scanner s = new Scanner(source); - try { - return implReadAllLines(s); - } finally { - s.close(); - } - } - - /** - * Read all lines from the specified input stream. Bytes from the stream are - * converted into characters using the specified charset. - * - * <p> On return, the input stream will be at end of stream. - * - * @param source - * The input stream to read from - * @param csn - * The name of the charset to be used - * - * @throws UnsupportedCharsetException - * If no support for the named charset is available - * in this instance of the Java virtual machine - * @throws java.nio.charset.MalformedInputException - * If a byte sequence that is not legal for the charset is read - * from the input - * @throws IOException - * If an I/O error occurs - */ - public static List<String> readAllLines(InputStream source, String csn) - throws IOException - { - ensureCharsetIsSupported(csn); - return implReadAllLines(new Scanner(source, csn)); - } - - /** - * Read all lines from the specified input stream. Bytes from the stream are - * converted into characters using the underlying platform's {@linkplain - * Charset#defaultCharset() default charset}. - * - * <p> On return, the input stream will be at end of stream. - * - * @param source - * The input stream to read from - * - * @return An unmodifiable list of the lines read from the input stream - * - * @throws java.nio.charset.MalformedInputException - * If a byte sequence that is not legal for the default charset is - * read from the input - * @throws IOException - * If an I/O error occurs - */ - public static List<String> readAllLines(InputStream source) throws IOException { - return implReadAllLines(new Scanner(source)); - } - - /** - * Read all lines from the from the specified source. - * - * <p> On return, the input source will be at end of stream. - * - * @param source - * The input stream to read from - * - * @return An unmodifiable list of the lines read from source - * - * @throws IOException - * If an I/O error occurs - */ - public static List<String> readAllLines(Readable source) throws IOException { - return implReadAllLines(new Scanner(source)); - } - - private static List<String> implReadAllLines(Scanner s) throws IOException { - try { - List<String> result = new ArrayList<String>(); - while (s.hasNextLine()) { - result.add(s.nextLine()); - } - return Collections.unmodifiableList(result); - } finally { - IOException ioe = s.ioException(); - if (ioe != null) - throw ioe; - } - } -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/io/Outputs.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,362 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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 conne02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.io; - -import java.io.BufferedWriter; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.io.OutputStreamWriter; - -import java.nio.ByteBuffer; -import java.nio.charset.Charset; -import java.nio.charset.UnsupportedCharsetException; -import java.nio.channels.Channels; -import java.nio.channels.WritableByteChannel; -import java.util.Arrays; -import java.util.List; - -import org.classpath.icedtea.java.nio.file.FileRef; - -import static org.classpath.icedtea.java.nio.file.StandardOpenOption.CREATE; -import static org.classpath.icedtea.java.nio.file.StandardOpenOption.TRUNCATE_EXISTING; -import static org.classpath.icedtea.java.nio.file.StandardOpenOption.WRITE; - -/** - * {@note experimental} - * This class consists exclusively of static methods that operate on output - * destinations. - * - * <p> The methods to write lines of text output a line terminator following - * each line. The line terminator that is output is platform line terminated, - * as defined by the {@code line.separator} system property. - * - * @since 1.7 - */ - -public final class Outputs { - private Outputs() { } - - // checks that charset is supported - private static void ensureCharsetIsSupported(String csn) { - if (csn == null) - throw new NullPointerException("'csn' is null"); - if (!Charset.isSupported(csn)) - throw new UnsupportedCharsetException(csn); - } - - /** - * Writes a byte array to a file. The file is created if it does not exist. - * If the file already exists, it is first truncated. - * - * @throws IOException - * If an I/O error occurs - */ - public static void write(FileRef file, byte[] bytes) throws IOException { - write(file, bytes, 0, bytes.length); - } - - /** - * Writes a byte array to a file. The file is created if it does not exist. - * If the file already exists, it is first truncated. - * - * @throws IndexOutOfBoundsException - * If {@code off} or {@code len} is negative, or {@code off+len} - * is greater than the length of the array - * @throws IOException - * If an I/O error occurs - */ - public static void write(FileRef file, byte[] bytes, int off, int len) - throws IOException - { - WritableByteChannel wbc = file.newByteChannel(WRITE, CREATE, TRUNCATE_EXISTING); - try { - int pos = off; - while (pos < len) { - int size = Math.min(len-pos, 8192); - ByteBuffer bb = ByteBuffer.wrap(bytes, pos, size); - int n = wbc.write(bb); - pos += n; - } - } finally { - wbc.close(); - } - } - - /** - * Writes the given lines of text to the specified file. The characters in - * each line are encoded into bytes using the specified charset. When all - * lines have been written, or an I/O error occurs, then the file is closed. - * - * @param file - * The file - * @param lines - * The list of lines to write (in order) - * @param csn - * The name of the charset to be used - * - * @throws java.nio.charset.UnsupportedCharsetException - * If no support for the named charset is available - * in this instance of the Java virtual machine - * @throws java.nio.charset.UnmappableCharacterException - * Where a line contains a character that cannot be mapped to an - * output byte sequence - * @throws IOException - * If an I/O error occurs - */ - public static void writeLines(FileRef file, List<String> lines, String csn) - throws IOException - { - ensureCharsetIsSupported(csn); - WritableByteChannel wbc = file.newByteChannel(WRITE, CREATE, TRUNCATE_EXISTING); - BufferedWriter writer = new BufferedWriter(Channels.newWriter(wbc, csn)); - try { - implWriteLines(writer, lines); - } finally { - writer.close(); - } - } - - /** - * Writes the given lines of text to the specified file. The characters in - * each line are encoded into bytes using the underlying platform's {@linkplain - * Charset#defaultCharset() default charset}. When all lines have been - * written, or an I/O error occurs, then the file is closed. - * - * @param file - * The file - * @param lines - * The list of lines to write (in order) - * - * @throws java.nio.charset.UnmappableCharacterException - * Where a line contains a character that cannot be mapped to an - * output byte sequence - * @throws IOException - * If an I/O error occurs - */ - public static void writeLines(FileRef file, List<String> lines) - throws IOException - { - writeLines(file, lines, Charset.defaultCharset().name()); - } - - /** - * Writes the given lines of text to the specified file. The characters in - * each line are encoded into bytes using the underlying platform's {@linkplain - * Charset#defaultCharset() default charset}. When all lines have been - * written, or an I/O error occurs, then the file is closed. - * - * @param file - * The file - * @param lines - * The array of lines to write (in order) - * - * @throws java.nio.charset.UnmappableCharacterException - * Where a line contains a character that cannot be mapped to an - * output byte sequence - * @throws IOException - * If an I/O error occurs - */ - public static void writeLines(FileRef file, String... lines) - throws IOException - { - writeLines(file, Arrays.asList(lines), Charset.defaultCharset().name()); - } - - /** - * Writes a byte array to a file. The file is created if it does not exist. - * If the file already exists, it is first truncated. - * - * @param file - * The file - * @param bytes - * The byte array to write to the file - * - * @throws IOException - * If an I/O error occurs - */ - public static void write(File file, byte[] bytes) throws IOException { - write(file, bytes, 0, bytes.length); - } - - /** - * Writes a byte array to a file. The file is created if it does not exist. - * If the file already exists, it is first truncated. - * - * @throws IndexOutOfBoundsException - * If {@code off} or {@code len} is negative, or {@code off+len} - * is greater than the length of the array - * @throws IOException - * If an I/O error occurs - */ - public static void write(File file, byte[] bytes, int off, int len) - throws IOException - { - FileOutputStream out = new FileOutputStream(file); - try { - out.write(bytes, off, len); - } finally { - out.close(); - } - } - - /** - * Writes the given lines of text to the specified file. The characters in - * each line are encoded into bytes using the specified charset. When all - * lines have been written, or an I/O error occurs, then the file is closed. - * - * @param file - * The file - * @param lines - * The list of lines to write (in order) - * @param csn - * The name of the charset to be used - * - * @throws java.nio.charset.UnsupportedCharsetException - * If no support for the named charset is available - * in this instance of the Java virtual machine - * @throws java.nio.charset.UnmappableCharacterException - * Where a line contains a character that cannot be mapped to an - * output byte sequence - * @throws IOException - * If an I/O error occurs - */ - public static void writeLines(File file, List<String> lines, String csn) - throws IOException - { - ensureCharsetIsSupported(csn); - FileOutputStream out = new FileOutputStream(file); - BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, csn)); - try { - implWriteLines(writer, lines); - } finally { - writer.close(); - } - } - - /** - * Writes the given lines of text to the specified file. The characters in - * each line are encoded into bytes using the underlying platform's {@linkplain - * Charset#defaultCharset() default charset}. When all lines have been - * written, or an I/O error occurs, then the file is closed. - * - * @param file - * The file - * @param lines - * The list of lines to write (in order) - * - * @throws java.nio.charset.UnmappableCharacterException - * Where a line contains a character that cannot be mapped to an - * output byte sequence - * @throws IOException - * If an I/O error occurs - */ - public static void writeLines(File file, List<String> lines) - throws IOException - { - writeLines(file, lines, Charset.defaultCharset().name()); - } - - /** - * Writes the given lines of text to the specified file. The characters in - * each line are encoded into bytes using the underlying platform's {@linkplain - * Charset#defaultCharset() default charset}. When all lines have been - * written, or an I/O error occurs, then the file is closed. - * - * @param file - * The file - * @param lines - * The array of lines to write (in order) - * - * @throws java.nio.charset.UnmappableCharacterException - * Where a line contains a character that cannot be mapped to an - * output byte sequence - * @throws IOException - * If an I/O error occurs - */ - public static void writeLines(File file, String... lines) - throws IOException - { - writeLines(file, Arrays.asList(lines), Charset.defaultCharset().name()); - } - - /** - * Writes the given lines of text to the specified output stream. The - * characters in each line are encoded into bytes using the specified charset. - * - * @param out - * The output stream - * @param lines - * The list of lines to write (in order) - * @param csn - * The name of the charset to be used - * - * @throws java.nio.charset.UnmappableCharacterException - * Where a line contains a character that cannot be mapped to an - * output byte sequence - * @throws IOException - * If an I/O error occurs - */ - public static void writeLines(OutputStream out, List<String> lines, String csn) - throws IOException - { - BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, csn)); - implWriteLines(writer, lines); - writer.flush(); - } - - /** - * Writes the given lines of text to the specified output stream. The - * characters in each line are encoded into bytes using the underlying - * platform's {@linkplain Charset#defaultCharset() default charset}. - * - * @param out - * The output stream - * @param lines - * The list of lines to write (in order) - * - * @throws java.nio.charset.UnmappableCharacterException - * Where a line contains a character that cannot be mapped to an - * output byte sequence - * @throws IOException - * If an I/O error occurs - */ - public static void writeLines(OutputStream out, List<String> lines) - throws IOException - { - writeLines(out, lines, Charset.defaultCharset().name()); - } - - private static void implWriteLines(BufferedWriter writer, List<String> lines) - throws IOException - { - for (String line: lines) { - writer.write(line); - writer.newLine(); - } - } -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/net/ProtocolFamily.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,40 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.net; - -/** - * Represents a family of communication protocols. - * - * @since 1.7 - */ - -public interface ProtocolFamily { - /** - * Returns the name of the protocol family. - */ - String name(); -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/net/SocketOption.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,56 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.net; - -/** - * A socket option associated with a socket. - * - * <p> In the {@link java.nio.channels channels} package, the {@link - * java.nio.channels.NetworkChannel} interface defines the {@link - * java.nio.channels.NetworkChannel#setOption(SocketOption,Object) setOption} - * and {@link java.nio.channels.NetworkChannel#getOption(SocketOption) getOption} - * methods to set and query the channel's socket options. - * - * @param <T> The type of the socket option value. - * - * @since 1.7 - * - * @see StandardSocketOption - */ - -public interface SocketOption<T> { - - /** - * Returns the name of the socket option. - */ - String name(); - - /** - * Returns the type of the socket option value. - */ - Class<T> type(); -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/net/StandardProtocolFamily.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,46 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.net; - -/** - * Defines the standard families of communication protocols. - * - * @since 1.7 - */ - -public enum StandardProtocolFamily implements ProtocolFamily { - - /** - * Internet Protocol Version 4 (IPv4) - */ - INET, - - /** - * Internet Protocol Version 6 (IPv6) - */ - INET6 -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/net/StandardSocketOption.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,370 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.net; - -import java.net.NetworkInterface; - -/** - * Defines the <em>standard</em> socket options. - * - * <p> The {@link SocketOption#name name} of each socket option defined by this - * class is its field name. - * - * <p> In this release, the socket options defined here are used by {@link - * java.nio.channels.NetworkChannel network} channels in the {@link - * java.nio.channels channels} package. - * - * @since 1.7 - */ - -public final class StandardSocketOption { - private StandardSocketOption() { } - - // -- SOL_SOCKET -- - - /** - * Allow transmission of broadcast datagrams. - * - * <p> The value of this socket option is a {@code Boolean} that represents - * whether the option is enabled or disabled. The option is specific to - * datagram-oriented sockets sending to {@link java.net.Inet4Address IPv4} - * broadcast addresses. When the socket option is enabled then the socket - * can be used to send <em>broadcast datagrams</em>. - * - * <p> The initial value of this socket option is {@code FALSE}. The socket - * option may be enabled or disabled at any time. Some operating systems may - * require that the Java virtual machine be started with implementation - * specific privileges to enable this option or send broadcast datagrams. - * - * @see <a href="http://www.ietf.org/rfc/rfc919.txt">RFC 929: - * Broadcasting Internet Datagrams</a> - * @see DatagramSocket#setBroadcast - */ - public static final SocketOption<Boolean> SO_BROADCAST = - new StdSocketOption<Boolean>("SO_BROADCAST", Boolean.class); - - /** - * Keep connection alive. - * - * <p> The value of this socket option is a {@code Boolean} that represents - * whether the option is enabled or disabled. When the {@code SO_KEEPALIVE} - * option is enabled the operating system may use a <em>keep-alive</em> - * mechanism to periodically probe the other end of a connection when the - * connection is otherwise idle. The exact semantics of the keep alive - * mechanism is system dependent and therefore unspecified. - * - * <p> The initial value of this socket option is {@code FALSE}. The socket - * option may be enabled or disabled at any time. - * - * @see <a href="http://www.ietf.org/rfc/rfc1122.txt">RFC 1122 - * Requirements for Internet Hosts -- Communication Layers</a> - * @see Socket#setKeepAlive - */ - public static final SocketOption<Boolean> SO_KEEPALIVE = - new StdSocketOption<Boolean>("SO_KEEPALIVE", Boolean.class); - - /** - * The size of the socket send buffer. - * - * <p> The value of this socket option is an {@code Integer} that is the - * size of the socket send buffer in bytes. The socket send buffer is an - * output buffer used by the networking implementation. It may need to be - * increased for high-volume connections. The value of the socket option is - * a <em>hint</em> to the implementation to size the buffer and the actual - * size may differ. The socket option can be queried to retrieve the actual - * size. - * - * <p> For datagram-oriented sockets, the size of the send buffer may limit - * the size of the datagrams that may be sent by the socket. Whether - * datagrams larger than the buffer size are sent or discarded is system - * dependent. - * - * <p> The initial/default size of the socket send buffer and the range of - * allowable values is system dependent although a negative size is not - * allowed. An attempt to set the socket send buffer to larger than its - * maximum size causes it to be set to its maximum size. - * - * <p> An implementation allows this socket option to be set before the - * socket is bound or connected. Whether an implementation allows the - * socket send buffer to be changed after the socket is bound is system - * dependent. - * - * @see Socket#setSendBufferSize - */ - public static final SocketOption<Integer> SO_SNDBUF = - new StdSocketOption<Integer>("SO_SNDBUF", Integer.class); - - - /** - * The size of the socket receive buffer. - * - * <p> The value of this socket option is an {@code Integer} that is the - * size of the socket receive buffer in bytes. The socket receive buffer is - * an input buffer used by the networking implementation. It may need to be - * increased for high-volume connections or decreased to limit the possible - * backlog of incoming data. The value of the socket option is a - * <em>hint</em> to the implementation to size the buffer and the actual - * size may differ. - * - * <p> For datagram-oriented sockets, the size of the receive buffer may - * limit the size of the datagrams that can be received. Whether datagrams - * larger than the buffer size can be received is system dependent. - * Increasing the socket receive buffer may be important for cases where - * datagrams arrive in bursts faster than they can be processed. - * - * <p> In the case of stream-oriented sockets and the TCP/IP protocol, the - * size of the socket receive buffer may be used when advertising the size - * of the TCP receive window to the remote peer. - * - * <p> The initial/default size of the socket receive buffer and the range - * of allowable values is system dependent although a negative size is not - * allowed. An attempt to set the socket receive buffer to larger than its - * maximum size causes it to be set to its maximum size. - * - * <p> An implementation allows this socket option to be set before the - * socket is bound or connected. Whether an implementation allows the - * socket receive buffer to be changed after the socket is bound is system - * dependent. - * - * @see <a href="http://www.ietf.org/rfc/rfc1323.txt">RFC 1323: TCP - * Extensions for High Performance</a> - * @see Socket#setReceiveBufferSize - * @see ServerSocket#setReceiveBufferSize - */ - public static final SocketOption<Integer> SO_RCVBUF = - new StdSocketOption<Integer>("SO_RCVBUF", Integer.class); - - /** - * Re-use address. - * - * <p> The value of this socket option is a {@code Boolean} that represents - * whether the option is enabled or disabled. The exact semantics of this - * socket option are socket type and system dependent. - * - * <p> In the case of stream-oriented sockets, this socket option will - * usually determine whether the socket can be bound to a socket address - * when a previous connection involving that socket address is in the - * <em>TIME_WAIT</em> state. On implementations where the semantics differ, - * and the socket option is not required to be enabled in order to bind the - * socket when a previous connection is in this state, then the - * implementation may choose to ignore this option. - * - * <p> For datagram-oriented sockets the socket option is used to allow - * multiple programs bind to the same address. This option should be enabled - * when the socket is to be used for Internet Protocol (IP) multicasting. - * - * <p> An implementation allows this socket option to be set before the - * socket is bound or connected. Changing the value of this socket option - * after the socket is bound has no effect. The default value of this - * socket option is system dependent. - * - * @see <a href="http://www.ietf.org/rfc/rfc793.txt">RFC 793: Transmission - * Control Protocol</a> - * @see ServerSocket#setReuseAddress - */ - public static final SocketOption<Boolean> SO_REUSEADDR = - new StdSocketOption<Boolean>("SO_REUSEADDR", Boolean.class); - - /** - * Linger on close if data is present. - * - * <p> The value of this socket option is an {@code Integer} that controls - * the action taken when unsent data is queued on the socket and a method - * to close the socket is invoked. If the value of the socket option is zero - * or greater, then it represents a timeout value, in seconds, known as the - * <em>linger interval</em>. The linger interval is the timeout for the - * {@code close} method to block while the operating system attempts to - * transmit the unsent data or it decides that it is unable to transmit the - * data. If the value of the socket option is less than zero then the option - * is disabled. In that case the {@code close} method does not wait until - * unsent data is transmitted; if possible the operating system will transmit - * any unsent data before the connection is closed. - * - * <p> This socket option is intended for use with sockets that are configured - * in {@link java.nio.channels.SelectableChannel#isBlocking() blocking} mode - * only. The behavior of the {@code close} method when this option is - * enabled on a non-blocking socket is not defined. - * - * <p> The initial value of this socket option is a negative value, meaning - * that the option is disabled. The option may be enabled, or the linger - * interval changed, at any time. The maximum value of the linger interval - * is system dependent. Setting the linger interval to a value that is - * greater than its maximum value causes the linger interval to be set to - * its maximum value. - * - * @see Socket#setSoLinger - */ - public static final SocketOption<Integer> SO_LINGER = - new StdSocketOption<Integer>("SO_LINGER", Integer.class); - - - // -- IPPROTO_IP -- - - /** - * The Type of Service (ToS) octet in the Internet Protocol (IP) header. - * - * <p> The value of this socket option is an {@code Integer} representing - * the value of the ToS octet in IP packets sent by sockets to an {@link - * StandardProtocolFamily#INET IPv4} socket. The interpretation of the ToS - * octet is network specific and is not defined by this class. Further - * information on the ToS octet can be found in <a - * href="http://www.ietf.org/rfc/rfc1349.txt">RFC 1349</a> and <a - * href="http://www.ietf.org/rfc/rfc2474.txt">RFC 2474</a>. The value - * of the socket option is a <em>hint</em>. An implementation may ignore the - * value, or ignore specific values. - * - * <p> The initial/default value of the TOS field in the ToS octet is - * implementation specific but will typically be {@code 0}. For - * datagram-oriented sockets the option may be configured at any time after - * the socket has been bound. The new value of the octet is used when sending - * subsequent datagrams. It is system dependent whether this option can be - * queried or changed prior to binding the socket. - * - * <p> The behavior of this socket option on a stream-oriented socket, or an - * {@link StandardProtocolFamily#INET6 IPv6} socket, is not defined in this - * release. - * - * @see DatagramSocket#setTrafficClass - */ - public static final SocketOption<Integer> IP_TOS = - new StdSocketOption<Integer>("IP_TOS", Integer.class); - - /** - * The network interface for Internet Protocol (IP) multicast datagrams. - * - * <p> The value of this socket option is a {@link NetworkInterface} that - * represents the outgoing interface for multicast datagrams sent by the - * datagram-oriented socket. For {@link StandardProtocolFamily#INET6 IPv6} - * sockets then it is system dependent whether setting this option also - * sets the outgoing interface for multlicast datagrams sent to IPv4 - * addresses. - * - * <p> The initial/default value of this socket option may be {@code null} - * to indicate that outgoing interface will be selected by the operating - * system, typically based on the network routing tables. An implementation - * allows this socket option to be set after the socket is bound. Whether - * the socket option can be queried or changed prior to binding the socket - * is system dependent. - * - * @see java.nio.channels.MulticastChannel - * @see MulticastSocket#setInterface - */ - public static final SocketOption<NetworkInterface> IP_MULTICAST_IF = - new StdSocketOption<NetworkInterface>("IP_MULTICAST_IF", NetworkInterface.class); - - /** - * The <em>time-to-live</em> for Internet Protocol (IP) multicast datagrams. - * - * <p> The value of this socket option is an {@code Integer} in the range - * <tt>0 <= value <= 255</tt>. It is used to control - * the scope of multicast datagrams sent by the datagram-oriented socket. - * In the case of an {@link StandardProtocolFamily#INET IPv4} socket - * the option is the time-to-live (TTL) on multicast datagrams sent by the - * socket. Datagrams with a TTL of zero are not transmitted on the network - * but may be delivered locally. In the case of an {@link - * StandardProtocolFamily#INET6 IPv6} socket the option is the - * <em>hop limit</em> which is number of <em>hops</em> that the datagram can - * pass through before expiring on the network. For IPv6 sockets it is - * system dependent whether the option also sets the <em>time-to-live</em> - * on multicast datagrams sent to IPv4 addresses. - * - * <p> The initial/default value of the time-to-live setting is typically - * {@code 1}. An implementation allows this socket option to be set after - * the socket is bound. Whether the socket option can be queried or changed - * prior to binding the socket is system dependent. - * - * @see java.nio.channels.MulticastChannel - * @see MulticastSocket#setTimeToLive - */ - public static final SocketOption<Integer> IP_MULTICAST_TTL = - new StdSocketOption<Integer>("IP_MULTICAST_TTL", Integer.class); - - /** - * Loopback for Internet Protocol (IP) multicast datagrams. - * - * <p> The value of this socket option is a {@code Boolean} that controls - * the <em>loopback</em> of multicast datagrams. The value of the socket - * option represents if the option is enabled or disabled. - * - * <p> The exact semantics of this socket options are system dependent. - * In particular, it is system dependent whether the loopback applies to - * multicast datagrams sent from the socket or received by the socket. - * For {@link StandardProtocolFamily#INET6 IPv6} sockets then it is - * system dependent whether the option also applies to multicast datagrams - * sent to IPv4 addresses. - * - * <p> The initial/default value of this socket option is {@code TRUE}. An - * implementation allows this socket option to be set after the socket is - * bound. Whether the socket option can be queried or changed prior to - * binding the socket is system dependent. - * - * @see java.nio.channels.MulticastChannel - * @see MulticastSocket#setLoopbackMode - */ - public static final SocketOption<Boolean> IP_MULTICAST_LOOP = - new StdSocketOption<Boolean>("IP_MULTICAST_LOOP", Boolean.class); - - - // -- IPPROTO_TCP -- - - /** - * Disable the Nagle algorithm. - * - * <p> The value of this socket option is a {@code Boolean} that represents - * whether the option is enabled or disabled. The socket option is specific to - * stream-oriented sockets using the TCP/IP protocol. TCP/IP uses an algorithm - * known as <em>The Nagle Algorithm</em> to coalesce short segments and - * improve network efficiency. - * - * <p> The default value of this socket option is {@code FALSE}. The - * socket option should only be enabled in cases where it is known that the - * coalescing impacts performance. The socket option may be enabled at any - * time. In other words, the Nagle Algorithm can be disabled. Once the option - * is enabled, it is system dependent whether it can be subsequently - * disabled. If it cannot, then invoking the {@code setOption} method to - * disable the option has no effect. - * - * @see <a href="http://www.ietf.org/rfc/rfc1122.txt">RFC 1122: - * Requirements for Internet Hosts -- Communication Layers</a> - * @see Socket#setTcpNoDelay - */ - public static final SocketOption<Boolean> TCP_NODELAY = - new StdSocketOption<Boolean>("TCP_NODELAY", Boolean.class); - - - private static class StdSocketOption<T> implements SocketOption<T> { - private final String name; - private final Class<T> type; - StdSocketOption(String name, Class<T> type) { - this.name = name; - this.type = type; - } - public String name() { return name; } - public Class<T> type() { return type; } - public String toString() { return name; } - } -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/AsynchronousByteChannel.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,206 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.channels; - -import java.nio.ByteBuffer; -import java.util.concurrent.Future; - -/** - * An asynchronous channel that can read and write bytes. - * - * <p> Some channels may not allow more than one read to be outstanding at any - * given time. If a thread invokes a read method before a previous read - * operation has completed then a {@link ReadPendingException} will be thrown. - * Similarly, if a write method is invoked before a previous write has completed - * then {@link WritePendingException} is thrown. Whether or not other kinds of - * I/O operations may proceed concurrently with a read operation depends upon - * the type of the channel. - * - * <p> Note that {@link java.nio.ByteBuffer ByteBuffers} are not safe for use by - * multiple concurrent threads. When a read or write operation is initiated then - * care must be taken to ensure that the buffer is not accessed until the - * operation completes. - * - * @see Channels#newInputStream(AsynchronousByteChannel) - * @see Channels#newOutputStream(AsynchronousByteChannel) - * - * @since 1.7 - */ - -public interface AsynchronousByteChannel - extends AsynchronousChannel -{ - /** - * Reads a sequence of bytes from this channel into the given buffer. - * - * <p> This method initiates an operation to read a sequence of bytes from - * this channel into the given buffer. The method returns a {@link Future} - * representing the pending result of the operation. The result of the - * operation, obtained by invoking the {@code Future} 's {@link - * Future#get() get} method, is the number of bytes read or {@code -1} if - * all bytes have been read and the channel has reached end-of-stream. - * - * <p> This method initiates a read operation to read up to <i>r</i> bytes - * from the channel, where <i>r</i> is the number of bytes remaining in the - * buffer, that is, {@code dst.remaining()} at the time that the read is - * attempted. Where <i>r</i> is 0, the read operation completes immediately - * with a result of {@code 0} without initiating an I/O operation. - * - * <p> Suppose that a byte sequence of length <i>n</i> is read, where - * <tt>0</tt> <tt><</tt> <i>n</i> <tt><=</tt> <i>r</i>. - * This byte sequence will be transferred into the buffer so that the first - * byte in the sequence is at index <i>p</i> and the last byte is at index - * <i>p</i> <tt>+</tt> <i>n</i> <tt>-</tt> <tt>1</tt>, - * where <i>p</i> is the buffer's position at the moment the read is - * performed. Upon completion the buffer's position will be equal to - * <i>p</i> <tt>+</tt> <i>n</i>; its limit will not have changed. - * - * <p> Buffers are not safe for use by multiple concurrent threads so care - * should be taken to not to access the buffer until the operaton has completed. - * - * <p> This method may be invoked at any time. Some channel types may not - * allow more than one read to be outstanding at any given time. If a thread - * initiates a read operation before a previous read operation has - * completed then a {@link ReadPendingException} will be thrown. - * - * <p> The <tt>handler</tt> parameter is used to specify a {@link - * CompletionHandler}. When the read operation completes the handler's - * {@link CompletionHandler#completed completed} method is executed. - * - * - * @param dst - * The buffer into which bytes are to be transferred - * @param attachment - * The object to attach to the I/O operation; can be {@code null} - * @param handler - * The completion handler object; can be {@code null} - * - * @return A Future representing the result of the operation - * - * @throws IllegalArgumentException - * If the buffer is read-only - * @throws ReadPendingException - * If the channel does not allow more than one read to be outstanding - * and a previous read has not completed - */ - <A> Future<Integer> read(ByteBuffer dst, - A attachment, - CompletionHandler<Integer,? super A> handler); - - /** - * Reads a sequence of bytes from this channel into the given buffer. - * - * <p> An invocation of this method of the form <tt>c.read(dst)</tt> - * behaves in exactly the same manner as the invocation - * <blockquote><pre> - * c.read(dst, null, null);</pre></blockquote> - * - * @param dst - * The buffer into which bytes are to be transferred - * - * @return A Future representing the result of the operation - * - * @throws IllegalArgumentException - * If the buffer is read-only - * @throws ReadPendingException - * If the channel does not allow more than one read to be outstanding - * and a previous read has not completed - */ - Future<Integer> read(ByteBuffer dst); - - /** - * Writes a sequence of bytes to this channel from the given buffer. - * - * <p> This method initiates an operation to write a sequence of bytes to - * this channel from the given buffer. This method returns a {@link - * Future} representing the pending result of the operation. The result - * of the operation, obtained by invoking the <tt>Future</tt>'s {@link - * Future#get() get} method, is the number of bytes written, possibly zero. - * - * <p> This method initiates a write operation to write up to <i>r</i> bytes - * to the channel, where <i>r</i> is the number of bytes remaining in the - * buffer, that is, {@code src.remaining()} at the moment the write is - * attempted. Where <i>r</i> is 0, the write operation completes immediately - * with a result of {@code 0} without initiating an I/O operation. - * - * <p> Suppose that a byte sequence of length <i>n</i> is written, where - * <tt>0</tt> <tt><</tt> <i>n</i> <tt><=</tt> <i>r</i>. - * This byte sequence will be transferred from the buffer starting at index - * <i>p</i>, where <i>p</i> is the buffer's position at the moment the - * write is performed; the index of the last byte written will be - * <i>p</i> <tt>+</tt> <i>n</i> <tt>-</tt> <tt>1</tt>. - * Upon completion the buffer's position will be equal to - * <i>p</i> <tt>+</tt> <i>n</i>; its limit will not have changed. - * - * <p> Buffers are not safe for use by multiple concurrent threads so care - * should be taken to not to access the buffer until the operaton has completed. - * - * <p> This method may be invoked at any time. Some channel types may not - * allow more than one write to be outstanding at any given time. If a thread - * initiates a write operation before a previous write operation has - * completed then a {@link WritePendingException} will be thrown. - * - * <p> The <tt>handler</tt> parameter is used to specify a {@link - * CompletionHandler}. When the write operation completes the handler's - * {@link CompletionHandler#completed completed} method is executed. - * - * @param src - * The buffer from which bytes are to be retrieved - * @param attachment - * The object to attach to the I/O operation; can be {@code null} - * @param handler - * The completion handler object; can be {@code null} - * - * @return A Future representing the result of the operation - * - * @throws WritePendingException - * If the channel does not allow more than one write to be outstanding - * and a previous write has not completed - */ - <A> Future<Integer> write(ByteBuffer src, - A attachment, - CompletionHandler<Integer,? super A> handler); - - /** - * Writes a sequence of bytes to this channel from the given buffer. - * - * <p> An invocation of this method of the form <tt>c.write(src)</tt> - * behaves in exactly the same manner as the invocation - * <blockquote><pre> - * c.write(src, null, null);</pre></blockquote> - * - * @param src - * The buffer from which bytes are to be retrieved - * - * @return A Future representing the result of the operation - * - * @throws WritePendingException - * If the channel does not allow more than one write to be outstanding - * and a previous write has not completed - */ - Future<Integer> write(ByteBuffer src); -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/AsynchronousChannel.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,118 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.channels; - -import java.io.IOException; -import java.nio.channels.Channel; -import java.util.concurrent.Future; // javadoc - -/** - * A channel that supports asynchronous I/O operations. Asynchronous I/O - * operations will usually take one of two forms: - * - * <ol> - * <li><pre>{@link Future}<V> <em>operation</em>(<em>...</em>)</pre></li> - * <li><pre>Future<V> <em>operation</em>(<em>...</em> A attachment, {@link CompletionHandler}<V,? super A> handler)</pre></li> - * </ol> - * - * where <i>operation</i> is the name of the I/O operation (read or write for - * example), <i>V</i> is the result type of the I/O operation, and <i>A</i> is - * the type of an object attached to the I/O operation to provide context when - * consuming the result. The attachment is important for cases where a - * <em>state-less</em> {@code CompletionHandler} is used to consume the result - * of many I/O operations. - * - * <p> In the first form, the methods defined by the {@link Future Future} - * interface may be used to check if the operation has completed, wait for its - * completion, and to retrieve the result. In the second form, a {@link - * CompletionHandler} is invoked to consume the result of the I/O operation when - * it completes, fails, or is cancelled. - * - * <p> A channel that implements this interface is <em>asynchronously - * closeable</em>: If an I/O operation is outstanding on the channel and the - * channel's {@link #close close} method is invoked, then the I/O operation - * fails with the exception {@link AsynchronousCloseException}. - * - * <p> Asynchronous channels are safe for use by multiple concurrent threads. - * Some channel implementations may support concurrent reading and writing, but - * may not allow more than one read and one write operation to be outstanding at - * any given time. - * - * <h4>Cancellation</h4> - * - * <p> The {@code Future} interface defines the {@link Future#cancel cancel} - * method to cancel execution of a task. - * - * <p> Where the {@code cancel} method is invoked with the {@code - * mayInterruptIfRunning} parameter set to {@code true} then the I/O operation - * may be interrupted by closing the channel. This will cause any other I/O - * operations outstanding on the channel to complete with the exception {@link - * AsynchronousCloseException}. - * - * <p> If a {@code CompletionHandler} is specified when initiating an I/O - * operation, and the {@code cancel} method is invoked to cancel the I/O - * operation before it completes, then the {@code CompletionHandler}'s {@link - * CompletionHandler#cancelled cancelled} method is invoked. - * - * <p> If an implementation of this interface supports a means to cancel I/O - * operations, and where cancellation may leave the channel, or the entity to - * which it is connected, in an inconsistent state, then the channel is put into - * an implementation specific <em>error state</em> that prevents further - * attempts to initiate I/O operations on the channel. For example, if a read - * operation is cancelled but the implementation cannot guarantee that bytes - * have not been read from the channel then it puts the channel into error state - * state; further attempts to initiate a {@code read} operation causes an - * unspecified runtime exception to be thrown. - * - * <p> Where the {@code cancel} method is invoked to cancel read or write - * operations then it recommended that all buffers used in the I/O operations be - * discarded or care taken to ensure that the buffers are not accessed while the - * channel remains open. - * - * @since 1.7 - */ - -public interface AsynchronousChannel - extends Channel -{ - /** - * Closes this channel. - * - * <p> Any outstanding asynchronous operations upon this channel will - * complete with the exception {@link AsynchronousCloseException}. After a - * channel is closed then further attempts to initiate asynchronous I/O - * operations complete immediately with cause {@link ClosedChannelException}. - * - * <p> This method otherwise behaves exactly as specified by the {@link - * Channel} interface. - * - * @throws IOException - * If an I/O error occurs - */ - - void close() throws IOException; -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/AsynchronousChannelGroup.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,317 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.channels; - -import java.io.IOException; -import java.util.concurrent.*; - -import org.classpath.icedtea.java.nio.channels.spi.AsynchronousChannelProvider; - -/** - * A grouping of asynchronous channels for the purpose of resource sharing. - * - * <p> An asynchronous channel group encapsulates the mechanics required to - * handle the completion of I/O operations initiated by {@link AsynchronousChannel - * asynchronous channels} that are bound to the group. A group has an associated - * thread pool to which tasks are submitted to handle I/O events and dispatch to - * {@link CompletionHandler completion-handlers} that consume the result of - * asynchronous operations performed on channels in the group. In addition to - * handling I/O events, the pooled threads may also execute other tasks required - * to support the execution of asynchronous I/O operations. - * - * <p> An asynchronous channel group is created by invoking the {@link - * #withFixedThreadPool withFixedThreadPool} or {@link #withCachedThreadPool - * withCachedThreadPool} methods with the appropriate thread pool. Channels are - * bound to a group by specifying the group when constructing the channel. The - * group <em>takes ownership</em> of the thread pool; termination of the group - * results in the shutdown of the thread pool. - * - * <p> In addition to groups created explicitly, the Java virtual machine - * maintains a system-wide <em>default group</em> that is constructed - * automatically. Asynchronous channels that do not specify a group at - * construction time are bound to the default group. The default group has an - * associated thread pool that creates new threads as needed. The default group - * may be configured by means of system properties defined in the table below. - * Where the {@link java.util.concurrent.ThreadFactory ThreadFactory} for the - * default group is not configured then the pooled threads of the default group - * are {@link Thread#isDaemon daemon} threads. - * - * <table border> - * <tr> - * <th>System property</th> - * <th>Description</th> - * </tr> - * <tr> - * <tr> - * <td> {@code java.nio.channels.DefaultThreadPool.threadFactory} </td> - * <td> The value of this property is taken to be the fully-qualified name - * of a concrete {@link java.util.concurrent.ThreadFactory ThreadFactory} - * class. The class is loaded using the system class loader and instantiated. - * The factory's {@link java.util.concurrent.ThreadFactory#newThread - * newThread} method is invoked to create each thread for the default - * group's thread pool. If the process to load and instantiate the value - * of the property fails then an unspecified error is thrown during the - * construction of the default group. </td> - * </tr> - * <tr> - * <td> {@code java.nio.channels.DefaultThreadPool.initialSize} </td> - * <td> The value of the {@code initialSize} parameter for the default - * group (see {@link #withCachedThreadPool withCachedThreadPool}). - * The value of the property is taken to be the {@code String} - * representation of an {@code Integer} that is the initial size parameter. - * If the value cannot be parsed as an {@code Integer} it causes an - * unspecified error to be thrown during the construction of the default - * group. </td> - * </tr> - * </table> - * - * <a name="threading"><h4>Threading</h4></a> - * - * <p> The completion handler for an I/O operation initiated on a channel bound - * to a group is guaranteed to be invoked by one of the pooled threads in the - * group. This ensures that the completion handler is run by a thread with the - * expected <em>identity</em>. - * - * <p> Where an I/O operation completes immediately, and the initiating thread - * is one of the pooled threads in the group then the completion handler may - * be invoked directly by the initiating thread. To avoid stack overflow, an - * implementation may impose a limit as to the number of activations on the - * thread stack. Some I/O operations may prohibit invoking the completion - * handler directly by the initiating thread (see {@link - * AsynchronousServerSocketChannel#accept(Object,CompletionHandler) accept}). - * - * <a name="shutdown"><h4>Shutdown and Termination</h4></a> - * - * <p> The {@link #shutdown() shutdown} method is used to initiate an <em>orderly - * shutdown</em> of the group. An orderly shutdown marks the group as shutdown; - * further attempts to construct a channel that binds to the group will throw - * {@link ShutdownChannelGroupException}. Whether or not a group is shutdown can - * be tested using the {@link #isShutdown() isShutdown} method. Once shutdown, a - * group <em>terminates</em> when all asynchronous channels that are bound to the - * group are closed, all actively executing completion handlers have run to - * completion, and resources used by the group are released. No attempt is made - * to stop or interrupt threads that are executing completion handlers. The - * {@link #isTerminated() isTerminated} method is used to test if the group has - * terminated, and the {@link #awaitTermination awaitTermination} method can be - * used to block until the group has terminated. - * - * <p> The {@link #shutdownNow() shutdownNow} method can be used to initiate a - * <em>forceful shutdown</em> of the group. In addition to the actions performed - * by an orderly shutdown, the {@code shutdownNow} method closes all open channels - * in the group as if by invoking the {@link AsynchronousChannel#close close} - * method. - * - * @since 1.7 - * - * @see AsynchronousSocketChannel#open - * @see AsynchronousServerSocketChannel#open - */ - -public abstract class AsynchronousChannelGroup { - private final AsynchronousChannelProvider provider; - - /** - * Initialize a new instance of this class. - * - * @param provider - * The asynchronous channel provider for this group - */ - protected AsynchronousChannelGroup(AsynchronousChannelProvider provider) { - this.provider = provider; - } - - /** - * Returns the provider that created this channel group. - * - * @return The provider that created this channel group - */ - public final AsynchronousChannelProvider provider() { - return provider; - } - - /** - * Creates an asynchronous channel group with a fixed thread pool. - * - * <p> The {@code executor} parameter is an {@code ExecutorService} that - * reuses a fixed number of threads operating off a shared unbounded queue. - * At any point, at most {@code nThreads} threads will be active processing - * tasks that are submitted to handle I/O events and dispatch completion - * results for operations initiated on asynchronous channels in the group. - * - * <p> The executor is intended to be used for the exclusive use of the - * resulting asynchronous channel group. Adjusting the maximum allowed - * number of threads or other policy parameters after the channel group is - * created is not recommended. Termination of the group results in the orderly - * {@link ExecutorService#shutdown shutdown} of the executor service. - * Shutting down the executor service by other means results in unspecified - * behavior. - * - * <p> The group is created by invoking the {@link - * AsynchronousChannelProvider#openAsynchronousChannelGroup - * openAsynchronousChannelGroup} method of the system-wide default {@link - * AsynchronousChannelProvider} object. - * - * @param executor - * The thread pool for the resulting group - * @param nThreads - * The number of threads in the pool - * - * @return A new asynchronous channel group - * - * @throws IllegalArgumentException - * If {@code nThreads <= 0} - * @throws IOException - * If an I/O error occurs - * - * @see Executors#newFixedThreadPool - */ - public static AsynchronousChannelGroup withFixedThreadPool(ExecutorService executor, - int nThreads) - throws IOException - { - return AsynchronousChannelProvider.provider() - .openAsynchronousChannelGroup(AsynchronousChannelProvider.ThreadPoolType.FIXED, - executor, - nThreads); - } - - /** - * Creates an asynchronous channel group that creates new threads as needed. - * - * <p> The {@code executor} parameter is an {@code ExecutorService} that - * creates new threads as needed to execute tasks that are submitted to - * handle I/O events and dispatch completion results for operations initiated - * on asynchronous channels in the group. It may reuse previously constructed - * threads when they are available. - * - * <p> The {@code initialSize} parameter may be used by the implementation - * as a <em>hint</em> as to the initial number of tasks it may submit. For - * example, it may be used to indictae the initial number of threads that - * wait on I/O events. - * - * <p> The executor is intended to be used for the exclusive use of the - * resulting asynchronous channel group. Termination of the group results in - * the orderly {@link ExecutorService#shutdown shutdown} of the executor - * service. Shutting down the executor service by other means results in - * unspecified behavior. - * - * <p> The group is created by invoking the {@link - * AsynchronousChannelProvider#openAsynchronousChannelGroup - * openAsynchronousChannelGroup} method of the system-wide default {@link - * AsynchronousChannelProvider} object. - * - * @param executor - * The thread pool for the resulting group - * @param initialSize - * A value {@code >=0} or a negative value for implementation - * specific default - * - * @return A new asynchronous channel group - * - * @throws IOException - * If an I/O error occurs - * - * @see Executors#newCachedThreadPool - */ - public static AsynchronousChannelGroup withCachedThreadPool(ExecutorService executor, - int initialSize) - throws IOException - { - return AsynchronousChannelProvider.provider() - .openAsynchronousChannelGroup(AsynchronousChannelProvider.ThreadPoolType.CACHED, - executor, - initialSize); - } - - /** - * Tells whether or not this asynchronous channel group is shutdown. - * - * @return {@code true} if this asynchronous channel group is shutdown or - * has been marked for shutdown. - */ - public abstract boolean isShutdown(); - - /** - * Tells whether or not this group has terminated. - * - * <p> Where this method returns {@code true}, then the associated has - * also {@link ExecutorService#isTerminated terminated}. - * - * @return {@code true} if this group has terminated - */ - public abstract boolean isTerminated(); - - /** - * Initiates an orderly shutdown of the group. - * - * <p> This method marks the group as shutdown. Further attempts to construct - * channel that binds to this group will throw {@link ShutdownChannelGroupException}. - * The group terminates when all asynchronous channels in the group are - * closed, all actively executing completion handlers have run to completion, - * and all resources have been released. This method has no effect if the - * group is already shutdown. - */ - public abstract void shutdown(); - - /** - * Shuts down the group and closes all open channels in the group. - * - * <p> In addition to the actions performed by the {@link #shutdown() shutdown} - * method, this method invokes the {@link AsynchronousChannel#close close} - * method on all open channels in the group. This method does not attempt to - * stop or interrupt threads that are executing completion handlers. The - * group terminates when all actively executing completion handlers have run - * to completion and all resources have been released. This method may be - * invoked at any time. If some other thread has already invoked it, then - * another invocation will block until the first invocation is complete, - * after which it will return without effect. - * - * @throws IOException - * If an I/O error occurs - */ - public abstract void shutdownNow() throws IOException; - - /** - * Awaits termination of the group. - - * <p> This method blocks until the group has terminated, or the timeout - * occurs, or the current thread is interrupted, whichever happens first. - * - * @param timeout - * The maximum time to wait, or zero or less to not wait - * @param unit - * The time unit of the timeout argument - * - * @return {@code true} if the group has terminated; {@code false} if the - * timeout elapsed before termination - * - * @throws InterruptedException - * If interrupted while waiting - */ - public abstract boolean awaitTermination(long timeout, TimeUnit unit) - throws InterruptedException; -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/AsynchronousDatagramChannel.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,707 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.channels; - -import java.util.concurrent.TimeUnit; -import java.util.concurrent.Future; -import java.io.IOException; -import java.net.SocketAddress; -import java.nio.ByteBuffer; - -import org.classpath.icedtea.java.net.ProtocolFamily; -import org.classpath.icedtea.java.net.SocketOption; - -import org.classpath.icedtea.java.nio.channels.spi.AsynchronousChannelProvider; - -/** - * An asynchronous channel for datagram-oriented sockets. - * - * <p> An asynchronous datagram channel is created by invoking one of the {@link - * #open open} methods defined by this class. It is not possible to create a channel - * for an arbitrary, pre-existing datagram socket. A newly-created asynchronous - * datagram channel is open but not connected. It need not be connected in order - * for the {@link #send send} and {@link #receive receive} methods to be used. - * A datagram channel may be connected, by invoking its {@link #connect connect} - * method, in order to avoid the overhead of the security checks that are otherwise - * performed as part of every send and receive operation when a security manager - * is set. The channel must be connected in order to use the {@link #read read} - * and {@link #write write} methods, since those methods do not accept or return - * socket addresses. Once connected, an asynchronous datagram channel remains - * connected until it is disconnected or closed. - * - * <p> Socket options are configured using the {@link #setOption(SocketOption,Object) - * setOption} method. An asynchronous datagram channel to an Internet Protocol - * (IP) socket supports the following options: - * <blockquote> - * <table border> - * <tr> - * <th>Option Name</th> - * <th>Description</th> - * </tr> - * <tr> - * <td> {@link java.net.StandardSocketOption#SO_SNDBUF SO_SNDBUF} </td> - * <td> The size of the socket send buffer </td> - * </tr> - * <tr> - * <td> {@link java.net.StandardSocketOption#SO_RCVBUF SO_RCVBUF} </td> - * <td> The size of the socket receive buffer </td> - * </tr> - * <tr> - * <td> {@link java.net.StandardSocketOption#SO_REUSEADDR SO_REUSEADDR} </td> - * <td> Re-use address </td> - * </tr> - * <tr> - * <td> {@link java.net.StandardSocketOption#SO_BROADCAST SO_BROADCAST} </td> - * <td> Allow transmission of broadcast datagrams </td> - * </tr> - * <tr> - * <td> {@link java.net.StandardSocketOption#IP_TOS IP_TOS} </td> - * <td> The Type of Service (ToS) octet in the Internet Protocol (IP) header </td> - * </tr> - * <tr> - * <td> {@link java.net.StandardSocketOption#IP_MULTICAST_IF IP_MULTICAST_IF} </td> - * <td> The network interface for Internet Protocol (IP) multicast datagrams </td> - * </tr> - * <tr> - * <td> {@link java.net.StandardSocketOption#IP_MULTICAST_TTL - * IP_MULTICAST_TTL} </td> - * <td> The <em>time-to-live</em> for Internet Protocol (IP) multicast - * datagrams </td> - * </tr> - * <tr> - * <td> {@link java.net.StandardSocketOption#IP_MULTICAST_LOOP - * IP_MULTICAST_LOOP} </td> - * <td> Loopback for Internet Protocol (IP) multicast datagrams </td> - * </tr> - * </table> - * </blockquote> - * Additional (implementation specific) options may also be supported. - * - * <p> <b>Usage Example:</b> - * <pre> - * final AsynchronousDatagramChannel dc = AsynchronousDatagramChannel.open() - * .bind(new InetSocketAddress(4000)); - * - * // print the source address of all packets that we receive - * dc.receive(buffer, buffer, new CompletionHandler<SocketAddress,ByteBuffer>() { - * public void completed(SocketAddress sa, ByteBuffer buffer) { - * try { - * System.out.println(sa); - * - * buffer.clear(); - * dc.receive(buffer, buffer, this); - * } catch (...) { ... } - * } - * public void failed(Throwable exc, ByteBuffer buffer) { - * ... - * } - * public void cancelled(ByteBuffer buffer) { - * ... - * } - * }); - * </pre> - * - * @since 1.7 - */ - -public abstract class AsynchronousDatagramChannel - implements AsynchronousByteChannel, MulticastChannel -{ - private final AsynchronousChannelProvider provider; - - /** - * Initializes a new instance of this class. - */ - protected AsynchronousDatagramChannel(AsynchronousChannelProvider provider) { - this.provider = provider; - } - - /** - * Returns the provider that created this channel. - */ - public final AsynchronousChannelProvider provider() { - return provider; - } - - /** - * Opens an asynchronous datagram channel. - * - * <p> The new channel is created by invoking the {@link - * java.nio.channels.spi.AsynchronousChannelProvider#openAsynchronousDatagramChannel - * openAsynchronousDatagramChannel} method on the {@link - * java.nio.channels.spi.AsynchronousChannelProvider} object that created - * the given group. If the group parameter is <tt>null</tt> then the - * resulting channel is created by the system-wide default provider, and - * bound to the <em>default group</em>. - * - * <p> The <tt>family</tt> parameter is used to specify the {@link ProtocolFamily}. - * If the datagram channel is to be used for Internet Protocol {@link - * MulticastChannel multicasting} then this parameter should correspond to - * the address type of the multicast groups that this channel will join. - * - * @param family - * The protocol family, or <tt>null</tt> to use the default protocol - * family - * @param group - * The group to which the newly constructed channel should be bound, - * or <tt>null</tt> for the default group - * - * @return A new asynchronous datagram channel - * - * @throws UnsupportedOperationException - * If the specified protocol family is not supported. For example, - * suppose the parameter is specified as {@link - * java.net.StandardProtocolFamily#INET6 INET6} but IPv6 is not - * enabled on the platform. - * @throws ShutdownChannelGroupException - * The specified group is shutdown - * @throws IOException - * If an I/O error occurs - */ - public static AsynchronousDatagramChannel open(ProtocolFamily family, - AsynchronousChannelGroup group) - throws IOException - { - AsynchronousChannelProvider provider = (group == null) ? - AsynchronousChannelProvider.provider() : group.provider(); - return provider.openAsynchronousDatagramChannel(family, group); - } - - /** - * Opens an asynchronous datagram channel. - * - * <p> This method returns an asynchronous datagram channel that is - * bound to the <em>default group</em>. This method is equivalent to evaluating - * the expression: - * <blockquote><pre> - * open((ProtocolFamily)null, (AsynchronousChannelGroup)null); - * </pre></blockquote> - * - * @return A new asynchronous datagram channel - * - * @throws IOException - * If an I/O error occurs - */ - public static AsynchronousDatagramChannel open() - throws IOException - { - return open(null, null); - } - - // -- Socket-specific operations -- - - /** - * @throws AlreadyBoundException {@inheritDoc} - * @throws UnsupportedAddressTypeException {@inheritDoc} - * @throws ClosedChannelException {@inheritDoc} - * @throws IOException {@inheritDoc} - * @throws SecurityException - * If a security manager has been installed and its {@link - * SecurityManager#checkListen checkListen} method denies the - * operation - */ - - public abstract AsynchronousDatagramChannel bind(SocketAddress local) - throws IOException; - - /** - * @throws IllegalArgumentException {@inheritDoc} - * @throws ClosedChannelException {@inheritDoc} - * @throws IOException {@inheritDoc} - */ - - public abstract <T> AsynchronousDatagramChannel setOption(SocketOption<T> name, T value) - throws IOException; - - /** - * Returns the remote address to which this channel is connected. - * - * <p> Where the channel is connected to an Internet Protocol socket address - * then the return value from this method is of type {@link - * java.net.InetSocketAddress}. - * - * @return The remote address; {@code null} if the channel's socket is not - * connected - * - * @throws ClosedChannelException - * If the channel is closed - * @throws IOException - * If an I/O error occurs - */ - public abstract SocketAddress getRemoteAddress() throws IOException; - - /** - * Connects this channel's socket. - * - * <p> The channel's socket is configured so that it only receives - * datagrams from, and sends datagrams to, the given remote <i>peer</i> - * address. Once connected, datagrams may not be received from or sent to - * any other address. A datagram socket remains connected until it is - * explicitly disconnected or until it is closed. - * - * <p> This method performs exactly the same security checks as the {@link - * java.net.DatagramSocket#connect connect} method of the {@link - * java.net.DatagramSocket} class. That is, if a security manager has been - * installed then this method verifies that its {@link - * java.lang.SecurityManager#checkAccept checkAccept} and {@link - * java.lang.SecurityManager#checkConnect checkConnect} methods permit - * datagrams to be received from and sent to, respectively, the given - * remote address. - * - * <p> This method may be invoked at any time. Whether it has any effect - * on outstanding read or write operations is implementation specific and - * therefore not specified. - * - * @param remote - * The remote address to which this channel is to be connected - * - * @return This datagram channel - * - * @throws ClosedChannelException - * If this channel is closed - * - * @throws SecurityException - * If a security manager has been installed - * and it does not permit access to the given remote address - * - * @throws IOException - * If some other I/O error occurs - */ - public abstract AsynchronousDatagramChannel connect(SocketAddress remote) - throws IOException; - - /** - * Disconnects this channel's socket. - * - * <p> The channel's socket is configured so that it can receive datagrams - * from, and sends datagrams to, any remote address so long as the security - * manager, if installed, permits it. - * - * <p> This method may be invoked at any time. It will not have any effect - * on read or write operations that are already in progress at the moment - * that it is invoked. - * - * <p> This method may be invoked at any time. Whether it has any effect - * on outstanding read or write operations is implementation specific and - * therefore not specified. - * - * @return This datagram channel - * - * @throws IOException - * If some other I/O error occurs - */ - public abstract AsynchronousDatagramChannel disconnect() throws IOException; - - /** - * Receives a datagram via this channel. - * - * <p> This method initiates the receiving of a datagram, returning a - * <tt>Future</tt> representing the pending result of the operation. - * The <tt>Future</tt>'s {@link Future#get() get} method returns - * the source address of the datagram upon successful completion. - * - * <p> The datagram is transferred into the given byte buffer starting at - * its current position, as if by a regular {@link AsynchronousByteChannel#read - * read} operation. If there are fewer bytes remaining in the buffer - * than are required to hold the datagram then the remainder of the datagram - * is silently discarded. - * - * <p> If a timeout is specified and the timeout elapses before the operation - * completes then the operation completes with the exception {@link - * InterruptedByTimeoutException}. - * - * <p> When a security manager has been installed and the channel is not - * connected, then it verifies that the source's address and port number are - * permitted by the security manager's {@link SecurityManager#checkAccept - * checkAccept} method. The permission check is performed with privileges that - * are restricted by the calling context of this method. If the permission - * check fails then the operation completes with a {@link SecurityException}. - * The overhead of this security check can be avoided by first connecting the - * socket via the {@link #connect connect} method. - * - * @param dst - * The buffer into which the datagram is to be transferred - * @param timeout - * The timeout, or <tt>0L</tt> for no timeout - * @param unit - * The time unit of the <tt>timeout</tt> argument - * @param attachment - * The object to attach to the I/O operation; can be {@code null} - * @param handler - * The handler for consuming the result; can be {@code null} - * - * @return a <tt>Future</tt> object representing the pending result - * - * @throws IllegalArgumentException - * If the timeout is negative or the buffer is read-only - * @throws ShutdownChannelGroupException - * If a handler is specified, and the channel group is shutdown - */ - public abstract <A> Future<SocketAddress> receive(ByteBuffer dst, - long timeout, - TimeUnit unit, - A attachment, - CompletionHandler<SocketAddress,? super A> handler); - - /** - * Receives a datagram via this channel. - * - * <p> This method initiates the receiving of a datagram, returning a - * <tt>Future</tt> representing the pending result of the operation. - * The <tt>Future</tt>'s {@link Future#get() get} method returns - * the source address of the datagram upon successful completion. - * - * <p> This method is equivalent to invoking {@link - * #receive(ByteBuffer,long,TimeUnit,Object,CompletionHandler)} with a - * timeout of <tt>0L</tt>. - * - * @param dst - * The buffer into which the datagram is to be transferred - * @param attachment - * The object to attach to the I/O operation; can be {@code null} - * @param handler - * The handler for consuming the result; can be {@code null} - * - * @return a <tt>Future</tt> object representing the pending result - * - * @throws IllegalArgumentException - * If the buffer is read-only - * @throws ShutdownChannelGroupException - * If a handler is specified, and the channel group is shutdown - */ - public final <A> Future<SocketAddress> receive(ByteBuffer dst, - A attachment, - CompletionHandler<SocketAddress,? super A> handler) - { - return receive(dst, 0L, TimeUnit.MILLISECONDS, attachment, handler); - } - - /** - * Receives a datagram via this channel. - * - * <p> This method initiates the receiving of a datagram, returning a - * <tt>Future</tt> representing the pending result of the operation. - * The <tt>Future</tt>'s {@link Future#get() get} method returns - * the source address of the datagram upon successful completion. - * - * <p> This method is equivalent to invoking {@link - * #receive(ByteBuffer,long,TimeUnit,Object,CompletionHandler)} with a - * timeout of {@code 0L}, and an attachment and completion handler - * of {@code null}. - * - * @param dst - * The buffer into which the datagram is to be transferred - * - * @return a <tt>Future</tt> object representing the pending result - * - * @throws IllegalArgumentException - * If the buffer is read-only - */ - public final <A> Future<SocketAddress> receive(ByteBuffer dst) { - return receive(dst, 0L, TimeUnit.MILLISECONDS, null, null); - } - - /** - * Sends a datagram via this channel. - * - * <p> This method initiates sending of a datagram, returning a - * <tt>Future</tt> representing the pending result of the operation. - * The operation sends the remaining bytes in the given buffer as a single - * datagram to the given target address. The result of the operation, obtained - * by invoking the <tt>Future</tt>'s {@link Future#get() get} - * method, is the number of bytes sent. - * - * <p> The datagram is transferred from the byte buffer as if by a regular - * {@link AsynchronousByteChannel#write write} operation. - * - * <p> If a timeout is specified and the timeout elapses before the operation - * completes then the operation completes with the exception {@link - * InterruptedByTimeoutException}. - * - * <p> If there is a security manager installed and the the channel is not - * connected then this method verifies that the target address and port number - * are permitted by the security manager's {@link SecurityManager#checkConnect - * checkConnect} method. The overhead of this security check can be avoided - * by first connecting the socket via the {@link #connect connect} method. - * - * @param src - * The buffer containing the datagram to be sent - * @param target - * The address to which the datagram is to be sent - * @param timeout - * The timeout, or <tt>0L</tt> for no timeout - * @param unit - * The time unit of the <tt>timeout</tt> argument - * @param attachment - * The object to attach to the I/O operation; can be {@code null} - * @param handler - * The handler for consuming the result; can be {@code null} - * - * @return a <tt>Future</tt> object representing the pending result - * - * @throws UnresolvedAddressException - * If the given remote address is not fully resolved - * @throws UnsupportedAddressTypeException - * If the type of the given remote address is not supported - * @throws IllegalArgumentException - * If the channel's socket is connected and is connected to an - * address that is not equal to {@code target} - * @throws SecurityException - * If a security manager has been installed and it does not permit - * datagrams to be sent to the given address - * @throws ShutdownChannelGroupException - * If a handler is specified, and the channel group is shutdown - */ - public abstract <A> Future<Integer> send(ByteBuffer src, - SocketAddress target, - long timeout, - TimeUnit unit, - A attachment, - CompletionHandler<Integer,? super A> handler); - - /** - * Sends a datagram via this channel. - * - * <p> This method initiates sending of a datagram, returning a - * <tt>Future</tt> representing the pending result of the operation. - * The operation sends the remaining bytes in the given buffer as a single - * datagram to the given target address. The result of the operation, obtained - * by invoking the <tt>Future</tt>'s {@link Future#get() get} - * method, is the number of bytes sent. - * - * <p> This method is equivalent to invoking {@link - * #send(ByteBuffer,SocketAddress,long,TimeUnit,Object,CompletionHandler)} - * with a timeout of <tt>0L</tt>. - * - * @param src - * The buffer containing the datagram to be sent - * @param target - * The address to which the datagram is to be sent - * @param attachment - * The object to attach to the I/O operation; can be {@code null} - * @param handler - * The handler for consuming the result; can be {@code null} - * - * @return a <tt>Future</tt> object representing the pending result - * - * @throws UnresolvedAddressException - * If the given remote address is not fully resolved - * @throws UnsupportedAddressTypeException - * If the type of the given remote address is not supported - * @throws IllegalArgumentException - * If the channel's socket is connected and is connected to an - * address that is not equal to {@code target} - * @throws SecurityException - * If a security manager has been installed and it does not permit - * datagrams to be sent to the given address - * @throws ShutdownChannelGroupException - * If a handler is specified, and the channel group is shutdown - */ - public final <A> Future<Integer> send(ByteBuffer src, - SocketAddress target, - A attachment, - CompletionHandler<Integer,? super A> handler) - { - return send(src, target, 0L, TimeUnit.MILLISECONDS, attachment, handler); - } - - /** - * Sends a datagram via this channel. - * - * <p> This method initiates sending of a datagram, returning a - * <tt>Future</tt> representing the pending result of the operation. - * The operation sends the remaining bytes in the given buffer as a single - * datagram to the given target address. The result of the operation, obtained - * by invoking the <tt>Future</tt>'s {@link Future#get() get} - * method, is the number of bytes sent. - * - * <p> This method is equivalent to invoking {@link - * #send(ByteBuffer,SocketAddress,long,TimeUnit,Object,CompletionHandler)} - * with a timeout of {@code 0L} and an attachment and completion handler - * of {@code null}. - * - * @param src - * The buffer containing the datagram to be sent - * @param target - * The address to which the datagram is to be sent - * - * @return a <tt>Future</tt> object representing the pending result - * - * @throws UnresolvedAddressException - * If the given remote address is not fully resolved - * @throws UnsupportedAddressTypeException - * If the type of the given remote address is not supported - * @throws IllegalArgumentException - * If the channel's socket is connected and is connected to an - * address that is not equal to {@code target} - * @throws SecurityException - * If a security manager has been installed and it does not permit - * datagrams to be sent to the given address - */ - public final Future<Integer> send(ByteBuffer src, SocketAddress target) { - return send(src, target, 0L, TimeUnit.MILLISECONDS, null, null); - } - - /** - * Receives a datagram via this channel. - * - * <p> This method initiates the receiving of a datagram, returning a - * <tt>Future</tt> representing the pending result of the operation. - * The <tt>Future</tt>'s {@link Future#get() get} method returns - * the number of bytes transferred upon successful completion. - * - * <p> This method may only be invoked if this channel is connected, and it - * only accepts datagrams from the peer that the channel is connected too. - * The datagram is transferred into the given byte buffer starting at - * its current position and exactly as specified in the {@link - * AsynchronousByteChannel} interface. If there are fewer bytes - * remaining in the buffer than are required to hold the datagram then the - * remainder of the datagram is silently discarded. - * - * <p> If a timeout is specified and the timeout elapses before the operation - * completes then the operation completes with the exception {@link - * InterruptedByTimeoutException}. - * - * @param dst - * The buffer into which the datagram is to be transferred - * @param timeout - * The timeout, or <tt>0L</tt> for no timeout - * @param unit - * The time unit of the <tt>timeout</tt> argument - * @param attachment - * The object to attach to the I/O operation; can be {@code null} - * @param handler - * The handler for consuming the result; can be {@code null} - * - * @return a <tt>Future</tt> object representing the pending result - * - * @throws IllegalArgumentException - * If the timeout is negative or buffer is read-only - * @throws NotYetConnectedException - * If this channel is not connected - * @throws ShutdownChannelGroupException - * If a handler is specified, and the channel group is shutdown - */ - public abstract <A> Future<Integer> read(ByteBuffer dst, - long timeout, - TimeUnit unit, - A attachment, - CompletionHandler<Integer,? super A> handler); - - /** - * @throws NotYetConnectedException - * If this channel is not connected - * @throws ShutdownChannelGroupException - * If a handler is specified, and the channel group is shutdown - */ - - public final <A> Future<Integer> read(ByteBuffer dst, - A attachment, - CompletionHandler<Integer,? super A> handler) - { - return read(dst, 0L, TimeUnit.MILLISECONDS, attachment, handler); - } - - /** - * @throws NotYetConnectedException - * If this channel is not connected - */ - - public final Future<Integer> read(ByteBuffer dst) { - return read(dst, 0L, TimeUnit.MILLISECONDS, null, null); - } - - /** - * Writes a datagram to this channel. - * - * <p> This method initiates sending of a datagram, returning a - * <tt>Future</tt> representing the pending result of the operation. - * The operation sends the remaining bytes in the given buffer as a single - * datagram. The result of the operation, obtained by invoking the - * <tt>Future</tt>'s {@link Future#get() get} method, is the - * number of bytes sent. - * - * <p> The datagram is transferred from the byte buffer as if by a regular - * {@link AsynchronousByteChannel#write write} operation. - * - * <p> This method may only be invoked if this channel is connected, - * in which case it sends datagrams directly to the socket's peer. Otherwise - * it behaves exactly as specified in the {@link - * AsynchronousByteChannel} interface. - * - * <p> If a timeout is specified and the timeout elapses before the operation - * completes then the operation completes with the exception {@link - * InterruptedByTimeoutException}. - * - * @param src - * The buffer containing the datagram to be sent - * @param timeout - * The timeout, or <tt>0L</tt> for no timeout - * @param unit - * The time unit of the <tt>timeout</tt> argument - * @param attachment - * The object to attach to the I/O operation; can be {@code null} - * @param handler - * The handler for consuming the result; can be {@code null} - * - * @return a <tt>Future</tt> object representing the pending result - * - * @throws IllegalArgumentException - * If the timeout is negative - * @throws NotYetConnectedException - * If this channel is not connected - * @throws ShutdownChannelGroupException - * If a handler is specified, and the channel group is shutdown - */ - public abstract <A> Future<Integer> write(ByteBuffer src, - long timeout, - TimeUnit unit, - A attachment, - CompletionHandler<Integer,? super A> handler); - /** - * @throws NotYetConnectedException - * If this channel is not connected - * @throws ShutdownChannelGroupException - * If a handler is specified, and the channel group is shutdown - */ - - public final <A> Future<Integer> write(ByteBuffer src, - A attachment, - CompletionHandler<Integer,? super A> handler) - { - return write(src, 0L, TimeUnit.MILLISECONDS, attachment, handler); - } - - /** - * @throws NotYetConnectedException - * If this channel is not connected - */ - - public final Future<Integer> write(ByteBuffer src) { - return write(src, 0L, TimeUnit.MILLISECONDS, null, null); - } -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/AsynchronousFileChannel.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,777 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.channels; - -import java.nio.ByteBuffer; -import java.io.IOException; -import java.util.concurrent.Future; -import java.util.concurrent.ExecutorService; -import java.util.Set; -import java.util.HashSet; -import java.util.Collections; - -import org.classpath.icedtea.java.nio.file.OpenOption; -import org.classpath.icedtea.java.nio.file.Path; -import org.classpath.icedtea.java.nio.file.attribute.FileAttribute; -import org.classpath.icedtea.java.nio.file.spi.FileSystemProvider; - -/** - * An asynchronous channel for reading, writing, and manipulating a file. - * - * <p> An asynchronous file channel is created when a file is opened by invoking - * one of the {@link #open open} methods defined by this class. The file contains - * a variable-length sequence of bytes that can be read and written and whose - * current size can be {@link #size() queried}. The size of the file increases - * when bytes are written beyond its current size; the size of the file decreases - * when it is {@link #truncate truncated}. - * - * <p> An asynchronous file channel does not have a <i>current position</i> - * within the file. Instead, the file position is specified to each read and - * write operation. - * - * <p> In addition to read and write operations, this class defines the - * following operations: </p> - * - * <ul> - * - * <li><p> Updates made to a file may be {@link #force <i>forced - * out</i>} to the underlying storage device, ensuring that data are not - * lost in the event of a system crash. </p></li> - * - * <li><p> A region of a file may be {@link FileLock <i>locked</i>} - * against access by other programs. </p></li> - * - * </ul> - * - * <p> The {@link #read read}, {@link #write write}, and {@link #lock lock} - * methods defined by this class are asynchronous and return a {@link Future} - * to represent the pending result of the operation. This may be used to check - * if the operation has completed, to wait for its completion, and to retrieve - * the result. These method may optionally specify a {@link CompletionHandler} - * that is invoked to consume the result of the I/O operation when it completes. - * - * <p> An {@code AsynchronousFileChannel} is associated with a thread pool to - * which tasks are submitted to handle I/O events and dispatch to completion - * handlers that consume the results of I/O operations on the channel. The - * completion handler for an I/O operation initiated on a channel is guaranteed - * to be invoked by one threads in the thread pool (This ensures that the - * completion handler is run by a thread with the expected <em>identity</em>). - * Where an I/O operation completes immediately, and the initiating thread is - * itself a thread in the thread pool, then the completion handler may be invoked - * directly by the initiating thread. When an {@code AsynchronousFileChannel} is - * created without specifying a thread pool then the channel is associated with - * a system-dependent and default thread pool that may be shared with other - * channels. The default thread pool is configured by the system properties - * defined by the {@link AsynchronousChannelGroup} class. - * - * <p> Channels of this type are safe for use by multiple concurrent threads. The - * {@link Channel#close close} method may be invoked at any time, as specified - * by the {@link Channel} interface. This causes all outstanding asynchronous - * operations on the channel to complete with the exception {@link - * AsynchronousCloseException}. Multiple read and write operations may be - * outstanding at the same time. When multiple read and write operations are - * outstanding then the ordering of the I/O operations, and the order that the - * completion handlers are invoked, is not specified; they are not, in particular, - * guaranteed to execute in the order that the operations were initiated. The - * {@link java.nio.ByteBuffer ByteBuffers} used when reading or writing are not - * safe for use by multiple concurrent I/O operations. Furthermore, after an I/O - * operation is initiated then care should be taken to ensure that the buffer is - * not accessed until after the operation has completed. - * - * <p> As with {@link FileChannel}, the view of a file provided by an instance of - * this class is guaranteed to be consistent with other views of the same file - * provided by other instances in the same program. The view provided by an - * instance of this class may or may not, however, be consistent with the views - * seen by other concurrently-running programs due to caching performed by the - * underlying operating system and delays induced by network-filesystem protocols. - * This is true regardless of the language in which these other programs are - * written, and whether they are running on the same machine or on some other - * machine. The exact nature of any such inconsistencies are system-dependent - * and are therefore unspecified. - * - * @since 1.7 - */ - -public abstract class AsynchronousFileChannel - implements AsynchronousChannel -{ - /** - * Initializes a new instance of this class. - */ - protected AsynchronousFileChannel() { - } - - /** - * Closes this channel. - * - * <p> If this channel is associated with its own thread pool then closing - * the channel causes the thread pool to shutdown after all actively - * executing completion handlers have completed. No attempt is made to stop - * or interrupt actively completion handlers. - * - * <p> This method otherwise behaves exactly as specified by the {@link - * AsynchronousChannel} interface. - * - * @throws IOException {@inheritDoc} - */ - - public abstract void close() throws IOException; - - /** - * Opens or creates a file for reading and/or writing, returning an - * asynchronous file channel to access the file. - * - * <p> The {@code options} parameter determines how the file is opened. - * The {@link StandardOpenOption#READ READ} and {@link StandardOpenOption#WRITE - * WRITE} options determines if the file should be opened for reading and/or - * writing. If neither option is contained in the array then an existing file - * is opened for reading. - * - * <p> In addition to {@code READ} and {@code WRITE}, the following options - * may be present: - * - * <table border=1 cellpadding=5 summary=""> - * <tr> <th>Option</th> <th>Description</th> </tr> - * <tr> - * <td> {@link StandardOpenOption#TRUNCATE_EXISTING TRUNCATE_EXISTING} </td> - * <td> When opening an existing file, the file is first truncated to a - * size of 0 bytes. This option is ignored when the file is opened only - * for reading.</td> - * </tr> - * <tr> - * <td> {@link StandardOpenOption#CREATE_NEW CREATE_NEW} </td> - * <td> If this option is present then a new file is created, failing if - * the file already exists. When creating a file the check for the - * existence of the file and the creation of the file if it does not exist - * is atomic with respect to other file system operations. This option is - * ignored when the file is opened only for reading. </td> - * </tr> - * <tr> - * <td > {@link StandardOpenOption#CREATE CREATE} </td> - * <td> If this option is present then an existing file is opened if it - * exists, otherwise a new file is created. When creating a file the check - * for the existence of the file and the creation of the file if it does - * not exist is atomic with respect to other file system operations. This - * option is ignored if the {@code CREATE_NEW} option is also present or - * the file is opened only for reading. </td> - * </tr> - * <tr> - * <td > {@link StandardOpenOption#DELETE_ON_CLOSE DELETE_ON_CLOSE} </td> - * <td> When this option is present then the implementation makes a - * <em>best effort</em> attempt to delete the file when closed by the - * the {@link #close close} method. If the {@code close} method is not - * invoked then a <em>best effort</em> attempt is made to delete the file - * when the Java virtual machine terminates. </td> - * </tr> - * <tr> - * <td>{@link StandardOpenOption#SPARSE SPARSE} </td> - * <td> When creating a new file this option is a <em>hint</em> that the - * new file will be sparse. This option is ignored when not creating - * a new file. </td> - * </tr> - * <tr> - * <td> {@link StandardOpenOption#SYNC SYNC} </td> - * <td> Requires that every update to the file's content or metadata be - * written synchronously to the underlying storage device. (see <a - * href="../file/package-summary.html#integrity"> Synchronized I/O file - * integrity</a>). </td> - * <tr> - * <tr> - * <td> {@link StandardOpenOption#DSYNC DSYNC} </td> - * <td> Requires that every update to the file's content be written - * synchronously to the underlying storage device. (see <a - * href="../file/package-summary.html#integrity"> Synchronized I/O file - * integrity</a>). </td> - * </tr> - * </table> - * - * <p> An implementation may also support additional options. - * - * <p> The {@code executor} parameter is the {@link ExecutorService} to - * which tasks are submitted to handle I/O events and dispatch completion - * results for operations initiated on resulting channel. - * The nature of these tasks is highly implementation specific and so care - * should be taken when configuring the {@code Executor}. Minimally it - * should support an unbounded work queue and should not run tasks on the - * caller thread of the {@link ExecutorService#execute execute} method. - * {@link #close Closing} the channel results in the orderly {@link - * ExecutorService#shutdown shutdown} of the executor service. Shutting down - * the executor service by other means results in unspecified behavior. - * - * <p> The {@code attrs} parameter is an optional array of file {@link - * FileAttribute file-attributes} to set atomically when creating the file. - * - * <p> The new channel is created by invoking the {@link - * FileSystemProvider#newFileChannel newFileChannel} method on the - * provider that created the {@code Path}. - * - * @param file - * The path of the file to open or create - * @param options - * Options specifying how the file is opened - * @param executor - * The thread pool or {@code null} to associate the channel with - * the default thread pool - * @param attrs - * An optional list of file attributes to set atomically when - * creating the file - * - * @return A new asynchronous file channel - * - * @throws IllegalArgumentException - * If the set contains an invalid combination of options - * @throws UnsupportedOperationException - * If the {@code file} is associated with a provider that does not - * support creating asynchronous file channels, or an unsupported - * open option is specified, or the array contains an attribute that - * cannot be set atomically when creating the file - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * If a security manager is installed and it denies an - * unspecified permission required by the implementation. - * In the case of the default provider, the {@link - * SecurityManager#checkRead(String)} method is invoked to check - * read access if the file is opened for reading. The {@link - * SecurityManager#checkWrite(String)} method is invoked to check - * write access if the file is opened for writing - */ - public static AsynchronousFileChannel open(Path file, - Set<? extends OpenOption> options, - ExecutorService executor, - FileAttribute<?>... attrs) - throws IOException - { - FileSystemProvider provider = file.getFileSystem().provider(); - return provider.newAsynchronousFileChannel(file, options, executor, attrs); - } - - private static final FileAttribute<?>[] NO_ATTRIBUTES = new FileAttribute[0]; - - /** - * Opens or creates a file for reading and/or writing, returning an - * asynchronous file channel to access the file. - * - * <p> An invocation of this method behaves in exactly the same way as the - * invocation - * <pre> - * ch.{@link #open(Path,Set,ExecutorService,FileAttribute[]) open}(file, opts, null, new FileAttribute<?>[0]); - * </pre> - * where {@code opts} is a {@code Set} containing the options specified to - * this method. - * - * <p> The resulting channel is associated with default thread pool to which - * tasks are submitted to handle I/O events and dispatch to completion - * handlers that consume the result of asynchronous operations performed on - * the resulting channel. - * - * @param file - * The path of the file to open or create - * @param options - * Options specifying how the file is opened - * - * @return A new asynchronous file channel - * - * @throws IllegalArgumentException - * If the set contains an invalid combination of options - * @throws UnsupportedOperationException - * If the {@code file} is associated with a provider that does not - * support creating file channels, or an unsupported open option is - * specified - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * If a security manager is installed and it denies an - * unspecified permission required by the implementation. - * In the case of the default provider, the {@link - * SecurityManager#checkRead(String)} method is invoked to check - * read access if the file is opened for reading. The {@link - * SecurityManager#checkWrite(String)} method is invoked to check - * write access if the file is opened for writing - */ - public static AsynchronousFileChannel open(Path file, OpenOption... options) - throws IOException - { - Set<OpenOption> set = new HashSet<OpenOption>(options.length); - Collections.addAll(set, options); - return open(file, set, null, NO_ATTRIBUTES); - } - - /** - * Returns the current size of this channel's file. - * - * @return The current size of this channel's file, measured in bytes - * - * @throws ClosedChannelException - * If this channel is closed - * @throws IOException - * If some other I/O error occurs - */ - public abstract long size() throws IOException; - - /** - * Truncates this channel's file to the given size. - * - * <p> If the given size is less than the file's current size then the file - * is truncated, discarding any bytes beyond the new end of the file. If - * the given size is greater than or equal to the file's current size then - * the file is not modified. </p> - * - * @param size - * The new size, a non-negative byte count - * - * @return This file channel - * - * @throws NonWritableChannelException - * If this channel was not opened for writing - * - * @throws ClosedChannelException - * If this channel is closed - * - * @throws IllegalArgumentException - * If the new size is negative - * - * @throws IOException - * If some other I/O error occurs - */ - public abstract AsynchronousFileChannel truncate(long size) throws IOException; - - /** - * Forces any updates to this channel's file to be written to the storage - * device that contains it. - * - * <p> If this channel's file resides on a local storage device then when - * this method returns it is guaranteed that all changes made to the file - * since this channel was created, or since this method was last invoked, - * will have been written to that device. This is useful for ensuring that - * critical information is not lost in the event of a system crash. - * - * <p> If the file does not reside on a local device then no such guarantee - * is made. - * - * <p> The {@code metaData} parameter can be used to limit the number of - * I/O operations that this method is required to perform. Passing - * {@code false} for this parameter indicates that only updates to the - * file's content need be written to storage; passing {@code true} - * indicates that updates to both the file's content and metadata must be - * written, which generally requires at least one more I/O operation. - * Whether this parameter actually has any effect is dependent upon the - * underlying operating system and is therefore unspecified. - * - * <p> Invoking this method may cause an I/O operation to occur even if the - * channel was only opened for reading. Some operating systems, for - * example, maintain a last-access time as part of a file's metadata, and - * this time is updated whenever the file is read. Whether or not this is - * actually done is system-dependent and is therefore unspecified. - * - * <p> This method is only guaranteed to force changes that were made to - * this channel's file via the methods defined in this class. - * - * @param metaData - * If {@code true} then this method is required to force changes - * to both the file's content and metadata to be written to - * storage; otherwise, it need only force content changes to be - * written - * - * @throws ClosedChannelException - * If this channel is closed - * - * @throws IOException - * If some other I/O error occurs - */ - public abstract void force(boolean metaData) throws IOException; - - /** - * Acquires a lock on the given region of this channel's file. - * - * <p> This method initiates an operation to acquire a lock on the given region - * of this channel's file. The method returns a {@code Future} representing - * the pending result of the operation. Its {@link Future#get() get} - * method returns the {@link FileLock} on successful completion. - * - * <p> The region specified by the {@code position} and {@code size} - * parameters need not be contained within, or even overlap, the actual - * underlying file. Lock regions are fixed in size; if a locked region - * initially contains the end of the file and the file grows beyond the - * region then the new portion of the file will not be covered by the lock. - * If a file is expected to grow in size and a lock on the entire file is - * required then a region starting at zero, and no smaller than the - * expected maximum size of the file, should be locked. The two-argument - * {@link #lock(Object,CompletionHandler)} method simply locks a region - * of size {@link Long#MAX_VALUE}. If a lock that overlaps the requested - * region is already held by this Java virtual machine, or this method has - * been invoked to lock an overlapping region and that operation has not - * completed, then this method throws {@link OverlappingFileLockException}. - * - * <p> Some operating systems do not support a mechanism to acquire a file - * lock in an asynchronous manner. Consequently an implementation may - * acquire the file lock in a background thread or from a task executed by - * a thread in the associated thread pool. If there are many lock operations - * outstanding then it may consume threads in the Java virtual machine for - * indefinite periods. - * - * <p> Some operating systems do not support shared locks, in which case a - * request for a shared lock is automatically converted into a request for - * an exclusive lock. Whether the newly-acquired lock is shared or - * exclusive may be tested by invoking the resulting lock object's {@link - * FileLock#isShared() isShared} method. - * - * <p> File locks are held on behalf of the entire Java virtual machine. - * They are not suitable for controlling access to a file by multiple - * threads within the same virtual machine. - * - * @param position - * The position at which the locked region is to start; must be - * non-negative - * @param size - * The size of the locked region; must be non-negative, and the sum - * {@code position} + {@code size} must be non-negative - * @param shared - * {@code true} to request a shared lock, in which case this - * channel must be open for reading (and possibly writing); - * {@code false} to request an exclusive lock, in which case this - * channel must be open for writing (and possibly reading) - * @param attachment - * The object to attach to the I/O operation; can be {@code null} - * @param handler - * The handler for consuming the result; can be {@code null} - * - * @return a {@code Future} object representing the pending result - * - * @throws OverlappingFileLockException - * If a lock that overlaps the requested region is already held by - * this Java virtual machine, or there is already a pending attempt - * to lock an overlapping region - * @throws IllegalArgumentException - * If the preconditions on the parameters do not hold - * @throws NonReadableChannelException - * If {@code shared} is true this channel but was not opened for reading - * @throws NonWritableChannelException - * If {@code shared} is false but this channel was not opened for writing - * @throws ShutdownChannelGroupException - * If a handler is specified, the channel is closed, and the channel - * was originally created with its own thread pool - */ - public abstract <A> Future<FileLock> lock(long position, - long size, - boolean shared, - A attachment, - CompletionHandler<FileLock,? super A> handler); - - /** - * Acquires an exclusive lock on this channel's file. - * - * <p> This method initiates an operation to acquire an exclusive lock on this - * channel's file. The method returns a {@code Future} representing - * the pending result of the operation. Its {@link Future#get() get} - * method returns the {@link FileLock} on successful completion. - * - * <p> An invocation of this method of the form {@code ch.lock(att,handler)} - * behaves in exactly the same way as the invocation - * <pre> - * ch.{@link #lock(long,long,boolean,Object,CompletionHandler) lock}(0L, Long.MAX_VALUE, false, att, handler) - * </pre> - * - * @param attachment - * The object to attach to the I/O operation; can be {@code null} - * @param handler - * The handler for consuming the result; can be {@code null} - * - * @return a {@code Future} object representing the pending result - * - * @throws OverlappingFileLockException - * If a lock is already held by this Java virtual machine, or there - * is already a pending attempt to lock a region - * @throws NonWritableChannelException - * If this channel was not opened for writing - * @throws ShutdownChannelGroupException - * If a handler is specified, the channel is closed, and the channel - * was originally created with its own thread pool - */ - public final <A> Future<FileLock> lock(A attachment, - CompletionHandler<FileLock,? super A> handler) - { - return lock(0L, Long.MAX_VALUE, false, attachment, handler); - } - - /** - * Acquires an exclusive lock on this channel's file. - * - * <p> This method initiates an operation to acquire an exclusive lock on this - * channel's file. The method returns a {@code Future} representing the - * pending result of the operation. Its {@link Future#get() get} method - * returns the {@link FileLock} on successful completion. - * - * <p> An invocation of this method behaves in exactly the same way as the - * invocation - * <pre> - * ch.{@link #lock(long,long,boolean,Object,CompletionHandler) lock}(0L, Long.MAX_VALUE, false, null, null) - * </pre> - * - * @return A {@code Future} object representing the pending result - * - * @throws OverlappingFileLockException - * If a lock is already held by this Java virtual machine, or there - * is already a pending attempt to lock a region - * @throws NonWritableChannelException - * If this channel was not opened for writing - */ - public final Future<FileLock> lock() { - return lock(0L, Long.MAX_VALUE, false, null, null); - } - - /** - * Attempts to acquire a lock on the given region of this channel's file. - * - * <p> This method does not block. An invocation always returns immediately, - * either having acquired a lock on the requested region or having failed to - * do so. If it fails to acquire a lock because an overlapping lock is held - * by another program then it returns {@code null}. If it fails to acquire - * a lock for any other reason then an appropriate exception is thrown. - * - * @param position - * The position at which the locked region is to start; must be - * non-negative - * - * @param size - * The size of the locked region; must be non-negative, and the sum - * {@code position} + {@code size} must be non-negative - * - * @param shared - * {@code true} to request a shared lock, - * {@code false} to request an exclusive lock - * - * @return A lock object representing the newly-acquired lock, - * or {@code null} if the lock could not be acquired - * because another program holds an overlapping lock - * - * @throws IllegalArgumentException - * If the preconditions on the parameters do not hold - * @throws ClosedChannelException - * If this channel is closed - * @throws OverlappingFileLockException - * If a lock that overlaps the requested region is already held by - * this Java virtual machine, or if another thread is already - * blocked in this method and is attempting to lock an overlapping - * region of the same file - * @throws NonReadableChannelException - * If {@code shared} is true this channel but was not opened for reading - * @throws NonWritableChannelException - * If {@code shared} is false but this channel was not opened for writing - * - * @throws IOException - * If some other I/O error occurs - * - * @see #lock(Object,CompletionHandler) - * @see #lock(long,long,boolean,Object,CompletionHandler) - * @see #tryLock() - */ - public abstract FileLock tryLock(long position, long size, boolean shared) - throws IOException; - - /** - * Attempts to acquire an exclusive lock on this channel's file. - * - * <p> An invocation of this method of the form {@code ch.tryLock()} - * behaves in exactly the same way as the invocation - * - * <pre> - * ch.{@link #tryLock(long,long,boolean) tryLock}(0L, Long.MAX_VALUE, false) </pre> - * - * @return A lock object representing the newly-acquired lock, - * or {@code null} if the lock could not be acquired - * because another program holds an overlapping lock - * - * @throws ClosedChannelException - * If this channel is closed - * @throws OverlappingFileLockException - * If a lock that overlaps the requested region is already held by - * this Java virtual machine, or if another thread is already - * blocked in this method and is attempting to lock an overlapping - * region - * @throws NonWritableChannelException - * If {@code shared} is false but this channel was not opened for writing - * - * @throws IOException - * If some other I/O error occurs - * - * @see #lock(Object,CompletionHandler) - * @see #lock(long,long,boolean,Object,CompletionHandler) - * @see #tryLock(long,long,boolean) - */ - public final FileLock tryLock() throws IOException { - return tryLock(0L, Long.MAX_VALUE, false); - } - - /** - * Reads a sequence of bytes from this channel into the given buffer, - * starting at the given file position. - * - * <p> This method initiates the reading of a sequence of bytes from this - * channel into the given buffer, starting at the given file position. This - * method returns a {@code Future} representing the pending result of the - * operation. The Future's {@link Future#get() get} method returns the - * number of bytes read or {@code -1} if the given position is greater than - * or equal to the file's size at the time that the read is attempted. - * - * <p> This method works in the same manner as the {@link - * AsynchronousByteChannel#read(ByteBuffer,Object,CompletionHandler)} - * method, except that bytes are read starting at the given file position. - * If the given file position is greater than the file's size at the time - * that the read is attempted then no bytes are read. - * - * @param dst - * The buffer into which bytes are to be transferred - * @param position - * The file position at which the transfer is to begin; - * must be non-negative - * @param attachment - * The object to attach to the I/O operation; can be {@code null} - * @param handler - * The handler for consuming the result; can be {@code null} - * - * @return A {@code Future} object representing the pending result - * - * @throws IllegalArgumentException - * If the position is negative or the buffer is read-only - * @throws NonReadableChannelException - * If this channel was not opened for reading - * @throws ShutdownChannelGroupException - * If a handler is specified, the channel is closed, and the channel - * was originally created with its own thread pool - */ - public abstract <A> Future<Integer> read(ByteBuffer dst, - long position, - A attachment, - CompletionHandler<Integer,? super A> handler); - - /** - * Reads a sequence of bytes from this channel into the given buffer, - * starting at the given file position. - * - * <p> This method initiates the reading of a sequence of bytes from this - * channel into the given buffer, starting at the given file position. This - * method returns a {@code Future} representing the pending result of the - * operation. The Future's {@link Future#get() get} method returns the - * number of bytes read or {@code -1} if the given position is greater - * than or equal to the file's size at the time that the read is attempted. - * - * <p> This method is equivalent to invoking {@link - * #read(ByteBuffer,long,Object,CompletionHandler)} with the {@code attachment} - * and handler parameters set to {@code null}. - * - * @param dst - * The buffer into which bytes are to be transferred - * @param position - * The file position at which the transfer is to begin; - * must be non-negative - * - * @return A {@code Future} object representing the pending result - * - * @throws IllegalArgumentException - * If the position is negative or the buffer is read-only - * @throws NonReadableChannelException - * If this channel was not opened for reading - */ - public final Future<Integer> read(ByteBuffer dst, long position) { - return read(dst, position, null, null); - } - - /** - * Writes a sequence of bytes to this channel from the given buffer, starting - * at the given file position. - * - * <p> This method initiates the writing of a sequence of bytes to this channel - * from the given buffer, starting at the given file position. The method - * returns a {@code Future} representing the pending result of the write - * operation. The Future's {@link Future#get() get} method returns the - * number of bytes written. - * - * <p> This method works in the same manner as the {@link - * AsynchronousByteChannel#write(ByteBuffer,Object,CompletionHandler)} - * method, except that bytes are written starting at the given file position. - * If the given position is greater than the file's size, at the time that - * the write is attempted, then the file will be grown to accommodate the new - * bytes; the values of any bytes between the previous end-of-file and the - * newly-written bytes are unspecified. - * - * @param src - * The buffer from which bytes are to be transferred - * @param position - * The file position at which the transfer is to begin; - * must be non-negative - * @param attachment - * The object to attach to the I/O operation; can be {@code null} - * @param handler - * The handler for consuming the result; can be {@code null} - * - * @return A {@code Future} object representing the pending result - * - * @throws IllegalArgumentException - * If the position is negative - * @throws NonWritableChannelException - * If this channel was not opened for writing - * @throws ShutdownChannelGroupException - * If a handler is specified, the channel is closed, and the channel - * was originally created with its own thread pool - */ - public abstract <A> Future<Integer> write(ByteBuffer src, - long position, - A attachment, - CompletionHandler<Integer,? super A> handler); - - /** - * Writes a sequence of bytes to this channel from the given buffer, starting - * at the given file position. - * - * <p> This method initiates the writing of a sequence of bytes to this channel - * from the given buffer, starting at the given file position. The method - * returns a {@code Future} representing the pending result of the write - * operation. The Future's {@link Future#get() get} method returns the - * number of bytes written. - * - * <p> This method is equivalent to invoking {@link - * #write(ByteBuffer,long,Object,CompletionHandler)} with the {@code attachment} - * and handler parameters set to {@code null}. - * - * @param src - * The buffer from which bytes are to be transferred - * @param position - * The file position at which the transfer is to begin; - * must be non-negative - * - * @return A {@code Future} object representing the pending result - * - * @throws IllegalArgumentException - * If the position is negative - * @throws NonWritableChannelException - * If this channel was not opened for writing - */ - public final Future<Integer> write(ByteBuffer src, long position) { - return write(src, position, null, null); - } -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/AsynchronousServerSocketChannel.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,305 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.channels; - -import java.net.SocketAddress; -import java.util.concurrent.Future; -import java.io.IOException; - -import org.classpath.icedtea.java.net.SocketOption; -import org.classpath.icedtea.java.nio.channels.spi.AsynchronousChannelProvider; - -/** - * An asynchronous channel for stream-oriented listening sockets. - * - * <p> An asynchronous server-socket channel is created by invoking the - * {@link #open open} method of this class. - * A newly-created asynchronous server-socket channel is open but not yet bound. - * It can be bound to a local address and configured to listen for connections - * by invoking the {@link #bind(SocketAddress,int) bind} method. Once bound, - * the {@link #accept(Object,CompletionHandler) accept} method - * is used to initiate the accepting of connections to the channel's socket. - * An attempt to invoke the <tt>accept</tt> method on an unbound channel will - * cause a {@link NotYetBoundException} to be thrown. - * - * <p> Channels of this type are safe for use by multiple concurrent threads - * though at most one accept operation can be outstanding at any time. - * If a thread initiates an accept operation before a previous accept operation - * has completed then an {@link AcceptPendingException} will be thrown. - * - * <p> Socket options are configured using the {@link #setOption(SocketOption,Object) - * setOption} method. Channels of this type support the following options: - * <blockquote> - * <table border> - * <tr> - * <th>Option Name</th> - * <th>Description</th> - * </tr> - * <tr> - * <td> {@link java.net.StandardSocketOption#SO_RCVBUF SO_RCVBUF} </td> - * <td> The size of the socket receive buffer </td> - * </tr> - * <tr> - * <td> {@link java.net.StandardSocketOption#SO_REUSEADDR SO_REUSEADDR} </td> - * <td> Re-use address </td> - * </tr> - * </table> - * </blockquote> - * Additional (implementation specific) options may also be supported. - * - * <p> <b>Usage Example:</b> - * <pre> - * final AsynchronousServerSocketChannel listener = - * AsynchronousServerSocketChannel.open().bind(new InetSocketAddress(5000)); - * - * listener.accept(null, new CompletionHandler<AsynchronousSocketChannel,Void>() { - * public void completed(AsynchronousSocketChannel ch, Void att) { - * // accept the next connection - * listener.accept(null, this); - * - * // handle this connection - * handle(ch); - * } - * public void failed(Throwable exc, Void att) { - * ... - * } - * public void cancelled(Void att) { - * ... - * } - * }); - * </pre> - * - * @since 1.7 - */ - -public abstract class AsynchronousServerSocketChannel - implements AsynchronousChannel, NetworkChannel -{ - private final AsynchronousChannelProvider provider; - - /** - * Initializes a new instance of this class. - */ - protected AsynchronousServerSocketChannel(AsynchronousChannelProvider provider) { - this.provider = provider; - } - - /** - * Returns the provider that created this channel. - */ - public final AsynchronousChannelProvider provider() { - return provider; - } - - /** - * Opens an asynchronous server-socket channel. - * - * <p> The new channel is created by invoking the {@link - * java.nio.channels.spi.AsynchronousChannelProvider#openAsynchronousServerSocketChannel - * openAsynchronousServerSocketChannel} method on the {@link - * java.nio.channels.spi.AsynchronousChannelProvider} object that created - * the given group. If the group parameter is <tt>null</tt> then the - * resulting channel is created by the system-wide default provider, and - * bound to the <em>default group</em>. - * - * @param group - * The group to which the newly constructed channel should be bound, - * or <tt>null</tt> for the default group - * - * @return A new asynchronous server socket channel - * - * @throws ShutdownChannelGroupException - * If the channel group is shutdown - * @throws IOException - * If an I/O error occurs - */ - public static AsynchronousServerSocketChannel open(AsynchronousChannelGroup group) - throws IOException - { - AsynchronousChannelProvider provider = (group == null) ? - AsynchronousChannelProvider.provider() : group.provider(); - return provider.openAsynchronousServerSocketChannel(group); - } - - /** - * Opens an asynchronous server-socket channel. - * - * <p> This method returns an asynchronous server socket channel that is - * bound to the <em>default group</em>. This method is equivalent to evaluating - * the expression: - * <blockquote><pre> - * open((AsynchronousChannelGroup)null); - * </pre></blockquote> - * - * @return A new asynchronous server socket channel - * - * @throws IOException - * If an I/O error occurs - */ - public static AsynchronousServerSocketChannel open() - throws IOException - { - return open(null); - } - - /** - * Binds the channel's socket to a local address and configures the socket to - * listen for connections. - * - * <p> An invocation of this method is equivalent to the following: - * <blockquote><pre> - * bind(local, 0); - * </pre></blockquote> - * - * @param local - * The local address to bind the socket, or <tt>null</tt> to bind - * to an automatically assigned socket address - * - * @return This channel - * - * @throws AlreadyBoundException {@inheritDoc} - * @throws UnsupportedAddressTypeException {@inheritDoc} - * @throws SecurityException {@inheritDoc} - * @throws ClosedChannelException {@inheritDoc} - * @throws IOException {@inheritDoc} - */ - public final AsynchronousServerSocketChannel bind(SocketAddress local) - throws IOException - { - return bind(local, 0); - } - - /** - * Binds the channel's socket to a local address and configures the socket to - * listen for connections. - * - * <p> This method is used to establish an association between the socket and - * a local address. Once an association is established then the socket remains - * bound until the associated channel is closed. - * - * <p> The {@code backlog} parameter is the maximum number of pending - * connections on the socket. Its exact semantics are implementation specific. - * In particular, an implementation may impose a maximum length or may choose - * to ignore the parameter altogther. If the {@code backlog} parameter has - * the value {@code 0}, or a negative value, then an implementation specific - * default is used. - * - * @param local - * The local address to bind the socket, or {@code null} to bind - * to an automatically assigned socket address - * @param backlog - * The maximum number of pending connections - * - * @return This channel - * - * @throws AlreadyBoundException - * If the socket is already bound - * @throws UnsupportedAddressTypeException - * If the type of the given address is not supported - * @throws SecurityException - * If a security manager has been installed and its {@link - * SecurityManager#checkListen checkListen} method denies the operation - * @throws ClosedChannelException - * If the channel is closed - * @throws IOException - * If some other I/O error occurs - */ - public abstract AsynchronousServerSocketChannel bind(SocketAddress local, int backlog) - throws IOException; - - /** - * @throws IllegalArgumentException {@inheritDoc} - * @throws ClosedChannelException {@inheritDoc} - * @throws IOException {@inheritDoc} - */ - public abstract <T> AsynchronousServerSocketChannel setOption(SocketOption<T> name, T value) - throws IOException; - - /** - * Accepts a connection. - * - * <p> This method initiates accepting a connection made to this channel's - * socket, returning a {@link Future} representing the pending result - * of the operation. The {@code Future}'s {@link Future#get() get} - * method will return the {@link AsynchronousSocketChannel} for the new - * connection on successful completion. - * - * <p> When a new connection is accepted then the resulting {@code - * AsynchronousSocketChannel} will be bound to the same {@link - * AsynchronousChannelGroup} as this channel. If the group is {@link - * AsynchronousChannelGroup#isShutdown shutdown} and a connection is accepted, - * then the connection is closed, and the operation completes with an {@code - * IOException} and cause {@link ShutdownChannelGroupException}. - * - * <p> To allow for concurrent handling of new connections, the completion - * handler is not invoked directly by the initiating thread when a new - * connection is accepted immediately (see <a - * href="AsynchronousChannelGroup.html#threading">Threading<a>). - * - * <p> If a security manager has been installed then it verifies that the - * address and port number of the connection's remote endpoint are permitted - * by the security manager's {@link SecurityManager#checkAccept checkAccept} - * method. The permission check is performed with privileges that are restricted - * by the calling context of this method. If the permission check fails then - * the connection is closed and the operation completes with a {@link - * SecurityException}. - * - * @param attachment - * The object to attach to the I/O operation; can be {@code null} - * @param handler - * The handler for consuming the result; can be {@code null} - * - * @return an <tt>Future</tt> object representing the pending result - * - * @throws AcceptPendingException - * If an accept operation is already in progress on this channel - * @throws NotYetBoundException - * If this channel's socket has not yet been bound - * @throws ShutdownChannelGroupException - * If a handler is specified, and the channel group is shutdown - */ - public abstract <A> Future<AsynchronousSocketChannel> - accept(A attachment, CompletionHandler<AsynchronousSocketChannel,? super A> handler); - - /** - * Accepts a connection. - * - * <p> This method is equivalent to invoking {@link - * #accept(Object,CompletionHandler)} with the {@code attachment} - * and {@code handler} parameters set to {@code null}. - * - * @return an <tt>Future</tt> object representing the pending result - * - * @throws AcceptPendingException - * If an accept operation is already in progress on this channel - * @throws NotYetBoundException - * If this channel's socket has not yet been bound - */ - public final Future<AsynchronousSocketChannel> accept() { - return accept(null, null); - } -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/AsynchronousSocketChannel.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,672 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.channels; - -import java.util.concurrent.TimeUnit; -import java.util.concurrent.Future; -import java.io.IOException; -import java.net.SocketAddress; -import java.nio.ByteBuffer; - -import org.classpath.icedtea.java.net.SocketOption; -import org.classpath.icedtea.java.nio.channels.spi.AsynchronousChannelProvider; - -/** - * An asynchronous channel for stream-oriented connecting sockets. - * - * <p> Asynchronous socket channels are created in one of two ways. A newly-created - * {@code AsynchronousSocketChannel} is created by invoking one of the {@link - * #open open} methods defined by this class. A newly-created channel is open but - * not yet connected. A connected {@code AsynchronousSocketChannel} is created - * when a connection is made to the socket of an {@link AsynchronousServerSocketChannel}. - * It is not possible to create an asynchronous socket channel for an arbitrary, - * pre-existing {@link java.net.Socket socket}. - * - * <p> A newly-created channel is connected by invoking its {@link #connect connect} - * method; once connected, a channel remains connected until it is closed. Whether - * or not a socket channel is connected may be determined by invoking its {@link - * #getRemoteAddress getRemoteAddress} method. An attempt to invoke an I/O - * operation upon an unconnected channel will cause a {@link NotYetConnectedException} - * to be thrown. - * - * <p> Channels of this type are safe for use by multiple concurrent threads. - * They support concurrent reading and writing, though at most one read operation - * and one write operation can be outstanding at any time. - * If a thread initiates a read operation before a previous read operation has - * completed then a {@link ReadPendingException} will be thrown. Similarly, an - * attempt to initiate a write operation before a previous write has completed - * will throw a {@link WritePendingException}. - * - * <p> Socket options are configured using the {@link #setOption(SocketOption,Object) - * setOption} method. Asynchronous socket channels support the following options: - * <blockquote> - * <table border> - * <tr> - * <th>Option Name</th> - * <th>Description</th> - * </tr> - * <tr> - * <td> {@link java.net.StandardSocketOption#SO_SNDBUF SO_SNDBUF} </td> - * <td> The size of the socket send buffer </td> - * </tr> - * <tr> - * <td> {@link java.net.StandardSocketOption#SO_RCVBUF SO_RCVBUF} </td> - * <td> The size of the socket receive buffer </td> - * </tr> - * <tr> - * <td> {@link java.net.StandardSocketOption#SO_KEEPALIVE SO_KEEPALIVE} </td> - * <td> Keep connection alive </td> - * </tr> - * <tr> - * <td> {@link java.net.StandardSocketOption#SO_REUSEADDR SO_REUSEADDR} </td> - * <td> Re-use address </td> - * </tr> - * <tr> - * <td> {@link java.net.StandardSocketOption#TCP_NODELAY TCP_NODELAY} </td> - * <td> Disable the Nagle algorithm </td> - * </tr> - * </table> - * </blockquote> - * Additional (implementation specific) options may also be supported. - * - * <h4>Timeouts</h4> - * - * <p> The {@link #read(ByteBuffer,long,TimeUnit,Object,CompletionHandler) read} - * and {@link #write(ByteBuffer,long,TimeUnit,Object,CompletionHandler) write} - * methods defined by this class allow a timeout to be specified when initiating - * a read or write operation. If the timeout elapses before an operation completes - * then the operation completes with the exception {@link - * InterruptedByTimeoutException}. A timeout may leave the channel, or the - * underlying connection, in an inconsistent state. Where the implementation - * cannot guarantee that bytes have not been read from the channel then it puts - * the channel into an implementation specific <em>error state</em>. A subsequent - * attempt to initiate a {@code read} operation causes an unspecified runtime - * exception to be thrown. Similarly if a {@code write} operation times out and - * the implementation cannot guarantee bytes have not been written to the - * channel then further attempts to {@code write} to the channel cause an - * unspecified runtime exception to be thrown. When a timeout elapses then the - * state of the {@link ByteBuffer}, or the sequence of buffers, for the I/O - * operation is not defined. Buffers should be discarded or at least care must - * be taken to ensure that the buffers are not accessed while the channel remains - * open. - * - * @since 1.7 - */ - -public abstract class AsynchronousSocketChannel - implements AsynchronousByteChannel, NetworkChannel -{ - private final AsynchronousChannelProvider provider; - - /** - * Initializes a new instance of this class. - */ - protected AsynchronousSocketChannel(AsynchronousChannelProvider provider) { - this.provider = provider; - } - - /** - * Returns the provider that created this channel. - */ - public final AsynchronousChannelProvider provider() { - return provider; - } - - /** - * Opens an asynchronous socket channel. - * - * <p> The new channel is created by invoking the {@link - * AsynchronousChannelProvider#openAsynchronousSocketChannel - * openAsynchronousSocketChannel} method on the {@link - * AsynchronousChannelProvider} that created the group. If the group parameter - * is {@code null} then the resulting channel is created by the system-wide - * default provider, and bound to the <em>default group</em>. - * - * @param group - * The group to which the newly constructed channel should be bound, - * or {@code null} for the default group - * - * @return A new asynchronous socket channel - * - * @throws ShutdownChannelGroupException - * If the channel group is shutdown - * @throws IOException - * If an I/O error occurs - */ - public static AsynchronousSocketChannel open(AsynchronousChannelGroup group) - throws IOException - { - AsynchronousChannelProvider provider = (group == null) ? - AsynchronousChannelProvider.provider() : group.provider(); - return provider.openAsynchronousSocketChannel(group); - } - - /** - * Opens an asynchronous socket channel. - * - * <p> This method returns an asynchronous socket channel that is bound to - * the <em>default group</em>.This method is equivalent to evaluating the - * expression: - * <blockquote><pre> - * open((AsynchronousChannelGroup)null); - * </pre></blockquote> - * - * @return A new asynchronous socket channel - * - * @throws IOException - * If an I/O error occurs - */ - public static AsynchronousSocketChannel open() - throws IOException - { - return open(null); - } - - - // -- socket options and related -- - - /** - * @throws ConnectionPendingException - * If a connection operation is already in progress on this channel - * @throws AlreadyBoundException {@inheritDoc} - * @throws UnsupportedAddressTypeException {@inheritDoc} - * @throws ClosedChannelException {@inheritDoc} - * @throws IOException {@inheritDoc} - */ - - public abstract AsynchronousSocketChannel bind(SocketAddress local) - throws IOException; - - /** - * @throws IllegalArgumentException {@inheritDoc} - * @throws ClosedChannelException {@inheritDoc} - * @throws IOException {@inheritDoc} - */ - - public abstract <T> AsynchronousSocketChannel setOption(SocketOption<T> name, T value) - throws IOException; - - /** - * Shutdown the connection for reading without closing the channel. - * - * <p> Once shutdown for reading then further reads on the channel will - * return {@code -1}, the end-of-stream indication. If the input side of the - * connection is already shutdown then invoking this method has no effect. - * The effect on an outstanding read operation is system dependent and - * therefore not specified. The effect, if any, when there is data in the - * socket receive buffer that has not been read, or data arrives subsequently, - * is also system dependent. - * - * @return The channel - * - * @throws NotYetConnectedException - * If this channel is not yet connected - * @throws ClosedChannelException - * If this channel is closed - * @throws IOException - * If some other I/O error occurs - */ - public abstract AsynchronousSocketChannel shutdownInput() throws IOException; - - /** - * Shutdown the connection for writing without closing the channel. - * - * <p> Once shutdown for writing then further attempts to write to the - * channel will throw {@link ClosedChannelException}. If the output side of - * the connection is already shutdown then invoking this method has no - * effect. The effect on an outstanding write operation is system dependent - * and therefore not specified. - * - * @return The channel - * - * @throws NotYetConnectedException - * If this channel is not yet connected - * @throws ClosedChannelException - * If this channel is closed - * @throws IOException - * If some other I/O error occurs - */ - public abstract AsynchronousSocketChannel shutdownOutput() throws IOException; - - // -- state -- - - /** - * Returns the remote address to which this channel's socket is connected. - * - * <p> Where the channel is bound and connected to an Internet Protocol - * socket address then the return value from this method is of type {@link - * java.net.InetSocketAddress}. - * - * @return The remote address; {@code null} if the channel's socket is not - * connected - * - * @throws ClosedChannelException - * If the channel is closed - * @throws IOException - * If an I/O error occurs - */ - public abstract SocketAddress getRemoteAddress() throws IOException; - - // -- asynchronous operations -- - - /** - * Connects this channel. - * - * <p> This method initiates an operation to connect this channel, returning - * a {@code Future} representing the pending result of the operation. If - * the connection is successfully established then the {@code Future}'s - * {@link Future#get() get} method will return {@code null}. If the - * connection cannot be established then the channel is closed. In that case, - * invoking the {@code get} method throws {@link - * java.util.concurrent.ExecutionException} with an {@code IOException} as - * the cause. - * - * <p> This method performs exactly the same security checks as the {@link - * java.net.Socket} class. That is, if a security manager has been - * installed then this method verifies that its {@link - * java.lang.SecurityManager#checkConnect checkConnect} method permits - * connecting to the address and port number of the given remote endpoint. - * - * @param remote - * The remote address to which this channel is to be connected - * @param attachment - * The object to attach to the I/O operation; can be {@code null} - * @param handler - * The handler for consuming the result; can be {@code null} - * - * @return A {@code Future} object representing the pending result - * - * @throws UnresolvedAddressException - * If the given remote address is not fully resolved - * @throws UnsupportedAddressTypeException - * If the type of the given remote address is not supported - * @throws AlreadyConnectedException - * If this channel is already connected - * @throws ConnectionPendingException - * If a connection operation is already in progress on this channel - * @throws ShutdownChannelGroupException - * If a handler is specified, and the channel group is shutdown - * @throws SecurityException - * If a security manager has been installed - * and it does not permit access to the given remote endpoint - * - * @see #getRemoteAddress - */ - public abstract <A> Future<Void> connect(SocketAddress remote, - A attachment, - CompletionHandler<Void,? super A> handler); - - /** - * Connects this channel. - * - * <p> This method is equivalent to invoking {@link - * #connect(SocketAddress,Object,CompletionHandler)} with the {@code attachment} - * and handler parameters set to {@code null}. - * - * @param remote - * The remote address to which this channel is to be connected - * - * @return A {@code Future} object representing the pending result - * - * @throws UnresolvedAddressException - * If the given remote address is not fully resolved - * @throws UnsupportedAddressTypeException - * If the type of the given remote address is not supported - * @throws AlreadyConnectedException - * If this channel is already connected - * @throws ConnectionPendingException - * If a connection operation is already in progress on this channel - * @throws SecurityException - * If a security manager has been installed - * and it does not permit access to the given remote endpoint - */ - public final Future<Void> connect(SocketAddress remote) { - return connect(remote, null, null); - } - - /** - * Reads a sequence of bytes from this channel into the given buffer. - * - * <p> This method initiates the reading of a sequence of bytes from this - * channel into the given buffer, returning a {@code Future} representing - * the pending result of the operation. The {@code Future}'s {@link - * Future#get() get} method returns the number of bytes read or {@code -1} - * if all bytes have been read and channel has reached end-of-stream. - * - * <p> If a timeout is specified and the timeout elapses before the operation - * completes then the operation completes with the exception {@link - * InterruptedByTimeoutException}. Where a timeout occurs, and the - * implementation cannot guarantee that bytes have not been read, or will not - * be read from the channel into the given buffer, then further attempts to - * read from the channel will cause an unspecific runtime exception to be - * thrown. - * - * <p> Otherwise this method works in the same manner as the {@link - * AsynchronousByteChannel#read(ByteBuffer,Object,CompletionHandler)} - * method. - * - * @param dst - * The buffer into which bytes are to be transferred - * @param timeout - * The timeout, or {@code 0L} for no timeout - * @param unit - * The time unit of the {@code timeout} argument - * @param attachment - * The object to attach to the I/O operation; can be {@code null} - * @param handler - * The handler for consuming the result; can be {@code null} - * - * @return A {@code Future} object representing the pending result - * - * @throws IllegalArgumentException - * If the {@code timeout} parameter is negative or the buffer is - * read-only - * @throws ReadPendingException - * If a read operation is already in progress on this channel - * @throws NotYetConnectedException - * If this channel is not yet connected - * @throws ShutdownChannelGroupException - * If a handler is specified, and the channel group is shutdown - */ - public abstract <A> Future<Integer> read(ByteBuffer dst, - long timeout, - TimeUnit unit, - A attachment, - CompletionHandler<Integer,? super A> handler); - - /** - * @throws IllegalArgumentException {@inheritDoc} - * @throws ReadPendingException {@inheritDoc} - * @throws NotYetConnectedException - * If this channel is not yet connected - * @throws ShutdownChannelGroupException - * If a handler is specified, and the channel group is shutdown - */ - - public final <A> Future<Integer> read(ByteBuffer dst, - A attachment, - CompletionHandler<Integer,? super A> handler) - { - return read(dst, 0L, TimeUnit.MILLISECONDS, attachment, handler); - } - - /** - * @throws IllegalArgumentException {@inheritDoc} - * @throws ReadPendingException {@inheritDoc} - * @throws NotYetConnectedException - * If this channel is not yet connected - */ - - public final Future<Integer> read(ByteBuffer dst) { - return read(dst, 0L, TimeUnit.MILLISECONDS, null, null); - } - - /** - * Reads a sequence of bytes from this channel into a subsequence of the - * given buffers. This operation, sometimes called a <em>scattering read</em>, - * is often useful when implementing network protocols that group data into - * segments consisting of one or more fixed-length headers followed by a - * variable-length body. - * - * <p> This method initiates a read of up to <i>r</i> bytes from this channel, - * where <i>r</i> is the total number of bytes remaining in the specified - * subsequence of the given buffer array, that is, - * - * <blockquote><pre> - * dsts[offset].remaining() - * + dsts[offset+1].remaining() - * + ... + dsts[offset+length-1].remaining()</pre></blockquote> - * - * at the moment that the read is attempted. - * - * <p> Suppose that a byte sequence of length <i>n</i> is read, where - * <tt>0</tt> <tt><</tt> <i>n</i> <tt><=</tt> <i>r</i>. - * Up to the first <tt>dsts[offset].remaining()</tt> bytes of this sequence - * are transferred into buffer <tt>dsts[offset]</tt>, up to the next - * <tt>dsts[offset+1].remaining()</tt> bytes are transferred into buffer - * <tt>dsts[offset+1]</tt>, and so forth, until the entire byte sequence - * is transferred into the given buffers. As many bytes as possible are - * transferred into each buffer, hence the final position of each updated - * buffer, except the last updated buffer, is guaranteed to be equal to - * that buffer's limit. The underlying operating system may impose a limit - * on the number of buffers that may be used in an I/O operation. Where the - * number of buffers (with bytes remaining), exceeds this limit, then the - * I/O operation is performed with the maximum number of buffers allowed by - * the operating system. - * - * <p> The return value from this method is a {@code Future} representing - * the pending result of the operation. The {@code Future}'s {@link - * Future#get() get} method returns the number of bytes read or {@code -1L} - * if all bytes have been read and the channel has reached end-of-stream. - * - * <p> If a timeout is specified and the timeout elapses before the operation - * completes then it completes with the exception {@link - * InterruptedByTimeoutException}. Where a timeout occurs, and the - * implementation cannot guarantee that bytes have not been read, or will not - * be read from the channel into the given buffers, then further attempts to - * read from the channel will cause an unspecific runtime exception to be - * thrown. - * - * @param dsts - * The buffers into which bytes are to be transferred - * @param offset - * The offset within the buffer array of the first buffer into which - * bytes are to be transferred; must be non-negative and no larger than - * {@code dsts.length} - * @param length - * The maximum number of buffers to be accessed; must be non-negative - * and no larger than {@code dsts.length - offset} - * @param timeout - * The timeout, or {@code 0L} for no timeout - * @param unit - * The time unit of the {@code timeout} argument - * @param attachment - * The object to attach to the I/O operation; can be {@code null} - * @param handler - * The handler for consuming the result; can be {@code null} - * - * @return A {@code Future} object representing the pending result - * - * @throws IndexOutOfBoundsException - * If the pre-conditions for the {@code offset} and {@code length} - * parameter aren't met - * @throws IllegalArgumentException - * If the {@code timeout} parameter is negative, or a buffer is - * read-only - * @throws ReadPendingException - * If a read operation is already in progress on this channel - * @throws NotYetConnectedException - * If this channel is not yet connected - * @throws ShutdownChannelGroupException - * If a handler is specified, and the channel group is shutdown - */ - public abstract <A> Future<Long> read(ByteBuffer[] dsts, - int offset, - int length, - long timeout, - TimeUnit unit, - A attachment, - CompletionHandler<Long,? super A> handler); - - /** - * Writes a sequence of bytes to this channel from the given buffer. - * - * <p> This method initiates the writing of a sequence of bytes to this channel - * from the given buffer, returning a {@code Future} representing the - * pending result of the operation. The {@code Future}'s {@link Future#get() - * get} method will return the number of bytes written. - * - * <p> If a timeout is specified and the timeout elapses before the operation - * completes then it completes with the exception {@link - * InterruptedByTimeoutException}. Where a timeout occurs, and the - * implementation cannot guarantee that bytes have not been written, or will - * not be written to the channel from the given buffer, then further attempts - * to write to the channel will cause an unspecific runtime exception to be - * thrown. - * - * <p> Otherwise this method works in the same manner as the {@link - * AsynchronousByteChannel#write(ByteBuffer,Object,CompletionHandler)} - * method. - * - * @param src - * The buffer from which bytes are to be retrieved - * @param timeout - * The timeout, or {@code 0L} for no timeout - * @param unit - * The time unit of the {@code timeout} argument - * @param attachment - * The object to attach to the I/O operation; can be {@code null} - * @param handler - * The handler for consuming the result; can be {@code null} - * - * @return A {@code Future} object representing the pending result - * - * @throws IllegalArgumentException - * If the {@code timeout} parameter is negative - * @throws WritePendingException - * If a write operation is already in progress on this channel - * @throws NotYetConnectedException - * If this channel is not yet connected - * @throws ShutdownChannelGroupException - * If a handler is specified, and the channel group is shutdown - */ - public abstract <A> Future<Integer> write(ByteBuffer src, - long timeout, - TimeUnit unit, - A attachment, - CompletionHandler<Integer,? super A> handler); - - /** - * @throws WritePendingException {@inheritDoc} - * @throws NotYetConnectedException - * If this channel is not yet connected - * @throws ShutdownChannelGroupException - * If a handler is specified, and the channel group is shutdown - */ - - public final <A> Future<Integer> write(ByteBuffer src, - A attachment, - CompletionHandler<Integer,? super A> handler) - - { - return write(src, 0L, TimeUnit.MILLISECONDS, attachment, handler); - } - - /** - * @throws WritePendingException {@inheritDoc} - * @throws NotYetConnectedException - * If this channel is not yet connected - */ - - public final Future<Integer> write(ByteBuffer src) { - return write(src, 0L, TimeUnit.MILLISECONDS, null, null); - } - - /** - * Writes a sequence of bytes to this channel from a subsequence of the given - * buffers. This operation, sometimes called a <em>gathering write</em>, is - * often useful when implementing network protocols that group data into - * segments consisting of one or more fixed-length headers followed by a - * variable-length body. - * - * <p> This method initiates a write of up to <i>r</i> bytes to this channel, - * where <i>r</i> is the total number of bytes remaining in the specified - * subsequence of the given buffer array, that is, - * - * <blockquote><pre> - * srcs[offset].remaining() - * + srcs[offset+1].remaining() - * + ... + srcs[offset+length-1].remaining()</pre></blockquote> - * - * at the moment that the write is attempted. - * - * <p> Suppose that a byte sequence of length <i>n</i> is written, where - * <tt>0</tt> <tt><</tt> <i>n</i> <tt><=</tt> <i>r</i>. - * Up to the first <tt>srcs[offset].remaining()</tt> bytes of this sequence - * are written from buffer <tt>srcs[offset]</tt>, up to the next - * <tt>srcs[offset+1].remaining()</tt> bytes are written from buffer - * <tt>srcs[offset+1]</tt>, and so forth, until the entire byte sequence is - * written. As many bytes as possible are written from each buffer, hence - * the final position of each updated buffer, except the last updated - * buffer, is guaranteed to be equal to that buffer's limit. The underlying - * operating system may impose a limit on the number of buffers that may be - * used in an I/O operation. Where the number of buffers (with bytes - * remaining), exceeds this limit, then the I/O operation is performed with - * the maximum number of buffers allowed by the operating system. - * - * <p> The return value from this method is a {@code Future} representing - * the pending result of the operation. The {@code Future}'s {@link - * Future#get() get} method will return the number of bytes written. - * - * <p> If a timeout is specified and the timeout elapses before the operation - * completes then it completes with the exception {@link - * InterruptedByTimeoutException}. Where a timeout occurs, and the - * implementation cannot guarantee that bytes have not been written, or will - * not be written to the channel from the given buffers, then further attempts - * to write to the channel will cause an unspecific runtime exception to be - * thrown. - * - * @param srcs - * The buffers from which bytes are to be retrieved - * @param offset - * The offset within the buffer array of the first buffer from which - * bytes are to be retrieved; must be non-negative and no larger - * than {@code srcs.length} - * @param length - * The maximum number of buffers to be accessed; must be non-negative - * and no larger than {@code srcs.length - offset} - * @param timeout - * The timeout, or {@code 0L} for no timeout - * @param unit - * The time unit of the {@code timeout} argument - * @param attachment - * The object to attach to the I/O operation; can be {@code null} - * @param handler - * The handler for consuming the result; can be {@code null} - * - * @return A {@code Future} object representing the pending result - * - * @throws IndexOutOfBoundsException - * If the pre-conditions for the {@code offset} and {@code length} - * parameter aren't met - * @throws IllegalArgumentException - * If the {@code timeout} parameter is negative - * @throws WritePendingException - * If a write operation is already in progress on this channel - * @throws NotYetConnectedException - * If this channel is not yet connected - * @throws ShutdownChannelGroupException - * If a handler is specified, and the channel group is shutdown - */ - public abstract <A> Future<Long> write(ByteBuffer[] srcs, - int offset, - int length, - long timeout, - TimeUnit unit, - A attachment, - CompletionHandler<Long,? super A> handler); -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/Channels.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,214 +0,0 @@ -/* - * Copyright 2000-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.channels; - -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.Reader; -import java.io.Writer; -import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.charset.Charset; -import java.nio.charset.CharsetDecoder; -import java.nio.charset.CharsetEncoder; -import java.nio.charset.UnsupportedCharsetException; -import java.nio.channels.spi.AbstractInterruptibleChannel; -import java.util.concurrent.ExecutionException; -import sun.nio.ch.ChannelInputStream; -import sun.nio.cs.StreamDecoder; -import sun.nio.cs.StreamEncoder; - - -/** - * Utility methods for channels and streams. - * - * <p> This class defines static methods that support the interoperation of the - * stream classes of the <tt>{@link java.io}</tt> package with the channel - * classes of this package. </p> - * - * - * @author Mark Reinhold - * @author Mike McCloskey - * @author JSR-51 Expert Group - * @since 1.4 - */ - -public final class Channels { - - private Channels() { } // No instantiation - - /** - * {@note new} - * Constructs a stream that reads bytes from the given channel. - * - * <p> The stream will not be buffered, and it will not support the {@link - * InputStream#mark mark} or {@link InputStream#reset reset} methods. The - * stream will be safe for access by multiple concurrent threads. Closing - * the stream will in turn cause the channel to be closed. </p> - * - * @param ch - * The channel from which bytes will be read - * - * @return A new input stream - * - * @since 1.7 - */ - public static InputStream newInputStream(final AsynchronousByteChannel ch) { - return new InputStream() { - - private ByteBuffer bb = null; - private byte[] bs = null; // Invoker's previous array - private byte[] b1 = null; - - - public synchronized int read() throws IOException { - if (b1 == null) - b1 = new byte[1]; - int n = this.read(b1); - if (n == 1) - return b1[0] & 0xff; - return -1; - } - - - public synchronized int read(byte[] bs, int off, int len) - throws IOException - { - if ((off < 0) || (off > bs.length) || (len < 0) || - ((off + len) > bs.length) || ((off + len) < 0)) { - throw new IndexOutOfBoundsException(); - } else if (len == 0) - return 0; - - ByteBuffer bb = ((this.bs == bs) - ? this.bb - : ByteBuffer.wrap(bs)); - bb.position(off); - bb.limit(Math.min(off + len, bb.capacity())); - this.bb = bb; - this.bs = bs; - - boolean interrupted = false; - try { - for (;;) { - try { - return ch.read(bb).get(); - } catch (ExecutionException ee) { - throw new IOException(ee.getCause()); - } catch (InterruptedException ie) { - interrupted = true; - } - } - } finally { - if (interrupted) - Thread.currentThread().interrupt(); - } - } - - - public void close() throws IOException { - ch.close(); - } - }; - } - - /** - * {@note new} - * Constructs a stream that writes bytes to the given channel. - * - * <p> The stream will not be buffered. The stream will be safe for access - * by multiple concurrent threads. Closing the stream will in turn cause - * the channel to be closed. </p> - * - * @param ch - * The channel to which bytes will be written - * - * @return A new output stream - * - * @since 1.7 - */ - public static OutputStream newOutputStream(final AsynchronousByteChannel ch) { - return new OutputStream() { - - private ByteBuffer bb = null; - private byte[] bs = null; // Invoker's previous array - private byte[] b1 = null; - - - public synchronized void write(int b) throws IOException { - if (b1 == null) - b1 = new byte[1]; - b1[0] = (byte)b; - this.write(b1); - } - - - public synchronized void write(byte[] bs, int off, int len) - throws IOException - { - if ((off < 0) || (off > bs.length) || (len < 0) || - ((off + len) > bs.length) || ((off + len) < 0)) { - throw new IndexOutOfBoundsException(); - } else if (len == 0) { - return; - } - ByteBuffer bb = ((this.bs == bs) - ? this.bb - : ByteBuffer.wrap(bs)); - bb.limit(Math.min(off + len, bb.capacity())); - bb.position(off); - this.bb = bb; - this.bs = bs; - - boolean interrupted = false; - try { - while (bb.remaining() > 0) { - try { - ch.write(bb).get(); - } catch (ExecutionException ee) { - throw new IOException(ee.getCause()); - } catch (InterruptedException ie) { - interrupted = true; - } - } - } finally { - if (interrupted) - Thread.currentThread().interrupt(); - } - } - - - public void close() throws IOException { - ch.close(); - } - }; - } - - -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/CompletionHandler.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,78 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.channels; - -/** - * A handler for consuming the result of an asynchronous I/O operation. - * - * <p> The asynchronous channels defined in this package allow a completion - * handler to be specified to consume the result of an asynchronous operation. - * The {@link #completed completed} method is invoked when the I/O operation - * completes successfully. The {@link #failed failed} method is invoked if the - * I/O operations fails. The {@link #cancelled cancelled} method is invoked when - * the I/O operation is cancelled by invoking the {@link - * java.util.concurrent.Future#cancel cancel} method. The implementations of - * these methods should complete in a timely manner so as to avoid keeping the - * invoking thread from dispatching to other completion handlers. - * - * @param <V> The result type of the I/O operation - * @param <A> The type of the object attached to the I/O operation - * - * @since 1.7 - */ - -public interface CompletionHandler<V,A> { - - /** - * Invoked when an operation has completed. - * - * @param result - * The result of the I/O operation. - * @param attachment - * The object attached to the I/O operation when it was initiated. - */ - void completed(V result, A attachment); - - /** - * Invoked when an operation fails. - * - * @param exc - * The exception - * @param attachment - * The object attached to the I/O operation when it was initiated. - */ - void failed(Throwable exc, A attachment); - - /** - * Invoked when an operation is cancelled by invoking the {@link - * java.util.concurrent.Future#cancel cancel} method. - * - * @param attachment - * The object attached to the I/O operation when it was initiated. - */ - void cancelled(A attachment); -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/DatagramChannel.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,223 +0,0 @@ -/* - * Copyright 2000-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.channels; - -import java.io.IOException; -import java.net.DatagramSocket; -import java.net.SocketAddress; -import java.nio.ByteBuffer; - -import org.classpath.icedtea.java.net.ProtocolFamily; -import org.classpath.icedtea.java.net.SocketOption; - -import org.classpath.icedtea.java.nio.channels.spi.SelectorProvider; - -/** - * A selectable channel for datagram-oriented sockets. - * - * <p> {@note revised} A datagram channel is created by invoking one of the {@link #open open} methods - * of this class. It is not possible to create a channel for an arbitrary, - * pre-existing datagram socket. A newly-created datagram channel is open but not - * connected. A datagram channel need not be connected in order for the {@link #send - * send} and {@link #receive receive} methods to be used. A datagram channel may be - * connected, by invoking its {@link #connect connect} method, in order to - * avoid the overhead of the security checks are otherwise performed as part of - * every send and receive operation. A datagram channel must be connected in - * order to use the {@link #read(java.nio.ByteBuffer) read} and {@link - * #write(java.nio.ByteBuffer) write} methods, since those methods do not - * accept or return socket addresses. - * - * <p> Once connected, a datagram channel remains connected until it is - * disconnected or closed. Whether or not a datagram channel is connected may - * be determined by invoking its {@link #isConnected isConnected} method. - * - * <p> Socket options are configured using the {@link #setOption(SocketOption,Object) - * setOption} method. A datagram channel to an Internet Protocol socket supports - * the following options: - * <blockquote> - * <table border> - * <tr> - * <th>Option Name</th> - * <th>Description</th> - * </tr> - * <tr> - * <td> {@link java.net.StandardSocketOption#SO_SNDBUF SO_SNDBUF} </td> - * <td> The size of the socket send buffer </td> - * </tr> - * <tr> - * <td> {@link java.net.StandardSocketOption#SO_RCVBUF SO_RCVBUF} </td> - * <td> The size of the socket receive buffer </td> - * </tr> - * <tr> - * <td> {@link java.net.StandardSocketOption#SO_REUSEADDR SO_REUSEADDR} </td> - * <td> Re-use address </td> - * </tr> - * <tr> - * <td> {@link java.net.StandardSocketOption#SO_BROADCAST SO_BROADCAST} </td> - * <td> Allow transmission of broadcast datagrams </td> - * </tr> - * <tr> - * <td> {@link java.net.StandardSocketOption#IP_TOS IP_TOS} </td> - * <td> The Type of Service (ToS) octet in the Internet Protocol (IP) header </td> - * </tr> - * <tr> - * <td> {@link java.net.StandardSocketOption#IP_MULTICAST_IF IP_MULTICAST_IF} </td> - * <td> The network interface for Internet Protocol (IP) multicast datagrams </td> - * </tr> - * <tr> - * <td> {@link java.net.StandardSocketOption#IP_MULTICAST_TTL - * IP_MULTICAST_TTL} </td> - * <td> The <em>time-to-live</em> for Internet Protocol (IP) multicast - * datagrams </td> - * </tr> - * <tr> - * <td> {@link java.net.StandardSocketOption#IP_MULTICAST_LOOP - * IP_MULTICAST_LOOP} </td> - * <td> Loopback for Internet Protocol (IP) multicast datagrams </td> - * </tr> - * </table> - * </blockquote> - * Additional (implementation specific) options may also be supported. - * - * <p> Datagram channels are safe for use by multiple concurrent threads. They - * support concurrent reading and writing, though at most one thread may be - * reading and at most one thread may be writing at any given time. </p> - * - * @author Mark Reinhold - * @author JSR-51 Expert Group - * @since 1.4 - * @updated 1.7 - */ - -public abstract class DatagramChannel - extends java.nio.channels.DatagramChannel - implements MulticastChannel -{ - - /** - * Initializes a new instance of this class. - */ - protected DatagramChannel(SelectorProvider provider) { - super(provider); - } - - /** - * Opens a datagram channel. - * - * <p> The new channel is created by invoking the {@link - * java.nio.channels.spi.SelectorProvider#openDatagramChannel() - * openDatagramChannel} method of the system-wide default {@link - * java.nio.channels.spi.SelectorProvider} object. The channel will not be - * connected. </p> - * - * @return A new datagram channel - * - * @throws IOException - * If an I/O error occurs - */ - public static DatagramChannel open() throws IOException { - return SelectorProvider.provider().openDatagramChannel(); - } - - /** - * Opens a datagram channel. - * - * <p> The {@code family} parameter is used to specify the {@link - * ProtocolFamily}. If the datagram channel is to be used for IP multicasing - * then this should correspond to the address type of the multicast groups - * that this channel will join. - * - * <p> The new channel is created by invoking the {@link - * java.nio.channels.spi.SelectorProvider#openDatagramChannel(ProtocolFamily) - * openDatagramChannel} method of the system-wide default {@link - * java.nio.channels.spi.SelectorProvider} object. The channel will not be - * connected. - * - * @param family - * The protocol family - * - * @return A new datagram channel - * - * @throws UnsupportedOperationException - * If the specified protocol family is not supported. For example, - * suppose the parameter is specified as {@link - * java.net.StandardProtocolFamily#INET6 StandardProtocolFamily.INET6} - * but IPv6 is not enabled on the platform. - * @throws IOException - * If an I/O error occurs - * - * @since 1.7 - */ - public static DatagramChannel open(ProtocolFamily family) throws IOException { - return SelectorProvider.provider().openDatagramChannel(family); - } - - - // -- Socket-specific operations -- - - /** - * @throws AlreadyBoundException {@inheritDoc} - * @throws UnsupportedAddressTypeException {@inheritDoc} - * @throws ClosedChannelException {@inheritDoc} - * @throws IOException {@inheritDoc} - * @throws SecurityException - * If a security manager has been installed and its {@link - * SecurityManager#checkListen checkListen} method denies the - * operation - * - * @since 1.7 - */ - public abstract DatagramChannel bind(SocketAddress local) - throws IOException; - - /** - * @throws IllegalArgumentException {@inheritDoc} - * @throws ClosedChannelException {@inheritDoc} - * @throws IOException {@inheritDoc} - * - * @since 1.7 - */ - public abstract <T> DatagramChannel setOption(SocketOption<T> name, T value) - throws IOException; - - /** - * {@note new} - * Returns the remote address to which this channel's socket is connected. - * - * @return The remote address; {@code null} if the channel's socket is not - * connected - * - * @throws ClosedChannelException - * If the channel is closed - * @throws IOException - * If an I/O error occurs - * - * @since 1.7 - */ - public abstract SocketAddress getRemoteAddress() throws IOException; - -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/FileChannel.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,404 +0,0 @@ -/* - * Copyright 2000-2005 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.channels; - -import java.io.*; -import java.nio.ByteBuffer; -import java.nio.MappedByteBuffer; -import java.nio.channels.GatheringByteChannel; -import java.nio.channels.ReadableByteChannel; -import java.nio.channels.ScatteringByteChannel; -import java.nio.channels.WritableByteChannel; -import java.nio.channels.spi.AbstractInterruptibleChannel; -import java.util.Set; -import java.util.HashSet; -import java.util.Collections; - -import org.classpath.icedtea.java.nio.file.OpenOption; -import org.classpath.icedtea.java.nio.file.Path; -import org.classpath.icedtea.java.nio.file.attribute.FileAttribute; -import org.classpath.icedtea.java.nio.file.spi.FileSystemProvider; - -/** - * A channel for reading, writing, mapping, and manipulating a file. - * - * <p> {@note revised} - * A file channel is a {@link SeekableByteChannel} that is connected to - * a file. It has a current <i>position</i> within its file which can - * be both {@link #position() <i>queried</i>} and {@link #position(long) - * <i>modified</i>}. The file itself contains a variable-length sequence - * of bytes that can be read and written and whose current {@link #size - * <i>size</i>} can be queried. The size of the file increases - * when bytes are written beyond its current size; the size of the file - * decreases when it is {@link #truncate </code><i>truncated</i><code>}. The - * file may also have some associated <i>metadata</i> such as access - * permissions, content type, and last-modification time; this class does not - * define methods for metadata access. - * - * <p> In addition to the familiar read, write, and close operations of byte - * channels, this class defines the following file-specific operations: </p> - * - * <ul> - * - * <li><p> Bytes may be {@link #read(ByteBuffer, long) read} or - * {@link #write(ByteBuffer, long) <i>written</i>} at an absolute - * position in a file in a way that does not affect the channel's current - * position. </p></li> - * - * <li><p> A region of a file may be {@link #map <i>mapped</i>} - * directly into memory; for large files this is often much more efficient - * than invoking the usual <tt>read</tt> or <tt>write</tt> methods. - * </p></li> - * - * <li><p> Updates made to a file may be {@link #force <i>forced - * out</i>} to the underlying storage device, ensuring that data are not - * lost in the event of a system crash. </p></li> - * - * <li><p> Bytes can be transferred from a file {@link #transferTo <i>to - * some other channel</i>}, and {@link #transferFrom <i>vice - * versa</i>}, in a way that can be optimized by many operating systems - * into a very fast transfer directly to or from the filesystem cache. - * </p></li> - * - * <li><p> A region of a file may be {@link FileLock <i>locked</i>} - * against access by other programs. </p></li> - * - * </ul> - * - * <p> File channels are safe for use by multiple concurrent threads. The - * {@link Channel#close close} method may be invoked at any time, as specified - * by the {@link Channel} interface. Only one operation that involves the - * channel's position or can change its file's size may be in progress at any - * given time; attempts to initiate a second such operation while the first is - * still in progress will block until the first operation completes. Other - * operations, in particular those that take an explicit position, may proceed - * concurrently; whether they in fact do so is dependent upon the underlying - * implementation and is therefore unspecified. - * - * <p> The view of a file provided by an instance of this class is guaranteed - * to be consistent with other views of the same file provided by other - * instances in the same program. The view provided by an instance of this - * class may or may not, however, be consistent with the views seen by other - * concurrently-running programs due to caching performed by the underlying - * operating system and delays induced by network-filesystem protocols. This - * is true regardless of the language in which these other programs are - * written, and whether they are running on the same machine or on some other - * machine. The exact nature of any such inconsistencies are system-dependent - * and are therefore unspecified. - * - * <p> A file channel is created by invoking one of the {@link #open open} - * methods defined by this class. A file channel can also be obtained from an - * existing {@link java.io.FileInputStream#getChannel FileInputStream}, {@link - * java.io.FileOutputStream#getChannel FileOutputStream}, or {@link - * java.io.RandomAccessFile#getChannel RandomAccessFile} object by invoking - * that object's <tt>getChannel</tt> method, which returns a file channel that - * is connected to the same underlying file. Where the file channel is obtained - * from an existing stream or random access file then the state of the file - * channel is intimately connected to that of the object whose <tt>getChannel</tt> - * method returned the channel. Changing the channel's position, whether - * explicitly or by reading or writing bytes, will change the file position of - * the originating object, and vice versa. Changing the file's length via the - * file channel will change the length seen via the originating object, and vice - * versa. Changing the file's content by writing bytes will change the content - * seen by the originating object, and vice versa. - * - * <a name="open-mode"></a> <p> At various points this class specifies that an - * instance that is "open for reading," "open for writing," or "open for - * reading and writing" is required. A channel obtained via the {@link - * java.io.FileInputStream#getChannel getChannel} method of a {@link - * java.io.FileInputStream} instance will be open for reading. A channel - * obtained via the {@link java.io.FileOutputStream#getChannel getChannel} - * method of a {@link java.io.FileOutputStream} instance will be open for - * writing. Finally, a channel obtained via the {@link - * java.io.RandomAccessFile#getChannel getChannel} method of a {@link - * java.io.RandomAccessFile} instance will be open for reading if the instance - * was created with mode <tt>"r"</tt> and will be open for reading and writing - * if the instance was created with mode <tt>"rw"</tt>. - * - * <a name="append-mode"></a><p> A file channel that is open for writing may be in - * <i>append mode</i>, for example if it was obtained from a file-output stream - * that was created by invoking the {@link - * java.io.FileOutputStream#FileOutputStream(java.io.File,boolean) - * FileOutputStream(File,boolean)} constructor and passing <tt>true</tt> for - * the second parameter. In this mode each invocation of a relative write - * operation first advances the position to the end of the file and then writes - * the requested data. Whether the advancement of the position and the writing - * of the data are done in a single atomic operation is system-dependent and - * therefore unspecified. - * - * @see java.io.FileInputStream#getChannel() - * @see java.io.FileOutputStream#getChannel() - * @see java.io.RandomAccessFile#getChannel() - * - * @author Mark Reinhold - * @author Mike McCloskey - * @author JSR-51 Expert Group - * @since 1.4 - * @updated 1.7 - */ - -public abstract class FileChannel - extends java.nio.channels.FileChannel - implements SeekableByteChannel -{ - /** - * Initializes a new instance of this class. - */ - protected FileChannel() { } - - /** - * {@note new} - * Opens or creates a file, returning a file channel to access the file. - * - * <p> The {@code options} parameter determines how the file is opened. - * The {@link StandardOpenOption#READ READ} and {@link StandardOpenOption#WRITE - * WRITE} options determine if the file should be opened for reading and/or - * writing. If neither option (or the {@link StandardOpenOption#APPEND APPEND} - * option) is contained in the array then the file is opened for reading. - * By default reading or writing commences at the beginning of the file. - * - * <p> In the addition to {@code READ} and {@code WRITE}, the following - * options may be present: - * - * <table border=1 cellpadding=5 summary=""> - * <tr> <th>Option</th> <th>Description</th> </tr> - * <tr> - * <td> {@link StandardOpenOption#APPEND APPEND} </td> - * <td> If this option is present then the file is opened for writing and - * each invocation of the channel's {@code write} method first advances - * the position to the end of the file and then writes the requested - * data. Whether the advancement of the position and the writing of the - * data are done in a single atomic operation is system-dependent and - * therefore unspecified. This option may not be used in conjunction - * with the {@code READ} or {@code TRUNCATE_EXISTING} options. </td> - * </tr> - * <tr> - * <td> {@link StandardOpenOption#TRUNCATE_EXISTING TRUNCATE_EXISTING} </td> - * <td> If this option is present then the existing file is truncated to - * a size of 0 bytes. This option is ignored when the file is opened only - * for reading. </td> - * </tr> - * <tr> - * <td> {@link StandardOpenOption#CREATE_NEW CREATE_NEW} </td> - * <td> If this option is present then a new file is created, failing if - * the file already exists. When creating a file the check for the - * existence of the file and the creation of the file if it does not exist - * is atomic with respect to other file system operations. This option is - * ignored when the file is opened only for reading. </td> - * </tr> - * <tr> - * <td > {@link StandardOpenOption#CREATE CREATE} </td> - * <td> If this option is present then an existing file is opened if it - * exists, otherwise a new file is created. When creating a file the check - * for the existence of the file and the creation of the file if it does - * not exist is atomic with respect to other file system operations. This - * option is ignored if the {@code CREATE_NEW} option is also present or - * the file is opened only for reading. </td> - * </tr> - * <tr> - * <td > {@link StandardOpenOption#DELETE_ON_CLOSE DELETE_ON_CLOSE} </td> - * <td> When this option is present then the implementation makes a - * <em>best effort</em> attempt to delete the file when closed by the - * the {@link #close close} method. If the {@code close} method is not - * invoked then a <em>best effort</em> attempt is made to delete the file - * when the Java virtual machine terminates. </td> - * </tr> - * <tr> - * <td>{@link StandardOpenOption#SPARSE SPARSE} </td> - * <td> When creating a new file this option is a <em>hint</em> that the - * new file will be sparse. This option is ignored when not creating - * a new file. </td> - * </tr> - * <tr> - * <td> {@link StandardOpenOption#SYNC SYNC} </td> - * <td> Requires that every update to the file's content or metadata be - * written synchronously to the underlying storage device. (see <a - * href="../file/package-summary.html#integrity"> Synchronized I/O file - * integrity</a>). </td> - * <tr> - * <tr> - * <td> {@link StandardOpenOption#DSYNC DSYNC} </td> - * <td> Requires that every update to the file's content be written - * synchronously to the underlying storage device. (see <a - * href="../file/package-summary.html#integrity"> Synchronized I/O file - * integrity</a>). </td> - * </tr> - * </table> - * - * <p> An implementation may also support additional options. - * - * <p> The {@code attrs} parameter is an optional array of file {@link - * FileAttribute file-attributes} to set atomically when creating the file. - * - * <p> The new channel is created by invoking the {@link - * FileSystemProvider#newFileChannel newFileChannel} method on the - * provider that created the {@code Path}. - * - * @param file - * The path of the file to open or create - * @param options - * Options specifying how the file is opened - * @param attrs - * An optional list of file attributes to set atomically when - * creating the file - * - * @return A new file channel - * - * @throws IllegalArgumentException - * If the set contains an invalid combination of options - * @throws UnsupportedOperationException - * If the {@code file} is associated with a provider that does not - * support creating file channels, or an unsupported open option is - * specified, or the array contains an attribute that cannot be set - * atomically when creating the file - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * If a security manager is installed and it denies an - * unspecified permission required by the implementation. - * In the case of the default provider, the {@link - * SecurityManager#checkRead(String)} method is invoked to check - * read access if the file is opened for reading. The {@link - * SecurityManager#checkWrite(String)} method is invoked to check - * write access if the file is opened for writing - * - * @since 1.7 - */ - public static FileChannel open(Path file, - Set<? extends OpenOption> options, - FileAttribute<?>... attrs) - throws IOException - { - FileSystemProvider provider = file.getFileSystem().provider(); - return provider.newFileChannel(file, options, attrs); - } - - private static final FileAttribute<?>[] NO_ATTRIBUTES = new FileAttribute[0]; - - /** - * {@note new} - * Opens or creates a file, returning a file channel to access the file. - * - * <p> An invocation of this method behaves in exactly the same way as the - * invocation - * <pre> - * fc.{@link #open(Path,Set,FileAttribute[]) open}(file, options, new FileAttribute<?>[0]); - * </pre> - * - * @param file - * The path of the file to open or create - * @param options - * Options specifying how the file is opened - * - * @return A new file channel - * - * @throws IllegalArgumentException - * If the set contains an invalid combination of options - * @throws UnsupportedOperationException - * If the {@code file} is associated with a provider that does not - * support creating file channels, or an unsupported open option is - * specified - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * If a security manager is installed and it denies an - * unspecified permission required by the implementation. - * In the case of the default provider, the {@link - * SecurityManager#checkRead(String)} method is invoked to check - * read access if the file is opened for reading. The {@link - * SecurityManager#checkWrite(String)} method is invoked to check - * write access if the file is opened for writing - * - * @since 1.7 - */ - public static FileChannel open(Path file, OpenOption... options) - throws IOException - { - Set<OpenOption> set = new HashSet<OpenOption>(options.length); - Collections.addAll(set, options); - return open(file, set, NO_ATTRIBUTES); - } - - /** - * Sets this channel's file position. - * - * <p> Setting the position to a value that is greater than the file's - * current size is legal but does not change the size of the file. A later - * attempt to read bytes at such a position will immediately return an - * end-of-file indication. A later attempt to write bytes at such a - * position will cause the file to be grown to accommodate the new bytes; - * the values of any bytes between the previous end-of-file and the - * newly-written bytes are unspecified. </p> - * - * @param newPosition - * The new position, a non-negative integer counting - * the number of bytes from the beginning of the file - * - * @return This file channel - * - * @throws ClosedChannelException - * If this channel is closed - * - * @throws IllegalArgumentException - * If the new position is negative - * - * @throws IOException - * If some other I/O error occurs - */ - public abstract FileChannel positionSBC(long newPosition) throws IOException; - - /** - * Truncates this channel's file to the given size. - * - * <p> If the given size is less than the file's current size then the file - * is truncated, discarding any bytes beyond the new end of the file. If - * the given size is greater than or equal to the file's current size then - * the file is not modified. In either case, if this channel's file - * position is greater than the given size then it is set to that size. - * </p> - * - * @param size - * The new size, a non-negative byte count - * - * @return This file channel - * - * @throws NonWritableChannelException - * If this channel was not opened for writing - * - * @throws ClosedChannelException - * If this channel is closed - * - * @throws IllegalArgumentException - * If the new size is negative - * - * @throws IOException - * If some other I/O error occurs - */ - public abstract FileChannel truncateSBC(long size) throws IOException; - - -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/FileLock.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,321 +0,0 @@ -/* - * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.channels; - -import java.io.IOException; - -import java.nio.channels.Channel; - -/** - * A token representing a lock on a region of a file. - * - * <p> A file-lock object is created each time a lock is acquired on a file via - * one of the {@link FileChannel#lock(long,long,boolean) lock} or {@link - * FileChannel#tryLock(long,long,boolean) tryLock} methods of the - * {@link FileChannel} class, or the {@link - * AsynchronousFileChannel#lock(long,long,boolean,Object,CompletionHandler) lock} - * or {@link AsynchronousFileChannel#tryLock(long,long,boolean) tryLock} - * methods of the {@link AsynchronousFileChannel} class. - * - * <p> A file-lock object is initially valid. It remains valid until the lock - * is released by invoking the {@link #release release} method, by closing the - * channel that was used to acquire it, or by the termination of the Java - * virtual machine, whichever comes first. The validity of a lock may be - * tested by invoking its {@link #isValid isValid} method. - * - * <p> A file lock is either <i>exclusive</i> or <i>shared</i>. A shared lock - * prevents other concurrently-running programs from acquiring an overlapping - * exclusive lock, but does allow them to acquire overlapping shared locks. An - * exclusive lock prevents other programs from acquiring an overlapping lock of - * either type. Once it is released, a lock has no further effect on the locks - * that may be acquired by other programs. - * - * <p> Whether a lock is exclusive or shared may be determined by invoking its - * {@link #isShared isShared} method. Some platforms do not support shared - * locks, in which case a request for a shared lock is automatically converted - * into a request for an exclusive lock. - * - * <p> The locks held on a particular file by a single Java virtual machine do - * not overlap. The {@link #overlaps overlaps} method may be used to test - * whether a candidate lock range overlaps an existing lock. - * - * <p> A file-lock object records the file channel upon whose file the lock is - * held, the type and validity of the lock, and the position and size of the - * locked region. Only the validity of a lock is subject to change over time; - * all other aspects of a lock's state are immutable. - * - * <p> File locks are held on behalf of the entire Java virtual machine. - * They are not suitable for controlling access to a file by multiple - * threads within the same virtual machine. - * - * <p> File-lock objects are safe for use by multiple concurrent threads. - * - * - * <a name="pdep"><h4> Platform dependencies </h4></a> - * - * <p> This file-locking API is intended to map directly to the native locking - * facility of the underlying operating system. Thus the locks held on a file - * should be visible to all programs that have access to the file, regardless - * of the language in which those programs are written. - * - * <p> Whether or not a lock actually prevents another program from accessing - * the content of the locked region is system-dependent and therefore - * unspecified. The native file-locking facilities of some systems are merely - * <i>advisory</i>, meaning that programs must cooperatively observe a known - * locking protocol in order to guarantee data integrity. On other systems - * native file locks are <i>mandatory</i>, meaning that if one program locks a - * region of a file then other programs are actually prevented from accessing - * that region in a way that would violate the lock. On yet other systems, - * whether native file locks are advisory or mandatory is configurable on a - * per-file basis. To ensure consistent and correct behavior across platforms, - * it is strongly recommended that the locks provided by this API be used as if - * they were advisory locks. - * - * <p> On some systems, acquiring a mandatory lock on a region of a file - * prevents that region from being {@link java.nio.channels.FileChannel#map - * <i>mapped into memory</i>}, and vice versa. Programs that combine - * locking and mapping should be prepared for this combination to fail. - * - * <p> On some systems, closing a channel releases all locks held by the Java - * virtual machine on the underlying file regardless of whether the locks were - * acquired via that channel or via another channel open on the same file. It - * is strongly recommended that, within a program, a unique channel be used to - * acquire all locks on any given file. - * - * <p> Some network filesystems permit file locking to be used with - * memory-mapped files only when the locked regions are page-aligned and a - * whole multiple of the underlying hardware's page size. Some network - * filesystems do not implement file locks on regions that extend past a - * certain position, often 2<sup>30</sup> or 2<sup>31</sup>. In general, great - * care should be taken when locking files that reside on network filesystems. - * - * - * @author Mark Reinhold - * @author JSR-51 Expert Group - * @since 1.4 - * @updated 1.7 - */ - -public abstract class FileLock { - - private final Channel channel; - private final long position; - private final long size; - private final boolean shared; - - /** - * Initializes a new instance of this class. </p> - * - * @param channel - * The file channel upon whose file this lock is held - * - * @param position - * The position within the file at which the locked region starts; - * must be non-negative - * - * @param size - * The size of the locked region; must be non-negative, and the sum - * <tt>position</tt> + <tt>size</tt> must be non-negative - * - * @param shared - * <tt>true</tt> if this lock is shared, - * <tt>false</tt> if it is exclusive - * - * @throws IllegalArgumentException - * If the preconditions on the parameters do not hold - */ - protected FileLock(FileChannel channel, - long position, long size, boolean shared) - { - if (position < 0) - throw new IllegalArgumentException("Negative position"); - if (size < 0) - throw new IllegalArgumentException("Negative size"); - if (position + size < 0) - throw new IllegalArgumentException("Negative position + size"); - this.channel = channel; - this.position = position; - this.size = size; - this.shared = shared; - } - - /** - * {@note new} Initializes a new instance of this class. - * - * @param channel - * The channel upon whose file this lock is held - * - * @param position - * The position within the file at which the locked region starts; - * must be non-negative - * - * @param size - * The size of the locked region; must be non-negative, and the sum - * <tt>position</tt> + <tt>size</tt> must be non-negative - * - * @param shared - * <tt>true</tt> if this lock is shared, - * <tt>false</tt> if it is exclusive - * - * @throws IllegalArgumentException - * If the preconditions on the parameters do not hold - * - * @since 1.7 - */ - protected FileLock(AsynchronousFileChannel channel, - long position, long size, boolean shared) - { - if (position < 0) - throw new IllegalArgumentException("Negative position"); - if (size < 0) - throw new IllegalArgumentException("Negative size"); - if (position + size < 0) - throw new IllegalArgumentException("Negative position + size"); - this.channel = channel; - this.position = position; - this.size = size; - this.shared = shared; - } - - /** - * {@note revised} - * Returns the file channel upon whose file this lock was acquired. - * - * <p> This method has been superseded by the {@link #acquiredBy acquiredBy} - * method. - * - * @return The file channel, or {@code null} if the file lock was not - * acquired by a file channel. - */ - public final FileChannel channel() { - return (channel instanceof FileChannel) ? (FileChannel)channel : null; - } - - /** - * {@note new} - * Returns the channel upon whose file this lock was acquired. - * - * @return The channel upon whose file this lock was acquired. - * - * @since 1.7 - */ - public Channel acquiredBy() { - return channel; - } - - /** - * Returns the position within the file of the first byte of the locked - * region. - * - * <p> A locked region need not be contained within, or even overlap, the - * actual underlying file, so the value returned by this method may exceed - * the file's current size. </p> - * - * @return The position - */ - public final long position() { - return position; - } - - /** - * Returns the size of the locked region in bytes. - * - * <p> A locked region need not be contained within, or even overlap, the - * actual underlying file, so the value returned by this method may exceed - * the file's current size. </p> - * - * @return The size of the locked region - */ - public final long size() { - return size; - } - - /** - * Tells whether this lock is shared. </p> - * - * @return <tt>true</tt> if lock is shared, - * <tt>false</tt> if it is exclusive - */ - public final boolean isShared() { - return shared; - } - - /** - * Tells whether or not this lock overlaps the given lock range. </p> - * - * @return <tt>true</tt> if, and only if, this lock and the given lock - * range overlap by at least one byte - */ - public final boolean overlaps(long position, long size) { - if (position + size <= this.position) - return false; // That is below this - if (this.position + this.size <= position) - return false; // This is below that - return true; - } - - /** - * Tells whether or not this lock is valid. - * - * <p> A lock object remains valid until it is released or the associated - * file channel is closed, whichever comes first. </p> - * - * @return <tt>true</tt> if, and only if, this lock is valid - */ - public abstract boolean isValid(); - - /** - * Releases this lock. - * - * <p> If this lock object is valid then invoking this method releases the - * lock and renders the object invalid. If this lock object is invalid - * then invoking this method has no effect. </p> - * - * @throws ClosedChannelException - * If the channel that was used to acquire this lock - * is no longer open - * - * @throws IOException - * If an I/O error occurs - */ - public abstract void release() throws IOException; - - /** - * Returns a string describing the range, type, and validity of this lock. - * - * @return A descriptive string - */ - public final String toString() { - return (this.getClass().getName() - + "[" + position - + ":" + size - + " " + (shared ? "shared" : "exclusive") - + " " + (isValid() ? "valid" : "invalid") - + "]"); - } - -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/MembershipKey.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,183 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.channels; - -import java.net.InetAddress; -import java.net.NetworkInterface; -import java.io.IOException; - -/** - * A token representing the membership of an Internet Protocol (IP) multicast - * group. - * - * <p> A membership key may represent a membership to receive all datagrams sent - * to the group, or it may be <em>source-specific</em>, meaning that it - * represents a membership that receives only datagrams from a specific source - * address. Whether or not a membership key is source-specific may be determined - * by invoking its {@link #sourceAddress() sourceAddress} method. - * - * <p> A membership key is valid upon creation and remains valid until the - * membership is dropped by invoking the {@link #drop() drop} method, or - * the channel is closed. The validity of the membership key may be tested - * by invoking its {@link #isValid() isValid} method. - * - * <p> Where a membership key is not source-specific and the underlying operation - * system supports source filtering, then the {@link #block block} and {@link - * #unblock unblock} methods can be used to block or unblock multicast datagrams - * from particular source addresses. - * - * @see MulticastChannel - * - * @since 1.7 - */ -public abstract class MembershipKey { - - /** - * Initializes a new instance of this class. - */ - protected MembershipKey() { - } - - /** - * Tells whether or not this membership is valid. - * - * <p> A multicast group membership is valid upon creation and remains - * valid until the membership is dropped by invoking the {@link #drop() drop} - * method, or the channel is closed. - * - * @return {@code true} if this membership key is valid, {@code false} - * otherwise - */ - public abstract boolean isValid(); - - /** - * Drop membership. - * - * <p> If the membership key represents a membership to receive all datagrams - * then the membership is dropped and the channel will no longer receive any - * datagrams sent to the group. If the membership key is source-specific - * then the channel will no longer receive datagrams sent to the group from - * that source address. - * - * <p> After membership is dropped it may still be possible to receive - * datagrams sent to the group. This can arise when datagrams are waiting to - * be received in the socket's receive buffer. After membership is dropped - * then the channel may {@link MulticastChannel#join join} the group again - * in which case a new membership key is returned. - * - * <p> Upon return, this membership object will be {@link #isValid() invalid}. - * If the multicast group membership is already invalid then invoking this - * method has no effect. Once a multicast group membership is invalid, - * it remains invalid forever. - * - * @throws IOException - * If an I/O error occurs - */ - public abstract void drop() throws IOException; - - /** - * Block multicast datagrams from the given source address. - * - * <p> If this membership key is not source-specific, and the underlying - * operating system supports source filtering, then this method blocks - * multicast datagrams from the given source address. If the given source - * address is already blocked then this method has no effect. - * After a source address is blocked it may still be possible to receive - * datagams from that source. This can arise when datagrams are waiting to - * be received in the socket's receive buffer. - * - * @param source - * The source address to block - * - * @return This membership key - * - * @throws IllegalArgumentException - * If the {@code source} parameter is not a unicast address or - * is not the same address type as the multicast group - * @throws IllegalStateException - * If this membership key is source-specific or is no longer valid - * @throws UnsupportedOperationException - * If the underlying operating system does not support source - * filtering - * @throws IOException - * If an I/O error occurs - */ - public abstract MembershipKey block(InetAddress source) throws IOException; - - /** - * Unblock multicast datagrams from the given source address that was - * previously blocked using the {@link #block(InetAddress) block} method. - * - * @param source - * The source address to unblock - * - * @return This membership key - * - * @throws IllegalStateException - * If the given source address is not currently blocked or the - * membership key is no longer valid - * @throws IOException - * If an I/O error occurs - */ - public abstract MembershipKey unblock(InetAddress source) throws IOException; - - /** - * Returns the channel for which this membership key was created. This - * method will continue to return the channel even after the membership - * becomes {@link #isValid invalid}. - * - * @return the channel - */ - public abstract MulticastChannel channel(); - - /** - * Returns the multicast group for which this membership key was created. - * This method will continue to return the group even after the membership - * becomes {@link #isValid invalid}. - * - * @return the multicast group - */ - public abstract InetAddress group(); - - /** - * Returns the network interface for which this membership key was created. - * This method will continue to return the network interface even after the - * membership becomes {@link #isValid invalid}. - * - * @return the network interface - */ - public abstract NetworkInterface networkInterface(); - - /** - * Returns the source address if this membership key is source-specific, - * or {@code null} if this membership is not source-specific. - * - * @return The source address if this membership key is source-specific, - * otherwise {@code null} - */ - public abstract InetAddress sourceAddress(); -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/MulticastChannel.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,216 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.channels; - -import java.net.InetAddress; -import java.net.NetworkInterface; -import java.io.IOException; - -import org.classpath.icedtea.java.net.ProtocolFamily; // javadoc -import org.classpath.icedtea.java.net.StandardProtocolFamily; // javadoc -import org.classpath.icedtea.java.net.StandardSocketOption; // javadoc - -/** - * A network channel that supports Internet Protocol (IP) multicasting. - * - * <p> IP multicasting is the transmission of IP datagrams to members of - * a <em>group</em> that is zero or more hosts identified by a single destination - * address. - * - * <p> In the case of a channel to an {@link StandardProtocolFamily#INET IPv4} socket, - * the underlying operating system supports <a href="http://www.ietf.org/rfc/rfc2236.txt"> - * <i>RFC 2236: Internet Group Management Protocol, Version 2 (IGMPv2)</i></a>. - * It may optionally support source filtering as specified by <a - * href="http://www.ietf.org/rfc/rfc3376.txt"> <i>RFC 3376: Internet Group - * Management Protocol, Version 3 (IGMPv3)</i></a>. - * For channels to an {@link StandardProtocolFamily#INET6 IPv6} socket, the equivalent - * standards are <a href="http://www.ietf.org/rfc/rfc2710.txt"> <i>RFC 2710: - * Multicast Listener Discovery (MLD) for IPv6</i></a> and <a - * href="http://www.ietf.org/rfc/rfc3810.txt"> <i>RFC 3810: Multicast Listener - * Discovery Version 2 (MLDv2) for IPv6</i></a>. - * - * <p> The {@link #join(InetAddress,NetworkInterface)} method is used to - * join a group and receive all multicast datagrams sent to the group. A channel - * may join several multicast groups and may join the same group on several - * {@link NetworkInterface interfaces}. Membership is dropped by invoking the {@link - * MembershipKey#drop drop} method on the returned {@link MembershipKey}. If the - * underlying platform supports source filtering then the {@link MembershipKey#block - * block} and {@link MembershipKey#unblock unblock} methods can be used to block or - * unblock multicast datagrams from particular source addresses. - * - * <p> The {@link #join(InetAddress,NetworkInterface,InetAddress)} method - * is used to begin receiving datagrams sent to a group whose source address matches - * a given source address. This method throws {@link UnsupportedOperationException} - * if the underlying platform does not support source filtering. Membership is - * <em>cumulative</em> and this method may be invoked again with the same group - * and interface to allow receiving datagrams from other source addresses. The - * method returns a {@link MembershipKey} that represents membership to receive - * datagrams from the given source address. Invoking the key's {@link - * MembershipKey#drop drop} method drops membership so that datagrams from the - * source address can no longer be received. - * - * <h4>Platform dependencies</h4> - * - * The multicast implementation is intended to map directly to the native - * multicasting facility. Consequently, the following items should be considered - * when developing an application that receives IP multicast datagrams: - * - * <ol> - * - * <li><p> The creation of the channel should specify the {@link ProtocolFamily} - * that corresponds to the address type of the multicast groups that the channel - * will join. There is no guarantee that a channel to a socket in one protocol - * family can join and receive multicast datagrams when the address of the - * multicast group corresponds to another protocol family. For example, it is - * implementation specific if a channel to an {@link StandardProtocolFamily#INET6 IPv6} - * socket can join an {@link StandardProtocolFamily#INET IPv4} multicast group and receive - * multicast datagrams sent to the group. </p></li> - * - * <li><p> The channel's socket should be bound to the {@link - * InetAddress#isAnyLocalAddress wildcard} address. If the socket is bound to - * a specific address, rather than the wildcard address then it is implementation - * specific if multicast datagrams are received by the socket. </p></li> - * - * <li><p> The {@link StandardSocketOption#SO_REUSEADDR SO_REUSEADDR} option should be - * enabled prior to {@link NetworkChannel#bind binding} the socket. This is - * required to allow multiple members of the group to bind to the same - * address. </p></li> - * - * </ol> - * - * <p> <b>Usage Example:</b> - * <pre> - * // join multicast group on this interface, and also use this - * // interface for outgoing multicast datagrams - * NetworkInterface ni = NetworkInterface.getByName("hme0"); - * - * DatagramChannel dc = DatagramChannel.open(StandardProtocolFamily.INET) - * .setOption(StandardSocketOption.SO_REUSEADDR, true) - * .bind(new InetSocketAddress(5000)) - * .setOption(StandardSocketOption.IP_MULTICAST_IF, ni); - * - * InetAddress group = InetAddress.getByName("225.4.5.6"); - * - * MembershipKey key = dc.join(group, ni); - * </pre> - * - * @since 1.7 - */ - -public interface MulticastChannel - extends NetworkChannel -{ - /** - * Joins a multicast group to begin receiving all datagrams sent to the group, - * returning a membership key. - * - * <p> If this channel is currently a member of the group on the given - * interface to receive all datagrams then the membership key, representing - * that membership, is returned. Otherwise this channel joins the group and - * the resulting new membership key is returned. The resulting membership key - * is not {@link MembershipKey#sourceAddress source-specific}. - * - * <p> A multicast channel may join several multicast groups, including - * the same group on more than one interface. An implementation may impose a - * limit on the number of groups that may be joined at the same time. - * - * @param group - * The multicast address to join - * @param interf - * The network interface on which to join the group - * - * @return The membership key - * - * @throws IllegalArgumentException - * If the group parameter is not a {@link InetAddress#isMulticastAddress - * multicast} address, or the group parameter is an address type - * that is not supported by this channel - * @throws IllegalStateException - * If the channel already has source-specific membership of the - * group on the interface - * @throws UnsupportedOperationException - * If the channel's socket is not an Internet Protocol socket - * @throws ClosedChannelException - * If this channel is closed - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * If a security manager is set, and its - * {@link SecurityManager#checkMulticast(InetAddress) checkMulticast} - * method denies access to the multiast group - */ - MembershipKey join(InetAddress group, NetworkInterface interf) - throws IOException; - - /** - * Joins a multicast group to begin receiving datagrams sent to the group - * from a given source address. - * - * <p> If this channel is currently a member of the group on the given - * interface to receive datagrams from the given source address then the - * membership key, representing that membership, is returned. Otherwise this - * channel joins the group and the resulting new membership key is returned. - * The resulting membership key is {@link MembershipKey#sourceAddress - * source-specific}. - * - * <p> Membership is <em>cumulative</em> and this method may be invoked - * again with the same group and interface to allow receiving datagrams sent - * by other source addresses to the group. - * - * @param group - * The multicast address to join - * @param interf - * The network interface on which to join the group - * @param source - * The source address - * - * @return The membership key - * - * @throws IllegalArgumentException - * If the group parameter is not a {@link - * InetAddress#isMulticastAddress multicast} address, the - * source parameter is not a unicast address, the group - * parameter is an address type that is not supported by this channel, - * or the source parameter is not the same address type as the group - * @throws IllegalStateException - * If the channel is currently a member of the group on the given - * interface to receive all datagrams - * @throws UnsupportedOperationException - * If the channel's socket is not an Internet Protocol socket or - * source filtering is not supported - * @throws ClosedChannelException - * If this channel is closed - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * If a security manager is set, and its - * {@link SecurityManager#checkMulticast(InetAddress) checkMulticast} - * method denies access to the multiast group - */ - MembershipKey join(InetAddress group, NetworkInterface interf, InetAddress source) - throws IOException; -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/NetworkChannel.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,165 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.channels; - -import java.net.SocketAddress; - -import java.nio.channels.Channel; - -import java.util.Set; -import java.io.IOException; - -import org.classpath.icedtea.java.net.SocketOption; - -/** - * A channel to a network socket. - * - * <p> A channel that implements this interface is a channel to a network - * socket. The {@link #bind(SocketAddress) bind} method is used to bind the - * socket to a local {@link SocketAddress address}, the {@link #getLocalAddress() - * getLocalAddress} method returns the address that the socket is bound to, and - * the {@link #setOption(SocketOption,Object) setOption} and {@link - * #getOption(SocketOption) getOption} methods are used to set and query socket - * options. An implementation of this interface should specify the socket options - * that it supports. - * - * <p> The {@link #bind bind} and {@link #setOption setOption} methods that do - * not otherwise have a value to return are specified to return the network - * channel upon which they are invoked. This allows method invocations to be - * chained. Implementations of this interface should specialize the return type - * so that method invocations on the implementation class can be chained. - * - * @since 1.7 - */ - -public interface NetworkChannel - extends Channel -{ - /** - * Binds the channel's socket to a local address. - * - * <p> This method is used to establish an association between the socket and - * a local address. Once an association is established then the socket remains - * bound until the channel is closed. If the {@code local} parameter has the - * value {@code null} then the socket will be bound to an address that is - * assigned automatically. - * - * @param local - * The address to bind the socket, or {@code null} to bind the socket - * to an automatically assigned socket address - * - * @return This channel - * - * @throws AlreadyBoundException - * If the socket is already bound - * @throws UnsupportedAddressTypeException - * If the type of the given address is not supported - * @throws ClosedChannelException - * If the channel is closed - * @throws IOException - * If some other I/O error occurs - * @throws SecurityException - * If a security manager is installed and it denies an unspecified - * permission. An implementation of this interface should specify - * any required permissions. - * - * @see #getLocalAddress - */ - NetworkChannel bind(SocketAddress local) throws IOException; - - /** - * Returns the socket address that this channel's socket is bound to, or - * {@code null} if the socket is not bound. - * - * <p> Where the channel is {@link #bind bound} to an Internet Protocol - * socket address then the return value from this method is of type {@link - * java.net.InetSocketAddress}. - * - * @return The socket address that the socket is bound to, or {@code null} - * if the channel's socket is not bound - * - * @throws ClosedChannelException - * If the channel is closed - * @throws IOException - * If an I/O error occurs - */ - SocketAddress getLocalAddress() throws IOException; - - /** - * Sets the value of a socket option. - * - * @param name - * The socket option - * @param value - * The value of the socket option. A value of {@code null} may be - * a valid value for some socket options. - * - * @return This channel - * - * @throws UnsupportedOperationException - * If the socket option is not supported by this channel - * @throws IllegalArgumentException - * If the value is not a valid value for this socket option - * @throws ClosedChannelException - * If this channel is closed - * @throws IOException - * If an I/O error occurs - * - * @see java.net.StandardSocketOption - */ - <T> NetworkChannel setOption(SocketOption<T> name, T value) throws IOException; - - /** - * Returns the value of a socket option. - * - * @param name - * The socket option - * - * @return The value of the socket option. A value of {@code null} may be - * a valid value for some socket options. - * - * @throws UnsupportedOperationException - * If the socket option is not supported by this channel - * @throws ClosedChannelException - * If this channel is closed - * @throws IOException - * If an I/O error occurs - * - * @see java.net.StandardSocketOption - */ - <T> T getOption(SocketOption<T> name) throws IOException; - - /** - * Returns a set of the socket options supported by this channel. - * - * <p> This method will continue to return the set of options even after the - * channel has been closed. - * - * @return A set of the socket options supported by this channel - */ - Set<SocketOption<?>> supportedOptions(); -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/SeekableByteChannel.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,170 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.channels; - -import java.nio.ByteBuffer; -import java.nio.channels.ByteChannel; -import java.io.IOException; - -/** - * A byte channel that maintains a current <i>position</i> and allows the - * position to be changed. - * - * <p> A seekable byte channel is connected to an entity, typically a file, - * that contains a variable-length sequence of bytes that can be read and - * written. The current position can be {@link #position() <i>queried</i>} and - * {@link #position(long) <i>modified</i>}. The channel also provides access to - * the current <i>size</i> of the entity to which the channel is connected. The - * size increases when bytes are written beyond its current size; the size - * decreases when it is {@link #truncate <i>truncated</i>}. - * - * <p> The {@link #position(long) position} and {@link #truncate truncate} methods - * which do not otherwise have a value to return are specified to return the - * channel upon which they are invoked. This allows method invocations to be - * chained. Implementations of this interface should specialize the return type - * so that method invocations on the implementation class can be chained. - * - * @since 1.7 - * @see java.nio.file.FileRef#newByteChannel - */ - -public interface SeekableByteChannel - extends ByteChannel -{ - /** - * Reads a sequence of bytes from this channel into the given buffer. - * - * <p> Bytes are read starting at this channel's current position, and - * then the position is updated with the number of bytes actually read. - * Otherwise this method behaves exactly as specified in the {@link - * ReadableByteChannel} interface. - */ - - int read(ByteBuffer dst) throws IOException; - - /** - * Writes a sequence of bytes to this channel from the given buffer. - * - * <p> Bytes are written starting at this channel's current position, unless - * the channel is connected to an entity such as a file that is opened with - * the {@link java.nio.file.StandardOpenOption#APPEND APPEND} option, in - * which case the position is first advanced to the end. The entity to which - * the channel is connected is grown, if necessary, to accommodate the - * written bytes, and then the position is updated with the number of bytes - * actually written. Otherwise this method behaves exactly as specified by - * the {@link WritableByteChannel} interface. - */ - - int write(ByteBuffer src) throws IOException; - - /** - * Returns this channel's position. - * - * @return This channel's position, - * a non-negative integer counting the number of bytes - * from the beginning of the entity to the current position - * - * @throws ClosedChannelException - * If this channel is closed - * @throws IOException - * If some other I/O error occurs - */ - long position() throws IOException; - - /** - * Sets this channel's position. - * - * <p> Setting the position to a value that is greater than the current size - * is legal but does not change the size of the entity. A later attempt to - * read bytes at such a position will immediately return an end-of-file - * indication. A later attempt to write bytes at such a position will cause - * the entity to grow to accommodate the new bytes; the values of any bytes - * between the previous end-of-file and the newly-written bytes are - * unspecified. - * - * <p> Setting the channel's position is not recommended when connected to - * an entity, typically a file, that is opened with the {@link - * java.nio.file.StandardOpenOption#APPEND APPEND} option. When opened for - * append, the position is first advanced to the end before writing. - * - * @param newPosition - * The new position, a non-negative integer counting - * the number of bytes from the beginning of the entity - * - * @return This channel - * - * @throws ClosedChannelException - * If this channel is closed - * @throws IllegalArgumentException - * If the new position is negative - * @throws IOException - * If some other I/O error occurs - */ - SeekableByteChannel positionSBC(long newPosition) throws IOException; - - /** - * Returns the current size of entity to which this channel is connected. - * - * @return The current size, measured in bytes - * - * @throws ClosedChannelException - * If this channel is closed - * @throws IOException - * If some other I/O error occurs - */ - long size() throws IOException; - - /** - * Truncates the entity, to which this channel is connected, to the given - * size. - * - * <p> If the given size is less than the current size then the entity is - * truncated, discarding any bytes beyond the new end. If the given size is - * greater than or equal to the current size then the entity is not modified. - * In either case, if the current position is greater than the given size - * then it is set to that size. - * - * <p> An implementation of this interface may prohibit truncation when - * connected to an entity, typically a file, opened with the {@link - * java.nio.file.StandardOpenOption#APPEND APPEND} option. - * - * @param size - * The new size, a non-negative byte count - * - * @return This channel - * - * @throws NonWritableChannelException - * If this channel was not opened for writing - * @throws ClosedChannelException - * If this channel is closed - * @throws IllegalArgumentException - * If the new size is negative - * @throws IOException - * If some other I/O error occurs - */ - SeekableByteChannel truncateSBC(long size) throws IOException; -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/exceptions Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,68 +0,0 @@ -# -# Copyright 2000-2008 Sun Microsystems, Inc. All Rights Reserved. -# 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. Sun designates this -# particular file as subject to the "Classpath" exception as provided -# by Sun in the LICENSE file that accompanied this code. -# -# 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. -# -# Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, -# CA 95054 USA or visit www.sun.com if you need additional information or -# have any questions. -# - -# Generated exception classes for java.nio.channels - -PACKAGE=org.classpath.icedtea.java.nio.channels -# This year should only change if the generated source is modified. -COPYRIGHT_YEARS=2000-2007 -SINCE=1.7 - -SUPER=java.io.IOException - -gen InterruptedByTimeoutException " - * Checked exception received by a thread when a timeout elapses before an - * asynchronous operation completes." \ - -4268008601014042947L - -SUPER=IllegalArgumentException - -gen IllegalChannelGroupException " - * Unchecked exception thrown when an attempt is made to open a channel - * in a group that was not created by the same provider. " \ - -2495041211157744253L - -SUPER=IllegalStateException - -gen AcceptPendingException " - * Unchecked exception thrown when an attempt is made to initiate an accept - * operation on a channel and a previous accept operation has not completed." \ - 2721339977965416421L - -gen ReadPendingException " - * Unchecked exception thrown when an attempt is made to read from an - * asynchronous socket channel and a previous read has not completed." \ - 1986315242191227217L - -gen WritePendingException " - * Unchecked exception thrown when an attempt is made to write to an - * asynchronous socket channel and a previous write has not completed." \ - 7031871839266032276L - -gen ShutdownChannelGroupException " - * Unchecked exception thrown when an attempt is made to construct a channel in - * a group that is shutdown or the completion handler for an I/O operation - * cannot be invoked because the channel group is shutdown." \ - -3903801676350154157L
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/package-info.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,293 +0,0 @@ -/* - * Copyright 2001-2008 Sun Microsystems, Inc. All Rights Reserved. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -/** - * Defines channels, which represent connections to entities that are capable of - * performing I/O operations, such as files and sockets; defines selectors, for - * multiplexed, non-blocking I/O operations. - * - * <a name="channels"></a> - * - * <blockquote><table cellspacing=1 cellpadding=0 summary="Lists channels and their descriptions"> - * <tr><th><p align="left">Channels</p></th><th><p align="left">Description</p></th></tr> - * <tr><td valign=top><tt><i>{@link java.nio.channels.Channel}</i></tt></td> - * <td>A nexus for I/O operations</td></tr> - * <tr><td valign=top><tt> <i>{@link java.nio.channels.ReadableByteChannel}</i></tt></td> - * <td>Can read into a buffer</td></tr> - * <tr><td valign=top><tt> <i>{@link java.nio.channels.ScatteringByteChannel} </i></tt></td> - * <td>Can read into a sequence of buffers</td></tr> - * <tr><td valign=top><tt> <i>{@link java.nio.channels.WritableByteChannel}</i></tt></td> - * <td>Can write from a buffer</td></tr> - * <tr><td valign=top><tt> <i>{@link java.nio.channels.GatheringByteChannel}</i></tt></td> - * <td>Can write from a sequence of buffers</td></tr> - * <tr><td valign=top><tt> <i>{@link java.nio.channels.ByteChannel}</i></tt></td> - * <td>Can read/write to/from a buffer</td></tr> - * <tr><td valign=top><tt> <i>{@link java.nio.channels.SeekableByteChannel}</i></tt></td> - * <td>A {@code ByteChannel} connected to an entity that contains a variable-length sequence of bytes</td></tr> - * <tr><td valign=top><tt> <i>{@link java.nio.channels.AsynchronousChannel}</i></tt></td> - * <td>Supports asynchronous I/O operations.</td></tr> - * <tr><td valign=top><tt> <i>{@link java.nio.channels.AsynchronousByteChannel}</i></tt></td> - * <td>Can read and write bytes asynchronously</td></tr> - * <tr><td valign=top><tt> <i>{@link java.nio.channels.NetworkChannel}</i></tt></td> - * <td>A channel to a network socket</td></tr> - * <tr><td valign=top><tt> <i>{@link java.nio.channels.MulticastChannel}</i></tt></td> - * <td>Can join Internet Protocol (IP) multicast groups</td></tr> - * <tr><td valign=top><tt>{@link org.classpath.icedtea.java.nio.channels.Channels}</tt></td> - * <td>Utility methods for channel/stream interoperation</td></tr> - * </table></blockquote> - * - * <p> A <i>channel</i> represents an open connection to an entity such as a - * hardware device, a file, a network socket, or a program component that is - * capable of performing one or more distinct I/O operations, for example reading - * or writing. As specified in the {@link java.nio.channels.Channel} interface, - * channels are either open or closed, and they are both <i>asynchronously - * closeable</i> and <i>interruptible</i>. - * - * <p> The {@link java.nio.channels.Channel} interface is extended by several - * other interfaces. - * - * <p> The {@link java.nio.channels.ReadableByteChannel} interface specifies a - * {@link java.nio.channels.ReadableByteChannel#read read} method that reads bytes - * from the channel into a buffer; similarly, the {@link - * java.nio.channels.WritableByteChannel} interface specifies a {@link - * java.nio.channels.WritableByteChannel#write write} method that writes bytes - * from a buffer to the channel. The {@link java.nio.channels.ByteChannel} - * interface unifies these two interfaces for the common case of channels that can - * both read and write bytes. The {@link java.nio.channels.SeekableByteChannel} - * interface extends the {@code ByteChannel} interface with methods to {@link - * java.nio.channels.SeekableByteChannel#position() query} and {@link - * java.nio.channels.SeekableByteChannel#position(long) modify} the channel's - * current position, and its {@link java.nio.channels.SeekableByteChannel#size - * size}. - * - * <p> The {@link java.nio.channels.ScatteringByteChannel} and {@link - * java.nio.channels.GatheringByteChannel} interfaces extend the {@link - * java.nio.channels.ReadableByteChannel} and {@link - * java.nio.channels.WritableByteChannel} interfaces, respectively, adding {@link - * java.nio.channels.ScatteringByteChannel#read read} and {@link - * java.nio.channels.GatheringByteChannel#write write} methods that take a - * sequence of buffers rather than a single buffer. - * - * <p> The {@link java.nio.channels.NetworkChannel} interface specifies methods - * to {@link java.nio.channels.NetworkChannel#bind bind} the channel's socket, - * obtain the address to which the socket is bound, and methods to {@link - * java.nio.channels.NetworkChannel#getOption get} and {@link - * java.nio.channels.NetworkChannel#setOption set} socket options. The {@link - * java.nio.channels.MulticastChannel} interface specifies methods to join - * Internet Protocol (IP) multicast groups. - * - * <p> The {@link org.classpath.icedtea.java.nio.channels.Channels} utility class defines static methods - * that support the interoperation of the stream classes of the <tt>{@link - * java.io}</tt> package with the channel classes of this package. An appropriate - * channel can be constructed from an {@link java.io.InputStream} or an {@link - * java.io.OutputStream}, and conversely an {@link java.io.InputStream} or an - * {@link java.io.OutputStream} can be constructed from a channel. A {@link - * java.io.Reader} can be constructed that uses a given charset to decode bytes - * from a given readable byte channel, and conversely a {@link java.io.Writer} can - * be constructed that uses a given charset to encode characters into bytes and - * write them to a given writable byte channel. - * - * <blockquote><table cellspacing=1 cellpadding=0 summary="Lists file channels and their descriptions"> - * <tr><th><p align="left">File channels</p></th><th><p align="left">Description</p></th></tr> - * <tr><td valign=top><tt>{@link org.classpath.icedtea.java.nio.channels.FileChannel}</tt></td> - * <td>Reads, writes, maps, and manipulates files</td></tr> - * <tr><td valign=top><tt>{@link org.classpath.icedtea.java.nio.channels.FileLock}</tt></td> - * <td>A lock on a (region of a) file</td></tr> - * <tr><td valign=top><tt>{@link java.nio.MappedByteBuffer}/{@link java.nio.MappedBigByteBuffer} </tt></td> - * <td>A direct byte buffer or big byte buffer mapped to a region of a file</td></tr> - * </table></blockquote> - * - * <p> The {@link org.classpath.icedtea.java.nio.channels.FileChannel} class supports the usual - * operations of reading bytes from, and writing bytes to, a channel connected to - * a file, as well as those of querying and modifying the current file position - * and truncating the file to a specific size. It defines methods for acquiring - * locks on the whole file or on a specific region of a file; these methods return - * instances of the {@link org.classpath.icedtea.java.nio.channels.FileLock} class. Finally, it defines - * methods for forcing updates to the file to be written to the storage device that - * contains it, for efficiently transferring bytes between the file and other - * channels, and for mapping a region of the file directly into memory. - * - * <p> A {@code FileChannel} is created by invoking one of its static {@link - * java.nio.channels.FileChannel#open open} methods, or by invoking the {@code - * getChannel} method of a {@link java.io.FileInputStream}, {@link - * java.io.FileOutputStream}, or {@link java.io.RandomAccessFile} to return a - * file channel connected to the same underlying file as the <tt>{@link java.io}</tt> - * class. - * - * <a name="multiplex"></a> - * <blockquote><table cellspacing=1 cellpadding=0 summary="Lists multiplexed, non-blocking channels and their descriptions"> - * <tr><th><p align="left">Multiplexed, non-blocking I/O</p></th><th><p align="left">Description</p></th></tr> - * <tr><td valign=top><tt>{@link java.nio.channels.SelectableChannel}</tt></td> - * <td>A channel that can be multiplexed</td></tr> - * <tr><td valign=top><tt> {@link java.nio.channels.DatagramChannel}</tt></td> - * <td>A channel to a datagram-oriented socket</td></tr> - * <tr><td valign=top><tt> {@link java.nio.channels.Pipe.SinkChannel}</tt></td> - * <td>The write end of a pipe</td></tr> - * <tr><td valign=top><tt> {@link java.nio.channels.Pipe.SourceChannel}</tt></td> - * <td>The read end of a pipe</td></tr> - * <tr><td valign=top><tt> {@link java.nio.channels.ServerSocketChannel} </tt></td> - * <td>A channel to a stream-oriented listening socket</td></tr> - * <tr><td valign=top><tt> {@link java.nio.channels.SocketChannel}</tt></td> - * <td>A channel for a stream-oriented connecting socket</td></tr> - * <tr><td valign=top><tt>{@link java.nio.channels.Selector}</tt></td> - * <td>A multiplexor of selectable channels</td></tr> - * <tr><td valign=top><tt>{@link java.nio.channels.SelectionKey}</tt></td> - * <td>A token representing the registration <br> of a channel - * with a selector</td></tr> - * <tr><td valign=top><tt>{@link java.nio.channels.Pipe}</tt></td> - * <td>Two channels that form a unidirectional pipe</td></tr> - * </table></blockquote> - * - * <p> Multiplexed, non-blocking I/O, which is much more scalable than - * thread-oriented, blocking I/O, is provided by <i>selectors</i>, <i>selectable - * channels</i>, and <i>selection keys</i>. - * - * <p> A <a href="Selector.html"><i>selector</i></a> is a multiplexor of <a - * href="SelectableChannel.html"><i>selectable channels</i></a>, which in turn are - * a special type of channel that can be put into <a - * href="SelectableChannel.html#bm"><i>non-blocking mode</i></a>. To perform - * multiplexed I/O operations, one or more selectable channels are first created, - * put into non-blocking mode, and {@link - * java.nio.channels.SelectableChannel#register <i>registered</i>} - * with a selector. Registering a channel specifies the set of I/O operations - * that will be tested for readiness by the selector, and returns a <a - * href="SelectionKey.html"><i>selection key</i></a> that represents the - * registration. - * - * <p> Once some channels have been registered with a selector, a <a - * href="Selector.html#selop"><i>selection operation</i></a> can be performed in - * order to discover which channels, if any, have become ready to perform one or - * more of the operations in which interest was previously declared. If a channel - * is ready then the key returned when it was registered will be added to the - * selector's <i>selected-key set</i>. The key set, and the keys within it, can - * be examined in order to determine the operations for which each channel is - * ready. From each key one can retrieve the corresponding channel in order to - * perform whatever I/O operations are required. - * - * <p> That a selection key indicates that its channel is ready for some operation - * is a hint, but not a guarantee, that such an operation can be performed by a - * thread without causing the thread to block. It is imperative that code that - * performs multiplexed I/O be written so as to ignore these hints when they prove - * to be incorrect. - * - * <p> This package defines selectable-channel classes corresponding to the {@link - * java.net.DatagramSocket}, {@link java.net.ServerSocket}, and {@link - * java.net.Socket} classes defined in the <tt>{@link java.net}</tt> package. - * Minor changes to these classes have been made in order to support sockets that - * are associated with channels. This package also defines a simple class that - * implements unidirectional pipes. In all cases, a new selectable channel is - * created by invoking the static <tt>open</tt> method of the corresponding class. - * If a channel needs an associated socket then a socket will be created as a side - * effect of this operation. - * - * <p> The implementation of selectors, selectable channels, and selection keys - * can be replaced by "plugging in" an alternative definition or instance of the - * {@link java.nio.channels.spi.SelectorProvider} class defined in the <tt>{@link - * java.nio.channels.spi}</tt> package. It is not expected that many developers - * will actually make use of this facility; it is provided primarily so that - * sophisticated users can take advantage of operating-system-specific - * I/O-multiplexing mechanisms when very high performance is required. - * - * <p> Much of the bookkeeping and synchronization required to implement the - * multiplexed-I/O abstractions is performed by the {@link - * java.nio.channels.spi.AbstractInterruptibleChannel}, {@link - * java.nio.channels.spi.AbstractSelectableChannel}, {@link - * java.nio.channels.spi.AbstractSelectionKey}, and {@link - * java.nio.channels.spi.AbstractSelector} classes in the <tt>{@link - * java.nio.channels.spi}</tt> package. When defining a custom selector provider, - * only the {@link java.nio.channels.spi.AbstractSelector} and {@link - * java.nio.channels.spi.AbstractSelectionKey} classes should be subclassed - * directly; custom channel classes should extend the appropriate {@link - * java.nio.channels.SelectableChannel} subclasses defined in this package. - * - * <a name="async"></a> - * - * <blockquote><table cellspacing=1 cellpadding=0 summary="Lists asynchronous channels and their descriptions"> - * <tr><th><p align="left">Asynchronous I/O</p></th><th><p align="left">Description</p></th></tr> - * <tr><td valign=top><tt>{@link org.classpath.icedtea.java.nio.channels.AsynchronousFileChannel}</tt></td> - * <td>An asynchronous channel for reading, writing, and manipulating a file</td></tr> - * <tr><td valign=top><tt>{@link org.classpath.icedtea.java.nio.channels.AsynchronousSocketChannel}</tt></td> - * <td>An asynchronous channel to a stream-oriented connecting socket</td></tr> - * <tr><td valign=top><tt>{@link org.classpath.icedtea.java.nio.channels.AsynchronousServerSocketChannel} </tt></td> - * <td>An asynchronous channel to a stream-oriented listening socket</td></tr> - * <tr><td valign=top><tt>{@link org.classpath.icedtea.java.nio.channels.AsynchronousDatagramChannel}</tt></td> - * <td>An asynchronous channel to a datagram-oriented socket</td></tr> - * <tr><td valign=top><tt>{@link org.classpath.icedtea.java.nio.channels.CompletionHandler}</tt></td> - * <td>A handler for consuming the result of an asynchronous operation</td></tr> - * <tr><td valign=top><tt>{@link org.classpath.icedtea.java.nio.channels.AsynchronousChannelGroup}</tt></td> - * <td>A grouping of asynchronous channels for the purpose of resource sharing</td></tr> - * </table></blockquote> - * - * <p> {@link org.classpath.icedtea.java.nio.channels.AsynchronousChannel Asynchronous channels} are a - * special type of channel capable of asynchronous I/O operations. Asynchronous - * channels are non-blocking and define methods to initiate asynchronous - * operations, returning a {@link java.util.concurrent.Future} representing the - * pending result of each operation. The {@code Future} can be used to poll or - * wait for the result of the operation. Asynchronous I/O operations can also - * specify a {@link org.classpath.icedtea.java.nio.channels.CompletionHandler} to invoke when the - * operation completes. A completion handler is user provided code that is executed - * to consume the result of I/O operation. - * - * <p> This package defines asynchronous-channel classes that are connected to - * a stream-oriented connecting or listening socket, or a datagram-oriented socket. - * It also defines the {@link org.classpath.icedtea.java.nio.channels.AsynchronousFileChannel} class - * for asynchronous reading, writing, and manipulating a file. As with the {@link - * org.classpath.icedtea.java.nio.channels.FileChannel} it supports operations to truncate the file - * to a specific size, force updates to the file to be written to the storage - * device, or acquire locks on the whole file or on a specific region of the file. - * Unlike the {@code FileChannel} it does not define methods for mapping a - * region of the file directly into memory. Where memory mapped I/O is required, - * then a {@code FileChannel} can be used. - * - * <p> Asynchronous channels are bound to an asynchronous channel group for the - * purpose of resource sharing. A group has an associated {@link - * java.util.concurrent.ExecutorService} to which tasks are submitted to handle - * I/O events and dispatch to completion handlers that consume the result of - * asynchronous operations performed on channels in the group. The group can - * optionally be specified when creating the channel or the channel can be bound - * to a <em>default group</em>. Sophisticated users may wish to create their - * own asynchronous channel groups or configure the {@code ExecutorService} - * that will be used for the default group. - * - * <p> As with selectors, the implementatin of asynchronous channels can be - * replaced by "plugging in" an alternative definition or instance of the {@link - * java.nio.channels.spi.AsynchronousChannelProvider} class defined in the - * <tt>{@link java.nio.channels.spi}</tt> package. It is not expected that many - * developers will actually make use of this facility; it is provided primarily - * so that sophisticated users can take advantage of operating-system-specific - * asynchronous I/O mechanisms when very high performance is required. - * - * <hr width="80%"> - * <p> Unless otherwise noted, passing a <tt>null</tt> argument to a constructor - * or method in any class or interface in this package will cause a {@link - * java.lang.NullPointerException NullPointerException} to be thrown. - * - * @since 1.4 - * @updated 1.7 - * @author Mark Reinhold - * @author JSR-51 Expert Group - */ - -package org.classpath.icedtea.java.nio.channels;
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/spi/AsynchronousChannelProvider.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,284 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.channels.spi; - -import java.nio.channels.*; -import java.io.IOException; -import java.util.Iterator; -import java.util.ServiceLoader; -import java.util.ServiceConfigurationError; -import java.util.concurrent.*; -import java.security.AccessController; -import java.security.PrivilegedAction; - -import org.classpath.icedtea.java.net.ProtocolFamily; - -import org.classpath.icedtea.java.nio.channels.AsynchronousChannelGroup; -import org.classpath.icedtea.java.nio.channels.AsynchronousDatagramChannel; -import org.classpath.icedtea.java.nio.channels.AsynchronousServerSocketChannel; -import org.classpath.icedtea.java.nio.channels.AsynchronousSocketChannel; - -/** - * Service-provider class for asynchronous channels. - * - * <p> An asynchronous channel provider is a concrete subclass of this class that - * has a zero-argument constructor and implements the abstract methods specified - * below. A given invocation of the Java virtual machine maintains a single - * system-wide default provider instance, which is returned by the {@link - * #provider() provider} method. The first invocation of that method will locate - * the default provider as specified below. - * - * <p> All of the methods in this class are safe for use by multiple concurrent - * threads. </p> - * - * @since 1.7 - */ - -public abstract class AsynchronousChannelProvider { - - private static final Object lock = new Object(); - private static AsynchronousChannelProvider provider = null; - - private static Void checkPermission() { - SecurityManager sm = System.getSecurityManager(); - if (sm != null) - sm.checkPermission(new RuntimePermission("asynchronousChannelProvider")); - return null; - } - private AsynchronousChannelProvider(Void ignore) { } - - /** - * Initializes a new instance of this class. - * - * @throws SecurityException - * If a security manager has been installed and it denies - * {@link RuntimePermission}<tt>("asynchronousChannelProvider")</tt> - */ - protected AsynchronousChannelProvider() { - this(checkPermission()); - } - - private static boolean loadProviderFromProperty() { - String cn = System.getProperty("org.classpath.icedtea.java.nio.channels.spi.AsynchronousChannelProvider"); - if (cn == null) - return false; - try { - Class<?> c = Class.forName(cn, true, - ClassLoader.getSystemClassLoader()); - provider = (AsynchronousChannelProvider)c.newInstance(); - return true; - } catch (ClassNotFoundException x) { - throw new ServiceConfigurationError(null, x); - } catch (IllegalAccessException x) { - throw new ServiceConfigurationError(null, x); - } catch (InstantiationException x) { - throw new ServiceConfigurationError(null, x); - } catch (SecurityException x) { - throw new ServiceConfigurationError(null, x); - } - } - - private static boolean loadProviderAsService() { - - ServiceLoader<AsynchronousChannelProvider> sl = - ServiceLoader.load(AsynchronousChannelProvider.class, - ClassLoader.getSystemClassLoader()); - Iterator<AsynchronousChannelProvider> i = sl.iterator(); - for (;;) { - try { - if (!i.hasNext()) - return false; - provider = i.next(); - return true; - } catch (ServiceConfigurationError sce) { - if (sce.getCause() instanceof SecurityException) { - // Ignore the security exception, try the next provider - continue; - } - throw sce; - } - } - } - - /** - * Returns the system-wide default asynchronous channel provider for this - * invocation of the Java virtual machine. - * - * <p> The first invocation of this method locates the default provider - * object as follows: </p> - * - * <ol> - * - * <li><p> If the system property - * <tt>java.nio.channels.spi.AsynchronousChannelProvider</tt> is defined - * then it is taken to be the fully-qualified name of a concrete provider class. - * The class is loaded and instantiated; if this process fails then an - * unspecified error is thrown. </p></li> - * - * <li><p> If a provider class has been installed in a jar file that is - * visible to the system class loader, and that jar file contains a - * provider-configuration file named - * <tt>java.nio.channels.spi.AsynchronousChannelProvider</tt> in the resource - * directory <tt>META-INF/services</tt>, then the first class name - * specified in that file is taken. The class is loaded and - * instantiated; if this process fails then an unspecified error is - * thrown. </p></li> - * - * <li><p> Finally, if no provider has been specified by any of the above - * means then the system-default provider class is instantiated and the - * result is returned. </p></li> - * - * </ol> - * - * <p> Subsequent invocations of this method return the provider that was - * returned by the first invocation. </p> - * - * @return The system-wide default AsynchronousChannel provider - */ - public static AsynchronousChannelProvider provider() { - synchronized (lock) { - if (provider != null) { - return provider; - } - return AccessController - .doPrivileged(new PrivilegedAction<AsynchronousChannelProvider>() { - public AsynchronousChannelProvider run() { - if (loadProviderFromProperty()) - return provider; - if (loadProviderAsService()) - return provider; - provider = sun.nio.ch.DefaultAsynchronousChannelProvider.create(); - return provider; - } - }); - } - } - - /** - * The types of thread pool that an asynchronous channel group can be - * constructed with. - * - * @since 1.7 - */ - public static enum ThreadPoolType { - /** - * Fixed thread pool. - * - * @see Executors#newFixedThreadPool - */ - FIXED, - /** - * Cached thread pool. - * - * @see Executors#newCachedThreadPool - */ - CACHED; - } - - /** - * Constructs a new asynchronous channel group. - * - * @param poolType - * The type of thread pool - * @param executor - * The thread pool - * @param nThreads - * The number of threads or initial size, depending on the thread - * pool type. - * - * @throws IllegalArgumentException - * If the {@code nThreads} parameter is invalid for the thread - * pool type - * @throws IOException - * If an I/O error occurs - */ - public AsynchronousChannelGroup openAsynchronousChannelGroup - (ThreadPoolType poolType, ExecutorService executor, int nThreads) throws IOException - { - return null; - } - - /** - * Opens an asynchronous server-socket channel. - * - * @param group - * The group to which the channel is bound, or {@code null} to - * bind to the default group - * - * @return The new channel - * - * @throws IllegalChannelGroupException - * If the provider that created the group differs from this provider - * @throws ShutdownChannelGroupException - * The group is shutdown - * @throws IOException - * If an I/O error occurs - */ - public abstract AsynchronousServerSocketChannel openAsynchronousServerSocketChannel - (AsynchronousChannelGroup group) throws IOException; - - /** - * Opens an asynchronous socket channel. - * - * @param group - * The group to which the channel is bound, or {@code null} to - * bind to the default group - * - * @return The new channel - * - * @throws IllegalChannelGroupException - * If the provider that created the group differs from this provider - * @throws ShutdownChannelGroupException - * The group is shutdown - * @throws IOException - * If an I/O error occurs - */ - public abstract AsynchronousSocketChannel openAsynchronousSocketChannel - (AsynchronousChannelGroup group) throws IOException; - - /** - * Opens an asynchronous datagram channel. - * - * @param family - * The protocol family, or {@code null} for the default protocol - * family - * @param group - * The group to which the channel is bound, or {@code null} to - * bind to the default group - * - * @return The new channel - * - * @throws IllegalChannelGroupException - * If the provider that created the group differs from this provider - * @throws ShutdownChannelGroupException - * The group is shutdown - * @throws IOException - * If an I/O error occurs - */ - public abstract AsynchronousDatagramChannel openAsynchronousDatagramChannel - (ProtocolFamily family, AsynchronousChannelGroup group) throws IOException; -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/spi/SelectorProvider.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,199 +0,0 @@ -/* - * Copyright 2000-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.channels.spi; - -import java.io.IOException; - -import java.security.AccessController; -import java.security.PrivilegedAction; - -import java.util.Iterator; -import java.util.ServiceLoader; -import java.util.ServiceConfigurationError; - -import org.classpath.icedtea.java.net.ProtocolFamily; - -import org.classpath.icedtea.java.nio.channels.DatagramChannel; - -/** - * Service-provider class for selectors and selectable channels. - * - * <p> A selector provider is a concrete subclass of this class that has a - * zero-argument constructor and implements the abstract methods specified - * below. A given invocation of the Java virtual machine maintains a single - * system-wide default provider instance, which is returned by the {@link - * #provider() provider} method. The first invocation of that method will locate - * the default provider as specified below. - * - * <p> The system-wide default provider is used by the static <tt>open</tt> - * methods of the {@link java.nio.channels.DatagramChannel#open - * DatagramChannel}, {@link java.nio.channels.Pipe#open Pipe}, {@link - * java.nio.channels.Selector#open Selector}, {@link - * java.nio.channels.ServerSocketChannel#open ServerSocketChannel}, and {@link - * java.nio.channels.SocketChannel#open SocketChannel} classes. It is also - * used by the {@link java.lang.System#inheritedChannel System.inheritedChannel()} - * method. A program may make use of a provider other than the default provider - * by instantiating that provider and then directly invoking the <tt>open</tt> - * methods defined in this class. - * - * <p> All of the methods in this class are safe for use by multiple concurrent - * threads. </p> - * - * - * @author Mark Reinhold - * @author JSR-51 Expert Group - * @since 1.4 - */ - -public abstract class SelectorProvider - extends java.nio.channels.spi.SelectorProvider { - - private static final Object lock = new Object(); - private static SelectorProvider provider = null; - - /** - * Opens a datagram channel. </p> - * - * @return The new channel - */ - public abstract DatagramChannel openDatagramChannel() - throws IOException; - - /** - * {@note new} - * Opens a datagram channel. - * - * @param family - * The protocol family - * - * @return A new datagram channel - * - * @throws UnsupportedOperationException - * If the specified protocol family is not supported - * @throws IOException - * If an I/O error occurs - * - * @since 1.7 - */ - public abstract DatagramChannel openDatagramChannel(ProtocolFamily family) - throws IOException; - - /** - * Returns the system-wide default selector provider for this invocation of - * the Java virtual machine. - * - * <p> The first invocation of this method locates the default provider - * object as follows: </p> - * - * <ol> - * - * <li><p> If the system property - * <tt>java.nio.channels.spi.SelectorProvider</tt> is defined then it is - * taken to be the fully-qualified name of a concrete provider class. - * The class is loaded and instantiated; if this process fails then an - * unspecified error is thrown. </p></li> - * - * <li><p> If a provider class has been installed in a jar file that is - * visible to the system class loader, and that jar file contains a - * provider-configuration file named - * <tt>java.nio.channels.spi.SelectorProvider</tt> in the resource - * directory <tt>META-INF/services</tt>, then the first class name - * specified in that file is taken. The class is loaded and - * instantiated; if this process fails then an unspecified error is - * thrown. </p></li> - * - * <li><p> Finally, if no provider has been specified by any of the above - * means then the system-default provider class is instantiated and the - * result is returned. </p></li> - * - * </ol> - * - * <p> Subsequent invocations of this method return the provider that was - * returned by the first invocation. </p> - * - * @return The system-wide default selector provider - */ - public static SelectorProvider provider() { - synchronized (lock) { - if (provider != null) - return provider; - return AccessController - .doPrivileged(new PrivilegedAction<SelectorProvider>() { - public SelectorProvider run() { - if (loadProviderFromProperty()) - return provider; - if (loadProviderAsService()) - return provider; - provider = sun.nio.ch.DefaultSelectorProvider.create(); - return provider; - } - }); - } - } - - private static boolean loadProviderFromProperty() { - String cn = System.getProperty("org.classpath.icedtea.java.nio.channels.spi.SelectorProvider"); - if (cn == null) - return false; - try { - Class<?> c = Class.forName(cn, true, - ClassLoader.getSystemClassLoader()); - provider = (SelectorProvider)c.newInstance(); - return true; - } catch (ClassNotFoundException x) { - throw new ServiceConfigurationError(null, x); - } catch (IllegalAccessException x) { - throw new ServiceConfigurationError(null, x); - } catch (InstantiationException x) { - throw new ServiceConfigurationError(null, x); - } catch (SecurityException x) { - throw new ServiceConfigurationError(null, x); - } - } - - private static boolean loadProviderAsService() { - - ServiceLoader<SelectorProvider> sl = - ServiceLoader.load(SelectorProvider.class, - ClassLoader.getSystemClassLoader()); - Iterator<SelectorProvider> i = sl.iterator(); - for (;;) { - try { - if (!i.hasNext()) - return false; - provider = i.next(); - return true; - } catch (ServiceConfigurationError sce) { - if (sce.getCause() instanceof SecurityException) { - // Ignore the security exception, try the next provider - continue; - } - throw sce; - } - } - } -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/channels/spi/package.html Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,46 +0,0 @@ -<!-- - Copyright 2000-2005 Sun Microsystems, Inc. All Rights Reserved. - Copyright 2009 Red Hat, Inc. - 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. Sun designates this - particular file as subject to the "Classpath" exception as provided - by Sun in the LICENSE file that accompanied this code. - - 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. - - Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - CA 95054 USA or visit www.sun.com if you need additional information or - have any questions. ---> - -<!doctype html public "-//IETF//DTD HTML//EN"> -<html> -<body bgcolor="white"> - -Service-provider classes for the <tt>{@link org.classpath.icedtea.java.nio.channels}</tt> package. - -<p> Only developers who are defining new asynchronous channel providers should need -to make direct use of this package. </p> - -<p> Unless otherwise noted, passing a <tt>null</tt> argument to a constructor -or method in any class or interface in this package will cause a {@link -java.lang.NullPointerException NullPointerException} to be thrown. - - -@since 1.7 -@author Mark Reinhold -@author JSR-51 Expert Group - -</body> -</html>
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/AccessDeniedException.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,69 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file; - -/** - * Checked exception thrown when a file system operation is denied, typically - * due to a file permission or other access check. - * - * <p> This exception is not related to the {@link - * java.security.AccessControlException AccessControlException} or {@link - * SecurityException} thrown by access controllers or security managers when - * access to a file is denied. - * - * @since 1.7 - */ - -public class AccessDeniedException - extends FileSystemException -{ - private static final long serialVersionUID = 4943049599949219617L; - - /** - * Constructs an instance of this class. - * - * @param file - * A string identifying the file or {@code null} if not known. - */ - public AccessDeniedException(String file) { - super(file); - } - - /** - * Constructs an instance of this class. - * - * @param file - * A string identifying the file or {@code null} if not known. - * @param other - * A string identifying the other file or {@code null} if not known. - * @param reason - * A reason message with additional information or {@code null} - */ - public AccessDeniedException(String file, String other, String reason) { - super(file, other, reason); - } -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/AccessMode.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,50 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file; - -/** - * Defines access modes used to test the accessibility of a file. - * - * @since 1.7 - * - * @see FileRef#checkAccess - */ - -public enum AccessMode { - /** - * Test read access. - */ - READ, - /** - * Test write access. - */ - WRITE, - /** - * Test execute access. - */ - EXECUTE; -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/AtomicMoveNotSupportedException.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,57 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file; - -/** - * Checked exception thrown when a file cannot be moved as an atomic file system - * operation. - * - * @since 1.7 - */ - -public class AtomicMoveNotSupportedException - extends FileSystemException -{ - static final long serialVersionUID = 5402760225333135579L; - - /** - * Constructs an instance of this class. - * - * @param source - * A string identifying the source file or {@code null} if not known. - * @param target - * A string identifying the target file or {@code null} if not known. - * @param reason - * A reason message with additional information - */ - public AtomicMoveNotSupportedException(String source, - String target, - String reason) - { - super(source, target, reason); - } -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/ClosedDirectoryStreamException.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,46 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file; - -/** - * Unchecked exception thrown when an attempt is made to invoke an operation on - * a directory stream that is closed. - * - * @since 1.7 - */ - -public class ClosedDirectoryStreamException - extends IllegalStateException -{ - static final long serialVersionUID = 4228386650900895400L; - - /** - * Constructs an instance of this class. - */ - public ClosedDirectoryStreamException() { - } -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/ClosedFileSystemException.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,44 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file; - -/** - * Unchecked exception thrown when an attempt is made to invoke an operation on - * a file and the file system is closed. - */ - -public class ClosedFileSystemException - extends IllegalStateException -{ - static final long serialVersionUID = -8158336077256193488L; - - /** - * Constructs an instance of this class. - */ - public ClosedFileSystemException() { - } -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/ClosedWatchServiceException.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,44 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file; - -/** - * Unchecked exception thrown when an attempt is made to invoke an operation on - * a watch service that is closed. - */ - -public class ClosedWatchServiceException - extends IllegalStateException -{ - static final long serialVersionUID = 1853336266231677732L; - - /** - * Constructs an instance of this class. - */ - public ClosedWatchServiceException() { - } -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/CopyOption.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,42 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file; - -/** - * An object that configures how to copy or move a file. - * - * <p> Objects of this type may be used with the {@link Path#copyTo copyTo} and - * {@link Path#moveTo moveTo} methods to configure how a file is copied or moved. - * - * <p> The {@link StandardCopyOption} enumeration type defines the - * <i>standard</i> options. - * - * @since 1.7 - */ - -public interface CopyOption { -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/DirectoryNotEmptyException.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,50 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file; - -/** - * Checked exception thrown when a file system operation fails because a - * directory is not empty. - * - * @since 1.7 - */ - -public class DirectoryNotEmptyException - extends FileSystemException -{ - static final long serialVersionUID = 3056667871802779003L; - - /** - * Constructs an instance of this class. - * - * @param dir - * A string identifying the directory or {@code null} if not known. - */ - public DirectoryNotEmptyException(String dir) { - super(dir); - } -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/DirectoryStream.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,139 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file; - -import java.util.Iterator; -import java.io.Closeable; - -/** - * An object to iterate over the entries in a directory. A directory stream - * allows for convenient use of the for-each construct: - * <pre> - * Path dir = ... - * DirectoryStream<Path> stream = dir.newDirectoryStream(); - * try { - * for (Path entry: stream) { - * .. - * } - * } finally { - * stream.close(); - * } - * </pre> - * - * <p><b> A {@code DirectoryStream} is not a general-purpose {@code Iterable}. - * While this interface extends {@code Iterable}, the {@code iterator} method - * may only be invoked once to obtain the iterator; a second, or subsequent, - * call to the {@code iterator} method throws {@code IllegalStateException}. </b> - * - * <p> A {@code DirectoryStream} is opened upon creation and is closed by - * invoking the {@link #close close} method. Closing the directory stream - * releases any resources associated with the stream. The {@link - * Files#withDirectory Files.withDirectory} utility method is useful for cases - * where a task is performed on entries in a directory. This method automatically - * closes the directory stream when iteration is complete (or an error occurs). - * Once a directory stream is closed, all further method invocations on the - * iterator throw {@link java.util.concurrent.ConcurrentModificationException} - * with cause {@link ClosedDirectoryStreamException}. - * - * <p> A directory stream is not required to be <i>asynchronously closeable</i>. - * If a thread is blocked on the directory stream's iterator, reading from the - * directory, and another thread invokes the {@code close} method then it may - * require to block until the read operation is complete. - * - * <p> The {@link Iterator#hasNext() hasNext} and {@link Iterator#next() next} - * methods can encounter an I/O error when iterating over the directory in which - * case {@code ConcurrentModificationException} is thrown with cause - * {@link java.io.IOException}. The {@code hasNext} method is guaranteed to - * read-ahead by at least one element. This means that if the {@code hasNext} - * method returns {@code true} and is followed by a call to the {@code next} - * method then it is guaranteed not to fail with a {@code - * ConcurrentModificationException}. - * - * <p> The elements returned by the iterator are in no specific order. Some file - * systems maintain special links to the directory itself and the directory's - * parent directory. Entries representing these links are not returned by the - * iterator. - * - * <p> The iterator's {@link Iterator#remove() remove} method removes the - * directory entry for the last element returned by the iterator, as if by - * invoking the {@link FileRef#delete delete} method. If an I/O error or - * security exception occurs then {@code ConcurrentModificationException} is - * thrown with the cause. - * - * <p> The iterator is <i>weakly consistent</i>. It is thread safe but does not - * freeze the directory while iterating, so it may (or may not) reflect updates - * to the directory that occur after the {@code DirectoryStream} is created. - * - * @param <T> The type of element returned by the iterator - * - * @since 1.7 - * - * @see Path#newDirectoryStream - */ - -public interface DirectoryStream<T> - extends Closeable, Iterable<T> -{ - /** - * An interface that is implemented by objects that decide if a directory - * entry should be accepted or filtered. A {@code Filter} is passed as the - * parameter to the {@link Path#newDirectoryStream(DirectoryStream.Filter) - * newDirectoryStream} method when opening a directory to iterate over the - * entries in the directory. - * - * <p> The {@link DirectoryStreamFilters} class defines factory methods to - * create filters for a number of common usages and also methods to combine - * filters. - * - * @param <T> The type of the directory entry - * - * @since 1.7 - */ - public static interface Filter<T> { - /** - * Decides if the given directory entry should be accept or filtered. - * - * @param entry - * The directory entry to be tested - * - * @return {@code true} if the directory entry should be accepted - */ - boolean accept(T entry); - } - - /** - * Returns the iterator associated with this {@code DirectoryStream}. - * - * @return The iterator associated with this {@code DirectoryStream} - * - * @throws IllegalStateException - * If this directory stream is closed or the iterator has already - * been returned - */ - - Iterator<T> iterator(); -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/DirectoryStreamFilters.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,211 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file; - -import java.io.IOException; -import java.io.IOError; -import sun.nio.fs.MimeType; - -/** - * This class consists exclusively of static methods that construct or combine - * filters. - * - * @since 1.7 - */ - -public final class DirectoryStreamFilters { - private DirectoryStreamFilters() { } - - /** - * Constructs a directory stream filter that filters directory entries by - * their <a href="http://www.ietf.org/rfc/rfc2045.txt">MIME</a> content - * type. The directory stream filter's {@link - * java.nio.file.DirectoryStream.Filter#accept accept} method returns {@code - * true} if the content type of the directory entry can be determined by - * invoking the {@link Files#probeContentType probeContentType} method, and - * the content type matches the given content type. - * - * <p> The {@code type} parameter is the value of a Multipurpose Internet - * Mail Extension (MIME) content type as defined by <a - * href="http://www.ietf.org/rfc/rfc2045.txt"><i>RFC 2045: Multipurpose - * Internet Mail Extensions (MIME) Part One: Format of Internet Message - * Bodies</i></a>. It is parsable according to the grammar in the RFC. Any - * space characters (<code>'\u0020'</code>) surrounding its components are - * ignored. The {@code type} parameter is parsed into its primary and subtype - * components which are used to match the primary and subtype components of - * each directory entry's content type. Parameters are not allowed. The - * primary type matches if it has value {@code '*'} or is equal to the - * primary type of the directory entry's content type without regard to - * case. The subtype matches if has the value {@code '*'} or is equal to the - * subtype of the directory entry's content type without regard to case. If - * both the primary and subtype match then the filter's {@code accept} method - * returns {@code true}. If the content type of a directory entry cannot be - * determined then the entry is filtered. - * - * <p> The {@code accept} method of the resulting directory stream filter - * throws {@link IOError} if the probing of the content type fails by - * throwing an {@link IOException}. Security exceptions are also propogated - * to the caller of the {@code accept} method. - * - * <p> <b>Usage Example:</b> - * Suppose we require to list only the HTML files in a directory. - * <pre> - * DirectoryStream.Filter<FileRef> filter = - * DirectoryStreamFilters.newContentTypeFilter("text/html"); - * </pre> - * - * @param type - * The content type - * - * @return A new directory stream filter - * - * @throws IllegalArgumentException - * If the {@code type} parameter cannot be parsed as a MIME type - * or it has parameters - */ - public static <T extends FileRef> DirectoryStream.Filter<T> - newContentTypeFilter(String type) - { - final MimeType matchType = MimeType.parse(type); - if (matchType.hasParameters()) - throw new IllegalArgumentException("Parameters not allowed"); - return new DirectoryStream.Filter<T>() { - - public boolean accept(T entry) { - String fileType; - try { - fileType = Files.probeContentType(entry); - } catch (IOException x) { - throw new IOError(x); - } - if (fileType != null) { - return matchType.match(fileType); - } - return false; - } - }; - } - - /** - * Returns a directory stream filter that {@link DirectoryStream.Filter#accept - * accepts} a directory entry if the entry is accepted by all of the given - * filters. - * - * <p> This method returns a filter that invokes, in iterator order, the - * {@code accept} method of each of the filters. If {@code false} is returned - * by any of the filters then the directory entry is filtered. If the - * directory entry is not filtered then the resulting filter accepts the - * entry. If the iterator returns zero elements then the resulting filter - * accepts all directory entries. - * - * <p> <b>Usage Example:</b> - * <pre> - * List<DirectoryStream.Filter<? super Path>> filters = ... - * DirectoryStream.Filter<Path> filter = DirectoryStreamFilters.allOf(filters); - * </pre> - * - * @param filters - * The sequence of filters - * - * @return The resulting filter - */ - public static <T> DirectoryStream.Filter<T> - allOf(final Iterable<? extends DirectoryStream.Filter<? super T>> filters) - { - if (filters == null) - throw new NullPointerException("'filters' is null"); - return new DirectoryStream.Filter<T>() { - - public boolean accept(T entry) { - for (DirectoryStream.Filter<? super T> filter: filters) { - if (!filter.accept(entry)) - return false; - } - return true; - } - }; - } - - /** - * Returns a directory stream filter that {@link DirectoryStream.Filter#accept - * accepts} a directory entry if the entry is accepted by one or more of - * the given filters. - * - * <p> This method returns a filter that invokes, in iteration order, the - * {@code accept} method of each of filter. If {@code true} is returned by - * any of the filters then the directory entry is accepted. If none of the - * filters accepts the directory entry then it is filtered. If the iterator - * returns zero elements then the resulting filter filters all directory - * entries. - * - * @param filters - * The sequence of filters - * - * @return The resulting filter - */ - public static <T> DirectoryStream.Filter<T> - anyOf(final Iterable<? extends DirectoryStream.Filter<? super T>> filters) - { - if (filters == null) - throw new NullPointerException("'filters' is null"); - return new DirectoryStream.Filter<T>() { - - public boolean accept(T entry) { - for (DirectoryStream.Filter<? super T> filter: filters) { - if (filter.accept(entry)) - return true; - } - return false; - } - }; - } - - /** - * Returns a directory stream filter that is the <em>complement</em> of the - * given filter. The resulting filter {@link - * java.nio.file.DirectoryStream.Filter#accept accepts} a directory entry - * if filtered by the given filter, and filters any entries that are accepted - * by the given filter. - * - * @param filter - * The given filter - * - * @return The resulting filter that is the complement of the given filter - */ - public static <T> DirectoryStream.Filter<T> - complementOf(final DirectoryStream.Filter<T> filter) - { - if (filter == null) - throw new NullPointerException("'filter' is null"); - return new DirectoryStream.Filter<T>() { - - public boolean accept(T entry) { - return !filter.accept(entry); - } - }; - } -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/FileAction.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,65 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file; - -import java.io.IOException; - -/** - * An interface that is implemented by objects that operate on a file. An - * implementation of this interface is provided to the {@link Files#withDirectory - * withDirectory} utility method so that the file action is {@link #invoke - * invoked} for all accepted entries in the directory, after which, the directory - * is automatically closed. - * - * <p> <b>Usage Example:</b> - * Suppose we require to perform a task on all class files in a directory: - * <pre> - * Path dir = ... - * Files.withDirectory(dir, "*.class", new FileAction<Path>() { - * public void invoke(Path entry) { - * : - * } - * }); - * </pre> - * - * @param <T> The type of file reference - * - * @since 1.7 - */ - -public interface FileAction<T extends FileRef> { - /** - * Invoked for a file. - * - * @param file - * The file - * - * @throws IOException - * If the block terminates due an uncaught I/O exception - */ - void invoke(T file) throws IOException; -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/FileAlreadyExistsException.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,64 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file; - -/** - * Checked exception thrown when an attempt is made to create a file or - * directory and a file of that name already exists. - * - * @since 1.7 - */ - -public class FileAlreadyExistsException - extends FileSystemException -{ - static final long serialVersionUID = 7579540934498831181L; - - /** - * Constructs an instance of this class. - * - * @param file - * A string identifying the file or {@code null} if not known. - */ - public FileAlreadyExistsException(String file) { - super(file); - } - - /** - * Constructs an instance of this class. - * - * @param file - * A string identifying the file or {@code null} if not known. - * @param other - * A string identifying the other file or {@code null} if not known. - * @param reason - * A reason message with additional information or {@code null} - */ - public FileAlreadyExistsException(String file, String other, String reason) { - super(file, other, reason); - } -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/FileRef.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,425 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file; - -import java.io.IOException; - -import org.classpath.icedtea.java.nio.channels.SeekableByteChannel; - -import org.classpath.icedtea.java.nio.file.attribute.FileAttributeView; - -/** - * A reference to a file. - * - * <p> A {@code FileRef} is an object that locates a file and defines methods to - * access the file. The means by which the file is located depends on the - * implementation. In many cases, a file is located by a {@link Path} but it may - * be located by other means such as a file-system identifier. - * - * <p> This interface defines the following operations: - * <ul> - * <li><p> The {@link #newByteChannel newByteChannel} method - * may be used to open a file and obtain a byte channel for reading or - * writing. </p></li> - * <li><p> The {@link #delete delete} method may be used to delete a file. - * </p></li> - * <li><p> The {@link #checkAccess checkAccess} method may be used to check - * the existence or accessibility of a file. </p></li> - * <li><p> The {@link #isSameFile isSameFile} method may be used to test if - * two file references locate the same file. </p></li> - * <li><p> The {@link #getFileStore getFileStore} method may be used to - * obtain the {@link FileStore} representing the storage where a file is - * located. </p></li> - * </ul> - * - * <p> Access to associated metadata or file attributes requires an appropriate - * {@link FileAttributeView FileAttributeView}. The {@link - * #getFileAttributeView(Class,LinkOption[]) getFileAttributeView(Class,LinkOption[])} - * method may be used to obtain a file attribute view that defines type-safe - * methods to read or update file attributes. The {@link - * #getFileAttributeView(String,LinkOption[]) getFileAttributeView(String,LinkOption[])} - * method may be used to obtain a file attribute view where dynamic access to - * file attributes where required. - * - * <p> A {@code FileRef} is immutable and safe for use by multiple concurrent - * threads. - * - * @since 1.7 - */ - -public interface FileRef { - - /** - * Opens the file referenced by this object, returning a seekable byte - * channel to access the file. - * - * <p> The {@code options} parameter determines how the file is opened. - * The {@link StandardOpenOption#READ READ} and {@link StandardOpenOption#WRITE - * WRITE} options determine if the file should be opened for reading and/or - * writing. If neither option (or the {@link StandardOpenOption#APPEND APPEND} - * option) is contained in the array then the file is opened for reading. - * By default reading or writing commences at the beginning of the file. - * - * <p> In the addition to {@code READ} and {@code WRITE}, the following - * options may be present: - * - * <table border=1 cellpadding=5 summary=""> - * <tr> <th>Option</th> <th>Description</th> </tr> - * <tr> - * <td> {@link StandardOpenOption#APPEND APPEND} </td> - * <td> If this option is present then the file is opened for writing and - * each invocation of the channel's {@code write} method first advances - * the position to the end of the file and then writes the requested - * data. Whether the advancement of the position and the writing of the - * data are done in a single atomic operation is system-dependent and - * therefore unspecified. This option may not be used in conjunction - * with the {@code READ} or {@code TRUNCATE_EXISTING} options. </td> - * </tr> - * <tr> - * <td> {@link StandardOpenOption#TRUNCATE_EXISTING TRUNCATE_EXISTING} </td> - * <td> If this option is present then the existing file is truncated to - * a size of 0 bytes. This option is ignored when the file is opened only - * for reading. </td> - * </tr> - * <tr> - * <td> {@link StandardOpenOption#SYNC SYNC} </td> - * <td> Requires that every update to the file's content or metadata be - * written synchronously to the underlying storage device. (see <a - * href="package-summary.html#integrity"> Synchronized I/O file - * integrity</a>). </td> - * </tr> - * <tr> - * <td> {@link StandardOpenOption#DSYNC DSYNC} </td> - * <td> Requires that every update to the file's content be written - * synchronously to the underlying storage device. (see <a - * href="package-summary.html#integrity"> Synchronized I/O file - * integrity</a>). </td> - * </tr> - * </table> - * - * <p> An implementation of this interface may support additional options - * defined by the {@link StandardOpenOption} enumeration type or other - * implementation specific options. - * - * <p> The {@link java.nio.channels.Channels} utility classes defines methods - * to construct input and output streams where inter-operation with the - * {@link java.io} package is required. - * - * @param options - * Options specifying how the file is opened - * - * @return a new seekable byte channel - * - * @throws IllegalArgumentException - * If an invalid combination of options is specified - * @throws UnsupportedOperationException - * If an unsupported open option is specified - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * In the case of the default provider, and a security manager is - * installed, the {@link SecurityManager#checkRead(String) checkRead} - * method is invoked to check read access to the path if the file is - * opened for reading. The {@link SecurityManager#checkWrite(String) - * checkWrite} method is invoked to check write access to the path - * if the file is opened for writing. - */ - SeekableByteChannel newByteChannel(OpenOption... options) - throws IOException; - - /** - * Returns the {@link FileStore} representing the file store where the file - * referenced by this object is stored. - * - * <p> Once a reference to the {@code FileStore} is obtained it is - * implementation specific if operations on the returned {@code FileStore}, - * or {@link FileStoreAttributeView} objects obtained from it, continue - * to depend on the existence of the file. In particular the behavior is not - * defined for the case that the file is deleted or moved to a different - * file store. - * - * @return The file store where the file is stored - * - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * In the case of the default provider, and a security manager is - * installed, the {@link SecurityManager#checkRead(String) checkRead} - * method is invoked to check read access to the file. - */ - FileStore getFileStore() throws IOException; - - /** - * Checks the existence and optionally the accessibility of the file - * referenced by this object. - * - * <p> This method checks the existence of a file and that this Java virtual - * machine has appropriate privileges that would allow it access the file - * according to all of access modes specified in the {@code modes} parameter - * as follows: - * - * <table border=1 cellpadding=5 summary=""> - * <tr> <th>Value</th> <th>Description</th> </tr> - * <tr> - * <td> {@link AccessMode#READ READ} </td> - * <td> Checks that the file exists and that the Java virtual machine has - * permission to read the file. </td> - * </tr> - * <tr> - * <td> {@link AccessMode#WRITE WRITE} </td> - * <td> Checks that the file exists and that the Java virtual machine has - * permission to write to the file, </td> - * </tr> - * <tr> - * <td> {@link AccessMode#EXECUTE EXECUTE} </td> - * <td> Checks that the file exists and that the Java virtual machine has - * permission to {@link Runtime#exec execute} the file. The semantics - * may differ when checking access to a directory. For example, on UNIX - * systems, checking for {@code EXECUTE} access checks that the Java - * virtual machine has permission to search the directory in order to - * access file or subdirectories. </td> - * </tr> - * </table> - * - * <p> If the {@code modes} parameter is of length zero, then the existence - * of the file is checked. - * - * <p> This method follows symbolic links if the file referenced by this - * object is a symbolic link. Depending on the implementation, this method - * may require to read file permissions, access control lists, or other - * file attributes in order to check the effective access to the file. To - * determine the effective access to a file may require access to several - * attributes and so in some implementations this method may not be atomic - * with respect to other file system operations. Furthermore, as the result - * of this method is immediately outdated, there is no guarantee that a - * subsequence access will succeed (or even that it will access the same - * file). Care should be taken when using this method in security sensitive - * applications. - * - * @param modes - * The access modes to check; may have zero elements - * - * @throws UnsupportedOperationException - * An implementation is required to support checking for - * {@code READ}, {@code WRITE}, and {@code EXECUTE} access. This - * exception is specified to allow for the {@code Access} enum to - * be extended in future releases. - * @throws NoSuchFileException - * If a file does not exist <i>(optional specific exception)</i> - * @throws AccessDeniedException - * The requested access would be denied or the access cannot be - * determined because the Java virtual machine has insufficient - * privileges or other reasons. <i>(optional specific exception)</i> - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * In the case of the default provider, and a security manager is - * installed, the {@link SecurityManager#checkRead(String) checkRead} - * is invoked when checking read access to the file or only the - * existence of the file, the {@link SecurityManager#checkWrite(String) - * checkWrite} is invoked when checking write access to the file, - * and {@link SecurityManager#checkExec(String) checkExec} is invoked - * when checking execute access. - */ - void checkAccess(AccessMode... modes) throws IOException; - - /** - * Returns a file attribute view of a given type. - * - * <p> A file attribute view provides a read-only or updatable view of the - * file attributes that is supports. This method is intended to be used where - * the file attribute view defines type-safe methods to read or update the - * file attributes. The {@code type} parameter is the type of the attribute - * view required and the method returns an instance of that type if - * supported. The {@link BasicFileAttributeView} type supports access to the - * basic attributes of a file. Invoking this method to select a file - * attribute view of that type will always return an instance of that class. - * - * <p> The {@code options} array may be used to indicate how symbolic links - * are handled by the resulting file attribute view for the case that the - * file is a symbolic link. By default, symbolic links are followed. If the - * option {@link LinkOption#NOFOLLOW_LINKS NOFOLLOW_LINKS} is present then - * symbolic links are not followed. This option is ignored by implementations - * that do not support symbolic links. - * - * @param type - * The {@code Class} object corresponding to the file attribute view - * @param options - * Options indicating how symbolic links are handled - * - * @return A file attribute view of the specified type, or {@code null} if - * the attribute view type is not available - * - * @throws UnsupportedOperationException - * If options contains an unsupported option. This exception is - * specified to allow the {@code LinkOption} enum be extended - * in future releases. - * - * @see Attributes#readBasicFileAttributes - */ - <V extends FileAttributeView> V getFileAttributeView(Class<V> type, LinkOption... options); - - /** - * Returns a file attribute view of the given name. - * - * <p> A file attribute view provides a read-only or updatable view of the - * file attributes that is supports. This method is intended to be used where - * <em>dynamic access</em> to the file attributes is required. The {@code - * name} parameter specifies the {@link FileAttributeView#name name} of the - * file attribute view and this method returns an instance of that view if - * supported. The {@link BasicFileAttributeView} type supports access to the - * basic attributes of a file and is name {@code "basic"}. Invoking this - * method to select a file attribute view named {@code "basic"} will always - * return an instance of that class. - * - * <p> The {@code options} array may be used to indicate how symbolic links - * are handled by the resulting file attribute view for the case that the - * file is a symbolic link. By default, symbolic links are followed. If the - * option {@link LinkOption#NOFOLLOW_LINKS NOFOLLOW_LINKS} is present then - * symbolic links are not followed. This option is ignored by implementations - * that do not support symbolic links. - * - * @param name - * The name of the file attribute view - * @param options - * Options indicating how symbolic links are handled - * - * @return A file attribute view of the given name, or {@code null} if - * the attribute view is not available - * - * @throws UnsupportedOperationException - * If options contains an unsupported option. This exception is - * specified to allow the {@code LinkOption} enum be extended - * in future releases. - */ - FileAttributeView getFileAttributeView(String name, LinkOption... options); - - /** - * Tests if the file referenced by this object is the same file referenced - * by another object. - * - * <p> If this {@code FileRef} and the given {@code FileRef} are {@link - * #equals(Object) equal} then this method returns {@code true} without checking - * if the file exists. If the {@code FileRef} and the given {@code FileRef} - * are associated with different providers, or the given {@code FileRef} is - * {@code null} then this method returns {@code false}. Otherwise, this method - * checks if both {@code FileRefs} locate the same file, and depending on the - * implementation, may require to open or access both files. - * - * <p> If the file system and files remain static, then this method implements - * an equivalence relation for non-null {@code FileRefs}. - * <ul> - * <li>It is <i>reflexive</i>: for a non-null {@code FileRef} {@code f}, - * {@code f.isSameFile(f)} should return {@code true}. - * <li>It is <i>symmetric</i>: for two non-null {@code FileRefs} - * {@code f} and {@code g}, {@code f.isSameFile(g)} will equal - * {@code g.isSameFile(f)}. - * <li>It is <i>transitive</i>: for three {@code FileRefs} - * {@code f}, {@code g}, and {@code h}, if {@code f.isSameFile(g)} returns - * {@code true} and {@code g.isSameFile(h)} returns {@code true}, then - * {@code f.isSameFile(h)} will return return {@code true}. - * </ul> - * - * @param other - * The other file reference - * - * @return {@code true} if, and only if, this object and the given object - * locate the same file - * - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * In the case of the default provider, and a security manager is - * installed, the {@link SecurityManager#checkRead(String) checkRead} - * method is invoked to check read access to both files. - * - * @see java.nio.file.attribute.BasicFileAttributes#fileKey - */ - boolean isSameFile(FileRef other) throws IOException; - - /** - * Deletes the file referenced by this object. - * - * <p> An implementation may require to examine the file to determine if the - * file is a directory. Consequently this method may not be atomic with respect - * to other file system operations. If the file is a symbolic-link then the - * link is deleted and not the final target of the link. - * - * <p> If the file is a directory then the directory must be empty. In some - * implementations a directory has entries for special files or links that - * are created when the directory is created. In such implementations a - * directory is considered empty when only the special entries exist. - * - * <p> On some operating systems it may not be possible to remove a file when - * it is open and in use by this Java virtual machine or other programs. - * - * @throws NoSuchFileException - * If the file does not exist <i>(optional specific exception)</i> - * @throws DirectoryNotEmptyException - * If the file is a directory and could not otherwise be deleted - * because the directory is not empty <i>(optional specific - * exception)</i> - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * In the case of the default provider, and a security manager is - * installed, the {@link SecurityManager#checkDelete(String)} method - * is invoked to check delete access to the file - */ - void delete() throws IOException; - - /** - * Tests this object for equality with another object. - * - * <p> If the given object is not a {@code FileRef} then this method - * immediately returns {@code false}. - * - * <p> For two file references to be considered equal requires that they - * are both the same type of {@code FileRef} and encapsulate components - * to locate the same file. This method does not access the file system and - * the file may not exist. - * - * <p> This method satisfies the general contract of the {@link - * java.lang.Object#equals(Object) Object.equals} method. </p> - * - * @param ob The object to which this object is to be compared - * - * @return {@code true} if, and only if, the given object is a {@code FileRef} - * that is identical to this {@code FileRef} - * - * @see #isSameFile - */ - boolean equals(Object ob); - - /** - * Returns the hash-code value for this object. - * - * <p> This method satisfies the general contract of the - * {@link java.lang.Object#hashCode() Object.hashCode} method. - */ - int hashCode(); -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/FileStore.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,173 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file; - -import java.util.Set; - -import org.classpath.icedtea.java.nio.file.attribute.FileAttributeView; -import org.classpath.icedtea.java.nio.file.attribute.FileStoreAttributeView; - -/** - * Storage for files. A {@code FileStore} represents a storage pool, device, - * partition, volume, concrete file system or other implementation specific means - * of file storage. The {@code FileStore} for where a file is stored is obtained - * by invoking the {@link FileRef#getFileStore getFileStore} method, or all file - * stores can be enumerated by invoking the {@link FileSystem#getFileStores - * getFileStores} method. - * - * <p> In addition to the methods defined by this class, a file store may support - * one or more {@link FileStoreAttributeView FileStoreAttributeView} classes - * that provide a read-only or updatable view of a set of file store attributes. - * File stores associated with the default provider support the {@link - * FileStoreSpaceAttributeView} to read the space related attributes of the - * file store. - * - * @since 1.7 - */ - -public abstract class FileStore { - - /** - * Initializes a new instance of this class. - */ - protected FileStore() { - } - - /** - * Returns the name of this file store. The format of the name is highly - * implementation specific. It will typically be the name of the storage - * pool or volume. - * - * <p> The string returned by this method may differ from the string - * returned by the {@link Object#toString() toString} method. - * - * @return The name of this file store - */ - public abstract String name(); - - /** - * Returns the <em>type</em> of this file store. The format of the string - * returned by this method is highly implementation specific. It may - * indicate, for example, the format used or if the file store is local - * or remote. - * - * @return A string representing the type of this file store - */ - public abstract String type(); - - /** - * Tells whether this file store is read-only. A file store is read-only if - * it does not support write operations or other changes to files. Any - * attempt to create a file, open an existing file for writing etc. causes - * an {@code IOException} to be thrown. - * - * @return {@code true} if, and only if, this file store is read-only - */ - public abstract boolean isReadOnly(); - - /** - * Tells whether or not this file store supports the file attributes - * identified by the given file attribute view. - * - * <p> Invoking this method to test if the file store supports {@link - * BasicFileAttributeView} will always return {@code true}. In the case of - * the default provider, this method cannot guarantee to give the correct - * result when the file store is not a local storage device. The reasons for - * this are implementation specific and therefore unspecified. - * - * @param type - * The file attribute view type - * - * @return {@code true} if, and only if, the file attribute view is - * supported - */ - public abstract boolean supportsFileAttributeView(Class<? extends FileAttributeView> type); - - /** - * Tells whether or not this file store supports the file attributes - * identified by the given file attribute view. - * - * <p> Invoking this method to test if the file store supports {@link - * BasicFileAttributeView}, identified by the name "{@code basic}" will - * always return {@code true}. In the case of the default provider, this - * method cannot guarantee to give the correct result when the file store is - * not a local storage device. The reasons for this are implementation - * specific and therefore unspecified. - * - * @param name - * The {@link FileAttributeView#name name} of file attribute view - * - * @return {@code true} if, and only if, the file attribute view is - * supported - */ - public abstract boolean supportsFileAttributeView(String name); - - /** - * Returns a {@code FileStoreAttributeView} of the given type. - * - * <p> This method is intended to be used where the file store attribute - * view defines type-safe methods to read or update the file store attributes. - * The {@code type} parameter is the type of the attribute view required and - * the method returns an instance of that type if supported. - * - * <p> For {@code FileStore} objects created by the default provider, then - * the file stores support the {@link FileStoreSpaceAttributeView} that - * provides access to space attributes. In that case invoking this method - * with a parameter value of {@code FileStoreSpaceAttributeView.class} will - * always return an instance of that class. - * - * @param type - * The {@code Class} object corresponding to the attribute view - * - * @return A file store attribute view of the specified type or - * {@code null} if the attribute view is not available - */ - public abstract <V extends FileStoreAttributeView> V - getFileStoreAttributeView(Class<V> type); - - /** - * Returns a {@code FileStoreAttributeView} of the given name. - * - * <p> This method is intended to be used where <em>dynamic access</em> to - * file store attributes is required. The {@code name} parameter specifies - * the {@link FileAttributeView#name name} of the file store attribute view - * and this method returns an instance of that view if supported. - * - * <p> For {@code FileStore} objects created by the default provider, then - * the file stores support the {@link FileStoreSpaceAttributeView} that - * provides access to space attributes. In that case invoking this method - * with a parameter value of {@code "space"} will always return an instance - * of that class. - * - * @param name - * The name of the attribute view - * - * @return A file store attribute view of the given name, or {@code null} - * if the attribute view is not available - */ - public abstract FileStoreAttributeView getFileStoreAttributeView(String name); -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/FileSystem.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,426 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file; - -import java.util.Set; -import java.io.Closeable; -import java.io.IOException; - -import org.classpath.icedtea.java.nio.file.attribute.UserPrincipalLookupService; - -import org.classpath.icedtea.java.nio.file.spi.FileSystemProvider; - -/** - * Provides an interface to a file system and is the factory for objects to - * access files and other objects in the file system. - * - * <p> The default file system, obtained by invoking the {@link FileSystems#getDefault - * FileSystems.getDefault} method, provides access to the file system that is - * accessible to the Java virtual machine. The {@link FileSystems} class defines - * methods to create file systems that provide access to other types of file - * systems. - * - * <p> A file system is the factory for several types of objects: - * - * <ul> - * <li><p> The {@link #getPath getPath} method converts a system dependent - * <em>path string</em>, returning a {@link Path} object that may be used - * to locate and access a file. </p></li> - * <li><p> The {@link #getNameMatcher getNameMatcher} method is used - * to create a {@link PathMatcher} that performs match operations on - * file names. </p></li> - * <li><p> The {@link #getFileStores getFileStores} method returns an iterator - * over the underlying {@link FileStore file-stores}. </p></li> - * <li><p> The {@link #getUserPrincipalLookupService getUserPrincipalLookupService} - * method returns the {@link UserPrincipalLookupService} to lookup users or - * groups by name. </p></li> - * <li><p> The {@link #newWatchService newWatchService} method creates a - * {@link WatchService} that may be used to watch objects for changes and - * events. </p></li> - * </ul> - * - * <p> File systems vary greatly. In some cases the file system is a single - * hierarchy of files with one top-level root directory. In other cases it may - * have several distinct file hierarchies, each with its own top-level root - * directory. The {@link #getRootDirectories getRootDirectories} method may be - * used to iterate over the root directories in the file system. A file system - * is typically composed of one or more underlying {@link FileStore file-stores} - * that provide the storage for the files. Theses file stores can also vary in - * the features they support, and the file attributes or <em>meta-data</em> that - * they associate with files. - * - * <p> A file system is open upon creation and can be closed by invoking its - * {@link #close() close} method. Once closed, any further attempt to access - * objects in the file system cause {@link ClosedFileSystemException} to be - * thrown. File systems created by the default {@link FileSystemProvider provider} - * cannot be closed. - * - * <p> A {@code FileSystem} can provide read-only or read-write access to the - * file system. Whether or not a file system provides read-only access is - * established when the {@code FileSystem} is created and can be tested by invoking - * its {@link #isReadOnly() isReadOnly} method. Attempts to write to file stores - * by means of an object associated with a read-only file system throws {@link - * ReadOnlyFileSystemException}. - * - * <p> File systems are safe for use by multiple concurrent threads. The {@link - * #close close} method may be invoked at any time to close a file system but - * whether a file system is <i>asynchronously closeable</i> is provider specific - * and therefore unspecified. In other words, if a thread is accessing an - * object in a file system, and another thread invokes the {@code close} method - * then it may require to block until the first operation is complete. Closing - * a file system causes all open channels, watch services, and other {@link - * Closeable closeable} objects associated with the file system to be closed. - * - * @since 1.7 - */ - -public abstract class FileSystem - implements Closeable -{ - /** - * Initializes a new instance of this class. - */ - protected FileSystem() { - } - - /** - * Returns the provider that created this file system. - * - * @return The provider that created this file system. - */ - public abstract FileSystemProvider provider(); - - /** - * Closes this file system. - * - * <p> After a file system is closed then all subsequent access to the file - * system, either by methods defined by this class or on objects associated - * with this file system, throw {@link ClosedFileSystemException}. If the - * file system is already closed then invoking this method has no effect. - * - * <p> Closing a file system will close all open {@link - * java.nio.channels.Channel channels}, {@link DirectoryStream directory-streams}, - * {@link WatchService watch-service}, and other closeable objects associated - * with this file system. The {@link FileSystems#getDefault default} file - * system cannot be closed. - * - * @throws IOException - * If an I/O error occurs - * @throws UnsupportedOperationException - * Thrown in the case of the default file system - */ - - public abstract void close() throws IOException; - - /** - * Tells whether or not this file system is open. - * - * <p> File systems created by the default provider are always open. - * - * @return {@code true} if, and only if, this file system is open - */ - public abstract boolean isOpen(); - - /** - * Tells whether or not this file system allows only read-only access to - * its file stores. - * - * @return {@code true} if, and only if, this file system provides - * read-only access - */ - public abstract boolean isReadOnly(); - - /** - * Returns the name separator, represented as a string. - * - * <p> The name separator is used to separate names in a path string. An - * implementation may support multiple name separators in which case this - * method returns an implementation specific <em>default</em> name separator. - * This separator is used when creating path strings by invoking the {@link - * Path#toString() toString()} method. - * - * <p> In the case of the default provider, this method returns the same - * separator as {@link java.io.File#separator}. - * - * @return The name separator - */ - public abstract String getSeparator(); - - /** - * Returns an object to iterate over the paths of the root directories. - * - * <p> A file system provides access to a file store that may be composed - * of a number of distinct file hierarchies, each with its own top-level - * root directory. Unless denied by the security manager, each element in - * the returned iterator corresponds to the root directory of a distinct - * file hierarchy. The order of the elements is not defined. The file - * hierarchies may change during the lifetime of the Java virtual machine. - * For example, in some implementations, the insertion of removable media - * may result in the creation of a new file hierarchy with its own - * top-level directory. - * - * <p> When a security manager is installed, it is invoked to check access - * to the each root directory. If denied, the root directory is not returned - * by the iterator. In the case of the default provider, the {@link - * SecurityManager#checkRead(String)} method is invoked to check read access - * to each root directory. It is system dependent if the permission checks - * are done when the iterator is obtained or during iteration. - * - * @return An object to iterate over the root directories - */ - public abstract Iterable<Path> getRootDirectories(); - - /** - * Returns an object to iterate over the underlying file stores. - * - * <p> The elements of the returned iterator are the {@link - * FileStore FileStores} for this file system. The order of the elements is - * not defined and the file stores may change during the lifetime of the - * Java virtual machine. When an I/O error occurs, perhaps because a file - * store is not accessible, then it is not returned by the iterator. - * - * <p> When a security manager is installed, it is invoked to check access - * to each file store. If denied, the file store is not returned by the - * iterator. In the case of the default provider, the {@link - * SecurityManager#checkRead(String)} method is invoked to check read access - * to the file store's <em>top-most</em> directory. It is system dependent - * if the permission checks are done when the iterator is obtained or during - * iteration. - * - * <p> <b>Usage Example:</b> - * Suppose we want to print the space usage for all file stores: - * <pre> - * for (FileStore store: FileSystems.getDefault().getFileStores()) { - * FileStoreSpaceAttributes attrs = Attributes.readFileStoreSpaceAttributes(store); - * long total = attrs.totalSpace() / 1024; - * long used = (attrs.totalSpace() - attrs.unallocatedSpace()) / 1024; - * long avail = attrs.usableSpace() / 1024; - * System.out.format("%-20s %12d %12d %12d%n", store, total, used, avail); - * } - * </pre> - * - * @return An object to iterate over the backing file stores - */ - public abstract Iterable<FileStore> getFileStores(); - - /** - * Returns the set of the {@link FileAttributeView#name names} of the file - * attribute views supported by this {@code FileSystem}. - * - * <p> The {@link BasicFileAttributeView} is required to be supported and - * therefore the set contains at least one element, "basic". - * - * <p> The {@link FileStore#supportsFileAttributeView(String) - * supportsFileAttributeView(String)} method may be used to test if an - * underlying {@link FileStore} supports the file attributes identified by a - * file attribute view. - * - * @return An unmodifiable set of the names of the supported file attribute - * views - */ - public abstract Set<String> supportedFileAttributeViews(); - - /** - * Converts a path string to a {@code Path}. - * - * <p> The parsing and conversion to a path object is inherently - * implementation dependent. In the simplest case, the path string is rejected, - * and {@link InvalidPathException} thrown, if the path string contains - * characters that cannot be converted to characters that are <em>legal</em> - * to the file store. For example, on UNIX systems, the NUL (\u0000) - * character is not allowed to be present in a path. An implementation may - * choose to reject path strings that contain names that are longer than those - * allowed by any file store, and where an implementation supports a complex - * path syntax, it may choose to reject path strings that are <em>badly - * formed</em>. - * - * <p> In the case of the default provider, path strings are parsed based - * on the definition of paths at the platform or virtual file system level. - * For example, an operating system may not allow specific characters to be - * present in a file name, but a specific underlying file store may impose - * different or additional restrictions on the set of legal - * characters. - * - * <p> This method throws {@link InvalidPathException} when the path string - * cannot be converted to a path. Where possible, and where applicable, - * the exception is created with an {@link InvalidPathException#getIndex - * index} value indicating the first position in the {@code path} parameter - * that caused the path string to be rejected. - * - * <p> Invoking this method with an empty path string throws - * {@code InvalidPathException}. - * - * @param path - * The path string - * - * @return A {@code Path} object - * - * @throws InvalidPathException - * If the path string cannot be converted - */ - public abstract Path getPath(String path); - - /** - * Returns a {@code PathMatcher} that performs match operations on file - * {@link Path#getName names} by interpreting a given pattern. - * - * <p> The {@code syntax} parameter identifies the syntax. This method - * supports the "{@code glob}" and "{@code regex}" syntaxes, and may - * support others. The value of the syntax component is compared without - * regard to case. - * - * <p> When the syntax is "{@code glob}" then the {@code String} - * representation of the file name is matched using a limited pattern - * language that resembles regular expressions but with a simpler syntax. - * For example: - * - * <blockquote> - * <table border="0"> - * <tr> - * <td>{@code *.java}</td> - * <td>Matches file names ending in {@code .java}</td> - * </tr> - * <tr> - * <td>{@code *.*}</td> - * <td>Matches file names containing a dot</td> - * </tr> - * <tr> - * <tr> - * <td>{@code *.{java,class}}</td> - * <td>Matches file names ending with {@code .java} or {@code .class}</td> - * </tr> - * <tr> - * <td>{@code foo.?}</td> - * <td>Matches file names starting with {@code foo.} and a single - * character extension</td> - * </tr> - * </table> - * </blockquote> - * - * <p> The following rules are used to interprete glob patterns: - * - * <p> <ul> - * <li><p> The {@code *} character matches zero or more {@link Character - * characters}. </p></li> - * - * <li><p> The {@code ?} character matches exactly one character. </p></li> - * - * <li><p> The backslash character ({@code \}) is used to escape characters - * that would otherwise be interpreted as special characters. The expression - * {@code \\} matches a single backslash and "\{" matches a left brace - * for example. </p></li> - * - * <li><p> The {@code [ ]} characters are a <i>bracket expression</i> and - * match a single character that is contained within the brackets. For - * example, {@code [abc]} matches {@code "a"}, {@code "b"}, or {@code "c"}. - * The hyphen ({@code -}) may be used to specify a range so {@code [a-z]} - * specifies a range that matches from {@code "a"} to {@code "z"} (inclusive). - * These forms can be mixed so [abce-g] matches {@code "a"}, {@code "b"}, - * {@code "c"}, {@code "e"}, {@code "f"} or {@code "g"}. If the character - * after the {@code [} is a {@code !} then it is used for negation so {@code - * [!a-c]} matches any character except {@code "a"}, {@code "b"}, or {@code - * "c"}. - * <p> Within a bracket expression the {@code *}, {@code ?} and {@code \} - * characters match themselves. The ({@code -}) character matches itself if - * it is the first character within the brackets, or the first character - * after the {@code !} if negating.</p></li> - * - * <li><p> The {@code { }} characters are a group of subpatterns, where - * the group matches if any subpattern in the group matches. The {@code ","} - * character is used to separate the subpatterns. Groups cannot be nested. - * </p></li> - * - * <li><p>All other characters match themselves in an implementation - * dependent manner. </p></li> - * </ul> - * - * <p> When the syntax is "{@code regex}" then the pattern component is a - * regular expression as defined by the {@link java.util.regex.Pattern} - * class. - * - * <p> For both the glob and regex syntaxes then whether matching is case - * sensitive, and other matching details, are implementation-dependent. - * - * <p> The {@code PathMatcher} returned by this method matches on the {@link - * Path#getName name} component of a {@code Path}. If the {@link - * PathMatcher#matches matches} method is invoked with a {@code Path} that - * does not have a {@code name} component then it returns {@code false}. - * - * @param syntax - * The pattern syntax - * @param pattern - * The pattern - * - * @return A file name matcher that matches file names against the pattern - * - * @throws java.util.regex.PatternSyntaxException - * If the pattern is invalid - * @throws UnsupportedOperationException - * If the pattern syntax is not known to the implementation - * - * @see Path#newDirectoryStream(String) - */ - public abstract PathMatcher getNameMatcher(String syntax, String pattern); - - /** - * Returns the {@code UserPrincipalLookupService} for this file system - * <i>(optional operation)</i>. The resulting lookup service may be used to - * lookup user or group names. - * - * <p> <b>Usage Example:</b> - * Suppose we want to make "joe" the owner of a file: - * <pre> - * Path file = ... - * UserPrincipal joe = file.getFileSystem().getUserPrincipalLookupService() - * .lookupPrincipalByName("joe"); - * Attributes.setOwner(file, joe); - * </pre> - * - * @throws UnsupportedOperationException - * If this {@code FileSystem} does not does have a lookup service - * - * @return The {@code UserPrincipalLookupService} for this file system - */ - public abstract UserPrincipalLookupService getUserPrincipalLookupService(); - - /** - * Constructs a new {@link WatchService} <i>(optional operation)</i>. - * - * <p> This method constructs a new watch service that may be used to watch - * registered objects for changes and events. - * - * @return a new watch service - * - * @throws UnsupportedOperationException - * If this {@code FileSystem} does not support watching file system - * objects for changes and events. This exception is not thrown - * by {@code FileSystems} created by the default provider. - * @throws IOException - * If an I/O error occurs - */ - public abstract WatchService newWatchService() throws IOException; -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/FileSystemAlreadyExistsException.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,54 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file; - -/** - * Runtime exception thrown an attempt is made to create a file system that - * already exists. - */ - -public class FileSystemAlreadyExistsException - extends RuntimeException -{ - static final long serialVersionUID = -5438419127181131148L; - - /** - * Constructs an instance of this class. - */ - public FileSystemAlreadyExistsException() { - } - - /** - * Constructs an instance of this class. - * - * @param msg - * The detail message - */ - public FileSystemAlreadyExistsException(String msg) { - super(msg); - } -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/FileSystemException.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,126 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file; - -import java.io.IOException; - -/** - * Thrown when a file system operation fails on one or two files. This class is - * the general class for file system exceptions. - * - * @since 1.7 - */ - -public class FileSystemException - extends IOException -{ - static final long serialVersionUID = -3055425747967319812L; - - private final String file; - private final String other; - - /** - * Constructs an instance of this class. This constructor should be used - * when an operation involving one file fails and there isn't any additional - * information to explain the reason. - * - * @param file - * A string identifying the file or {@code null} if not known. - */ - public FileSystemException(String file) { - super((String)null); - this.file = file; - this.other = null; - } - - /** - * Constructs an instance of this class. This constructor should be used - * when an operation involving two files fails, or there is additional - * information to explain the reason. - * - * @param file - * A string identifying the file or {@code null} if not known. - * @param other - * A string identifying the other file or {@code null} if there - * isn't another file or if not known - * @param reason - * A reason message with additional information or {@code null} - */ - public FileSystemException(String file, String other, String reason) { - super(reason); - this.file = file; - this.other = other; - } - - /** - * Returns the file used to create this exception. - * - * @return The file (can be {@code null}) - */ - public String getFile() { - return file; - } - - /** - * Returns the other file used to create this exception. - * - * @return The other file (can be {@code null}) - */ - public String getOtherFile() { - return other; - } - - /** - * Returns the string explaining why the file system operation failed. - * - * @return The string explaining why the file system operation failed - */ - public String getReason() { - return super.getMessage(); - } - - /** - * Returns the detail message string. - */ - - public String getMessage() { - if (file == null && other == null) - return getReason(); - StringBuilder sb = new StringBuilder(); - if (file != null) - sb.append(file); - if (other != null) { - sb.append(" -> "); - sb.append(other); - } - if (getReason() != null) { - sb.append(": "); - sb.append(getReason()); - } - return sb.toString(); - } -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/FileSystemNotFoundException.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,53 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file; - -/** - * Runtime exception thrown when a file system cannot be found. - */ - -public class FileSystemNotFoundException - extends RuntimeException -{ - static final long serialVersionUID = 7999581764446402397L; - - /** - * Constructs an instance of this class. - */ - public FileSystemNotFoundException() { - } - - /** - * Constructs an instance of this class. - * - * @param msg - * The detail message - */ - public FileSystemNotFoundException(String msg) { - super(msg); - } -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/FileSystems.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,415 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file; - -import java.net.URI; -import java.io.IOException; -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.util.*; -import java.lang.reflect.Constructor; - -import org.classpath.icedtea.java.nio.file.spi.FileSystemProvider; - -/** - * Factory methods for file systems. This class defines the {@link #getDefault - * getDefault} method to get the default file system and factory methods to - * construct other types of file systems. - * - * <p> The first invocation of any of the methods defined by this class causes - * the default {@link FileSystemProvider provider} to be loaded. The default - * provider, identified by the URI scheme "file", creates the {@link FileSystem} - * that provides access to the file systems accessible to the Java virtual - * machine. If the process of loading or initializing the default provider fails - * then an unspecified error is thrown. - * - * <p> The first invocation of the {@link FileSystemProvider#installedProviders - * installedProviders} method, by way of invoking any of the {@code - * newFileSystem} methods defined by this class, locates and loads all - * installed file system providers. Installed providers are loaded using the - * service-provider loading facility defined by the {@link ServiceLoader} class. - * Installed providers are loaded using the system class loader. If the - * system class loader cannot be found then the extension class loader is used; - * if there is no extension class loader then the bootstrap class loader is used. - * Providers are typically installed by placing them in a JAR file on the - * application class path or in the extension directory, the JAR file contains a - * provider-configuration file named {@code java.nio.file.spi.FileSystemProvider} - * in the resource directory {@code META-INF/services}, and the file lists one or - * more fully-qualified names of concrete subclass of {@link FileSystemProvider} - * that have a zero argument constructor. - * The ordering that installed providers are located is implementation specific. - * If a provider is instantiated and its {@link FileSystemProvider#getScheme() - * getScheme} returns the same URI scheme of a provider that was previously - * instantiated then the most recently instantiated duplicate is discarded. URI - * schemes are compared without regard to case. During construction a provider - * may safely access files associated with the default provider but care needs - * to be taken to avoid circular loading of other installed providers. If - * circular loading of installed providers is detected then an unspecified error - * is thrown. - * - * <p> This class also defines factory methods that allow a {@link ClassLoader} - * to be specified when locating a provider. As with installed providers, the - * provider classes are identified by placing the provider configuration file - * in the resource directory {@code META-INF/services}. - * - * <p> If a thread initiates the loading of the installed file system providers - * and another thread invokes a method that also attempts to load the providers - * then the method will block until the loading completes. - * - * @since 1.7 - */ - -public final class FileSystems { - private FileSystems() { - } - - // lazy initialization of default file system - private static class LazyInitialization { - static final FileSystem defaultFileSystem = defaultFileSystem(); - - // returns default file system - private static FileSystem defaultFileSystem() { - // load default provider - FileSystemProvider provider = AccessController - .doPrivileged(new PrivilegedAction<FileSystemProvider>() { - public FileSystemProvider run() { - return getDefaultProvider(); - } - }); - - // return file system - return provider.getFileSystem(URI.create("file:///")); - } - - // returns default provider - private static FileSystemProvider getDefaultProvider() { - FileSystemProvider provider = sun.nio.fs.DefaultFileSystemProvider.create(); - - // if the property java.nio.file.spi.DefaultFileSystemProvider is - // set then its value is the name of the default provider (or a list) - String propValue = System - .getProperty("java.nio.file.spi.DefaultFileSystemProvider"); - if (propValue != null) { - for (String cn: propValue.split(",")) { - try { - Class<?> c = Class - .forName(cn, true, ClassLoader.getSystemClassLoader()); - Constructor<?> ctor = c - .getDeclaredConstructor(FileSystemProvider.class); - provider = (FileSystemProvider)ctor.newInstance(provider); - - // must be "file" - if (!provider.getScheme().equals("file")) - throw new Error("Default provider must use scheme 'file'"); - - } catch (Exception x) { - throw new Error(x); - } - } - } - return provider; - } - } - - /** - * Returns the default {@code FileSystem}. The default file system creates - * objects that provide access to the file systems accessible to the Java - * virtual machine. The <em>working directory</em> of the file system is - * the current user directory, named by the system property {@code user.dir}. - * This allows for interoperability with the {@link java.io.File java.io.File} - * class. - * - * <p> The first invocation of any of the methods defined by this class - * locates the default {@link FileSystemProvider provider} object. Where the - * system property {@code java.nio.file.spi.DefaultFileSystemProvider} is - * not defined then the default provider is a system-default provider that - * is invoked to create the default file system. - * - * <p> If the system property {@code java.nio.file.spi.DefaultFileSystemProvider} - * is defined then it is taken to be a list of one or more fully-qualified - * names of concrete provider classes identified by the URI scheme - * {@code "file"}. Where the property is a list of more than one name then - * the names are separated by a comma. Each class is loaded, using the system - * class loader, and instantiated by invoking a one argument constructor - * whose formal parameter type is {@code FileSystemProvider}. The providers - * are loaded and instantiated in the order they are listed in the property. - * If this process fails or a provider's scheme is not equal to {@code "file"} - * then an unspecified error is thrown. URI schemes are normally compared - * without regard to case but for the default provider, the scheme is - * required to be {@code "file"}. The first provider class is instantiated - * by invoking it with a reference to the system-default provider. - * The second provider class is instantiated by invoking it with a reference - * to the first provider instance. The third provider class is instantiated - * by invoking it with a reference to the second instance, and so on. The - * last provider to be instantiated becomes the default provider; its {@code - * getFileSystem} method is invoked with the URI {@code "file:///"} to create - * the default file system. - * - * <p> Subsequent invocations of this method return the file system that was - * returned by the first invocation. - * - * @return the default file system - */ - public static FileSystem getDefault() { - return LazyInitialization.defaultFileSystem; - } - - /** - * Returns a reference to an existing {@code FileSystem}. - * - * <p> This method iterates over the {@link FileSystemProvider#installedProviders() - * installed} providers to locate the provider that is identified by the URI - * {@link URI#getScheme scheme} of the given URI. URI schemes are compared - * without regard to case. The exact form of the URI is highly provider - * dependent. If found, the provider's {@link FileSystemProvider#getFileSystem - * getFileSystem} method is invoked to obtain a reference to the {@code - * FileSystem}. - * - * <p> Once a file system created by this provider is {@link FileSystem#close - * closed} it is provider-dependent if this method returns a reference to - * the closed file system or throws {@link FileSystemNotFoundException}. - * If the provider allows a new file system to be created with the same URI - * as a file system it previously created then this method throws the - * exception if invoked after the file system is closed (and before a new - * instance is created by the {@link #newFileSystem newFileSystem} method). - * - * <p> If a security manager is installed then a provider implementation - * may require to check a permission before returning a reference to an - * existing file system. In the case of the {@link FileSystems#getDefault - * default} file system, no permission check is required. - * - * @throws IllegalArgumentException - * If the pre-conditions for the {@code uri} parameter aren't met - * @throws FileSystemNotFoundException - * If the file system, identified by the URI, does not exist - * @throws ProviderNotFoundException - * If a provider supporting the URI scheme is not installed - * @throws SecurityException - * If a security manager is installed and it denies an unspecified - * permission. - */ - public static FileSystem getFileSystem(URI uri) { - String scheme = uri.getScheme(); - for (FileSystemProvider provider: FileSystemProvider.installedProviders()) { - if (scheme.equalsIgnoreCase(provider.getScheme())) { - return provider.getFileSystem(uri); - } - } - throw new ProviderNotFoundException("Provider \"" + scheme + "\" not found"); - } - - /** - * Constructs a new file system that is identified by a {@link URI} - * - * <p> This method iterates over the {@link FileSystemProvider#installedProviders() - * installed} providers to locate the provider that is identified by the URI - * {@link URI#getScheme scheme} of the given URI. URI schemes are compared - * without regard to case. The exact form of the URI is highly provider - * dependent. If found, the provider's {@link FileSystemProvider#newFileSystem(URI,Map) - * newFileSystem(URI,Map)} method is invoked to construct the new file system. - * - * <p> Once a file system is {@link FileSystem#close closed} it is - * provider-dependent if the provider allows a new file system to be created - * with the same URI as a file system it previously created. - * - * <p> <b>Usage Example:</b> - * Suppose there is a provider identified by the scheme {@code "memory"} - * installed: - * <pre> - * Map<String,String> env = new HashMap<String,String>(); - * env.put("capacity", "16G"); - * env.put("blockSize", "4k"); - * FileSystem fs = FileSystems.newFileSystem(URI.create("memory:///?name=logfs"), env); - * </pre> - * - * @param uri - * The URI identifying the file system - * @param env - * A map of provider specific properties to configure the file system; - * may be empty - * - * @return A new file system - * - * @throws IllegalArgumentException - * If the pre-conditions for the {@code uri} parameter aren't met, - * or the {@code env} parameter does not contain properties required - * by the provider, or a property value is invalid - * @throws FileSystemAlreadyExistsException - * If the file system has already been created - * @throws ProviderNotFoundException - * If a provider supporting the URI scheme is not installed - * @throws IOException - * An I/O error occurs creating the file system - * @throws SecurityException - * If a security manager is installed and it denies an unspecified - * permission required by the file system provider implementation - */ - public static FileSystem newFileSystem(URI uri, Map<String,?> env) - throws IOException - { - return newFileSystem(uri, env, null); - } - - /** - * Constructs a new file system that is identified by a {@link URI} - * - * <p> This method first attempts to locate an installed provider in exactly - * the same manner as the {@link #newFileSystem(URI,Map) newFileSystem(URI,Map)} - * method. If none of the installed providers support the URI scheme then an - * attempt is made to locate the provider using the given class loader. If a - * provider supporting the URI scheme is located then its {@link - * FileSystemProvider#newFileSystem(URI,Map) newFileSystem(URI,Map)} is - * invoked to construct the new file system. - * - * @param uri - * The URI identifying the file system - * @param env - * A map of provider specific properties to configure the file system; - * may be empty - * @param loader - * The class loader to locate the provider or {@code null} to only - * attempt to locate an installed provider - * - * @return A new file system - * - * @throws IllegalArgumentException - * If the pre-conditions for the {@code uri} parameter aren't met, - * or the {@code env} parameter does not contain properties required - * by the provider, or a property value is invalid - * @throws FileSystemAlreadyExistsException - * If the URI scheme identifies an installed provider and the file - * system has already been created - * @throws ProviderNotFoundException - * If a provider supporting the URI scheme is not found - * @throws ServiceConfigurationError - * When an error occurs while loading a service provider - * @throws IOException - * An I/O error occurs creating the file system - * @throws SecurityException - * If a security manager is installed and it denies an unspecified - * permission required by the file system provider implementation - */ - public static FileSystem newFileSystem(URI uri, Map<String,?> env, ClassLoader loader) - throws IOException - { - String scheme = uri.getScheme(); - - // check installed providers - for (FileSystemProvider provider: FileSystemProvider.installedProviders()) { - if (scheme.equalsIgnoreCase(provider.getScheme())) { - return provider.newFileSystem(uri, env); - } - } - - // if not found, use service-provider loading facility - if (loader != null) { - ServiceLoader<FileSystemProvider> sl = ServiceLoader - .load(FileSystemProvider.class, loader); - for (FileSystemProvider provider: sl) { - if (scheme.equalsIgnoreCase(provider.getScheme())) { - return provider.newFileSystem(uri, env); - } - } - } - - throw new ProviderNotFoundException("Provider \"" + scheme + "\" not found"); - } - - /** - * Constructs a new {@code FileSystem} to access the contents of a file as a - * file system. - * - * <p> This method makes use of specialized providers that create pseudo file - * systems where the contents of one or more files is treated as a file - * system. The {@code file} parameter is a reference to an existing file - * and the {@code env} parameter is a map of provider specific properties to - * configure the file system. - * - * <p> This method iterates over the {@link FileSystemProvider#installedProviders() - * installed} providers. It invokes, in turn, each provider's {@link - * FileSystemProvider#newFileSystem(FileRef,Map) newFileSystem(FileRef,Map)} method. - * If a provider returns a file system then the iteration terminates - * and the file system is returned. If none of the installed providers return - * a {@code FileSystem} then an attempt is made to locate the provider using - * the given class loader. If a provider returns a file system then the lookup - * terminates and the file system is returned. - * - * @param file - * A reference to a file - * @param env - * A map of provider specific properties to configure the file system; - * may be empty - * @param loader - * The class loader to locate the provider or {@code null} to only - * attempt to locate an installed provider - * - * @return A new file system - * - * @throws IllegalArgumentException - * If the {@code env} parameter does not contain properties required - * by the provider, or a property value is invalid - * @throws ProviderNotFoundException - * If a provider supporting this file type cannot be located - * @throws ServiceConfigurationError - * When an error occurs while loading a service provider - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * If a security manager is installed and it denies an unspecified - * permission. - */ - public static FileSystem newFileSystem(FileRef file, - Map<String,?> env, - ClassLoader loader) - throws IOException - { - if (file == null) - throw new NullPointerException(); - - // check installed providers - for (FileSystemProvider provider: FileSystemProvider.installedProviders()) { - try { - return provider.newFileSystem(file, env); - } catch (UnsupportedOperationException uoe) { - } - } - - // if not found, use service-provider loading facility - if (loader != null) { - ServiceLoader<FileSystemProvider> sl = ServiceLoader - .load(FileSystemProvider.class, loader); - for (FileSystemProvider provider: sl) { - try { - return provider.newFileSystem(file, env); - } catch (UnsupportedOperationException uoe) { - } - } - } - - throw new ProviderNotFoundException("Provider not found"); - } -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/FileTreeWalker.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,247 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file; - -import java.io.IOException; -import java.util.*; - -import org.classpath.icedtea.java.nio.file.attribute.Attributes; -import org.classpath.icedtea.java.nio.file.attribute.BasicFileAttributes; - -/** - * Simple file tree walker that works in a similar manner to nftw(3C). - * - * @see Files#walkFileTree - */ - -class FileTreeWalker { - private final boolean followLinks; - private final boolean detectCycles; - private final LinkOption[] linkOptions; - private final FileVisitor<? super Path> visitor; - - FileTreeWalker(Set<FileVisitOption> options, FileVisitor<? super Path> visitor) { - boolean fl = false; - boolean dc = false; - for (FileVisitOption option: options) { - switch (option) { - case FOLLOW_LINKS : fl = true; break; - case DETECT_CYCLES : dc = true; break; - default: - if (option == null) - throw new NullPointerException("Visit options contains 'null'"); - throw new AssertionError("Should not get here"); - } - } - this.followLinks = fl; - this.detectCycles = fl | dc; - this.linkOptions = (fl) ? new LinkOption[0] : - new LinkOption[] { LinkOption.NOFOLLOW_LINKS }; - this.visitor = visitor; - } - - /** - * Walk file tree starting at the given file - */ - void walk(Path start, int maxDepth) { - FileVisitResult result = walk(start, - maxDepth, - new ArrayList<AncestorDirectory>()); - if (result == null) { - throw new NullPointerException("Visitor returned 'null'"); - } - } - - /** - * @param file - * The directory to visit - * @param path - * list of directories that is relative path from starting file - * @param depth - * Depth remaining - * @param ancestors - * use when cycle detection is enabled - */ - private FileVisitResult walk(Path file, - int depth, - List<AncestorDirectory> ancestors) - { - // depth check - if (depth-- < 0) - return FileVisitResult.CONTINUE; - - BasicFileAttributes attrs = null; - IOException exc = null; - - // attempt to get attributes of file. If fails and we are following - // links then a link target might not exist so get attributes of link - try { - try { - attrs = Attributes.readBasicFileAttributes(file, linkOptions); - } catch (IOException x1) { - if (followLinks) { - try { - attrs = Attributes - .readBasicFileAttributes(file, LinkOption.NOFOLLOW_LINKS); - } catch (IOException x2) { - exc = x2; - } - } else { - exc = x1; - } - } - } catch (SecurityException x) { - return FileVisitResult.CONTINUE; - } - - // unable to get attributes of file - if (exc != null) { - return visitor.visitFileFailed(file, exc); - } - - // file is not a directory so invoke visitFile method - if (!attrs.isDirectory()) { - return visitor.visitFile(file, attrs); - } - - // check for cycles - if (detectCycles) { - Object key = attrs.fileKey(); - - // if this directory and ancestor has a file key then we compare - // them; otherwise we use less efficient isSameFile test. - for (AncestorDirectory ancestor: ancestors) { - Object ancestorKey = ancestor.fileKey(); - if (key != null && ancestorKey != null) { - if (key.equals(ancestorKey)) { - // cycle detected - return visitor.visitFile(file, attrs); - } - } else { - try { - if (file.isSameFile(ancestor.file())) { - // cycle detected - return visitor.visitFile(file, attrs); - } - } catch (IOException x) { - // ignore - } catch (SecurityException x) { - // ignore - } - } - } - - ancestors.add(new AncestorDirectory(file, key)); - } - - // visit directory - try { - DirectoryStream<Path> stream = null; - FileVisitResult result; - - // open the directory - try { - stream = file.newDirectoryStream(); - } catch (IOException x) { - return visitor.preVisitDirectoryFailed(file, x); - } catch (SecurityException x) { - // ignore, as per spec - return FileVisitResult.CONTINUE; - } - - // the exception notified to the postVisitDirectory method - IOException ioe = null; - - // invoke preVisitDirectory and then visit each entry - try { - result = visitor.preVisitDirectory(file); - if (result != FileVisitResult.CONTINUE) { - return result; - } - - // if an I/O occurs during iteration then a CME is thrown. We - // need to distinguish this from a CME thrown by the visitor. - boolean inAction = false; - - try { - for (Path entry: stream) { - inAction = true; - result = walk(entry, depth, ancestors); - inAction = false; - - // returning null will cause NPE to be thrown - if (result == null || result == FileVisitResult.TERMINATE) - return result; - - // skip remaining siblings in this directory - if (result == FileVisitResult.SKIP_SIBLINGS) - break; - } - } catch (ConcurrentModificationException x) { - // if CME thrown because the iteration failed then remember - // the IOException so that it is notified to postVisitDirectory - if (!inAction) { - // iteration failed - Throwable t = x.getCause(); - if (t instanceof IOException) - ioe = (IOException)t; - } - if (ioe == null) - throw x; - } - } finally { - try { - stream.close(); - } catch (IOException x) { } - } - - // invoke postVisitDirectory last - return visitor.postVisitDirectory(file, ioe); - - } finally { - // remove key from trail if doing cycle detection - if (detectCycles) { - ancestors.remove(ancestors.size()-1); - } - } - } - - private static class AncestorDirectory { - private final FileRef dir; - private final Object key; - AncestorDirectory(FileRef dir, Object key) { - this.dir = dir; - this.key = key; - } - FileRef file() { - return dir; - } - Object fileKey() { - return key; - } - } -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/FileVisitOption.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,46 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file; - -/** - * Defines the file tree traversal options. - * - * @since 1.7 - * - * @see Files#walkFileTree - */ - -public enum FileVisitOption { - /** - * Follow symbolic links. - */ - FOLLOW_LINKS, - /** - * Detect cycles in the file tree. - */ - DETECT_CYCLES; -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/FileVisitResult.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,63 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file; - -/** - * The result type of a {@link FileVisitor FileVisitor}. - * - * @since 1.7 - * - * @see Files#walkFileTree - */ - -public enum FileVisitResult { - /** - * Continue. When returned from a {@link FileVisitor#preVisitDirectory - * preVisitDirectory} method then the entries in the directory should also - * be visited. - */ - CONTINUE, - /** - * Terminate. - */ - TERMINATE, - /** - * Continue without visiting the entries in this directory. This result - * is only meaningful when returned from the {@link - * FileVisitor#preVisitDirectory preVisitDirectory} method; otherwise - * this result type is the same as returning {@link #CONTINUE}. - */ - SKIP_SUBTREE, - /** - * Continue without visiting the <em>siblings</em> of this file or directory. - * If returned from the {@link FileVisitor#preVisitDirectory - * preVisitDirectory} method then the entries in the directory are also - * skipped and the {@link FileVisitor#postVisitDirectory postVisitDirectory} - * method is not invoked. - */ - SKIP_SIBLINGS; -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/FileVisitor.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,177 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file; - -import java.io.IOException; - -import org.classpath.icedtea.java.nio.file.attribute.BasicFileAttributes; - -/** - * A visitor of files. An implementation of this interface is provided to the - * {@link Files#walkFileTree walkFileTree} utility method to visit each file - * in a tree. - * - * <p> <b>Usage Examples:</b> - * Suppose we want to delete a file tree. In that case, each directory should - * be deleted after the entries in the directory are deleted. - * <pre> - * Path start = ... - * Files.walkFileTree(start, new SimpleFileVisitor<Path>() { - * @Override - * public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { - * try { - * file.delete(false); - * } catch (IOException exc) { - * // failed to delete - * } - * return FileVisitResult.CONTINUE; - * } - * @Override - * public FileVisitResult postVisitDirectory(Path dir, IOException e) { - * if (e == null) { - * try { - * dir.delete(false); - * } catch (IOException exc) { - * // failed to delete - * } - * } else { - * // directory iteration failed - * } - * return FileVisitResult.CONTINUE; - * } - * }); - * </pre> - * <p> Furthermore, suppose we want to copy a file tree rooted at a source - * directory to a target location. In that case, symbolic links should be - * followed and the target directory should be created before the entries in - * the directory are copied. - * <pre> - * final Path source = ... - * final Path target = ... - * - * Files.walkFileTree(source, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, - * new SimpleFileVisitor<Path>() { - * @Override - * public FileVisitResult preVisitDirectory(Path dir) { - * try { - * dir.copyTo(target.resolve(source.relativize(dir))); - * } catch (FileAlreadyExistsException e) { - * // ignore - * } catch (IOException e) { - * // copy failed, skip rest of directory and descendants - * return SKIP_SUBTREE; - * } - * return CONTINUE; - * } - * @Override - * public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { - * try { - * file.copyTo(target.resolve(source.relativize(file))); - * } catch (IOException e) { - * // copy failed - * } - * return CONTINUE; - * } - * }); - * </pre> - * - * @since 1.7 - */ - -public interface FileVisitor<T extends FileRef> { - - /** - * Invoked for a directory before entries in the directory are visited. - * - * <p> If this method returns {@link FileVisitResult#CONTINUE CONTINUE}, - * then entries in the directory are visited. If this method returns {@link - * FileVisitResult#SKIP_SUBTREE SKIP_SUBTREE} or {@link - * FileVisitResult#SKIP_SIBLINGS SKIP_SIBLINGS} then entries in the - * directory (and any descendants) will not be visited. - * - * @param dir - * A reference to the directory - * - * @return the visit result - */ - FileVisitResult preVisitDirectory(T dir); - - /** - * Invoked for a directory that could not be opened. - * - * @param dir - * A reference to the directory - * @param exc - * The I/O exception thrown from the attempt to open the directory - * - * @return the visit result - */ - FileVisitResult preVisitDirectoryFailed(T dir, IOException exc); - - /** - * Invoked for a file in a directory. - * - * @param file - * A reference to the file - * @param attrs - * The file's basic attributes - * - * @return the visit result - */ - FileVisitResult visitFile(T file, BasicFileAttributes attrs); - - /** - * Invoked for a file when its basic file attributes could not be read. - * - * @param file - * A reference to the file - * @param exc - * The I/O exception thrown from the attempt to read the file - * attributes - * - * @return the visit result - */ - FileVisitResult visitFileFailed(T file, IOException exc); - - /** - * Invoked for a directory after entries in the directory, and all of their - * descendants, have been visited. This method is also invoked when iteration - * of the directory completes prematurely (by a {@link #visitFile visitFile} - * method returning {@link FileVisitResult#SKIP_SIBLINGS SKIP_SIBLINGS}, - * or an I/O error when iterating over the directory). - * - * @param dir - * A reference to the directory - * @param exc - * {@code null} if the iteration of the directory completes without - * an error; otherwise the I/O exception that caused the iteration - * of the directory to complete prematurely - * - * @return the visit result - */ - FileVisitResult postVisitDirectory(T dir, IOException exc); -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/Files.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,405 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file; - -import java.io.IOException; -import java.util.*; -import java.security.AccessController; -import java.security.PrivilegedAction; - -import org.classpath.icedtea.java.nio.file.spi.FileTypeDetector; - -/** - * Utility methods for files and directories. - * - * @since 1.7 - */ - -public final class Files { - private Files() { } - - // lazy loading of default and installed file type detectors - private static class LazyInitialization { - static final FileTypeDetector defaultFileTypeDetector = - sun.nio.fs.DefaultFileTypeDetector.create(); - static final List<FileTypeDetector> installeDetectors = - loadInstalledDetectors(); - - // loads all installed file type detectors - private static List<FileTypeDetector> loadInstalledDetectors() { - return AccessController - .doPrivileged(new PrivilegedAction<List<FileTypeDetector>>() { - public List<FileTypeDetector> run() { - List<FileTypeDetector> list = new ArrayList<FileTypeDetector>(); - ServiceLoader<FileTypeDetector> loader = ServiceLoader - .load(FileTypeDetector.class, ClassLoader.getSystemClassLoader()); - for (FileTypeDetector detector: loader) { - list.add(detector); - } - return list; - }}); - } - } - - /** - * Probes the content type of a file. - * - * <p> This method uses the installed {@link FileTypeDetector} implementations - * to probe the given file to determine its content type. Each file type - * detector's {@link FileTypeDetector#probeContentType probeContentType} is - * invoked, in turn, to probe the file type. If the file is recognized then - * the content type is returned. If the file is not recognized by any of the - * installed file type detectors then a system-default file type detector is - * invoked to guess the content type. - * - * <p> A given invocation of the Java virtual machine maintains a system-wide - * list of file type detectors. Installed file type detectors are loaded - * using the service-provider loading facility defined by the {@link ServiceLoader} - * class. Installed file type detectors are loaded using the system class - * loader. If the system class loader cannot be found then the extension class - * loader is used; If the extension class loader cannot be found then the - * bootstrap class loader is used. File type detectors are typically installed - * by placing them in a JAR file on the application class path or in the - * extension directory, the JAR file contains a provider-configuration file - * named {@code java.nio.file.spi.FileTypeDetector} in the resource directory - * {@code META-INF/services}, and the file lists one or more fully-qualified - * names of concrete subclass of {@code FileTypeDetector } that have a zero - * argument constructor. If the process of locating or instantiating the - * installed file type detectors fails then an unspecified error is thrown. - * The ordering that installed providers are located is implementation - * specific. - * - * <p> The return value of this method is the string form of the value of a - * Multipurpose Internet Mail Extension (MIME) content type as - * defined by <a href="http://www.ietf.org/rfc/rfc2045.txt"><i>RFC 2045: - * Multipurpose Internet Mail Extensions (MIME) Part One: Format of Internet - * Message Bodies</i></a>. The string is guaranteed to be parsable according - * to the grammar in the RFC. - * - * @param file - * The file reference - * - * @return The content type of the file, or {@code null} if the content - * type cannot be determined - * - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * If a security manager is installed and it denies an unspecified - * permission required by a file type detector implementation. - * - * @see DirectoryStreamFilters#newContentTypeFilter - */ - public static String probeContentType(FileRef file) - throws IOException - { - // try installed file type detectors - for (FileTypeDetector detector: LazyInitialization.installeDetectors) { - String result = detector.probeContentType(file); - if (result != null) - return result; - } - - // fallback to default - return LazyInitialization.defaultFileTypeDetector.probeContentType(file); - } - - /** - * Invokes a {@link FileAction} for each entry in a directory accepted - * by a given {@link java.nio.file.DirectoryStream.Filter filter}. - * - * <p> This method opens the given directory and invokes the file action's - * {@link FileAction#invoke invoke} method for each entry accepted by the - * filter. When iteration is completed then the directory is closed. If the - * {@link DirectoryStream#close close} method throws an {@code IOException} - * then it is silently ignored. - * - * <p> If the {@code FileAction}'s {@code invoke} method terminates due - * to an uncaught {@link IOException}, {@code Error} or {@code RuntimeException} - * then the exception is propagated by this method after closing the - * directory. - * - * @param dir - * The directory - * @param filter - * The filter, or {@code null} to accept all entries - * @param action - * The {@code FileAction} to invoke for each accepted entry - * - * @throws NotDirectoryException - * If the {@code dir} parameter is not a directory <i>(optional - * specific exception)</i> - * @throws IOException - * If an I/O error occurs or the {@code invoke} method terminates - * due to an uncaught {@code IOException} - * @throws SecurityException - * In the case of the default provider, the {@link - * SecurityManager#checkRead(String) checkRead} method is invoked - * to check read access to the directory. - */ - public static void withDirectory(Path dir, - DirectoryStream.Filter<? super Path> filter, - FileAction<? super Path> action) - throws IOException - { - // explicit null check required in case directory is empty - if (action == null) - throw new NullPointerException(); - - DirectoryStream<Path> stream = dir.newDirectoryStream(filter); - try { - // set to true when invoking the action so as to distinguish a - // CME thrown by the iteration from a CME thrown by the invoke - boolean inAction = false; - try { - for (Path entry: stream) { - inAction = true; - action.invoke(entry); - inAction = false; - } - } catch (ConcurrentModificationException cme) { - if (!inAction) { - Throwable cause = cme.getCause(); - if (cause instanceof IOException) - throw (IOException)cause; - } - throw cme; - } - } finally { - try { - stream.close(); - } catch (IOException x) { } - } - } - - /** - * Invokes a {@link FileAction} for each entry in a directory with a - * file name that matches a given pattern. - * - * <p> This method opens the given directory and invokes the file action's - * {@link FileAction#invoke invoke} method for each entry that matches the - * given pattern. When iteration is completed then the directory is closed. - * If the {@link DirectoryStream#close close} method throws an {@code - * IOException} then it is silently ignored. - * - * <p> If the {@code FileAction}'s {@code invoke} method terminates due - * to an uncaught {@link IOException}, {@code Error} or {@code RuntimeException} - * then the exception is propagated by this method after closing the - * directory. - * - * <p> The globbing pattern language supported by this method is as - * specified by the {@link FileSystem#getNameMatcher getNameMatcher} method. - * - * @param dir - * The directory - * @param glob - * The globbing pattern - * @param action - * The {@code FileAction} to invoke for each entry - * - * @throws NotDirectoryException - * If the {@code dir} parameter is not a directory <i>(optional - * specific exception)</i> - * @throws IOException - * If an I/O error occurs or the {@code invoke} method terminates - * due to an uncaught {@code IOException} - * @throws SecurityException - * In the case of the default provider, the {@link - * SecurityManager#checkRead(String) checkRead} method is invoked - * to check read access to the directory. - */ - public static void withDirectory(Path dir, - String glob, - FileAction<? super Path> action) - throws IOException - { - final PathMatcher matcher = dir.getFileSystem().getNameMatcher("glob", glob); - DirectoryStream.Filter<Path> filter = new DirectoryStream.Filter<Path>() { - - public boolean accept(Path entry) { - return matcher.matches(entry.getName()); - } - }; - withDirectory(dir, filter, action); - } - - /** - * Invokes a {@link FileAction} for all entries in a directory. - * - * <p> This method works as if invoking it were equivalent to evaluating the - * expression: - * <blockquote><pre> - * withDirectory(dir, "*", action) - * </pre></blockquote> - * - * @param dir - * The directory - * @param action - * The {@code FileAction} to invoke for each entry - * - * @throws NotDirectoryException - * If the {@code dir} parameter is not a directory <i>(optional - * specific exception)</i> - * @throws IOException - * If an I/O error occurs or the {@code invoke} method terminates - * due to an uncaught {@code IOException} - * @throws SecurityException - * In the case of the default provider, the {@link - * SecurityManager#checkRead(String) checkRead} method is invoked - * to check read access to the directory. - */ - public static void withDirectory(Path dir, FileAction<? super Path> action) - throws IOException - { - withDirectory(dir, "*", action); - } - - /** - * Walks a file tree. - * - * <p> This method walks a file tree rooted at a given starting file. The - * file tree traversal is <em>depth-first</em> with the given {@link - * FileVisitor} invoked for each file encountered. File tree traversal - * completes when all accessible files in the tree have been visited, a - * visitor returns a result of {@link FileVisitResult#TERMINATE TERMINATE}, - * or the visitor terminates due to an uncaught {@code Error} or {@code - * RuntimeException}. - * - * <p> For each file encountered this method attempts to gets its {@link - * java.nio.file.attribute.BasicFileAttributes}. If the file is not a - * directory then the {@link FileVisitor#visitFile visitFile} method is - * invoked with the file attributes. If the file attributes cannot be read, - * due to an I/O exception, then the {@link FileVisitor#visitFileFailed - * visitFileFailed} method is invoked with the I/O exception. - * - * <p> Where the file is a directory, this method attempts to open it by - * invoking its {@link Path#newDirectoryStream newDirectoryStream} method. - * Where the directory could not be opened, due to an {@code IOException}, - * then the {@link FileVisitor#preVisitDirectoryFailed preVisitDirectoryFailed} - * method is invoked with the I/O exception, after which, the file tree walk - * continues, by default, at the next <em>sibling</em> of the directory. - * - * <p> Where the directory is opened successfully, then the entries in the - * directory, and their <em>descendants</em> are visited. When all entries - * have been visited, or an I/O error occurs during iteration of the - * directory, then the directory is closed and the visitor's {@link - * FileVisitor#postVisitDirectory postVisitDirectory} method is invoked. - * The file tree walk then continues, by default, at the next <em>sibling</em> - * of the directory. - * - * <p> By default, symbolic links are not automatically followed by this - * method. If the {@code options} parameter contains the {@link - * FileVisitOption#FOLLOW_LINKS FOLLOW_LINKS} option then symbolic links are - * followed. When following links, and the attributes of the target cannot - * be read, then this method attempts to get the {@code BasicFileAttributes} - * of the link. If they can be read then the {@code visitFile} method is - * invoked with the attributes of the link (otherwise the {@code visitFileFailed} - * method is invoked as specified above). - * - * <p> If the {@code options} parameter contains the {@link - * FileVisitOption#DETECT_CYCLES DETECT_CYCLES} or {@link - * FileVisitOption#FOLLOW_LINKS FOLLOW_LINKS} options then this method keeps - * track of directories visited so that cycles can be detected. A cycle - * arises when there is an entry in a directory that is an ancestor of the - * directory. Cycle detection is done by recording the {@link - * java.nio.file.attribute.BasicFileAttributes#fileKey file-key} of directories, - * or if file keys are not available, by invoking the {@link FileRef#isSameFile - * isSameFile} method to test if a directory is the same file as an - * ancestor. When a cycle is detected the {@link FileVisitor#visitFile - * visitFile} is invoked with the attributes of the directory. The {@link - * java.nio.file.attribute.BasicFileAttributes#isDirectory isDirectory} - * method may be used to test if the file is a directory and that a cycle is - * detected. The {@code preVisitDirectory} and {@code postVisitDirectory} - * methods are not invoked. - * - * <p> The {@code maxDepth} parameter is the maximum number of levels of - * directories to visit. A value of {@code 0} means that only the starting - * file is visited, unless denied by the security manager. A value of - * {@link Integer#MAX_VALUE MAX_VALUE} may be used to indicate that all - * levels should be visited. - * - * <p> If a visitor returns a result of {@code null} then {@code - * NullPointerException} is thrown. - * - * <p> When a security manager is installed and it denies access to a file - * (or directory), then it is ignored and the visitor is not invoked for - * that file (or directory). - * - * @param start - * The starting file - * @param options - * Options to configure the traversal - * @param maxDepth - * The maximum number of directory levels to visit - * @param visitor - * The file visitor to invoke for each file - * - * @throws IllegalArgumentException - * If the {@code maxDepth} parameter is negative - * @throws SecurityException - * If the security manager denies access to the starting file. - * In the case of the default provider, the {@link - * SecurityManager#checkRead(String) checkRead} method is invoked - * to check read access to the directory. - */ - public static void walkFileTree(Path start, - Set<FileVisitOption> options, - int maxDepth, - FileVisitor<? super Path> visitor) - { - if (maxDepth < 0) - throw new IllegalArgumentException("'maxDepth' is negative"); - new FileTreeWalker(options, visitor).walk(start, Integer.MAX_VALUE); - } - - /** - * Walks a file tree. - * - * <p> This method works as if invoking it were equivalent to evaluating the - * expression: - * <blockquote><pre> - * walkFileTree(start, EnumSet.noneOf(FileVisitOption.class), Integer.MAX_VALUE, visitor) - * </pre></blockquote> - * - * @param start - * The starting file - * @param visitor - * The file visitor to invoke for each file - * - * @throws SecurityException - * If the security manager denies access to the starting file. - * In the case of the default provider, the {@link - * SecurityManager#checkRead(String) checkRead} method is invoked - * to check read access to the directory. - */ - public static void walkFileTree(Path start, FileVisitor<? super Path> visitor) { - walkFileTree(start, - EnumSet.noneOf(FileVisitOption.class), - Integer.MAX_VALUE, - visitor); - } -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/InvalidPathException.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,131 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file; - -/** - * Unchecked exception thrown when path string cannot be converted into a - * {@link Path} because the path string contains invalid characters, or - * the path string is invalid for other file system specific reasons. - */ - -public class InvalidPathException - extends IllegalArgumentException -{ - static final long serialVersionUID = 4355821422286746137L; - - private String input; - private int index; - - /** - * Constructs an instance from the given input string, reason, and error - * index. - * - * @param input The input string - * @param reason A string explaining why the input was rejected - * @param index The index at which the error occurred, - * or <tt>-1</tt> if the index is not known - * - * @throws NullPointerException - * If either the input or reason strings are <tt>null</tt> - * - * @throws IllegalArgumentException - * If the error index is less than <tt>-1</tt> - */ - public InvalidPathException(String input, String reason, int index) { - super(reason); - if ((input == null) || (reason == null)) - throw new NullPointerException(); - if (index < -1) - throw new IllegalArgumentException(); - this.input = input; - this.index = index; - } - - /** - * Constructs an instance from the given input string and reason. The - * resulting object will have an error index of <tt>-1</tt>. - * - * @param input The input string - * @param reason A string explaining why the input was rejected - * - * @throws NullPointerException - * If either the input or reason strings are <tt>null</tt> - */ - public InvalidPathException(String input, String reason) { - this(input, reason, -1); - } - - /** - * Returns the input string. - * - * @return The input string - */ - public String getInput() { - return input; - } - - /** - * Returns a string explaining why the input string was rejected. - * - * @return The reason string - */ - public String getReason() { - return super.getMessage(); - } - - /** - * Returns an index into the input string of the position at which the - * error occurred, or <tt>-1</tt> if this position is not known. - * - * @return The error index - */ - public int getIndex() { - return index; - } - - /** - * Returns a string describing the error. The resulting string - * consists of the reason string followed by a colon character - * (<tt>':'</tt>), a space, and the input string. If the error index is - * defined then the string <tt>" at index "</tt> followed by the index, in - * decimal, is inserted after the reason string and before the colon - * character. - * - * @return A string describing the error - */ - public String getMessage() { - StringBuffer sb = new StringBuffer(); - sb.append(getReason()); - if (index > -1) { - sb.append(" at index "); - sb.append(index); - } - sb.append(": "); - sb.append(input); - return sb.toString(); - } -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/LinkOption.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,44 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file; - -/** - * Defines the options as to how symbolic links are handled. - * - * @since 1.7 - */ - -public enum LinkOption implements OpenOption, CopyOption { - /** - * Do not follow symbolic links. - * - * @see FileRef#getFileAttributeView(Class,LinkOption[]) - * @see Path#copyTo - * @see SecureDirectoryStream#newByteChannel - */ - NOFOLLOW_LINKS; -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/LinkPermission.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,108 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file; - -import java.security.BasicPermission; - -/** - * The {@code Permission} class for link creation operations. - * - * <p> The following table provides a summary description of what the permission - * allows, and discusses the risks of granting code the permission. - * - * <table border=1 cellpadding=5 - * summary="Table shows permission target name, what the permission allows, and associated risks"> - * <tr> - * <th>Permission Target Name</th> - * <th>What the Permission Allows</th> - * <th>Risks of Allowing this Permission</th> - * </tr> - * <tr> - * <td>hard</td> - * <td> Ability to add an existing file to a directory. This is sometimes - * known as creating a link, or hard link. </td> - * <td> Extreme care should be taken when granting this permission. It allows - * linking to any file or directory in the file system thus allowing the - * attacker to access to all files. </td> - * </tr> - * <tr> - * <td>symbolic</td> - * <td> Ability to create symbolic links. </td> - * <td> Extreme care should be taken when granting this permission. It allows - * linking to any file or directory in the file system thus allowing the - * attacker to access to all files. </td> - * </tr> - * </table> - * - * @since 1.7 - * - * @see Path#createLink - * @see Path#createSymbolicLink - */ -public final class LinkPermission extends BasicPermission { - static final long serialVersionUID = -1441492453772213220L; - - private void checkName(String name) { - if (!name.equals("hard") && !name.equals("symbolic")) { - throw new IllegalArgumentException("name: " + name); - } - } - - /** - * Constructs a {@code LinkPermission} with the specified name. - * - * @param name - * The name of the permission. It must be "hard" or "symbolic". - * - * @throws IllegalArgumentException - * If name is empty or invalid. - */ - public LinkPermission(String name) { - super(name); - checkName(name); - } - - /** - * Constructs a {@code LinkPermission} with the specified name. - * - * @param name - * The name of the permission; must be "hard" or "symbolic". - * @param actions - * The actions for the permission; must be the empty string or - * {@code null} - * - * @throws IllegalArgumentException - * If name is empty or invalid. - */ - public LinkPermission(String name, String actions) { - super(name); - checkName(name); - if (actions != null && actions.length() > 0) { - throw new IllegalArgumentException("actions: " + actions); - } - } -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/NoSuchFileException.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,64 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file; - -/** - * Checked exception thrown when an attempt is made to access a file that does - * not exist. - * - * @since 1.7 - */ - -public class NoSuchFileException - extends FileSystemException -{ - static final long serialVersionUID = -1390291775875351931L; - - /** - * Constructs an instance of this class. - * - * @param file - * A string identifying the file or {@code null} if not known. - */ - public NoSuchFileException(String file) { - super(file); - } - - /** - * Constructs an instance of this class. - * - * @param file - * A string identifying the file or {@code null} if not known. - * @param other - * A string identifying the other file or {@code null} if not known. - * @param reason - * A reason message with additional information or {@code null} - */ - public NoSuchFileException(String file, String other, String reason) { - super(file, other, reason); - } -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/NotDirectoryException.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,50 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file; - -/** - * Checked exception thrown when a file system operation, intended for a - * directory, fails because the file is not a directory. - * - * @since 1.7 - */ - -public class NotDirectoryException - extends FileSystemException -{ - private static final long serialVersionUID = -9011457427178200199L; - - /** - * Constructs an instance of this class. - * - * @param file - * A string identifying the file or {@code null} if not known. - */ - public NotDirectoryException(String file) { - super(file); - } -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/NotLinkException.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,64 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file; - -/** - * Checked exception thrown when a file system operation fails because a file - * is not a link. - * - * @since 1.7 - */ - -public class NotLinkException - extends FileSystemException -{ - static final long serialVersionUID = -388655596416518021L; - - /** - * Constructs an instance of this class. - * - * @param file - * A string identifying the file or {@code null} if not known. - */ - public NotLinkException(String file) { - super(file); - } - - /** - * Constructs an instance of this class. - * - * @param file - * A string identifying the file or {@code null} if not known. - * @param other - * A string identifying the other file or {@code null} if not known. - * @param reason - * A reason message with additional information or {@code null} - */ - public NotLinkException(String file, String other, String reason) { - super(file, other, reason); - } -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/OpenOption.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,46 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file; - -/** - * An object that configures how to open or create a file. - * - * <p> Objects of this type are used by methods such as {@link - * Path#newOutputStream(OpenOption[]) newOutputStream}, {@link - * FileRef#newByteChannel newByteChannel}, {@link - * java.nio.channels.FileChannel#open FileChannel.open}, and {@link - * java.nio.channels.AsynchronousFileChannel#open AsynchronousFileChannel.open} - * when opening or creating a file. - * - * <p> The {@link StandardOpenOption} enumeration type defines the - * <i>standard</i> options. - * - * @since 1.7 - */ - -public interface OpenOption { -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/Path.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,1575 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file; - -import java.nio.channels.*; -import java.io.*; -import java.net.URI; -import java.util.*; - -import org.classpath.icedtea.java.nio.channels.SeekableByteChannel; - -import org.classpath.icedtea.java.nio.file.attribute.FileAttribute; - -/** - * A file reference that locates a file using a system dependent path. The file - * is not required to exist. - * - * <p> On many platforms a <em>path</em> is the means to locate and access files - * in a file system. A path is hierarchical and composed of a sequence of - * directory names separated by a special separator or delimiter. - * - * <h4>Path operations</h4> - * - * <p> A system dependent path represented by this class is conceptually a - * sequence of name elements and optionally a <em>root component</em>. The name - * that is <em>farthest</em> from the root of the directory hierarchy is the - * name of a file or directory. The other elements are directory names. The root - * component typically identifies a file system hierarchy. A {@code Path} can - * represent a root, a root and a sequence of names, or simply one or more name - * elements. It defines the {@link #getName() getName}, {@link #getParent - * getParent}, {@link #getRoot getRoot}, and {@link #subpath subpath} methods - * to access the components or a subsequence of its name elements. - * - * <p> In addition to accessing the components of a path, a {@code Path} also - * defines {@link #resolve(Path) resolve} and {@link #relativize relativize} - * operations. Paths can also be {@link #compareTo compared}, and tested - * against each using using the {@link #startsWith startsWith} and {@link - * #endsWith endWith} methods. - * - * <h4>File operations</h4> - * - * <p> A {@code Path} is either <em>absolute</em> or <em>relative</em>. An - * absolute path is complete in that does not need to be combined with another - * path in order to locate a file. All operations on relative paths are first - * resolved against a file system's default directory as if by invoking the - * {@link #toAbsolutePath toAbsolutePath} method. - * - * <p> In addition to the operations defined by the {@link FileRef} interface, - * this class defines the following operations: - * - * <ul> - * <li><p> Files may be {@link #createFile(FileAttribute[]) created}, or - * directories may be {@link #createDirectory(FileAttribute[]) created}. - * </p></li> - * <li><p> Directories can be {@link #newDirectoryStream opened} so as to - * iterate over the entries in the directory. </p></li> - * <li><p> Files can be {@link #copyTo(Path,CopyOption[]) copied} or - * {@link #moveTo(Path,CopyOption[]) moved}. </p></li> - * <li><p> Symbolic-links may be {@link #createSymbolicLink created}, or the - * target of a link may be {@link #readSymbolicLink read}. </p></li> - * <li><p> {@link #newInputStream InputStream} or {@link #newOutputStream - * OutputStream} streams can be created to allow for interoperation with the - * <a href="../../../java/io/package-summary.html">{@code java.io}</a> package - * where required. </li></p> - * <li><p> The {@link #toRealPath real} path of an existing file may be - * obtained. </li></p> - * </ul> - * - * <p> This class implements {@link Watchable} interface so that a directory - * located by a path can be {@link #register registered} with a {@link WatchService}. - * and entries in the directory watched. - * - * <h4>File attributes</h4> - * - * The <a href="attribute/package-summary.html">{@code java.nio.file.attribute}</a> - * package provides access to file attributes or <em>meta-data</em> associated - * with files. The {@link Attributes Attributes} class defines methods that - * operate on or return file attributes. For example, the file type, size, - * timestamps, and other <em>basic</em> meta-data is obtained, in bulk, by - * invoking the {@link Attributes#readBasicFileAttributes - * Attributes.readBasicFileAttributes} method: - * <pre> - * Path file = ... - * BasicFileAttributes attrs = Attributes.readBasicFileAttributes(file); - * </pre> - * - * <a name="interop"><h4>Interoperability</h4></a> - * - * <p> Paths created by file systems associated with the default {@link - * java.nio.file.spi.FileSystemProvider provider} are generally interoperable - * with the {@link java.io.File java.io.File} class. Paths created by other - * providers are unlikely to be interoperable with the abstract path names - * represented by {@code java.io.File}. The {@link java.io.File#toPath - * File.toPath} method may be used to obtain a {@code Path} from the abstract - * path name represented by a {@code java.io.File java.io.File} object. The - * resulting {@code Path} can be used to operate on the same file as the {@code - * java.io.File} object. - * - * <p> Path objects created by file system's associated with the default - * provider are interoperable with objects created by other file systems created - * by the same provider. Path objects created by file systems associated with - * other providers may not be interoperable with other file systems created by - * the same provider. The reasons for this are provider specific. - * - * <h4>Concurrency</h4></a> - * - * <p> Instances of this class are immutable and safe for use by multiple concurrent - * threads. - * - * @since 1.7 - */ - -public abstract class Path - implements FileRef, Comparable<Path>, Iterable<Path>, Watchable -{ - /** - * Initializes a new instance of this class. - */ - protected Path() { } - - /** - * Returns the file system that created this object. - * - * @return The file system that created this object - */ - public abstract FileSystem getFileSystem(); - - /** - * Tells whether or not this path is absolute. - * - * <p> An absolute path is complete in that it doesn't need to be - * combined with other path information in order to locate a file. - * - * @return {@code true} if, and only if, this path is absolute - */ - public abstract boolean isAbsolute(); - - /** - * Returns the root component of this path as a {@code Path} object, - * or {@code null} if this path does not have a root component. - * - * @return A path representing the root component of this path, - * or {@code null} - */ - public abstract Path getRoot(); - - /** - * Returns the name of the file or directory denoted by this path. The - * file name is the <em>farthest</em> element from the root in the directory - * hierarchy. - * - * @return A path representing the name of the file or directory, or - * {@code null} if this path has zero elements - */ - public abstract Path getName(); - - /** - * Returns the <em>parent path</em>, or {@code null} if this path does not - * have a parent. - * - * <p> The parent of this path object consists of this path's root - * component, if any, and each element in the path except for the - * <em>farthest</em> from the root in the directory hierarchy. This method - * does not access the file system; the path or its parent may not exist. - * Furthermore, this method does not eliminate special names such as "." - * and ".." that may be used in some implementations. On UNIX for example, - * the parent of "{@code /a/b/c}" is "{@code /a/b}", and the parent of - * {@code "x/y/.}" is "{@code x/y}". This method may be used with the {@link - * #normalize normalize} method, to eliminate redundant names, for cases where - * <em>shell-like</em> navigation is required. - * - * <p> If this path has one or more elements, and no root component, then - * this method is equivalent to evaluating the expression: - * <blockquote><pre> - * subpath(0, getNameCount()-1); - * </pre></blockquote> - * - * @return A path representing the path's parent - */ - public abstract Path getParent(); - - /** - * Returns the number of name elements in the path. - * - * @return The number of elements in the path, or {@code 0} if this path - * only represents a root component - */ - public abstract int getNameCount(); - - /** - * Returns a name element of this path. - * - * <p> The {@code index} parameter is the index of the name element to return. - * The element that is <em>closest</em> to the root in the directory hierarchy - * has index {@code 0}. The element that is <em>farthest</em> from the root - * has index {@link #getNameCount count}{@code -1}. - * - * @param index - * The index of the element - * - * @return The name element - * - * @throws IllegalArgumentException - * If {@code index} is negative, {@code index} is greater than or - * equal to the number of elements, or this path has zero name - * elements. - */ - public abstract Path getName(int index); - - /** - * Returns a relative {@code Path} that is a subsequence of the name - * elements of this path. - * - * <p> The {@code beginIndex} and {@code endIndex} parameters specify the - * subsequence of name elements. The name that is <em>closest</em> to the root - * in the directory hierarchy has index {@code 0}. The name that is - * <em>farthest</em> from the root has index {@link #getNameCount - * count}{@code -1}. The returned {@code Path} object has the name elements - * that begin at {@code beginIndex} and extend to the element at index {@code - * endIndex-1}. - * - * @param beginIndex - * The index of the first element, inclusive - * @param endIndex - * The index of the last element, exclusive - * - * @return A new {@code Path} object that is a subsequence of the name - * elements in this {@code Path} - * - * @throws IllegalArgumentException - * If {@code beginIndex} is negative, or greater than or equal to - * the number of elements. If {@code endIndex} is less than or - * equal to {@code beginIndex}, or larger than the number of elements. - */ - public abstract Path subpath(int beginIndex, int endIndex); - - /** - * Tests if this path starts with the given path. - * - * <p> This path <em>starts</em> with the given path if this path's root - * component <em>starts</em> with the root component of the given path, - * and this path starts with the same name elements as the given path. - * If the given path has more name elements than this path then {@code false} - * is returned. - * - * <p> Whether or not the root component of this path starts with the root - * component of the given path is file system specific. If this path does - * not have a root component and the given path has a root component then - * this path does not start with the given path. - * - * @param other - * The given path - * - * @return {@code true} if this path starts with the given path; otherwise - * {@code false} - */ - public abstract boolean startsWith(Path other); - - /** - * Tests if this path ends with the given path. - * - * <p> If the given path has <em>N</em> elements, and no root component, - * and this path has <em>N</em> or more elements, then this path ends with - * the given path if the last <em>N</em> elements of each path, starting at - * the element farthest from the root, are equal. - * - * <p> If the given path has a root component then this path ends with the - * given path if the root component of this path <em>ends with</em> the root - * component of the given path, and the corresponding elements of both paths - * are equal. Whether or not the root component of this path ends with the - * root component of the given path is file system specific. If this path - * does not have a root component and the given path has a root component - * then this path does not end with the given path. - * - * @param other - * The given path - * - * @return {@code true} if this path ends with the given path; otherwise - * {@code false} - */ - public abstract boolean endsWith(Path other); - - /** - * Returns a path that is this path with redundant name elements eliminated. - * - * <p> The precise definition of this method is implementation dependent but - * in general it derives from this path, a path that does not contain - * <em>redundant</em> name elements. In many file systems, the "{@code .}" - * and "{@code ..}" are special names used to indicate the current directory - * and parent directory. In such file systems all occurrences of "{@code .}" - * are considered redundant. If a "{@code ..}" is preceded by a - * non-"{@code ..}" name then both names are considered redundant (the - * process to identify such names is repeated until is it no longer - * applicable). - * - * <p> This method does not access the file system; the path may not locate - * a file that exists. Eliminating "{@code ..}" and a preceding name from a - * path may result in the path that locates a different file than the original - * path. This can arise when the preceding name is a symbolic link. - * - * @return The resulting path, or this path if it does not contain - * redundant name elements, or {@code null} if this path does not - * have a root component and all name elements are redundant. - * - * @see #getParent - * @see #toRealPath - */ - public abstract Path normalize(); - - // -- resolution and relativization -- - - /** - * Resolve the given path against this path. - * - * <p> If the {@code other} parameter is an {@link #isAbsolute() absolute} - * path then this method trivially returns {@code other}. If {@code other} - * is {@code null} then this path is returned. Otherwise this method - * considers this path to be a directory and resolves the given path - * against this path. In the simplest case, the given path does not have - * a {@link #getRoot root} component, in which case this method <em>joins</em> - * the given path to this path and returns a resulting path that {@link - * #endsWith ends} with the given path. Where the given path has a root - * component then resolution is highly implementation dependent and therefore - * unspecified. - * - * @param other - * The path to resolve against this path; can be {@code null} - * - * @return The resulting path - * - * @see #relativize - */ - public abstract Path resolve(Path other); - - /** - * Converts a given path string to a {@code Path} and resolves it against - * this {@code Path} in exactly the manner specified by the {@link - * #resolve(Path) resolve} method. - * - * @param other - * The path string to resolve against this path - * - * @return The resulting path - * - * @throws InvalidPathException - * If the path string cannot be converted to a Path. - * - * @see FileSystem#getPath - */ - public abstract Path resolve(String other); - - /** - * Constructs a relative path between this path and a given path. - * - * <p> Relativization is the inverse of {@link #resolve(Path) resolution}. - * This method attempts to construct a {@link #isAbsolute relative} path - * that when {@link #resolve(Path) resolved} against this path, yields a - * path that locates the same file as the given path. For example, on UNIX, - * if this path is {@code "/a/b"} and the given path is {@code "/a/b/c/d"} - * then the resulting relative path would be {@code "c/d"}. Where this - * path and the given path do not have a {@link #getRoot root} component, - * then a relative path can be constructed. A relative path cannot be - * constructed if only one of the paths have a root component. Where both - * paths have a root component then it is implementation dependent if a - * relative path can be constructed. If this path and the given path are - * {@link #equals equal} then {@code null} is returned. - * - * <p> For any two paths <i>p</i> and <i>q</i>, where <i>q</i> does not have - * a root component, - * <blockquote> - * <i>p</i><tt>.relativize(</tt><i>p</i><tt>.resolve(</tt><i>q</i><tt>)).equals(</tt><i>q</i><tt>)</tt> - * </blockquote> - * - * <p> When symbolic-links are supported, then whether the resulting path, - * when resolved against this path, yields a path that can be used to locate - * the {@link #isSameFile same} file as {@code other} is implementation - * dependent. For example, if this path is {@code "/a/b"} and the given - * path is {@code "/a/x"} then the resulting relative path may be {@code - * "../x"}. If {@code "b"} is a symbolic-link then is implementation - * dependent if {@code "a/b/../x"} would locate the same file as {@code "/a/x"}. - * - * @param other - * The resulting path - * - * @return The resulting relative path, or {@code null} if both paths are - * equal - * - * @throws IllegalArgumentException - * If {@code other} is not a {@code Path} that can be relativized - * against this path - */ - public abstract Path relativize(Path other); - - // -- file operations -- - - /** - * Deletes the file located by this path. - * - * <p> The {@code failIfNotExists} parameter determines how the method - * behaves when the file does not exist. When {@code true}, and the file - * does not exist, then the method fails. When {@code false} then the method - * does not fail. - * - * <p> As with the {@link FileRef#delete delete()} method, an implementation - * may require to examine the file to determine if the file is a directory. - * Consequently this method may not be atomic with respect to other file - * system operations. If the file is a symbolic-link then the link is - * deleted and not the final target of the link. - * - * <p> If the file is a directory then the directory must be empty. In some - * implementations a directory has entries for special files or links that - * are created when the directory is created. In such implementations a - * directory is considered empty when only the special entries exist. - * - * <p> On some operating systems it may not be possible to remove a file when - * it is open and in use by this Java virtual machine or other programs. - * - * @param failIfNotExists - * {@code true} if the method should fail when the file does not - * exist - * - * @throws NoSuchFileException - * If the value of the {@code failIfNotExists} is {@code true} and - * the file does not exist <i>(optional specific exception)</i> - * @throws DirectoryNotEmptyException - * If the file is a directory and could not otherwise be deleted - * because the directory is not empty <i>(optional specific - * exception)</i> - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * In the case of the default provider, and a security manager is - * installed, the {@link SecurityManager#checkDelete(String)} method - * is invoked to check delete access to the file - */ - public abstract void delete(boolean failIfNotExists) throws IOException; - - /** - * Creates a symbolic link to a target <i>(optional operation)</i>. - * - * <p> The {@code target} parameter is the target of the link. It may be an - * {@link Path#isAbsolute absolute} or relative path and may not exist. When - * the target is a relative path then file system operations on the resulting - * link are relative to the path of the link. - * - * <p> The {@code attrs} parameter is an optional array of {@link FileAttribute - * attributes} to set atomically when creating the link. Each attribute is - * identified by its {@link FileAttribute#name name}. If more than one attribute - * of the same name is included in the array then all but the last occurrence - * is ignored. - * - * <p> Where symbolic links are supported, but the underlying {@link FileStore} - * does not support symbolic links, then this may fail with an {@link - * IOException}. Additionally, some operating systems may require that the - * Java virtual machine be started with implementation specific privileges to - * create symbolic links, in which case this method may throw {@code IOException}. - * - * @param target - * The target of the link - * @param attrs - * The array of attributes to set atomically when creating the - * symbolic link - * - * @return this path - * - * @throws UnsupportedOperationException - * If the implementation does not support symbolic links or the - * array contains an attribute that cannot be set atomically when - * creating the symbolic link - * @throws FileAlreadyExistsException - * If a file with the name already exists <i>(optional specific - * exception)</i> - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * In the case of the the default provider, and a security manager - * is installed, it denies {@link LinkPermission}<tt>("symbolic")</tt> - * or its {@link SecurityManager#checkWrite(String) checkWrite} - * method denies write access to the path of the symbolic link. - */ - public abstract Path createSymbolicLink(Path target, FileAttribute<?>... attrs) - throws IOException; - - /** - * Creates a new link (directory entry) for an existing file <i>(optional - * operation)</i>. - * - * <p> This path locates the directory entry to create. The {@code existing} - * parameter is the path to an existing file. This method creates a new - * directory entry for the file so that it can be accessed using this path. - * On some file systems this is known as creating a "hard link". Whether the - * file attributes are maintained for the file or for each directory entry - * is file system specific and therefore not specified. Typically, a file - * system requires that all links (directory entries) for a file be on the - * same file system. Furthermore, on some platforms, the Java virtual machine - * may require to be started with implementation specific privileges to - * create hard links or to create links to directories. - * - * @param existing - * A reference to an existing file - * - * @return this path - * - * @throws UnsupportedOperationException - * If the implementation does not support adding an existing file - * to a directory - * @throws FileAlreadyExistsException - * If the entry could not otherwise be created because a file of - * that name already exists <i>(optional specific exception)</i> - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * In the case of the the default provider, and a security manager - * is installed, it denies {@link LinkPermission}<tt>("hard")</tt> - * or its {@link SecurityManager#checkWrite(String) checkWrite} - * method denies write access to both this path and the path of the - * existing file - * - * @see BasicFileAttributes#linkCount - */ - public abstract Path createLink(Path existing) throws IOException; - - /** - * Reads the target of a symbolic link <i>(optional operation)</i>. - * - * <p> If the file system supports <a href="package-summary.html#links">symbolic - * links</a> then this method is used read the target of the link, failing - * if the file is not a link. The target of the link need not exist. The - * returned {@code Path} object will be associated with the same file - * system as this {@code Path}. - * - * @return A {@code Path} object representing the target of the link - * - * @throws UnsupportedOperationException - * If the implementation does not support symbolic links - * @throws NotLinkException - * If the target could otherwise not be read because the file - * is not a link <i>(optional specific exception)</i> - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * In the case of the the default provider, and a security manager - * is installed, it checks that {@code FilePermission} has been - * granted with the "{@code readlink}" action to read the link. - */ - public abstract Path readSymbolicLink() throws IOException; - - /** - * Returns a URI to represent this path. - * - * <p> This method constructs a hierarchical {@link URI} that is absolute - * with a non-empty path component. Its {@link URI#getScheme() scheme} is - * equal to the URI scheme that identifies the provider. The exact form of - * the other URI components is highly provider dependent. In particular, it - * is implementation dependent if its query, fragment, and authority - * components are defined or undefined. - * - * <p> For the default provider the {@link URI#getPath() path} component - * will represent the {@link #toAbsolutePath absolute} path; the query, - * fragment components are undefined. Whether the authority component is - * defined or not is implementation dependent. There is no guarantee that - * the {@code URI} may be used to construct a {@link java.io.File java.io.File}. - * In particular, if this path represents a Universal Naming Convention (UNC) - * path, then the UNC server name may be encoded in the authority component - * of the resulting URI. In the case of the default provider, and the file - * exists, and it can be determined that the file is a directory, then the - * resulting {@code URI} will end with a slash. - * - * <p> The default provider provides a similar <em>round-trip</em> guarantee - * to the {@link java.io.File} class. For a given {@code Path} <i>p</i> it - * is guaranteed that - * <blockquote><tt> - * {@link Paths#get(URI) Paths.get}(</tt><i>p</i><tt>.toUri()).equals(</tt><i>p</i> - * <tt>.{@link #toAbsolutePath() toAbsolutePath}())</tt> - * </blockquote> - * so long as the original {@code Path}, the {@code URI}, and the new {@code - * Path} are all created in (possibly different invocations of) the same - * Java virtual machine. Whether other providers make any guarantees is - * provider specific and therefore unspecified. - * - * <p> When a file system is constructed to access the contents of a file - * as a file system then it is highly implementation specific if the returned - * URI represents the given path in the file system or it represents a - * <em>compound</em> URI that encodes the URI of the enclosing file system. - * A format for compound URIs is not defined in this release; such a scheme - * may be added in a future release. - * - * @return An absolute, hierarchical URI with a non-empty path component - * - * @throws IOError - * If an I/O error occurs obtaining the absolute path, or where a - * file system is constructed to access the contents of a file as - * a file system, the URI of the enclosing file system cannot be - * obtained. - * - * @throws SecurityException - * In the case of the the default provider, and a security manager - * is installed, the {@link #toAbsolutePath toAbsolutePath} method - * throws a security exception. - */ - public abstract URI toUri(); - - /** - * Returns a {@code Path} object representing the absolute path of this - * path. - * - * <p> If this path is already {@link Path#isAbsolute absolute} then this - * method simply returns this path. Otherwise, this method resolves the path - * in an implementation dependent manner, typically by resolving the path - * against a file system default directory. Depending on the implementation, - * this method may throw an I/O error if the file system is not accessible. - * - * @return A {@code Path} object representing the absolute path - * - * @throws IOError - * If an I/O error occurs - * @throws SecurityException - * In the case of the the default provider, and a security manager - * is installed, its {@link SecurityManager#checkPropertyAccess(String) - * checkPropertyAccess} method is invoked to check access to the - * system property {@code user.dir} - */ - public abstract Path toAbsolutePath(); - - /** - * Returns the <em>real</em> path of an existing file. - * - * <p> The precise definition of this method is implementation dependent but - * in general it derives from this path, an {@link #isAbsolute absolute} - * path that locates the {@link #isSameFile same} file as this path, but - * with name elements that represent the actual name of the directories - * and the file. For example, where filename comparisons on a file system - * are case insensitive then the name elements represent the names in their - * actual case. Additionally, the resulting path has redundant name - * elements removed. - * - * <p> If this path is relative then its absolute path is first obtained, - * as if by invoking the {@link #toAbsolutePath toAbsolutePath} method. - * - * <p> The {@code resolveLinks} parameter specifies if symbolic links - * should be resolved. This parameter is ignored when symbolic links are - * not supported. Where supported, and the parameter has the value {@code - * true} then symbolic links are resolved to their final target. Where the - * parameter has the value {@code false} then this method does not resolve - * symbolic links. Some implementations allow special names such as - * "{@code ..}" to refer to the parent directory. When deriving the <em>real - * path</em>, and a "{@code ..}" (or equivalent) is preceded by a - * non-"{@code ..}" name then an implementation will typically causes both - * names to be removed. When not resolving symbolic links and the preceding - * name is a symbolic link then the names are only removed if it guaranteed - * that the resulting path will locate the same file as this path. - * - * @return An absolute path represent the <em>real</em> path of the file - * located by this object - * - * @throws IOException - * If the file does not exist or an I/O error occurs - * @throws SecurityException - * In the case of the the default provider, and a security manager - * is installed, its {@link SecurityManager#checkRead(String) checkRead} - * method is invoked to check read access to the file, and where - * this path is not absolute, its {@link SecurityManager#checkPropertyAccess(String) - * checkPropertyAccess} method is invoked to check access to the - * system property {@code user.dir} - */ - public abstract Path toRealPath(boolean resolveLinks) throws IOException; - - /** - * Copy the file located by this path to a target location. - * - * <p> This method copies the file located by this {@code Path} to the - * target location with the {@code options} parameter specifying how the - * copy is performed. By default, the copy fails if the target file already - * exists, except if the source and target are the {@link #isSameFile same} - * file, in which case this method has no effect. File attributes are not - * required to be copied to the target file. If symbolic links are supported, - * and the file is a link, then the final target of the link is copied. If - * the file is a directory then it creates an empty directory in the target - * location (entries in the directory are not copied). This method can be - * used with the {@link Files#walkFileTree Files.walkFileTree} utility - * method to copy a directory and all entries in the directory, or an entire - * <i>file-tree</i> where required. - * - * <p> The {@code options} parameter is an array of options and may contain - * any of the following: - * - * <table border=1 cellpadding=5 summary=""> - * <tr> <th>Option</th> <th>Description</th> </tr> - * <tr> - * <td> {@link StandardCopyOption#REPLACE_EXISTING REPLACE_EXISTING} </td> - * <td> If the target file exists, then the target file is replaced if it - * is not a non-empty directory. If the target file exists and is a - * symbolic-link then the symbolic-link is replaced (not the target of - * the link. </td> - * </tr> - * <tr> - * <td> {@link StandardCopyOption#COPY_ATTRIBUTES COPY_ATTRIBUTES} </td> - * <td> Attempts to copy the file attributes associated with this file to - * the target file. The exact file attributes that are copied is platform - * and file system dependent and therefore unspecified. Minimally, the - * {@link BasicFileAttributes#lastModifiedTime last-modified-time} is - * copied to the target file. </td> - * </tr> - * <tr> - * <td> {@link LinkOption#NOFOLLOW_LINKS NOFOLLOW_LINKS} </td> - * <td> Symbolic-links are not followed. If the file, located by this path, - * is a symbolic-link then the link is copied rather than the target of - * the link. It is implementation specific if file attributes can be - * copied to the new link. In other words, the {@code COPY_ATTRIBUTES} - * option may be ignored when copying a link. </td> - * </tr> - * </table> - * - * <p> An implementation of this interface may support additional - * implementation specific options. - * - * <p> Copying a file is not an atomic operation. If an {@link IOException} - * is thrown then it possible that the target file is incomplete or some of - * its file attributes have not been copied from the source file. When the - * {@code REPLACE_EXISTING} option is specified and the target file exists, - * then the target file is replaced. The check for the existence of the file - * and the creation of the new file may not be atomic with respect to other - * file system activities. - * - * @param target - * The target location - * @param options - * Options specifying how the copy should be done - * - * @return The target - * - * @throws UnsupportedOperationException - * If the array contains a copy option that is not supported - * @throws FileAlreadyExistsException - * The target file exists and cannot be replaced because the - * {@code REPLACE_EXISTING} option is not specified, or the target - * file is a non-empty directory <i>(optional specific exception)</i> - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * In the case of the default provider, and a security manager is - * installed, the {@link SecurityManager#checkRead(String) checkRead} - * method is invoked to check read access to the source file, the - * {@link SecurityManager#checkWrite(String) checkWrite} is invoked - * to check write access to the target file. If a symbolic link is - * copied the security manager is invoked to check {@link - * LinkPermission}{@code ("symbolic")}. - */ - public abstract Path copyTo(Path target, CopyOption... options) - throws IOException; - - /** - * Move or rename the file located by this path to a target location. - * - * <p> By default, this method attempts to move the file to the target - * location, failing if the target file exists except if the source and - * target are the {@link #isSameFile same} file, in which case this method - * has no effect. If the file is a symbolic link then the link is moved and - * not the target of the link. This method may be invoked to move an empty - * directory. In some implementations a directory has entries for special - * files or links that are created when the directory is created. In such - * implementations a directory is considered empty when only the special - * entries exist. When invoked to move a directory that is not empty then the - * directory is moved if it does not require moving the entries in the directory. - * For example, renaming a directory on the same {@link FileStore} will usually - * not require moving the entries in the directory. When moving a directory - * requires that its entries be moved then this method fails (by throwing - * an {@code IOException}). To move a <i>file tree</i> may involve copying - * rather than moving directories and this can be done using the {@link - * #copyTo copyTo} method in conjunction with the {@link - * Files#walkFileTree Files.walkFileTree} utility method. - * - * <p> The {@code options} parameter is an array of options and may contain - * any of the following: - * - * <table border=1 cellpadding=5 summary=""> - * <tr> <th>Option</th> <th>Description</th> </tr> - * <tr> - * <td> {@link StandardCopyOption#REPLACE_EXISTING REPLACE_EXISTING} </td> - * <td> If the target file exists, then the target file is replaced if it - * is not a non-empty directory. If the target file exists and is a - * symbolic-link then the symbolic-link is replaced and not the target of - * the link. </td> - * </tr> - * <tr> - * <td> {@link StandardCopyOption#ATOMIC_MOVE ATOMIC_MOVE} </td> - * <td> The move is performed as an atomic file system operation and all - * other options are ignored. If the target file exists then it is - * implementation specific if the existing file is replaced or this method - * fails by throwing an {@link IOException}. If the move cannot be - * performed as an atomic file system operation then {@link - * AtomicMoveNotSupportedException} is thrown. This can arise, for - * example, when the target location is on a different {@code FileStore} - * and would require that the file be copied, or target location is - * associated with a different provider to this object. </td> - * </table> - * - * <p> An implementation of this interface may support additional - * implementation specific options. - * - * <p> Where the move requires that the file be copied then the {@link - * BasicFileAttributes#lastModifiedTime last-modified-time} is copied to the - * new file. An implementation may also attempt to copy other file - * attributes but is not required to fail if the file attributes cannot be - * copied. When the move is performed as a non-atomic operation, and a {@code - * IOException} is thrown, then the state of the files is not defined. The - * original file and the target file may both exist, the target file may be - * incomplete or some of its file attributes may not been copied from the - * original file. - * - * @param target - * The target location - * @param options - * Options specifying how the move should be done - * - * @return The target - * - * @throws UnsupportedOperationException - * If the array contains a copy option that is not supported - * @throws FileAlreadyExistsException - * The target file exists and cannot be replaced because the - * {@code REPLACE_EXISTING} option is not specified, or the target - * file is a non-empty directory - * @throws AtomicMoveNotSupportedException - * The options array contains the {@code ATOMIC_MOVE} option but - * the file cannot be moved as an atomic file system operation. - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * In the case of the default provider, and a security manager is - * installed, the {@link SecurityManager#checkWrite(String) checkWrite} - * method is invoked to check write access to both the source and - * target file. - */ - public abstract Path moveTo(Path target, CopyOption... options) - throws IOException; - - /** - * Opens the directory referenced by this object, returning a {@code - * DirectoryStream} to iterate over all entries in the directory. The - * elements returned by the directory stream's {@link DirectoryStream#iterator - * iterator} are of type {@code Path}, each one representing an entry in the - * directory. The {@code Path} objects are obtained as if by {@link - * #resolve(Path) resolving} the name of the directory entry against this - * path. - * - * <p> The directory stream's {@code close} method should be invoked after - * iteration is completed so as to free any resources held for the open - * directory. The {@link Files#withDirectory Files.withDirectory} utility - * method is useful for cases where a task is performed on each accepted - * entry in a directory. This method closes the directory when iteration is - * complete (or an error occurs). - * - * <p> When an implementation supports operations on entries in the - * directory that execute in a race-free manner then the returned directory - * stream is a {@link SecureDirectoryStream}. - * - * @return A new and open {@code DirectoryStream} object - * - * @throws NotDirectoryException - * If the file could not otherwise be opened because it is not - * a directory <i>(optional specific exception)</i> - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * In the case of the default provider, and a security manager is - * installed, the {@link SecurityManager#checkRead(String) checkRead} - * method is invoked to check read access to the directory. - */ - public abstract DirectoryStream<Path> newDirectoryStream() - throws IOException; - - /** - * Opens the directory referenced by this object, returning a {@code - * DirectoryStream} to iterate over the entries in the directory. The - * elements returned by the directory stream's {@link DirectoryStream#iterator - * iterator} are of type {@code Path}, each one representing an entry in the - * directory. The {@code Path} objects are obtained as if by {@link - * #resolve(Path) resolving} the name of the directory entry against this - * path. The entries returned by the iterator are filtered by matching the - * {@code String} representation of their file names against the given - * <em>globbing</em> pattern. - * - * <p> For example, suppose we want to iterate over the files ending with - * ".java" in a directory: - * <pre> - * Path dir = ... - * DirectoryStream<Path> stream = dir.newDirectoryStream("*.java"); - * </pre> - * - * <p> The globbing pattern is specified by the {@link - * FileSystem#getNameMatcher getNameMatcher} method. - * - * <p> The directory stream's {@code close} method should be invoked after - * iteration is completed so as to free any resources held for the open - * directory. - * - * <p> When an implementation supports operations on entries in the - * directory that execute in a race-free manner then the returned directory - * stream is a {@link SecureDirectoryStream}. - * - * @param glob - * The glob pattern - * - * @return A new and open {@code DirectoryStream} object - * - * @throws java.util.regex.PatternSyntaxException - * If the pattern is invalid - * @throws UnsupportedOperationException - * If the pattern syntax is not known to the implementation - * @throws NotDirectoryException - * If the file could not otherwise be opened because it is not - * a directory <i>(optional specific exception)</i> - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * In the case of the default provider, and a security manager is - * installed, the {@link SecurityManager#checkRead(String) checkRead} - * method is invoked to check read access to the directory. - */ - public abstract DirectoryStream<Path> newDirectoryStream(String glob) - throws IOException; - - /** - * Opens the directory referenced by this object, returning a {@code - * DirectoryStream} to iterate over the entries in the directory. The - * elements returned by the directory stream's {@link DirectoryStream#iterator - * iterator} are of type {@code Path}, each one representing an entry in the - * directory. The {@code Path} objects are obtained as if by {@link - * #resolve(Path) resolving} the name of the directory entry against this - * path. The entries returned by the iterator are filtered by the given - * {@link DirectoryStream.Filter filter}. The {@link DirectoryStreamFilters} - * class defines factory methods that create useful filters. - * - * <p> The directory stream's {@code close} method should be invoked after - * iteration is completed so as to free any resources held for the open - * directory. The {@link Files#withDirectory Files.withDirectory} utility - * method is useful for cases where a task is performed on each accepted - * entry in a directory. This method closes the directory when iteration is - * complete (or an error occurs). - * - * <p> When an implementation supports operations on entries in the - * directory that execute in a race-free manner then the returned directory - * stream is a {@link SecureDirectoryStream}. - * - * <p> <b>Usage Example:</b> - * Suppose we want to iterate over the files in a directory that are - * larger than 8K. - * <pre> - * DirectoryStream.Filter<Path> filter = new DirectoryStream.Filter<Path>() { - * public boolean accept(Path file) { - * try { - * long size = Attributes.readBasicFileAttributes(file).size(); - * return (size > 8192L); - * } catch (IOException e) { - * // failed to get size - * return false; - * } - * } - * }; - * Path dir = ... - * DirectoryStream<Path> stream = dir.newDirectoryStream(filter); - * </pre> - * @param filter - * The directory stream filter - * - * @return A new and open {@code DirectoryStream} object - * - * @throws NotDirectoryException - * If the file could not otherwise be opened because it is not - * a directory <i>(optional specific exception)</i> - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * In the case of the default provider, and a security manager is - * installed, the {@link SecurityManager#checkRead(String) checkRead} - * method is invoked to check read access to the directory. - */ - public abstract DirectoryStream<Path> newDirectoryStream(DirectoryStream.Filter<? super Path> filter) - throws IOException; - - /** - * Creates a new and empty file, failing if the file already exists. - * - * <p> This {@code Path} locates the file to create. The check for the - * existence of the file and the creation of the new file if it does not - * exist are a single operation that is atomic with respect to all other - * filesystem activities that might affect the directory. - * - * <p> The {@code attrs} parameter is an optional array of {@link FileAttribute - * file-attributes} to set atomically when creating the file. Each attribute - * is identified by its {@link FileAttribute#name name}. If more than one - * attribute of the same name is included in the array then all but the last - * occurrence is ignored. - * - * @param attrs - * An optional list of file attributes to set atomically when - * creating the file - * - * @return This path - * - * @throws UnsupportedOperationException - * If the array contains an attribute that cannot be set atomically - * when creating the file - * @throws FileAlreadyExistsException - * If a file of that name already exists - * <i>(optional specific exception)</i> - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * In the case of the default provider, and a security manager is - * installed, the {@link SecurityManager#checkWrite(String) checkWrite} - * method is invoked to check write access to the new file. - */ - public abstract Path createFile(FileAttribute<?>... attrs) throws IOException; - - /** - * Creates a new directory. - * - * <p> This {@code Path} locates the directory to create. The check for the - * existence of the file and the creation of the directory if it does not - * exist are a single operation that is atomic with respect to all other - * filesystem activities that might affect the directory. - * - * <p> The {@code attrs} parameter is an optional array of {@link FileAttribute - * file-attributes} to set atomically when creating the directory. Each - * file attribute is identified by its {@link FileAttribute#name name}. If - * more than one attribute of the same name is included in the array then all - * but the last occurrence is ignored. - * - * @param attrs - * An optional list of file attributes to set atomically when - * creating the directory - * - * @return This path - * - * @throws UnsupportedOperationException - * If the array contains an attribute that cannot be set atomically - * when creating the directory - * @throws FileAlreadyExistsException - * If a directory could not otherwise be created because a file of - * that name already exists <i>(optional specific exception)</i> - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * In the case of the default provider, and a security manager is - * installed, the {@link SecurityManager#checkWrite(String) checkWrite} - * method is invoked to check write access to the new directory. - */ - public abstract Path createDirectory(FileAttribute<?>... attrs) - throws IOException; - - /** - * Opens or creates a file, returning a seekable byte channel to access the - * file. - * - * <p> The {@code options} parameter determines how the file is opened. - * The {@link StandardOpenOption#READ READ} and {@link StandardOpenOption#WRITE WRITE} - * options determine if the file should be opened for reading and/or writing. - * If neither option (or the {@link StandardOpenOption#APPEND APPEND} - * option) is contained in the array then the file is opened for reading. - * By default reading or writing commences at the beginning of the file. - * - * <p> In the addition to {@code READ} and {@code WRITE}, the following - * options may be present: - * - * <table border=1 cellpadding=5 summary=""> - * <tr> <th>Option</th> <th>Description</th> </tr> - * <tr> - * <td> {@link StandardOpenOption#APPEND APPEND} </td> - * <td> If this option is present then the file is opened for writing and - * each invocation of the channel's {@code write} method first advances - * the position to the end of the file and then writes the requested - * data. Whether the advancement of the position and the writing of the - * data are done in a single atomic operation is system-dependent and - * therefore unspecified. This option may not be used in conjunction - * with the {@code READ} or {@code TRUNCATE_EXISTING} options. </td> - * </tr> - * <tr> - * <td> {@link StandardOpenOption#TRUNCATE_EXISTING TRUNCATE_EXISTING} </td> - * <td> If this option is present then the existing file is truncated to - * a size of 0 bytes. This option is ignored when the file is opened only - * for reading. </td> - * </tr> - * <tr> - * <td> {@link StandardOpenOption#CREATE_NEW CREATE_NEW} </td> - * <td> If this option is present then a new file is created, failing if - * the file already exists or is a symbolic link. When creating a file the - * check for the existence of the file and the creation of the file if it - * does not exist is atomic with respect to other file system operations. - * This option is ignored when the file is opened only for reading. </td> - * </tr> - * <tr> - * <td > {@link StandardOpenOption#CREATE CREATE} </td> - * <td> If this option is present then an existing file is opened if it - * exists, otherwise a new file is created. This option is ignored if the - * {@code CREATE_NEW} option is also present or the file is opened only - * for reading. </td> - * </tr> - * <tr> - * <td > {@link StandardOpenOption#DELETE_ON_CLOSE DELETE_ON_CLOSE} </td> - * <td> When this option is present then the implementation makes a - * <em>best effort</em> attempt to delete the file when closed by the - * {@link SeekableByteChannel#close close} method. If the {@code close} - * method is not invoked then a <em>best effort</em> attempt is made to - * delete the file when the Java virtual machine terminates. </td> - * </tr> - * <tr> - * <td>{@link StandardOpenOption#SPARSE SPARSE} </td> - * <td> When creating a new file this option is a <em>hint</em> that the - * new file will be sparse. This option is ignored when not creating - * a new file. </td> - * </tr> - * <tr> - * <td> {@link StandardOpenOption#SYNC SYNC} </td> - * <td> Requires that every update to the file's content or metadata be - * written synchronously to the underlying storage device. (see <a - * href="package-summary.html#integrity"> Synchronized I/O file - * integrity</a>). </td> - * <tr> - * <tr> - * <td> {@link StandardOpenOption#DSYNC DSYNC} </td> - * <td> Requires that every update to the file's content be written - * synchronously to the underlying storage device. (see <a - * href="package-summary.html#integrity"> Synchronized I/O file - * integrity</a>). </td> - * </tr> - * </table> - * - * <p> An implementation may also support additional implementation specific - * options. - * - * <p> The {@code attrs} parameter is an optional array of file {@link - * FileAttribute file-attributes} to set atomically when a new file is created. - * - * <p> In the case of the default provider, the returned seekable byte channel - * is a {@link FileChannel}. - * - * <p> <b>Usage Examples:</b> - * <pre> - * Path file = ... - * - * // open file for reading - * ReadableByteChannel rbc = file.newByteChannel(EnumSet.of(READ))); - * - * // open file for writing to the end of an existing file, creating - * // the file if it doesn't already exist - * WritableByteChannel wbc = file.newByteChannel(EnumSet.of(CREATE,APPEND)); - * - * // create file with initial permissions, opening it for both reading and writing - * FileAttribute<Set<PosixFilePermission>> perms = ... - * SeekableByteChannel sbc = file.newByteChannel(EnumSet.of(CREATE_NEW,READ,WRITE), perms); - * </pre> - * - * @param options - * Options specifying how the file is opened - * @param attrs - * An optional list of file attributes to set atomically when - * creating the file - * - * @return a new seekable byte channel - * - * @throws IllegalArgumentException - * If the set contains an invalid combination of options - * @throws UnsupportedOperationException - * If an unsupported open option is specified or the array contains - * attributes that cannot be set atomically when creating the file - * @throws FileAlreadyExistsException - * If a file of that name already exists and the {@link - * StandardOpenOption#CREATE_NEW CREATE_NEW} option is specified - * <i>(optional specific exception)</i> - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * In the case of the default provider, and a security manager is - * installed, the {@link SecurityManager#checkRead(String) checkRead} - * method is invoked to check read access to the path if the file is - * opened for reading. The {@link SecurityManager#checkWrite(String) - * checkWrite} method is invoked to check write access to the path - * if the file is opened for writing. - */ - public abstract SeekableByteChannel newByteChannel(Set<? extends OpenOption> options, - FileAttribute<?>... attrs) - throws IOException; - - /** - * Opens or creates a file, returning a seekable byte channel to access the - * file. - * - * <p> This method extends the options defined by the {@code FileRef} - * interface and to the options specified by the {@link - * #newByteChannel(Set,FileAttribute[]) newByteChannel} method - * except that the options are specified by an array. In the case of the - * default provider, the returned seekable byte channel is a {@link - * FileChannel}. - * - * @param options - * Options specifying how the file is opened - * - * @return a new seekable byte channel - * - * @throws IllegalArgumentException - * If the set contains an invalid combination of options - * @throws UnsupportedOperationException - * If an unsupported open option is specified - * @throws FileAlreadyExistsException - * If a file of that name already exists and the {@link - * StandardOpenOption#CREATE_NEW CREATE_NEW} option is specified - * <i>(optional specific exception)</i> - * @throws IOException {@inheritDoc} - * @throws SecurityException {@inheritDoc} - */ - - public abstract SeekableByteChannel newByteChannel(OpenOption... options) - throws IOException; - - /** - * Opens the file located by this path for reading, returning an input - * stream to read bytes from the file. The stream will not be buffered, and - * is not required to support the {@link InputStream#mark mark} or {@link - * InputStream#reset reset} methods. The stream will be safe for access by - * multiple concurrent threads. Reading commences at the beginning of the file. - * - * @return An input stream to read bytes from the file - * - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * In the case of the default provider, and a security manager is - * installed, the {@link SecurityManager#checkRead(String) checkRead} - * method is invoked to check read access to the file. - */ - public abstract InputStream newInputStream() throws IOException; - - /** - * Opens or creates the file located by this path for writing, returning an - * output stream to write bytes to the file. - * - * <p> This method opens or creates a file in exactly the manner specified - * by the {@link Path#newByteChannel(Set,FileAttribute[]) newByteChannel} - * method except that the {@link StandardOpenOption#READ READ} option may not - * be present in the array of open options. If no open options are present - * then this method creates a new file for writing or truncates an existing - * file. - * - * <p> The resulting stream will not be buffered. The stream will be safe - * for access by multiple concurrent threads. - * - * <p> <b>Usage Example:</b> - * Suppose we wish to open a log file for writing so that we append to the - * file if it already exists, or create it when it doesn't exist. - * <pre> - * Path logfile = ... - * OutputStream out = new BufferedOutputStream(logfile.newOutputStream(CREATE, APPEND)); - * </pre> - * - * @param options - * Options specifying how the file is opened - * - * @return a new seekable byte channel - * - * @throws IllegalArgumentException - * If {@code options} contains an invalid combination of options - * @throws UnsupportedOperationException - * If an unsupported open option is specified - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * In the case of the default provider, and a security manager is - * installed, the {@link SecurityManager#checkWrite(String) checkWrite} - * method is invoked to check write access to the file. - */ - public abstract OutputStream newOutputStream(OpenOption... options) - throws IOException; - - /** - * Opens or creates the file located by this path for writing, returning an - * output stream to write bytes to the file. - * - * <p> This method opens or creates a file in exactly the manner specified - * by the {@link Path#newByteChannel(Set,FileAttribute[]) newByteChannel} - * method except that {@code options} parameter may not contain the {@link - * StandardOpenOption#READ READ} option. If no open options are present - * then this method creates a new file for writing or truncates an existing - * file. - * - * <p> The resulting stream will not be buffered. The stream will be safe - * for access by multiple concurrent threads. - * - * @param options - * Options specifying how the file is opened - * @param attrs - * An optional list of file attributes to set atomically when - * creating the file - * - * @return A new output stream - * - * @throws IllegalArgumentException - * If the set contains an invalid combination of options - * @throws UnsupportedOperationException - * If an unsupported open option is specified or the array contains - * attributes that cannot be set atomically when creating the file - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * In the case of the default provider, and a security manager is - * installed, the {@link SecurityManager#checkWrite(String) checkWrite} - * method is invoked to check write access to the file. - */ - public abstract OutputStream newOutputStream(Set<? extends OpenOption> options, - FileAttribute<?>... attrs) - throws IOException; - - /** - * Tells whether or not the file located by this object is considered - * <em>hidden</em>. The exact definition of hidden is platform or provider - * dependent. On UNIX for example a file is considered to be hidden if its - * name begins with a period character ('.'). On Windows a file is - * considered hidden if it isn't a directory and the DOS {@link - * DosFileAttributes#isHidden hidden} attribute is set. - * - * <p> Depending on the implementation this method may require to access - * the file system to determine if the file is considered hidden. - * - * @return {@code true} if the file is considered hidden - * - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * In the case of the default provider, and a security manager is - * installed, the {@link SecurityManager#checkRead(String) checkRead} - * method is invoked to check read access to the file. - */ - public abstract boolean isHidden() throws IOException; - - /** - * Tests whether the file located by this path exists. - * - * <p> This convenience method is intended for cases where it is required to - * take action when it can be confirmed that a file exists. This method simply - * invokes the {@link #checkAccess checkAccess} method to check if the file - * exists. If the {@code checkAccess} method succeeds then this method returns - * {@code true}, otherwise if an {@code IOException} is thrown (because the - * file doesn't exist or cannot be accessed by this Java virtual machine) - * then {@code false} is returned. - * - * <p> Note that the result of this method is immediately outdated. If this - * method indicates the file exists then there is no guarantee that a - * subsequence access will succeed. Care should be taken when using this - * method in security sensitive applications. - * - * @return {@code true} if the file exists; {@code false} if the file does - * not exist or its existence cannot be determined. - * - * @throws SecurityException - * In the case of the default provider, the {@link - * SecurityManager#checkRead(String)} is invoked to check - * read access to the file. - * - * @see #notExists - */ - public abstract boolean exists(); - - /** - * Tests whether the file located by this path does not exist. - * - * <p> This convenience method is intended for cases where it is required to - * take action when it can be confirmed that a file does not exist. This - * method invokes the {@link #checkAccess checkAccess} method to check if the - * file exists. If the file does not exist then {@code true} is returned, - * otherwise the file exists or cannot be accessed by this Java virtual - * machine and {@code false} is returned. - * - * <p> Note that this method is not the complement of the {@link #exists - * exists} method. Where it is not possible to determine if a file exists - * or not then both methods return {@code false}. As with the {@code exists} - * method, the result of this method is immediately outdated. If this - * method indicates the file does exist then there is no guarantee that a - * subsequence attempt to create the file will succeed. Care should be taken - * when using this method in security sensitive applications. - * - * @return {@code true} if the file does not exist; {@code false} if the - * file exists or its existence cannot be determined. - * - * @throws SecurityException - * In the case of the default provider, the {@link - * SecurityManager#checkRead(String)} is invoked to check - * read access to the file. - */ - public abstract boolean notExists(); - - // -- watchable -- - - /** - * Registers the file located by this path with a watch service. - * - * <p> In this release, this path locates a directory that exists. The - * directory is registered with the watch service so that entries in the - * directory can be watched. The {@code events} parameter is an array of - * events to register and may contain the following events: - * <ul> - * <li>{@link StandardWatchEventKind#ENTRY_CREATE ENTRY_CREATE} - - * entry created or moved into the directory</li> - * <li>{@link StandardWatchEventKind#ENTRY_DELETE ENTRY_DELETE} - - * entry deleted or moved out of the directory</li> - * <li>{@link StandardWatchEventKind#ENTRY_MODIFY ENTRY_MODIFY} - - * entry in directory was modified</li> - * </ul> - * - * <p> The {@link WatchEvent#context context} for these events is the - * relative path between the directory located by this path, and the path - * that locates the directory entry that is created, deleted, or modified. - * - * <p> The set of events may include additional implementation specific - * event that are not defined by the enum {@link StandardWatchEventKind} - * - * <p> The {@code modifiers} parameter is an array of <em>modifiers</em> - * that qualify how the directory is registered. This release does not - * define any <em>standard</em> modifiers. The array may contain - * implementation specific modifiers. - * - * <p> Where a file is registered with a watch service by means of a symbolic - * link then it is implementation specific if the watch continues to depend - * on the existence of the link after it is registered. - * - * <p> <b>Usage Example:</b> - * Suppose we wish register a directory for entry create, delete, and modify - * events: - * <pre> - * Path dir = ... - * WatchService watcher = ... - * - * WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY); - * </pre> - * - * @param watcher - * The watch service to which this object is to be registered - * @param events - * The events for which this object should be registered - * @param modifiers - * The modifiers, if any, that modify how the object is registered - * - * @return A key representing the registration of this object with the - * given watch service - * - * @throws UnsupportedOperationException - * If unsupported events or modifiers are specified - * @throws IllegalArgumentException - * If an invalid combination of events or modifiers is specified - * @throws ClosedWatchServiceException - * If the watch service is closed - * @throws NotDirectoryException - * If the file is registered to watch the entries in a directory - * and the file is not a directory <i>(optional specific exception)</i> - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * In the case of the default provider, and a security manager is - * installed, the {@link SecurityManager#checkRead(String) checkRead} - * method is invoked to check read access to the file. - */ - - public abstract WatchKey register(WatchService watcher, - WatchEvent.Kind<?>[] events, - WatchEvent.Modifier... modifiers) - throws IOException; - - // -- Iterable -- - - /** - * Returns an iterator over the name elements of this path. - * - * <p> The first element returned by the iterator represents the name - * element that is closest to the root in the directory hierarchy, the - * second element is the next closest, and so on. The last element returned - * is the name of the file or directory denoted by this path. The {@link - * #getRoot root} component, if present, is not returned by the iterator. - * - * @return An iterator over the name elements of this path. - */ - - public abstract Iterator<Path> iterator(); - - // -- compareTo/equals/hashCode -- - - /** - * Compares two abstract paths lexicographically. The ordering defined by - * this method is provider specific, and in the case of the default - * provider, platform specific. This method does not access the file system - * and neither file is required to exist. - * - * @param other The path compared to this path. - * - * @return Zero if the argument is {@link #equals equal} to this path, a - * value less than zero if this path is lexicographically less than - * the argument, or a value greater than zero if this path is - * lexicographically greater than the argument - */ - - public abstract int compareTo(Path other); - - /** - * Tests this path for equality with the given object. - * - * <p> If the given object is not a Path, or is a Path associated with a - * different provider, then this method immediately returns {@code false}. - * - * <p> Whether or not two path are equal depends on the file system - * implementation. In some cases the paths are compared without regard - * to case, and others are case sensitive. This method does not access the - * file system and the file is not required to exist. - * - * <p> This method satisfies the general contract of the {@link - * java.lang.Object#equals(Object) Object.equals} method. </p> - * - * @param ob - * The object to which this object is to be compared - * - * @return {@code true} if, and only if, the given object is a {@code Path} - * that is identical to this {@code Path} - */ - - public abstract boolean equals(Object ob); - - /** - * Computes a hash code for this path. - * - * <p> The hash code is based upon the components of the path, and - * satisfies the general contract of the {@link Object#hashCode - * Object.hashCode} method. - * - * @return The hash-code value for this Path - */ - - public abstract int hashCode(); - - /** - * Returns the string representation of this path. - * - * <p> If this path was created by converting a path string using the - * {@link FileSystem#getPath getPath} method then the path string returned - * by this method may differ from the original String used to create the path. - * - * <p> The returned path string uses the default name {@link - * FileSystem#getSeparator separator} to separate names in the path. - * - * @return The string representation of this path - */ - - public abstract String toString(); -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/PathMatcher.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,50 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file; - -/** - * An interface that is implemented by objects that perform match operations on - * paths. - * - * @since 1.7 - * - * @see FileSystem#getNameMatcher - * @see Path#newDirectoryStream(String) - */ - -public interface PathMatcher { - /** - * Tells if given path matches this matcher's pattern. - * - * @param path - * The path to match - * - * @return {@code true} if, and only if, the path matches this - * matcher's pattern - */ - boolean matches(Path path); -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/Paths.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,126 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file; - -import java.net.URI; -import java.util.Iterator; - -import org.classpath.icedtea.java.nio.file.spi.FileSystemProvider; - -/** - * This class consists exclusively of static methods that return a {@link Path} - * by converting a path string or {@link URI}. - * - * @since 1.7 - */ - -public class Paths { - private Paths() { } - - /** - * Constructs a {@code Path} by converting the given path string. - * - * <p> The {@code Path} is obtained by invoking the {@link FileSystem#getPath - * getPath} method of the {@link FileSystems#getDefault default} {@link - * FileSystem}. - * - * @param path - * The path string to convert - * - * @return The resulting {@code Path} - * - * @throws InvalidPathException - * If the path string cannot be converted to a {@code Path} - * - * @see FileSystem#getPath - */ - public static Path get(String path) { - return FileSystems.getDefault().getPath(path); - } - - /** - * Converts the given URI to a {@link Path} object. - * - * <p> This method iterates over the {@link FileSystemProvider#installedProviders() - * installed} providers to locate the provider that is identified by the - * URI {@link URI#getScheme scheme} of the given URI. URI schemes are - * compared without regard to case. If the provider is found then its {@link - * FileSystemProvider#getPath getPath} method is invoked to convert the - * URI. - * - * <p> In the case of the default provider, identified by the URI scheme - * "file", the given URI has a non-empty path component, and undefined query - * and fragment components. Whether the authority component may be present - * is platform specific. The returned {@code Path} is associated with the - * {@link FileSystems#getDefault default} file system. - * - * <p> The default provider provides a similar <em>round-trip</em> guarantee - * to the {@link java.io.File} class. For a given {@code Path} <i>p</i> it - * is guaranteed that - * <blockquote><tt> - * Paths.get(</tt><i>p</i><tt>.{@link Path#toUri() toUri}()).equals(</tt> - * <i>p</i><tt>.{@link Path#toAbsolutePath() toAbsolutePath}())</tt> - * </blockquote> - * so long as the original {@code Path}, the {@code URI}, and the new {@code - * Path} are all created in (possibly different invocations of) the same - * Java virtual machine. Whether other providers make any guarantees is - * provider specific and therefore unspecified. - * - * @param uri - * The URI to convert - * - * @return The resulting {@code Path} - * - * @throws IllegalArgumentException - * If preconditions on the {@code uri} parameter do not hold. The - * format of the URI is provider specific. - * @throws FileSystemNotFoundException - * If the file system identified by the URI does not exist or the - * provider identified by the URI's scheme component is not installed - * @throws SecurityException - * If a security manager is installed and it denies an unspecified - * permission to access the file system - */ - public static Path get(URI uri) { - String scheme = uri.getScheme(); - if (scheme == null) - throw new IllegalArgumentException("Missing scheme"); - - // check for default provider to avoid loading of installed providers - if (scheme.equalsIgnoreCase("file")) - return FileSystems.getDefault().provider().getPath(uri); - - // try to find provider - for (FileSystemProvider provider: FileSystemProvider.installedProviders()) { - if (provider.getScheme().equalsIgnoreCase(scheme)) { - return provider.getPath(uri); - } - } - - throw new FileSystemNotFoundException("Provider \"" + scheme + "\" not installed"); - } -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/ProviderMismatchException.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,54 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file; - -/** - * Unchecked exception thrown when an attempt is made to invoke a method on an - * object created by one file system provider with a parameter created by a - * different file system provider. - */ -public class ProviderMismatchException - extends java.lang.IllegalArgumentException -{ - static final long serialVersionUID = 4990847485741612530L; - - /** - * Constructs an instance of this class. - */ - public ProviderMismatchException() { - } - - /** - * Constructs an instance of this class. - * - * @param msg - * The detail message - */ - public ProviderMismatchException(String msg) { - super(msg); - } -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/ProviderNotFoundException.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,53 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file; - -/** - * Runtime exception thrown a provider of the required type cannot be found. - */ - -public class ProviderNotFoundException - extends RuntimeException -{ - static final long serialVersionUID = -1880012509822920354L; - - /** - * Constructs an instance of this class. - */ - public ProviderNotFoundException() { - } - - /** - * Constructs an instance of this class. - * - * @param msg - * The detail message - */ - public ProviderNotFoundException(String msg) { - super(msg); - } -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/ReadOnlyFileSystemException.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,44 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file; - -/** - * Unchecked exception thrown when an attempt is made to update an object in a - * file system that is accessed through a read-only {@code FileSystem}. - */ - -public class ReadOnlyFileSystemException - extends UnsupportedOperationException -{ - static final long serialVersionUID = -6822409595617487197L; - - /** - * Constructs an instance of this class. - */ - public ReadOnlyFileSystemException() { - } -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/SecureDirectoryStream.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,327 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classname" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package org.classpath.icedtea.java.nio.file; - -import java.util.Set; -import java.io.IOException; - -import org.classpath.icedtea.java.nio.channels.SeekableByteChannel; -import org.classpath.icedtea.java.nio.file.attribute.FileAttribute; -import org.classpath.icedtea.java.nio.file.attribute.FileAttributeView; - -/** - * A {@code DirectoryStream} that defines operations on files that are located - * relative to an open directory. A {@code SecureDirectoryStream} is intended - * for use by sophisticated or security sensitive applications requiring to - * traverse file trees or otherwise operate on directories in a race-free manner. - * Race conditions can arise when a sequence of file operations cannot be - * carried out in isolation. Each of the file operations defined by this - * interface specify a relative {@link Path}. All access to the file is relative - * to the open directory irrespective of if the directory is moved or replaced - * by an attacker while the directory is open. A {@code SecureDirectoryStream} - * may also be used as a virtual <em>working directory</em>. - * - * <p> A {@code SecureDirectoryStream} requires corresponding support from the - * underlying operating system. Where an implementation supports this features - * then the {@code DirectoryStream} returned by the {@link Path#newDirectoryStream - * newDirectoryStream} method will be a {@code SecureDirectoryStream} and must - * be cast to that type in order to invoke the methods defined by this interface. - * - * <p> As specified by {@code DirectoryStream}, the iterator's {@link - * java.util.Iterator#remove() remove} method removes the directory entry for - * the last element returned by the iterator. In the case of a {@code - * SecureDirectoryStream} the {@code remove} method behaves as if by invoking - * the {@link #deleteFile deleteFile} or {@link #deleteDirectory deleteDirectory} - * methods defined by this interface. The {@code remove} may require to examine - * the file to determine if the file is a directory, and consequently, it may - * not be atomic with respect to other file system operations. - * - * <p> In the case of the default {@link java.nio.file.spi.FileSystemProvider - * provider}, and a security manager is set, then the permission checks are - * performed using the path obtained by resolving the given relative path - * against the <i>original path</i> of the directory (irrespective of if the - * directory is moved since it was opened). - * - * @since 1.7 - */ - -public abstract class SecureDirectoryStream - implements DirectoryStream<Path> -{ - /** - * Initialize a new instance of this class. - */ - protected SecureDirectoryStream() { } - - /** - * Opens the directory identified by the given path, returning a {@code - * SecureDirectoryStream} to iterate over the entries in the directory. - * - * <p> This method works in exactly the manner specified by the {@link - * Path#newDirectoryStream newDirectoryStream} method for the case that - * the {@code path} parameter is an {@link Path#isAbsolute absolute} path. - * When the parameter is a relative path then the directory to open is - * relative to this open directory. The {@code followLinks} parameter - * determines if links should be followed. If this parameter is {@code - * false} and the file is a symbolic link then this method fails (by - * throwing an I/O exception). - * - * <p> The new directory stream, once created, is not dependent upon the - * directory stream used to create it. Closing this directory stream has no - * effect upon newly created directory stream. - * - * @param path - * The path to the directory to open - * @param followLinks - * {@code true} if the links should be followed - * @param filter - * The directory stream filter or {@code null}. - * - * @return A new and open {@code SecureDirectoryStream} object - * - * @throws ClosedDirectoryStreamException - * If the directory stream is closed - * @throws NotDirectoryException - * If the file could not otherwise be opened because it is not - * a directory <i>(optional specific exception)</i> - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * In the case of the default provider, and a security manager is - * installed, the {@link SecurityManager#checkRead(String) checkRead} - * method is invoked to check read access to the directory. - */ - public abstract SecureDirectoryStream newDirectoryStream(Path path, - boolean followLinks, - DirectoryStream.Filter<? super Path> filter) - throws IOException; - - /** - * Opens or creates a file in this directory, returning a seekable byte - * channel to access the file. - * - * <p> This method works in exactly the manner specified by the {@link - * Path#newByteChannel Path.newByteChannel} method for the - * case that the {@code path} parameter is an {@link Path#isAbsolute absolute} - * path. When the parameter is a relative path then the file to open or - * create is relative to this open directory. In addition to the options - * defined by the {@code Path.newByteChannel} method, the {@link - * LinkOption#NOFOLLOW_LINKS NOFOLLOW_LINKS} option may be used to - * ensure that this method fails if the file is a symbolic link. - * - * <p> The channel, once created, is not dependent upon the directory stream - * used to create it. Closing this directory stream has no effect upon the - * channel. - * - * @param path - * The path of the file to open open or create - * @param options - * Options specifying how the file is opened - * @param attrs - * An optional list of attributes to set atomically when creating - * the file - * - * @throws ClosedDirectoryStreamException - * If the directory stream is closed - * @throws IllegalArgumentException - * If the set contains an invalid combination of options - * @throws UnsupportedOperationException - * If an unsupported open option is specified or the array contains - * attributes that cannot be set atomically when creating the file - * @throws FileAlreadyExistsException - * If a file of that name already exists and the {@link - * StandardOpenOption#CREATE_NEW CREATE_NEW} option is specified - * <i>(optional specific exception)</i> - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * In the case of the default provider, and a security manager is - * installed, the {@link SecurityManager#checkRead(String) checkRead} - * method is invoked to check read access to the path if the file - * is opened for reading. The {@link SecurityManager#checkWrite(String) - * checkWrite} method is invoked to check write access to the path - * if the file is opened for writing. - */ - public abstract SeekableByteChannel newByteChannel(Path path, - Set<? extends OpenOption> options, - FileAttribute<?>... attrs) - throws IOException; - - /** - * Deletes a file. - * - * <p> Unlike the {@link FileRef#delete delete()} method, this method - * does not first examine the file to determine if the file is a directory. - * Whether a directory is deleted by this method is system dependent and - * therefore not specified. If the file is a symbolic-link then the link is - * deleted (not the final target of the link). When the parameter is a - * relative path then the file to delete is relative to this open directory. - * - * @param path - * The path of the file to delete - * - * @throws ClosedDirectoryStreamException - * If the directory stream is closed - * @throws NoSuchFileException - * If the the file does not exist <i>(optional specific exception)</i> - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * In the case of the default provider, and a security manager is - * installed, the {@link SecurityManager#checkDelete(String) checkDelete} - * method is invoked to check delete access to the file - */ - public abstract void deleteFile(Path path) throws IOException; - - /** - * Deletes a directory. - * - * <p> Unlike the {@link FileRef#delete delete()} method, this method - * does not first examine the file to determine if the file is a directory. - * Whether non-directories are deleted by this method is system dependent and - * therefore not specified. When the parameter is a relative path then the - * directory to delete is relative to this open directory. - * - * @param path - * The path of the directory to delete - * - * @throws ClosedDirectoryStreamException - * If the directory stream is closed - * @throws NoSuchFileException - * If the the directory does not exist <i>(optional specific exception)</i> - * @throws DirectoryNotEmptyException - * If the directory could not otherwise be deleted because it is - * not empty <i>(optional specific exception)</i> - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * In the case of the default provider, and a security manager is - * installed, the {@link SecurityManager#checkDelete(String) checkDelete} - * method is invoked to check delete access to the directory - */ - public abstract void deleteDirectory(Path path) throws IOException; - - /** - * Move a file from this directory to another directory. - * - * <p> This method works in a similar manner to {@link Path#moveTo moveTo} - * method when the {@link StandardCopyOption#ATOMIC_MOVE ATOMIC_MOVE} option - * is specified. That is, this method moves a file as an atomic file system - * operation. If the {@code srcpath} parameter is an {@link Path#isAbsolute - * absolute} path then it locates the source file. If the parameter is a - * relative path then it is located relative to this open directory. If - * the {@code targetpath} parameter is absolute then it locates the target - * file (the {@code targetdir} parameter is ignored). If the parameter is - * a relative path it is located relative to the open directory identified - * by the {@code targetdir} parameter. In all cases, if the target file - * exists then it is implementation specific if it is replaced or this - * method fails. - * - * @param srcpath - * The name of the file to move - * @param targetdir - * The destination directory - * @param targetpath - * The name to give the file in the destination directory - * - * @throws ClosedDirectoryStreamException - * If this or the target directory stream is closed - * @throws FileAlreadyExistsException - * The file already exists in the target directory and cannot - * be replaced <i>(optional specific exception)</i> - * @throws AtomicMoveNotSupportedException - * The file cannot be moved as an atomic file system operation - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * In the case of the default provider, and a security manager is - * installed, the {@link SecurityManager#checkWrite(String) checkWrite} - * method is invoked to check write access to both the source and - * target file. - */ - public abstract void move(Path srcpath, SecureDirectoryStream targetdir, Path targetpath) - throws IOException; - - /** - * Returns a new file attribute view to access the file attributes of this - * directory. - * - * <p> The resulting file attribute view can be used to read or update the - * attributes of this (open) directory. The {@code type} parameter specifies - * the type of the attribute view and the method returns an instance of that - * type if supported. Invoking this method to obtain a {@link - * BasicFileAttributeView} always returns an instance of that class that is - * bound to this open directory. - * - * <p> The state of resulting file attribute view is intimately connected - * to this directory stream. Once the directory stream is {@link #close closed}, - * then all methods to read or update attributes will throw {@link - * ClosedDirectoryStreamException ClosedDirectoryStreamException}. - * - * @param type - * The {@code Class} object corresponding to the file attribute view - * - * @return A new file attribute view of the specified type bound to - * this directory stream, or {@code null} if the attribute view - * type is not available - */ - public abstract <V extends FileAttributeView> V getFileAttributeView(Class<V> type); - - /** - * Returns a new file attribute view to access the file attributes of a file - * in this directory. - * - * <p> The resulting file attribute view can be used to read or update the - * attributes of file in this directory. The {@code type} parameter specifies - * the type of the attribute view and the method returns an instance of that - * type if supported. Invoking this method to obtain a {@link - * BasicFileAttributeView} always returns an instance of that class that is - * bound to the file in the directory. - * - * <p> The state of resulting file attribute view is intimately connected - * to this directory stream. Once the directory stream {@link #close closed}, - * then all methods to read or update attributes will throw {@link - * ClosedDirectoryStreamException ClosedDirectoryStreamException}. The - * file is not required to exist at the time that the file attribute view - * is created but methods to read or update attributes of the file will - * fail when invoked and the file does not exist. - * - * @param path - * The path of the file - * @param type - * The {@code Class} object corresponding to the file attribute view - * @param options - * Options indicating how symbolic links are handled - * - * @return A new file attribute view of the specified type bound to a - * this directory stream, or {@code null} if the attribute view - * type is not available - * - */ - public abstract <V extends FileAttributeView> V getFileAttributeView(Path path, - Class<V> type, - LinkOption... options); -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/SimpleFileVisitor.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,123 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file; - -import java.io.IOException; -import java.io.IOError; - -import org.classpath.icedtea.java.nio.file.attribute.BasicFileAttributes; - -/** - * A simple visitor of files with default behavior to visit all files and to - * re-throw I/O errors. - * - * <p> Methods in this class may be overridden subject to their general contract. - * - * @param <T> The type of reference to the files - * - * @since 1.7 - */ - -public class SimpleFileVisitor<T extends FileRef> implements FileVisitor<T> { - /** - * Initializes a new instance of this class. - */ - protected SimpleFileVisitor() { - } - - /** - * Invoked for a directory before entries in the directory are visited. - * - * <p> Unless overridden, this method returns {@link FileVisitResult#CONTINUE - * CONTINUE}. - */ - - public FileVisitResult preVisitDirectory(T dir) { - return FileVisitResult.CONTINUE; - } - - /** - * Invoked for a directory that could not be opened. - * - * <p> Unless overridden, this method throws {@link IOError} with the I/O - * exception as cause. - * - * @throws IOError - * With the I/O exception thrown when the attempt to open the - * directory failed - */ - - public FileVisitResult preVisitDirectoryFailed(T dir, IOException exc) { - throw new IOError(exc); - } - - /** - * Invoked for a file in a directory. - * - * <p> Unless overridden, this method returns {@link FileVisitResult#CONTINUE - * CONTINUE}. - */ - - public FileVisitResult visitFile(T file, BasicFileAttributes attrs) { - return FileVisitResult.CONTINUE; - } - - /** - * Invoked for a file when its basic file attributes could not be read. - * - * <p> Unless overridden, this method throws {@link IOError} with the I/O - * exception as cause. - * - * @throws IOError - * With the I/O exception thrown when the attempt to read the file - * attributes failed - */ - - public FileVisitResult visitFileFailed(T file, IOException exc) { - throw new IOError(exc); - } - - /** - * Invoked for a directory after entries in the directory, and all of their - * descendants, have been visited. - * - * <p> Unless overridden, this method returns {@link FileVisitResult#CONTINUE - * CONTINUE} if the directory iteration completes without an I/O exception; - * otherwise this method throws {@link IOError} with the I/O exception as - * cause. - * - * @throws IOError - * If iteration of the directory completed prematurely due to an - * I/O error - */ - - public FileVisitResult postVisitDirectory(T dir, IOException exc) { - if (exc != null) - throw new IOError(exc); - return FileVisitResult.CONTINUE; - } -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/StandardCopyOption.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,48 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file; - -/** - * Defines the standard copy options. - * - * @since 1.7 - */ - -public enum StandardCopyOption implements CopyOption { - /** - * Replace an existing file if it exists. - */ - REPLACE_EXISTING, - /** - * Copy attributes to the new file. - */ - COPY_ATTRIBUTES, - /** - * Move the file as an atomic file system operation. - */ - ATOMIC_MOVE; -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/StandardOpenOption.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,126 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file; - -/** - * Defines the standard open options. - * - * @since 1.7 - */ - -public enum StandardOpenOption implements OpenOption { - /** - * Open for read access. - */ - READ, - - /** - * Open for write access. - */ - WRITE, - - /** - * If the file is opened for {@link #WRITE} access then bytes will be written - * to the end of the file rather than the beginning. - * - * <p> If the file is opened for write access by other programs, then it - * is file system specific if writing to the end of the file is atomic. - */ - APPEND, - - /** - * If the file already exists and it is opened for {@link #WRITE} - * access, then its length is truncated to 0. This option is ignored - * if the file is opened only for {@link #READ} access. - */ - TRUNCATE_EXISTING, - - /** - * Create a new file if it does not exist. - * This option is ignored if the {@link #CREATE_NEW} option is also set. - * The check for the existence of the file and the creation of the file - * if it does not exist is atomic with respect to other file system - * operations. - */ - CREATE, - - /** - * Create a new file, failing if the file already exists. - * The check for the existence of the file and the creation of the file - * if it does not exist is atomic with respect to other file system - * operations. - */ - CREATE_NEW, - - /** - * Delete on close. When this option is present then the implementation - * makes a <em>best effort</em> attempt to delete the file when the closed - * by the appropriate {@code close} method. If the {@code close} method is - * not invoked then a <em>best effort</em> attempt is made to delete the - * file when the Java virtual machine terminates (either normally, as - * defined by the Java Language Specification, or where possible, abnormally). - * This option is primarily intended for use with <em>work files</em> that - * are used solely by a single instance of the Java virtual machine. This - * option is not recommended for use when opening files that are open - * concurrently by other entities. Many of the details as to when and how - * the file is deleted are implementation specific and therefore not - * specified. In particular, an implementation may be unable to guarantee - * that it deletes the expected file when replaced by an attacker while the - * file is open. Consequently, security sensitive applications should take - * care when using this option. - * - * <p> For security reasons, this option may imply the {@link - * LinkOption#NOFOLLOW_LINKS} option. In other words, if the option is present - * when opening an existing file that is a symbolic link then it may fail - * (by throwing {@link java.io.IOException}). - */ - DELETE_ON_CLOSE, - - /** - * Sparse file. When used with the {@link #CREATE_NEW} option then this - * option provides a <em>hint</em> that the new file will be sparse. The - * option is ignored when the file system does not support the creation of - * sparse files. - */ - SPARSE, - - /** - * Requires that every update to the file's content or metadata be written - * synchronously to the underlying storage device. - * - * @see <a href="package-summary.html#integrity">Synchronized I/O file integrity</a> - */ - SYNC, - - /** - * Requires that every update to the file's content be written - * synchronously to the underlying storage device. - * - * @see <a href="package-summary.html#integrity">Synchronized I/O file integrity</a> - */ - DSYNC; -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/StandardWatchEventKind.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,95 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file; - -/** - * Defines the <em>standard</em> event kinds. - * - * @since 1.7 - */ - -public class StandardWatchEventKind { - private StandardWatchEventKind() { } - - /** - * A special event to indicate that events may have been lost or - * discarded. - * - * <p> The {@link WatchEvent#context context} for this event is - * implementation specific and may be {@code null}. The event {@link - * WatchEvent#count count} may be greater than {@code 1}. - * - * @see WatchService - */ - public static final WatchEvent.Kind<Void> OVERFLOW = - new StdWatchEventKind<Void>("OVERFLOW", Void.class); - - /** - * Directory entry created. - * - * <p> When a directory is registered for this event then the {@link WatchKey} - * is queued when it is observed that an entry is created in the directory - * or renamed into the directory. The event {@link WatchEvent#count count} - * for this event is always {@code 1}. - */ - public static final WatchEvent.Kind<Path> ENTRY_CREATE = - new StdWatchEventKind<Path>("ENTRY_CREATE", Path.class); - - /** - * Directory entry deleted. - * - * <p> When a directory is registered for this event then the {@link WatchKey} - * is queued when it is observed that an entry is deleted or renamed out of - * the directory. The event {@link WatchEvent#count count} for this event - * is always {@code 1}. - */ - public static final WatchEvent.Kind<Path> ENTRY_DELETE = - new StdWatchEventKind<Path>("ENTRY_DELETE", Path.class); - - /** - * Directory entry modified. - * - * <p> When a directory is registered for this event then the {@link WatchKey} - * is queued when it is observed that an entry in the directory has been - * modified. The event {@link WatchEvent#count count} for this event is - * {@code 1} or greater. - */ - public static final WatchEvent.Kind<Path> ENTRY_MODIFY = - new StdWatchEventKind<Path>("ENTRY_MODIFY", Path.class); - - private static class StdWatchEventKind<T> implements WatchEvent.Kind<T> { - private final String name; - private final Class<T> type; - StdWatchEventKind(String name, Class<T> type) { - this.name = name; - this.type = type; - } - public String name() { return name; } - public Class<T> type() { return type; } - public String toString() { return name; } - } -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/WatchEvent.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,117 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file; - -/** - * An event or a repeated event for an object that is registered with a {@link - * WatchService}. - * - * <p> An event is classified by its {@link #kind() kind} and has a {@link - * #count() count} to indicate the number of times that the event has been - * observed. This allows for efficient representation of repeated events. The - * {@link #context() context} method returns any context associated with - * the event. In the case of a repeated event then the context is the same for - * all events. - * - * <p> Watch events are immutable and safe for use by multiple concurrent - * threads. - * - * @param <T> The type of the context object associated with the event - * - * @since 1.7 - */ - -public abstract class WatchEvent<T> { - - /** - * An event kind, for the purposes of identification. - * - * @since 1.7 - * @see StandardWatchEventKind - */ - public static interface Kind<T> { - /** - * Returns the name of the event kind. - */ - String name(); - - /** - * Returns the type of the {@link WatchEvent#context context} value. - */ - Class<T> type(); - } - - /** - * Initializes a new instance of this class. - */ - protected WatchEvent() { } - - /** - * An event modifier that qualifies how a {@link Watchable} is registered - * with a {@link WatchService}. - * - * <p> This release does not define any <em>standard</em> modifiers. - * - * @since 1.7 - * @see Watchable#register - */ - public static interface Modifier { - /** - * Returns the name of the modifier. - */ - String name(); - } - - /** - * Returns the event kind. - * - * @return The event kind - */ - public abstract Kind<T> kind(); - - /** - * Returns the event count. If the event count is greater than {@code 1} - * then this is a repeated event. - * - * @return The event count - */ - public abstract int count(); - - /** - * Returns the context for the event. - * - * <p> In the case of {@link StandardWatchEventKind#ENTRY_CREATE ENTRY_CREATE}, - * {@link StandardWatchEventKind#ENTRY_DELETE ENTRY_DELETE}, and {@link - * StandardWatchEventKind#ENTRY_MODIFY ENTRY_MODIFY} events the context is - * a {@code Path} that is the {@link Path#relativize relative} path between - * the directory registered with the watch service, and the entry that is - * created, deleted, or modified. - * - * @return The event context; may be {@code null} - */ - public abstract T context(); -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/WatchKey.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,138 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file; - -import java.util.List; - -/** - * A key representing the registration of an object with a {@link WatchService}. - * - * <p> A watch key is created when a {@link Watchable Watchable} object is - * registered with a watch service. The key remains {@link #isValid valid} until: - * <ol> - * <li> It is cancelled, explicitly, by invoking its {@link #cancel cancel} - * method, or</li> - * <li> Cancelled implicitly, because the object is no longer accessible, - * or </li> - * <li> By {@link WatchService#close closing} the watch service. </li> - * </ol> - * - * <p> A watch key has a state. When initially created the key is said to be - * <em>ready</em>. When an event is detected then the key is <em>signalled</em> - * and queued so that it can be retrieved by invoking the watch service's {@link - * WatchService#poll() poll} or {@link WatchService#take() take} methods. Once - * signalled, a key remains in this state until its {@link #reset reset} method - * is invoked to return the key to the ready state. Events detected while the - * key is in the signalled state are queued but do not cause the key to be - * re-queued for retrieval from the watch service. Events are retrieved by - * invoking the key's {@link #pollEvents pollEvents} method. This method - * retrieves and removes all events accumulated for the object. When initially - * created, a watch key has no pending events. Typically events are retrieved - * when the key is in the signalled state leading to the following idiom: - * - * <pre> - * for (;;) { - * // retrieve key - * WatchKey key = watcher.take(); - * - * // process events - * for (WatchEvent<?> event: key.pollEvents()) { - * : - * } - * - * // reset the key - * boolean valid = key.reset(); - * if (!valid) { - * // object no longer registered - * } - * } - * </pre> - * - * <p> Watch keys are safe for use by multiple concurrent threads. Where there - * are several threads retrieving signalled keys from a watch service then care - * should be taken to ensure that the {@code reset} method is only invoked after - * the events for the object have been processed. This ensures that one thread - * is processing the events for an object at any time. - * - * @since 1.7 - */ - -public abstract class WatchKey { - /** - * Initializes a new instance of this class. - */ - protected WatchKey() { } - - /** - * Tells whether or not this watch key is valid. - * - * <p> A watch key is valid upon creation and remains until it is cancelled, - * or its watch service is closed. - * - * @return {@code true} if, and only if, this watch key is valid - */ - public abstract boolean isValid(); - - /** - * Retrieves and removes all pending events for this watch key, returning - * a {@code List} of the events that were retrieved. - * - * <p> Note that this method does not wait if there are no events pending. - * - * @return The list of the events retrieved - */ - public abstract List<WatchEvent<?>> pollEvents(); - - /** - * Resets this watch key. - * - * <p> If this watch key has been cancelled or this watch key is already in - * the ready state then invoking this method has no effect. Otherwise - * if there are pending events for the object then this watch key is - * immediately re-queued to the watch service. If there are no pending - * events then the watch key is put into the ready state and will remain in - * that state until an event is detected or the watch key is cancelled. - * - * @return {@code true} if the watch key is valid and has been reset; - * {@code false} if the watch key could not be reset because it is - * no longer {@link #isValid valid} - */ - public abstract boolean reset(); - - /** - * Cancels the registration with the watch service. Upon return the watch key - * will be invalid. If the watch key is enqueued, waiting to be retrieved - * from the watch service, then it will remain in the queue until it is - * removed. Pending events, if any, remain pending and may be retrieved by - * invoking the {@link #pollEvents pollEvents} method event after the key is - * cancelled. - * - * <p> If this watch key has already been cancelled then invoking this - * method has no effect. Once cancelled, a watch key remains forever invalid. - */ - public abstract void cancel(); -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/WatchService.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,179 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file; - -import java.io.Closeable; -import java.io.IOException; -import java.util.concurrent.TimeUnit; - -/** - * A watch service that <em>watches</em> registered objects for changes and - * events. For example a file manager may use a watch service to monitor a - * directory for changes so that it can update its display of the list of files - * when files are created or deleted. - * - * <p> A {@link Watchable} object is registered with a watch service by invoking - * its {@link Watchable#register register} method, returning a {@link WatchKey} - * to represent the registration. When an event for an object is detected the - * key is <em>signalled</em>, and if not currently signalled, it is queued to - * the watch service so that it can be retrieved by consumers that invoke the - * {@link #poll() poll} or {@link #take() take} methods to retrieve keys - * and process events. Once the events have been processed the consumer - * invokes the key's {@link WatchKey#reset reset} method to reset the key which - * allows the key to be signalled and re-queued with further events. - * - * <p> Registration with a watch service is cancelled by invoking the key's - * {@link WatchKey#cancel cancel} method. A key that is queued at the time that - * it is cancelled remains in the queue until it is retrieved. Depending on the - * object, a key may be cancelled automatically. For example, suppose a - * directory is watched and the watch service detects that it has been deleted - * or its file system is no longer accessible. When a key is cancelled in this - * manner it is signalled and queued, if not currently signalled. To ensure - * that the consumer is notified the return value from the {@code reset} - * method indicates if the key is valid. - * - * <p> A watch service is safe for use by multiple concurrent consumers. To - * ensure that only one consumer processes the events for a particular object at - * any time then care should be taken to ensure that the key's {@code reset} - * method is only invoked after its events have been processed. The {@link - * #close close} method may be invoked at any time to close the service causing - * any threads waiting to retrieve keys, to throw {@code - * ClosedWatchServiceException}. - * - * <p> File systems may report events faster than they can be retrieved or - * processed and an implementation may impose an unspecified limit on the number - * of events that it may accumulate. Where an implementation <em>knowingly</em> - * discards events then it arranges for the key's {@link WatchKey#pollEvents - * pollEvents} method to return an element with an event type of {@link - * StandardWatchEventKind#OVERFLOW OVERFLOW}. This event can be used by the - * consumer as a trigger to re-examine the state of the object. - * - * <p> When an event is reported to indicate that a file in a watched directory - * has been modified then there is no guarantee that the program (or programs) - * that have modified the file have completed. Care should be taken to coordinate - * access with other programs that may be updating the file. - * The {@link java.nio.channels.FileChannel FileChannel} class defines methods - * to lock regions of a file against access by other programs. - * - * <h4>Platform dependencies</h4> - * - * <p> The implementation that observes events from the file system is intended - * to map directly on to the native file event notification facility where - * available, or to use a primitive mechanism, such as polling, when a native - * facility is not available. Consequently, many of the details on how events - * are detected, their timeliness, and whether their ordering is preserved are - * highly implementation specific. For example, when a file in a watched - * directory is modified then it may result in a single {@link - * StandardWatchEventKind#ENTRY_MODIFY ENTRY_MODIFY} event in some - * implementations but several events in other implementations. Short-lived - * files (meaning files that are deleted very quickly after they are created) - * may not be detected by primitive implementations that periodically poll the - * file system to detect changes. - * - * <p> If a watched file is not located on a local storage device then it is - * implementation specific if changes to the file can be detected. In particular, - * it is not required that changes to files carried out on remote systems be - * detected. - * - * @since 1.7 - * - * @see FileSystem#newWatchService - */ - -public abstract class WatchService - implements Closeable -{ - /** - * Initializes a new instance of this class. - */ - protected WatchService() { } - - /** - * Closes this watch service. - * - * <p> If a thread is currently blocked in the {@link #take take} or {@link - * #poll(long,TimeUnit) poll} methods waiting for a key to be queued then - * it immediately receives a {@link ClosedWatchServiceException}. Any - * valid keys associated with this watch service are {@link WatchKey#isValid - * invalidated}. - * - * <p> After a watch service is closed, any further attempt to invoke - * operations upon it will throw {@link ClosedWatchServiceException}. - * If this watch service is already closed then invoking this method - * has no effect. - * - * @throws IOException - * If an I/O error occurs - */ - - public abstract void close() throws IOException; - - /** - * Retrieves and removes the next watch key, or {@code null} if none are - * present. - * - * @return The next watch key, or {@code null} - * - * @throws ClosedWatchServiceException - * If this watch service is closed - */ - public abstract WatchKey poll(); - - /** - * Retrieves and removes the next watch key, waiting if necessary up to the - * specified wait time if none are yet present. - * - * @param timeout - * how to wait before giving up, in units of unit - * @param unit - * a {@code TimeUnit} determining how to interpret the timeout - * parameter - * - * @return The next watch key, or {@code null} - * - * @throws ClosedWatchServiceException - * If this watch service is closed, or it is closed while waiting - * for the next key - * @throws InterruptedException - * If interrupted while waiting - */ - public abstract WatchKey poll(long timeout, TimeUnit unit) - throws InterruptedException; - - /** - * Retrieves and removes next watch key waiting if none are yet present. - * - * @return The next watch key - * - * @throws ClosedWatchServiceException - * If this watch service is closed, or it is closed while waiting - * for the next key - * @throws InterruptedException - * If interrupted while waiting - */ - public abstract WatchKey take() throws InterruptedException; -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/Watchable.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,128 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file; - -import java.io.IOException; - -/** - * An object that may be registered with a watch service so that it can be - * <em>watched</em> for changes and events. - * - * <p> This interface defines the {@link #register register} method to register - * the object with a {@link WatchService} returning a {@link WatchKey} to - * represent the registration. An object may be registered with more than one - * watch service. Registration with a watch service is cancelled by invoking the - * key's {@link WatchKey#cancel cancel} method. - * - * @since 1.7 - * - * @see Path#register - */ - -public interface Watchable { - - /** - * Registers an object with a watch service. - * - * <p> If the file system object identified by this object is currently - * registered with the watch service then the watch key, representing that - * registration, is returned after changing the event set or modifiers to - * those specified by the {@code events} and {@code modifiers} parameters. - * Changing the event set does not cause pending events for the object to be - * discarded. Objects are automatically registered for the {@link - * StandardWatchEventKind#OVERFLOW OVERFLOW} event. This event is not - * required to be present in the array of events. - * - * <p> Otherwise the file system object has not yet been registered with the - * given watch service, so it is registered and the resulting new key is - * returned. - * - * <p> Implementations of this interface should specify the events they - * support. - * - * @param watcher - * The watch service to which this object is to be registered - * @param events - * The events for which this object should be registered - * @param modifiers - * The modifiers, if any, that modify how the object is registered - * - * @return A key representing the registration of this object with the - * given watch service - * - * @throws UnsupportedOperationException - * If unsupported events or modifiers are specified - * @throws IllegalArgumentException - * If an invalid of combination of events are modifiers are specified - * @throws ClosedWatchServiceException - * If the watch service is closed - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * If a security manager is installed and it denies an unspecified - * permission required to monitor this object. Implementations of - * this interface should specify the permission checks. - */ - WatchKey register(WatchService watcher, - WatchEvent.Kind<?>[] events, - WatchEvent.Modifier... modifiers) - throws IOException; - - - /** - * Registers an object with a watch service. - * - * <p> An invocation of this method behaves in exactly the same way as the - * invocation - * <pre> - * watchable.{@link #register(WatchService,WatchEvent.Kind[],WatchEvent.Modifier[]) register}(watcher, events, new WatchEvent.Modifier[0]); - * </pre> - * - * @param watcher - * The watch service to which this object is to be registered - * @param events - * The events for which this object should be registered - * - * @return A key representing the registration of this object with the - * given watch service - * - * @throws UnsupportedOperationException - * If unsupported events are specified - * @throws IllegalArgumentException - * If an invalid of combination of events are specified - * @throws ClosedWatchServiceException - * If the watch service is closed - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * If a security manager is installed and it denies an unspecified - * permission required to monitor this object. Implementations of - * this interface should specify the permission checks. - */ - WatchKey register(WatchService watcher, WatchEvent.Kind<?>... events) - throws IOException; -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/AclEntry.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,395 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file.attribute; - -import java.util.*; - -/** - * An entry in an access control list (ACL). - * - * <p> The ACL entry represented by this class is based on the ACL model - * specified in <a href="http://www.ietf.org/rfc/rfc3530.txt"><i>RFC 3530: - * Network File System (NFS) version 4 Protocol</i></a>. Each entry has four - * components as follows: - * - * <ol> - * <li><p> The {@link #type() type} component determines if the entry - * grants or denies access. </p></li> - * - * <li><p> The {@link #principal() principal} component, sometimes called the - * "who" component, is a {@link UserPrincipal} corresponding to the identity - * that the entry grants or denies access - * </p></li> - * - * <li><p> The {@link #permissions permissions} component is a set of - * {@link AclEntryPermission permissions} - * </p></li> - * - * <li><p> The {@link #flags flags} component is a set of {@link AclEntryFlag - * flags} to indicate how entries are inherited and propagated </p></li> - * </ol> - * - * <p> ACL entries are created using an associated {@link Builder} object by - * invoking its {@link Builder#build build} method. - * - * <p> ACL entries are immutable and are safe for use by multiple concurrent - * threads. - * - * @since 1.7 - */ - -public final class AclEntry { - - private final AclEntryType type; - private final UserPrincipal who; - private final Set<AclEntryPermission> perms; - private final Set<AclEntryFlag> flags; - - // cached hash code - private volatile int hash; - - // private constructor - private AclEntry(AclEntryType type, - UserPrincipal who, - Set<AclEntryPermission> perms, - Set<AclEntryFlag> flags) - { - this.type = type; - this.who = who; - this.perms = perms; - this.flags = flags; - } - - /** - * A builder of {@link AclEntry} objects. - * - * <p> A {@code Builder} object is obtained by invoking one of the {@link - * AclEntry#newBuilder newBuilder} methods defined by the {@code AclEntry} - * class. - * - * <p> Builder objects are mutable and are not safe for use by multiple - * concurrent threads without appropriate synchronization. - * - * @since 1.7 - */ - public static final class Builder { - private AclEntryType type; - private UserPrincipal who; - private Set<AclEntryPermission> perms; - private Set<AclEntryFlag> flags; - - private Builder(AclEntryType type, - UserPrincipal who, - Set<AclEntryPermission> perms, - Set<AclEntryFlag> flags) - { - assert perms != null && flags != null; - this.type = type; - this.who = who; - this.perms = perms; - this.flags = flags; - } - - /** - * Constructs an {@link AclEntry} from the components of this builder. - * The type and who components are required to have been set in order - * to construct an {@code AclEntry}. - * - * @return A new ACL entry - * - * @throws IllegalStateException - * If the type or who component have not been set. - */ - public AclEntry build() { - if (type == null) - throw new IllegalStateException("Missing type component"); - if (who == null) - throw new IllegalStateException("Missing who component"); - return new AclEntry(type, who, perms, flags); - } - - /** - * Sets the type component of this builder. - * - * @return This builder - */ - public Builder setType(AclEntryType type) { - if (type == null) - throw new NullPointerException(); - this.type = type; - return this; - } - - /** - * Sets the principal component of this builder. - * - * @return This builder - */ - public Builder setPrincipal(UserPrincipal who) { - if (who == null) - throw new NullPointerException(); - this.who = who; - return this; - } - - // check set only contains elements of the given type - private static void checkSet(Set<?> set, Class<?> type) { - for (Object e: set) { - if (e == null) - throw new NullPointerException(); - type.cast(e); - } - } - - /** - * Sets the permissions component of this builder. On return, the - * permissions component of this builder is a copy of the given set. - * - * @return This builder - * - * @throws ClassCastException - * If the sets contains elements that are not of type {@code - * AclEntryPermission} - */ - public Builder setPermissions(Set<AclEntryPermission> perms) { - // copy and check for erroneous elements - perms = new HashSet<AclEntryPermission>(perms); - checkSet(perms, AclEntryPermission.class); - this.perms = perms; - return this; - } - - /** - * Sets the permissions component of this builder. On return, the - * permissions component of this builder is a copy of the permissions in - * the given array. - * - * @return This builder - */ - public Builder setPermissions(AclEntryPermission... perms) { - Set<AclEntryPermission> set = - new HashSet<AclEntryPermission>(perms.length); - // copy and check for null elements - for (AclEntryPermission p: perms) { - if (p == null) - throw new NullPointerException(); - set.add(p); - } - this.perms = set; - return this; - } - - /** - * Sets the flags component of this builder. On return, the flags - * component of this builder is a copy of the given set. - * - * @return This builder - * - * @throws ClassCastException - * If the sets contains elements that are not of type {@code - * AclEntryFlag} - */ - public Builder setFlags(Set<AclEntryFlag> flags) { - // copy and check for erroneous elements - flags = new HashSet<AclEntryFlag>(flags); - checkSet(flags, AclEntryFlag.class); - this.flags = flags; - return this; - } - - /** - * Sets the flags component of this builder. On return, the flags - * component of this builder is a copy of the flags in the given - * array. - * - * @return This builder - */ - public Builder setFlags(AclEntryFlag... flags) { - Set<AclEntryFlag> set = new HashSet<AclEntryFlag>(flags.length); - // copy and check for null elements - for (AclEntryFlag f: flags) { - if (f == null) - throw new NullPointerException(); - set.add(f); - } - this.flags = set; - return this; - } - } - - /** - * Constructs a new builder. The initial value of the type and who - * components is {@code null}. The initial value of the permissions and - * flags components is the empty set. - * - * @return A new builder - */ - public static Builder newBuilder() { - Set<AclEntryPermission> perms = Collections.emptySet(); - Set<AclEntryFlag> flags = Collections.emptySet(); - return new Builder(null, null, perms, flags); - } - - /** - * Constructs a new builder with the components of an existing ACL entry. - * - * @param entry - * An ACL entry - * - * @return A new builder - */ - public static Builder newBuilder(AclEntry entry) { - return new Builder(entry.type, entry.who, entry.perms, entry.flags); - } - - /** - * Returns the ACL entry type. - */ - public AclEntryType type() { - return type; - } - - /** - * Returns the principal component. - */ - public UserPrincipal principal() { - return who; - } - - /** - * Returns a copy of the permissions component. - * - * <p> The returned set is a modifiable copy of the permissions. - */ - public Set<AclEntryPermission> permissions() { - return new HashSet<AclEntryPermission>(perms); - } - - /** - * Returns a copy of the flags component. - * - * <p> The returned set is a modifiable copy of the flags. - */ - public Set<AclEntryFlag> flags() { - return new HashSet<AclEntryFlag>(flags); - } - - /** - * Compares the specified object with this ACL entry for equality. - * - * <p> If the given object is not an {@code AclEntry} then this method - * immediately returns {@code false}. - * - * <p> For two ACL entries to be considered equals requires that they are - * both the same type, their who components are equal, their permissions - * components are equal, and their flags components are equal. - * - * <p> This method satisfies the general contract of the {@link - * java.lang.Object#equals(Object) Object.equals} method. </p> - * - * @param ob The object to which this object is to be compared - * - * @return {@code true} if, and only if, the given object is an AclEntry that - * is identical to this AclEntry - */ - - public boolean equals(Object ob) { - if (ob == this) - return true; - if (ob == null || !(ob instanceof AclEntry)) - return false; - AclEntry other = (AclEntry)ob; - if (this.type != other.type) - return false; - if (!this.who.equals(other.who)) - return false; - if (!this.perms.equals(other.perms)) - return false; - if (!this.flags.equals(other.flags)) - return false; - return true; - } - - private static int hash(int h, Object o) { - return h * 127 + o.hashCode(); - } - - /** - * Returns the hash-code value for this ACL entry. - * - * <p> This method satisfies the general contract of the {@link - * Object#hashCode method}. - */ - - public int hashCode() { - // return cached hash if available - if (hash != 0) - return hash; - int h = type.hashCode(); - h = hash(h, who); - h = hash(h, perms); - h = hash(h, flags); - hash = h; - return hash; - } - - /** - * Returns the string representation of this ACL entry. - * - * @return The string representation of this entry - */ - - public String toString() { - StringBuilder sb = new StringBuilder(); - - // who - sb.append(who.getName()); - sb.append(':'); - - // permissions - for (AclEntryPermission perm: perms) { - sb.append(perm.name()); - sb.append('/'); - } - sb.setLength(sb.length()-1); // drop final slash - sb.append(':'); - - // flags - if (!flags.isEmpty()) { - for (AclEntryFlag flag: flags) { - sb.append(flag.name()); - sb.append('/'); - } - sb.setLength(sb.length()-1); // drop final slash - sb.append(':'); - } - - // type - sb.append(type.name()); - return sb.toString(); - } -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/AclEntryFlag.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,66 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file.attribute; - -/** - * Defines the flags for used by the flags component of an ACL {@link AclEntry - * entry}. - * - * <p> In this release, this class does not define flags related to {@link - * AclEntryType#AUDIT} and {@link AclEntryType#ALARM} entry types. - * - * @since 1.7 - */ - -public enum AclEntryFlag { - - /** - * Can be placed on a directory and indicates that the ACL entry should be - * added to each new non-directory file created. - */ - FILE_INHERIT, - - /** - * Can be placed on a directory and indicates that the ACL entry should be - * added to each new directory created. - */ - DIRECTORY_INHERIT, - - /** - * Can be placed on a directory to indicate that the ACL entry should not - * be placed on the newly created directory which is inheritable by - * subdirectories of the created directory. - */ - NO_PROPAGATE_INHERIT, - - /** - * Can be placed on a directory but does not apply to the directory, - * only to newly created files/directories as specified by the - * {@link #FILE_INHERIT} and {@link #DIRECTORY_INHERIT} flags. - */ - INHERIT_ONLY; -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/AclEntryPermission.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,131 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file.attribute; - -/** - * Defines the permissions for use with the permissions component of an ACL - * {@link AclEntry entry}. - * - * @since 1.7 - */ - -public enum AclEntryPermission { - - /** - * Permission to read the data of the file. - */ - READ_DATA, - - /** - * Permission to modify the file's data. - */ - WRITE_DATA, - - /** - * Permission to append data to a file. - */ - APPEND_DATA, - - /** - * Permission to read the named attributes of a file. - * - * <p> <a href="http://www.ietf.org/rfc/rfc3530.txt">RFC 3530: Network - * File System (NFS) version 4 Protocol</a> defines <em>named attributes</em> - * as opaque files associated with a file in the file system. - */ - READ_NAMED_ATTRS, - - /** - * Permission to write the named attributes of a file. - * - * <p> <a href="http://www.ietf.org/rfc/rfc3530.txt">RFC 3530: Network - * File System (NFS) version 4 Protocol</a> defines <em>named attributes</em> - * as opaque files associated with a file in the file system. - */ - WRITE_NAMED_ATTRS, - - /** - * Permission to execute a file. - */ - EXECUTE, - - /** - * Permission to delete a file or directory within a directory. - */ - DELETE_CHILD, - - /** - * The ability to read (non-acl) file attributes. - */ - READ_ATTRIBUTES, - - /** - * The ability to write (non-acl) file attributes. - */ - WRITE_ATTRIBUTES, - - /** - * Permission to delete the file. - */ - DELETE, - - /** - * Permission to read the ACL attribute. - */ - READ_ACL, - - /** - * Permission to write the ACL attribute. - */ - WRITE_ACL, - - /** - * Permission to change the owner. - */ - WRITE_OWNER, - - /** - * Permission to access file locally at the server with synchronous reads - * and writes. - */ - SYNCHRONIZE; - - /** - * Permission to list the entries of a directory (equal to {@link #READ_DATA}) - */ - public static final AclEntryPermission LIST_DIRECTORY = READ_DATA; - - /** - * Permission to add a new file to a directory (equal to {@link #WRITE_DATA}) - */ - public static final AclEntryPermission ADD_FILE = WRITE_DATA; - - /** - * Permission to create a subdirectory to a directory (equal to {@link #APPEND_DATA}) - */ - public static final AclEntryPermission ADD_SUBDIRECTORY = APPEND_DATA; -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/AclEntryType.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,57 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file.attribute; - -/** - * A typesafe enumeration of the access control entry types. - * - * @since 1.7 - */ - -public enum AclEntryType { - /** - * Explicitly grants access to a file or directory. - */ - ALLOW, - - /** - * Explicitly denies access to a file or directory. - */ - DENY, - - /** - * Log, in a system dependent way, the access specified in the - * permissions component of the ACL entry. - */ - AUDIT, - - /** - * Generate an alarm, in a system dependent way, the access specified in the - * permissions component of the ACL entry. - */ - ALARM -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/AclFileAttributeView.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,211 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file.attribute; - -import java.util.List; -import java.io.IOException; - -/** - * A file attribute view that supports reading or updating a file's Access - * Control Lists (ACL) or file owner attributes. - * - * <p> ACLs are used to specify access rights to file system objects. An ACL is - * an ordered list of {@link AclEntry access-control-entries}, each specifying a - * {@link UserPrincipal} and the level of access for that user principal. This - * file attribute view defines the {@link #getAcl() getAcl}, and {@link - * #setAcl(List) setAcl} methods to read and write ACLs based on the ACL - * model specified in <a href="http://www.ietf.org/rfc/rfc3530.txt"><i>RFC 3530: - * Network File System (NFS) version 4 Protocol</i></a>. This file attribute view - * is intended for file system implementations that support the NFSv4 ACL model - * or have a <em>well-defined</em> mapping between the NFSv4 ACL model and the ACL - * model used by the file system. The details of such mapping are implementation - * dependent and are therefore unspecified. - * - * <p> This class also extends {@code FileOwnerAttributeView} so as to define - * methods to get and set the file owner. - * - * <p> When a file system provides access to a set of {@link FileStore - * file-systems} that are not homogeneous then only some of the file systems may - * support ACLs. The {@link FileStore#supportsFileAttributeView - * supportsFileAttributeView} method can be used to test if a file system - * supports ACLs. - * - * <a name="interop"><h4>Interoperability</h4></a> - * - * RFC 3530 allows for special user identities to be used on platforms that - * support the POSIX defined access permissions. The special user identities - * are "{@code OWNER@}", "{@code GROUP@}", and "{@code EVERYONE@}". When both - * the {@code AclFileAttributeView} and the {@link PosixFileAttributeView} - * are supported then these special user identities may be included in ACL {@link - * AclEntry entries} that are read or written. The file system's {@link - * UserPrincipalLookupService} may be used to obtain a {@link UserPrincipal} - * to represent these special identities by invoking the {@link - * UserPrincipalLookupService#lookupPrincipalByName lookupPrincipalByName} - * method. - * - * <p> <b>Usage Example:</b> - * Suppose we wish to add an entry to an existing ACL to grant "joe" access: - * <pre> - * // lookup "joe" - * UserPrincipal joe = file.getFileSystem().getUserPrincipalLookupService() - * .lookupPrincipalByName("joe"); - * - * // get view - * AclFileAttributeView view = file.newFileAttributeView(AclFileAttributeView.class); - * - * // create ACE to give "joe" read access - * AclEntry entry = AclEntry.newBuilder() - * .setType(AclEntryType.ALLOW) - * .setPrincipal(joe) - * .setPermissions(AclEntryPermission.READ_DATA, AclEntryPermission.READ_ATTRIBUTES) - * .build(); - * - * // read ACL, insert ACE, re-write ACL - * List<AclEntry> acl = view.getAcl(); - * acl.add(0, entry); // insert before any DENY entries - * view.setAcl(acl); - * </pre> - * - * <h4> Dynamic Access </h4> - * <p> Where dynamic access to file attributes is required, the attributes - * supported by this attribute view are as follows: - * <blockquote> - * <table border="1" cellpadding="8"> - * <tr> - * <th> Name </th> - * <th> Type </th> - * </tr> - * <tr> - * <td> "acl" </td> - * <td> {@link List}<{@link AclEntry}> </td> - * </tr> - * <tr> - * <td> "owner" </td> - * <td> {@link UserPrincipal} </td> - * </tr> - * </table> - * </blockquote> - * - * <p> The {@link #getAttribute getAttribute} or {@link #readAttributes - * readAttributes} methods may be used to read the ACL or owner attributes as if - * by invoking the {@link #getAcl getAcl} or {@link #getOwner getOwner} methods. - * - * <p> The {@link #setAttribute setAttribute} method may be used to update the - * ACL or owner attributes as if by invoking the {@link #setAcl setAcl} or {@link - * #setOwner setOwner} methods. - * - * <h4> Setting the ACL when creating a file </h4> - * - * <p> Implementations supporting this attribute view may also support setting - * the initial ACL when creating a file or directory. The initial ACL - * may be provided to methods such as {@link Path#createFile createFile} or {@link - * Path#createDirectory createDirectory} as an {@link FileAttribute} with {@link - * FileAttribute#name name} {@code "acl:acl"} and a {@link FileAttribute#value - * value} that is the list of {@code AclEntry} objects. - * - * <p> Where an implementation supports an ACL model that differs from the NFSv4 - * defined ACL model then setting the initial ACL when creating the file must - * translate the ACL to the model supported by the file system. Methods that - * create a file should reject (by throwing {@link IOException IOException}) - * any attempt to create a file that would be less secure as a result of the - * translation. - * - * @since 1.7 - * @see Attributes#getAcl - * @see Attributes#setAcl - */ - -public interface AclFileAttributeView - extends FileOwnerAttributeView -{ - /** - * Returns the name of the attribute view. Attribute views of this type - * have the name {@code "acl"}. - */ - - String name(); - - /** - * Reads the access control list. - * - * <p> When the file system uses an ACL model that differs from the NFSv4 - * defined ACL model, then this method returns an ACL that is the translation - * of the ACL to the NFSv4 ACL model. - * - * <p> The returned list is modifiable so as to facilitate changes to the - * existing ACL. The {@link #setAcl setAcl} method is used to update - * the file's ACL attribute. - * - * @return An ordered list of {@link AclEntry entries} representing the - * ACL - * - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * In the case of the default provider, a security manager is - * installed, and it denies {@link RuntimePermission}<tt>("accessUserInformation")</tt> - * or its {@link SecurityManager#checkRead(String) checkRead} method - * denies read access to the file. - */ - List<AclEntry> getAcl() throws IOException; - - /** - * Updates (replace) the access control list. - * - * <p> Where the file system supports Access Control Lists, and it uses an - * ACL model that differs from the NFSv4 defined ACL model, then this method - * must translate the ACL to the model supported by the file system. This - * method should reject (by throwing {@link IOException IOException}) any - * attempt to write an ACL that would appear to make the file more secure - * than would be the case if the ACL were updated. Where an implementation - * does not support a mapping of {@link AclEntryType#AUDIT} or {@link - * AclEntryType#ALARM} entries, then this method ignores these entries when - * writing the ACL. - * - * <p> If an ACL entry contains a {@link AclEntry#principal user-principal} - * that is not associated with the same provider as this attribute view then - * {@link ProviderMismatchException} is thrown. Additional validation, if - * any, is implementation dependent. - * - * <p> If the file system supports other security related file attributes - * (such as a file {@link PosixFileAttributes#permissions - * access-permissions} for example), the updating the access control list - * may also cause these security related attributes to be updated. - * - * @param acl - * The new access control list - * - * @throws IOException - * If an I/O error occurs or the ACL is invalid - * @throws SecurityException - * In the case of the default provider, a security manager is - * installed, it denies {@link RuntimePermission}<tt>("accessUserInformation")</tt> - * or its {@link SecurityManager#checkWrite(String) checkWrite} - * method denies write access to the file. - */ - void setAcl(List<AclEntry> acl) throws IOException; -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/AttributeView.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,119 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file.attribute; - -import java.util.*; -import java.io.IOException; - -/** - * An object that provides a read-only or updatable <em>view</em> of non-opaque - * values associated with an object in a filesystem. This interface is extended - * or implemented by specific attribute views that define the attributes - * supported by the view. A specific attribute view will typically define - * type-safe methods to read or update the attributes that it supports. It also - * provides <em>dynamic access</em> where the {@link #readAttributes - * readAttributes}, {@link #getAttribute getAttribute} and {@link #setAttribute - * setAttributs} methods are used to access the attributes by names defined - * by the attribute view. Implementations must ensure that the attribute names - * do not contain the colon (':') or comma (',') characters. - * - * @since 1.7 - */ - -public interface AttributeView { - /** - * Returns the name of the attribute view. - */ - String name(); - - /** - * Reads the value of an attribute. - * - * @param attribute - * The attribute name (case sensitive) - * - * @return The value of the attribute, or {@code null} if the attribute is - * not supported - * - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * If a security manager is set and it denies access - */ - Object getAttribute(String attribute) throws IOException; - - /** - * Sets/updates the value of an attribute. - * - * @param attribute - * The attribute name (case sensitive) - * @param value - * The attribute value - * - * @throws UnsupportedOperationException - * If the attribute is not supported or this attribute view does - * not support updating the value of the attribute - * @throws IllegalArgumentException - * If the attribute value is of the correct type but has an - * inappropriate value - * @throws ClassCastException - * If the attribute value is not of the expected type or is a - * collection containing elements that are not of the expected - * type - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * If a security manager is set and it denies access - */ - void setAttribute(String attribute, Object value) throws IOException; - - /** - * Reads all, or a subset, of the attributes supported by this file attribute - * view. - * - * <p> The {@code first} and {@code rest} parameters are the names of the - * attributes to read. If any of the parameters has the value {@code "*"} - * then all attributes are read. Attributes that are not supported are - * ignored and will not be present in the returned map. It is implementation - * specific if all attributes are read as an atomic operation with respect - * to other file system operations. - * - * @param first - * The name of an attribute to read (case sensitive) - * @param rest - * The names of others attributes to read (case sensitive) - * - * @return An unmodifiable map of the attributes; may be empty. Its keys are - * the attribute names, its values are the attribute values - * - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * If a security manager is set and it denies access - */ - Map<String,?> readAttributes(String first, String... rest) throws IOException; -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/Attributes.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,714 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file.attribute; - -import java.io.IOException; -import java.util.*; -import java.util.concurrent.TimeUnit; - -import org.classpath.icedtea.java.nio.file.FileRef; -import org.classpath.icedtea.java.nio.file.FileStore; -import org.classpath.icedtea.java.nio.file.LinkOption; - -/** - * This class consists exclusively of static methods that operate on or return - * the attributes of files or file stores. These methods provide for convenient - * use of the {@link AttributeView attribute-views} defined in this package. - * - * @since 1.7 - */ - -public final class Attributes { - private Attributes() { - } - - /** - * Splits the given attribute name into the name of an attribute view and - * the attribute. If the attribute view is not identified then it assumed - * to be "basic". - */ - private static String[] split(String attribute) { - String[] s = new String[2]; - int pos = attribute.indexOf(':'); - if (pos == -1) { - s[0] = "basic"; - s[1] = attribute; - } else { - s[0] = attribute.substring(0, pos++); - s[1] = (pos == attribute.length()) ? "" : attribute.substring(pos); - } - return s; - } - - /** - * Sets the value of a file attribute. - * - * <p> The {@code attribute} parameter identifies the attribute to be set - * and takes the form: - * <blockquote> - * [<i>view-name</i><b>:</b>]<i>attribute-name</i> - * </blockquote> - * where square brackets [...] delineate an optional component and the - * character {@code ':'} stands for itself. - * - * <p> <i>view-name</i> is the {@link FileAttributeView#name name} of a {@link - * FileAttributeView} that identifies a set of file attributes. If not - * specified then it defaults to {@code "basic"}, the name of the file - * attribute view that identifies the basic set of file attributes common to - * many file systems. <i>attribute-name</i> is the name of the attribute - * within the set. - * - * <p> <b>Usage Example:</b> - * Suppose we want to set the DOS "hidden" attribute: - * <pre> - * Attributes.setAttribute(file, "dos:hidden", true); - * </pre> - * - * @param file - * A file reference that locates the file - * @param attribute - * The attribute to set - * @param value - * The attribute value - * - * @throws UnsupportedOperationException - * If the attribute view is not available or it does not - * support updating the attribute - * @throws IllegalArgumentException - * If the attribute value is of the correct type but has an - * inappropriate value - * @throws ClassCastException - * If the attribute value is not of the expected type or is a - * collection containing elements that are not of the expected - * type - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * In the case of the default provider, and a security manager is - * installed, its {@link SecurityManager#checkWrite(String) checkWrite} - * method denies write access to the file. If this method is invoked - * to set security sensitive attributes then the security manager - * may be invoked to check for additional permissions. - */ - public static void setAttribute(FileRef file, String attribute, Object value) - throws IOException - { - String[] s = split(attribute); - FileAttributeView view = file.getFileAttributeView(s[0]); - if (view == null) - throw new UnsupportedOperationException("View '" + s[0] + "' not available"); - view.setAttribute(s[1], value); - } - - /** - * Reads the value of a file attribute. - * - * <p> The {@code attribute} parameter identifies the attribute to be read - * and takes the form: - * <blockquote> - * [<i>view-name</i><b>:</b>]<i>attribute-name</i> - * </blockquote> - * where square brackets [...] delineate an optional component and the - * character {@code ':'} stands for itself. - * - * <p> <i>view-name</i> is the {@link FileAttributeView#name name} of a {@link - * FileAttributeView} that identifies a set of file attributes. If not - * specified then it defaults to {@code "basic"}, the name of the file - * attribute view that identifies the basic set of file attributes common to - * many file systems. <i>attribute-name</i> is the name of the attribute. - * - * <p> The {@code options} array may be used to indicate how symbolic links - * are handled for the case that the file is a symbolic link. By default, - * symbolic links are followed and the file attribute of the final target - * of the link is read. If the option {@link LinkOption#NOFOLLOW_LINKS - * NOFOLLOW_LINKS} is present then symbolic links are not followed and so - * the method returns the file attribute of the symbolic link. - * - * <p> <b>Usage Example:</b> - * Suppose we require the user ID of the file owner on a system that - * supports a "{@code unix}" view: - * <pre> - * int uid = (Integer)Attributes.getAttribute(file, "unix:uid"); - * </pre> - * - * @param file - * A file reference that locates the file - * @param attribute - * The attribute to read - * @param options - * Options indicating how symbolic links are handled - * - * @return The attribute value, or {@code null} if the attribute view - * is not available or it does not support reading the attribute - * - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * In the case of the default provider, and a security manager is - * installed, its {@link SecurityManager#checkRead(String) checkRead} - * method denies read access to the file. If this method is invoked - * to read security sensitive attributes then the security manager - * may be invoked to check for additional permissions. - */ - public static Object getAttribute(FileRef file, - String attribute, - LinkOption... options) - throws IOException - { - String[] s = split(attribute); - FileAttributeView view = file.getFileAttributeView(s[0], options); - if (view != null) - return view.getAttribute(s[1]); - // view not available - return null; - } - - /** - * Reads a set of file attributes as a bulk operation. - * - * <p> The {@code attributes} parameter identifies the attributes to be read - * and takes the form: - * <blockquote> - * [<i>view-name</i><b>:</b>]<i>attribute-list</i> - * </blockquote> - * where square brackets [...] delineate an optional component and the - * character {@code ':'} stands for itself. - * - * <p> <i>view-name</i> is the {@link FileAttributeView#name name} of a {@link - * FileAttributeView} that identifies a set of file attributes. If not - * specified then it defaults to {@code "basic"}, the name of the file - * attribute view that identifies the basic set of file attributes common to - * many file systems. - * - * <p> The <i>attribute-list</i> component is a comma separated list of - * zero or more names of attributes to read. If the list contains the value - * {@code "*"} then all attributes are read. Attributes that are not supported - * are ignored and will not be present in the returned map. It is - * implementation specific if all attributes are read as an atomic operation - * with respect to other file system operations. - * - * <p> The following examples demonstrate possible values for the {@code - * attributes} parameter: - * - * <blockquote> - * <table border="0"> - * <tr> - * <td> {@code "*"} </td> - * <td> Read all {@link BasicFileAttributes basic-file-attributes}. </td> - * </tr> - * <tr> - * <td> {@code "size,lastModifiedTime,lastAccessTime"} </td> - * <td> Reads the file size, last modified time, and last access time - * attributes. </td> - * </tr> - * <tr> - * <td> {@code "posix:*"} </td> - * <td> Read all {@link PosixFileAttributes POSIX-file-attributes}.. </td> - * </tr> - * <tr> - * <td> {@code "posix:permissions,owner,size"} </td> - * <td> Reads the POSX file permissions, owner, and file size. </td> - * </tr> - * </table> - * </blockquote> - * - * <p> The {@code options} array may be used to indicate how symbolic links - * are handled for the case that the file is a symbolic link. By default, - * symbolic links are followed and the file attributes of the final target - * of the link are read. If the option {@link LinkOption#NOFOLLOW_LINKS - * NOFOLLOW_LINKS} is present then symbolic links are not followed and so - * the method returns the file attributes of the symbolic link. - * - * @param file - * A file reference that locates the file - * @param attributes - * The attributes to read - * @param options - * Options indicating how symbolic links are handled - * - * @return A map of the attributes returned; may be empty. The map's keys - * are the attribute names, its values are the attribute values - * - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * In the case of the default provider, and a security manager is - * installed, its {@link SecurityManager#checkRead(String) checkRead} - * method denies read access to the file. If this method is invoked - * to read security sensitive attributes then the security manager - * may be invoke to check for additional permissions. - */ - public static Map<String,?> readAttributes(FileRef file, - String attributes, - LinkOption... options) - throws IOException - { - String[] s = split(attributes); - FileAttributeView view = file.getFileAttributeView(s[0], options); - if (view != null) { - // further split attributes into the first and rest. - String[] names = s[1].split(","); - int rem = names.length-1; - String first = names[0]; - String[] rest = new String[rem]; - if (rem > 0) System.arraycopy(names, 1, rest, 0, rem); - - return view.readAttributes(first, rest); - } - // view not available - return Collections.emptyMap(); - } - - /** - * Reads the basic file attributes of a file. - * - * <p> The {@code options} array may be used to indicate how symbolic links - * are handled for the case that the file is a symbolic link. By default, - * symbolic links are followed and the file attributes of the final target - * of the link are read. If the option {@link LinkOption#NOFOLLOW_LINKS - * NOFOLLOW_LINKS} is present then symbolic links are not followed and so - * the method returns the file attributes of the symbolic link. This option - * should be used where there is a need to determine if a file is a - * symbolic link: - * <pre> - * boolean isSymbolicLink = Attributes.readBasicFileAttributes(file, NOFOLLOW_LINKS).isSymbolicLink(); - * </pre> - * - * <p> It is implementation specific if all file attributes are read as an - * atomic operation with respect to other file system operations. - * - * @param file - * A file reference that locates the file - * @param options - * Options indicating how symbolic links are handled - * - * @return The basic file attributes - * - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * In the case of the default provider, the security manager's {@link - * SecurityManager#checkRead(String) checkRead} method is invoked - * to check read access to file - * - * @see BasicFileAttributeView#readAttributes - */ - public static BasicFileAttributes readBasicFileAttributes(FileRef file, - LinkOption... options) - throws IOException - { - return file.getFileAttributeView(BasicFileAttributeView.class, options) - .readAttributes(); - } - - /** - * Reads the POSIX file attributes of a file. - * - * <p> The {@code file} parameter locates a file that supports the {@link - * PosixFileAttributeView}. This file attribute view provides access to a - * subset of the file attributes commonly associated with files on file - * systems used by operating systems that implement the Portable Operating - * System Interface (POSIX) family of standards. It is implementation - * specific if all file attributes are read as an atomic operation with - * respect to other file system operations. - * - * <p> The {@code options} array may be used to indicate how symbolic links - * are handled for the case that the file is a symbolic link. By default, - * symbolic links are followed and the file attributes of the final target - * of the link are read. If the option {@link LinkOption#NOFOLLOW_LINKS - * NOFOLLOW_LINKS} is present then symbolic links are not followed and so - * the method returns the file attributes of the symbolic link. - * - * @param file - * A file reference that locates the file - * @param options - * Options indicating how symbolic links are handled - * - * @return The POSIX file attributes - * - * @throws UnsupportedOperationException - * If the {@code PosixFileAttributeView} is not available - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * In the case of the default provider, and a security manager is - * installed, it denies {@link RuntimePermission}<tt>("accessUserInformation")</tt> - * or its {@link SecurityManager#checkRead(String) checkRead} method - * denies read access to the file. - * - * @see PosixFileAttributeView#readAttributes - */ - public static PosixFileAttributes readPosixFileAttributes(FileRef file, - LinkOption... options) - throws IOException - { - PosixFileAttributeView view = - file.getFileAttributeView(PosixFileAttributeView.class, options); - if (view == null) - throw new UnsupportedOperationException(); - return view.readAttributes(); - } - - /** - * Reads the DOS file attributes of a file. - * - * <p> The {@code file} parameter locates a file that supports the {@link - * DosFileAttributeView}. This file attribute view provides access to - * legacy "DOS" attributes supported by the file systems such as File - * Allocation Table (FAT), commonly used in <em>consumer devices</em>. It is - * implementation specific if all file attributes are read as an atomic - * operation with respect to other file system operations. - * - * <p> The {@code options} array may be used to indicate how symbolic links - * are handled for the case that the file is a symbolic link. By default, - * symbolic links are followed and the file attributes of the final target - * of the link are read. If the option {@link LinkOption#NOFOLLOW_LINKS - * NOFOLLOW_LINKS} is present then symbolic links are not followed and so - * the method returns the file attributes of the symbolic link. - * - * @param file - * A file reference that locates the file - * @param options - * Options indicating how symbolic links are handled - * - * @return The DOS file attributes - * - * @throws UnsupportedOperationException - * If the {@code DosFileAttributeView} is not available - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * In the case of the default provider, the security manager's {@link - * SecurityManager#checkRead(String) checkRead} method is invoked - * to check read access to file - * - * @see DosFileAttributeView#readAttributes - */ - public static DosFileAttributes readDosFileAttributes(FileRef file, - LinkOption... options) - throws IOException - { - DosFileAttributeView view = - file.getFileAttributeView(DosFileAttributeView.class, options); - if (view == null) - throw new UnsupportedOperationException(); - return view.readAttributes(); - } - - /** - * Returns the owner of a file. - * - * <p> The {@code file} parameter locates a file that supports the {@link - * FileOwnerAttributeView}. This file attribute view provides access to - * a file attribute that is the owner of the file. - * - * @param file - * A file reference that locates the file - * - * @return A user principal representing the owner of the file - * - * @throws UnsupportedOperationException - * If the {@code FileOwnerAttributeView} is not available - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * In the case of the default provider, and a security manager is - * installed, it denies {@link RuntimePermission}<tt>("accessUserInformation")</tt> - * or its {@link SecurityManager#checkRead(String) checkRead} method - * denies read access to the file. - * - * @see FileOwnerAttributeView#getOwner - */ - public static UserPrincipal getOwner(FileRef file) throws IOException { - FileOwnerAttributeView view = - file.getFileAttributeView(FileOwnerAttributeView.class); - if (view == null) - throw new UnsupportedOperationException(); - return view.getOwner(); - } - - /** - * Updates the file owner. - * - * <p> The {@code file} parameter locates a file that supports the {@link - * FileOwnerAttributeView}. This file attribute view provides access to - * a file attribute that is the owner of the file. - * - * @param file - * A file reference that locates the file - * @param owner - * The new file owner - * - * @throws UnsupportedOperationException - * If the {@code FileOwnerAttributeView} is not available - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * In the case of the default provider, and a security manager is - * installed, it denies {@link RuntimePermission}<tt>("accessUserInformation")</tt> - * or its {@link SecurityManager#checkWrite(String) checkWrite} - * method denies write access to the file. - * - * @see FileOwnerAttributeView#setOwner - */ - public static void setOwner(FileRef file, UserPrincipal owner) - throws IOException - { - FileOwnerAttributeView view = - file.getFileAttributeView(FileOwnerAttributeView.class); - if (view == null) - throw new UnsupportedOperationException(); - view.setOwner(owner); - } - - /** - * Reads a file's Access Control List (ACL). - * - * <p> The {@code file} parameter locates a file that supports the {@link - * AclFileAttributeView}. This file attribute view provides access to ACLs - * based on the ACL model specified in - * <a href="http://www.ietf.org/rfc/rfc3530.txt"><i>RFC 3530</i></a>. - * - * @param file - * A file reference that locates the file - * - * @return An ordered list of {@link AclEntry entries} representing the - * ACL. The returned list is modifiable. - * - * @throws UnsupportedOperationException - * If the {@code AclAttributeView} is not available - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * In the case of the default provider, and a security manager is - * installed, it denies {@link RuntimePermission}<tt>("accessUserInformation")</tt> - * or its {@link SecurityManager#checkRead(String) checkRead} method - * denies read access to the file. - * - * @see AclFileAttributeView#getAcl - */ - public static List<AclEntry> getAcl(FileRef file) throws IOException { - AclFileAttributeView view = - file.getFileAttributeView(AclFileAttributeView.class); - if (view == null) - throw new UnsupportedOperationException(); - return view.getAcl(); - } - - /** - * Updates a file's Access Control List (ACL). - * - * <p> The {@code file} parameter locates a file that supports the {@link - * AclFileAttributeView}. This file attribute view provides access to ACLs - * based on the ACL model specified in - * <a href="http://www.ietf.org/rfc/rfc3530.txt"><i>RFC 3530</i></a>. - * - * @param file - * A file reference that locates the file - * @param acl - * The new file ACL - * - * @throws UnsupportedOperationException - * If the {@code AclFileAttributeView} is not available - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * In the case of the default provider, and a security manager is - * installed, it denies {@link RuntimePermission}<tt>("accessUserInformation")</tt> - * or its {@link SecurityManager#checkWrite(String) checkWrite} - * method denies write access to the file. - * - * @see AclFileAttributeView#setAcl - */ - public static void setAcl(FileRef file, List<AclEntry> acl) - throws IOException - { - AclFileAttributeView view = - file.getFileAttributeView(AclFileAttributeView.class); - if (view == null) - throw new UnsupportedOperationException(); - view.setAcl(acl); - } - - /** - * Updates the value of a file's last modified time attribute. - * - * <p> The time value is measured since the epoch - * (00:00:00 GMT, January 1, 1970) and is converted to the precision supported - * by the file system. Converting from finer to coarser granularities result - * in precision loss. - * - * <p> If the file system does not support a last modified time attribute then - * this method has no effect. - * - * @param file - * A file reference that locates the file - * - * @param lastModifiedTime - * The new last modified time, or {@code -1L} to update it to - * the current time - * @param unit - * A {@code TimeUnit} determining how to interpret the - * {@code lastModifiedTime} parameter - * - * @throws IllegalArgumentException - * If the {@code lastModifiedime} parameter is a negative value other - * than {@code -1L} - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * In the case of the default provider, the security manager's {@link - * SecurityManager#checkWrite(String) checkWrite} method is invoked - * to check write access to file - * - * @see BasicFileAttributeView#setTimes - */ - public static void setLastModifiedTime(FileRef file, - long lastModifiedTime, - TimeUnit unit) - throws IOException - { - file.getFileAttributeView(BasicFileAttributeView.class) - .setTimes(lastModifiedTime, null, null, unit); - } - - /** - * Updates the value of a file's last access time attribute. - * - * <p> The time value is measured since the epoch - * (00:00:00 GMT, January 1, 1970) and is converted to the precision supported - * by the file system. Converting from finer to coarser granularities result - * in precision loss. - * - * <p> If the file system does not support a last access time attribute then - * this method has no effect. - * - * @param lastAccessTime - * The new last access time, or {@code -1L} to update it to - * the current time - * @param unit - * A {@code TimeUnit} determining how to interpret the - * {@code lastModifiedTime} parameter - * - * @throws IllegalArgumentException - * If the {@code lastAccessTime} parameter is a negative value other - * than {@code -1L} - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * In the case of the default provider, the security manager's {@link - * SecurityManager#checkWrite(String) checkWrite} method is invoked - * to check write access to file - * - * @see BasicFileAttributeView#setTimes - */ - public static void setLastAccessTime(FileRef file, - long lastAccessTime, - TimeUnit unit) - throws IOException - { - file.getFileAttributeView(BasicFileAttributeView.class) - .setTimes(null, lastAccessTime, null, unit); - } - - /** - * Sets a file's POSIX permissions. - * - * <p> The {@code file} parameter is a reference to an existing file. It - * supports the {@link PosixFileAttributeView} that provides access to file - * attributes commonly associated with files on file systems used by - * operating systems that implement the Portable Operating System Interface - * (POSIX) family of standards. - * - * @param file - * A file reference that locates the file - * @param perms - * The new set of permissions - * - * @throws UnsupportedOperationException - * If {@code PosixFileAttributeView} is not available - * @throws ClassCastException - * If the sets contains elements that are not of type {@code - * PosixFilePermission} - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * In the case of the default provider, and a security manager is - * installed, it denies {@link RuntimePermission}<tt>("accessUserInformation")</tt> - * or its {@link SecurityManager#checkWrite(String) checkWrite} - * method denies write access to the file. - * - * @see PosixFileAttributeView#setPermissions - */ - public static void setPosixFilePermissions(FileRef file, - Set<PosixFilePermission> perms) - throws IOException - { - PosixFileAttributeView view = - file.getFileAttributeView(PosixFileAttributeView.class); - if (view == null) - throw new UnsupportedOperationException(); - view.setPermissions(perms); - } - - /** - * Reads the space attributes of a file store. - * - * <p> The {@code store} parameter is a file store that supports the - * {@link FileStoreSpaceAttributeView} providing access to the space related - * attributes of the file store. It is implementation specific if all attributes - * are read as an atomic operation with respect to other file system operations. - * - * @param store - * The file store - * - * @return The file store space attributes - * - * @throws UnsupportedOperationException - * If the file store space attribute view is not supported - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * In the case of the default provider, and a security manager is - * installed, its {@link SecurityManager#checkRead(String) checkRead} - * method is invoked to check read access to the file used to {@link - * FileRef#getFileStore obtain} access to the file - * store, and in addition it checks {@link RuntimePermission}<tt> - * ("getFileStoreAttributes")</tt> - * - * @see FileStoreSpaceAttributeView#readAttributes() - */ - public static FileStoreSpaceAttributes readFileStoreSpaceAttributes(FileStore store) - throws IOException - { - FileStoreSpaceAttributeView view = - store.getFileStoreAttributeView(FileStoreSpaceAttributeView.class); - if (view == null) - throw new UnsupportedOperationException(); - return view.readAttributes(); - } -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/BasicFileAttributeView.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,185 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file.attribute; - -import java.util.concurrent.TimeUnit; -import java.io.IOException; - -/** - * A file attribute view that provides a view of a <em>basic set</em> of file - * attributes common to many file systems. The basic set of file attributes - * consist of <em>mandatory</em> and <em>optional</em> file attributes as - * defined by the {@link BasicFileAttributes} interface. - - * <p> The file attributes are retrieved from the file system as a <em>bulk - * operation</em> by invoking the {@link #readAttributes() readAttributes} method. - * This class also defines the {@link #setTimes setTimes} method to update the - * file's time attributes. - * - * <p> Where dynamic access to file attributes is required, the attributes - * supported by this attribute view have the following names and types: - * <blockquote> - * <table border="1" cellpadding="8"> - * <tr> - * <th> Name </th> - * <th> Type </th> - * </tr> - * <tr> - * <td> "lastModifiedTime" </td> - * <td> {@link Long} </td> - * </tr> - * <tr> - * <td> "lastAccessTime" </td> - * <td> {@link Long} </td> - * </tr> - * <tr> - * <td> "creationTime" </td> - * <td> {@link Long} </td> - * </tr> - * <tr> - * <td> "resolution" </td> - * <td> {@link java.util.concurrent.TimeUnit} </td> - * </tr> - * <tr> - * <td> "size" </td> - * <td> {@link Long} </td> - * </tr> - * <tr> - * <td> "isRegularFile" </td> - * <td> {@link Boolean} </td> - * </tr> - * <tr> - * <td> "isDirectory" </td> - * <td> {@link Boolean} </td> - * </tr> - * <tr> - * <td> "isSymbolicLink" </td> - * <td> {@link Boolean} </td> - * </tr> - * <tr> - * <td> "isOther" </td> - * <td> {@link Boolean} </td> - * </tr> - * <tr> - * <td> "linkCount" </td> - * <td> {@link Integer} </td> - * </tr> - * <tr> - * <td> "fileKey" </td> - * <td> {@link Object} </td> - * </tr> - * </table> - * </blockquote> - * - * <p> The {@link #getAttribute getAttribute} or {@link - * #readAttributes(String,String[]) readAttributes(String,String[])} methods may - * be used to read any of these attributes as if by invoking the {@link - * #readAttributes() readAttributes()} method. - * - * <p> The {@link #setAttribute setAttribute} method may be used to update the - * file's last modified time, last access time or create time attributes as if - * by invoking the {@link #setTimes setTimes} method. In that case, the time - * value is interpreted in {@link TimeUnit#MILLISECONDS milliseconds} and - * converted to the precision supported by the file system. - * - * @since 1.7 - * @see Attributes - */ - -public interface BasicFileAttributeView - extends FileAttributeView -{ - /** - * Returns the name of the attribute view. Attribute views of this type - * have the name {@code "basic"}. - */ - - String name(); - - /** - * Reads the basic file attributes as a bulk operation. - * - * <p> It is implementation specific if all file attributes are read as an - * atomic operation with respect to other file system operations. - * - * @return The file attributes - * - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * In the case of the default provider, a security manager is - * installed, its {@link SecurityManager#checkRead(String) checkRead} - * method is invoked to check read access to the file - */ - BasicFileAttributes readAttributes() throws IOException; - - /** - * Updates any or all of the file's last modified time, last access time, - * and create time attributes. - * - * <p> This method updates the file's timestamp attributes. The values are - * measured since the epoch (00:00:00 GMT, January 1, 1970) and converted to - * the precision supported by the file system. Converting from finer to - * coarser granularities result in precision loss. - * - * <p> If any of the {@code lastModifiedTime}, {@code lastAccessTime}, - * or {@code createTime} parameters has the value {@code null} then the - * corresponding timestamp is not changed. An implementation may require to - * read the existing values of the file attributes when only some, but not - * all, of the timestamp attributes are updated. Consequently, this method - * may not be an atomic operation with respect to other file system - * operations. If all of the {@code lastModifiedTime}, {@code - * lastAccessTime} and {@code createTime} parameters are {@code null} then - * this method has no effect. - * - * @param lastModifiedTime - * The new last modified time, or {@code -1L} to update it to - * the current time, or {@code null} to not change the attribute - * @param lastAccessTime - * The last access time, or {@code -1L} to update it to - * the current time, or {@code null} to not change the attribute. - * @param createTime - * The file's create time, or {@code -1L} to update it to - * the current time, or {@code null} to not change the attribute - * @param unit - * A {@code TimeUnit} determining how to interpret the time values - * - * @throws IllegalArgumentException - * If any of the parameters is a negative value other than {@code - * -1L} - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * In the case of the default provider, a security manager is - * installed, its {@link SecurityManager#checkWrite(String) checkWrite} - * method is invoked to check write access to the file - */ - void setTimes(Long lastModifiedTime, - Long lastAccessTime, - Long createTime, - TimeUnit unit) throws IOException; -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/BasicFileAttributes.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,164 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file.attribute; - -import java.util.concurrent.TimeUnit; - -/** - * Basic attributes associated with a file in a file system. - * - * <p> Basic file attributes are attributes that are common to many file systems - * and consist of mandatory and optional file attributes as defined by this - * interface. - * - * <p> <b>Usage Example:</b> - * <pre> - * FileRef file = ... - * BasicFileAttributes attrs = Attributes.readBasicFileAttributes(file); - * </pre> - * - * @since 1.7 - * - * @see BasicFileAttributeView - */ - -public interface BasicFileAttributes { - - /** - * Returns the time of last modification. - * - * <p> The {@link #resolution() resolution} method returns the {@link TimeUnit} - * to interpret the return value of this method. - * - * @return A <code>long</code> value representing the time the file was - * last modified since the epoch (00:00:00 GMT, January 1, 1970), - * or {@code -1L} if the attribute is not supported. - */ - long lastModifiedTime(); - - /** - * Returns the time of last access if supported. - * - * <p> The {@link #resolution() resolution} method returns the {@link TimeUnit} - * to interpret the return value of this method. - * - * @return A <code>long</code> value representing the time of last access - * since the epoch (00:00:00 GMT, January 1, 1970), or {@code -1L} - * if the attribute is not supported. - */ - long lastAccessTime(); - - /** - * Returns the creation time if supported. The creation time is the time - * that the file was created. - * - * <p> The {@link #resolution() resolution} method returns the {@link TimeUnit} - * to interpret the return value of this method. - * - * @return A <code>long</code> value representing the time the file was - * created since the epoch (00:00:00 GMT, January 1, 1970), or - * {@code -1L} if the attribute is not supported. - */ - long creationTime(); - - /** - * Returns the {@link TimeUnit} required to interpret the time of last - * modification, time of last access, and creation time. - * - * @return The {@code TimeUnit} required to interpret the file time stamps - */ - TimeUnit resolution(); - - /** - * Tells whether the file is a regular file with opaque content. - */ - boolean isRegularFile(); - - /** - * Tells whether the file is a directory. - */ - boolean isDirectory(); - - /** - * Tells whether the file is a symbolic-link. - */ - boolean isSymbolicLink(); - - /** - * Tells whether the file is something other than a regular file, directory, - * or link. - */ - boolean isOther(); - - /** - * Returns the size of the file (in bytes). The size may differ from the - * actual size on the file system due to compression, support for sparse - * files, or other reasons. The size of files that are not {@link - * #isRegularFile regular} files is implementation specific and - * therefore unspecified. - * - * @return The file size, in bytes - */ - long size(); - - /** - * Returns the number of <em>links</em> to this file. - * - * <p> On file systems where the same file may be in several directories then - * the link count is the number of directory entries for the file. The return - * value is {@code 1} on file systems that only allow a file to have a - * single name in a single directory. - * - * @see java.nio.file.Path#createLink - */ - int linkCount(); - - /** - * Returns an object that uniquely identifies the given file, or {@code - * null} if a file key is not available. On some platforms or file systems - * it is possible to use an identifier, or a combination of identifiers to - * uniquely identify a file. Such identifiers are important for operations - * such as file tree traversal in file systems that support <a - * href="../package-summary.html#links">symbolic links</a> or file systems - * that allow a file to be an entry in more than one directory. On UNIX file - * systems, for example, the <em>device ID</em> and <em>inode</em> are - * commonly used for such purposes. - * - * <p> The file key returned by this method can only be guaranteed to be - * unique if the file system and files remain static. Whether a file system - * re-use identifiers after a file is deleted is implementation dependent and - * therefore unspecified. - * - * <p> File keys returned by this method can be compared for equality and are - * suitable for use in collections. If the file system and files remain static, - * and two files are the {@link java.nio.file.FileRef#isSameFile same} with - * non-{@code null} file keys, then their file keys are equal. - * - * @see java.nio.file.Files#walkFileTree - */ - Object fileKey(); -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/DosFileAttributeView.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,180 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file.attribute; - -import java.io.IOException; - -/** - * A file attribute view that provides a view of the legacy "DOS" file attributes. - * These attributes are supported by file systems such as the File Allocation - * Table (FAT) format commonly used in <em>consumer devices</em>. - * - * <p> A {@code DosFileAttributeView} is a {@link BasicFileAttributeView} that - * additionally supports access to the set of DOS attribute flags that are used - * to indicate if the file is read-only, hidden, a system file, or archived. - * - * <p> Where dynamic access to file attributes is required, the attributes - * supported by this attribute view are as defined by {@code - * BasicFileAttributeView}, and in addition, the following attributes are - * supported: - * <blockquote> - * <table border="1" cellpadding="8"> - * <tr> - * <th> Name </th> - * <th> Type </th> - * </tr> - * <tr> - * <td> readonly </td> - * <td> {@link Boolean} </td> - * </tr> - * <tr> - * <td> hidden </td> - * <td> {@link Boolean} </td> - * </tr> - * <tr> - * <td> system </td> - * <td> {@link Boolean} </td> - * </tr> - * <tr> - * <td> archive </td> - * <td> {@link Boolean} </td> - * </tr> - * </table> - * </blockquote> - * - * <p> The {@link #getAttribute getAttribute} or {@link #readAttributes(String,String[]) - * readAttributes(String,String[])} methods may be used to read any of these - * attributes, or any of the attributes defined by {@link BasicFileAttributeView} - * as if by invoking the {@link #readAttributes readAttributes()} method. - * - * <p> The {@link #setAttribute setAttribute} method may be used to update the - * file's last modified time, last access time or create time attributes as - * defined by {@link BasicFileAttributeView}. It may also be used to update - * the DOS attributes as if by invoking the {@link #setReadOnly setReadOnly}, - * {@link #setHidden setHidden}, {@link #setSystem setSystem}, and {@link - * #setArchive setArchive} methods respectively. - * - * @since 1.7 - */ - -public interface DosFileAttributeView - extends BasicFileAttributeView -{ - /** - * Returns the name of the attribute view. Attribute views of this type - * have the name {@code "dos"}. - */ - - String name(); - - /** - * @throws IOException {@inheritDoc} - * @throws SecurityException {@inheritDoc} - */ - - DosFileAttributes readAttributes() throws IOException; - - /** - * Updates the value of the read-only attribute. - * - * <p> It is implementation specific if the attribute can be updated as an - * atomic operation with respect to other file system operations. An - * implementation may, for example, require to read the existing value of - * the DOS attribute in order to update this attribute. - * - * @param value - * The new value of the attribute - * - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * In the case of the default, and a security manager is installed, - * its {@link SecurityManager#checkWrite(String) checkWrite} method - * is invoked to check write access to the file - */ - void setReadOnly(boolean value) throws IOException; - - /** - * Updates the value of the hidden attribute. - * - * <p> It is implementation specific if the attribute can be updated as an - * atomic operation with respect to other file system operations. An - * implementation may, for example, require to read the existing value of - * the DOS attribute in order to update this attribute. - * - * @param value - * The new value of the attribute - * - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * In the case of the default, and a security manager is installed, - * its {@link SecurityManager#checkWrite(String) checkWrite} method - * is invoked to check write access to the file - */ - void setHidden(boolean value) throws IOException; - - /** - * Updates the value of the system attribute. - * - * <p> It is implementation specific if the attribute can be updated as an - * atomic operation with respect to other file system operations. An - * implementation may, for example, require to read the existing value of - * the DOS attribute in order to update this attribute. - * - * @param value - * The new value of the attribute - * - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * In the case of the default, and a security manager is installed, - * its {@link SecurityManager#checkWrite(String) checkWrite} method - * is invoked to check write access to the file - */ - void setSystem(boolean value) throws IOException; - - /** - * Updates the value of the archive attribute. - * - * <p> It is implementation specific if the attribute can be updated as an - * atomic operation with respect to other file system operations. An - * implementation may, for example, require to read the existing value of - * the DOS attribute in order to update this attribute. - * - * @param value - * The new value of the attribute - * - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * In the case of the default, and a security manager is installed, - * its {@link SecurityManager#checkWrite(String) checkWrite} method - * is invoked to check write access to the file - */ - void setArchive(boolean value) throws IOException; -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/DosFileAttributes.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,85 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file.attribute; - -/** - * File attributes associated with a file in a file system that supports - * legacy "DOS" attributes. - * - * <p> The DOS attributes of a file are retrieved using a {@link - * DosFileAttributeView} by invoking its {@link DosFileAttributeView#readAttributes - * readAttributes} method. - * - * @since 1.7 - * - * @see Attributes#readDosFileAttributes - */ - -public interface DosFileAttributes - extends BasicFileAttributes -{ - /** - * Returns the value of the read-only attribute. - * - * <p> This attribute is often used as a simple access control mechanism - * to prevent files from being deleted or updated. Whether the file system - * or platform does any enforcement to prevent <em>read-only</em> files - * from being updated is implementation specific. - * - * @return The value of the read-only attribute. - */ - boolean isReadOnly(); - - /** - * Returns the value of the hidden attribute. - * - * <p> This attribute is often used to indicate if the file is visible to - * users. - * - * @return The value of the hidden attribute. - */ - boolean isHidden(); - - /** - * Returns the value of the archive attribute. - * - * <p> This attribute is typically used by backup programs. - * - * @return The value of the archive attribute. - */ - boolean isArchive(); - - /** - * Returns the value of the system attribute. - * - * <p> This attribute is often used to indicate that the file is a component - * of the operating system. - * - * @return The value of the system attribute. - */ - boolean isSystem(); -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/FileAttribute.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,51 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file.attribute; - -/** - * An object that encapsulates the value of a file attribute that can be set - * atomically when creating a new file or directory by invoking the {@link - * java.nio.file.Path#createFile createFile} or {@link - * java.nio.file.Path#createDirectory createDirectory} methods. - * - * @param <T> The type of the file attribute value - * - * @since 1.7 - * @see PosixFilePermissions#asFileAttribute - */ - -public interface FileAttribute<T> { - /** - * Returns the attribute name. - */ - String name(); - - /** - * Returns the attribute value. - */ - T value(); -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/FileAttributeView.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,44 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file.attribute; - -/** - * An attribute view that is a read-only or updatable view of non-opaque - * values associated with a file in a filesystem. This interface is extended or - * implemented by specific file attribute views that define methods to read - * and/or update the attributes of a file. - * - * @since 1.7 - * - * @see java.nio.file.FileRef#getFileAttributeView(Class,java.nio.file.LinkOption[]) - * @see java.nio.file.FileRef#getFileAttributeView(String,java.nio.file.LinkOption[]) - */ - -public interface FileAttributeView - extends AttributeView -{ -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/FileOwnerAttributeView.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,102 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file.attribute; - -import java.io.IOException; - -/** - * A file attribute view that supports reading or updating the owner of a file. - * This file attribute view is intended for file system implementations that - * support a file attribute that represents an identity that is the owner of - * the file. Often the owner of a file is the identity of the entity that - * created the file. - * - * <p> The {@link #getOwner getOwner} or {@link #setOwner setOwner} methods may - * be used to read or update the owner of the file. - * - * <p> Where dynamic access to file attributes is required, the owner attribute - * is identified by the name {@code "owner"}, and the value of the attribute is - * a {@link UserPrincipal}. The {@link #readAttributes readAttributes}, {@link - * #getAttribute getAttribute} and {@link #setAttribute setAttributes} methods - * may be used to read or update the file owner. - * - * @since 1.7 - */ - -public interface FileOwnerAttributeView - extends FileAttributeView -{ - /** - * Returns the name of the attribute view. Attribute views of this type - * have the name {@code "owner"}. - */ - - String name(); - - /** - * Read the file owner. - * - * <p> It it implementation specific if the file owner can be a {@link - * GroupPrincipal group}. - * - * @return the file owner - * - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * In the case of the default provider, a security manager is - * installed, and it denies {@link - * RuntimePermission}<tt>("accessUserInformation")</tt> or its - * {@link SecurityManager#checkRead(String) checkRead} method - * denies read access to the file. - */ - UserPrincipal getOwner() throws IOException; - - /** - * Updates the file owner. - * - * <p> It it implementation specific if the file owner can be a {@link - * GroupPrincipal group}. To ensure consistent and correct behavior - * across platforms it is recommended that this method should only be used - * to set the file owner to a user principal that is not a group. - * - * @param owner - * The new file owner - * - * @throws IOException - * If an I/O error occurs, or the {@code owner} parameter is a - * group and this implementation does not support setting the owner - * to a group - * @throws SecurityException - * In the case of the default provider, a security manager is - * installed, and it denies {@link - * RuntimePermission}<tt>("accessUserInformation")</tt> or its - * {@link SecurityManager#checkWrite(String) checkWrite} method - * denies write access to the file. - */ - void setOwner(UserPrincipal owner) throws IOException; -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/FileStoreAttributeView.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,39 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file.attribute; - -/** - * An attribute view that is a read-only or updatable view of the attributes of - * a {@link java.nio.file.FileStore}. - * - * @since 1.7 - */ - -public interface FileStoreAttributeView - extends AttributeView -{ -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/FileStoreSpaceAttributeView.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,94 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file.attribute; - -import java.util.Map; -import java.io.IOException; - -/** - * A file store attribute view that supports reading of space attributes. - * - * <p> Where dynamic access to file attributes is required, the attributes - * supported by this attribute view have the following names and types: - * <blockquote> - * <table border="1" cellpadding="8"> - * <tr> - * <th> Name </th> - * <th> Type </th> - * </tr> - * <tr> - * <td> "totalSpace" </td> - * <td> {@link Long} </td> - * </tr> - * <tr> - * <td> "usableSpace" </td> - * <td> {@link Long} </td> - * </tr> - * <tr> - * <td> "unallocatedSpace" </td> - * <td> {@link Long} </td> - * </tr> - * </table> - * </blockquote> - * <p> The {@link #getAttribute getAttribute} or {@link #readAttributes - * readAttributes(String,String[])} methods may be used to read any of these - * attributes as if by invoking the {@link #readAttributes readAttributes()} - * method. - * - * @since 1.7 - */ - -public interface FileStoreSpaceAttributeView - extends FileStoreAttributeView -{ - /** - * Returns the name of the attribute view. Attribute views of this type - * have the name {@code "space"}. - */ - - String name(); - - /** - * Reads the disk space attributes as a bulk operation. - * - * <p> It is file system specific if all attributes are read as an - * atomic operation with respect to other file system operations. - * - * @return The disk space attributes - * - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * In the case of the default provider, and a security manager is - * installed, its {@link SecurityManager#checkRead(String) checkRead} - * method is invoked to check read access to the file used to {@link - * FileRef#getFileStore obtain} access to the file - * system, and in addition it checks {@link RuntimePermission}<tt> - * ("getFileStoreAttributes")</tt> - */ - FileStoreSpaceAttributes readAttributes() throws IOException; -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/FileStoreSpaceAttributes.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,67 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file.attribute; - -/** - * Space related attributes of a file store. - * - * @since 1.7 - * - * @see Attributes#readFileStoreSpaceAttributes - */ - -public interface FileStoreSpaceAttributes { - /** - * Returns the size, in bytes, of the file store. - */ - long totalSpace(); - - /** - * Returns the number of bytes available to this Java virtual machine on the - * file store. - * - * <p> The returned number of available bytes is a hint, but not a - * guarantee, that it is possible to use most or any of these bytes. The - * number of usable bytes is most likely to be accurate immediately - * after the space attributes are obtained. It is likely to be made inaccurate - * by any external I/O operations including those made on the system outside - * of this Java virtual machine. - */ - long usableSpace(); - - /** - * Returns the number of unallocated bytes in the file store. - * - * <p> The returned number of unallocated bytes is a hint, but not a - * guarantee, that it is possible to use most or any of these bytes. The - * number of unallocated bytes is most likely to be accurate immediately - * after the space attributes are obtained. It is likely to be - * made inaccurate by any external I/O operations including those made on - * the system outside of this virtual machine. - */ - long unallocatedSpace(); -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/GroupPrincipal.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,43 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file.attribute; - -/** - * A {@code UserPrincipal} representing a <em>group identity</em>, used to - * determine access rights to objects in a file system. The exact definition of - * a group is implementation specific, but typically, it represents an identity - * created for administrative purposes so as to determine the access rights for - * the members of the group. Whether an entity can be a member of multiple - * groups, and whether groups can be nested, are implementation specified and - * therefore not specified. - * - * @since 1.7 - * - * @see UserPrincipalLookupService#lookupPrincipalByGroupName - */ - -public interface GroupPrincipal extends UserPrincipal { }
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/NamedAttributeView.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,231 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file.attribute; - -import java.nio.ByteBuffer; -import java.util.List; -import java.io.IOException; - -/** - * A file attribute view that provides a view of a file's user-defined - * attributes, sometimes known as <em>extended attributes</em>. Named attributes - * are used to store metadata with a file that is not meaningful to the file - * system. It is primarily intended for file system implementations that support - * such a capability directly but may be emulated. The details of such emulation - * are highly implementation specific and therefore not specified. - * - * <p> This {@code FileAttributeView} provides a view of a file's named - * attributes as a set of name/value pairs, where the attribute name is - * represented by a {@code String}. An implementation may require to encode and - * decode from the platform or file system representation when accessing the - * attribute. The value has opaque content. This attribute view defines the - * {@link #read read} and {@link #write write} methods to read the value into - * or write from a {@link ByteBuffer}. This {@code FileAttributeView} is not - * intended for use where the size of an attribute value is larger than {@link - * Integer#MAX_VALUE}. - * - * <p> Named attributes may be used in some implementations to store security - * related attributes so consequently, in the case of the default provider at - * least, all methods that access named attributes require the - * {@code RuntimePermission("accessNamedAttributes")} permission when a - * security manager is installed. - * - * <p> The {@link java.nio.file.FileStore#supportsFileAttributeView - * supportsFileAttributeView} method may be used to test if a specific {@link - * java.nio.file.FileStore FileStore} supports the storage of named attributes. - * - * <p> Where dynamic access to file attributes is required, the {@link - * #getAttribute getAttribute} or {@link #readAttributes(String,String[]) - * readAttributes(String,String[])} methods may be used to read the attribute - * value. The attribute value is returned as a byte array (byte[]). The {@link - * #setAttribute setAttribute} method may be used to write the value of a - * user-defined/named attribute from a buffer (as if by invoking the {@link - * #write write} method), or byte array (byte[]). - * - * @since 1.7 - */ - -public interface NamedAttributeView - extends FileAttributeView -{ - /** - * Returns the name of this attribute view. Attribute views of this type - * have the name {@code "xattr"}. - */ - - String name(); - - /** - * Returns a list containing the names of the user-defined/named - * attributes. - * - * @return An unmodifiable list continaing the names of the file's - * user-defined/named attributes - * - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * In the case of the default provider, a security manager is - * installed, and it denies {@link - * RuntimePermission}<tt>("accessNamedAttributes")</tt> - * or its {@link SecurityManager#checkRead(String) checkRead} method - * denies read access to the file. - */ - List<String> list() throws IOException; - - /** - * Returns the size of the value of a user-defined/named attribute. - * - * @param name - * The attribute name - * - * @return The size of the attribute value, in bytes. - * - * @throws ArithmeticException - * If the size of the attribute is larger than {@link Integer#MAX_VALUE} - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * In the case of the default provider, a security manager is - * installed, and it denies {@link - * RuntimePermission}<tt>("accessNamedAttributes")</tt> - * or its {@link SecurityManager#checkRead(String) checkRead} method - * denies read access to the file. - */ - int size(String name) throws IOException; - - /** - * Read the value of a user-defined/named attribute into a buffer. - * - * <p> This method reads the value of the attribute into the given buffer - * as a sequence of bytes, failing if the number of bytes remaining in - * the buffer is insufficient to read the complete attribute value. The - * number of bytes transferred into the buffer is {@code n}, where {@code n} - * is the size of the attribute value. The first byte in the sequence is at - * index {@code p} and the last byte is at index {@code p + n - 1}, where - * {@code p} is the buffer's position. Upon return the buffer's position - * will be equal to {@code p + n}; its limit will not have changed. - * - * <p> <b>Usage Example:</b> - * Suppose we want to read a file's MIME type that is stored as a named - * attribute: - * <pre> - * NamedAttributeView view = file.getFileAttributeView(NamedAttributeView.class); - * String name = "user.mimetype"; - * ByteBuffer buf = ByteBuffer.allocate(view.size(name)); - * view.read(name, buf); - * buf.flip(); - * String value = Charset.defaultCharset().decode(buf).toString(); - * </pre> - * - * @param name - * The attribute name - * @param dst - * The destination buffer - * - * @return The number of bytes read, possibly zero - * - * @throws IllegalArgumentException - * If the destination buffer is read-only - * @throws IOException - * If an I/O error occurs or there is insufficient space in the - * destination buffer for the attribute value - * @throws SecurityException - * In the case of the default provider, a security manager is - * installed, and it denies {@link - * RuntimePermission}<tt>("accessNamedAttributes")</tt> - * or its {@link SecurityManager#checkRead(String) checkRead} method - * denies read access to the file. - * - * @see #size - */ - int read(String name, ByteBuffer dst) throws IOException; - - /** - * Writes the value of a user-defined/named attribute from a buffer. - * - * <p> This method writes the value of the attribute from a given buffer as - * a sequence of bytes. The size of the value to transfer is {@code r}, - * where {@code r} is the number of bytes remaining in the buffer, that is - * {@code src.remaining()}. The sequence of bytes is transferred from the - * buffer starting at index {@code p}, where {@code p} is the buffer's - * position. Upon return, the buffer's position will be equal to {@code - * p + n}, where {@code n} is the number of bytes transferred; its limit - * will not have changed. - * - * <p> If an attribute of the given name already exists then its value is - * replaced. If the attribute does not exist then it is created. If it - * implementation specific if a test to check for the existence of the - * attribute and the creation of attribute are atomic with repect to other - * file system activities. - * - * <p> Where there is insufficient space to store the attribute, or the - * attribute name or value exceed an implementation specific maximum size - * then an {@code IOException} is thrown. - * - * <p> <b>Usage Example:</b> - * Suppose we want to write a file's MIME type as a named attribute: - * <pre> - * NamedAttributeView view = file.getFileAttributeView(NamedAttributeView.class); - * view.write("user.mimetype", Charset.defaultCharset().encode("text/html")); - * </pre> - * - * @param name - * The attribute name - * @param src - * The buffer containing the attribute value - * - * @return The number of bytes written, possibly zero - * - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * In the case of the default provider, a security manager is - * installed, and it denies {@link - * RuntimePermission}<tt>("accessNamedAttributes")</tt> - * or its {@link SecurityManager#checkWrite(String) checkWrite} - * method denies write access to the file. - */ - int write(String name, ByteBuffer src) throws IOException; - - /** - * Deletes a user-defined/named attribute. - * - * @param name - * The attribute name - * - * @throws IOException - * If an I/O error occurs or the attribute does not exist - * @throws SecurityException - * In the case of the default provider, a security manager is - * installed, and it denies {@link - * RuntimePermission}<tt>("accessNamedAttributes")</tt> - * or its {@link SecurityManager#checkWrite(String) checkWrite} - * method denies write access to the file. - */ - void delete(String name) throws IOException; -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/PosixFileAttributeView.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,196 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file.attribute; - -import java.util.Set; -import java.io.IOException; - -/** - * A file attribute view that provides a view of the file attributes commonly - * associated with files on file systems used by operating systems that implement - * the Portable Operating System Interface (POSIX) family of standards. - * - * <p> Operating systems that implement the <a href="http://www.opengroup.org"> - * POSIX</a> family of standards commonly use file systems that have a - * file <em>owner</em>, <em>group-owner</em>, and related <em>access - * permissions</em>. This file attribute view provides read and write access - * to these attributes. - * - * <p> The {@link #readAttributes() readAttributes} method is used to read the - * file's attributes. The file {@link PosixFileAttributes#owner() owner} is - * represented by a {@link UserPrincipal} that is the identity of the file owner - * for the purposes of access control. The {@link PosixFileAttributes#group() - * group-owner}, represented by a {@link GroupPrincipal}, is the identity of the - * group owner, where a group is an identity created for administrative purposes - * so as to determine the access rights for the members of the group. - * - * <p> The {@link PosixFileAttributes#permissions() permissions} attribute is a - * set of access permissions. This file attribute view provides access to the nine - * permission defined by the {@link PosixFilePermission} class. - * These nine permission bits determine the <em>read</em>, <em>write</em>, and - * <em>execute</em> access for the file owner, group, and others (others - * meaning identities other than the owner and members of the group). Some - * operating systems and file systems may provide additional permission bits - * but access to these other bits is not defined by this class in this release. - * - * <p> <b>Usage Example:</b> - * Suppose we need to print out the owner and access permissions of a file: - * <pre> - * FileRef file = ... - * PosixFileAttributes attrs = file.newFileAttributeView(PosixFileAttributeView.class) - * .readAttributes(); - * System.out.format("%s %s%n", - * atts.owner().getName(), - * PosixFilePermissions.toString(attrs.permissions())); - * </pre> - * - * <h4> Dynamic Access </h4> - * <p> Where dynamic access to file attributes is required, the attributes - * supported by this attribute view are as defined by {@link - * BasicFileAttributeView} and {@link FileOwnerAttributeView}, and in addition, - * the following attributes are supported: - * <blockquote> - * <table border="1" cellpadding="8"> - * <tr> - * <th> Name </th> - * <th> Type </th> - * </tr> - * <tr> - * <td> "permissions" </td> - * <td> {@link Set}<{@link PosixFilePermission}> </td> - * </tr> - * <tr> - * <td> "group" </td> - * <td> {@link GroupPrincipal} </td> - * </tr> - * </table> - * </blockquote> - * - * <p> The {@link #getAttribute getAttribute} or {@link - * #readAttributes(String,String[]) readAttributes(String,String[])} methods may - * be used to read any of these attributes, or any of the attributes defined by - * {@link BasicFileAttributeView} as if by invoking the {@link #readAttributes - * readAttributes()} method. - * - * <p> The {@link #setAttribute setAttribute} method may be used to update the - * file's last modified time, last access time or create time attributes as - * defined by {@link BasicFileAttributeView}. It may also be used to update - * the permissions, owner, or group-owner as if by invoking the {@link - * #setPermissions setPermissions}, {@link #setOwner setOwner}, and {@link - * #setGroup setGroup} methods respectively. - * - * <h4> Setting Initial Permissions </h4> - * <p> Implementations supporting this attribute view may also support setting - * the initial permissions when creating a file or directory. The - * initial permissions are provided to the {@link Path#createFile createFile} - * or {@link Path#createDirectory createDirectory} methods as a {@link - * FileAttribute} with {@link FileAttribute#name name} {@code "posix:permissions"} - * and a {@link FileAttribute#value value} that is the set of permissions. The - * following example uses the {@link PosixFilePermissions#asFileAttribute - * asFileAttribute} method to construct a {@code FileAttribute} when creating a - * file: - * - * <pre> - * Path path = ... - * Set<PosixFilePermission> perms = - * EnumSet.of(OWNER_READ, OWNER_WRITE, OWNER_EXECUTE, GROUP_READ); - * path.createFile(PosixFilePermissions.asFileAttribute(perms)); - * </pre> - * - * <p> When the access permissions are set at file creation time then the actual - * value of the permissions may differ that the value of the attribute object. - * The reasons for this are implementation specific. On UNIX systems, for - * example, a process has a <em>umask</em> that impacts the permission bits - * of newly created files. Where an implementation supports the setting of - * the access permissions, and the underlying file system supports access - * permissions, then it is required that the value of the actual access - * permissions will be equal or less than the value of the attribute - * provided to the {@link java.nio.file.Path#createFile createFile} or - * {@link java.nio.file.Path#createDirectory createDirectory} methods. In - * other words, the file may be more secure than requested. - * - * @since 1.7 - * - * @see Attributes#readPosixFileAttributes - */ - -public interface PosixFileAttributeView - extends BasicFileAttributeView, FileOwnerAttributeView -{ - /** - * Returns the name of the attribute view. Attribute views of this type - * have the name {@code "posix"}. - */ - - String name(); - - /** - * @throws IOException {@inheritDoc} - * @throws SecurityException - * In the case of the default provider, a security manager is - * installed, and it denies {@link RuntimePermission}<tt>("accessUserInformation")</tt> - * or its {@link SecurityManager#checkRead(String) checkRead} method - * denies read access to the file. - */ - - PosixFileAttributes readAttributes() throws IOException; - - /** - * Updates the file permissions. - * - * @param perms - * The new set of permissions - * - * @throws ClassCastException - * If the sets contains elements that are not of type {@code - * PosixFilePermission} - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * In the case of the default provider, a security manager is - * installed, and it denies {@link RuntimePermission}<tt>("accessUserInformation")</tt> - * or its {@link SecurityManager#checkWrite(String) checkWrite} - * method denies write access to the file. - */ - void setPermissions(Set<PosixFilePermission> perms) throws IOException; - - /** - * Updates the file group-owner. - * - * @param group - * The new file group-owner - - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * In the case of the default provider, and a security manager is - * installed, it denies {@link RuntimePermission}<tt>("accessUserInformation")</tt> - * or its {@link SecurityManager#checkWrite(String) checkWrite} - * method denies write access to the file. - */ - void setGroup(GroupPrincipal group) throws IOException; -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/PosixFileAttributes.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,78 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file.attribute; - -import java.util.Set; - -/** - * File attributes associated with files on file systems used by operating systems - * that implement the Portable Operating System Interface (POSIX) family of - * standards. - * - * <p> The POSIX attributes of a file are retrieved using a {@link - * PosixFileAttributeView} by invoking its {@link - * PosixFileAttributeView#readAttributes readAttributes} method. - * - * @since 1.7 - * - * @see Attributes#readPosixFileAttributes - */ - -public interface PosixFileAttributes - extends BasicFileAttributes -{ - /** - * Returns the owner of the file. - * - * @return The file owner - * - * @see PosixFileAttributeView#setOwner - */ - UserPrincipal owner(); - - /** - * Returns the group owner of the file. - * - * @return The file group owner - * - * @see PosixFileAttributeView#setGroup - */ - GroupPrincipal group(); - - /** - * Returns the permissions of the file. The file permissions are returned - * as a set of {@link PosixFilePermission} elements. The returned set is a - * copy of the file permissions and is modifiable. This allows the result - * to be modified and passed to the {@link PosixFileAttributeView#setPermissions - * setPermissions} method to update the file's permissions. - * - * @return The file permissions - * - * @see PosixFileAttributeView#setPermissions - */ - Set<PosixFilePermission> permissions(); -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/PosixFilePermission.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,87 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file.attribute; - -import java.util.*; - -/** - * Defines the bits for use with the {@link PosixFileAttributes#permissions() - * permissions} attribute. - * - * <p> The {@link PosixFileAttributes} class defines method methods for - * manipulating {@link Set sets} of permissions. - * - * @since 1.7 - */ - -public enum PosixFilePermission { - - /** - * Read permission, owner. - */ - OWNER_READ, - - /** - * Write permission, owner. - */ - OWNER_WRITE, - - /** - * Execute/search permission, owner. - */ - OWNER_EXECUTE, - - /** - * Read permission, group. - */ - GROUP_READ, - - /** - * Write permission, group. - */ - GROUP_WRITE, - - /** - * Execute/search permission, group. - */ - GROUP_EXECUTE, - - /** - * Read permission, others. - */ - OTHERS_READ, - - /** - * Write permission, others. - */ - OTHERS_WRITE, - - /** - * Execute/search permission, others. - */ - OTHERS_EXECUTE; -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/PosixFilePermissions.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,190 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file.attribute; - -import java.util.*; - -import static org.classpath.icedtea.java.nio.file.attribute.PosixFilePermission.OWNER_READ; -import static org.classpath.icedtea.java.nio.file.attribute.PosixFilePermission.OWNER_WRITE; -import static org.classpath.icedtea.java.nio.file.attribute.PosixFilePermission.OWNER_EXECUTE; -import static org.classpath.icedtea.java.nio.file.attribute.PosixFilePermission.GROUP_READ; -import static org.classpath.icedtea.java.nio.file.attribute.PosixFilePermission.GROUP_WRITE; -import static org.classpath.icedtea.java.nio.file.attribute.PosixFilePermission.GROUP_EXECUTE; -import static org.classpath.icedtea.java.nio.file.attribute.PosixFilePermission.OTHERS_READ; -import static org.classpath.icedtea.java.nio.file.attribute.PosixFilePermission.OTHERS_WRITE; -import static org.classpath.icedtea.java.nio.file.attribute.PosixFilePermission.OTHERS_EXECUTE; - -/** - * This class consists exclusively of static methods that operate on sets of - * {@link PosixFilePermission} objects. - * - * @since 1.7 - */ - -public class PosixFilePermissions { - private PosixFilePermissions() { } - - // Write string representation of permission bits to {@code sb}. - private static void writeBits(StringBuilder sb, boolean r, boolean w, boolean x) { - if (r) { - sb.append('r'); - } else { - sb.append('-'); - } - if (w) { - sb.append('w'); - } else { - sb.append('-'); - } - if (x) { - sb.append('x'); - } else { - sb.append('-'); - } - } - - /** - * Returns the {@code String} representation of a set of permissions. - * - * <p> If the set contains {@code null} or elements that are not of type - * {@code PosixFilePermission} then these elements are ignored. - * - * @param perms - * The set of permissions - * - * @return The string representation of the permission set - * - * @see #fromString - */ - public static String toString(Set<PosixFilePermission> perms) { - StringBuilder sb = new StringBuilder(9); - writeBits(sb, perms.contains(OWNER_READ), perms.contains(OWNER_WRITE), - perms.contains(OWNER_EXECUTE)); - writeBits(sb, perms.contains(GROUP_READ), perms.contains(GROUP_WRITE), - perms.contains(GROUP_EXECUTE)); - writeBits(sb, perms.contains(OTHERS_READ), perms.contains(OTHERS_WRITE), - perms.contains(OTHERS_EXECUTE)); - return sb.toString(); - } - - private static boolean isSet(char c, char setValue) { - if (c == setValue) - return true; - if (c == '-') - return false; - throw new IllegalArgumentException("Invalid mode"); - } - private static boolean isR(char c) { return isSet(c, 'r'); } - private static boolean isW(char c) { return isSet(c, 'w'); } - private static boolean isX(char c) { return isSet(c, 'x'); } - - /** - * Returns the set of permissions corresponding to a given {@code String} - * representation. - * - * <p> The {@code perms} parameter is a {@code String} representing the - * permissions. It has 9 characters that are interpreted as three sets of - * three. The first set refers to the owner's permissions; the next to the - * group permissions and the last to others. Within each set, the first - * character is {@code 'r'} to indicate permission to read, the second - * character is {@code 'w'} to indicate permission to write, and the third - * character is {@code 'x'} for execute permission. Where a permission is - * not set then the corresponding character is set to {@code '-'}. - * - * <p> <b>Usage Example:</b> - * Suppose we require the set of permissions that indicate the owner has read, - * write, and execute permissions, the group has read and execute permissions - * and others have none. - * <pre> - * Set<PosixFilePermission> perms = PosixFilePermissions.fromString("rwxr-x---"); - * </pre> - * - * @param perms - * String representing a set of permissions - * - * @return The resulting set of permissions - * - * @throws IllegalArgumentException - * If the string cannot be converted to a set of permissions - * - * @see #toString(Set) - */ - public static Set<PosixFilePermission> fromString(String perms) { - if (perms.length() != 9) - throw new IllegalArgumentException("Invalid mode"); - Set<PosixFilePermission> result = new HashSet<PosixFilePermission>(); - if (isR(perms.charAt(0))) result.add(OWNER_READ); - if (isW(perms.charAt(1))) result.add(OWNER_WRITE); - if (isX(perms.charAt(2))) result.add(OWNER_EXECUTE); - if (isR(perms.charAt(3))) result.add(GROUP_READ); - if (isW(perms.charAt(4))) result.add(GROUP_WRITE); - if (isX(perms.charAt(5))) result.add(GROUP_EXECUTE); - if (isR(perms.charAt(6))) result.add(OTHERS_READ); - if (isW(perms.charAt(7))) result.add(OTHERS_WRITE); - if (isX(perms.charAt(8))) result.add(OTHERS_EXECUTE); - return result; - } - - /** - * Creates a {@link FileAttribute}, encapsulating a copy of the given file - * permissions, suitable for passing to the {@link java.nio.file.Path#createFile - * createFile} or {@link java.nio.file.Path#createDirectory createDirectory} - * methods. - * - * @param perms - * The set of permissions - * - * @return An attribute encapsulating the given file permissions with - * {@link FileAttribute#name name} {@code "posix:permissions"} - * - * @throws ClassCastException - * If the sets contains elements that are not of type {@code - * PosixFilePermission} - */ - public static FileAttribute<Set<PosixFilePermission>> - asFileAttribute(Set<PosixFilePermission> perms) - { - // copy set and check for nulls (CCE will be thrown if an element is not - // a PosixFilePermission) - perms = new HashSet<PosixFilePermission>(perms); - for (PosixFilePermission p: perms) { - if (p == null) - throw new NullPointerException(); - } - final Set<PosixFilePermission> value = perms; - return new FileAttribute<Set<PosixFilePermission>>() { - - public String name() { - return "posix:permissions"; - } - - public Set<PosixFilePermission> value() { - return Collections.unmodifiableSet(value); - } - }; - } -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/UserPrincipal.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,55 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file.attribute; - -import java.security.Principal; - -/** - * A {@code Principal} representing an identity used to determine access rights - * to objects in a file system. - * - * <p> On many platforms and file systems an entity requires appropriate access - * rights or permissions in order to access objects in a file system. The - * access rights are generally performed by checking the identity of the entity. - * For example, on implementations that use Access Control Lists (ACLs) to - * enforce privilege separation then a file in the file system may have an - * associated ACL that determine the access rights of identities specified in the - * ACL. - * - * <p> A {@code UserPrincipal} object is an abstract representation of an - * identity. It has a {@link #getName() name} that is typically the username or - * account name that it represents. User principal objects may be obtained using - * a {@link UserPrincipalLookupService}, or returned by {@link - * FileAttributeView} implementations that provide access to identity related - * attributes. For example, the {@link AclFileAttributeView} and {@link - * PosixFileAttributeView} provide access to a file's {@link - * PosixFileAttributes#owner owner}. - * - * @since 1.7 - */ - -public interface UserPrincipal extends Principal { }
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/UserPrincipalLookupService.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,105 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file.attribute; - -import java.io.IOException; - -/** - * An object to lookup user and group principals by name. A {@link UserPrincipal} - * represents an identity that may be used to determine access rights to objects - * in a file system. A {@link GroupPrincipal} represents a <em>group identity</em>. - * A {@code UserPrincipalLookupService} defines methods to lookup identities by - * name or group name (which are typically user or account names). Whether names - * and group names are case sensitive or not depends on the implementation. - * The exact definition of a group is implementation specific but typically a - * group represents an identity created for administrative purposes so as to - * determine the access rights for the members of the group. In particular it is - * implementation specific if the <em>namespace</em> for names and groups is the - * same or is distinct. To ensure consistent and correct behavior across - * platforms it is recommended that this API be used as if the namespaces are - * distinct. In other words, the {@link #lookupPrincipalByName - * lookupPrincipalByName} should be used to lookup users, and {@link - * #lookupPrincipalByGroupName lookupPrincipalByGroupName} should be used to - * lookup groups. - * - * @since 1.7 - * - * @see java.nio.file.FileSystem#getUserPrincipalLookupService - */ - -public abstract class UserPrincipalLookupService { - - /** - * Initializes a new instance of this class. - */ - protected UserPrincipalLookupService() { - } - - /** - * Lookup a user principal by name. - * - * @param name - * The string representation of the user principal to lookup - * - * @return A user principal - * - * @throws UserPrincipalNotFoundException - * The principal does not exist - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * In the case of the default provider, and a security manager is - * installed, it checks {@link RuntimePermission}<tt>("lookupUserInformation")</tt> - */ - public abstract UserPrincipal lookupPrincipalByName(String name) - throws IOException; - - /** - * Lookup a group principal by group name. - * - * <p> Where an implementation does not support any notion of group then - * this method always throws {@link UserPrincipalNotFoundException}. Where - * the namespace for user accounts and groups is the same, then this method - * is identical to invoking {@link #lookupPrincipalByName - * lookupPrincipalByName}. - * - * @param group - * The string representation of the group to lookup - * - * @return A user principal. - * - * @throws UserPrincipalNotFoundException - * The principal does not exist or is not a group - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * In the case of the default provider, and a security manager is - * installed, it checks {@link RuntimePermission}<tt>("lookupUserInformation")</tt> - */ - public abstract GroupPrincipal lookupPrincipalByGroupName(String group) - throws IOException; -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/UserPrincipalNotFoundException.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,65 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file.attribute; - -import java.io.IOException; - -/** - * Checked exception thrown when a lookup of {@link UserPrincipal} fails because - * the principal does not exist. - * - * @since 1.7 - */ - -public class UserPrincipalNotFoundException - extends IOException -{ - static final long serialVersionUID = -5369283889045833024L; - - private final String name; - - /** - * Constructs an instance of this class. - * - * @param name - * The principal name; may be {@code null} - */ - public UserPrincipalNotFoundException(String name) { - super(); - this.name = name; - } - - /** - * Returns the user principal name if this exception was created with the - * user principal name that was not found, otherwise <tt>null</tt>. - * - * @return The user principal name or {@code null} - */ - public String getName() { - return name; - } -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/attribute/package-info.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,120 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -/** - * Interfaces and classes providing access to file and file system attributes. - * - * <blockquote><table cellspacing=1 cellpadding=0 summary="Attribute views"> - * <tr><th><p align="left">Attribute views</p></th><th><p align="left">Description</p></th></tr> - * <tr><td valign=top><tt><i>{@link org.classpath.icedtea.java.nio.file.attribute.AttributeView}</i></tt></td> - * <td>Can read or update non-opaque values associated with objects in a file system</td></tr> - * <tr><td valign=top><tt> <i>{@link org.classpath.icedtea.java.nio.file.attribute.FileAttributeView}</i></tt></td> - * <td>Can read or update file attributes</td></tr> - * <tr><td valign=top><tt> <i>{@link org.classpath.icedtea.java.nio.file.attribute.BasicFileAttributeView} </i></tt></td> - * <td>Can read or update a basic set of file attributes</td></tr> - * <tr><td valign=top><tt> <i>{@link org.classpath.icedtea.java.nio.file.attribute.PosixFileAttributeView} </i></tt></td> - * <td>Can read or update POSIX defined file attributes</td></tr> - * <tr><td valign=top><tt> <i>{@link org.classpath.icedtea.java.nio.file.attribute.DosFileAttributeView} </i></tt></td> - * <td>Can read or update FAT file attributes</td></tr> - * <tr><td valign=top><tt>  <i>{@link org.classpath.icedtea.java.nio.file.attribute.FileOwnerAttributeView} </i></tt></td> - * <td>Can read or update the owner of a file</td></tr> - * <tr><td valign=top><tt> <i>{@link org.classpath.icedtea.java.nio.file.attribute.AclFileAttributeView} </i></tt></td> - * <td>Can read or update Access Control Lists</td></tr> - * <tr><td valign=top><tt> <i>{@link org.classpath.icedtea.java.nio.file.attribute.NamedAttributeView} </i></tt></td> - * <td>Can read or update Named Attributes</td></tr> - * <tr><td valign=top><tt> <i>{@link org.classpath.icedtea.java.nio.file.attribute.FileStoreAttributeView}</i></tt></td> - * <td>Can read or update file system attributes</td></tr> - * <tr><td valign=top><tt> <i>{@link org.classpath.icedtea.java.nio.file.attribute.FileStoreSpaceAttributeView} </i></tt></td> - * <td>Can read file system <em>space usage</em> related attributes</td></tr> - * </table></blockquote> - * - * <p> An attribute view provides a read-only or updatable view of the non-opaque - * values, or <em>metadata</em>, associated with objects in a file system. - * The {@link org.classpath.icedtea.java.nio.file.attribute.FileAttributeView} interface is - * extended by several other interfaces that that views to specific sets of file - * attributes. {@code FileAttributeViews} are selected by invoking the {@link - * org.classpath.icedtea.java.nio.file.FileRef#getFileAttributeView} method with a - * <em>type-token</em> to identify the required view. Views can also be identified - * by name. The {@link org.classpath.icedtea.java.nio.file.attribute.FileStoreAttributeView} interface - * provides access to file store attributes. A {@code FileStoreAttributeView} of - * a given type is obtained by invoking the {@link - * org.classpath.icedtea.java.nio.file.FileStore#getFileStoreAttributeView} method. - * - * <p> The {@link org.classpath.icedtea.java.nio.file.attribute.BasicFileAttributeView} - * class defines methods to read and update a <em>basic</em> set of file - * attributes that are common to many file systems. - * - * <p> The {@link org.classpath.icedtea.java.nio.file.attribute.PosixFileAttributeView} - * interface extends {@code BasicFileAttributeView} by defining methods - * to access the file attributes commonly used by file systems and operating systems - * that implement the Portable Operating System Interface (POSIX) family of - * standards. - * - * <p> The {@link org.classpath.icedtea.java.nio.file.attribute.DosFileAttributeView} - * class extends {@code BasicFileAttributeView} by defining methods to - * access the legacy "DOS" file attributes supported on file systems such as File - * Allocation Tabl (FAT), commonly used in consumer devices. - * - * <p> The {@link org.classpath.icedtea.java.nio.file.attribute.AclFileAttributeView} - * class defines methods to read and write the Access Control List (ACL) - * file attribute. The ACL model used by this file attribute view is based - * on the model defined by <a href="http://www.ietf.org/rfc/rfc3530.txt"> - * <i>RFC 3530: Network File System (NFS) version 4 Protocol</i></a>. - * - * <p> The {@link org.classpath.icedtea.java.nio.file.attribute.FileStoreSpaceAttributeView} class - * defines methods to read file system space usage related attributes of a file system. - * - * <p> The {@link org.classpath.icedtea.java.nio.file.attribute.Attributes} utility class defines - * static methods to access file or file system attribute using the above - * attribute views. - * - * <p> In addition to attribute views, this package also defines classes and - * interfaces that are used when accessing attributes: - * - * <ul> - * - * <p><li> The {@link org.classpath.icedtea.java.nio.file.attribute.UserPrincipal} and - * {@link org.classpath.icedtea.java.nio.file.attribute.GroupPrincipal} interfaces represent an - * identity or group identity. </li> - * - * <p><li> The {@link org.classpath.icedtea.java.nio.file.attribute.UserPrincipalLookupService} - * interface defines methods to lookup user or group principals. </li> - * - * <p><li> The {@link org.classpath.icedtea.java.nio.file.attribute.Attribute} interface - * represents the value of an attribute for cases where the attribute value is - * require to be set atomically when creating an object in the file system. </li> - * - * </ul> - * - * - * <p> Unless otherwise noted, passing a <tt>null</tt> argument to a constructor - * or method in any class or interface in this package will cause a {@link - * java.lang.NullPointerException NullPointerException} to be thrown. - * - * @since 1.7 - */ - -package org.classpath.icedtea.java.nio.file.attribute;
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/package-info.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,116 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -/** - * Define interfaces and classes for the Java virtual machine to access files, - * file attributes, and file systems. - * - * <p> The org.classpath.icedtea.java.nio.file package defines classes to access files and file - * systems. The API to access file and file system attributes is defined in the - * {@link org.classpath.icedtea.java.nio.file.attribute} package. The {@link org.classpath.icedtea.java.nio.file.spi} - * package is used by service provider implementors wishing to extend the - * platform default provider, or to construct other provider implementations. - * - * <a name="links"><h3>Symbolic Links</h3></a> - * Many operating systems and file systems support <em>symbolic links</em>. - * A symbolic link is a special file that serves as a reference to another file. - * For the most part, symbolic links are transparent to applications and - * operations on symbolic links are automatically redirected to the <em>target</em> - * of the link. Exceptions to this are when a symbolic link is deleted or - * renamed/moved in which case the link is deleted or removed rather than the - * target of the link. This package includes support for symbolic links where - * implementations provide these semantics. File systems may support other types - * that are semantically close but support for these other types of links is - * not included in this package. - * - * <a name="interop"><h3>Interoperability</h3></a> - * The {@link org.classpath.icedtea.java.io.File} class defines the {@link org.classpath.icedtea.java.io.File#toPath - * toPath} method to construct a {@link org.classpath.icedtea.java.nio.file.Path} by converting - * the abstract path represented by the {@code org.classpath.icedtea.java.io.File} object. The resulting - * {@code Path} can be used to operate on the same file as the {@code File} - * object. The {@code Path} specification provides further information - * on the <a href="Path.html#interop">interoperability</a> between {@code Path} - * and {@code org.classpath.icedtea.java.io.File} objects. - * - * <h3>Visibility</h3> - * The view of the files and file system provided by classes in this package are - * guaranteed to be consistent with other views provided by other instances in the - * same Java virtual machine. The view may or may not, however, be consistent with - * the view of the file system as seen by other concurrently running programs due - * to caching performed by the underlying operating system and delays induced by - * network-filesystem protocols. This is true regardless of the language in which - * these other programs are written, and whether they are running on the same machine - * or on some other machine. The exact nature of any such inconsistencies are - * system-dependent and are therefore unspecified. - * - * <a name="integrity"><h3>Synchronized I/O File Integrity</h3></a> - * The {@link org.classpath.icedtea.java.nio.file.StandardOpenOption#SYNC SYNC} and {@link - * org.classpath.icedtea.java.nio.file.StandardOpenOption#DSYNC DSYNC} options are used when opening a file - * to require that updates to the file are written synchronously to the underlying - * storage device. In the case of the default provider, and the file resides on - * a local storage device, and the {@link java.nio.channels.SeekableByteChannel - * seekable} channel is connected to a file that was opened with one of these - * options, then an invocation of the {@link - * java.nio.channels.WritableByteChannel#write(java.nio.ByteBuffer) write} - * method is only guaranteed to return when all changes made to the file - * by that invocation have been written to the device. These options are useful - * for ensuring that critical information is not lost in the event of a system - * crash. If the file does not reside on a local device then no such guarantee - * is made. Whether this guarantee is possible with other {@link - * org.classpath.icedtea.java.nio.file.spi.FileSystemProvider provider} implementations is provider - * specific. - * - * <h3>General Exceptions</h3> - * Unless otherwise noted, passing a {@code null} argument to a constructor - * or method of any class or interface in this package will cause a {@link - * java.lang.NullPointerException NullPointerException} to be thrown. Additionally, - * invoking a method with a collection containing a {@code null} element will - * cause a {@code NullPointerException}, unless otherwise specified. - * - * <p> Unless otherwise noted, methods that attempt to access the file system - * will throw {@link org.classpath.icedtea.java.nio.file.ClosedFileSystemException} when invoked on - * objects associated with a {@link org.classpath.icedtea.java.nio.file.FileSystem} that has been - * {@link org.classpath.icedtea.java.nio.file.FileSystem#close closed}. Additionally, any methods - * that attempt write access to a file system will throw {@link - * org.classpath.icedtea.java.nio.file.ReadOnlyFileSystemException} when invoked on an object associated - * with a {@link org.classpath.icedtea.java.nio.file.FileSystem} that only provides read-only access. - * - * <p> Unless otherwise noted, invoking a method of any class or interface in - * this package created by one {@link org.classpath.icedtea.java.nio.file.spi.FileSystemProvider - * provider} with a parameter that is an object created by another provider, - * will throw {@link org.classpath.icedtea.java.nio.file.ProviderMismatchException}. - * - * <h3>Optional Specific Exceptions</h3> - * Most of the methods defined by classes in this package that access the - * file system specify that {@link java.io.IOException} be thrown when an I/O - * error occurs. In some cases, these methods define specific I/O exceptions - * for common cases. These exceptions, noted as <i>optional specific exceptions</i>, - * are thrown by the implementation where it can detect the specific error. - * Where the specific error cannot be detected then the more general {@code - * IOException} is thrown. - * - * @since 1.7 - */ -package org.classpath.icedtea.java.nio.file;
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/spi/AbstractPath.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,542 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file.spi; - -import java.nio.channels.*; -import java.nio.ByteBuffer; -import java.io.*; -import java.util.*; - -import org.classpath.icedtea.java.nio.channels.SeekableByteChannel; - -import org.classpath.icedtea.java.nio.file.AtomicMoveNotSupportedException; -import org.classpath.icedtea.java.nio.file.CopyOption; -import org.classpath.icedtea.java.nio.file.DirectoryStream; -import org.classpath.icedtea.java.nio.file.FileRef; -import org.classpath.icedtea.java.nio.file.LinkOption; -import org.classpath.icedtea.java.nio.file.NoSuchFileException; -import org.classpath.icedtea.java.nio.file.OpenOption; -import org.classpath.icedtea.java.nio.file.Path; -import org.classpath.icedtea.java.nio.file.PathMatcher; -import org.classpath.icedtea.java.nio.file.StandardOpenOption; -import org.classpath.icedtea.java.nio.file.StandardCopyOption; -import org.classpath.icedtea.java.nio.file.WatchEvent; -import org.classpath.icedtea.java.nio.file.WatchKey; -import org.classpath.icedtea.java.nio.file.WatchService; - -import org.classpath.icedtea.java.nio.file.attribute.Attributes; -import org.classpath.icedtea.java.nio.file.attribute.BasicFileAttributes; -import org.classpath.icedtea.java.nio.file.attribute.BasicFileAttributeView; -import org.classpath.icedtea.java.nio.file.attribute.FileAttribute; - -/** - * Base implementation class for a {@code Path}. - * - * <p> This class is intended to be extended by provider implementors. It - * implements, or provides default implementations for several of the methods - * defined by the {@code Path} class. It implements the {@link #copyTo copyTo} - * and {@link #moveTo moveTo} methods for the case that the source and target - * are not associated with the same provider. - * - * @since 1.7 - */ - -public abstract class AbstractPath extends Path { - - /** - * Initializes a new instance of this class. - */ - protected AbstractPath() { } - - /** - * @throws NoSuchFileException {@inheritDoc} - * @throws DirectoryNotEmptyException {@inheritDoc} - * @throws IOException {@inheritDoc} - * @throws SecurityException {@inheritDoc} - */ - - public final void delete() throws IOException { - delete(true); - } - - /** - * @throws IllegalArgumentException {@inheritDoc} - * @throws FileAlreadyExistsException {@inheritDoc} - * @throws IOException {@inheritDoc} - * @throws SecurityException {@inheritDoc} - */ - - public final Path createFile(FileAttribute<?>... attrs) - throws IOException - { - EnumSet<StandardOpenOption> options = - EnumSet.of(StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE); - SeekableByteChannel sbc = newByteChannel(options, attrs); - try { - sbc.close(); - } catch (IOException x) { - // ignore - } - return this; - } - - /** - * @throws IllegalArgumentException {@inheritDoc} - * @throws FileAlreadyExistsException {@inheritDoc} - * @throws IOException {@inheritDoc} - * @throws SecurityException {@inheritDoc} - */ - - public final SeekableByteChannel newByteChannel(OpenOption... options) - throws IOException - { - Set<OpenOption> set = new HashSet<OpenOption>(options.length); - Collections.addAll(set, options); - return newByteChannel(set); - } - - /** - * Opens the file located by this path for reading, returning an input - * stream to read bytes from the file. - * - * <p> This method returns an {@code InputStream} that is constructed by - * invoking the {@link java.nio.channels.Channels#newInputStream - * Channels.newInputStream} method. It may be overridden where a more - * efficient implementation is available. - * - * @throws IOException {@inheritDoc} - * @throws SecurityException {@inheritDoc} - */ - - public InputStream newInputStream() throws IOException { - return Channels.newInputStream(newByteChannel(StandardOpenOption.READ)); - } - - /** - * Opens or creates the file located by this path for writing, returning an - * output stream to write bytes to the file. - * - * <p> This method returns an {@code OutputStream} that is constructed by - * invoking the {@link java.nio.channels.Channels#newOutputStream - * Channels.newOutputStream} method. It may be overridden where a more - * efficient implementation is available. - * - * @throws IllegalArgumentException {@inheritDoc} - * @throws IOException {@inheritDoc} - * @throws SecurityException {@inheritDoc} - */ - - public OutputStream newOutputStream(OpenOption... options) throws IOException { - - int len = options.length; - Set<OpenOption> opts = new HashSet<OpenOption>(len + 3); - if (len == 0) { - opts.add(StandardOpenOption.CREATE); - opts.add(StandardOpenOption.TRUNCATE_EXISTING); - } else { - for (OpenOption opt: options) { - if (opt == StandardOpenOption.READ) - throw new IllegalArgumentException("READ not allowed"); - opts.add(opt); - } - } - opts.add(StandardOpenOption.WRITE); - return Channels.newOutputStream(newByteChannel(opts)); - } - - /** - * Opens or creates the file located by this path for writing, returning an - * output stream to write bytes to the file. - * - * <p> This method returns an {@code OutputStream} that is constructed by - * invoking the {@link java.nio.channels.Channels#newOutputStream - * Channels.newOutputStream} method. It may be overridden where a more - * efficient implementation is available. - * - * @throws IllegalArgumentException {@inheritDoc} - * @throws IOException {@inheritDoc} - * @throws SecurityException {@inheritDoc} - */ - - public OutputStream newOutputStream(Set<? extends OpenOption> options, - FileAttribute<?>... attrs) - throws IOException - { - Set<OpenOption> opts = new HashSet<OpenOption>(options); - if (opts.isEmpty()) { - opts.add(StandardOpenOption.CREATE); - opts.add(StandardOpenOption.TRUNCATE_EXISTING); - } else { - if (opts.contains(StandardOpenOption.READ)) - throw new IllegalArgumentException("READ not allowed"); - } - opts.add(StandardOpenOption.WRITE); - return Channels.newOutputStream(newByteChannel(opts, attrs)); - } - - /** - * @throws NotDirectoryException {@inheritDoc} - * @throws IOException {@inheritDoc} - * @throws SecurityException {@inheritDoc} - */ - - public final DirectoryStream<Path> newDirectoryStream() throws IOException { - return newDirectoryStream(acceptAllFilter); - } - private static final DirectoryStream.Filter<Path> acceptAllFilter = - new DirectoryStream.Filter<Path>() { - public boolean accept(Path entry) { return true; } - }; - - /** - * Opens the directory referenced by this object, returning a {@code - * DirectoryStream} to iterate over the entries in the directory. The - * entries are filtered by matching the {@code String} representation of - * their file names against a given pattern. - * - * <p> This method constructs a {@link PathMatcher} by invoking the - * file system's {@link java.nio.file.FileSystem#getNameMatcher - * getNameMatcher} method. This method may be overridden where a more - * efficient implementation is available. - * - * @throws java.util.regex.PatternSyntaxException {@inheritDoc} - * @throws UnsupportedOperationException {@inheritDoc} - * @throws NotDirectoryException {@inheritDoc} - * @throws IOException {@inheritDoc} - * @throws SecurityException {@inheritDoc} - */ - - public DirectoryStream<Path> newDirectoryStream(String glob) - throws IOException - { - // avoid creating a matcher if all entries are required. - if (glob.equals("*")) - return newDirectoryStream(); - - // create a matcher and return a filter that uses it. - final PathMatcher matcher = getFileSystem().getNameMatcher("glob", glob); - DirectoryStream.Filter<Path> filter = new DirectoryStream.Filter<Path>() { - - public boolean accept(Path entry) { - return matcher.matches(entry.getName()); - } - }; - return newDirectoryStream(filter); - } - - - public final boolean exists() { - try { - checkAccess(); - return true; - } catch (IOException x) { - // unable to determine if file exists - } - return false; - } - - - public final boolean notExists() { - try { - checkAccess(); - return false; - } catch (NoSuchFileException x) { - // file confirmed not to exist - return true; - } catch (IOException x) { - return false; - } - } - - - public final WatchKey register(WatchService watcher, WatchEvent.Kind<?>... events) - throws IOException - { - return register(watcher, events, NO_MODIFIERS); - } - private static final WatchEvent.Modifier[] NO_MODIFIERS = new WatchEvent.Modifier[0]; - - /** - * Copy the file located by this path to a target location. - * - * <p> This method is invoked by the {@link #copyTo copyTo} method for - * the case that this {@code Path} and the target {@code Path} are - * associated with the same provider. - * - * @param target - * The target location - * @param options - * Options specifying how the copy should be done - * - * @throws IllegalArgumentException - * If an invalid option is specified - * @throws FileAlreadyExistsException - * The target file exists and cannot be replaced because the - * {@code REPLACE_EXISTING} option is not specified, or the target - * file is a non-empty directory <i>(optional specific exception)</i> - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * In the case of the default provider, and a security manager is - * installed, the {@link SecurityManager#checkRead(String) checkRead} - * method is invoked to check read access to the source file, the - * {@link SecurityManager#checkWrite(String) checkWrite} is invoked - * to check write access to the target file. If a symbolic link is - * copied the security manager is invoked to check {@link - * LinkPermission}{@code ("symbolic")}. - */ - protected abstract void implCopyTo(Path target, CopyOption... options) - throws IOException; - - /** - * Move the file located by this path to a target location. - * - * <p> This method is invoked by the {@link #moveTo moveTo} method for - * the case that this {@code Path} and the target {@code Path} are - * associated with the same provider. - * - * @param target - * The target location - * @param options - * Options specifying how the move should be done - * - * @throws IllegalArgumentException - * If an invalid option is specified - * @throws FileAlreadyExistsException - * The target file exists and cannot be replaced because the - * {@code REPLACE_EXISTING} option is not specified, or the target - * file is a non-empty directory - * @throws AtomicMoveNotSupportedException - * The options array contains the {@code ATOMIC_MOVE} option but - * the file cannot be moved as an atomic file system operation. - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * In the case of the default provider, and a security manager is - * installed, the {@link SecurityManager#checkWrite(String) checkWrite} - * method is invoked to check write access to both the source and - * target file. - */ - protected abstract void implMoveTo(Path target, CopyOption... options) - throws IOException; - - /** - * Copy the file located by this path to a target location. - * - * <p> If this path is associated with the same {@link FileSystemProvider - * provider} as the {@code target} then the {@link #implCopyTo implCopyTo} - * method is invoked to copy the file. Otherwise, this method attempts to - * copy the file to the target location in a manner that may be less - * efficient than would be the case that target is associated with the same - * provider as this path. - * - * @throws IllegalArgumentException {@inheritDoc} - * @throws FileAlreadyExistsException {@inheritDoc} - * @throws IOException {@inheritDoc} - * @throws SecurityException {@inheritDoc} - */ - - public final Path copyTo(Path target, CopyOption... options) - throws IOException - { - if ((getFileSystem().provider() == target.getFileSystem().provider())) { - implCopyTo(target, options); - } else { - xProviderCopyTo(target, options); - } - return target; - } - - /** - * Move or rename the file located by this path to a target location. - * - * <p> If this path is associated with the same {@link FileSystemProvider - * provider} as the {@code target} then the {@link #implCopyTo implMoveTo} - * method is invoked to move the file. Otherwise, this method attempts to - * copy the file to the target location and delete the source file. This - * implementation may be less efficient than would be the case that - * target is associated with the same provider as this path. - * - * @throws IllegalArgumentException {@inheritDoc} - * @throws FileAlreadyExistsException {@inheritDoc} - * @throws IOException {@inheritDoc} - * @throws SecurityException {@inheritDoc} - */ - - public final Path moveTo(Path target, CopyOption... options) - throws IOException - { - if ((getFileSystem().provider() == target.getFileSystem().provider())) { - implMoveTo(target, options); - } else { - // different providers so copy + delete - xProviderCopyTo(target, convertMoveToCopyOptions(options)); - delete(false); - } - return target; - } - - /** - * Converts the given array of options for moving a file to options suitable - * for copying the file when a move is implemented as copy + delete. - */ - private static CopyOption[] convertMoveToCopyOptions(CopyOption... options) - throws AtomicMoveNotSupportedException - { - int len = options.length; - CopyOption[] newOptions = new CopyOption[len+2]; - for (int i=0; i<len; i++) { - CopyOption option = options[i]; - if (option == StandardCopyOption.ATOMIC_MOVE) { - throw new AtomicMoveNotSupportedException(null, null, - "Atomic move between providers is not supported"); - } - newOptions[i] = option; - } - newOptions[len] = LinkOption.NOFOLLOW_LINKS; - newOptions[len+1] = StandardCopyOption.COPY_ATTRIBUTES; - return newOptions; - } - - /** - * Parses the arguments for a file copy operation. - */ - private static class CopyOptions { - boolean replaceExisting = false; - boolean copyAttributes = false; - boolean followLinks = true; - - private CopyOptions() { } - - static CopyOptions parse(CopyOption... options) { - CopyOptions result = new CopyOptions(); - for (CopyOption option: options) { - if (option == StandardCopyOption.REPLACE_EXISTING) { - result.replaceExisting = true; - continue; - } - if (option == LinkOption.NOFOLLOW_LINKS) { - result.followLinks = false; - continue; - } - if (option == StandardCopyOption.COPY_ATTRIBUTES) { - result.copyAttributes = true; - continue; - } - if (option == null) - throw new NullPointerException(); - throw new IllegalArgumentException("'" + option + - "' is not a valid copy option"); - } - return result; - } - } - - /** - * Simple cross-provider copy where the target is a Path. - */ - private void xProviderCopyTo(Path target, CopyOption... options) - throws IOException - { - CopyOptions opts = CopyOptions.parse(options); - LinkOption[] linkOptions = (opts.followLinks) ? new LinkOption[0] : - new LinkOption[] { LinkOption.NOFOLLOW_LINKS }; - - // attributes of source file - BasicFileAttributes attrs = Attributes - .readBasicFileAttributes(this, linkOptions); - if (attrs.isSymbolicLink()) - throw new IOException("Copying of symbolic links not supported"); - - // delete target file - if (opts.replaceExisting) - target.delete(false); - - // create directory or file - if (attrs.isDirectory()) { - target.createDirectory(); - } else { - target.createFile(); - xProviderCopyRegularFileTo(target); - } - - // copy basic attributes to target - if (opts.copyAttributes) { - BasicFileAttributeView view = target - .getFileAttributeView(BasicFileAttributeView.class, linkOptions); - try { - view.setTimes(attrs.lastModifiedTime(), - attrs.lastAccessTime(), - attrs.creationTime(), - attrs.resolution()); - } catch (IOException x) { - // rollback - try { - target.delete(false); - } catch (IOException ignore) { } - throw x; - } - } - } - - - /** - * Simple copy of regular file to a target file that exists. - */ - private void xProviderCopyRegularFileTo(FileRef target) - throws IOException - { - ReadableByteChannel rbc = newByteChannel(); - try { - // open target file for writing - SeekableByteChannel sbc = target - .newByteChannel(StandardOpenOption.WRITE); - - // simple copy loop - try { - ByteBuffer buf = ByteBuffer.wrap(new byte[8192]); - int n = 0; - for (;;) { - n = rbc.read(buf); - if (n < 0) - break; - assert n > 0; - buf.flip(); - while (buf.hasRemaining()) { - sbc.write(buf); - } - buf.rewind(); - } - - } finally { - sbc.close(); - } - } finally { - rbc.close(); - } - } -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/spi/FileSystemProvider.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,441 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file.spi; - -import java.net.URI; -import java.util.*; -import java.util.concurrent.ExecutorService; -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.io.IOException; - -import org.classpath.icedtea.java.nio.channels.AsynchronousFileChannel; -import org.classpath.icedtea.java.nio.channels.FileChannel; -import org.classpath.icedtea.java.nio.file.FileRef; -import org.classpath.icedtea.java.nio.file.FileSystem; -import org.classpath.icedtea.java.nio.file.FileSystems; -import org.classpath.icedtea.java.nio.file.OpenOption; -import org.classpath.icedtea.java.nio.file.Path; -import org.classpath.icedtea.java.nio.file.attribute.FileAttribute; - -/** - * Service-provider class for file systems. - * - * <p> A file system provider is a concrete implementation of this class that - * implements the abstract methods defined by this class. A provider is - * identified by a {@code URI} {@link #getScheme() scheme}. The default provider - * is identified by the URI scheme "file". It creates the {@link FileSystem} that - * provides access to the file systems accessible to the Java virtual machine. - * The {@link FileSystems} class defines how file system providers are located - * and loaded. The default provider is typically a system-default provider but - * may be overridden if the system property {@code - * java.nio.file.spi.DefaultFileSystemProvider} is set. In that case, the - * provider has a one argument constructor whose formal parameter type is {@code - * FileSystemProvider}. All other providers have a zero argument constructor - * that initializes the provider. - * - * <p> A provider is a factory for one or more {@link FileSystem} instances. Each - * file system is identified by a {@code URI} where the URI's scheme matches - * the provider's {@link #getScheme scheme}. The default file system, for example, - * is identified by the URI {@code "file:///"}. A memory-based file system, - * for example, may be identified by a URI such as {@code "memory:///?name=logfs"}. - * The {@link #newFileSystem newFileSystem} method may be used to create a file - * system, and the {@link #getFileSystem getFileSystem} method may be used to - * obtain a reference to an existing file system created by the provider. Where - * a provider is the factory for a single file system then it is provider dependent - * if the file system is created when the provider is initialized, or later when - * the {@code newFileSystem} method is invoked. In the case of the default - * provider, the {@code FileSystem} is created when the provider is initialized. - * - * <p> In addition to file systems, a provider is also a factory for {@link - * FileChannel} and {@link AsynchronousFileChannel} channels. The {@link - * #newFileChannel newFileChannel} and {@link #newAsynchronousFileChannel - * AsynchronousFileChannel} methods are defined to open or create files, returning - * a channel to access the file. These methods are invoked by static factory - * methods defined in the {@link java.nio.channels} package. - * - * <p> All of the methods in this class are safe for use by multiple concurrent - * threads. - * - * @since 1.7 - */ - -public abstract class FileSystemProvider { - // lock using when loading providers - private static final Object lock = new Object(); - - // installed providers - private static volatile List<FileSystemProvider> installedProviders; - - // used to avoid recursive loading of instaled providers - private static boolean loadingProviders = false; - - private static Void checkPermission() { - SecurityManager sm = System.getSecurityManager(); - if (sm != null) - sm.checkPermission(new RuntimePermission("fileSystemProvider")); - return null; - } - private FileSystemProvider(Void ignore) { } - - /** - * Initializes a new instance of this class. - * - * <p> During construction a provider may safely access files associated - * with the default provider but care needs to be taken to avoid circular - * loading of other installed providers. If circular loading of installed - * providers is detected then an unspecified error is thrown. - * - * @throws SecurityException - * If a security manager has been installed and it denies - * {@link RuntimePermission}<tt>("fileSystemProvider")</tt> - */ - protected FileSystemProvider() { - this(checkPermission()); - } - - // loads all installed providers - private static List<FileSystemProvider> loadInstalledProviders() { - List<FileSystemProvider> list = new ArrayList<FileSystemProvider>(); - - ServiceLoader<FileSystemProvider> sl = ServiceLoader - .load(FileSystemProvider.class, ClassLoader.getSystemClassLoader()); - - // ServiceConfigurationError may be throw here - for (FileSystemProvider provider: sl) { - String scheme = provider.getScheme(); - - // add to list if the provider is not "file" and isn't a duplicate - if (!scheme.equalsIgnoreCase("file")) { - boolean found = false; - for (FileSystemProvider p: list) { - if (p.getScheme().equalsIgnoreCase(scheme)) { - found = true; - break; - } - } - if (!found) { - list.add(provider); - } - } - } - return list; - } - - /** - * Returns a list of the installed file system providers. - * - * <p> The first invocation of this method causes the default provider to be - * initialized (if not already initialized) and loads any other installed - * providers as described by the {@link FileSystems} class. - * - * @return An unmodifiable list of the installed file system providers. The - * list contains at least one element, that is the default file - * system provider - * - * @throws ServiceConfigurationError - * When an error occurs while loading a service provider - */ - public static List<FileSystemProvider> installedProviders() { - if (installedProviders == null) { - // ensure default provider is initialized - FileSystemProvider defaultProvider = FileSystems.getDefault().provider(); - - synchronized (lock) { - if (installedProviders == null) { - if (loadingProviders) { - throw new Error("Circular loading of installed providers detected"); - } - loadingProviders = true; - - List<FileSystemProvider> list = AccessController - .doPrivileged(new PrivilegedAction<List<FileSystemProvider>>() { - - public List<FileSystemProvider> run() { - return loadInstalledProviders(); - }}); - - // insert the default provider at the start of the list - list.add(0, defaultProvider); - - installedProviders = Collections.unmodifiableList(list); - } - } - } - return installedProviders; - } - - /** - * Returns the URI scheme that identifies this provider. - * - * @return The URI scheme - */ - public abstract String getScheme(); - - /** - * Constructs a new {@code FileSystem} object identified by a URI. This - * method is invoked by the {@link FileSystems#newFileSystem(URI,Map)} - * method to open a new file system identified by a URI. - * - * <p> The {@code uri} parameter is an absolute, hierarchical URI, with a - * scheme equal (without regard to case) to the scheme supported by this - * provider. The exact form of the URI is highly provider dependent. The - * {@code env} parameter is a map of provider specific properties to configure - * the file system. - * - * <p> This method throws {@link FileSystemAlreadyExistsException} if the - * file system already exists because it was previously created by an - * invocation of this method. Once a file system is {@link FileSystem#close - * closed} it is provider-dependent if the provider allows a new file system - * to be created with the same URI as a file system it previously created. - * - * @param uri - * URI reference - * @param env - * A map of provider specific properties to configure the file system; - * may be empty - * - * @return A new file system - * - * @throws IllegalArgumentException - * If the pre-conditions for the {@code uri} parameter aren't met, - * or the {@code env} parameter does not contain properties required - * by the provider, or a property value is invalid - * @throws IOException - * An I/O error occurs creating the file system - * @throws SecurityException - * If a security manager is installed and it denies an unspecified - * permission required by the file system provider implementation - * @throws FileSystemAlreadyExistsException - * If the file system has already been created - */ - public abstract FileSystem newFileSystem(URI uri, Map<String,?> env) - throws IOException; - - /** - * Returns an existing {@code FileSystem} created by this provider. - * - * <p> This method returns a reference to a {@code FileSystem} that was - * created by invoking the {@link #newFileSystem(URI,Map) newFileSystem(URI,Map)} - * method. File systems created the {@link #newFileSystem(FileRef,Map) - * newFileSystem(FileRef,Map)} method are not returned by this method. - * The file system is identified by its {@code URI}. Its exact form - * is highly provider dependent. In the case of the default provider the URI's - * path component is {@code "/"} and the authority, query and fragment components - * are undefined (Undefined components are represented by {@code null}). - * - * <p> Once a file system created by this provider is {@link FileSystem#close - * closed} it is provider-dependent if this method returns a reference to - * the closed file system or throws {@link FileSystemNotFoundException}. - * If the provider allows a new file system to be created with the same URI - * as a file system it previously created then this method throws the - * exception if invoked after the file system is closed (and before a new - * instance is created by the {@link #newFileSystem newFileSystem} method). - * - * <p> If a security manager is installed then a provider implementation - * may require to check a permission before returning a reference to an - * existing file system. In the case of the {@link FileSystems#getDefault - * default} file system, no permission check is required. - * - * @param uri - * URI reference - * - * @return The file system - * - * @throws IllegalArgumentException - * If the pre-conditions for the {@code uri} parameter aren't met - * @throws FileSystemNotFoundException - * If the file system does not exist - * @throws SecurityException - * If a security manager is installed and it denies an unspecified - * permission. - */ - public abstract FileSystem getFileSystem(URI uri); - - /** - * Return a {@code Path} object by converting the given {@link URI}. - * - * <p> The exact form of the URI is file system provider dependent. In the - * case of the default provider, the URI scheme is {@code "file"} and the - * given URI has a non-empty path component, and undefined query, and - * fragment components. The resulting {@code Path} is associated with the - * default {@link FileSystems#getDefault default} {@code FileSystem}. - * - * <p> If a security manager is installed then a provider implementation - * may require to check a permission. In the case of the {@link - * FileSystems#getDefault default} file system, no permission check is - * required. - * - * @param uri - * The URI to convert - * - * @throws IllegalArgumentException - * If the URI scheme does not identify this provider or other - * preconditions on the uri parameter do not hold - * @throws FileSystemNotFoundException - * The file system, identified by the URI, does not exist - * @throws SecurityException - * If a security manager is installed and it denies an unspecified - * permission. - */ - public abstract Path getPath(URI uri); - - /** - * Constructs a new {@code FileSystem} to access the contents of a file as a - * file system. - * - * <p> This method is intended for specialized providers of pseudo file - * systems where the contents of one or more files is treated as a file - * system. The {@code file} parameter is a reference to an existing file - * and the {@code env} parameter is a map of provider specific properties to - * configure the file system. - * - * <p> If this provider does not support the creation of such file systems - * or if the provider does not recognize the file type of the given file then - * it throws {@code UnsupportedOperationException}. The default implementation - * of this method throws {@code UnsupportedOperationException}. - * - * @param file - * The file - * @param env - * A map of provider specific properties to configure the file system; - * may be empty - * - * @return A new file system - * - * @throws UnsupportedOperationException - * If this provider does not support access to the contents as a - * file system or it does not recognize the file type of the - * given file - * @throws IllegalArgumentException - * If the {@code env} parameter does not contain properties required - * by the provider, or a property value is invalid - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * If a security manager is installed and it denies an unspecified - * permission. - */ - public FileSystem newFileSystem(FileRef file, Map<String,?> env) - throws IOException - { - throw new UnsupportedOperationException(); - } - - /** - * Opens or creates a file for reading and/or writing, returning a file - * channel to access the file. - * - * <p> This method is invoked by the {@link FileChannel#open(Path,Set,FileAttribute[]) - * FileChannel.open} method to open a file channel. A provider that does not - * support all the features required to construct a file channel throws - * {@code UnsupportedOperationException}. The default provider is required - * to support the creation of file channels. When not overridden, the - * default implementation throws {@code UnsupportedOperationException}. - * - * @param path - * The path of the file to open or create - * @param options - * Options specifying how the file is opened - * @param attrs - * An optional list of file attributes to set atomically when - * creating the file - * - * @return A new file channel - * - * @throws IllegalArgumentException - * If the set contains an invalid combination of options - * @throws UnsupportedOperationException - * If this provider that does not support creating file channels, - * or an unsupported open option or file attribute is specified - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * In the case of the default file system, the {@link - * SecurityManager#checkRead(String)} method is invoked to check - * read access if the file is opened for reading. The {@link - * SecurityManager#checkWrite(String)} method is invoked to check - * write access if the file is opened for writing - */ - public FileChannel newFileChannel(Path path, - Set<? extends OpenOption> options, - FileAttribute<?>... attrs) - throws IOException - { - throw new UnsupportedOperationException(); - } - - /** - * Opens or creates a file for reading and/or writing, returning an - * asynchronous file channel to access the file. - * - * <p> This method is invoked by the {@link - * AsynchronousFileChannel#open(Path,Set,ExecutorService,FileAttribute[]) - * AsynchronousFileChannel.open} method to open an asynchronous file channel. - * A provider that does not support all the features required to construct - * an asynchronous file channel throws {@code UnsupportedOperationException}. - * The default provider is required to support the creation of asynchronous - * file channels. When not overridden, the default implementation of this - * method throws {@code UnsupportedOperationException}. - * - * @param path - * The path of the file to open or create - * @param options - * Options specifying how the file is opened - * @param executor - * The thread pool or {@code null} to associate the channel with - * the default thread pool - * @param attrs - * An optional list of file attributes to set atomically when - * creating the file - * - * @return A new asynchronous file channel - * - * @throws IllegalArgumentException - * If the set contains an invalid combination of options - * @throws UnsupportedOperationException - * If this provider that does not support creating asynchronous file - * channels, or an unsupported open option or file attribute is - * specified - * @throws IOException - * If an I/O error occurs - * @throws SecurityException - * In the case of the default file system, the {@link - * SecurityManager#checkRead(String)} method is invoked to check - * read access if the file is opened for reading. The {@link - * SecurityManager#checkWrite(String)} method is invoked to check - * write access if the file is opened for writing - */ - public AsynchronousFileChannel newAsynchronousFileChannel(Path path, - Set<? extends OpenOption> options, - ExecutorService executor, - FileAttribute<?>... attrs) - throws IOException - { - throw new UnsupportedOperationException(); - } -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/spi/FileTypeDetector.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,102 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.nio.file.spi; - -import java.io.IOException; - -import org.classpath.icedtea.java.nio.file.FileRef; - -/** - * A file type detector for probing a file to guess its file type. - * - * <p> A file type detector is a concrete implementation of this class, has a - * zero-argument constructor, and implements the abstract methods specified - * below. - * - * <p> The means by which a file type detector determines the file type is - * highly implementation specific. A simple implementation might examine the - * <em>file extension</em> (a convention used in some platforms) and map it to - * a file type. In other cases, the file type may be stored as a file <a - * href="../attribute/package-summary.html"> attribute</a> or the bytes in a - * file may be examined to guess its file type. - * - * @see java.nio.file.Files#probeContentType(FileRef) - * - * @since 1.7 - */ - -public abstract class FileTypeDetector { - - /** - * Initializes a new instance of this class. - * - * @throws SecurityException - * If a security manager has been installed and it denies - * {@link RuntimePermission}<tt>("fileTypeDetector")</tt> - */ - protected FileTypeDetector() { - SecurityManager sm = System.getSecurityManager(); - if (sm != null) - sm.checkPermission(new RuntimePermission("fileTypeDetector")); - } - - /** - * Probes the given file to guess its content type. - * - * <p> The means by which this method determines the file type is highly - * implementation specific. It may simply examine the file name, it may use - * a file <a href="../attribute/package-summary.html">attribute</a>, - * or it may examines bytes in the file. - * - * <p> The probe result is the string form of the value of a - * Multipurpose Internet Mail Extension (MIME) content type as - * defined by <a href="http://www.ietf.org/rfc/rfc2045.txt"><i>RFC 2045: - * Multipurpose Internet Mail Extensions (MIME) Part One: Format of Internet - * Message Bodies</i></a>. The string must be parsable according to the - * grammar in the RFC 2045. - * - * @param file - * The file to probe - * - * @return The content type or {@code null} if the file type is not - * recognized - * - * @throws IOException - * An I/O error occurs - * @throws SecurityException - * If the implementation requires to access the file, and a - * security manager is installed, and it denies an unspecified - * permission required by a file system provider implementation. - * If the file reference is associated with the default file system - * provider then the {@link SecurityManager#checkRead(String)} method - * is invoked to check read access to the file. - * - * @see java.nio.file.Files#probeContentType - */ - public abstract String probeContentType(FileRef file) - throws IOException; -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/nio/file/spi/package-info.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,39 +0,0 @@ -/* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -/** - * Service-provider classes for the <tt>{@link org.classpath.icedtea.java.nio.file}</tt> package. - * - * <p> Only developers who are defining new file system providers or file type - * detectors should need to make direct use of this package. </p> - * - * <p> Unless otherwise noted, passing a <tt>null</tt> argument to a constructor - * or method in any class or interface in this package will cause a {@link - * java.lang.NullPointerException NullPointerException} to be thrown. - * - * @since 1.7 - */ - -package org.classpath.icedtea.java.nio.file.spi;
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/util/Scanner.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,2657 +0,0 @@ -/* - * Copyright 2003-2006 Sun Microsystems, Inc. All Rights Reserved. - * Copyright 2009 Red Hat, Inc. - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package org.classpath.icedtea.java.util; - -import java.util.regex.*; -import java.io.*; -import java.math.*; -import java.nio.*; -import java.nio.channels.*; -import java.nio.charset.*; -import java.text.*; -import java.util.InputMismatchException; -import java.util.Iterator; -import java.util.Locale; -import java.util.NoSuchElementException; -import sun.misc.LRUCache; - -import org.classpath.icedtea.java.nio.file.FileRef; - -/** - * A simple text scanner which can parse primitive types and strings using - * regular expressions. - * - * <p>A <code>Scanner</code> breaks its input into tokens using a - * delimiter pattern, which by default matches whitespace. The resulting - * tokens may then be converted into values of different types using the - * various <tt>next</tt> methods. - * - * <p>For example, this code allows a user to read a number from - * <tt>System.in</tt>: - * <blockquote><pre> - * Scanner sc = new Scanner(System.in); - * int i = sc.nextInt(); - * </pre></blockquote> - * - * <p>As another example, this code allows <code>long</code> types to be - * assigned from entries in a file <code>myNumbers</code>: - * <blockquote><pre> - * Scanner sc = new Scanner(new File("myNumbers")); - * while (sc.hasNextLong()) { - * long aLong = sc.nextLong(); - * }</pre></blockquote> - * - * <p>The scanner can also use delimiters other than whitespace. This - * example reads several items in from a string: - *<blockquote><pre> - * String input = "1 fish 2 fish red fish blue fish"; - * Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*"); - * System.out.println(s.nextInt()); - * System.out.println(s.nextInt()); - * System.out.println(s.next()); - * System.out.println(s.next()); - * s.close(); </pre></blockquote> - * <p> - * prints the following output: - * <blockquote><pre> - * 1 - * 2 - * red - * blue </pre></blockquote> - * - * <p>The same output can be generated with this code, which uses a regular - * expression to parse all four tokens at once: - *<blockquote><pre> - * String input = "1 fish 2 fish red fish blue fish"; - * Scanner s = new Scanner(input); - * s.findInLine("(\\d+) fish (\\d+) fish (\\w+) fish (\\w+)"); - * MatchResult result = s.match(); - * for (int i=1; i<=result.groupCount(); i++) - * System.out.println(result.group(i)); - * s.close(); </pre></blockquote> - * - * <p>The <a name="default-delimiter">default whitespace delimiter</a> used - * by a scanner is as recognized by {@link java.lang.Character}.{@link - * java.lang.Character#isWhitespace(char) isWhitespace}. The {@link #reset} - * method will reset the value of the scanner's delimiter to the default - * whitespace delimiter regardless of whether it was previously changed. - * - * <p>A scanning operation may block waiting for input. - * - * <p>The {@link #next} and {@link #hasNext} methods and their - * primitive-type companion methods (such as {@link #nextInt} and - * {@link #hasNextInt}) first skip any input that matches the delimiter - * pattern, and then attempt to return the next token. Both <tt>hasNext</tt> - * and <tt>next</tt> methods may block waiting for further input. Whether a - * <tt>hasNext</tt> method blocks has no connection to whether or not its - * associated <tt>next</tt> method will block. - * - * <p> The {@link #findInLine}, {@link #findWithinHorizon}, and {@link #skip} - * methods operate independently of the delimiter pattern. These methods will - * attempt to match the specified pattern with no regard to delimiters in the - * input and thus can be used in special circumstances where delimiters are - * not relevant. These methods may block waiting for more input. - * - * <p>When a scanner throws an {@link InputMismatchException}, the scanner - * will not pass the token that caused the exception, so that it may be - * retrieved or skipped via some other method. - * - * <p>Depending upon the type of delimiting pattern, empty tokens may be - * returned. For example, the pattern <tt>"\\s+"</tt> will return no empty - * tokens since it matches multiple instances of the delimiter. The delimiting - * pattern <tt>"\\s"</tt> could return empty tokens since it only passes one - * space at a time. - * - * <p> A scanner can read text from any object which implements the {@link - * java.lang.Readable} interface. If an invocation of the underlying - * readable's {@link java.lang.Readable#read} method throws an {@link - * java.io.IOException} then the scanner assumes that the end of the input - * has been reached. The most recent <tt>IOException</tt> thrown by the - * underlying readable can be retrieved via the {@link #ioException} method. - * - * <p>When a <code>Scanner</code> is closed, it will close its input source - * if the source implements the {@link java.io.Closeable} interface. - * - * <p>A <code>Scanner</code> is not safe for multithreaded use without - * external synchronization. - * - * <p>Unless otherwise mentioned, passing a <code>null</code> parameter into - * any method of a <code>Scanner</code> will cause a - * <code>NullPointerException</code> to be thrown. - * - * <p>A scanner will default to interpreting numbers as decimal unless a - * different radix has been set by using the {@link #useRadix} method. The - * {@link #reset} method will reset the value of the scanner's radix to - * <code>10</code> regardless of whether it was previously changed. - * - * <a name="localized-numbers"> - * <h4> Localized numbers </h4> - * - * <p> An instance of this class is capable of scanning numbers in the standard - * formats as well as in the formats of the scanner's locale. A scanner's - * <a name="initial-locale">initial locale </a>is the value returned by the {@link - * java.util.Locale#getDefault} method; it may be changed via the {@link - * #useLocale} method. The {@link #reset} method will reset the value of the - * scanner's locale to the initial locale regardless of whether it was - * previously changed. - * - * <p>The localized formats are defined in terms of the following parameters, - * which for a particular locale are taken from that locale's {@link - * java.text.DecimalFormat DecimalFormat} object, <tt>df</tt>, and its and - * {@link java.text.DecimalFormatSymbols DecimalFormatSymbols} object, - * <tt>dfs</tt>. - * - * <blockquote><table> - * <tr><td valign="top"><i>LocalGroupSeparator </i></td> - * <td valign="top">The character used to separate thousands groups, - * <i>i.e.,</i> <tt>dfs.</tt>{@link - * java.text.DecimalFormatSymbols#getGroupingSeparator - * getGroupingSeparator()}</td></tr> - * <tr><td valign="top"><i>LocalDecimalSeparator </i></td> - * <td valign="top">The character used for the decimal point, - * <i>i.e.,</i> <tt>dfs.</tt>{@link - * java.text.DecimalFormatSymbols#getDecimalSeparator - * getDecimalSeparator()}</td></tr> - * <tr><td valign="top"><i>LocalPositivePrefix </i></td> - * <td valign="top">The string that appears before a positive number (may - * be empty), <i>i.e.,</i> <tt>df.</tt>{@link - * java.text.DecimalFormat#getPositivePrefix - * getPositivePrefix()}</td></tr> - * <tr><td valign="top"><i>LocalPositiveSuffix </i></td> - * <td valign="top">The string that appears after a positive number (may be - * empty), <i>i.e.,</i> <tt>df.</tt>{@link - * java.text.DecimalFormat#getPositiveSuffix - * getPositiveSuffix()}</td></tr> - * <tr><td valign="top"><i>LocalNegativePrefix </i></td> - * <td valign="top">The string that appears before a negative number (may - * be empty), <i>i.e.,</i> <tt>df.</tt>{@link - * java.text.DecimalFormat#getNegativePrefix - * getNegativePrefix()}</td></tr> - * <tr><td valign="top"><i>LocalNegativeSuffix </i></td> - * <td valign="top">The string that appears after a negative number (may be - * empty), <i>i.e.,</i> <tt>df.</tt>{@link - * java.text.DecimalFormat#getNegativeSuffix - * getNegativeSuffix()}</td></tr> - * <tr><td valign="top"><i>LocalNaN </i></td> - * <td valign="top">The string that represents not-a-number for - * floating-point values, - * <i>i.e.,</i> <tt>dfs.</tt>{@link - * java.text.DecimalFormatSymbols#getNaN - * getNaN()}</td></tr> - * <tr><td valign="top"><i>LocalInfinity </i></td> - * <td valign="top">The string that represents infinity for floating-point - * values, <i>i.e.,</i> <tt>dfs.</tt>{@link - * java.text.DecimalFormatSymbols#getInfinity - * getInfinity()}</td></tr> - * </table></blockquote> - * - * <a name="number-syntax"> - * <h4> Number syntax </h4> - * - * <p> The strings that can be parsed as numbers by an instance of this class - * are specified in terms of the following regular-expression grammar, where - * Rmax is the highest digit in the radix being used (for example, Rmax is 9 - * in base 10). - * - * <p> - * <table cellspacing=0 cellpadding=0 align=center> - * - * <tr><td valign=top align=right><i>NonASCIIDigit</i> ::</td> - * <td valign=top>= A non-ASCII character c for which - * {@link java.lang.Character#isDigit Character.isDigit}<tt>(c)</tt> - * returns true</td></tr> - * - * <tr><td> </td></tr> - * - * <tr><td align=right><i>Non0Digit</i> ::</td> - * <td><tt>= [1-</tt><i>Rmax</i><tt>] | </tt><i>NonASCIIDigit</i></td></tr> - * - * <tr><td> </td></tr> - * - * <tr><td align=right><i>Digit</i> ::</td> - * <td><tt>= [0-</tt><i>Rmax</i><tt>] | </tt><i>NonASCIIDigit</i></td></tr> - * - * <tr><td> </td></tr> - * - * <tr><td valign=top align=right><i>GroupedNumeral</i> ::</td> - * <td valign=top> - * <table cellpadding=0 cellspacing=0> - * <tr><td><tt>= ( </tt></td> - * <td><i>Non0Digit</i><tt> - * </tt><i>Digit</i><tt>? - * </tt><i>Digit</i><tt>?</tt></td></tr> - * <tr><td></td> - * <td><tt>( </tt><i>LocalGroupSeparator</i><tt> - * </tt><i>Digit</i><tt> - * </tt><i>Digit</i><tt> - * </tt><i>Digit</i><tt> )+ )</tt></td></tr> - * </table></td></tr> - * - * <tr><td> </td></tr> - * - * <tr><td align=right><i>Numeral</i> ::</td> - * <td><tt>= ( ( </tt><i>Digit</i><tt>+ ) - * | </tt><i>GroupedNumeral</i><tt> )</tt></td></tr> - * - * <tr><td> </td></tr> - * - * <tr><td valign=top align=right> - * <a name="Integer-regex"><i>Integer</i> ::</td> - * <td valign=top><tt>= ( [-+]? ( </tt><i>Numeral</i><tt> - * ) )</tt></td></tr> - * <tr><td></td> - * <td><tt>| </tt><i>LocalPositivePrefix</i><tt> </tt><i>Numeral</i><tt> - * </tt><i>LocalPositiveSuffix</i></td></tr> - * <tr><td></td> - * <td><tt>| </tt><i>LocalNegativePrefix</i><tt> </tt><i>Numeral</i><tt> - * </tt><i>LocalNegativeSuffix</i></td></tr> - * - * <tr><td> </td></tr> - * - * <tr><td align=right><i>DecimalNumeral</i> ::</td> - * <td><tt>= </tt><i>Numeral</i></td></tr> - * <tr><td></td> - * <td><tt>| </tt><i>Numeral</i><tt> - * </tt><i>LocalDecimalSeparator</i><tt> - * </tt><i>Digit</i><tt>*</tt></td></tr> - * <tr><td></td> - * <td><tt>| </tt><i>LocalDecimalSeparator</i><tt> - * </tt><i>Digit</i><tt>+</tt></td></tr> - * - * <tr><td> </td></tr> - * - * <tr><td align=right><i>Exponent</i> ::</td> - * <td><tt>= ( [eE] [+-]? </tt><i>Digit</i><tt>+ )</tt></td></tr> - * - * <tr><td> </td></tr> - * - * <tr><td align=right> - * <a name="Decimal-regex"><i>Decimal</i> ::</td> - * <td><tt>= ( [-+]? </tt><i>DecimalNumeral</i><tt> - * </tt><i>Exponent</i><tt>? )</tt></td></tr> - * <tr><td></td> - * <td><tt>| </tt><i>LocalPositivePrefix</i><tt> - * </tt><i>DecimalNumeral</i><tt> - * </tt><i>LocalPositiveSuffix</i> - * </tt><i>Exponent</i><tt>?</td></tr> - * <tr><td></td> - * <td><tt>| </tt><i>LocalNegativePrefix</i><tt> - * </tt><i>DecimalNumeral</i><tt> - * </tt><i>LocalNegativeSuffix</i> - * </tt><i>Exponent</i><tt>?</td></tr> - * - * <tr><td> </td></tr> - * - * <tr><td align=right><i>HexFloat</i> ::</td> - * <td><tt>= [-+]? 0[xX][0-9a-fA-F]*\.[0-9a-fA-F]+ - * ([pP][-+]?[0-9]+)?</tt></td></tr> - * - * <tr><td> </td></tr> - * - * <tr><td align=right><i>NonNumber</i> ::</td> - * <td valign=top><tt>= NaN - * | </tt><i>LocalNan</i><tt> - * | Infinity - * | </tt><i>LocalInfinity</i></td></tr> - * - * <tr><td> </td></tr> - * - * <tr><td align=right><i>SignedNonNumber</i> ::</td> - * <td><tt>= ( [-+]? </tt><i>NonNumber</i><tt> )</tt></td></tr> - * <tr><td></td> - * <td><tt>| </tt><i>LocalPositivePrefix</i><tt> - * </tt><i>NonNumber</i><tt> - * </tt><i>LocalPositiveSuffix</i></td></tr> - * <tr><td></td> - * <td><tt>| </tt><i>LocalNegativePrefix</i><tt> - * </tt><i>NonNumber</i><tt> - * </tt><i>LocalNegativeSuffix</i></td></tr> - * - * <tr><td> </td></tr> - * - * <tr><td valign=top align=right> - * <a name="Float-regex"><i>Float</i> ::</td> - * <td valign=top><tt>= </tt><i>Decimal</i><tt></td></tr> - * <tr><td></td> - * <td><tt>| </tt><i>HexFloat</i><tt></td></tr> - * <tr><td></td> - * <td><tt>| </tt><i>SignedNonNumber</i><tt></td></tr> - * - * </table> - * </center> - * - * <p> Whitespace is not significant in the above regular expressions. - * - * @since 1.5 - */ -public final class Scanner implements Iterator<String> { - - // Internal buffer used to hold input - private CharBuffer buf; - - // Size of internal character buffer - private static final int BUFFER_SIZE = 1024; // change to 1024; - - // The index into the buffer currently held by the Scanner - private int position; - - // Internal matcher used for finding delimiters - private Matcher matcher; - - // Pattern used to delimit tokens - private Pattern delimPattern; - - // Pattern found in last hasNext operation - private Pattern hasNextPattern; - - // Position after last hasNext operation - private int hasNextPosition; - - // Result after last hasNext operation - private String hasNextResult; - - // The input source - private Readable source; - - // Boolean is true if source is done - private boolean sourceClosed = false; - - // Boolean indicating more input is required - private boolean needInput = false; - - // Boolean indicating if a delim has been skipped this operation - private boolean skipped = false; - - // A store of a position that the scanner may fall back to - private int savedScannerPosition = -1; - - // A cache of the last primitive type scanned - private Object typeCache = null; - - // Boolean indicating if a match result is available - private boolean matchValid = false; - - // Boolean indicating if this scanner has been closed - private boolean closed = false; - - // The current radix used by this scanner - private int radix = 10; - - // The default radix for this scanner - private int defaultRadix = 10; - - // The locale used by this scanner - private Locale locale = null; - - // A cache of the last few recently used Patterns - private LRUCache<String,Pattern> patternCache = - new LRUCache<String,Pattern>(7) { - protected Pattern create(String s) { - return Pattern.compile(s); - } - protected boolean hasName(Pattern p, String s) { - return p.pattern().equals(s); - } - }; - - // A holder of the last IOException encountered - private IOException lastException; - - // A pattern for java whitespace - private static Pattern WHITESPACE_PATTERN = Pattern.compile( - "\\p{javaWhitespace}+"); - - // A pattern for any token - private static Pattern FIND_ANY_PATTERN = Pattern.compile("(?s).*"); - - // A pattern for non-ASCII digits - private static Pattern NON_ASCII_DIGIT = Pattern.compile( - "[\\p{javaDigit}&&[^0-9]]"); - - // Fields and methods to support scanning primitive types - - /** - * Locale dependent values used to scan numbers - */ - private String groupSeparator = "\\,"; - private String decimalSeparator = "\\."; - private String nanString = "NaN"; - private String infinityString = "Infinity"; - private String positivePrefix = ""; - private String negativePrefix = "\\-"; - private String positiveSuffix = ""; - private String negativeSuffix = ""; - - /** - * Fields and an accessor method to match booleans - */ - private static volatile Pattern boolPattern; - private static final String BOOLEAN_PATTERN = "true|false"; - private static Pattern boolPattern() { - Pattern bp = boolPattern; - if (bp == null) - boolPattern = bp = Pattern.compile(BOOLEAN_PATTERN, - Pattern.CASE_INSENSITIVE); - return bp; - } - - /** - * Fields and methods to match bytes, shorts, ints, and longs - */ - private Pattern integerPattern; - private String digits = "0123456789abcdefghijklmnopqrstuvwxyz"; - private String non0Digit = "[\\p{javaDigit}&&[^0]]"; - private int SIMPLE_GROUP_INDEX = 5; - private String buildIntegerPatternString() { - String radixDigits = digits.substring(0, radix); - // \\p{javaDigit} is not guaranteed to be appropriate - // here but what can we do? The final authority will be - // whatever parse method is invoked, so ultimately the - // Scanner will do the right thing - String digit = "((?i)["+radixDigits+"]|\\p{javaDigit})"; - String groupedNumeral = "("+non0Digit+digit+"?"+digit+"?("+ - groupSeparator+digit+digit+digit+")+)"; - // digit++ is the possessive form which is necessary for reducing - // backtracking that would otherwise cause unacceptable performance - String numeral = "(("+ digit+"++)|"+groupedNumeral+")"; - String javaStyleInteger = "([-+]?(" + numeral + "))"; - String negativeInteger = negativePrefix + numeral + negativeSuffix; - String positiveInteger = positivePrefix + numeral + positiveSuffix; - return "("+ javaStyleInteger + ")|(" + - positiveInteger + ")|(" + - negativeInteger + ")"; - } - private Pattern integerPattern() { - if (integerPattern == null) { - integerPattern = patternCache.forName(buildIntegerPatternString()); - } - return integerPattern; - } - - /** - * Fields and an accessor method to match line separators - */ - private static volatile Pattern separatorPattern; - private static volatile Pattern linePattern; - private static final String LINE_SEPARATOR_PATTERN = - "\r\n|[\n\r\u2028\u2029\u0085]"; - private static final String LINE_PATTERN = ".*("+LINE_SEPARATOR_PATTERN+")|.+$"; - - private static Pattern separatorPattern() { - Pattern sp = separatorPattern; - if (sp == null) - separatorPattern = sp = Pattern.compile(LINE_SEPARATOR_PATTERN); - return sp; - } - - private static Pattern linePattern() { - Pattern lp = linePattern; - if (lp == null) - linePattern = lp = Pattern.compile(LINE_PATTERN); - return lp; - } - - /** - * Fields and methods to match floats and doubles - */ - private Pattern floatPattern; - private Pattern decimalPattern; - private void buildFloatAndDecimalPattern() { - // \\p{javaDigit} may not be perfect, see above - String digit = "([0-9]|(\\p{javaDigit}))"; - String exponent = "([eE][+-]?"+digit+"+)?"; - String groupedNumeral = "("+non0Digit+digit+"?"+digit+"?("+ - groupSeparator+digit+digit+digit+")+)"; - // Once again digit++ is used for performance, as above - String numeral = "(("+digit+"++)|"+groupedNumeral+")"; - String decimalNumeral = "("+numeral+"|"+numeral + - decimalSeparator + digit + "*+|"+ decimalSeparator + - digit + "++)"; - String nonNumber = "(NaN|"+nanString+"|Infinity|"+ - infinityString+")"; - String positiveFloat = "(" + positivePrefix + decimalNumeral + - positiveSuffix + exponent + ")"; - String negativeFloat = "(" + negativePrefix + decimalNumeral + - negativeSuffix + exponent + ")"; - String decimal = "(([-+]?" + decimalNumeral + exponent + ")|"+ - positiveFloat + "|" + negativeFloat + ")"; - String hexFloat = - "[-+]?0[xX][0-9a-fA-F]*\\.[0-9a-fA-F]+([pP][-+]?[0-9]+)?"; - String positiveNonNumber = "(" + positivePrefix + nonNumber + - positiveSuffix + ")"; - String negativeNonNumber = "(" + negativePrefix + nonNumber + - negativeSuffix + ")"; - String signedNonNumber = "(([-+]?"+nonNumber+")|" + - positiveNonNumber + "|" + - negativeNonNumber + ")"; - floatPattern = Pattern.compile(decimal + "|" + hexFloat + "|" + - signedNonNumber); - decimalPattern = Pattern.compile(decimal); - } - private Pattern floatPattern() { - if (floatPattern == null) { - buildFloatAndDecimalPattern(); - } - return floatPattern; - } - private Pattern decimalPattern() { - if (decimalPattern == null) { - buildFloatAndDecimalPattern(); - } - return decimalPattern; - } - - // Constructors - - /** - * Constructs a <code>Scanner</code> that returns values scanned - * from the specified source delimited by the specified pattern. - * - * @param source A character source implementing the Readable interface - * @param pattern A delimiting pattern - * @return A scanner with the specified source and pattern - */ - private Scanner(Readable source, Pattern pattern) { - if (source == null) - throw new NullPointerException("source"); - if (pattern == null) - throw new NullPointerException("pattern"); - this.source = source; - delimPattern = pattern; - buf = CharBuffer.allocate(BUFFER_SIZE); - buf.limit(0); - matcher = delimPattern.matcher(buf); - matcher.useTransparentBounds(true); - matcher.useAnchoringBounds(false); - useLocale(Locale.getDefault()); - } - - /** - * Constructs a new <code>Scanner</code> that produces values scanned - * from the specified source. - * - * @param source A character source implementing the {@link Readable} - * interface - */ - public Scanner(Readable source) { - this(source, WHITESPACE_PATTERN); - } - - /** - * Constructs a new <code>Scanner</code> that produces values scanned - * from the specified input stream. Bytes from the stream are converted - * into characters using the underlying platform's - * {@linkplain java.nio.charset.Charset#defaultCharset() default charset}. - * - * @param source An input stream to be scanned - */ - public Scanner(InputStream source) { - this(new InputStreamReader(source), WHITESPACE_PATTERN); - } - - /** - * Constructs a new <code>Scanner</code> that produces values scanned - * from the specified input stream. Bytes from the stream are converted - * into characters using the specified charset. - * - * @param source An input stream to be scanned - * @param charsetName The encoding type used to convert bytes from the - * stream into characters to be scanned - * @throws IllegalArgumentException if the specified character set - * does not exist - */ - public Scanner(InputStream source, String charsetName) { - this(makeReadable(source, charsetName), WHITESPACE_PATTERN); - } - - private static Readable makeReadable(InputStream source, - String charsetName) - { - if (source == null) - throw new NullPointerException("source"); - InputStreamReader isr = null; - try { - isr = new InputStreamReader(source, charsetName); - } catch (UnsupportedEncodingException uee) { - IllegalArgumentException iae = new IllegalArgumentException(); - iae.initCause(uee); - throw iae; - } - return isr; - } - - /** - * Constructs a new <code>Scanner</code> that produces values scanned - * from the specified file. Bytes from the file are converted into - * characters using the underlying platform's - * {@linkplain java.nio.charset.Charset#defaultCharset() default charset}. - * - * @param source A file to be scanned - * @throws FileNotFoundException if source is not found - */ - public Scanner(File source) - throws FileNotFoundException - { - this((ReadableByteChannel)(new FileInputStream(source).getChannel())); - } - - /** - * Constructs a new <code>Scanner</code> that produces values scanned - * from the specified file. Bytes from the file are converted into - * characters using the specified charset. - * - * @param source A file to be scanned - * @param charsetName The encoding type used to convert bytes from the file - * into characters to be scanned - * @throws FileNotFoundException if source is not found - * @throws IllegalArgumentException if the specified encoding is - * not found - */ - public Scanner(File source, String charsetName) - throws FileNotFoundException - { - this((ReadableByteChannel)(new FileInputStream(source).getChannel()), - charsetName); - } - - /** - * {@note new} - * Constructs a new <code>Scanner</code> that produces values scanned - * from the specified file. Bytes from the file are converted into - * characters using the underlying platform's - * {@linkplain java.nio.charset.Charset#defaultCharset() default charset}. - * - * @param source - * A file to be scanned - * @throws IOException - * if an I/O error occurs opening source - * - * @since 1.7 - */ - public Scanner(FileRef source) - throws IOException - { - this(source.newByteChannel()); - } - - /** - * {@note new} - * Constructs a new <code>Scanner</code> that produces values scanned - * from the specified file. Bytes from the file are converted into - * characters using the specified charset. - * - * @param source - * A file to be scanned - * @param charsetName - * The encoding type used to convert bytes from the file - * into characters to be scanned - * @throws IOException - * if an I/O error occurs opening source - * @throws IllegalArgumentException - * if the specified encoding is not found - * @since 1.7 - */ - public Scanner(FileRef source, String charsetName) - throws IOException - { - this(source.newByteChannel(), charsetName); - } - - /** - * Constructs a new <code>Scanner</code> that produces values scanned - * from the specified string. - * - * @param source A string to scan - */ - public Scanner(String source) { - this(new StringReader(source), WHITESPACE_PATTERN); - } - - /** - * Constructs a new <code>Scanner</code> that produces values scanned - * from the specified channel. Bytes from the source are converted into - * characters using the underlying platform's - * {@linkplain java.nio.charset.Charset#defaultCharset() default charset}. - * - * @param source A channel to scan - */ - public Scanner(ReadableByteChannel source) { - this(makeReadable(source), WHITESPACE_PATTERN); - } - - private static Readable makeReadable(ReadableByteChannel source) { - if (source == null) - throw new NullPointerException("source"); - String defaultCharsetName = - java.nio.charset.Charset.defaultCharset().name(); - return Channels.newReader(source, - java.nio.charset.Charset.defaultCharset().name()); - } - - /** - * Constructs a new <code>Scanner</code> that produces values scanned - * from the specified channel. Bytes from the source are converted into - * characters using the specified charset. - * - * @param source A channel to scan - * @param charsetName The encoding type used to convert bytes from the - * channel into characters to be scanned - * @throws IllegalArgumentException if the specified character set - * does not exist - */ - public Scanner(ReadableByteChannel source, String charsetName) { - this(makeReadable(source, charsetName), WHITESPACE_PATTERN); - } - - private static Readable makeReadable(ReadableByteChannel source, - String charsetName) - { - if (source == null) - throw new NullPointerException("source"); - if (!Charset.isSupported(charsetName)) - throw new IllegalArgumentException(charsetName); - return Channels.newReader(source, charsetName); - } - - // Private primitives used to support scanning - - private void saveState() { - savedScannerPosition = position; - } - - private void revertState() { - this.position = savedScannerPosition; - savedScannerPosition = -1; - skipped = false; - } - - private boolean revertState(boolean b) { - this.position = savedScannerPosition; - savedScannerPosition = -1; - skipped = false; - return b; - } - - private void cacheResult() { - hasNextResult = matcher.group(); - hasNextPosition = matcher.end(); - hasNextPattern = matcher.pattern(); - } - - private void cacheResult(String result) { - hasNextResult = result; - hasNextPosition = matcher.end(); - hasNextPattern = matcher.pattern(); - } - - // Clears both regular cache and type cache - private void clearCaches() { - hasNextPattern = null; - typeCache = null; - } - - // Also clears both the regular cache and the type cache - private String getCachedResult() { - position = hasNextPosition; - hasNextPattern = null; - typeCache = null; - return hasNextResult; - } - - // Also clears both the regular cache and the type cache - private void useTypeCache() { - if (closed) - throw new IllegalStateException("Scanner closed"); - position = hasNextPosition; - hasNextPattern = null; - typeCache = null; - } - - // Tries to read more input. May block. - private void readInput() { - if (buf.limit() == buf.capacity()) - makeSpace(); - - // Prepare to receive data - int p = buf.position(); - buf.position(buf.limit()); - buf.limit(buf.capacity()); - - int n = 0; - try { - n = source.read(buf); - } catch (IOException ioe) { - lastException = ioe; - n = -1; - } - - if (n == -1) { - sourceClosed = true; - needInput = false; - } - - if (n > 0) - needInput = false; - - // Restore current position and limit for reading - buf.limit(buf.position()); - buf.position(p); - } - - // After this method is called there will either be an exception - // or else there will be space in the buffer - private boolean makeSpace() { - clearCaches(); - int offset = savedScannerPosition == -1 ? - position : savedScannerPosition; - buf.position(offset); - // Gain space by compacting buffer - if (offset > 0) { - buf.compact(); - translateSavedIndexes(offset); - position -= offset; - buf.flip(); - return true; - } - // Gain space by growing buffer - int newSize = buf.capacity() * 2; - CharBuffer newBuf = CharBuffer.allocate(newSize); - newBuf.put(buf); - newBuf.flip(); - translateSavedIndexes(offset); - position -= offset; - buf = newBuf; - matcher.reset(buf); - return true; - } - - // When a buffer compaction/reallocation occurs the saved indexes must - // be modified appropriately - private void translateSavedIndexes(int offset) { - if (savedScannerPosition != -1) - savedScannerPosition -= offset; - } - - // If we are at the end of input then NoSuchElement; - // If there is still input left then InputMismatch - private void throwFor() { - skipped = false; - if ((sourceClosed) && (position == buf.limit())) - throw new NoSuchElementException(); - else - throw new InputMismatchException(); - } - - // Returns true if a complete token or partial token is in the buffer. - // It is not necessary to find a complete token since a partial token - // means that there will be another token with or without more input. - private boolean hasTokenInBuffer() { - matchValid = false; - matcher.usePattern(delimPattern); - matcher.region(position, buf.limit()); - - // Skip delims first - if (matcher.lookingAt()) - position = matcher.end(); - - // If we are sitting at the end, no more tokens in buffer - if (position == buf.limit()) - return false; - - return true; - } - - /* - * Returns a "complete token" that matches the specified pattern - * - * A token is complete if surrounded by delims; a partial token - * is prefixed by delims but not postfixed by them - * - * The position is advanced to the end of that complete token - * - * Pattern == null means accept any token at all - * - * Triple return: - * 1. valid string means it was found - * 2. null with needInput=false means we won't ever find it - * 3. null with needInput=true means try again after readInput - */ - private String getCompleteTokenInBuffer(Pattern pattern) { - matchValid = false; - - // Skip delims first - matcher.usePattern(delimPattern); - if (!skipped) { // Enforcing only one skip of leading delims - matcher.region(position, buf.limit()); - if (matcher.lookingAt()) { - // If more input could extend the delimiters then we must wait - // for more input - if (matcher.hitEnd() && !sourceClosed) { - needInput = true; - return null; - } - // The delims were whole and the matcher should skip them - skipped = true; - position = matcher.end(); - } - } - - // If we are sitting at the end, no more tokens in buffer - if (position == buf.limit()) { - if (sourceClosed) - return null; - needInput = true; - return null; - } - - // Must look for next delims. Simply attempting to match the - // pattern at this point may find a match but it might not be - // the first longest match because of missing input, or it might - // match a partial token instead of the whole thing. - - // Then look for next delims - matcher.region(position, buf.limit()); - boolean foundNextDelim = matcher.find(); - if (foundNextDelim && (matcher.end() == position)) { - // Zero length delimiter match; we should find the next one - // using the automatic advance past a zero length match; - // Otherwise we have just found the same one we just skipped - foundNextDelim = matcher.find(); - } - if (foundNextDelim) { - // In the rare case that more input could cause the match - // to be lost and there is more input coming we must wait - // for more input. Note that hitting the end is okay as long - // as the match cannot go away. It is the beginning of the - // next delims we want to be sure about, we don't care if - // they potentially extend further. - if (matcher.requireEnd() && !sourceClosed) { - needInput = true; - return null; - } - int tokenEnd = matcher.start(); - // There is a complete token. - if (pattern == null) { - // Must continue with match to provide valid MatchResult - pattern = FIND_ANY_PATTERN; - } - // Attempt to match against the desired pattern - matcher.usePattern(pattern); - matcher.region(position, tokenEnd); - if (matcher.matches()) { - String s = matcher.group(); - position = matcher.end(); - return s; - } else { // Complete token but it does not match - return null; - } - } - - // If we can't find the next delims but no more input is coming, - // then we can treat the remainder as a whole token - if (sourceClosed) { - if (pattern == null) { - // Must continue with match to provide valid MatchResult - pattern = FIND_ANY_PATTERN; - } - // Last token; Match the pattern here or throw - matcher.usePattern(pattern); - matcher.region(position, buf.limit()); - if (matcher.matches()) { - String s = matcher.group(); - position = matcher.end(); - return s; - } - // Last piece does not match - return null; - } - - // There is a partial token in the buffer; must read more - // to complete it - needInput = true; - return null; - } - - // Finds the specified pattern in the buffer up to horizon. - // Returns a match for the specified input pattern. - private String findPatternInBuffer(Pattern pattern, int horizon) { - matchValid = false; - matcher.usePattern(pattern); - int bufferLimit = buf.limit(); - int horizonLimit = -1; - int searchLimit = bufferLimit; - if (horizon > 0) { - horizonLimit = position + horizon; - if (horizonLimit < bufferLimit) - searchLimit = horizonLimit; - } - matcher.region(position, searchLimit); - if (matcher.find()) { - if (matcher.hitEnd() && (!sourceClosed)) { - // The match may be longer if didn't hit horizon or real end - if (searchLimit != horizonLimit) { - // Hit an artificial end; try to extend the match - needInput = true; - return null; - } - // The match could go away depending on what is next - if ((searchLimit == horizonLimit) && matcher.requireEnd()) { - // Rare case: we hit the end of input and it happens - // that it is at the horizon and the end of input is - // required for the match. - needInput = true; - return null; - } - } - // Did not hit end, or hit real end, or hit horizon - position = matcher.end(); - return matcher.group(); - } - - if (sourceClosed) - return null; - - // If there is no specified horizon, or if we have not searched - // to the specified horizon yet, get more input - if ((horizon == 0) || (searchLimit != horizonLimit)) - needInput = true; - return null; - } - - // Returns a match for the specified input pattern anchored at - // the current position - private String matchPatternInBuffer(Pattern pattern) { - matchValid = false; - matcher.usePattern(pattern); - matcher.region(position, buf.limit()); - if (matcher.lookingAt()) { - if (matcher.hitEnd() && (!sourceClosed)) { - // Get more input and try again - needInput = true; - return null; - } - position = matcher.end(); - return matcher.group(); - } - - if (sourceClosed) - return null; - - // Read more to find pattern - needInput = true; - return null; - } - - // Throws if the scanner is closed - private void ensureOpen() { - if (closed) - throw new IllegalStateException("Scanner closed"); - } - - // Public methods - - /** - * Closes this scanner. - * - * <p> If this scanner has not yet been closed then if its underlying - * {@linkplain java.lang.Readable readable} also implements the {@link - * java.io.Closeable} interface then the readable's <tt>close</tt> method - * will be invoked. If this scanner is already closed then invoking this - * method will have no effect. - * - * <p>Attempting to perform search operations after a scanner has - * been closed will result in an {@link IllegalStateException}. - * - */ - public void close() { - if (closed) - return; - if (source instanceof Closeable) { - try { - ((Closeable)source).close(); - } catch (IOException ioe) { - lastException = ioe; - } - } - sourceClosed = true; - source = null; - closed = true; - } - - /** - * Returns the <code>IOException</code> last thrown by this - * <code>Scanner</code>'s underlying <code>Readable</code>. This method - * returns <code>null</code> if no such exception exists. - * - * @return the last exception thrown by this scanner's readable - */ - public IOException ioException() { - return lastException; - } - - /** - * Returns the <code>Pattern</code> this <code>Scanner</code> is currently - * using to match delimiters. - * - * @return this scanner's delimiting pattern. - */ - public Pattern delimiter() { - return delimPattern; - } - - /** - * Sets this scanner's delimiting pattern to the specified pattern. - * - * @param pattern A delimiting pattern - * @return this scanner - */ - public Scanner useDelimiter(Pattern pattern) { - delimPattern = pattern; - return this; - } - - /** - * Sets this scanner's delimiting pattern to a pattern constructed from - * the specified <code>String</code>. - * - * <p> An invocation of this method of the form - * <tt>useDelimiter(pattern)</tt> behaves in exactly the same way as the - * invocation <tt>useDelimiter(Pattern.compile(pattern))</tt>. - * - * <p> Invoking the {@link #reset} method will set the scanner's delimiter - * to the <a href= "#default-delimiter">default</a>. - * - * @param pattern A string specifying a delimiting pattern - * @return this scanner - */ - public Scanner useDelimiter(String pattern) { - delimPattern = patternCache.forName(pattern); - return this; - } - - /** - * Returns this scanner's locale. - * - * <p>A scanner's locale affects many elements of its default - * primitive matching regular expressions; see - * <a href= "#localized-numbers">localized numbers</a> above. - * - * @return this scanner's locale - */ - public Locale locale() { - return this.locale; - } - - /** - * Sets this scanner's locale to the specified locale. - * - * <p>A scanner's locale affects many elements of its default - * primitive matching regular expressions; see - * <a href= "#localized-numbers">localized numbers</a> above. - * - * <p>Invoking the {@link #reset} method will set the scanner's locale to - * the <a href= "#initial-locale">initial locale</a>. - * - * @param locale A string specifying the locale to use - * @return this scanner - */ - public Scanner useLocale(Locale locale) { - if (locale.equals(this.locale)) - return this; - - this.locale = locale; - DecimalFormat df = - (DecimalFormat)NumberFormat.getNumberInstance(locale); - DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(locale); - - // These must be literalized to avoid collision with regex - // metacharacters such as dot or parenthesis - groupSeparator = "\\" + dfs.getGroupingSeparator(); - decimalSeparator = "\\" + dfs.getDecimalSeparator(); - - // Quoting the nonzero length locale-specific things - // to avoid potential conflict with metacharacters - nanString = "\\Q" + dfs.getNaN() + "\\E"; - infinityString = "\\Q" + dfs.getInfinity() + "\\E"; - positivePrefix = df.getPositivePrefix(); - if (positivePrefix.length() > 0) - positivePrefix = "\\Q" + positivePrefix + "\\E"; - negativePrefix = df.getNegativePrefix(); - if (negativePrefix.length() > 0) - negativePrefix = "\\Q" + negativePrefix + "\\E"; - positiveSuffix = df.getPositiveSuffix(); - if (positiveSuffix.length() > 0) - positiveSuffix = "\\Q" + positiveSuffix + "\\E"; - negativeSuffix = df.getNegativeSuffix(); - if (negativeSuffix.length() > 0) - negativeSuffix = "\\Q" + negativeSuffix + "\\E"; - - // Force rebuilding and recompilation of locale dependent - // primitive patterns - integerPattern = null; - floatPattern = null; - - return this; - } - - /** - * Returns this scanner's default radix. - * - * <p>A scanner's radix affects elements of its default - * number matching regular expressions; see - * <a href= "#localized-numbers">localized numbers</a> above. - * - * @return the default radix of this scanner - */ - public int radix() { - return this.defaultRadix; - } - - /** - * Sets this scanner's default radix to the specified radix. - * - * <p>A scanner's radix affects elements of its default - * number matching regular expressions; see - * <a href= "#localized-numbers">localized numbers</a> above. - * - * <p>If the radix is less than <code>Character.MIN_RADIX</code> - * or greater than <code>Character.MAX_RADIX</code>, then an - * <code>IllegalArgumentException</code> is thrown. - * - * <p>Invoking the {@link #reset} method will set the scanner's radix to - * <code>10</code>. - * - * @param radix The radix to use when scanning numbers - * @return this scanner - * @throws IllegalArgumentException if radix is out of range - */ - public Scanner useRadix(int radix) { - if ((radix < Character.MIN_RADIX) || (radix > Character.MAX_RADIX)) - throw new IllegalArgumentException("radix:"+radix); - - if (this.defaultRadix == radix) - return this; - this.defaultRadix = radix; - // Force rebuilding and recompilation of radix dependent patterns - integerPattern = null; - return this; - } - - // The next operation should occur in the specified radix but - // the default is left untouched. - private void setRadix(int radix) { - if (this.radix != radix) { - // Force rebuilding and recompilation of radix dependent patterns - integerPattern = null; - this.radix = radix; - } - } - - /** - * Returns the match result of the last scanning operation performed - * by this scanner. This method throws <code>IllegalStateException</code> - * if no match has been performed, or if the last match was - * not successful. - * - * <p>The various <code>next</code>methods of <code>Scanner</code> - * make a match result available if they complete without throwing an - * exception. For instance, after an invocation of the {@link #nextInt} - * method that returned an int, this method returns a - * <code>MatchResult</code> for the search of the - * <a href="#Integer-regex"><i>Integer</i></a> regular expression - * defined above. Similarly the {@link #findInLine}, - * {@link #findWithinHorizon}, and {@link #skip} methods will make a - * match available if they succeed. - * - * @return a match result for the last match operation - * @throws IllegalStateException If no match result is available - */ - public MatchResult match() { - if (!matchValid) - throw new IllegalStateException("No match result available"); - return matcher.toMatchResult(); - } - - /** - * <p>Returns the string representation of this <code>Scanner</code>. The - * string representation of a <code>Scanner</code> contains information - * that may be useful for debugging. The exact format is unspecified. - * - * @return The string representation of this scanner - */ - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("java.util.Scanner"); - sb.append("[delimiters=" + delimPattern + "]"); - sb.append("[position=" + position + "]"); - sb.append("[match valid=" + matchValid + "]"); - sb.append("[need input=" + needInput + "]"); - sb.append("[source closed=" + sourceClosed + "]"); - sb.append("[skipped=" + skipped + "]"); - sb.append("[group separator=" + groupSeparator + "]"); - sb.append("[decimal separator=" + decimalSeparator + "]"); - sb.append("[positive prefix=" + positivePrefix + "]"); - sb.append("[negative prefix=" + negativePrefix + "]"); - sb.append("[positive suffix=" + positiveSuffix + "]"); - sb.append("[negative suffix=" + negativeSuffix + "]"); - sb.append("[NaN string=" + nanString + "]"); - sb.append("[infinity string=" + infinityString + "]"); - return sb.toString(); - } - - /** - * Returns true if this scanner has another token in its input. - * This method may block while waiting for input to scan. - * The scanner does not advance past any input. - * - * @return true if and only if this scanner has another token - * @throws IllegalStateException if this scanner is closed - * @see java.util.Iterator - */ - public boolean hasNext() { - ensureOpen(); - saveState(); - while (!sourceClosed) { - if (hasTokenInBuffer()) - return revertState(true); - readInput(); - } - boolean result = hasTokenInBuffer(); - return revertState(result); - } - - /** - * Finds and returns the next complete token from this scanner. - * A complete token is preceded and followed by input that matches - * the delimiter pattern. This method may block while waiting for input - * to scan, even if a previous invocation of {@link #hasNext} returned - * <code>true</code>. - * - * @return the next token - * @throws NoSuchElementException if no more tokens are available - * @throws IllegalStateException if this scanner is closed - * @see java.util.Iterator - */ - public String next() { - ensureOpen(); - clearCaches(); - - while (true) { - String token = getCompleteTokenInBuffer(null); - if (token != null) { - matchValid = true; - skipped = false; - return token; - } - if (needInput) - readInput(); - else - throwFor(); - } - } - - /** - * The remove operation is not supported by this implementation of - * <code>Iterator</code>. - * - * @throws UnsupportedOperationException if this method is invoked. - * @see java.util.Iterator - */ - public void remove() { - throw new UnsupportedOperationException(); - } - - /** - * Returns true if the next token matches the pattern constructed from the - * specified string. The scanner does not advance past any input. - * - * <p> An invocation of this method of the form <tt>hasNext(pattern)</tt> - * behaves in exactly the same way as the invocation - * <tt>hasNext(Pattern.compile(pattern))</tt>. - * - * @param pattern a string specifying the pattern to scan - * @return true if and only if this scanner has another token matching - * the specified pattern - * @throws IllegalStateException if this scanner is closed - */ - public boolean hasNext(String pattern) { - return hasNext(patternCache.forName(pattern)); - } - - /** - * Returns the next token if it matches the pattern constructed from the - * specified string. If the match is successful, the scanner advances - * past the input that matched the pattern. - * - * <p> An invocation of this method of the form <tt>next(pattern)</tt> - * behaves in exactly the same way as the invocation - * <tt>next(Pattern.compile(pattern))</tt>. - * - * @param pattern a string specifying the pattern to scan - * @return the next token - * @throws NoSuchElementException if no such tokens are available - * @throws IllegalStateException if this scanner is closed - */ - public String next(String pattern) { - return next(patternCache.forName(pattern)); - } - - /** - * Returns true if the next complete token matches the specified pattern. - * A complete token is prefixed and postfixed by input that matches - * the delimiter pattern. This method may block while waiting for input. - * The scanner does not advance past any input. - * - * @param pattern the pattern to scan for - * @return true if and only if this scanner has another token matching - * the specified pattern - * @throws IllegalStateException if this scanner is closed - */ - public boolean hasNext(Pattern pattern) { - ensureOpen(); - if (pattern == null) - throw new NullPointerException(); - hasNextPattern = null; - saveState(); - - while (true) { - if (getCompleteTokenInBuffer(pattern) != null) { - matchValid = true; - cacheResult(); - return revertState(true); - } - if (needInput) - readInput(); - else - return revertState(false); - } - } - - /** - * Returns the next token if it matches the specified pattern. This - * method may block while waiting for input to scan, even if a previous - * invocation of {@link #hasNext(Pattern)} returned <code>true</code>. - * If the match is successful, the scanner advances past the input that - * matched the pattern. - * - * @param pattern the pattern to scan for - * @return the next token - * @throws NoSuchElementException if no more tokens are available - * @throws IllegalStateException if this scanner is closed - */ - public String next(Pattern pattern) { - ensureOpen(); - if (pattern == null) - throw new NullPointerException(); - - // Did we already find this pattern? - if (hasNextPattern == pattern) - return getCachedResult(); - clearCaches(); - - // Search for the pattern - while (true) { - String token = getCompleteTokenInBuffer(pattern); - if (token != null) { - matchValid = true; - skipped = false; - return token; - } - if (needInput) - readInput(); - else - throwFor(); - } - } - - /** - * Returns true if there is another line in the input of this scanner. - * This method may block while waiting for input. The scanner does not - * advance past any input. - * - * @return true if and only if this scanner has another line of input - * @throws IllegalStateException if this scanner is closed - */ - public boolean hasNextLine() { - saveState(); - - String result = findWithinHorizon(linePattern(), 0); - if (result != null) { - MatchResult mr = this.match(); - String lineSep = mr.group(1); - if (lineSep != null) { - result = result.substring(0, result.length() - - lineSep.length()); - cacheResult(result); - - } else { - cacheResult(); - } - } - revertState(); - return (result != null); - } - - /** - * Advances this scanner past the current line and returns the input - * that was skipped. - * - * This method returns the rest of the current line, excluding any line - * separator at the end. The position is set to the beginning of the next - * line. - * - * <p>Since this method continues to search through the input looking - * for a line separator, it may buffer all of the input searching for - * the line to skip if no line separators are present. - * - * @return the line that was skipped - * @throws NoSuchElementException if no line was found - * @throws IllegalStateException if this scanner is closed - */ - public String nextLine() { - if (hasNextPattern == linePattern()) - return getCachedResult(); - clearCaches(); - - String result = findWithinHorizon(linePattern, 0); - if (result == null) - throw new NoSuchElementException("No line found"); - MatchResult mr = this.match(); - String lineSep = mr.group(1); - if (lineSep != null) - result = result.substring(0, result.length() - lineSep.length()); - if (result == null) - throw new NoSuchElementException(); - else - return result; - } - - // Public methods that ignore delimiters - - /** - * Attempts to find the next occurrence of a pattern constructed from the - * specified string, ignoring delimiters. - * - * <p>An invocation of this method of the form <tt>findInLine(pattern)</tt> - * behaves in exactly the same way as the invocation - * <tt>findInLine(Pattern.compile(pattern))</tt>. - * - * @param pattern a string specifying the pattern to search for - * @return the text that matched the specified pattern - * @throws IllegalStateException if this scanner is closed - */ - public String findInLine(String pattern) { - return findInLine(patternCache.forName(pattern)); - } - - /** - * Attempts to find the next occurrence of the specified pattern ignoring - * delimiters. If the pattern is found before the next line separator, the - * scanner advances past the input that matched and returns the string that - * matched the pattern. - * If no such pattern is detected in the input up to the next line - * separator, then <code>null</code> is returned and the scanner's - * position is unchanged. This method may block waiting for input that - * matches the pattern. - * - * <p>Since this method continues to search through the input looking - * for the specified pattern, it may buffer all of the input searching for - * the desired token if no line separators are present. - * - * @param pattern the pattern to scan for - * @return the text that matched the specified pattern - * @throws IllegalStateException if this scanner is closed - */ - public String findInLine(Pattern pattern) { - ensureOpen(); - if (pattern == null) - throw new NullPointerException(); - clearCaches(); - // Expand buffer to include the next newline or end of input - int endPosition = 0; - saveState(); - while (true) { - String token = findPatternInBuffer(separatorPattern(), 0); - if (token != null) { - endPosition = matcher.start(); - break; // up to next newline - } - if (needInput) { - readInput(); - } else { - endPosition = buf.limit(); - break; // up to end of input - } - } - revertState(); - int horizonForLine = endPosition - position; - // If there is nothing between the current pos and the next - // newline simply return null, invoking findWithinHorizon - // with "horizon=0" will scan beyond the line bound. - if (horizonForLine == 0) - return null; - // Search for the pattern - return findWithinHorizon(pattern, horizonForLine); - } - - /** - * Attempts to find the next occurrence of a pattern constructed from the - * specified string, ignoring delimiters. - * - * <p>An invocation of this method of the form - * <tt>findWithinHorizon(pattern)</tt> behaves in exactly the same way as - * the invocation - * <tt>findWithinHorizon(Pattern.compile(pattern, horizon))</tt>. - * - * @param pattern a string specifying the pattern to search for - * @return the text that matched the specified pattern - * @throws IllegalStateException if this scanner is closed - * @throws IllegalArgumentException if horizon is negative - */ - public String findWithinHorizon(String pattern, int horizon) { - return findWithinHorizon(patternCache.forName(pattern), horizon); - } - - /** - * Attempts to find the next occurrence of the specified pattern. - * - * <p>This method searches through the input up to the specified - * search horizon, ignoring delimiters. If the pattern is found the - * scanner advances past the input that matched and returns the string - * that matched the pattern. If no such pattern is detected then the - * null is returned and the scanner's position remains unchanged. This - * method may block waiting for input that matches the pattern. - * - * <p>A scanner will never search more than <code>horizon</code> code - * points beyond its current position. Note that a match may be clipped - * by the horizon; that is, an arbitrary match result may have been - * different if the horizon had been larger. The scanner treats the - * horizon as a transparent, non-anchoring bound (see {@link - * Matcher#useTransparentBounds} and {@link Matcher#useAnchoringBounds}). - * - * <p>If horizon is <code>0</code>, then the horizon is ignored and - * this method continues to search through the input looking for the - * specified pattern without bound. In this case it may buffer all of - * the input searching for the pattern. - * - * <p>If horizon is negative, then an IllegalArgumentException is - * thrown. - * - * @param pattern the pattern to scan for - * @return the text that matched the specified pattern - * @throws IllegalStateException if this scanner is closed - * @throws IllegalArgumentException if horizon is negative - */ - public String findWithinHorizon(Pattern pattern, int horizon) { - ensureOpen(); - if (pattern == null) - throw new NullPointerException(); - if (horizon < 0) - throw new IllegalArgumentException("horizon < 0"); - clearCaches(); - - // Search for the pattern - while (true) { - String token = findPatternInBuffer(pattern, horizon); - if (token != null) { - matchValid = true; - return token; - } - if (needInput) - readInput(); - else - break; // up to end of input - } - return null; - } - - /** - * Skips input that matches the specified pattern, ignoring delimiters. - * This method will skip input if an anchored match of the specified - * pattern succeeds. - * - * <p>If a match to the specified pattern is not found at the - * current position, then no input is skipped and a - * <tt>NoSuchElementException</tt> is thrown. - * - * <p>Since this method seeks to match the specified pattern starting at - * the scanner's current position, patterns that can match a lot of - * input (".*", for example) may cause the scanner to buffer a large - * amount of input. - * - * <p>Note that it is possible to skip something without risking a - * <code>NoSuchElementException</code> by using a pattern that can - * match nothing, e.g., <code>sc.skip("[ \t]*")</code>. - * - * @param pattern a string specifying the pattern to skip over - * @return this scanner - * @throws NoSuchElementException if the specified pattern is not found - * @throws IllegalStateException if this scanner is closed - */ - public Scanner skip(Pattern pattern) { - ensureOpen(); - if (pattern == null) - throw new NullPointerException(); - clearCaches(); - - // Search for the pattern - while (true) { - String token = matchPatternInBuffer(pattern); - if (token != null) { - matchValid = true; - position = matcher.end(); - return this; - } - if (needInput) - readInput(); - else - throw new NoSuchElementException(); - } - } - - /** - * Skips input that matches a pattern constructed from the specified - * string. - * - * <p> An invocation of this method of the form <tt>skip(pattern)</tt> - * behaves in exactly the same way as the invocation - * <tt>skip(Pattern.compile(pattern))</tt>. - * - * @param pattern a string specifying the pattern to skip over - * @return this scanner - * @throws IllegalStateException if this scanner is closed - */ - public Scanner skip(String pattern) { - return skip(patternCache.forName(pattern)); - } - - // Convenience methods for scanning primitives - - /** - * Returns true if the next token in this scanner's input can be - * interpreted as a boolean value using a case insensitive pattern - * created from the string "true|false". The scanner does not - * advance past the input that matched. - * - * @return true if and only if this scanner's next token is a valid - * boolean value - * @throws IllegalStateException if this scanner is closed - */ - public boolean hasNextBoolean() { - return hasNext(boolPattern()); - } - - /** - * Scans the next token of the input into a boolean value and returns - * that value. This method will throw <code>InputMismatchException</code> - * if the next token cannot be translated into a valid boolean value. - * If the match is successful, the scanner advances past the input that - * matched. - * - * @return the boolean scanned from the input - * @throws InputMismatchException if the next token is not a valid boolean - * @throws NoSuchElementException if input is exhausted - * @throws IllegalStateException if this scanner is closed - */ - public boolean nextBoolean() { - clearCaches(); - return Boolean.parseBoolean(next(boolPattern())); - } - - /** - * Returns true if the next token in this scanner's input can be - * interpreted as a byte value in the default radix using the - * {@link #nextByte} method. The scanner does not advance past any input. - * - * @return true if and only if this scanner's next token is a valid - * byte value - * @throws IllegalStateException if this scanner is closed - */ - public boolean hasNextByte() { - return hasNextByte(defaultRadix); - } - - /** - * Returns true if the next token in this scanner's input can be - * interpreted as a byte value in the specified radix using the - * {@link #nextByte} method. The scanner does not advance past any input. - * - * @param radix the radix used to interpret the token as a byte value - * @return true if and only if this scanner's next token is a valid - * byte value - * @throws IllegalStateException if this scanner is closed - */ - public boolean hasNextByte(int radix) { - setRadix(radix); - boolean result = hasNext(integerPattern()); - if (result) { // Cache it - try { - String s = (matcher.group(SIMPLE_GROUP_INDEX) == null) ? - processIntegerToken(hasNextResult) : - hasNextResult; - typeCache = Byte.parseByte(s, radix); - } catch (NumberFormatException nfe) { - result = false; - } - } - return result; - } - - /** - * Scans the next token of the input as a <tt>byte</tt>. - * - * <p> An invocation of this method of the form - * <tt>nextByte()</tt> behaves in exactly the same way as the - * invocation <tt>nextByte(radix)</tt>, where <code>radix</code> - * is the default radix of this scanner. - * - * @return the <tt>byte</tt> scanned from the input - * @throws InputMismatchException - * if the next token does not match the <i>Integer</i> - * regular expression, or is out of range - * @throws NoSuchElementException if input is exhausted - * @throws IllegalStateException if this scanner is closed - */ - public byte nextByte() { - return nextByte(defaultRadix); - } - - /** - * Scans the next token of the input as a <tt>byte</tt>. - * This method will throw <code>InputMismatchException</code> - * if the next token cannot be translated into a valid byte value as - * described below. If the translation is successful, the scanner advances - * past the input that matched. - * - * <p> If the next token matches the <a - * href="#Integer-regex"><i>Integer</i></a> regular expression defined - * above then the token is converted into a <tt>byte</tt> value as if by - * removing all locale specific prefixes, group separators, and locale - * specific suffixes, then mapping non-ASCII digits into ASCII - * digits via {@link Character#digit Character.digit}, prepending a - * negative sign (-) if the locale specific negative prefixes and suffixes - * were present, and passing the resulting string to - * {@link Byte#parseByte(String, int) Byte.parseByte} with the - * specified radix. - * - * @param radix the radix used to interpret the token as a byte value - * @return the <tt>byte</tt> scanned from the input - * @throws InputMismatchException - * if the next token does not match the <i>Integer</i> - * regular expression, or is out of range - * @throws NoSuchElementException if input is exhausted - * @throws IllegalStateException if this scanner is closed - */ - public byte nextByte(int radix) { - // Check cached result - if ((typeCache != null) && (typeCache instanceof Byte) - && this.radix == radix) { - byte val = ((Byte)typeCache).byteValue(); - useTypeCache(); - return val; - } - setRadix(radix); - clearCaches(); - // Search for next byte - try { - String s = next(integerPattern()); - if (matcher.group(SIMPLE_GROUP_INDEX) == null) - s = processIntegerToken(s); - return Byte.parseByte(s, radix); - } catch (NumberFormatException nfe) { - position = matcher.start(); // don't skip bad token - throw new InputMismatchException(nfe.getMessage()); - } - } - - /** - * Returns true if the next token in this scanner's input can be - * interpreted as a short value in the default radix using the - * {@link #nextShort} method. The scanner does not advance past any input. - * - * @return true if and only if this scanner's next token is a valid - * short value in the default radix - * @throws IllegalStateException if this scanner is closed - */ - public boolean hasNextShort() { - return hasNextShort(defaultRadix); - } - - /** - * Returns true if the next token in this scanner's input can be - * interpreted as a short value in the specified radix using the - * {@link #nextShort} method. The scanner does not advance past any input. - * - * @param radix the radix used to interpret the token as a short value - * @return true if and only if this scanner's next token is a valid - * short value in the specified radix - * @throws IllegalStateException if this scanner is closed - */ - public boolean hasNextShort(int radix) { - setRadix(radix); - boolean result = hasNext(integerPattern()); - if (result) { // Cache it - try { - String s = (matcher.group(SIMPLE_GROUP_INDEX) == null) ? - processIntegerToken(hasNextResult) : - hasNextResult; - typeCache = Short.parseShort(s, radix); - } catch (NumberFormatException nfe) { - result = false; - } - } - return result; - } - - /** - * Scans the next token of the input as a <tt>short</tt>. - * - * <p> An invocation of this method of the form - * <tt>nextShort()</tt> behaves in exactly the same way as the - * invocation <tt>nextShort(radix)</tt>, where <code>radix</code> - * is the default radix of this scanner. - * - * @return the <tt>short</tt> scanned from the input - * @throws InputMismatchException - * if the next token does not match the <i>Integer</i> - * regular expression, or is out of range - * @throws NoSuchElementException if input is exhausted - * @throws IllegalStateException if this scanner is closed - */ - public short nextShort() { - return nextShort(defaultRadix); - } - - /** - * Scans the next token of the input as a <tt>short</tt>. - * This method will throw <code>InputMismatchException</code> - * if the next token cannot be translated into a valid short value as - * described below. If the translation is successful, the scanner advances - * past the input that matched. - * - * <p> If the next token matches the <a - * href="#Integer-regex"><i>Integer</i></a> regular expression defined - * above then the token is converted into a <tt>short</tt> value as if by - * removing all locale specific prefixes, group separators, and locale - * specific suffixes, then mapping non-ASCII digits into ASCII - * digits via {@link Character#digit Character.digit}, prepending a - * negative sign (-) if the locale specific negative prefixes and suffixes - * were present, and passing the resulting string to - * {@link Short#parseShort(String, int) Short.parseShort} with the - * specified radix. - * - * @param radix the radix used to interpret the token as a short value - * @return the <tt>short</tt> scanned from the input - * @throws InputMismatchException - * if the next token does not match the <i>Integer</i> - * regular expression, or is out of range - * @throws NoSuchElementException if input is exhausted - * @throws IllegalStateException if this scanner is closed - */ - public short nextShort(int radix) { - // Check cached result - if ((typeCache != null) && (typeCache instanceof Short) - && this.radix == radix) { - short val = ((Short)typeCache).shortValue(); - useTypeCache(); - return val; - } - setRadix(radix); - clearCaches(); - // Search for next short - try { - String s = next(integerPattern()); - if (matcher.group(SIMPLE_GROUP_INDEX) == null) - s = processIntegerToken(s); - return Short.parseShort(s, radix); - } catch (NumberFormatException nfe) { - position = matcher.start(); // don't skip bad token - throw new InputMismatchException(nfe.getMessage()); - } - } - - /** - * Returns true if the next token in this scanner's input can be - * interpreted as an int value in the default radix using the - * {@link #nextInt} method. The scanner does not advance past any input. - * - * @return true if and only if this scanner's next token is a valid - * int value - * @throws IllegalStateException if this scanner is closed - */ - public boolean hasNextInt() { - return hasNextInt(defaultRadix); - } - - /** - * Returns true if the next token in this scanner's input can be - * interpreted as an int value in the specified radix using the - * {@link #nextInt} method. The scanner does not advance past any input. - * - * @param radix the radix used to interpret the token as an int value - * @return true if and only if this scanner's next token is a valid - * int value - * @throws IllegalStateException if this scanner is closed - */ - public boolean hasNextInt(int radix) { - setRadix(radix); - boolean result = hasNext(integerPattern()); - if (result) { // Cache it - try { - String s = (matcher.group(SIMPLE_GROUP_INDEX) == null) ? - processIntegerToken(hasNextResult) : - hasNextResult; - typeCache = Integer.parseInt(s, radix); - } catch (NumberFormatException nfe) { - result = false; - } - } - return result; - } - - /** - * The integer token must be stripped of prefixes, group separators, - * and suffixes, non ascii digits must be converted into ascii digits - * before parse will accept it. - */ - private String processIntegerToken(String token) { - String result = token.replaceAll(""+groupSeparator, ""); - boolean isNegative = false; - int preLen = negativePrefix.length(); - if ((preLen > 0) && result.startsWith(negativePrefix)) { - isNegative = true; - result = result.substring(preLen); - } - int sufLen = negativeSuffix.length(); - if ((sufLen > 0) && result.endsWith(negativeSuffix)) { - isNegative = true; - result = result.substring(result.length() - sufLen, - result.length()); - } - if (isNegative) - result = "-" + result; - return result; - } - - /** - * Scans the next token of the input as an <tt>int</tt>. - * - * <p> An invocation of this method of the form - * <tt>nextInt()</tt> behaves in exactly the same way as the - * invocation <tt>nextInt(radix)</tt>, where <code>radix</code> - * is the default radix of this scanner. - * - * @return the <tt>int</tt> scanned from the input - * @throws InputMismatchException - * if the next token does not match the <i>Integer</i> - * regular expression, or is out of range - * @throws NoSuchElementException if input is exhausted - * @throws IllegalStateException if this scanner is closed - */ - public int nextInt() { - return nextInt(defaultRadix); - } - - /** - * Scans the next token of the input as an <tt>int</tt>. - * This method will throw <code>InputMismatchException</code> - * if the next token cannot be translated into a valid int value as - * described below. If the translation is successful, the scanner advances - * past the input that matched. - * - * <p> If the next token matches the <a - * href="#Integer-regex"><i>Integer</i></a> regular expression defined - * above then the token is converted into an <tt>int</tt> value as if by - * removing all locale specific prefixes, group separators, and locale - * specific suffixes, then mapping non-ASCII digits into ASCII - * digits via {@link Character#digit Character.digit}, prepending a - * negative sign (-) if the locale specific negative prefixes and suffixes - * were present, and passing the resulting string to - * {@link Integer#parseInt(String, int) Integer.parseInt} with the - * specified radix. - * - * @param radix the radix used to interpret the token as an int value - * @return the <tt>int</tt> scanned from the input - * @throws InputMismatchException - * if the next token does not match the <i>Integer</i> - * regular expression, or is out of range - * @throws NoSuchElementException if input is exhausted - * @throws IllegalStateException if this scanner is closed - */ - public int nextInt(int radix) { - // Check cached result - if ((typeCache != null) && (typeCache instanceof Integer) - && this.radix == radix) { - int val = ((Integer)typeCache).intValue(); - useTypeCache(); - return val; - } - setRadix(radix); - clearCaches(); - // Search for next int - try { - String s = next(integerPattern()); - if (matcher.group(SIMPLE_GROUP_INDEX) == null) - s = processIntegerToken(s); - return Integer.parseInt(s, radix); - } catch (NumberFormatException nfe) { - position = matcher.start(); // don't skip bad token - throw new InputMismatchException(nfe.getMessage()); - } - } - - /** - * Returns true if the next token in this scanner's input can be - * interpreted as a long value in the default radix using the - * {@link #nextLong} method. The scanner does not advance past any input. - * - * @return true if and only if this scanner's next token is a valid - * long value - * @throws IllegalStateException if this scanner is closed - */ - public boolean hasNextLong() { - return hasNextLong(defaultRadix); - } - - /** - * Returns true if the next token in this scanner's input can be - * interpreted as a long value in the specified radix using the - * {@link #nextLong} method. The scanner does not advance past any input. - * - * @param radix the radix used to interpret the token as a long value - * @return true if and only if this scanner's next token is a valid - * long value - * @throws IllegalStateException if this scanner is closed - */ - public boolean hasNextLong(int radix) { - setRadix(radix); - boolean result = hasNext(integerPattern()); - if (result) { // Cache it - try { - String s = (matcher.group(SIMPLE_GROUP_INDEX) == null) ? - processIntegerToken(hasNextResult) : - hasNextResult; - typeCache = Long.parseLong(s, radix); - } catch (NumberFormatException nfe) { - result = false; - } - } - return result; - } - - /** - * Scans the next token of the input as a <tt>long</tt>. - * - * <p> An invocation of this method of the form - * <tt>nextLong()</tt> behaves in exactly the same way as the - * invocation <tt>nextLong(radix)</tt>, where <code>radix</code> - * is the default radix of this scanner. - * - * @return the <tt>long</tt> scanned from the input - * @throws InputMismatchException - * if the next token does not match the <i>Integer</i> - * regular expression, or is out of range - * @throws NoSuchElementException if input is exhausted - * @throws IllegalStateException if this scanner is closed - */ - public long nextLong() { - return nextLong(defaultRadix); - } - - /** - * Scans the next token of the input as a <tt>long</tt>. - * This method will throw <code>InputMismatchException</code> - * if the next token cannot be translated into a valid long value as - * described below. If the translation is successful, the scanner advances - * past the input that matched. - * - * <p> If the next token matches the <a - * href="#Integer-regex"><i>Integer</i></a> regular expression defined - * above then the token is converted into a <tt>long</tt> value as if by - * removing all locale specific prefixes, group separators, and locale - * specific suffixes, then mapping non-ASCII digits into ASCII - * digits via {@link Character#digit Character.digit}, prepending a - * negative sign (-) if the locale specific negative prefixes and suffixes - * were present, and passing the resulting string to - * {@link Long#parseLong(String, int) Long.parseLong} with the - * specified radix. - * - * @param radix the radix used to interpret the token as an int value - * @return the <tt>long</tt> scanned from the input - * @throws InputMismatchException - * if the next token does not match the <i>Integer</i> - * regular expression, or is out of range - * @throws NoSuchElementException if input is exhausted - * @throws IllegalStateException if this scanner is closed - */ - public long nextLong(int radix) { - // Check cached result - if ((typeCache != null) && (typeCache instanceof Long) - && this.radix == radix) { - long val = ((Long)typeCache).longValue(); - useTypeCache(); - return val; - } - setRadix(radix); - clearCaches(); - try { - String s = next(integerPattern()); - if (matcher.group(SIMPLE_GROUP_INDEX) == null) - s = processIntegerToken(s); - return Long.parseLong(s, radix); - } catch (NumberFormatException nfe) { - position = matcher.start(); // don't skip bad token - throw new InputMismatchException(nfe.getMessage()); - } - } - - /** - * The float token must be stripped of prefixes, group separators, - * and suffixes, non ascii digits must be converted into ascii digits - * before parseFloat will accept it. - * - * If there are non-ascii digits in the token these digits must - * be processed before the token is passed to parseFloat. - */ - private String processFloatToken(String token) { - String result = token.replaceAll(groupSeparator, ""); - if (!decimalSeparator.equals("\\.")) - result = result.replaceAll(decimalSeparator, "."); - boolean isNegative = false; - int preLen = negativePrefix.length(); - if ((preLen > 0) && result.startsWith(negativePrefix)) { - isNegative = true; - result = result.substring(preLen); - } - int sufLen = negativeSuffix.length(); - if ((sufLen > 0) && result.endsWith(negativeSuffix)) { - isNegative = true; - result = result.substring(result.length() - sufLen, - result.length()); - } - if (result.equals(nanString)) - result = "NaN"; - if (result.equals(infinityString)) - result = "Infinity"; - if (isNegative) - result = "-" + result; - - // Translate non-ASCII digits - Matcher m = NON_ASCII_DIGIT.matcher(result); - if (m.find()) { - StringBuilder inASCII = new StringBuilder(); - for (int i=0; i<result.length(); i++) { - char nextChar = result.charAt(i); - if (Character.isDigit(nextChar)) { - int d = Character.digit(nextChar, 10); - if (d != -1) - inASCII.append(d); - else - inASCII.append(nextChar); - } else { - inASCII.append(nextChar); - } - } - result = inASCII.toString(); - } - - return result; - } - - /** - * Returns true if the next token in this scanner's input can be - * interpreted as a float value using the {@link #nextFloat} - * method. The scanner does not advance past any input. - * - * @return true if and only if this scanner's next token is a valid - * float value - * @throws IllegalStateException if this scanner is closed - */ - public boolean hasNextFloat() { - setRadix(10); - boolean result = hasNext(floatPattern()); - if (result) { // Cache it - try { - String s = processFloatToken(hasNextResult); - typeCache = Float.valueOf(Float.parseFloat(s)); - } catch (NumberFormatException nfe) { - result = false; - } - } - return result; - } - - /** - * Scans the next token of the input as a <tt>float</tt>. - * This method will throw <code>InputMismatchException</code> - * if the next token cannot be translated into a valid float value as - * described below. If the translation is successful, the scanner advances - * past the input that matched. - * - * <p> If the next token matches the <a - * href="#Float-regex"><i>Float</i></a> regular expression defined above - * then the token is converted into a <tt>float</tt> value as if by - * removing all locale specific prefixes, group separators, and locale - * specific suffixes, then mapping non-ASCII digits into ASCII - * digits via {@link Character#digit Character.digit}, prepending a - * negative sign (-) if the locale specific negative prefixes and suffixes - * were present, and passing the resulting string to - * {@link Float#parseFloat Float.parseFloat}. If the token matches - * the localized NaN or infinity strings, then either "Nan" or "Infinity" - * is passed to {@link Float#parseFloat(String) Float.parseFloat} as - * appropriate. - * - * @return the <tt>float</tt> scanned from the input - * @throws InputMismatchException - * if the next token does not match the <i>Float</i> - * regular expression, or is out of range - * @throws NoSuchElementException if input is exhausted - * @throws IllegalStateException if this scanner is closed - */ - public float nextFloat() { - // Check cached result - if ((typeCache != null) && (typeCache instanceof Float)) { - float val = ((Float)typeCache).floatValue(); - useTypeCache(); - return val; - } - setRadix(10); - clearCaches(); - try { - return Float.parseFloat(processFloatToken(next(floatPattern()))); - } catch (NumberFormatException nfe) { - position = matcher.start(); // don't skip bad token - throw new InputMismatchException(nfe.getMessage()); - } - } - - /** - * Returns true if the next token in this scanner's input can be - * interpreted as a double value using the {@link #nextDouble} - * method. The scanner does not advance past any input. - * - * @return true if and only if this scanner's next token is a valid - * double value - * @throws IllegalStateException if this scanner is closed - */ - public boolean hasNextDouble() { - setRadix(10); - boolean result = hasNext(floatPattern()); - if (result) { // Cache it - try { - String s = processFloatToken(hasNextResult); - typeCache = Double.valueOf(Double.parseDouble(s)); - } catch (NumberFormatException nfe) { - result = false; - } - } - return result; - } - - /** - * Scans the next token of the input as a <tt>double</tt>. - * This method will throw <code>InputMismatchException</code> - * if the next token cannot be translated into a valid double value. - * If the translation is successful, the scanner advances past the input - * that matched. - * - * <p> If the next token matches the <a - * href="#Float-regex"><i>Float</i></a> regular expression defined above - * then the token is converted into a <tt>double</tt> value as if by - * removing all locale specific prefixes, group separators, and locale - * specific suffixes, then mapping non-ASCII digits into ASCII - * digits via {@link Character#digit Character.digit}, prepending a - * negative sign (-) if the locale specific negative prefixes and suffixes - * were present, and passing the resulting string to - * {@link Double#parseDouble Double.parseDouble}. If the token matches - * the localized NaN or infinity strings, then either "Nan" or "Infinity" - * is passed to {@link Double#parseDouble(String) Double.parseDouble} as - * appropriate. - * - * @return the <tt>double</tt> scanned from the input - * @throws InputMismatchException - * if the next token does not match the <i>Float</i> - * regular expression, or is out of range - * @throws NoSuchElementException if the input is exhausted - * @throws IllegalStateException if this scanner is closed - */ - public double nextDouble() { - // Check cached result - if ((typeCache != null) && (typeCache instanceof Double)) { - double val = ((Double)typeCache).doubleValue(); - useTypeCache(); - return val; - } - setRadix(10); - clearCaches(); - // Search for next float - try { - return Double.parseDouble(processFloatToken(next(floatPattern()))); - } catch (NumberFormatException nfe) { - position = matcher.start(); // don't skip bad token - throw new InputMismatchException(nfe.getMessage()); - } - } - - // Convenience methods for scanning multi precision numbers - - /** - * Returns true if the next token in this scanner's input can be - * interpreted as a <code>BigInteger</code> in the default radix using the - * {@link #nextBigInteger} method. The scanner does not advance past any - * input. - * - * @return true if and only if this scanner's next token is a valid - * <code>BigInteger</code> - * @throws IllegalStateException if this scanner is closed - */ - public boolean hasNextBigInteger() { - return hasNextBigInteger(defaultRadix); - } - - /** - * Returns true if the next token in this scanner's input can be - * interpreted as a <code>BigInteger</code> in the specified radix using - * the {@link #nextBigInteger} method. The scanner does not advance past - * any input. - * - * @param radix the radix used to interpret the token as an integer - * @return true if and only if this scanner's next token is a valid - * <code>BigInteger</code> - * @throws IllegalStateException if this scanner is closed - */ - public boolean hasNextBigInteger(int radix) { - setRadix(radix); - boolean result = hasNext(integerPattern()); - if (result) { // Cache it - try { - String s = (matcher.group(SIMPLE_GROUP_INDEX) == null) ? - processIntegerToken(hasNextResult) : - hasNextResult; - typeCache = new BigInteger(s, radix); - } catch (NumberFormatException nfe) { - result = false; - } - } - return result; - } - - /** - * Scans the next token of the input as a {@link java.math.BigInteger - * BigInteger}. - * - * <p> An invocation of this method of the form - * <tt>nextBigInteger()</tt> behaves in exactly the same way as the - * invocation <tt>nextBigInteger(radix)</tt>, where <code>radix</code> - * is the default radix of this scanner. - * - * @return the <tt>BigInteger</tt> scanned from the input - * @throws InputMismatchException - * if the next token does not match the <i>Integer</i> - * regular expression, or is out of range - * @throws NoSuchElementException if the input is exhausted - * @throws IllegalStateException if this scanner is closed - */ - public BigInteger nextBigInteger() { - return nextBigInteger(defaultRadix); - } - - /** - * Scans the next token of the input as a {@link java.math.BigInteger - * BigInteger}. - * - * <p> If the next token matches the <a - * href="#Integer-regex"><i>Integer</i></a> regular expression defined - * above then the token is converted into a <tt>BigInteger</tt> value as if - * by removing all group separators, mapping non-ASCII digits into ASCII - * digits via the {@link Character#digit Character.digit}, and passing the - * resulting string to the {@link - * java.math.BigInteger#BigInteger(java.lang.String) - * BigInteger(String, int)} constructor with the specified radix. - * - * @param radix the radix used to interpret the token - * @return the <tt>BigInteger</tt> scanned from the input - * @throws InputMismatchException - * if the next token does not match the <i>Integer</i> - * regular expression, or is out of range - * @throws NoSuchElementException if the input is exhausted - * @throws IllegalStateException if this scanner is closed - */ - public BigInteger nextBigInteger(int radix) { - // Check cached result - if ((typeCache != null) && (typeCache instanceof BigInteger) - && this.radix == radix) { - BigInteger val = (BigInteger)typeCache; - useTypeCache(); - return val; - } - setRadix(radix); - clearCaches(); - // Search for next int - try { - String s = next(integerPattern()); - if (matcher.group(SIMPLE_GROUP_INDEX) == null) - s = processIntegerToken(s); - return new BigInteger(s, radix); - } catch (NumberFormatException nfe) { - position = matcher.start(); // don't skip bad token - throw new InputMismatchException(nfe.getMessage()); - } - } - - /** - * Returns true if the next token in this scanner's input can be - * interpreted as a <code>BigDecimal</code> using the - * {@link #nextBigDecimal} method. The scanner does not advance past any - * input. - * - * @return true if and only if this scanner's next token is a valid - * <code>BigDecimal</code> - * @throws IllegalStateException if this scanner is closed - */ - public boolean hasNextBigDecimal() { - setRadix(10); - boolean result = hasNext(decimalPattern()); - if (result) { // Cache it - try { - String s = processFloatToken(hasNextResult); - typeCache = new BigDecimal(s); - } catch (NumberFormatException nfe) { - result = false; - } - } - return result; - } - - /** - * Scans the next token of the input as a {@link java.math.BigDecimal - * BigDecimal}. - * - * <p> If the next token matches the <a - * href="#Decimal-regex"><i>Decimal</i></a> regular expression defined - * above then the token is converted into a <tt>BigDecimal</tt> value as if - * by removing all group separators, mapping non-ASCII digits into ASCII - * digits via the {@link Character#digit Character.digit}, and passing the - * resulting string to the {@link - * java.math.BigDecimal#BigDecimal(java.lang.String) BigDecimal(String)} - * constructor. - * - * @return the <tt>BigDecimal</tt> scanned from the input - * @throws InputMismatchException - * if the next token does not match the <i>Decimal</i> - * regular expression, or is out of range - * @throws NoSuchElementException if the input is exhausted - * @throws IllegalStateException if this scanner is closed - */ - public BigDecimal nextBigDecimal() { - // Check cached result - if ((typeCache != null) && (typeCache instanceof BigDecimal)) { - BigDecimal val = (BigDecimal)typeCache; - useTypeCache(); - return val; - } - setRadix(10); - clearCaches(); - // Search for next float - try { - String s = processFloatToken(next(decimalPattern())); - return new BigDecimal(s); - } catch (NumberFormatException nfe) { - position = matcher.start(); // don't skip bad token - throw new InputMismatchException(nfe.getMessage()); - } - } - - /** - * Resets this scanner. - * - * <p> Resetting a scanner discards all of its explicit state - * information which may have been changed by invocations of {@link - * #useDelimiter}, {@link #useLocale}, or {@link #useRadix}. - * - * <p> An invocation of this method of the form - * <tt>scanner.reset()</tt> behaves in exactly the same way as the - * invocation - * - * <blockquote><pre> - * scanner.useDelimiter("\\p{javaWhitespace}+") - * .useLocale(Locale.getDefault()) - * .useRadix(10); - * </pre></blockquote> - * - * @return this scanner - * - * @since 1.6 - */ - public Scanner reset() { - delimPattern = WHITESPACE_PATTERN; - useLocale(Locale.getDefault()); - useRadix(10); - clearCaches(); - return this; - } -}
--- a/overlays/nio2/openjdk/jdk/src/share/classes/org/classpath/icedtea/java/util/concurrent/ScheduledThreadPoolExecutor.java Fri Feb 13 20:26:58 2009 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,1371 +0,0 @@ -/* - * 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -/* - * This file is available under and governed by the GNU General Public - * License version 2 only, as published by the Free Software Foundation. - * However, the following notice accompanied the original version of this - * file: - * - * Written by Doug Lea with assistance from members of JCP JSR-166 - * Expert Group and released to the public domain, as explained at - * http://creativecommons.org/licenses/publicdomain - */ - -package org.classpath.icedtea.java.util.concurrent; - -import java.util.*; - -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.Callable; -import java.util.concurrent.Delayed; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.FutureTask; -import java.util.concurrent.RejectedExecutionHandler; -import java.util.concurrent.RunnableScheduledFuture; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.ThreadPoolExecutor; - -import java.util.concurrent.atomic.*; -import java.util.concurrent.locks.*; - -import org.classpath.icedtea.misc.JavaUtilConcurrentThreadPoolExecutorAccess; -import org.classpath.icedtea.misc.SharedSecrets; - -/** - * A {@link ThreadPoolExecutor} that can additionally schedule - * commands to run after a given delay, or to execute - * periodically. This class is preferable to {@link java.util.Timer} - * when multiple worker threads are needed, or when the additional - * flexibility or capabilities of {@link ThreadPoolExecutor} (which - * this class extends) are required. - * - * <p>Delayed tasks execute no sooner than they are enabled, but - * without any real-time guarantees about when, after they are - * enabled, they will commence. Tasks scheduled for exactly the same - * execution time are enabled in first-in-first-out (FIFO) order of - * submission. - * - * <p>When a submitted task is cancelled before it is run, execution - * is suppressed. By default, such a cancelled task is not - * automatically removed from the work queue until its delay - * elapses. While this enables further inspection and monitoring, it - * may also cause unbounded retention of cancelled tasks. To avoid - * this, set {@link #setRemoveOnCancelPolicy} to {@code true}, which - * causes tasks to be immediately removed from the work queue at - * time of cancellation. - * - * <p>While this class inherits from {@link ThreadPoolExecutor}, a few - * of the inherited tuning methods are not useful for it. In - * particular, because it acts as a fixed-sized pool using - * {@code corePoolSize} threads and an unbounded queue, adjustments - * to {@code maximumPoolSize} have no useful effect. Additionally, it - * is almost never a good idea to set {@code corePoolSize} to zero or - * use {@code allowCoreThreadTimeOut} because this may leave the pool - * without threads to handle tasks once they become eligible to run. - * - * <p><b>Extension notes:</b> This class overrides the - * {@link ThreadPoolExecutor#execute execute} and - * {@link AbstractExecutorService#submit(Runnable) submit} - * methods to generate internal {@link ScheduledFuture} objects to - * control per-task delays and scheduling. To preserve - * functionality, any further overrides of these methods in - * subclasses must invoke superclass versions, which effectively - * disables additional task customization. However, this class - * provides alternative protected extension method - * {@code decorateTask} (one version each for {@code Runnable} and - * {@code Callable}) that can be used to customize the concrete task - * types used to execute commands entered via {@code execute}, - * {@code submit}, {@code schedule}, {@code scheduleAtFixedRate}, - * and {@code scheduleWithFixedDelay}. By default, a - * {@code ScheduledThreadPoolExecutor} uses a task type extending - * {@link FutureTask}. However, this may be modified or replaced using - * subclasses of the form: - * - * <pre> {@code - * public class CustomScheduledExecutor extends ScheduledThreadPoolExecutor { - * - * static class CustomTask<V> implements RunnableScheduledFuture<V> { ... } - * - * protected <V> RunnableScheduledFuture<V> decorateTask( - * Runnable r, RunnableScheduledFuture<V> task) { - * return new CustomTask<V>(r, task); - * } - * - * protected <V> RunnableScheduledFuture<V> decorateTask( - * Callable<V> c, RunnableScheduledFuture<V> task) { - * return new CustomTask<V>(c, task); - * } - * // ... add constructors, etc. - * }}</pre> - * - * @since 1.5 - * @author Doug Lea - */ -public class ScheduledThreadPoolExecutor - extends ThreadPoolExecutor - implements ScheduledExecutorService { - - /* - * This class specializes ThreadPoolExecutor implementation by - * - * 1. Using a custom task type, ScheduledFutureTask for - * tasks, even those that don't require scheduling (i.e., - * those submitted using ExecutorService execute, not - * ScheduledExecutorService methods) which are treated as - * delayed tasks with a delay of zero. - * - * 2. Using a custom queue (DelayedWorkQueue), a variant of - * unbounded DelayQueue. The lack of capacity constraint and - * the fact that corePoolSize and maximumPoolSize are - * effectively identical simplifies some execution mechanics - * (see delayedExecute) compared to ThreadPoolExecutor. - * - * 3. Supporting optional run-after-shutdown parameters, which - * leads to overrides of shutdown methods to remove and cancel - * tasks that should NOT be run after shutdown, as well as - * different recheck logic when task (re)submission overlaps - * with a shutdown. - * - * 4. Task decoration methods to allow interception and - * instrumentation, which are needed because subclasses cannot - * otherwise override submit methods to get this effect. These - * don't have any impact on pool control logic though. - */ - - /** - * False if should cancel/suppress periodic tasks on shutdown. - */ - private volatile boolean continueExistingPeriodicTasksAfterShutdown; - - /** - * False if should cancel non-periodic tasks on shutdown. - */ - private volatile boolean executeExistingDelayedTasksAfterShutdown = true; - - /** - * True if ScheduledFutureTask.cancel should remove from queue - */ - private volatile boolean removeOnCancel = false; - - /** - * Sequence number to break scheduling ties, and in turn to - * guarantee FIFO order among tied entries. - */ - private static final AtomicLong sequencer = new AtomicLong(0); - - /** - * Returns current nanosecond time. - */ - final long now() { - return System.nanoTime(); - } - - private class ScheduledFutureTask<V> - extends FutureTask<V> implements RunnableScheduledFuture<V> { - - /** Sequence number to break ties FIFO */ - private final long sequenceNumber; - - /** The time the task is enabled to execute in nanoTime units */ - private long time; - - /** - * Period in nanoseconds for repeating tasks. A positive - * value indicates fixed-rate execution. A negative value - * indicates fixed-delay execution. A value of 0 indicates a - * non-repeating task. - */ - private final long period; - - /** The actual task to be re-enqueued by reExecutePeriodic */ - RunnableScheduledFuture<V> outerTask = this; - - /** - * Index into delay queue, to support faster cancellation. - */ - int heapIndex; - - /** - * Creates a one-shot action with given nanoTime-based trigger time. - */ - ScheduledFutureTask(Runnable r, V result, long ns) { - super(r, result); - this.time = ns; - this.period = 0; - this.sequenceNumber = sequencer.getAndIncrement(); - } - - /** - * Creates a periodic action with given nano time and period. - */ - ScheduledFutureTask(Runnable r, V result, long ns, long period) { - super(r, result); - this.time = ns; - this.period = period; - this.sequenceNumber = sequencer.getAndIncrement(); - } - - /** - * Creates a one-shot action with given nanoTime-based trigger. - */ - ScheduledFutureTask(Callable<V> callable, long ns) { - super(callable); - this.time = ns; - this.period = 0; - this.sequenceNumber = sequencer.getAndIncrement(); - } - - public long getDelay(TimeUnit unit) { - return unit.convert(time - now(), TimeUnit.NANOSECONDS); - } - - public int compareTo(Delayed other) { - if (other == this) // compare zero ONLY if same object - return 0; - if (other instanceof ScheduledFutureTask) { - ScheduledFutureTask<?> x = (ScheduledFutureTask<?>)other; - long diff = time - x.time; - if (diff < 0) - return -1; - else if (diff > 0) - return 1; - else if (sequenceNumber < x.sequenceNumber) - return -1; - else - return 1; - } - long d = (getDelay(TimeUnit.NANOSECONDS) - - other.getDelay(TimeUnit.NANOSECONDS)); - return (d == 0) ? 0 : ((d < 0) ? -1 : 1); - } - - /** - * Returns true if this is a periodic (not a one-shot) action. - * - * @return true if periodic - */ - public boolean isPeriodic() { - return period != 0; - } - - /** - * Sets the next time to run for a periodic task. - */ - private void setNextRunTime() { - long p = period; - if (p > 0) - time += p; - else - time = triggerTime(-p); - } - - public boolean cancel(boolean mayInterruptIfRunning) { - boolean cancelled = super.cancel(mayInterruptIfRunning); - if (cancelled && removeOnCancel && heapIndex >= 0) - remove(this); - return cancelled; - } - - /** - * Overrides FutureTask version so as to reset/requeue if periodic. - */ - public void run() { - boolean periodic = isPeriodic(); - if (!canRunInCurrentRunState(periodic)) - cancel(false); - else if (!periodic) - ScheduledFutureTask.super.run(); - else if (ScheduledFutureTask.super.runAndReset()) { - setNextRunTime(); - reExecutePeriodic(outerTask); - } - } - } - - /** - * Returns true if can run a task given current run state - * and run-after-shutdown parameters. - * - * @param periodic true if this task periodic, false if delayed - */ - boolean canRunInCurrentRunState(boolean periodic) { - return isRunningOrShutdownSTPE(periodic ? - continueExistingPeriodicTasksAfterShutdown : - executeExistingDelayedTasksAfterShutdown); - } - - /** - * Main execution method for delayed or periodic tasks. If pool - * is shut down, rejects the task. Otherwise adds task to queue - * and starts a thread, if necessary, to run it. (We cannot - * prestart the thread to run the task because the task (probably) - * shouldn't be run yet,) If the pool is shut down while the task - * is being added, cancel and remove it if required by state and - * run-after-shutdown parameters. - * - * @param task the task - */ - private void delayedExecute(RunnableScheduledFuture<?> task) { - if (isShutdown()) - rejectSTPE(task); - else { - super.getQueue().add(task); - if (isShutdown() && - !canRunInCurrentRunState(task.isPeriodic()) && - remove(task)) - task.cancel(false); - else - prestartCoreThread(); - } - } - - /** - * Requeues a periodic task unless current run state precludes it. - * Same idea as delayedExecute except drops task rather than rejecting. - * - * @param task the task - */ - void reExecutePeriodic(RunnableScheduledFuture<?> task) { - if (canRunInCurrentRunState(true)) { - super.getQueue().add(task); - if (!canRunInCurrentRunState(true) && remove(task)) - task.cancel(false); - else - prestartCoreThread(); - } - } - - /** - * Cancels and clears the queue of all tasks that should not be run - * due to shutdown policy. Invoked within super.shutdown. - */ - void onShutdown() { - BlockingQueue<Runnable> q = super.getQueue(); - boolean keepDelayed = - getExecuteExistingDelayedTasksAfterShutdownPolicy(); - boolean keepPeriodic = - getContinueExistingPeriodicTasksAfterShutdownPolicy(); - if (!keepDelayed && !keepPeriodic) - q.clear(); - else { - // Traverse snapshot to avoid iterator exceptions - for (Object e : q.toArray()) { - if (e instanceof RunnableScheduledFuture) { - RunnableScheduledFuture<?> t = - (RunnableScheduledFuture<?>)e; - if ((t.isPeriodic() ? !keepPeriodic : !keepDelayed) || - t.isCancelled()) { // also remove if already cancelled - if (q.remove(t)) - t.cancel(false); - } - } - } - } - tryTerminateSTPE(); - } - - /** - * Modifies or replaces the task used to execute a runnable. - * This method can be used to override the concrete - * class used for managing internal tasks. - * The default implementation simply returns the given task. - * - * @param runnable the submitted Runnable - * @param task the task created to execute the runnable - * @return a task that can execute the runnable - * @since 1.6 - */ - protected <V> RunnableScheduledFuture<V> decorateTask( - Runnable runnable, RunnableScheduledFuture<V> task) { - return task; - } - - /** - * Modifies or replaces the task used to execute a callable. - * This method can be used to override the concrete - * class used for managing internal tasks. - * The default implementation simply returns the given task. - * - * @param callable the submitted Callable - * @param task the task created to execute the callable - * @return a task that can execute the callable - * @since 1.6 - */ - protected <V> RunnableScheduledFuture<V> decorateTask( - Callable<V> callable, RunnableScheduledFuture<V> task) { - return task; - } - - /** - * Creates a new {@code ScheduledThreadPoolExecutor} with the - * given core pool size. - * - * @param corePoolSize the number of threads to keep in the pool, even - * if they are idle, unless {@code allowCoreThreadTimeOut} is set - * @throws IllegalArgumentException if {@code corePoolSize < 0} - */ - public ScheduledThreadPoolExecutor(int corePoolSize) { - super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS, - new DelayedWorkQueue()); - } - - /** - * Creates a new {@code ScheduledThreadPoolExecutor} with the - * given initial parameters. - * - * @param corePoolSize the number of threads to keep in the pool, even - * if they are idle, unless {@code allowCoreThreadTimeOut} is set - * @param threadFactory the factory to use when the executor - * creates a new thread - * @throws IllegalArgumentException if {@code corePoolSize < 0} - * @throws NullPointerException if {@code threadFactory} is null - */ - public ScheduledThreadPoolExecutor(int corePoolSize, - ThreadFactory threadFactory) { - super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS, - new DelayedWorkQueue(), threadFactory); - } - - /** - * Creates a new ScheduledThreadPoolExecutor with the given - * initial parameters. - * - * @param corePoolSize the number of threads to keep in the pool, even - * if they are idle, unless {@code allowCoreThreadTimeOut} is set - * @param handler the handler to use when execution is blocked - * because the thread bounds and queue capacities are reached - * @throws IllegalArgumentException if {@code corePoolSize < 0} - * @throws NullPointerException if {@code handler} is null - */ - public ScheduledThreadPoolExecutor(int corePoolSize, - RejectedExecutionHandler handler) { - super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS, - new DelayedWorkQueue(), handler); - } - - /** - * Creates a new ScheduledThreadPoolExecutor with the given - * initial parameters. - * - * @param corePoolSize the number of threads to keep in the pool, even - * if they are idle, unless {@code allowCoreThreadTimeOut} is set - * @param threadFactory the factory to use when the executor - * creates a new thread - * @param handler the handler to use when execution is blocked - * because the thread bounds and queue capacities are reached - * @throws IllegalArgumentException if {@code corePoolSize < 0} - * @throws NullPointerException if {@code threadFactory} or - * {@code handler} is null - */ - public ScheduledThreadPoolExecutor(int corePoolSize, - ThreadFactory threadFactory, - RejectedExecutionHandler handler) { - super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS, - new DelayedWorkQueue(), threadFactory, handler); - } - - /** - * Returns the trigger time of a delayed action. - */ - private long triggerTime(long delay, TimeUnit unit) { - return triggerTime(unit.toNanos((delay < 0) ? 0 : delay)); - } - - /** - * Returns the trigger time of a delayed action. - */ - long triggerTime(long delay) { - return now() + - ((delay < (Long.MAX_VALUE >> 1)) ? delay : overflowFree(delay)); - } - - /** - * Constrains the values of all delays in the queue to be within - * Long.MAX_VALUE of each other, to avoid overflow in compareTo. - * This may occur if a task is eligible to be dequeued, but has - * not yet been, while some other task is added with a delay of - * Long.MAX_VALUE. - */ - private long overflowFree(long delay) { - Delayed head = (Delayed) super.getQueue().peek(); - if (head != null) { - long headDelay = head.getDelay(TimeUnit.NANOSECONDS); - if (headDelay < 0 && (delay - headDelay < 0)) - delay = Long.MAX_VALUE + headDelay; - } - return delay; - } - - /** - * @throws RejectedExecutionException {@inheritDoc} - * @throws NullPointerException {@inheritDoc} - */ - public ScheduledFuture<?> schedule(Runnable command, - long delay, - TimeUnit unit) { - if (command == null || unit == null) - throw new NullPointerException(); - RunnableScheduledFuture<?> t = decorateTask(command, - new ScheduledFutureTask<Void>(command, null, - triggerTime(delay, unit))); - delayedExecute(t); - return t; - } - - /** - * @throws RejectedExecutionException {@inheritDoc} - * @throws NullPointerException {@inheritDoc} - */ - public <V> ScheduledFuture<V> schedule(Callable<V> callable, - long delay, - TimeUnit unit) { - if (callable == null || unit == null) - throw new NullPointerException(); - RunnableScheduledFuture<V> t = decorateTask(callable, - new ScheduledFutureTask<V>(callable, - triggerTime(delay, unit))); - delayedExecute(t); - return t; - } - - /** - * @throws RejectedExecutionException {@inheritDoc} - * @throws NullPointerException {@inheritDoc} - * @throws IllegalArgumentException {@inheritDoc} - */ - public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, - long initialDelay, - long period, - TimeUnit unit) { - if (command == null || unit == null) - throw new NullPointerException(); - if (period <= 0) - throw new IllegalArgumentException(); - ScheduledFutureTask<Void> sft = - new ScheduledFutureTask<Void>(command, - null, - triggerTime(initialDelay, unit), - unit.toNanos(period)); - RunnableScheduledFuture<Void> t = decorateTask(command, sft); - sft.outerTask = t; - delayedExecute(t); - return t; - } - - /** - * @throws RejectedExecutionException {@inheritDoc} - * @throws NullPointerException {@inheritDoc} - * @throws IllegalArgumentException {@inheritDoc} - */ - public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, - long initialDelay, - long delay, - TimeUnit unit) { - if (command == null || unit == null) - throw new NullPointerException(); - if (delay <= 0) - throw new IllegalArgumentException(); - ScheduledFutureTask<Void> sft = - new ScheduledFutureTask<Void>(command, - null, - triggerTime(initialDelay, unit), - unit.toNanos(-delay)); - RunnableScheduledFuture<Void> t = decorateTask(command, sft); - sft.outerTask = t; - delayedExecute(t); - return t; - } - - /** - * Executes {@code command} with zero required delay. - * This has effect equivalent to - * {@link #schedule(Runnable,long,TimeUnit) schedule(command, 0, anyUnit)}. - * Note that inspections of the queue and of the list returned by - * {@code shutdownNow} will access the zero-delayed - * {@link ScheduledFuture}, not the {@code command} itself. - * - * <p>A consequence of the use of {@code ScheduledFuture} objects is - * that {@link ThreadPoolExecutor#afterExecute afterExecute} is always - * called with a null second {@code Throwable} argument, even if the - * {@code command} terminated abruptly. Instead, the {@code Throwable} - * thrown by such a task can be obtained via {@link Future#get}. - * - * @throws RejectedExecutionException at discretion of - * {@code RejectedExecutionHandler}, if the task - * cannot be accepted for execution because the - * executor has been shut down - * @throws NullPointerException {@inheritDoc} - */ - public void execute(Runnable command) { - schedule(command, 0, TimeUnit.NANOSECONDS); - } - - // Override AbstractExecutorService methods - - /** - * @throws RejectedExecutionException {@inheritDoc} - * @throws NullPointerException {@inheritDoc} - */ - public Future<?> submit(Runnable task) { - return schedule(task, 0, TimeUnit.NANOSECONDS); - } - - /** - * @throws RejectedExecutionException {@inheritDoc} - * @throws NullPointerException {@inheritDoc} - */ - public <T> Future<T> submit(Runnable task, T result) { - return schedule(Executors.callable(task, result), - 0, TimeUnit.NANOSECONDS); - } - - /** - * @throws RejectedExecutionException {@inheritDoc} - * @throws NullPointerException {@inheritDoc} - */ - public <T> Future<T> submit(Callable<T> task) { - return schedule(task, 0, TimeUnit.NANOSECONDS); - } - - /** - * Sets the policy on whether to continue executing existing - * periodic tasks even when this executor has been {@code shutdown}. - * In this case, these tasks will only terminate upon - * {@code shutdownNow} or after setting the policy to - * {@code false} when already shutdown. - * This value is by default {@code false}. - * - * @param value if {@code true}, continue after shutdown, else don't. - * @see #getContinueExistingPeriodicTasksAfterShutdownPolicy - */ - public void setContinueExistingPeriodicTasksAfterShutdownPolicy(boolean value) { - continueExistingPeriodicTasksAfterShutdown = value; - if (!value && isShutdown()) - onShutdown(); - } - - /** - * Gets the policy on whether to continue executing existing - * periodic tasks even when this executor has been {@code shutdown}. - * In this case, these tasks will only terminate upon - * {@code shutdownNow} or after setting the policy to - * {@code false} when already shutdown. - * This value is by default {@code false}. - * - * @return {@code true} if will continue after shutdown - * @see #setContinueExistingPeriodicTasksAfterShutdownPolicy - */ - public boolean getContinueExistingPeriodicTasksAfterShutdownPolicy() { - return continueExistingPeriodicTasksAfterShutdown; - } - - /** - * Sets the policy on whether to execute existing delayed - * tasks even when this executor has been {@code shutdown}. - * In this case, these tasks will only terminate upon - * {@code shutdownNow}, or after setting the policy to - * {@code false} when already shutdown. - * This value is by default {@code true}. - * - * @param value if {@code true}, execute after shutdown, else don't. - * @see #getExecuteExistingDelayedTasksAfterShutdownPolicy - */ - public void setExecuteExistingDelayedTasksAfterShutdownPolicy(boolean value) { - executeExistingDelayedTasksAfterShutdown = value; - if (!value && isShutdown()) - onShutdown(); - } - - /** - * Gets the policy on whether to execute existing delayed - * tasks even when this executor has been {@code shutdown}. - * In this case, these tasks will only terminate upon - * {@code shutdownNow}, or after setting the policy to - * {@code false} when already shutdown. - * This value is by default {@code true}. - * - * @return {@code true} if will execute after shutdown - * @see #setExecuteExistingDelayedTasksAfterShutdownPolicy - */ - public boolean getExecuteExistingDelayedTasksAfterShutdownPolicy() { - return executeExistingDelayedTasksAfterShutdown; - } - - /** - * Sets the policy on whether cancelled tasks should be immediately - * removed from the work queue at time of cancellation. This value is - * by default {@code false}. - * - * @param value if {@code true}, remove on cancellation, else don't - * @see #getRemoveOnCancelPolicy - * @since 1.7 - */ - public void setRemoveOnCancelPolicy(boolean value) { - removeOnCancel = value; - } - - /** - * Gets the policy on whether cancelled tasks should be immediately - * removed from the work queue at time of cancellation. This value is - * by default {@code false}. - * - * @return {@code true} if cancelled tasks are immediately removed - * from the queue - * @see #setRemoveOnCancelPolicy - * @since 1.7 - */ - public boolean getRemoveOnCancelPolicy() { - return removeOnCancel; - } - - /** - * Initiates an orderly shutdown in which previously submitted - * tasks are executed, but no new tasks will be accepted. - * Invocation has no additional effect if already shut down. - * - * <p>This method does not wait for previously submitted tasks to - * complete execution. Use {@link #awaitTermination awaitTermination} - * to do that. - * - * <p>If the {@code ExecuteExistingDelayedTasksAfterShutdownPolicy} - * has been set {@code false}, existing delayed tasks whose delays - * have not yet elapsed are cancelled. And unless the {@code - * ContinueExistingPeriodicTasksAfterShutdownPolicy} has been set - * {@code true}, future executions of existing periodic tasks will - * be cancelled. - * - * @throws SecurityException {@inheritDoc} - */ - public void shutdown() { - super.shutdown(); - } - - /** - * Attempts to stop all actively executing tasks, halts the - * processing of waiting tasks, and returns a list of the tasks - * that were awaiting execution. - * - * <p>This method does not wait for actively executing tasks to - * terminate. Use {@link #awaitTermination awaitTermination} to - * do that. - * - * <p>There are no guarantees beyond best-effort attempts to stop - * processing actively executing tasks. This implementation - * cancels tasks via {@link Thread#interrupt}, so any task that - * fails to respond to interrupts may never terminate. - * - * @return list of tasks that never commenced execution. - * Each element of this list is a {@link ScheduledFuture}, - * including those tasks submitted using {@code execute}, - * which are for scheduling purposes used as the basis of a - * zero-delay {@code ScheduledFuture}. - * @throws SecurityException {@inheritDoc} - */ - public List<Runnable> shutdownNow() { - return super.shutdownNow(); - } - - /** - * Returns the task queue used by this executor. Each element of - * this queue is a {@link ScheduledFuture}, including those - * tasks submitted using {@code execute} which are for scheduling - * purposes used as the basis of a zero-delay - * {@code ScheduledFuture}. Iteration over this queue is - * <em>not</em> guaranteed to traverse tasks in the order in - * which they will execute. - * - * @return the task queue - */ - public BlockingQueue<Runnable> getQueue() { - return super.getQueue(); - } - - /** - * Specialized delay queue. To mesh with TPE declarations, this - * class must be declared as a BlockingQueue<Runnable> even though - * it can only hold RunnableScheduledFutures. - */ - static class DelayedWorkQueue extends AbstractQueue<Runnable> - implements BlockingQueue<Runnable> { - - /* - * A DelayedWorkQueue is based on a heap-based data structure - * like those in DelayQueue and PriorityQueue, except that - * every ScheduledFutureTask also records its index into the - * heap array. This eliminates the need to find a task upon - * cancellation, greatly speeding up removal (down from O(n) - * to O(log n)), and reducing garbage retention that would - * otherwise occur by waiting for the element to rise to top - * before clearing. But because the queue may also hold - * RunnableScheduledFutures that are not ScheduledFutureTasks, - * we are not guaranteed to have such indices available, in - * which case we fall back to linear search. (We expect that - * most tasks will not be decorated, and that the faster cases - * will be much more common.) - * - * All heap operations must record index changes -- mainly - * within siftUp and siftDown. Upon removal, a task's - * heapIndex is set to -1. Note that ScheduledFutureTasks can - * appear at most once in the queue (this need not be true for - * other kinds of tasks or work queues), so are uniquely - * identified by heapIndex. - */ - - private static final int INITIAL_CAPACITY = 16; - private RunnableScheduledFuture[] queue = - new RunnableScheduledFuture[INITIAL_CAPACITY]; - private final ReentrantLock lock = new ReentrantLock(); - private int size = 0; - - /** - * Thread designated to wait for the task at the head of the - * queue. This variant of the Leader-Follower pattern - * (http://www.cs.wustl.edu/~schmidt/POSA/POSA2/) serves to - * minimize unnecessary timed waiting. When a thread becomes - * the leader, it waits only for the next delay to elapse, but - * other threads await indefinitely. The leader thread must - * signal some other thread before returning from take() or - * poll(...), unless some other thread becomes leader in the - * interim. Whenever the head of the queue is replaced with a - * task with an earlier expiration time, the leader field is - * invalidated by being reset to null, and some waiting - * thread, but not necessarily the current leader, is - * signalled. So waiting threads must be prepared to acquire - * and lose leadership while waiting. - */ - private Thread leader = null; - - /** - * Condition signalled when a newer task becomes available at the - * head of the queue or a new thread may need to become leader. - */ - private final Condition available = lock.newCondition(); - - /** - * Set f's heapIndex if it is a ScheduledFutureTask. - */ - private void setIndex(RunnableScheduledFuture f, int idx) { - if (f instanceof ScheduledFutureTask) - ((ScheduledFutureTask)f).heapIndex = idx; - } - - /** - * Sift element added at bottom up to its heap-ordered spot. - * Call only when holding lock. - */ - private void siftUp(int k, RunnableScheduledFuture key) { - while (k > 0) { - int parent = (k - 1) >>> 1; - RunnableScheduledFuture e = queue[parent]; - if (key.compareTo(e) >= 0) - break; - queue[k] = e; - setIndex(e, k); - k = parent; - } - queue[k] = key; - setIndex(key, k); - } - - /** - * Sift element added at top down to its heap-ordered spot. - * Call only when holding lock. - */ - private void siftDown(int k, RunnableScheduledFuture key) { - int half = size >>> 1; - while (k < half) { - int child = (k << 1) + 1; - RunnableScheduledFuture c = queue[child]; - int right = child + 1; - if (right < size && c.compareTo(queue[right]) > 0) - c = queue[child = right]; - if (key.compareTo(c) <= 0) - break; - queue[k] = c; - setIndex(c, k); - k = child; - } - queue[k] = key; - setIndex(key, k); - } - - /** - * Resize the heap array. Call only when holding lock. - */ - private void grow() { - int oldCapacity = queue.length; - int newCapacity = oldCapacity + (oldCapacity >> 1); // grow 50% - if (newCapacity < 0) // overflow - newCapacity = Integer.MAX_VALUE; - queue = Arrays.copyOf(queue, newCapacity); - } - - /** - * Find index of given object, or -1 if absent - */ - private int indexOf(Object x) { - if (x != null) { - if (x instanceof ScheduledFutureTask) { - int i = ((ScheduledFutureTask) x).heapIndex; - // Sanity check; x could conceivably be a - // ScheduledFutureTask from some other pool. - if (i >= 0 && i < size && queue[i] == x) - return i; - } else { - for (int i = 0; i < size; i++) - if (x.equals(queue[i])) - return i; - } - } - return -1; - } - - public boolean contains(Object x) { - final ReentrantLock lock = this.lock; - lock.lock(); - try { - return indexOf(x) != -1; - } finally { - lock.unlock(); - } - } - - public boolean remove(Object x) { - final ReentrantLock lock = this.lock; - lock.lock(); - try { - int i = indexOf(x); - if (i < 0) - return false; - - setIndex(queue[i], -1); - int s = --size; - RunnableScheduledFuture replacement = queue[s]; - queue[s] = null; - if (s != i) { - siftDown(i, replacement); - if (queue[i] == replacement) - siftUp(i, replacement); - } - return true; - } finally { - lock.unlock(); - } - } - - public int size() { - final ReentrantLock lock = this.lock; - lock.lock(); - try { - return size; - } finally { - lock.unlock(); - } - } - - public boolean isEmpty() { - return size() == 0; - } - - public int remainingCapacity() { - return Integer.MAX_VALUE; - } - - public RunnableScheduledFuture peek() { - final ReentrantLock lock = this.lock; - lock.lock(); - try { - return queue[0]; - } finally { - lock.unlock(); - } - } - - public boolean offer(Runnable x) { - if (x == null) - throw new NullPointerException(); - RunnableScheduledFuture e = (RunnableScheduledFuture)x; - final ReentrantLock lock = this.lock; - lock.lock(); - try { - int i = size; - if (i >= queue.length) - grow(); - size = i + 1; - if (i == 0) { - queue[0] = e; - setIndex(e, 0); - } else { - siftUp(i, e); - } - if (queue[0] == e) { - leader = null; - available.signal(); - } - } finally { - lock.unlock(); - } - return true; - } - - public void put(Runnable e) { - offer(e); - } - - public boolean add(Runnable e) { - return offer(e); - } - - public boolean offer(Runnable e, long timeout, TimeUnit unit) { - return offer(e); - } - - /** - * Performs common bookkeeping for poll and take: Replaces - * first element with last and sifts it down. Call only when - * holding lock. - * @param f the task to remove and return - */ - private RunnableScheduledFuture finishPoll(RunnableScheduledFuture f) { - int s = --size; - RunnableScheduledFuture x = queue[s]; - queue[s] = null; - if (s != 0) - siftDown(0, x); - setIndex(f, -1); - return f; - } - - public RunnableScheduledFuture poll() { - final ReentrantLock lock = this.lock; - lock.lock(); - try { - RunnableScheduledFuture first = queue[0]; - if (first == null || first.getDelay(TimeUnit.NANOSECONDS) > 0) - return null; - else - return finishPoll(first); - } finally { - lock.unlock(); - } - } - - public RunnableScheduledFuture take() throws InterruptedException { - final ReentrantLock lock = this.lock; - lock.lockInterruptibly(); - try { - for (;;) { - RunnableScheduledFuture first = queue[0]; - if (first == null) - available.await(); - else { - long delay = first.getDelay(TimeUnit.NANOSECONDS); - if (delay <= 0) - return finishPoll(first); - else if (leader != null) - available.await(); - else { - Thread thisThread = Thread.currentThread(); - leader = thisThread; - try { - available.awaitNanos(delay); - } finally { - if (leader == thisThread) - leader = null; - } - } - } - } - } finally { - if (leader == null && queue[0] != null) - available.signal(); - lock.unlock(); - } - } - - public RunnableScheduledFuture poll(long timeout, TimeUnit unit) - throws InterruptedException { - long nanos = unit.toNanos(timeout); - final ReentrantLock lock = this.lock; - lock.lockInterruptibly(); - try { - for (;;) { - RunnableScheduledFuture first = queue[0]; - if (first == null) { - if (nanos <= 0) - return null; - else - nanos = available.awaitNanos(nanos); - } else { - long delay = first.getDelay(TimeUnit.NANOSECONDS); - if (delay <= 0) - return finishPoll(first); - if (nanos <= 0) - return null; - if (nanos < delay || leader != null) - nanos = available.awaitNanos(nanos); - else { - Thread thisThread = Thread.currentThread(); - leader = thisThread; - try { - long timeLeft = available.awaitNanos(delay); - nanos -= delay - timeLeft; - } finally { - if (leader == thisThread) - leader = null; - } - } - } - } - } finally { - if (leader == null && queue[0] != null) - available.signal(); - lock.unlock(); - } - } - - public void clear() { - final ReentrantLock lock = this.lock; - lock.lock(); - try { - for (int i = 0; i < size; i++) { - RunnableScheduledFuture t = queue[i]; - if (t != null) { - queue[i] = null; - setIndex(t, -1); - } - } - size = 0; - } finally { - lock.unlock(); - } - } - - /** - * Return and remove first element only if it is expired. - * Used only by drainTo. Call only when holding lock. - */ - private RunnableScheduledFuture pollExpired() { - RunnableScheduledFuture first = queue[0]; - if (first == null || first.getDelay(TimeUnit.NANOSECONDS) > 0) - return null; - return finishPoll(first); - } - - public int drainTo(Collection<? super Runnable> c) { - if (c == null) - throw new NullPointerException(); - if (c == this) - throw new IllegalArgumentException(); - final ReentrantLock lock = this.lock; - lock.lock(); - try { - RunnableScheduledFuture first; - int n = 0; - while ((first = pollExpired()) != null) { - c.add(first); - ++n; - } - return n; - } finally { - lock.unlock(); - } - } - - public int drainTo(Collection<? super Runnable> c, int maxElements) { - if (c == null) - throw new NullPointerException(); - if (c == this) - throw new IllegalArgumentException(); - if (maxElements <= 0) - return 0; - final ReentrantLock lock = this.lock; - lock.lock(); - try { - RunnableScheduledFuture first; - int n = 0; - while (n < maxElements && (first = pollExpired()) != null) { - c.add(first); - ++n; - } - return n; - } finally { - lock.unlock(); - } - } - - public Object[] toArray() { - final ReentrantLock lock = this.lock; - lock.lock(); - try { - return Arrays.copyOf(queue, size, Object[].class); - } finally { - lock.unlock(); - } - } - - @SuppressWarnings("unchecked") - public <T> T[] toArray(T[] a) { - final ReentrantLock lock = this.lock; - lock.lock(); - try { - if (a.length < size) - return (T[]) Arrays.copyOf(queue, size, a.getClass()); - System.arraycopy(queue, 0, a, 0, size); - if (a.length > size) - a[size] = null; - return a; - } finally { - lock.unlock(); - } - } - - public Iterator<Runnable> iterator() { - return new Itr(Arrays.copyOf(queue, size)); - } - - /** - * Snapshot iterator that works off copy of underlying q array. - */ - private class Itr implements Iterator<Runnable> { - final RunnableScheduledFuture[] array; - int cursor = 0; // index of next element to return - int lastRet = -1; // index of last element, or -1 if no such - - Itr(RunnableScheduledFuture[] array) { - this.array = array; - } - - public boolean hasNext() { - return cursor < array.length; - } - - public Runnable next() { - if (cursor >= array.length) - throw new NoSuchElementException(); - lastRet = cursor; - return array[cursor++]; - } - - public void remove() { - if (lastRet < 0) - throw new IllegalStateException(); - DelayedWorkQueue.this.remove(array[lastRet]); - lastRet = -1; - } - } - } - - // Duplicated package-private methods from ThreadPoolExecutor - - private static final int COUNT_BITS = Integer.SIZE - 3; - private static final int CAPACITY = (1 << COUNT_BITS) - 1; - private static final int RUNNING = -1 << COUNT_BITS; - private static final int SHUTDOWN = 0 << COUNT_BITS; - private static final int TIDYING = 2 << COUNT_BITS; - private static final int TERMINATED = 3 << COUNT_BITS; - - // Packing and unpacking ctl - private static int runStateOf(int c) { return c & ~CAPACITY; } - private static int workerCountOf(int c) { return c & CAPACITY; } - private static int ctlOf(int rs, int wc) { return rs | wc; } - - private static final boolean ONLY_ONE = true; - - /** - * Transitions to TERMINATED state if either (SHUTDOWN and pool - * and queue empty) or (STOP and pool empty). If otherwise - * eligible to terminate but workerCount is nonzero, interrupts an - * idle worker to ensure that shutdown signals propagate. This - * method must be called following any action that might make - * termination possible -- reducing worker count or removing tasks - * from the queue during shutdown. The method is non-private to - * allow access from ScheduledThreadPoolExecutor. - */ - private final void tryTerminateSTPE() { - final JavaUtilConcurrentThreadPoolExecutorAccess juctpea = - SharedSecrets.getJavaUtilConcurrentThreadPoolExecutorAccess(); - final AtomicInteger ctl = juctpea.getCtl(this); - for (;;) { - int c = ctl.get(); - if (isRunning(c) || - runStateAtLeast(c, TIDYING) || - (runStateOf(c) == SHUTDOWN && ! juctpea.isWorkQueueEmpty(this))) - return; - if (workerCountOf(c) != 0) { // Eligible to terminate - juctpea.interruptIdleWorkers(this, ONLY_ONE); - return; - } - - juctpea.lockMainLock(this); - try { - if (ctl.compareAndSet(c, ctlOf(TIDYING, 0))) { - try { - terminated(); - } finally { - ctl.set(ctlOf(TERMINATED, 0)); - juctpea.signalAll(this); - } - return; - } - } finally { - juctpea.unlockMainLock(this); - } - // else retry on failed CAS - } - } - - /** - * State check needed by ScheduledThreadPoolExecutor to - * enable running tasks during shutdown. - * - * @param shutdownOK true if should return true if SHUTDOWN - */ - private final boolean isRunningOrShutdownSTPE(boolean shutdownOK) { - int rs = runStateOf(SharedSecrets.getJavaUtilConcurrentThreadPoolExecutorAccess().getCtl(this).get()); - return rs == RUNNING || (rs == SHUTDOWN && shutdownOK); - } - - /** - * Invokes the rejected execution handler for the given command. - * Package-protected for use by ScheduledThreadPoolExecutor. - */ - private final void rejectSTPE(Runnable command) { - SharedSecrets.getJavaUtilConcurrentThreadPoolExecutorAccess().rejectedExecution(command, this); - } - - private static boolean isRunning(int c) { - return c < SHUTDOWN; - } - - private static boolean runStateAtLeast(int c, int s) { - return c >= s; - } - -}