OpenJDK / jdk / hs
changeset 2092:b86b8d6d48bd
Merge
author | duke |
---|---|
date | Wed, 05 Jul 2017 16:48:18 +0200 |
parents | 7faffd237305 47cbb94e1da2 |
children | 5da0e6b9f4f1 |
files | jdk/src/solaris/classes/sun/nio/ch/FileDispatcher.java jdk/src/solaris/native/sun/nio/ch/FileDispatcher.c jdk/src/windows/classes/sun/nio/ch/FileDispatcher.java jdk/src/windows/native/sun/nio/ch/FileDispatcher.c |
diffstat | 423 files changed, 76046 insertions(+), 2216 deletions(-) [+] |
line wrap: on
line diff
--- a/.hgtags-top-repo Fri Feb 27 10:54:11 2009 -0800 +++ b/.hgtags-top-repo Wed Jul 05 16:48:18 2017 +0200 @@ -23,3 +23,4 @@ e8a2a4d187773a62f3309b0fa265c13425bc2258 jdk7-b46 d7744e86dedc21a8ecf6bdb73eb191b8eaf5b0da jdk7-b47 4ae9f4bfdb98f65bd957e3fe72471b320150b38e jdk7-b48 +aee93a8992d2389121eb610c00a86196f3e2b9b0 jdk7-b49
--- a/corba/.hgtags Fri Feb 27 10:54:11 2009 -0800 +++ b/corba/.hgtags Wed Jul 05 16:48:18 2017 +0200 @@ -23,3 +23,4 @@ 1691dbfc08f8ee3f4e23a1ff30cdff920718696c jdk7-b46 167ad0164301f318b069a947e1c9c07ed667748a jdk7-b47 0be222241fd405e48915647facfaa176621b39b9 jdk7-b48 +d70978bc64bc7a04be7797ab0dcd9b7b1b3a6bff jdk7-b49
--- a/hotspot/.hgtags Fri Feb 27 10:54:11 2009 -0800 +++ b/hotspot/.hgtags Wed Jul 05 16:48:18 2017 +0200 @@ -23,3 +23,4 @@ 16bb38eeda35b46268eefa4c1f829eb086e0ca46 jdk7-b46 fcb923bad68e2b10380a030ea83a723f4dc3d4d6 jdk7-b47 bcb33806d186561c781992e5f4d8a90bb033f9f0 jdk7-b48 +8b22ccb5aba2c6c11bddf6488a7bb7ef5b4bf2be jdk7-b49
--- a/jaxp/.hgtags Fri Feb 27 10:54:11 2009 -0800 +++ b/jaxp/.hgtags Wed Jul 05 16:48:18 2017 +0200 @@ -23,3 +23,4 @@ b2271877894af809b7703767fe8d4e38591a02a2 jdk7-b46 d711ad1954b294957737ea386cfd4d3c05028a36 jdk7-b47 39de90eb4822cafaacc69edd67ab5547e55ae920 jdk7-b48 +5c1f24531903573c1830775432276da567243f9c jdk7-b49
--- a/jaxws/.hgtags Fri Feb 27 10:54:11 2009 -0800 +++ b/jaxws/.hgtags Wed Jul 05 16:48:18 2017 +0200 @@ -23,3 +23,4 @@ af4a3eeb7812a5d09a241c50b51b3c648a9d45c1 jdk7-b46 223011570edbd49bb0fe51cdeb2089f95d305267 jdk7-b47 01e5dd31d0c10a2db3d50db346905d2d3db45e88 jdk7-b48 +18ca864890f3d4ed942ecbffb78c936a57759921 jdk7-b49
--- a/jdk/.hgtags Fri Feb 27 10:54:11 2009 -0800 +++ b/jdk/.hgtags Wed Jul 05 16:48:18 2017 +0200 @@ -23,3 +23,4 @@ 4b03e27a44090d1f646af28dc58f9ead827e24c7 jdk7-b46 b4ac413b1f129eeef0acab3f31081c1b7dfe3b27 jdk7-b47 5fbd9ea7def17186693b6f7099b5d0dc73903eee jdk7-b48 +8311105ea7a3db7bcbcb2b696459127c7f2297a4 jdk7-b49
--- a/jdk/make/common/Defs-windows.gmk Fri Feb 27 10:54:11 2009 -0800 +++ b/jdk/make/common/Defs-windows.gmk Wed Jul 05 16:48:18 2017 +0200 @@ -398,16 +398,7 @@ # SA will never be supported here. INCLUDE_SA = false else - # Hopefully, SA will be supported here one of these days, - # and these will be changed to true. Until then, - # to build SA on windows, do a control build with - # BUILD_WIN_SA=1 - # on the make command. - ifdef BUILD_WIN_SA - INCLUDE_SA = true - else - INCLUDE_SA = false - endif + INCLUDE_SA = true endif # Settings for the VERSIONINFO tap on windows.
--- a/jdk/make/docs/CORE_PKGS.gmk Fri Feb 27 10:54:11 2009 -0800 +++ b/jdk/make/docs/CORE_PKGS.gmk Wed Jul 05 16:48:18 2017 +0200 @@ -1,5 +1,5 @@ # -# Copyright 2001-2008 Sun Microsystems, Inc. All Rights Reserved. +# Copyright 2001-2009 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 @@ -110,6 +110,9 @@ java.nio.channels.spi \ java.nio.charset \ java.nio.charset.spi \ + java.nio.file \ + java.nio.file.attribute \ + java.nio.file.spi \ java.rmi \ java.rmi.activation \ java.rmi.dgc \
--- a/jdk/make/docs/NON_CORE_PKGS.gmk Fri Feb 27 10:54:11 2009 -0800 +++ b/jdk/make/docs/NON_CORE_PKGS.gmk Wed Jul 05 16:48:18 2017 +0200 @@ -1,5 +1,5 @@ # -# Copyright 2002-2008 Sun Microsystems, Inc. All Rights Reserved. +# Copyright 2002-2009 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 @@ -65,6 +65,8 @@ HTTPSERVER_PKGS = com.sun.net.httpserver \ com.sun.net.httpserver.spi +NIO_PKGS = com.sun.nio.file + DOCLETAPI_PKGS = com.sun.javadoc TAGLETAPI_FILE = com/sun/tools/doclets/Taglet.java @@ -92,6 +94,7 @@ $(MGMT_PKGS) \ $(JAAS_PKGS) \ $(JGSS_PKGS) \ + $(NIO_PKGS) \ $(OLD_JSSE_PKGS) \ $(HTTPSERVER_PKGS) \ $(SMARTCARDIO_PKGS) \
--- a/jdk/make/java/nio/Exportedfiles.gmk Fri Feb 27 10:54:11 2009 -0800 +++ b/jdk/make/java/nio/Exportedfiles.gmk Wed Jul 05 16:48:18 2017 +0200 @@ -1,5 +1,5 @@ # -# Copyright 2000-2005 Sun Microsystems, Inc. All Rights Reserved. +# Copyright 2000-2009 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 @@ -33,7 +33,7 @@ sun/nio/ch/DatagramChannelImpl.java \ sun/nio/ch/DatagramDispatcher.java \ sun/nio/ch/FileChannelImpl.java \ - sun/nio/ch/FileDispatcher.java \ + sun/nio/ch/FileDispatcherImpl.java \ sun/nio/ch/FileKey.java \ sun/nio/ch/FileLockImpl.java \ sun/nio/ch/IOStatus.java \
--- a/jdk/make/java/nio/FILES_c.gmk Fri Feb 27 10:54:11 2009 -0800 +++ b/jdk/make/java/nio/FILES_c.gmk Wed Jul 05 16:48:18 2017 +0200 @@ -1,5 +1,5 @@ # -# Copyright 2000-2005 Sun Microsystems, Inc. All Rights Reserved. +# Copyright 2000-2009 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 @@ -27,7 +27,7 @@ DatagramChannelImpl.c \ DatagramDispatcher.c \ FileChannelImpl.c \ - FileDispatcher.c \ + FileDispatcherImpl.c \ FileKey.c \ IOUtil.c \ MappedByteBuffer.c \
--- a/jdk/make/java/nio/FILES_java.gmk Fri Feb 27 10:54:11 2009 -0800 +++ b/jdk/make/java/nio/FILES_java.gmk Wed Jul 05 16:48:18 2017 +0200 @@ -1,5 +1,5 @@ # -# Copyright 2000-2008 Sun Microsystems, Inc. All Rights Reserved. +# Copyright 2000-2009 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 @@ -31,19 +31,29 @@ java/nio/MappedByteBuffer.java \ java/nio/StringCharBuffer.java \ \ + java/nio/channels/AsynchronousByteChannel.java \ + java/nio/channels/AsynchronousChannel.java \ + java/nio/channels/AsynchronousChannelGroup.java \ + java/nio/channels/AsynchronousDatagramChannel.java \ + java/nio/channels/AsynchronousFileChannel.java \ + java/nio/channels/AsynchronousServerSocketChannel.java \ + java/nio/channels/AsynchronousSocketChannel.java \ java/nio/channels/ByteChannel.java \ java/nio/channels/Channel.java \ java/nio/channels/Channels.java \ + java/nio/channels/CompletionHandler.java \ java/nio/channels/DatagramChannel.java \ java/nio/channels/FileChannel.java \ java/nio/channels/FileLock.java \ java/nio/channels/GatheringByteChannel.java \ java/nio/channels/InterruptibleChannel.java \ + java/nio/channels/Pipe.java \ java/nio/channels/MembershipKey.java \ java/nio/channels/MulticastChannel.java \ java/nio/channels/NetworkChannel.java \ java/nio/channels/ReadableByteChannel.java \ java/nio/channels/ScatteringByteChannel.java \ + java/nio/channels/SeekableByteChannel.java \ java/nio/channels/SelectableChannel.java \ java/nio/channels/Selector.java \ java/nio/channels/SelectionKey.java \ @@ -55,6 +65,7 @@ java/nio/channels/spi/AbstractSelectableChannel.java \ java/nio/channels/spi/AbstractSelectionKey.java \ java/nio/channels/spi/AbstractSelector.java \ + java/nio/channels/spi/AsynchronousChannelProvider.java \ java/nio/channels/spi/SelectorProvider.java \ \ java/nio/charset/Charset.java \ @@ -66,21 +77,117 @@ \ java/nio/charset/spi/CharsetProvider.java \ \ + java/nio/file/AccessDeniedException.java \ + java/nio/file/AccessMode.java \ + java/nio/file/AtomicMoveNotSupportedException.java \ + java/nio/file/ClosedDirectoryStreamException.java \ + java/nio/file/ClosedFileSystemException.java \ + java/nio/file/ClosedWatchServiceException.java \ + java/nio/file/CopyOption.java \ + java/nio/file/DirectoryNotEmptyException.java \ + java/nio/file/DirectoryStream.java \ + java/nio/file/DirectoryStreamFilters.java \ + java/nio/file/FileAction.java \ + java/nio/file/FileAlreadyExistsException.java \ + java/nio/file/FileRef.java \ + java/nio/file/FileStore.java \ + java/nio/file/FileSystem.java \ + java/nio/file/FileSystemAlreadyExistsException.java \ + java/nio/file/FileSystemException.java \ + java/nio/file/FileSystemNotFoundException.java \ + java/nio/file/FileSystems.java \ + java/nio/file/FileTreeWalker.java \ + java/nio/file/FileVisitOption.java \ + java/nio/file/FileVisitResult.java \ + java/nio/file/FileVisitor.java \ + java/nio/file/Files.java \ + java/nio/file/InvalidPathException.java \ + java/nio/file/LinkOption.java \ + java/nio/file/LinkPermission.java \ + java/nio/file/NoSuchFileException.java \ + java/nio/file/NotDirectoryException.java \ + java/nio/file/NotLinkException.java \ + java/nio/file/OpenOption.java \ + java/nio/file/Path.java \ + java/nio/file/PathMatcher.java \ + java/nio/file/Paths.java \ + java/nio/file/ProviderMismatchException.java \ + java/nio/file/ProviderNotFoundException.java \ + java/nio/file/ReadOnlyFileSystemException.java \ + java/nio/file/SecureDirectoryStream.java \ + java/nio/file/SimpleFileVisitor.java \ + java/nio/file/StandardCopyOption.java \ + java/nio/file/StandardOpenOption.java \ + java/nio/file/StandardWatchEventKind.java \ + java/nio/file/WatchEvent.java \ + java/nio/file/WatchKey.java \ + java/nio/file/WatchService.java \ + java/nio/file/Watchable.java \ + \ + java/nio/file/attribute/AclEntry.java \ + java/nio/file/attribute/AclEntryFlag.java \ + java/nio/file/attribute/AclEntryPermission.java \ + java/nio/file/attribute/AclEntryType.java \ + java/nio/file/attribute/AclFileAttributeView.java \ + java/nio/file/attribute/AttributeView.java \ + java/nio/file/attribute/Attributes.java \ + java/nio/file/attribute/BasicFileAttributeView.java \ + java/nio/file/attribute/BasicFileAttributes.java \ + java/nio/file/attribute/DosFileAttributeView.java \ + java/nio/file/attribute/DosFileAttributes.java \ + java/nio/file/attribute/FileAttribute.java \ + java/nio/file/attribute/FileAttributeView.java \ + java/nio/file/attribute/FileOwnerAttributeView.java \ + java/nio/file/attribute/FileStoreAttributeView.java \ + java/nio/file/attribute/FileStoreSpaceAttributeView.java \ + java/nio/file/attribute/FileStoreSpaceAttributes.java \ + java/nio/file/attribute/GroupPrincipal.java \ + java/nio/file/attribute/UserDefinedFileAttributeView.java \ + java/nio/file/attribute/PosixFileAttributeView.java \ + java/nio/file/attribute/PosixFileAttributes.java \ + java/nio/file/attribute/PosixFilePermission.java \ + java/nio/file/attribute/PosixFilePermissions.java \ + java/nio/file/attribute/UserPrincipal.java \ + java/nio/file/attribute/UserPrincipalLookupService.java \ + java/nio/file/attribute/UserPrincipalNotFoundException.java \ + \ + java/nio/file/spi/AbstractPath.java \ + java/nio/file/spi/FileSystemProvider.java \ + java/nio/file/spi/FileTypeDetector.java \ + \ + com/sun/nio/file/ExtendedCopyOption.java \ + com/sun/nio/file/ExtendedOpenOption.java \ + com/sun/nio/file/ExtendedWatchEventModifier.java \ + com/sun/nio/file/SensitivityWatchEventModifier.java \ + \ sun/nio/ByteBuffered.java \ \ + sun/nio/ch/AbstractFuture.java \ sun/nio/ch/AbstractPollArrayWrapper.java \ sun/nio/ch/AllocatedNativeObject.java \ + sun/nio/ch/AsynchronousChannelGroupImpl.java \ + sun/nio/ch/AsynchronousFileChannelImpl.java \ + sun/nio/ch/AsynchronousServerSocketChannelImpl.java \ + sun/nio/ch/AsynchronousSocketChannelImpl.java \ + sun/nio/ch/Cancellable.java \ sun/nio/ch/ChannelInputStream.java \ + sun/nio/ch/CompletedFuture.java \ sun/nio/ch/DatagramChannelImpl.java \ sun/nio/ch/DatagramDispatcher.java \ sun/nio/ch/DatagramSocketAdaptor.java \ + sun/nio/ch/DefaultAsynchronousChannelProvider.java \ sun/nio/ch/DefaultSelectorProvider.java \ sun/nio/ch/DirectBuffer.java \ sun/nio/ch/ExtendedSocketOption.java \ sun/nio/ch/FileChannelImpl.java \ sun/nio/ch/FileDispatcher.java \ + sun/nio/ch/FileDispatcherImpl.java \ sun/nio/ch/FileKey.java \ + sun/nio/ch/FileLockImpl.java \ + sun/nio/ch/FileLockTable.java \ + sun/nio/ch/Groupable.java \ sun/nio/ch/Interruptible.java \ + sun/nio/ch/Invoker.java \ sun/nio/ch/IOUtil.java \ sun/nio/ch/IOStatus.java \ sun/nio/ch/IOVecWrapper.java \ @@ -92,6 +199,7 @@ sun/nio/ch/NativeThreadSet.java \ sun/nio/ch/Net.java \ sun/nio/ch/OptionKey.java \ + sun/nio/ch/PendingFuture.java \ sun/nio/ch/PipeImpl.java \ sun/nio/ch/PollArrayWrapper.java \ sun/nio/ch/Reflect.java \ @@ -101,12 +209,14 @@ sun/nio/ch/SelChImpl.java \ sun/nio/ch/ServerSocketAdaptor.java \ sun/nio/ch/ServerSocketChannelImpl.java \ + sun/nio/ch/SimpleAsynchronousDatagramChannelImpl.java \ sun/nio/ch/SinkChannelImpl.java \ sun/nio/ch/SocketAdaptor.java \ sun/nio/ch/SocketChannelImpl.java \ sun/nio/ch/SocketDispatcher.java \ sun/nio/ch/SocketOptionRegistry.java \ sun/nio/ch/SourceChannelImpl.java \ + sun/nio/ch/ThreadPool.java \ sun/nio/ch/Util.java \ \ sun/nio/cs/AbstractCharsetProvider.java \ @@ -134,6 +244,25 @@ sun/nio/cs/UTF_32LE_BOM.java \ sun/nio/cs/UTF_32Coder.java \ \ + sun/nio/fs/AbstractAclFileAttributeView.java \ + sun/nio/fs/AbstractBasicFileAttributeView.java \ + sun/nio/fs/AbstractFileStoreSpaceAttributeView.java \ + sun/nio/fs/AbstractFileTypeDetector.java \ + sun/nio/fs/AbstractPoller.java \ + sun/nio/fs/AbstractUserDefinedFileAttributeView.java \ + sun/nio/fs/AbstractWatchKey.java \ + sun/nio/fs/AbstractWatchService.java \ + sun/nio/fs/BasicFileAttributesHolder.java \ + sun/nio/fs/Cancellable.java \ + sun/nio/fs/DefaultFileSystemProvider.java \ + sun/nio/fs/DefaultFileTypeDetector.java \ + sun/nio/fs/FileOwnerAttributeViewImpl.java \ + sun/nio/fs/Globs.java \ + sun/nio/fs/MimeType.java \ + sun/nio/fs/NativeBuffer.java \ + sun/nio/fs/NativeBuffers.java \ + sun/nio/fs/Reflect.java \ + \ java/net/DatagramSocket.java \ java/net/DatagramSocketImpl.java \ java/net/PlainSocketImpl.java \ @@ -244,24 +373,31 @@ java/nio/InvalidMarkException.java \ java/nio/ReadOnlyBufferException.java \ \ + java/nio/channels/AcceptPendingException.java \ java/nio/channels/AlreadyBoundException.java \ java/nio/channels/AlreadyConnectedException.java \ java/nio/channels/AsynchronousCloseException.java \ + java/nio/channels/CancelledKeyException.java \ java/nio/channels/ClosedByInterruptException.java \ java/nio/channels/ClosedChannelException.java \ java/nio/channels/ClosedSelectorException.java \ java/nio/channels/ConnectionPendingException.java \ java/nio/channels/FileLockInterruptionException.java \ java/nio/channels/IllegalBlockingModeException.java \ + java/nio/channels/IllegalChannelGroupException.java \ java/nio/channels/IllegalSelectorException.java \ + java/nio/channels/InterruptedByTimeoutException.java \ java/nio/channels/NoConnectionPendingException.java \ java/nio/channels/NonReadableChannelException.java \ java/nio/channels/NonWritableChannelException.java \ java/nio/channels/NotYetBoundException.java \ java/nio/channels/NotYetConnectedException.java \ java/nio/channels/OverlappingFileLockException.java \ + java/nio/channels/ReadPendingException.java \ + java/nio/channels/ShutdownChannelGroupException.java \ java/nio/channels/UnresolvedAddressException.java \ java/nio/channels/UnsupportedAddressTypeException.java \ + java/nio/channels/WritePendingException.java \ \ java/nio/charset/CharacterCodingException.java \ java/nio/charset/IllegalCharsetNameException.java \
--- a/jdk/make/java/nio/Makefile Fri Feb 27 10:54:11 2009 -0800 +++ b/jdk/make/java/nio/Makefile Wed Jul 05 16:48:18 2017 +0200 @@ -1,5 +1,5 @@ # -# Copyright 2000-2008 Sun Microsystems, Inc. All Rights Reserved. +# Copyright 2000-2009 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 @@ -56,56 +56,214 @@ sun/nio/ch/DevPollSelectorProvider.java \ sun/nio/ch/InheritedChannel.java \ sun/nio/ch/PollSelectorProvider.java \ - sun/nio/ch/PollSelectorImpl.java + sun/nio/ch/PollSelectorImpl.java \ + sun/nio/ch/Port.java \ + sun/nio/ch/SimpleAsynchronousFileChannelImpl.java \ + sun/nio/ch/SolarisAsynchronousChannelProvider.java \ + sun/nio/ch/SolarisEventPort.java \ + sun/nio/ch/UnixAsynchronousServerSocketChannelImpl.java \ + sun/nio/ch/UnixAsynchronousSocketChannelImpl.java \ + \ + sun/nio/fs/GnomeFileTypeDetector.java \ + sun/nio/fs/PollingWatchService.java \ + sun/nio/fs/SolarisAclFileAttributeView.java \ + sun/nio/fs/SolarisFileStore.java \ + sun/nio/fs/SolarisFileSystem.java \ + sun/nio/fs/SolarisFileSystemProvider.java \ + sun/nio/fs/SolarisUserDefinedFileAttributeView.java \ + sun/nio/fs/SolarisNativeDispatcher.java \ + sun/nio/fs/SolarisWatchService.java \ + sun/nio/fs/UnixChannelFactory.java \ + sun/nio/fs/UnixCopyFile.java \ + sun/nio/fs/UnixDirectoryStream.java \ + sun/nio/fs/UnixException.java \ + sun/nio/fs/UnixFileAttributeViews.java \ + sun/nio/fs/UnixFileAttributes.java \ + sun/nio/fs/UnixFileKey.java \ + sun/nio/fs/UnixFileModeAttribute.java \ + sun/nio/fs/UnixFileStore.java \ + sun/nio/fs/UnixFileStoreAttributes.java \ + sun/nio/fs/UnixFileSystem.java \ + sun/nio/fs/UnixFileSystemProvider.java \ + sun/nio/fs/UnixMountEntry.java \ + sun/nio/fs/UnixNativeDispatcher.java \ + sun/nio/fs/UnixPath.java \ + sun/nio/fs/UnixSecureDirectoryStream.java \ + sun/nio/fs/UnixUriUtils.java \ + sun/nio/fs/UnixUserPrincipals.java FILES_c += \ DevPollArrayWrapper.c \ InheritedChannel.c \ NativeThread.c \ - PollArrayWrapper.c + PollArrayWrapper.c \ + SolarisEventPort.c \ + UnixAsynchronousServerSocketChannelImpl.c \ + UnixAsynchronousSocketChannelImpl.c \ + \ + GnomeFileTypeDetector.c \ + SolarisNativeDispatcher.c \ + SolarisWatchService.c \ + UnixCopyFile.c \ + UnixNativeDispatcher.c FILES_export += \ sun/nio/ch/DevPollArrayWrapper.java \ sun/nio/ch/InheritedChannel.java \ - sun/nio/ch/NativeThread.java + sun/nio/ch/NativeThread.java \ + sun/nio/ch/SolarisEventPort.java \ + sun/nio/ch/UnixAsynchronousServerSocketChannelImpl.java \ + sun/nio/ch/UnixAsynchronousSocketChannelImpl.java \ + \ + sun/nio/fs/GnomeFileTypeDetector.java \ + sun/nio/fs/SolarisNativeDispatcher.java \ + sun/nio/fs/SolarisWatchService.java \ + sun/nio/fs/UnixCopyFile.java \ + sun/nio/fs/UnixNativeDispatcher.java + +FILES_gen += \ + sun/nio/fs/SolarisConstants.java \ + sun/nio/fs/UnixConstants.java endif # PLATFORM = solaris ifeq ($(PLATFORM), windows) FILES_java += \ + sun/nio/ch/Iocp.java \ + sun/nio/ch/PendingIoCache.java \ + sun/nio/ch/WindowsAsynchronousChannelProvider.java \ + sun/nio/ch/WindowsAsynchronousFileChannelImpl.java \ + sun/nio/ch/WindowsAsynchronousServerSocketChannelImpl.java \ + sun/nio/ch/WindowsAsynchronousSocketChannelImpl.java \ sun/nio/ch/WindowsSelectorImpl.java \ - sun/nio/ch/WindowsSelectorProvider.java + sun/nio/ch/WindowsSelectorProvider.java \ + \ + sun/nio/fs/RegistryFileTypeDetector.java \ + sun/nio/fs/WindowsAclFileAttributeView.java \ + sun/nio/fs/WindowsChannelFactory.java \ + sun/nio/fs/WindowsConstants.java \ + sun/nio/fs/WindowsDirectoryStream.java \ + sun/nio/fs/WindowsException.java \ + sun/nio/fs/WindowsFileAttributeViews.java \ + sun/nio/fs/WindowsFileAttributes.java \ + sun/nio/fs/WindowsFileCopy.java \ + sun/nio/fs/WindowsFileStore.java \ + sun/nio/fs/WindowsFileSystem.java \ + sun/nio/fs/WindowsFileSystemProvider.java \ + sun/nio/fs/WindowsLinkSupport.java \ + sun/nio/fs/WindowsUserDefinedFileAttributeView.java \ + sun/nio/fs/WindowsNativeDispatcher.java \ + sun/nio/fs/WindowsPath.java \ + sun/nio/fs/WindowsPathParser.java \ + sun/nio/fs/WindowsPathType.java \ + sun/nio/fs/WindowsSecurity.java \ + sun/nio/fs/WindowsSecurityDescriptor.java \ + sun/nio/fs/WindowsUriSupport.java \ + sun/nio/fs/WindowsUserPrincipals.java \ + sun/nio/fs/WindowsWatchService.java FILES_c += \ + Iocp.c \ + RegistryFileTypeDetector.c \ + WindowsAsynchronousFileChannelImpl.c \ + WindowsAsynchronousServerSocketChannelImpl.c \ + WindowsAsynchronousSocketChannelImpl.c \ + WindowsNativeDispatcher.c \ WindowsSelectorImpl.c FILES_export += \ - sun/nio/ch/WindowsSelectorImpl.java + sun/nio/ch/Iocp.java \ + sun/nio/ch/WindowsAsynchronousFileChannelImpl.java \ + sun/nio/ch/WindowsAsynchronousServerSocketChannelImpl.java \ + sun/nio/ch/WindowsAsynchronousSocketChannelImpl.java \ + sun/nio/ch/WindowsSelectorImpl.java \ + sun/nio/fs/WindowsNativeDispatcher.java \ + sun/nio/fs/RegistryFileTypeDetector.java endif # PLATFORM = windows ifeq ($(PLATFORM), linux) FILES_java += \ sun/nio/ch/AbstractPollSelectorImpl.java \ + sun/nio/ch/EPoll.java \ sun/nio/ch/EPollArrayWrapper.java \ + sun/nio/ch/EPollPort.java \ sun/nio/ch/EPollSelectorProvider.java \ sun/nio/ch/EPollSelectorImpl.java \ sun/nio/ch/InheritedChannel.java \ + sun/nio/ch/LinuxAsynchronousChannelProvider.java \ sun/nio/ch/PollSelectorProvider.java \ - sun/nio/ch/PollSelectorImpl.java + sun/nio/ch/PollSelectorImpl.java \ + sun/nio/ch/Port.java \ + sun/nio/ch/SimpleAsynchronousFileChannelImpl.java \ + sun/nio/ch/UnixAsynchronousServerSocketChannelImpl.java \ + sun/nio/ch/UnixAsynchronousSocketChannelImpl.java \ + \ + sun/nio/fs/GnomeFileTypeDetector.java \ + sun/nio/fs/LinuxDosFileAttributeView.java \ + sun/nio/fs/LinuxFileStore.java \ + sun/nio/fs/LinuxFileSystem.java \ + sun/nio/fs/LinuxFileSystemProvider.java \ + sun/nio/fs/LinuxUserDefinedFileAttributeView.java \ + sun/nio/fs/LinuxNativeDispatcher.java \ + sun/nio/fs/LinuxWatchService.java \ + sun/nio/fs/PollingWatchService.java \ + sun/nio/fs/UnixChannelFactory.java \ + sun/nio/fs/UnixCopyFile.java \ + sun/nio/fs/UnixDirectoryStream.java \ + sun/nio/fs/UnixException.java \ + sun/nio/fs/UnixFileAttributeViews.java \ + sun/nio/fs/UnixFileAttributes.java \ + sun/nio/fs/UnixFileKey.java \ + sun/nio/fs/UnixFileModeAttribute.java \ + sun/nio/fs/UnixFileStore.java \ + sun/nio/fs/UnixFileStoreAttributes.java \ + sun/nio/fs/UnixFileSystem.java \ + sun/nio/fs/UnixFileSystemProvider.java \ + sun/nio/fs/UnixMountEntry.java \ + sun/nio/fs/UnixNativeDispatcher.java \ + sun/nio/fs/UnixPath.java \ + sun/nio/fs/UnixSecureDirectoryStream.java \ + sun/nio/fs/UnixUriUtils.java \ + sun/nio/fs/UnixUserPrincipals.java FILES_c += \ + EPoll.c \ EPollArrayWrapper.c \ + EPollPort.c \ InheritedChannel.c \ NativeThread.c \ - PollArrayWrapper.c + PollArrayWrapper.c \ + UnixAsynchronousServerSocketChannelImpl.c \ + UnixAsynchronousSocketChannelImpl.c \ + \ + GnomeFileTypeDetector.c \ + LinuxNativeDispatcher.c \ + LinuxWatchService.c \ + UnixCopyFile.c \ + UnixNativeDispatcher.c FILES_export += \ + sun/nio/ch/EPoll.java \ sun/nio/ch/EPollArrayWrapper.java \ + sun/nio/ch/EPollPort.java \ sun/nio/ch/InheritedChannel.java \ - sun/nio/ch/NativeThread.java + sun/nio/ch/NativeThread.java \ + sun/nio/ch/UnixAsynchronousServerSocketChannelImpl.java \ + sun/nio/ch/UnixAsynchronousSocketChannelImpl.java \ + \ + sun/nio/fs/GnomeFileTypeDetector.java \ + sun/nio/fs/LinuxNativeDispatcher.java \ + sun/nio/fs/LinuxWatchService.java \ + sun/nio/fs/UnixCopyFile.java \ + sun/nio/fs/UnixNativeDispatcher.java + +FILES_gen += \ + sun/nio/fs/UnixConstants.java endif # PLATFORM = linux +# # Find platform-specific C source files # +vpath %.c $(PLATFORM_SRC)/native/sun/nio/fs vpath %.c $(PLATFORM_SRC)/native/sun/nio/ch vpath %.c $(SHARE_SRC)/native/sun/nio/ch @@ -175,12 +333,14 @@ CS_SRC=$(NIO_SRC)/charset SCH_SRC=$(SNIO_SRC)/ch SCS_SRC=$(SNIO_SRC)/cs +SFS_SRC=$(SNIO_SRC)/fs BUF_GEN=$(NIO_GEN) CH_GEN=$(NIO_GEN)/channels CS_GEN=$(NIO_GEN)/charset SCH_GEN=$(SNIO_GEN)/ch SCS_GEN=$(SNIO_GEN)/cs +SFS_GEN=$(SNIO_GEN)/fs FILES_gensbcs_out = $(FILES_gen_sbcs:%.java=$(GENSRCDIR)/%.java) @@ -670,4 +830,40 @@ $(BOOT_JAVA_CMD) -cp $(CHARSETMAPPING_JARFILE) build.tools.charsetmapping.GenerateSBCS \ $(GENCSSRC) $(SCS_GEN) sbcs +# +# Generated file system implementation classes (Unix only) +# + +GENUC_SRC = $(PLATFORM_SRC)/native/sun/nio/fs/genUnixConstants.c + +GENUC_EXE = $(TEMPDIR)/genUnixConstants + +GENUC_COPYRIGHT_YEARS = $(shell $(CAT) $(GENUC_SRC) | \ + $(NAWK) '/^.*Copyright.*Sun/ { print $$3 }') + +$(GENUC_EXE) : $(GENUC_SRC) + $(prep-target) + $(CC) $(CPPFLAGS) -o $@ $(GENUC_SRC) + +$(SFS_GEN)/UnixConstants.java: $(GENUC_EXE) + $(prep-target) + NAWK="$(NAWK)" SH="$(SH)" $(SH) -e addNotices.sh $(GENUC_COPYRIGHT_YEARS) > $@ + $(GENUC_EXE) >> $@ + +GENSC_SRC = $(PLATFORM_SRC)/native/sun/nio/fs/genSolarisConstants.c + +GENSC_EXE = $(TEMPDIR)/genSolarisConstants + +GENSC_COPYRIGHT_YEARS = $(shell $(CAT) $(GENSC_SRC) | \ + $(NAWK) '/^.*Copyright.*Sun/ { print $$3 }') + +$(GENSC_EXE) : $(GENSC_SRC) + $(prep-target) + $(CC) $(CPPFLAGS) -o $@ $(GENSC_SRC) + +$(SFS_GEN)/SolarisConstants.java: $(GENSC_EXE) + $(prep-target) + NAWK="$(NAWK)" SH="$(SH)" $(SH) -e addNotices.sh $(GENSC_COPYRIGHT_YEARS) > $@ + $(GENSC_EXE) >> $@ + .PHONY: sources
--- a/jdk/make/java/nio/mapfile-linux Fri Feb 27 10:54:11 2009 -0800 +++ b/jdk/make/java/nio/mapfile-linux Wed Jul 05 16:48:18 2017 +0200 @@ -1,5 +1,5 @@ # -# Copyright 2001-2008 Sun Microsystems, Inc. All Rights Reserved. +# Copyright 2001-2009 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 @@ -44,27 +44,38 @@ Java_sun_nio_ch_EPollArrayWrapper_interrupt; Java_sun_nio_ch_EPollArrayWrapper_offsetofData; Java_sun_nio_ch_EPollArrayWrapper_sizeofEPollEvent; + Java_sun_nio_ch_EPoll_init; + Java_sun_nio_ch_EPoll_eventSize; + Java_sun_nio_ch_EPoll_eventsOffset; + Java_sun_nio_ch_EPoll_dataOffset; + Java_sun_nio_ch_EPoll_epollCreate; + Java_sun_nio_ch_EPoll_epollCtl; + Java_sun_nio_ch_EPoll_epollWait; + Java_sun_nio_ch_EPollPort_close0; + Java_sun_nio_ch_EPollPort_drain1; + Java_sun_nio_ch_EPollPort_interrupt; + Java_sun_nio_ch_EPollPort_socketpair; Java_sun_nio_ch_FileChannelImpl_close0; - Java_sun_nio_ch_FileChannelImpl_force0; Java_sun_nio_ch_FileChannelImpl_initIDs; - Java_sun_nio_ch_FileChannelImpl_lock0; Java_sun_nio_ch_FileChannelImpl_map0; Java_sun_nio_ch_FileChannelImpl_position0; - Java_sun_nio_ch_FileChannelImpl_release0; - Java_sun_nio_ch_FileChannelImpl_size0; Java_sun_nio_ch_FileChannelImpl_transferTo0; - Java_sun_nio_ch_FileChannelImpl_truncate0; Java_sun_nio_ch_FileChannelImpl_unmap0; - Java_sun_nio_ch_FileDispatcher_close0; - Java_sun_nio_ch_FileDispatcher_closeIntFD; - Java_sun_nio_ch_FileDispatcher_init; - Java_sun_nio_ch_FileDispatcher_preClose0; - Java_sun_nio_ch_FileDispatcher_pread0; - Java_sun_nio_ch_FileDispatcher_pwrite0; - Java_sun_nio_ch_FileDispatcher_read0; - Java_sun_nio_ch_FileDispatcher_readv0; - Java_sun_nio_ch_FileDispatcher_write0; - Java_sun_nio_ch_FileDispatcher_writev0; + Java_sun_nio_ch_FileDispatcherImpl_close0; + Java_sun_nio_ch_FileDispatcherImpl_closeIntFD; + Java_sun_nio_ch_FileDispatcherImpl_force0; + Java_sun_nio_ch_FileDispatcherImpl_init; + Java_sun_nio_ch_FileDispatcherImpl_lock0; + Java_sun_nio_ch_FileDispatcherImpl_preClose0; + Java_sun_nio_ch_FileDispatcherImpl_pread0; + Java_sun_nio_ch_FileDispatcherImpl_pwrite0; + Java_sun_nio_ch_FileDispatcherImpl_read0; + Java_sun_nio_ch_FileDispatcherImpl_readv0; + Java_sun_nio_ch_FileDispatcherImpl_release0; + Java_sun_nio_ch_FileDispatcherImpl_size0; + Java_sun_nio_ch_FileDispatcherImpl_truncate0; + Java_sun_nio_ch_FileDispatcherImpl_write0; + Java_sun_nio_ch_FileDispatcherImpl_writev0; Java_sun_nio_ch_FileKey_init; Java_sun_nio_ch_FileKey_initIDs; Java_sun_nio_ch_InheritedChannel_close0; @@ -108,6 +119,76 @@ Java_sun_nio_ch_ServerSocketChannelImpl_accept0; Java_sun_nio_ch_ServerSocketChannelImpl_initIDs; Java_sun_nio_ch_SocketChannelImpl_checkConnect; + Java_sun_nio_ch_UnixAsynchronousServerSocketChannelImpl_accept0; + Java_sun_nio_ch_UnixAsynchronousServerSocketChannelImpl_initIDs; + Java_sun_nio_ch_UnixAsynchronousSocketChannelImpl_checkConnect; + Java_sun_nio_fs_GnomeFileTypeDetector_initializeGio; + Java_sun_nio_fs_GnomeFileTypeDetector_probeUsingGio; + Java_sun_nio_fs_GnomeFileTypeDetector_initializeGnomeVfs; + Java_sun_nio_fs_GnomeFileTypeDetector_probeUsingGnomeVfs; + Java_sun_nio_fs_LinuxWatchService_init; + Java_sun_nio_fs_LinuxWatchService_eventSize; + Java_sun_nio_fs_LinuxWatchService_eventOffsets; + Java_sun_nio_fs_LinuxWatchService_inotifyInit; + Java_sun_nio_fs_LinuxWatchService_inotifyAddWatch; + Java_sun_nio_fs_LinuxWatchService_inotifyRmWatch; + Java_sun_nio_fs_LinuxWatchService_configureBlocking; + Java_sun_nio_fs_LinuxWatchService_socketpair; + Java_sun_nio_fs_LinuxWatchService_poll; + Java_sun_nio_fs_LinuxNativeDispatcher_init; + Java_sun_nio_fs_LinuxNativeDispatcher_fgetxattr0; + Java_sun_nio_fs_LinuxNativeDispatcher_flistxattr; + Java_sun_nio_fs_LinuxNativeDispatcher_fsetxattr0; + Java_sun_nio_fs_LinuxNativeDispatcher_fremovexattr0; + Java_sun_nio_fs_LinuxNativeDispatcher_setmntent0; + Java_sun_nio_fs_LinuxNativeDispatcher_endmntent; + Java_sun_nio_fs_UnixNativeDispatcher_initIDs; + Java_sun_nio_fs_UnixNativeDispatcher_getcwd; + Java_sun_nio_fs_UnixNativeDispatcher_strerror; + Java_sun_nio_fs_UnixNativeDispatcher_dup; + Java_sun_nio_fs_UnixNativeDispatcher_access0; + Java_sun_nio_fs_UnixNativeDispatcher_stat0; + Java_sun_nio_fs_UnixNativeDispatcher_lstat0; + Java_sun_nio_fs_UnixNativeDispatcher_fstat; + Java_sun_nio_fs_UnixNativeDispatcher_fstatat0; + Java_sun_nio_fs_UnixNativeDispatcher_chmod0; + Java_sun_nio_fs_UnixNativeDispatcher_fchmod; + Java_sun_nio_fs_UnixNativeDispatcher_chown0; + Java_sun_nio_fs_UnixNativeDispatcher_lchown0; + Java_sun_nio_fs_UnixNativeDispatcher_fchown; + Java_sun_nio_fs_UnixNativeDispatcher_utimes0; + Java_sun_nio_fs_UnixNativeDispatcher_futimes; + Java_sun_nio_fs_UnixNativeDispatcher_open0; + Java_sun_nio_fs_UnixNativeDispatcher_openat0; + Java_sun_nio_fs_UnixNativeDispatcher_close; + Java_sun_nio_fs_UnixNativeDispatcher_read; + Java_sun_nio_fs_UnixNativeDispatcher_write; + Java_sun_nio_fs_UnixNativeDispatcher_fopen0; + Java_sun_nio_fs_UnixNativeDispatcher_fclose; + Java_sun_nio_fs_UnixNativeDispatcher_opendir0; + Java_sun_nio_fs_UnixNativeDispatcher_fdopendir; + Java_sun_nio_fs_UnixNativeDispatcher_readdir; + Java_sun_nio_fs_UnixNativeDispatcher_closedir; + Java_sun_nio_fs_UnixNativeDispatcher_link0; + Java_sun_nio_fs_UnixNativeDispatcher_unlink0; + Java_sun_nio_fs_UnixNativeDispatcher_unlinkat0; + Java_sun_nio_fs_UnixNativeDispatcher_rename0; + Java_sun_nio_fs_UnixNativeDispatcher_renameat0; + Java_sun_nio_fs_UnixNativeDispatcher_mkdir0; + Java_sun_nio_fs_UnixNativeDispatcher_rmdir0; + Java_sun_nio_fs_UnixNativeDispatcher_symlink0; + Java_sun_nio_fs_UnixNativeDispatcher_readlink0; + Java_sun_nio_fs_UnixNativeDispatcher_realpath0; + Java_sun_nio_fs_UnixNativeDispatcher_statvfs0; + Java_sun_nio_fs_UnixNativeDispatcher_pathconf0; + Java_sun_nio_fs_UnixNativeDispatcher_fpathconf; + Java_sun_nio_fs_UnixNativeDispatcher_mknod0; + Java_sun_nio_fs_UnixNativeDispatcher_getpwuid; + Java_sun_nio_fs_UnixNativeDispatcher_getgrgid; + Java_sun_nio_fs_UnixNativeDispatcher_getpwnam0; + Java_sun_nio_fs_UnixNativeDispatcher_getgrnam0; + Java_sun_nio_fs_UnixNativeDispatcher_getextmntent; + Java_sun_nio_fs_UnixCopyFile_transfer; local: *;
--- a/jdk/make/java/nio/mapfile-solaris Fri Feb 27 10:54:11 2009 -0800 +++ b/jdk/make/java/nio/mapfile-solaris Wed Jul 05 16:48:18 2017 +0200 @@ -1,5 +1,5 @@ # -# Copyright 2001-2008 Sun Microsystems, Inc. All Rights Reserved. +# Copyright 2001-2009 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 @@ -43,26 +43,26 @@ Java_sun_nio_ch_DevPollArrayWrapper_register; Java_sun_nio_ch_DevPollArrayWrapper_registerMultiple; Java_sun_nio_ch_FileChannelImpl_close0; - Java_sun_nio_ch_FileChannelImpl_force0; Java_sun_nio_ch_FileChannelImpl_initIDs; - Java_sun_nio_ch_FileChannelImpl_lock0; Java_sun_nio_ch_FileChannelImpl_map0; Java_sun_nio_ch_FileChannelImpl_position0; - Java_sun_nio_ch_FileChannelImpl_release0; - Java_sun_nio_ch_FileChannelImpl_size0; Java_sun_nio_ch_FileChannelImpl_transferTo0; - Java_sun_nio_ch_FileChannelImpl_truncate0; Java_sun_nio_ch_FileChannelImpl_unmap0; - Java_sun_nio_ch_FileDispatcher_close0; - Java_sun_nio_ch_FileDispatcher_closeIntFD; - Java_sun_nio_ch_FileDispatcher_init; - Java_sun_nio_ch_FileDispatcher_preClose0; - Java_sun_nio_ch_FileDispatcher_pread0; - Java_sun_nio_ch_FileDispatcher_pwrite0; - Java_sun_nio_ch_FileDispatcher_read0; - Java_sun_nio_ch_FileDispatcher_readv0; - Java_sun_nio_ch_FileDispatcher_write0; - Java_sun_nio_ch_FileDispatcher_writev0; + Java_sun_nio_ch_FileDispatcherImpl_close0; + Java_sun_nio_ch_FileDispatcherImpl_closeIntFD; + Java_sun_nio_ch_FileDispatcherImpl_force0; + Java_sun_nio_ch_FileDispatcherImpl_init; + Java_sun_nio_ch_FileDispatcherImpl_lock0; + Java_sun_nio_ch_FileDispatcherImpl_preClose0; + Java_sun_nio_ch_FileDispatcherImpl_pread0; + Java_sun_nio_ch_FileDispatcherImpl_pwrite0; + Java_sun_nio_ch_FileDispatcherImpl_read0; + Java_sun_nio_ch_FileDispatcherImpl_readv0; + Java_sun_nio_ch_FileDispatcherImpl_release0; + Java_sun_nio_ch_FileDispatcherImpl_size0; + Java_sun_nio_ch_FileDispatcherImpl_truncate0; + Java_sun_nio_ch_FileDispatcherImpl_write0; + Java_sun_nio_ch_FileDispatcherImpl_writev0; Java_sun_nio_ch_FileKey_init; Java_sun_nio_ch_FileKey_initIDs; Java_sun_nio_ch_InheritedChannel_close0; @@ -106,6 +106,75 @@ Java_sun_nio_ch_ServerSocketChannelImpl_accept0; Java_sun_nio_ch_ServerSocketChannelImpl_initIDs; Java_sun_nio_ch_SocketChannelImpl_checkConnect; + Java_sun_nio_ch_UnixAsynchronousServerSocketChannelImpl_accept0; + Java_sun_nio_ch_UnixAsynchronousServerSocketChannelImpl_initIDs; + Java_sun_nio_ch_UnixAsynchronousSocketChannelImpl_checkConnect; + Java_sun_nio_ch_SolarisEventPort_init; + Java_sun_nio_ch_SolarisEventPort_portCreate; + Java_sun_nio_ch_SolarisEventPort_portClose; + Java_sun_nio_ch_SolarisEventPort_portAssociate; + Java_sun_nio_ch_SolarisEventPort_portGet; + Java_sun_nio_ch_SolarisEventPort_portGetn; + Java_sun_nio_ch_SolarisEventPort_portSend; + Java_sun_nio_fs_GnomeFileTypeDetector_initializeGio; + Java_sun_nio_fs_GnomeFileTypeDetector_probeUsingGio; + Java_sun_nio_fs_GnomeFileTypeDetector_initializeGnomeVfs; + Java_sun_nio_fs_GnomeFileTypeDetector_probeUsingGnomeVfs; + Java_sun_nio_fs_UnixNativeDispatcher_initIDs; + Java_sun_nio_fs_UnixNativeDispatcher_getcwd; + Java_sun_nio_fs_UnixNativeDispatcher_strerror; + Java_sun_nio_fs_UnixNativeDispatcher_dup; + Java_sun_nio_fs_UnixNativeDispatcher_access0; + Java_sun_nio_fs_UnixNativeDispatcher_stat0; + Java_sun_nio_fs_UnixNativeDispatcher_lstat0; + Java_sun_nio_fs_UnixNativeDispatcher_fstat; + Java_sun_nio_fs_UnixNativeDispatcher_fstatat0; + Java_sun_nio_fs_UnixNativeDispatcher_chmod0; + Java_sun_nio_fs_UnixNativeDispatcher_fchmod; + Java_sun_nio_fs_UnixNativeDispatcher_chown0; + Java_sun_nio_fs_UnixNativeDispatcher_lchown0; + Java_sun_nio_fs_UnixNativeDispatcher_fchown; + Java_sun_nio_fs_UnixNativeDispatcher_utimes0; + Java_sun_nio_fs_UnixNativeDispatcher_futimes; + Java_sun_nio_fs_UnixNativeDispatcher_open0; + Java_sun_nio_fs_UnixNativeDispatcher_openat0; + Java_sun_nio_fs_UnixNativeDispatcher_close; + Java_sun_nio_fs_UnixNativeDispatcher_read; + Java_sun_nio_fs_UnixNativeDispatcher_write; + Java_sun_nio_fs_UnixNativeDispatcher_fopen0; + Java_sun_nio_fs_UnixNativeDispatcher_fclose; + Java_sun_nio_fs_UnixNativeDispatcher_opendir0; + Java_sun_nio_fs_UnixNativeDispatcher_fdopendir; + Java_sun_nio_fs_UnixNativeDispatcher_readdir; + Java_sun_nio_fs_UnixNativeDispatcher_closedir; + Java_sun_nio_fs_UnixNativeDispatcher_link0; + Java_sun_nio_fs_UnixNativeDispatcher_unlink0; + Java_sun_nio_fs_UnixNativeDispatcher_unlinkat0; + Java_sun_nio_fs_UnixNativeDispatcher_rename0; + Java_sun_nio_fs_UnixNativeDispatcher_renameat0; + Java_sun_nio_fs_UnixNativeDispatcher_mkdir0; + Java_sun_nio_fs_UnixNativeDispatcher_rmdir0; + Java_sun_nio_fs_UnixNativeDispatcher_symlink0; + Java_sun_nio_fs_UnixNativeDispatcher_readlink0; + Java_sun_nio_fs_UnixNativeDispatcher_realpath0; + Java_sun_nio_fs_UnixNativeDispatcher_statvfs0; + Java_sun_nio_fs_UnixNativeDispatcher_pathconf0; + Java_sun_nio_fs_UnixNativeDispatcher_fpathconf; + Java_sun_nio_fs_UnixNativeDispatcher_mknod0; + Java_sun_nio_fs_UnixNativeDispatcher_getpwuid; + Java_sun_nio_fs_UnixNativeDispatcher_getgrgid; + Java_sun_nio_fs_UnixNativeDispatcher_getpwnam0; + Java_sun_nio_fs_UnixNativeDispatcher_getgrnam0; + Java_sun_nio_fs_UnixNativeDispatcher_getextmntent; + Java_sun_nio_fs_UnixCopyFile_transfer; + Java_sun_nio_fs_SolarisNativeDispatcher_init; + Java_sun_nio_fs_SolarisNativeDispatcher_facl; + Java_sun_nio_fs_SolarisWatchService_init; + Java_sun_nio_fs_SolarisWatchService_portCreate; + Java_sun_nio_fs_SolarisWatchService_portAssociate; + Java_sun_nio_fs_SolarisWatchService_portDissociate; + Java_sun_nio_fs_SolarisWatchService_portSend; + Java_sun_nio_fs_SolarisWatchService_portGetn; local: *;
--- a/jdk/make/mksample/nio/Makefile Fri Feb 27 10:54:11 2009 -0800 +++ b/jdk/make/mksample/nio/Makefile Wed Jul 05 16:48:18 2017 +0200 @@ -1,5 +1,5 @@ # -# Copyright 2004-2008 Sun Microsystems, Inc. All Rights Reserved. +# Copyright 2004-2009 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 @@ -31,7 +31,7 @@ PRODUCT = java include $(BUILDDIR)/common/Defs.gmk -SUBDIRS = multicast server +SUBDIRS = file multicast server all build clean clobber:: $(SUBDIRS-loop)
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/make/mksample/nio/file/Makefile Wed Jul 05 16:48:18 2017 +0200 @@ -0,0 +1,56 @@ +# +# Copyright 2008-2009 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. +# + +# +# Makefile for the nio/file sample code +# + +BUILDDIR = ../../.. + +PRODUCT = java + +include $(BUILDDIR)/common/Defs.gmk + +SAMPLE_SRC_DIR = $(SHARE_SRC)/sample/nio/file +SAMPLE_DST_DIR = $(SAMPLEDIR)/nio/file + +SAMPLE_FILES = \ + $(SAMPLE_DST_DIR)/AclEdit.java \ + $(SAMPLE_DST_DIR)/Chmod.java \ + $(SAMPLE_DST_DIR)/Copy.java \ + $(SAMPLE_DST_DIR)/DiskUsage.java \ + $(SAMPLE_DST_DIR)/FileType.java \ + $(SAMPLE_DST_DIR)/WatchDir.java \ + $(SAMPLE_DST_DIR)/Xdd.java + +all build: $(SAMPLE_FILES) + +$(SAMPLE_DST_DIR)/%: $(SAMPLE_SRC_DIR)/% + $(install-file) + +clean clobber: + $(RM) -r $(SAMPLE_DST_DIR) + +.PHONY: all build clean clobber
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/src/share/classes/com/sun/nio/file/ExtendedCopyOption.java Wed Jul 05 16:48:18 2017 +0200 @@ -0,0 +1,43 @@ +/* + * Copyright 2007-2009 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. + */ + +package com.sun.nio.file; + +import java.nio.file.CopyOption; + +/** + * Defines <em>extended</em> copy options supported on some platforms + * by Sun's provider implementation. + * + * @since 1.7 + */ + +public enum ExtendedCopyOption implements CopyOption { + /** + * The copy may be interrupted by the {@link Thread#interrupt interrupt} + * method. + */ + INTERRUPTIBLE, +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/src/share/classes/com/sun/nio/file/ExtendedOpenOption.java Wed Jul 05 16:48:18 2017 +0200 @@ -0,0 +1,50 @@ +/* + * Copyright 2007-2009 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. + */ + +package com.sun.nio.file; + +import java.nio.file.OpenOption; + +/** + * Defines <em>extended</em> open options supported on some platforms + * by Sun's provider implementation. + * + * @since 1.7 + */ + +public enum ExtendedOpenOption implements OpenOption { + /** + * Prevent operations on the file that request read access. + */ + NOSHARE_READ, + /** + * Prevent operations on the file that request write access. + */ + NOSHARE_WRITE, + /** + * Prevent operations on the file that request delete access. + */ + NOSHARE_DELETE; +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/src/share/classes/com/sun/nio/file/ExtendedWatchEventModifier.java Wed Jul 05 16:48:18 2017 +0200 @@ -0,0 +1,43 @@ +/* + * Copyright 2007-2009 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. + */ + +package com.sun.nio.file; + +import java.nio.file.WatchEvent.Modifier; + +/** + * Defines <em>extended</em> watch event modifiers supported on some platforms + * by Sun's provider implementation. + * + * @since 1.7 + */ + +public enum ExtendedWatchEventModifier implements Modifier { + + /** + * Register a file tree instead of a single directory. + */ + FILE_TREE, +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/src/share/classes/com/sun/nio/file/SensitivityWatchEventModifier.java Wed Jul 05 16:48:18 2017 +0200 @@ -0,0 +1,62 @@ +/* + * Copyright 2007-2009 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. + */ + +package com.sun.nio.file; + +import java.nio.file.WatchEvent.Modifier; + +/** + * Defines the <em>sensitivity levels</em> when registering objects with a + * watch service implementation that polls the file system. + * + * @since 1.7 + */ + +public enum SensitivityWatchEventModifier implements Modifier { + /** + * High sensitivity. + */ + HIGH(2), + /** + * Medium sensitivity. + */ + MEDIUM(10), + /** + * Low sensitivity. + */ + LOW(30); + + /** + * Returns the sensitivity in seconds. + */ + public int sensitivityValueInSeconds() { + return sensitivity; + } + + private final int sensitivity; + private SensitivityWatchEventModifier(int sensitivity) { + this.sensitivity = sensitivity; + } +}
--- a/jdk/src/share/classes/java/io/File.java Fri Feb 27 10:54:11 2009 -0800 +++ b/jdk/src/share/classes/java/io/File.java Wed Jul 05 16:48:18 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 1994-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1994-2009 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 @@ -30,12 +30,12 @@ import java.net.URL; import java.net.MalformedURLException; import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.Map; -import java.util.Hashtable; -import java.util.Random; +import java.util.*; +import java.nio.file.*; +import java.nio.file.attribute.*; import java.security.AccessController; -import java.security.AccessControlException; +import java.security.PrivilegedAction; +import java.security.SecureRandom; import sun.security.action.GetPropertyAction; @@ -131,6 +131,18 @@ * created, the abstract pathname represented by a <code>File</code> object * will never change. * + * <h4>Interoperability with {@code java.nio.file} package</h4> + * + * <p> 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 */ @@ -573,6 +585,7 @@ * read access to the file * * @since JDK1.1 + * @see Path#toRealPath */ public String getCanonicalPath() throws IOException { return fs.canonicalize(fs.resolve(this)); @@ -597,6 +610,7 @@ * read access to the file * * @since 1.2 + * @see Path#toRealPath */ public File getCanonicalFile() throws IOException { String canonPath = getCanonicalPath(); @@ -663,6 +677,14 @@ * system is converted into an abstract pathname in a virtual machine on a * different operating system. * + * <p> Note that when this abstract pathname represents a UNC pathname then + * all components of the UNC (including the server name component) are encoded + * in the {@code URI} path. The authority component is undefined, meaning + * that it is represented as {@code null}. The {@link Path} class defines the + * {@link Path#toUri toUri} method to encode the server name in the authority + * component of the resulting {@code URI}. The {@link #toPath toPath} method + * may be used to obtain a {@code Path} representing this abstract pathname. + * * @return An absolute, hierarchical URI with a scheme equal to * <tt>"file"</tt>, a path representing this abstract pathname, * and undefined authority, query, and fragment components @@ -764,6 +786,8 @@ * If a security manager exists and its <code>{@link * java.lang.SecurityManager#checkRead(java.lang.String)}</code> * method denies read access to the file + * + * @see Attributes#readBasicFileAttributes */ public boolean isDirectory() { SecurityManager security = System.getSecurityManager(); @@ -788,6 +812,8 @@ * If a security manager exists and its <code>{@link * java.lang.SecurityManager#checkRead(java.lang.String)}</code> * method denies read access to the file + * + * @see Attributes#readBasicFileAttributes */ public boolean isFile() { SecurityManager security = System.getSecurityManager(); @@ -836,6 +862,8 @@ * If a security manager exists and its <code>{@link * java.lang.SecurityManager#checkRead(java.lang.String)}</code> * method denies read access to the file + * + * @see Attributes#readBasicFileAttributes */ public long lastModified() { SecurityManager security = System.getSecurityManager(); @@ -858,6 +886,8 @@ * If a security manager exists and its <code>{@link * java.lang.SecurityManager#checkRead(java.lang.String)}</code> * method denies read access to the file + * + * @see Attributes#readBasicFileAttributes */ public long length() { SecurityManager security = System.getSecurityManager(); @@ -907,6 +937,12 @@ * this pathname denotes a directory, then the directory must be empty in * order to be deleted. * + * <p> Note that the {@link Path} class defines the {@link Path#delete + * delete} method to throw an {@link IOException} when a file cannot be + * deleted. This is useful for error reporting and to diagnose why a file + * cannot be deleted. The {@link #toPath toPath} method may be used to + * obtain a {@code Path} representing this abstract pathname. + * * @return <code>true</code> if and only if the file or directory is * successfully deleted; <code>false</code> otherwise * @@ -973,6 +1009,13 @@ * will appear in any specific order; they are not, in particular, * guaranteed to appear in alphabetical order. * + * <p> Note that the {@link Path} class defines the {@link + * Path#newDirectoryStream newDirectoryStream} method to open a directory + * and iterate over the names of the files in the directory. This may use + * less resources when working with very large directories. The {@link + * #toPath toPath} method may be used to obtain a {@code Path} representing + * this abstract pathname. + * * @return An array of strings naming the files and directories in the * directory denoted by this abstract pathname. The array will be * empty if the directory is empty. Returns {@code null} if @@ -1024,13 +1067,13 @@ if ((names == null) || (filter == null)) { return names; } - ArrayList v = new ArrayList(); + List<String> v = new ArrayList<String>(); for (int i = 0 ; i < names.length ; i++) { if (filter.accept(this, names[i])) { v.add(names[i]); } } - return (String[])(v.toArray(new String[v.size()])); + return v.toArray(new String[v.size()]); } /** @@ -1052,6 +1095,13 @@ * will appear in any specific order; they are not, in particular, * guaranteed to appear in alphabetical order. * + * <p> Note that the {@link Path} class defines the {@link + * Path#newDirectoryStream newDirectoryStream} method to open a directory + * and iterate over the names of the files in the directory. This may use + * less resources when working with very large directories. The {@link + * #toPath toPath} method may be used to obtain a {@code Path} representing + * this abstract pathname. + * * @return An array of abstract pathnames denoting the files and * directories in the directory denoted by this abstract pathname. * The array will be empty if the directory is empty. Returns @@ -1157,6 +1207,12 @@ /** * Creates the directory named by this abstract pathname. * + * <p> Note that the {@link Path} class defines the {@link Path#createDirectory + * createDirectory} method to throw an {@link IOException} when a directory + * cannot be created. This is useful for error reporting and to diagnose why + * a directory cannot be created. The {@link #toPath toPath} method may be + * used to obtain a {@code Path} representing this abstract pathname. + * * @return <code>true</code> if and only if the directory was * created; <code>false</code> otherwise * @@ -1222,6 +1278,11 @@ * already exists. The return value should always be checked to make sure * that the rename operation was successful. * + * <p> Note that the {@link Path} class defines the {@link Path#moveTo + * moveTo} method to move or rename a file in a platform independent manner. + * The {@link #toPath toPath} method may be used to obtain a {@code Path} + * representing this abstract pathname. + * * @param dest The new abstract pathname for the named file * * @return <code>true</code> if and only if the renaming succeeded; @@ -1304,10 +1365,14 @@ return fs.setReadOnly(this); } - /** + /** * Sets the owner's or everybody's write permission for this abstract * pathname. * + * <p> The {@link Attributes Attributes} class defines methods that operate + * on file attributes including file permissions. This may be used when + * finer manipulation of file permissions is required. + * * @param writable * If <code>true</code>, sets the access permission to allow write * operations; if <code>false</code> to disallow write operations @@ -1371,6 +1436,10 @@ * Sets the owner's or everybody's read permission for this abstract * pathname. * + * <p> The {@link Attributes Attributes} class defines methods that operate + * on file attributes including file permissions. This may be used when + * finer manipulation of file permissions is required. + * * @param readable * If <code>true</code>, sets the access permission to allow read * operations; if <code>false</code> to disallow read operations @@ -1440,6 +1509,10 @@ * Sets the owner's or everybody's execute permission for this abstract * pathname. * + * <p> The {@link Attributes Attributes} class defines methods that operate + * on file attributes including file permissions. This may be used when + * finer manipulation of file permissions is required. + * * @param executable * If <code>true</code>, sets the access permission to allow execute * operations; if <code>false</code> to disallow execute operations @@ -1678,44 +1751,44 @@ /* -- Temporary files -- */ - private static final Object tmpFileLock = new Object(); - - private static int counter = -1; /* Protected by tmpFileLock */ + private static class TemporaryDirectory { + private TemporaryDirectory() { } - private static File generateFile(String prefix, String suffix, File dir) - throws IOException - { - if (counter == -1) { - counter = new Random().nextInt() & 0xffff; - } - counter++; - return new File(dir, prefix + Integer.toString(counter) + suffix); - } - - private static String tmpdir; /* Protected by tmpFileLock */ + static final String valueAsString = fs.normalize( + AccessController.doPrivileged(new GetPropertyAction("java.io.tmpdir"))); + static final File valueAsFile = + new File(valueAsString, fs.prefixLength(valueAsString)); - private static String getTempDir() { - if (tmpdir == null) - tmpdir = fs.normalize( - AccessController.doPrivileged( - new GetPropertyAction("java.io.tmpdir"))); - return tmpdir; - } + // file name generation + private static final SecureRandom random = new SecureRandom(); + static File generateFile(String prefix, String suffix, File dir) { + long n = random.nextLong(); + if (n == Long.MIN_VALUE) { + n = 0; // corner case + } else { + n = Math.abs(n); + } + return new File(dir, prefix + Long.toString(n) + suffix); + } - private static boolean checkAndCreate(String filename, SecurityManager sm) - throws IOException - { - if (sm != null) { - try { - sm.checkWrite(filename); - } catch (AccessControlException x) { - /* Throwing the original AccessControlException could disclose - the location of the default temporary directory, so we - re-throw a more innocuous SecurityException */ - throw new SecurityException("Unable to create temporary file"); - } + // 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(valueAsString) + .getFileStore().supportsFileAttributeView("posix"); + } catch (IOException e) { + throw new IOError(e); + } + } + }); } - return fs.createFileExclusively(filename); } /** @@ -1791,22 +1864,29 @@ File directory) throws IOException { - if (prefix == null) throw new NullPointerException(); if (prefix.length() < 3) throw new IllegalArgumentException("Prefix string too short"); - String s = (suffix == null) ? ".tmp" : suffix; - synchronized (tmpFileLock) { - if (directory == null) { - String tmpDir = getTempDir(); - directory = new File(tmpDir, fs.prefixLength(tmpDir)); + if (suffix == null) + suffix = ".tmp"; + + File tmpdir = (directory != null) ? + directory : TemporaryDirectory.valueAsFile; + SecurityManager sm = System.getSecurityManager(); + File f; + do { + f = TemporaryDirectory.generateFile(prefix, suffix, tmpdir); + if (sm != null) { + try { + sm.checkWrite(f.getPath()); + } catch (SecurityException se) { + // don't reveal temporary directory location + if (directory == null) + throw new SecurityException("Unable to create temporary file"); + throw se; + } } - SecurityManager sm = System.getSecurityManager(); - File f; - do { - f = generateFile(prefix, s, directory); - } while (!checkAndCreate(f.getPath(), sm)); - return f; - } + } while (!fs.createFileExclusively(f.getPath())); + return f; } /** @@ -1844,6 +1924,122 @@ return createTempFile(prefix, suffix, null); } + /** + * 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) + DeleteOnExitHook.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 + } + } + } /* -- Basic infrastructure -- */ @@ -1963,5 +2159,46 @@ ); } + // -- Integration with java.nio.file -- + private volatile transient Path filePath; + + /** + * 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) { + if (path.length() == 0) { + // assume default file system treats "." as current directory + filePath = Paths.get("."); + } else { + filePath = Paths.get(path); + } + } + } + } + return filePath; + } }
--- a/jdk/src/share/classes/java/io/FilePermission.java Fri Feb 27 10:54:11 2009 -0800 +++ b/jdk/src/share/classes/java/io/FilePermission.java Wed Jul 05 16:48:18 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 1997-2005 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1997-2009 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 @@ -29,7 +29,6 @@ import java.util.Enumeration; import java.util.List; import java.util.ArrayList; -import java.util.StringTokenizer; import java.util.Vector; import java.util.Collections; import java.io.ObjectStreamField; @@ -58,7 +57,8 @@ * <P> * 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", and "delete". Their meaning is defined as follows: + * "read", "write", "execute", "delete", and "readlink". Their meaning is + * defined as follows: * <P> * <DL> * <DT> read <DD> read permission @@ -69,6 +69,11 @@ * <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. @@ -114,11 +119,15 @@ * Delete action. */ private final static int DELETE = 0x8; + /** + * Read link action. + */ + private final static int READLINK = 0x10; /** - * All actions (read,write,execute,delete) + * All actions (read,write,execute,delete,readlink) */ - private final static int ALL = READ|WRITE|EXECUTE|DELETE; + private final static int ALL = READ|WRITE|EXECUTE|DELETE|READLINK; /** * No actions. */ @@ -235,7 +244,7 @@ * <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", and "delete". + * "read", "write", "execute", "delete", and "readlink". * * <p>A pathname that ends in "/*" (where "/" is * the file separator character, <code>File.separatorChar</code>) @@ -425,6 +434,8 @@ return EXECUTE; } else if (actions == SecurityConstants.FILE_DELETE_ACTION) { return DELETE; + } else if (actions == SecurityConstants.FILE_READLINK_ACTION) { + return READLINK; } char[] a = actions.toCharArray(); @@ -485,6 +496,18 @@ 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( @@ -529,7 +552,7 @@ /** * Return the canonical string representation of the actions. * Always returns present actions in the following order: - * read, write, execute, delete. + * read, write, execute, delete, readlink. * * @return the canonical string representation of the actions. */ @@ -561,14 +584,20 @@ 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. For example, if this FilePermission object - * allows both write and read actions, a call to <code>getActions</code> + * 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. @@ -678,7 +707,7 @@ implements Serializable { // Not serialized; see serialization section at end of class - private transient List perms; + private transient List<Permission> perms; /** * Create an empty FilePermissions object. @@ -686,7 +715,7 @@ */ public FilePermissionCollection() { - perms = new ArrayList(); + perms = new ArrayList<Permission>(); } /** @@ -791,7 +820,7 @@ // Don't call out.defaultWriteObject() // Write out Vector - Vector permissions = new Vector(perms.size()); + Vector<Permission> permissions = new Vector<Permission>(perms.size()); synchronized (this) { permissions.addAll(perms); } @@ -804,6 +833,7 @@ /* * 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() @@ -812,8 +842,8 @@ ObjectInputStream.GetField gfields = in.readFields(); // Get the one we want - Vector permissions = (Vector)gfields.get("permissions", null); - perms = new ArrayList(permissions.size()); + Vector<Permission> permissions = (Vector<Permission>)gfields.get("permissions", null); + perms = new ArrayList<Permission>(permissions.size()); perms.addAll(permissions); } }
--- a/jdk/src/share/classes/java/lang/Thread.java Fri Feb 27 10:54:11 2009 -0800 +++ b/jdk/src/share/classes/java/lang/Thread.java Wed Jul 05 16:48:18 2017 +0200 @@ -25,13 +25,17 @@ package java.lang; +import java.lang.ref.Reference; +import java.lang.ref.ReferenceQueue; +import java.lang.ref.WeakReference; import java.security.AccessController; import java.security.AccessControlContext; import java.security.PrivilegedAction; import java.util.Map; import java.util.HashMap; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; import java.util.concurrent.locks.LockSupport; -import sun.misc.SoftCache; import sun.nio.ch.Interruptible; import sun.security.util.SecurityConstants; @@ -1640,8 +1644,17 @@ new RuntimePermission("enableContextClassLoaderOverride"); /** cache of subclass security audit results */ - private static final SoftCache subclassAudits = new SoftCache(10); + /* Replace with ConcurrentReferenceHashMap when/if it appears in a future + * release */ + private static class Caches { + /** cache of subclass security audit results */ + static final ConcurrentMap<WeakClassKey,Boolean> subclassAudits = + new ConcurrentHashMap<WeakClassKey,Boolean>(); + /** queue for WeakReferences to audited subclasses */ + static final ReferenceQueue<Class<?>> subclassAuditsQueue = + new ReferenceQueue<Class<?>>(); + } /** * Verifies that this (possibly subclass) instance can be constructed @@ -1652,19 +1665,15 @@ private static boolean isCCLOverridden(Class cl) { if (cl == Thread.class) return false; - Boolean result = null; - synchronized (subclassAudits) { - result = (Boolean) subclassAudits.get(cl); - if (result == null) { - /* - * Note: only new Boolean instances (i.e., not Boolean.TRUE or - * Boolean.FALSE) must be used as cache values, otherwise cache - * entry will pin associated class. - */ - result = new Boolean(auditSubclass(cl)); - subclassAudits.put(cl, result); - } + + processQueue(Caches.subclassAuditsQueue, Caches.subclassAudits); + WeakClassKey key = new WeakClassKey(cl, Caches.subclassAuditsQueue); + Boolean result = Caches.subclassAudits.get(key); + if (result == null) { + result = Boolean.valueOf(auditSubclass(cl)); + Caches.subclassAudits.putIfAbsent(key, result); } + return result.booleanValue(); } @@ -1967,6 +1976,68 @@ getUncaughtExceptionHandler().uncaughtException(this, e); } + /** + * Removes from the specified map any keys that have been enqueued + * on the specified reference queue. + */ + static void processQueue(ReferenceQueue<Class<?>> queue, + ConcurrentMap<? extends + WeakReference<Class<?>>, ?> map) + { + Reference<? extends Class<?>> ref; + while((ref = queue.poll()) != null) { + map.remove(ref); + } + } + + /** + * Weak key for Class objects. + **/ + static class WeakClassKey extends WeakReference<Class<?>> { + /** + * saved value of the referent's identity hash code, to maintain + * a consistent hash code after the referent has been cleared + */ + private final int hash; + + /** + * Create a new WeakClassKey to the given object, registered + * with a queue. + */ + WeakClassKey(Class<?> cl, ReferenceQueue<Class<?>> refQueue) { + super(cl, refQueue); + hash = System.identityHashCode(cl); + } + + /** + * Returns the identity hash code of the original referent. + */ + @Override + public int hashCode() { + return hash; + } + + /** + * Returns true if the given object is this identical + * WeakClassKey instance, or, if this object's referent has not + * been cleared, if the given object is another WeakClassKey + * instance with the identical non-null referent as this one. + */ + @Override + public boolean equals(Object obj) { + if (obj == this) + return true; + + if (obj instanceof WeakClassKey) { + Object referent = get(); + return (referent != null) && + (referent == ((WeakClassKey) obj).get()); + } else { + return false; + } + } + } + /* Some private helper methods */ private native void setPriority0(int newPriority); private native void stop0(Object o);
--- a/jdk/src/share/classes/java/net/StandardProtocolFamily.java Fri Feb 27 10:54:11 2009 -0800 +++ b/jdk/src/share/classes/java/net/StandardProtocolFamily.java Wed Jul 05 16:48:18 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2007-2009 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 @@ -26,7 +26,7 @@ package java.net; /** - * Defines the standard family of communication protocols. + * Defines the standard families of communication protocols. * * @since 1.7 */
--- a/jdk/src/share/classes/java/net/StandardSocketOption.java Fri Feb 27 10:54:11 2009 -0800 +++ b/jdk/src/share/classes/java/net/StandardSocketOption.java Wed Jul 05 16:48:18 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2007-2009 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 @@ -59,6 +59,7 @@ * * @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); @@ -78,6 +79,7 @@ * * @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); @@ -107,6 +109,8 @@ * 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); @@ -145,6 +149,8 @@ * * @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); @@ -175,6 +181,7 @@ * * @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); @@ -205,6 +212,8 @@ * 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); @@ -215,15 +224,15 @@ /** * The Type of Service (ToS) octet in the Internet Protocol (IP) header. * - * <p> The value of this socket option is an {@code Integer}, the least - * significant 8 bits of which represents 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 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 @@ -235,6 +244,8 @@ * <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); @@ -257,6 +268,7 @@ * 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); @@ -283,6 +295,7 @@ * 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); @@ -307,6 +320,7 @@ * 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); @@ -328,11 +342,12 @@ * 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. In that case, invoking the {@code setOption} method to disable - * the option has no effect. + * 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);
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/src/share/classes/java/nio/channels/AsynchronousByteChannel.java Wed Jul 05 16:48:18 2017 +0200 @@ -0,0 +1,205 @@ +/* + * Copyright 2007-2009 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. + */ + +package 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 or write 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/jdk/src/share/classes/java/nio/channels/AsynchronousChannel.java Wed Jul 05 16:48:18 2017 +0200 @@ -0,0 +1,116 @@ +/* + * Copyright 2007-2009 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. + */ + +package java.nio.channels; + +import java.io.IOException; +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 + */ + @Override + void close() throws IOException; +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/src/share/classes/java/nio/channels/AsynchronousChannelGroup.java Wed Jul 05 16:48:18 2017 +0200 @@ -0,0 +1,344 @@ +/* + * Copyright 2007-2009 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. + */ + +package java.nio.channels; + +import java.nio.channels.spi.AsynchronousChannelProvider; +import java.io.IOException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.TimeUnit; + +/** + * 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 defined here. Channels are bound to a group by + * specifying the group when constructing the channel. The associated thread + * pool is <em>owned</em> by the group; termination of the group results in the + * shutdown of the associated 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 a 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, + * the 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(AsynchronousChannelGroup) + * @see AsynchronousServerSocketChannel#open(AsynchronousChannelGroup) + */ + +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 resulting asynchronous channel group reuses a fixed number of + * threads. 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 group is created by invoking the {@link + * AsynchronousChannelProvider#openAsynchronousChannelGroup(int,ThreadFactory) + * openAsynchronousChannelGroup(int,ThreadFactory)} method of the system-wide + * default {@link AsynchronousChannelProvider} object. + * + * @param nThreads + * The number of threads in the pool + * @param threadFactory + * The factory to use when creating new threads + * + * @return A new asynchronous channel group + * + * @throws IllegalArgumentException + * If {@code nThreads <= 0} + * @throws IOException + * If an I/O error occurs + */ + public static AsynchronousChannelGroup withFixedThreadPool(int nThreads, + ThreadFactory threadFactory) + throws IOException + { + return AsynchronousChannelProvider.provider() + .openAsynchronousChannelGroup(nThreads, threadFactory); + } + + /** + * Creates an asynchronous channel group with a given thread pool 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 exclusively by 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(ExecutorService,int) + * openAsynchronousChannelGroup(ExecutorService,int)} 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 java.util.concurrent.Executors#newCachedThreadPool + */ + public static AsynchronousChannelGroup withCachedThreadPool(ExecutorService executor, + int initialSize) + throws IOException + { + return AsynchronousChannelProvider.provider() + .openAsynchronousChannelGroup(executor, initialSize); + } + + /** + * Creates an asynchronous channel group with a given thread pool. + * + * <p> The {@code executor} parameter is an {@code ExecutorService} that + * executes tasks submitted to dispatch completion results for operations + * initiated on asynchronous channels in the group. + * + * <p> Care should be taken when configuring the executor service. It + * should support <em>direct handoff</em> or <em>unbounded queuing</em> of + * submitted tasks, and the thread that invokes the {@link + * ExecutorService#execute execute} method should never invoke the task + * directly. An implementation may mandate additional constraints. + * + * <p> The executor is intended to be used exclusively by 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(ExecutorService,int) + * openAsynchronousChannelGroup(ExecutorService,int)} method of the system-wide + * default {@link AsynchronousChannelProvider} object with an {@code + * initialSize} of {@code 0}. + * + * @param executor + * The thread pool for the resulting group + * + * @return A new asynchronous channel group + * + * @throws IOException + * If an I/O error occurs + */ + public static AsynchronousChannelGroup withThreadPool(ExecutorService executor) + throws IOException + { + return AsynchronousChannelProvider.provider() + .openAsynchronousChannelGroup(executor, 0); + } + + /** + * 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 thread + * pool 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/jdk/src/share/classes/java/nio/channels/AsynchronousDatagramChannel.java Wed Jul 05 16:48:18 2017 +0200 @@ -0,0 +1,718 @@ +/* + * Copyright 2007-2009 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. + */ + +package java.nio.channels; + +import java.nio.channels.spi.*; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.Future; +import java.io.IOException; +import java.net.SocketOption; +import java.net.SocketAddress; +import java.net.ProtocolFamily; +import java.nio.ByteBuffer; + +/** + * 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> Asynchronous datagram channels allow more than one read/receive and + * write/send to be oustanding at any given time. + * + * <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 (or the default provider where {@code group} is {@code + * null}). + * + * <p> The {@code family} 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 {@code null} to use the default protocol + * family + * @param group + * The group to which the newly constructed channel should be bound, + * or {@code null} 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 + */ + @Override + public abstract AsynchronousDatagramChannel bind(SocketAddress local) + throws IOException; + + /** + * @throws IllegalArgumentException {@inheritDoc} + * @throws ClosedChannelException {@inheritDoc} + * @throws IOException {@inheritDoc} + */ + @Override + 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. 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 + * {@code Future} representing the pending result of the operation. + * The {@code Future}'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}. When a timeout elapses then the state of + * the {@link ByteBuffer} is not defined. The buffers should be discarded or + * at least care must be taken to ensure that the buffer is not accessed + * while the channel remains open. + * + * <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 {@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 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 + * {@code Future} representing the pending result of the operation. + * The {@code Future}'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}. + * + * @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 {@code Future} 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 + * {@code Future} representing the pending result of the operation. + * The {@code Future}'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 {@code Future} 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 + * {@code Future} 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 {@code Future}'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}. When a timeout elapses then the state of + * the {@link ByteBuffer} is not defined. The buffers should be discarded or + * at least care must be taken to ensure that the buffer is not accessed + * while the channel remains open. + * + * <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 {@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 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 timeout is negative, or if the channel's socket 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 + * {@code Future} 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 {@code Future}'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}. + * + * @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 {@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 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 + * {@code Future} 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 {@code Future}'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 {@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 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 + * {@code Future} representing the pending result of the operation. + * The {@code Future}'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}. When a timeout elapses then the state of + * the {@link ByteBuffer} is not defined. The buffers should be discarded or + * at least care must be taken to ensure that the buffer is not accessed + * while the channel remains open. + * + * @param dst + * The buffer into which the datagram is 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 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 + */ + @Override + 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 + * @throws ShutdownChannelGroupException + * If a handler is specified, and the channel group is shutdown + */ + @Override + 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 + * {@code Future} 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 + * {@code Future}'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}. When a timeout elapses then the state of + * the {@link ByteBuffer} is not defined. The buffers should be discarded or + * at least care must be taken to ensure that the buffer is not accessed + * while the channel remains open. + * + * @param src + * The buffer containing the datagram to be sent + * @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 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 + */ + @Override + 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 + * @throws ShutdownChannelGroupException + * If a handler is specified, and the channel group is shutdown + */ + @Override + 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/jdk/src/share/classes/java/nio/channels/AsynchronousFileChannel.java Wed Jul 05 16:48:18 2017 +0200 @@ -0,0 +1,774 @@ +/* + * Copyright 2007-2009 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. + */ + +package java.nio.channels; + +import java.nio.file.*; +import java.nio.file.attribute.FileAttribute; +import java.nio.file.spi.*; +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; + +/** + * 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} + */ + @Override + 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/jdk/src/share/classes/java/nio/channels/AsynchronousServerSocketChannel.java Wed Jul 05 16:48:18 2017 +0200 @@ -0,0 +1,303 @@ +/* + * Copyright 2007-2009 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. + */ + +package java.nio.channels; + +import java.nio.channels.spi.*; +import java.net.SocketOption; +import java.net.SocketAddress; +import java.util.concurrent.Future; +import java.io.IOException; + +/** + * 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/jdk/src/share/classes/java/nio/channels/AsynchronousSocketChannel.java Wed Jul 05 16:48:18 2017 +0200 @@ -0,0 +1,670 @@ +/* + * Copyright 2007-2009 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. + */ + +package java.nio.channels; + +import java.nio.channels.spi.*; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.Future; +import java.io.IOException; +import java.net.SocketOption; +import java.net.SocketAddress; +import java.nio.ByteBuffer; + +/** + * 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} + */ + @Override + public abstract AsynchronousSocketChannel bind(SocketAddress local) + throws IOException; + + /** + * @throws IllegalArgumentException {@inheritDoc} + * @throws ClosedChannelException {@inheritDoc} + * @throws IOException {@inheritDoc} + */ + @Override + 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 + */ + @Override + 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 + */ + @Override + 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 + */ + @Override + 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 + */ + @Override + 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/jdk/src/share/classes/java/nio/channels/Channels.java Fri Feb 27 10:54:11 2009 -0800 +++ b/jdk/src/share/classes/java/nio/channels/Channels.java Wed Jul 05 16:48:18 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 2000-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2000-2009 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 @@ -33,15 +33,12 @@ import java.io.Writer; import java.io.IOException; import java.nio.ByteBuffer; -import java.nio.CharBuffer; -import java.nio.BufferOverflowException; -import java.nio.BufferUnderflowException; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.CharsetEncoder; -import java.nio.charset.CoderResult; 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; @@ -184,6 +181,155 @@ }; } + /** + * {@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) { + checkNotNull(ch, "ch"); + return new InputStream() { + + private ByteBuffer bb = null; + private byte[] bs = null; // Invoker's previous array + private byte[] b1 = null; + + @Override + 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; + } + + @Override + 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(); + } + } + + @Override + 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) { + checkNotNull(ch, "ch"); + return new OutputStream() { + + private ByteBuffer bb = null; + private byte[] bs = null; // Invoker's previous array + private byte[] b1 = null; + + @Override + public synchronized void write(int b) throws IOException { + if (b1 == null) + b1 = new byte[1]; + b1[0] = (byte)b; + this.write(b1); + } + + @Override + 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(); + } + } + + @Override + public void close() throws IOException { + ch.close(); + } + }; + } + // -- Channels from streams -- @@ -468,5 +614,4 @@ checkNotNull(csName, "csName"); return newWriter(ch, Charset.forName(csName).newEncoder(), -1); } - }
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/src/share/classes/java/nio/channels/CompletionHandler.java Wed Jul 05 16:48:18 2017 +0200 @@ -0,0 +1,77 @@ +/* + * Copyright 2007-2009 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. + */ + +package 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 to indicate why the I/O operation failed + * @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/jdk/src/share/classes/java/nio/channels/DatagramChannel.java Fri Feb 27 10:54:11 2009 -0800 +++ b/jdk/src/share/classes/java/nio/channels/DatagramChannel.java Wed Jul 05 16:48:18 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 2000-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2000-2009 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 @@ -31,7 +31,8 @@ import java.net.SocketOption; import java.net.SocketAddress; import java.nio.ByteBuffer; -import java.nio.channels.spi.*; +import java.nio.channels.spi.AbstractSelectableChannel; +import java.nio.channels.spi.SelectorProvider; /** * A selectable channel for datagram-oriented sockets. @@ -53,7 +54,8 @@ * be determined by invoking its {@link #isConnected isConnected} method. * * <p> Socket options are configured using the {@link #setOption(SocketOption,Object) - * setOption} method. Datagram channels support the following options: + * setOption} method. A datagram channel to an Internet Protocol socket supports + * the following options: * <blockquote> * <table border> * <tr> @@ -211,6 +213,7 @@ throws IOException; /** + * @throws UnsupportedOperationException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} * @throws ClosedChannelException {@inheritDoc} * @throws IOException {@inheritDoc} @@ -220,7 +223,6 @@ public abstract <T> DatagramChannel setOption(SocketOption<T> name, T value) throws IOException; - /** * Retrieves a datagram socket associated with this channel. * @@ -313,15 +315,17 @@ /** * Returns the remote address to which this channel's socket is connected. * - * @return The remote address; {@code null} if the channel is not {@link - * #isOpen open} or the channel's socket is not 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 getConnectedAddress() throws IOException; + public abstract SocketAddress getRemoteAddress() throws IOException; /** * Receives a datagram via this channel.
--- a/jdk/src/share/classes/java/nio/channels/FileChannel.java Fri Feb 27 10:54:11 2009 -0800 +++ b/jdk/src/share/classes/java/nio/channels/FileChannel.java Wed Jul 05 16:48:18 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 2000-2005 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2000-2009 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 @@ -29,16 +29,23 @@ import java.nio.ByteBuffer; import java.nio.MappedByteBuffer; import java.nio.channels.spi.AbstractInterruptibleChannel; - +import java.nio.file.*; +import java.nio.file.attribute.FileAttribute; +import java.nio.file.spi.*; +import java.util.Set; +import java.util.HashSet; +import java.util.Collections; /** * A channel for reading, writing, mapping, and manipulating a file. * - * <p> A file channel has a current <i>position</i> within its file which can - * be both {@link #position() </code>queried<code>} and {@link #position(long) - * </code>modified<code>}. The file itself contains a variable-length sequence + * <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 - * </code><i>size</i><code>} can be queried. The size of the file increases + * <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 @@ -50,27 +57,27 @@ * * <ul> * - * <li><p> Bytes may be {@link #read(ByteBuffer, long) </code>read<code>} or - * {@link #write(ByteBuffer, long) </code>written<code>} at an absolute + * <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 </code>mapped<code>} + * <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 </code>forced - * out<code>} to the underlying storage device, ensuring that data are not + * <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 </code>to - * some other channel<code>}, and {@link #transferFrom </code>vice - * versa<code>}, in a way that can be optimized by many operating systems + * <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 </code>locked<code>} + * <li><p> A region of a file may be {@link FileLock <i>locked</i>} * against access by other programs. </p></li> * * </ul> @@ -96,25 +103,23 @@ * machine. The exact nature of any such inconsistencies are system-dependent * and are therefore unspecified. * - * <p> This class does not define methods for opening existing files or for - * creating new ones; such methods may be added in a future release. In this - * release a file channel can be obtained from an existing {@link - * java.io.FileInputStream#getChannel FileInputStream}, {@link + * <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. + * 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. * - * <p> The state of a 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"><p> At various points this class specifies that an + * <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 @@ -127,7 +132,7 @@ * 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"><p> A file channel that is open for writing may be in + * <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) @@ -138,7 +143,6 @@ * 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() @@ -147,18 +151,190 @@ * @author Mike McCloskey * @author JSR-51 Expert Group * @since 1.4 + * @updated 1.7 */ public abstract class FileChannel extends AbstractInterruptibleChannel - implements ByteChannel, GatheringByteChannel, ScatteringByteChannel + implements SeekableByteChannel, GatheringByteChannel, ScatteringByteChannel { - /** * 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); + } // -- Channel operations -- @@ -286,7 +462,7 @@ public abstract FileChannel position(long newPosition) throws IOException; /** - * Returns the current size of this channel's file. </p> + * Returns the current size of this channel's file. </p> * * @return The current size of this channel's file, * measured in bytes @@ -359,7 +535,7 @@ * <p> This method is only guaranteed to force changes that were made to * this channel's file via the methods defined in this class. It may or * may not force changes that were made by modifying the content of a - * {@link MappedByteBuffer </code>mapped byte buffer<code>} obtained by + * {@link MappedByteBuffer <i>mapped byte buffer</i>} obtained by * invoking the {@link #map map} method. Invoking the {@link * MappedByteBuffer#force force} method of the mapped byte buffer will * force changes made to the buffer's content to be written. </p> @@ -678,7 +854,7 @@ * reading; for a read/write or private mapping, this channel must have * been opened for both reading and writing. * - * <p> The {@link MappedByteBuffer </code>mapped byte buffer<code>} + * <p> The {@link MappedByteBuffer <i>mapped byte buffer</i>} * returned by this method will have a position of zero and a limit and * capacity of <tt>size</tt>; its mark will be undefined. The buffer and * the mapping that it represents will remain valid until the buffer itself @@ -717,6 +893,8 @@ * The size of the region to be mapped; must be non-negative and * no greater than {@link java.lang.Integer#MAX_VALUE} * + * @return The mapped byte buffer + * * @throws NonReadableChannelException * If the <tt>mode</tt> is {@link MapMode#READ_ONLY READ_ONLY} but * this channel was not opened for reading
--- a/jdk/src/share/classes/java/nio/channels/FileLock.java Fri Feb 27 10:54:11 2009 -0800 +++ b/jdk/src/share/classes/java/nio/channels/FileLock.java Wed Jul 05 16:48:18 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2001-2009 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 @@ -27,14 +27,16 @@ import java.io.IOException; - /** * 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. + * 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 @@ -70,8 +72,7 @@ * <p> File-lock objects are safe for use by multiple concurrent threads. * * - * <a name="pdep"> - * <h4> Platform dependencies </h4> + * <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 @@ -93,7 +94,7 @@ * * <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 - * </code>mapped into memory<code>}, and vice versa. Programs that combine + * <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 @@ -113,11 +114,12 @@ * @author Mark Reinhold * @author JSR-51 Expert Group * @since 1.4 + * @updated 1.7 */ public abstract class FileLock { - private final FileChannel channel; + private final Channel channel; private final long position; private final long size; private final boolean shared; @@ -159,11 +161,66 @@ } /** - * Returns the file channel upon whose file this lock is held. </p> + * {@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 * - * @return The file channel + * @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; }
--- a/jdk/src/share/classes/java/nio/channels/MembershipKey.java Fri Feb 27 10:54:11 2009 -0800 +++ b/jdk/src/share/classes/java/nio/channels/MembershipKey.java Wed Jul 05 16:48:18 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2007-2009 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 @@ -28,7 +28,6 @@ import java.net.InetAddress; import java.net.NetworkInterface; import java.io.IOException; -import java.util.List; /** * A token representing the membership of an Internet Protocol (IP) multicast @@ -38,7 +37,7 @@ * 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 #getSourceAddress() getSourceAddress} method. + * 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 @@ -93,11 +92,8 @@ * 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; + public abstract void drop(); /** * Block multicast datagrams from the given source address. @@ -140,10 +136,8 @@ * @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; + public abstract MembershipKey unblock(InetAddress source); /** * Returns the channel for which this membership key was created. This @@ -152,7 +146,7 @@ * * @return the channel */ - public abstract MulticastChannel getChannel(); + public abstract MulticastChannel channel(); /** * Returns the multicast group for which this membership key was created. @@ -161,7 +155,7 @@ * * @return the multicast group */ - public abstract InetAddress getGroup(); + public abstract InetAddress group(); /** * Returns the network interface for which this membership key was created. @@ -170,7 +164,7 @@ * * @return the network interface */ - public abstract NetworkInterface getNetworkInterface(); + public abstract NetworkInterface networkInterface(); /** * Returns the source address if this membership key is source-specific, @@ -179,5 +173,5 @@ * @return The source address if this membership key is source-specific, * otherwise {@code null} */ - public abstract InetAddress getSourceAddress(); + public abstract InetAddress sourceAddress(); }
--- a/jdk/src/share/classes/java/nio/channels/MulticastChannel.java Fri Feb 27 10:54:11 2009 -0800 +++ b/jdk/src/share/classes/java/nio/channels/MulticastChannel.java Wed Jul 05 16:48:18 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2007-2009 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 @@ -123,6 +123,22 @@ extends NetworkChannel { /** + * Closes this channel. + * + * <p> If the channel is a member of a multicast group then the membership + * is {@link MembershipKey#drop dropped}. Upon return, the {@link + * MembershipKey membership-key} will be {@link MembershipKey#isValid + * invalid}. + * + * <p> This method otherwise behaves exactly as specified by the {@link + * Channel} interface. + * + * @throws IOException + * If an I/O error occurs + */ + @Override void close() throws IOException; + + /** * Joins a multicast group to begin receiving all datagrams sent to the group, * returning a membership key. * @@ -130,7 +146,7 @@ * 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#getSourceAddress source-specific}. + * 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 @@ -150,6 +166,8 @@ * @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 @@ -170,7 +188,7 @@ * 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#getSourceAddress + * The resulting membership key is {@link MembershipKey#sourceAddress * source-specific}. * * <p> Membership is <em>cumulative</em> and this method may be invoked @@ -196,7 +214,8 @@ * If the channel is currently a member of the group on the given * interface to receive all datagrams * @throws UnsupportedOperationException - * If the underlying operation system does not support source filtering + * 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
--- a/jdk/src/share/classes/java/nio/channels/NetworkChannel.java Fri Feb 27 10:54:11 2009 -0800 +++ b/jdk/src/share/classes/java/nio/channels/NetworkChannel.java Wed Jul 05 16:48:18 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2007-2009 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 @@ -95,9 +95,10 @@ * java.net.InetSocketAddress}. * * @return The socket address that the socket is bound to, or {@code null} - * if the channel is not {@link #isOpen open} or the channel's socket - * is not bound + * if the channel's socket is not bound * + * @throws ClosedChannelException + * If the channel is closed * @throws IOException * If an I/O error occurs */ @@ -114,9 +115,10 @@ * * @return This channel * + * @throws UnsupportedOperationException + * If the socket option is not supported by this channel * @throws IllegalArgumentException - * If the socket option is not supported by this channel, or - * the value is not a valid value for this socket option + * If the value is not a valid value for this socket option * @throws ClosedChannelException * If this channel is closed * @throws IOException @@ -135,7 +137,7 @@ * @return The value of the socket option. A value of {@code null} may be * a valid value for some socket options. * - * @throws IllegalArgumentException + * @throws UnsupportedOperationException * If the socket option is not supported by this channel * @throws ClosedChannelException * If this channel is closed @@ -154,5 +156,5 @@ * * @return A set of the socket options supported by this channel */ - Set<SocketOption<?>> options(); + Set<SocketOption<?>> supportedOptions(); }
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/src/share/classes/java/nio/channels/SeekableByteChannel.java Wed Jul 05 16:48:18 2017 +0200 @@ -0,0 +1,168 @@ +/* + * Copyright 2007-2009 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. + */ + +package java.nio.channels; + +import java.nio.ByteBuffer; +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. + */ + @Override + 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. + */ + @Override + 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 position(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 truncate(long size) throws IOException; +}
--- a/jdk/src/share/classes/java/nio/channels/ServerSocketChannel.java Fri Feb 27 10:54:11 2009 -0800 +++ b/jdk/src/share/classes/java/nio/channels/ServerSocketChannel.java Wed Jul 05 16:48:18 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 2000-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2000-2009 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 @@ -29,7 +29,8 @@ import java.net.ServerSocket; import java.net.SocketOption; import java.net.SocketAddress; -import java.nio.channels.spi.*; +import java.nio.channels.spi.AbstractSelectableChannel; +import java.nio.channels.spi.SelectorProvider; /** * A selectable channel for stream-oriented listening sockets. @@ -195,6 +196,7 @@ throws IOException; /** + * @throws UnsupportedOperationException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} * @throws ClosedChannelException {@inheritDoc} * @throws IOException {@inheritDoc}
--- a/jdk/src/share/classes/java/nio/channels/SocketChannel.java Fri Feb 27 10:54:11 2009 -0800 +++ b/jdk/src/share/classes/java/nio/channels/SocketChannel.java Wed Jul 05 16:48:18 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 2000-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2000-2009 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 @@ -30,7 +30,8 @@ import java.net.SocketOption; import java.net.SocketAddress; import java.nio.ByteBuffer; -import java.nio.channels.spi.*; +import java.nio.channels.spi.AbstractSelectableChannel; +import java.nio.channels.spi.SelectorProvider; /** * A selectable channel for stream-oriented connecting sockets. @@ -212,7 +213,7 @@ /** * @throws ConnectionPendingException - * If a non-blocking connection operation is already in progress on + * If a non-blocking connect operation is already in progress on * this channel * @throws AlreadyBoundException {@inheritDoc} * @throws UnsupportedAddressTypeException {@inheritDoc} @@ -226,6 +227,7 @@ throws IOException; /** + * @throws UnsupportedOperationException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} * @throws ClosedChannelException {@inheritDoc} * @throws IOException {@inheritDoc} @@ -432,15 +434,17 @@ * 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 is not {@link - * #isOpen open} or the channel's socket is not 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 getConnectedAddress() throws IOException; + public abstract SocketAddress getRemoteAddress() throws IOException; // -- ByteChannel operations --
--- a/jdk/src/share/classes/java/nio/channels/exceptions Fri Feb 27 10:54:11 2009 -0800 +++ b/jdk/src/share/classes/java/nio/channels/exceptions Wed Jul 05 16:48:18 2017 +0200 @@ -1,5 +1,5 @@ # -# Copyright 2000-2008 Sun Microsystems, Inc. All Rights Reserved. +# Copyright 2000-2009 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 @@ -150,6 +150,21 @@ 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 AlreadyBoundException " @@ -157,3 +172,23 @@ * network oriented channel that is already bound." \ 6796072983322737592L +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/jdk/src/share/classes/java/nio/channels/package-info.java Fri Feb 27 10:54:11 2009 -0800 +++ b/jdk/src/share/classes/java/nio/channels/package-info.java Wed Jul 05 16:48:18 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 2001-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2001-2009 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 @@ -46,6 +46,10 @@ * <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> @@ -218,12 +222,70 @@ * 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 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 java.nio.channels.AsynchronousSocketChannel}</tt></td> + * <td>An asynchronous channel to a stream-oriented connecting socket</td></tr> + * <tr><td valign=top><tt>{@link java.nio.channels.AsynchronousServerSocketChannel} </tt></td> + * <td>An asynchronous channel to a stream-oriented listening socket</td></tr> + * <tr><td valign=top><tt>{@link java.nio.channels.AsynchronousDatagramChannel}</tt></td> + * <td>An asynchronous channel to a datagram-oriented socket</td></tr> + * <tr><td valign=top><tt>{@link 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 java.nio.channels.AsynchronousChannelGroup}</tt></td> + * <td>A grouping of asynchronous channels for the purpose of resource sharing</td></tr> + * </table></blockquote> + * + * <p> {@link 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 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 java.nio.channels.AsynchronousFileChannel} class + * for asynchronous reading, writing, and manipulating a file. As with the {@link + * 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 */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/src/share/classes/java/nio/channels/spi/AsynchronousChannelProvider.java Wed Jul 05 16:48:18 2017 +0200 @@ -0,0 +1,264 @@ +/* + * Copyright 2007-2009 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. + */ + +package java.nio.channels.spi; + +import java.nio.channels.*; +import java.net.ProtocolFamily; +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; + +/** + * 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 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()); + } + + // lazy initialization of default provider + private static class ProviderHolder { + static final AsynchronousChannelProvider provider = load(); + + private static AsynchronousChannelProvider load() { + return AccessController + .doPrivileged(new PrivilegedAction<AsynchronousChannelProvider>() { + public AsynchronousChannelProvider run() { + AsynchronousChannelProvider p; + p = loadProviderFromProperty(); + if (p != null) + return p; + p = loadProviderAsService(); + if (p != null) + return p; + return sun.nio.ch.DefaultAsynchronousChannelProvider.create(); + }}); + } + + private static AsynchronousChannelProvider loadProviderFromProperty() { + String cn = System.getProperty("java.nio.channels.spi.AsynchronousChannelProvider"); + if (cn == null) + return null; + try { + Class<?> c = Class.forName(cn, true, + ClassLoader.getSystemClassLoader()); + return (AsynchronousChannelProvider)c.newInstance(); + } 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 AsynchronousChannelProvider loadProviderAsService() { + ServiceLoader<AsynchronousChannelProvider> sl = + ServiceLoader.load(AsynchronousChannelProvider.class, + ClassLoader.getSystemClassLoader()); + Iterator<AsynchronousChannelProvider> i = sl.iterator(); + for (;;) { + try { + return (i.hasNext()) ? i.next() : null; + } 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() { + return ProviderHolder.provider; + } + + /** + * Constructs a new asynchronous channel group with a fixed thread pool. + * + * @param nThreads + * The number of threads in the pool + * @param threadFactory + * The factory to use when creating new threads + * + * @throws IllegalArgumentException + * If {@code nThreads <= 0} + * @throws IOException + * If an I/O error occurs + * + * @see AsynchronousChannelGroup#withFixedThreadPool + */ + public abstract AsynchronousChannelGroup + openAsynchronousChannelGroup(int nThreads, ThreadFactory threadFactory) throws IOException; + + /** + * Constructs a new asynchronous channel group with the given thread pool. + * + * @param executor + * The thread pool + * @param initialSize + * A value {@code >=0} or a negative value for implementation + * specific default + * + * @throws IOException + * If an I/O error occurs + * + * @see AsynchronousChannelGroup#withCachedThreadPool + */ + public abstract AsynchronousChannelGroup + openAsynchronousChannelGroup(ExecutorService executor, int initialSize) throws IOException; + + /** + * 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/jdk/src/share/classes/java/nio/channels/spi/SelectorProvider.java Fri Feb 27 10:54:11 2009 -0800 +++ b/jdk/src/share/classes/java/nio/channels/spi/SelectorProvider.java Wed Jul 05 16:48:18 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 2000-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2000-2009 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 @@ -89,8 +89,8 @@ if (cn == null) return false; try { - Class c = Class.forName(cn, true, - ClassLoader.getSystemClassLoader()); + Class<?> c = Class.forName(cn, true, + ClassLoader.getSystemClassLoader()); provider = (SelectorProvider)c.newInstance(); return true; } catch (ClassNotFoundException x) {
--- a/jdk/src/share/classes/java/nio/channels/spi/package.html Fri Feb 27 10:54:11 2009 -0800 +++ b/jdk/src/share/classes/java/nio/channels/spi/package.html Wed Jul 05 16:48:18 2017 +0200 @@ -1,5 +1,5 @@ <!-- - Copyright 2000-2005 Sun Microsystems, Inc. All Rights Reserved. + Copyright 2000-2009 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 @@ -29,8 +29,8 @@ Service-provider classes for the <tt>{@link java.nio.channels}</tt> package. -<p> Only developers who are defining new selector providers should need to make -direct use of this package. </p> +<p> Only developers who are defining new selector providers or 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
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/src/share/classes/java/nio/file/AccessDeniedException.java Wed Jul 05 16:48:18 2017 +0200 @@ -0,0 +1,68 @@ +/* + * Copyright 2007-2009 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. + */ + +package 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/jdk/src/share/classes/java/nio/file/AccessMode.java Wed Jul 05 16:48:18 2017 +0200 @@ -0,0 +1,49 @@ +/* + * Copyright 2007-2009 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. + */ + +package 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/jdk/src/share/classes/java/nio/file/AtomicMoveNotSupportedException.java Wed Jul 05 16:48:18 2017 +0200 @@ -0,0 +1,56 @@ +/* + * Copyright 2007-2009 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. + */ + +package 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/jdk/src/share/classes/java/nio/file/ClosedDirectoryStreamException.java Wed Jul 05 16:48:18 2017 +0200 @@ -0,0 +1,45 @@ +/* + * Copyright 2007-2009 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. + */ + +package 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/jdk/src/share/classes/java/nio/file/ClosedFileSystemException.java Wed Jul 05 16:48:18 2017 +0200 @@ -0,0 +1,43 @@ +/* + * Copyright 2007-2009 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. + */ + +package 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/jdk/src/share/classes/java/nio/file/ClosedWatchServiceException.java Wed Jul 05 16:48:18 2017 +0200 @@ -0,0 +1,43 @@ +/* + * Copyright 2007-2009 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. + */ + +package 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/jdk/src/share/classes/java/nio/file/CopyOption.java Wed Jul 05 16:48:18 2017 +0200 @@ -0,0 +1,41 @@ +/* + * Copyright 2007-2009 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. + */ + +package 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/jdk/src/share/classes/java/nio/file/DirectoryNotEmptyException.java Wed Jul 05 16:48:18 2017 +0200 @@ -0,0 +1,49 @@ +/* + * Copyright 2007-2009 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. + */ + +package 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/jdk/src/share/classes/java/nio/file/DirectoryStream.java Wed Jul 05 16:48:18 2017 +0200 @@ -0,0 +1,138 @@ +/* + * Copyright 2007-2009 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. + */ + +package 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 the + * second thread may 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 accepted 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 + */ + @Override + Iterator<T> iterator(); +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/src/share/classes/java/nio/file/DirectoryStreamFilters.java Wed Jul 05 16:48:18 2017 +0200 @@ -0,0 +1,210 @@ +/* + * Copyright 2007-2009 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. + */ + +package 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>() { + @Override + 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>() { + @Override + 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>() { + @Override + 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>() { + @Override + public boolean accept(T entry) { + return !filter.accept(entry); + } + }; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/src/share/classes/java/nio/file/FileAction.java Wed Jul 05 16:48:18 2017 +0200 @@ -0,0 +1,64 @@ +/* + * Copyright 2007-2009 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. + */ + +package 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/jdk/src/share/classes/java/nio/file/FileAlreadyExistsException.java Wed Jul 05 16:48:18 2017 +0200 @@ -0,0 +1,63 @@ +/* + * Copyright 2007-2009 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. + */ + +package 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/jdk/src/share/classes/java/nio/file/FileRef.java Wed Jul 05 16:48:18 2017 +0200 @@ -0,0 +1,424 @@ +/* + * Copyright 2007-2009 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. + */ + +package java.nio.file; + +import java.nio.file.attribute.*; +import java.nio.channels.SeekableByteChannel; +import java.io.IOException; + +/** + * 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, and in + * addition it checks {@link RuntimePermission}<tt> + * ("getFileStoreAttributes")</tt>