asyncronous channel apis (#839)

* made changes to java reflection

* removed redundant method makeSound in Animal abstract class

* added project for play-framework article

* added project for regex

* changed regex project from own model to core-java

* added project for routing in play

* made changes to regex project

* refactored code for REST API with Play project

* refactored student store indexing to zero base

* added unit tests, removed bad names

* added NIO Selector project under core-java module

* requested changes made

* added project for nio2

* standardized exception based tests

* fixed exception based tests

* removed redundant files

* added network interface project

* used UUID other than timestamps

* fixed network interface tests

* removed filetest change

* made changes to NIO2 FileTest names

* added project for asyncronous channel apis

* added project for NIO2 advanced filesystems APIS
This commit is contained in:
Egima profile 2016-11-25 18:48:26 +03:00 committed by Grzegorz Piwowarek
parent cbd22b9ce5
commit cdb6dfd79e
9 changed files with 610 additions and 0 deletions

View File

@ -0,0 +1,60 @@
package com.baeldung.java.nio2.visitor;
import static java.nio.file.FileVisitResult.CONTINUE;
import static java.nio.file.FileVisitResult.TERMINATE;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
public class FileSearchExample implements FileVisitor<Path> {
private static String FILE_NAME;
private static Path START_DIR;
public FileSearchExample(String fileName, Path startingDir) {
FILE_NAME = fileName;
START_DIR = startingDir;
}
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
return CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
String fileName = file.getFileName().toString();
if (FILE_NAME.equals(fileName)) {
System.out.println("File found: " + file.toString());
return TERMINATE;
}
return CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
System.out.println("Failed to access file: " + file.toString());
return CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
boolean finishedSearch = Files.isSameFile(dir, START_DIR);
if (finishedSearch) {
System.out.println("File:" + FILE_NAME + " not found");
return TERMINATE;
}
return CONTINUE;
}
public static void main(String[] args) throws IOException {
Path startingDir = Paths.get("C:/Users/new/Desktop");
FileSearchExample crawler = new FileSearchExample("hibernate.txt", startingDir);
Files.walkFileTree(startingDir, crawler);
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.java.nio2.visitor;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
public class FileVisitorImpl implements FileVisitor<Path> {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
return null;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
return null;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) {
return null;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
return null;
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.java.nio2.watcher;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
public class DirectoryWatcherExample {
public static void main(String[] args) throws IOException, InterruptedException {
WatchService watchService = FileSystems.getDefault().newWatchService();
Path path = Paths.get(System.getProperty("user.home"));
path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);
WatchKey key;
while ((key = watchService.take()) != null) {
for (WatchEvent<?> event : key.pollEvents()) {
System.out.println("Event kind:" + event.kind() + ". File affected: " + event.context() + ".");
}
key.reset();
}
}
}

View File

@ -0,0 +1,82 @@
package com.baeldung.java.nio2.async;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
public class AsyncEchoClient {
private AsynchronousSocketChannel client;
private Future<Void> future;
private static AsyncEchoClient instance;
private AsyncEchoClient() {
try {
client = AsynchronousSocketChannel.open();
InetSocketAddress hostAddress = new InetSocketAddress("localhost", 4999);
future = client.connect(hostAddress);
start();
} catch (IOException e) {
e.printStackTrace();
}
}
public static AsyncEchoClient getInstance() {
if (instance == null)
instance = new AsyncEchoClient();
return instance;
}
private void start() {
try {
future.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
public String sendMessage(String message) {
byte[] byteMsg = new String(message).getBytes();
ByteBuffer buffer = ByteBuffer.wrap(byteMsg);
Future<Integer> writeResult = client.write(buffer);
while (!writeResult.isDone()) {
// do nothing
}
buffer.flip();
Future<Integer> readResult = client.read(buffer);
while (!readResult.isDone()) {
}
String echo = new String(buffer.array()).trim();
buffer.clear();
return echo;
}
public void stop() {
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
AsyncEchoClient client = AsyncEchoClient.getInstance();
client.start();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = null;
System.out.println("Message to server:");
while ((line = br.readLine()) != null) {
String response = client.sendMessage(line);
System.out.println("response from server: " + response);
System.out.println("Message to server:");
}
}
}

View File

@ -0,0 +1,79 @@
package com.baeldung.java.nio2.async;
import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
public class AsyncEchoServer {
private AsynchronousServerSocketChannel serverChannel;
private Future<AsynchronousSocketChannel> acceptResult;
private AsynchronousSocketChannel clientChannel;
public AsyncEchoServer() {
try {
serverChannel = AsynchronousServerSocketChannel.open();
InetSocketAddress hostAddress = new InetSocketAddress("localhost", 4999);
serverChannel.bind(hostAddress);
acceptResult = serverChannel.accept();
} catch (IOException e) {
e.printStackTrace();
}
}
public void runServer() {
try {
clientChannel = acceptResult.get();
if ((clientChannel != null) && (clientChannel.isOpen())) {
while (true) {
ByteBuffer buffer = ByteBuffer.allocate(32);
Future<Integer> readResult = clientChannel.read(buffer);
while (!readResult.isDone()) {
// do nothing
}
buffer.flip();
String message = new String(buffer.array()).trim();
if (message.equals("bye")) {
break; // while loop
}
buffer = ByteBuffer.wrap(new String(message).getBytes());
Future<Integer> writeResult = clientChannel.write(buffer);
while (!writeResult.isDone()) {
// do nothing
}
buffer.clear();
} // while()
clientChannel.close();
serverChannel.close();
}
} catch (InterruptedException | ExecutionException | IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
AsyncEchoServer server = new AsyncEchoServer();
server.runServer();
}
public static Process start() throws IOException, InterruptedException {
String javaHome = System.getProperty("java.home");
String javaBin = javaHome + File.separator + "bin" + File.separator + "java";
String classpath = System.getProperty("java.class.path");
String className = AsyncEchoServer.class.getCanonicalName();
ProcessBuilder builder = new ProcessBuilder(javaBin, "-cp", classpath, className);
return builder.start();
}
}

View File

@ -0,0 +1,100 @@
package com.baeldung.java.nio2.async;
import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.HashMap;
import java.util.Map;
public class AsyncEchoServer2 {
private AsynchronousServerSocketChannel serverChannel;
private AsynchronousSocketChannel clientChannel;
public AsyncEchoServer2() {
try {
serverChannel = AsynchronousServerSocketChannel.open();
InetSocketAddress hostAddress = new InetSocketAddress("localhost", 4999);
serverChannel.bind(hostAddress);
while (true) {
serverChannel.accept(null, new CompletionHandler<AsynchronousSocketChannel, Object>() {
@Override
public void completed(AsynchronousSocketChannel result, Object attachment) {
if (serverChannel.isOpen())
serverChannel.accept(null, this);
clientChannel = result;
if ((clientChannel != null) && (clientChannel.isOpen())) {
ReadWriteHandler handler = new ReadWriteHandler();
ByteBuffer buffer = ByteBuffer.allocate(32);
Map<String, Object> readInfo = new HashMap<>();
readInfo.put("action", "read");
readInfo.put("buffer", buffer);
clientChannel.read(buffer, readInfo, handler);
}
}
@Override
public void failed(Throwable exc, Object attachment) {
// process error
}
});
try {
System.in.read();
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
class ReadWriteHandler implements CompletionHandler<Integer, Map<String, Object>> {
@Override
public void completed(Integer result, Map<String, Object> attachment) {
Map<String, Object> actionInfo = attachment;
String action = (String) actionInfo.get("action");
if ("read".equals(action)) {
ByteBuffer buffer = (ByteBuffer) actionInfo.get("buffer");
buffer.flip();
actionInfo.put("action", "write");
clientChannel.write(buffer, actionInfo, this);
buffer.clear();
} else if ("write".equals(action)) {
ByteBuffer buffer = ByteBuffer.allocate(32);
actionInfo.put("action", "read");
actionInfo.put("buffer", buffer);
clientChannel.read(buffer, actionInfo, this);
}
}
@Override
public void failed(Throwable exc, Map<String, Object> attachment) {
}
}
public static void main(String[] args) {
new AsyncEchoServer2();
}
public static Process start() throws IOException, InterruptedException {
String javaHome = System.getProperty("java.home");
String javaBin = javaHome + File.separator + "bin" + File.separator + "java";
String classpath = System.getProperty("java.class.path");
String className = AsyncEchoServer2.class.getCanonicalName();
ProcessBuilder builder = new ProcessBuilder(javaBin, "-cp", classpath, className);
return builder.start();
}
}

View File

@ -0,0 +1,36 @@
package com.baeldung.java.nio2.async;
import static org.junit.Assert.*;
import java.io.IOException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class AsyncEchoTest {
Process server;
AsyncEchoClient client;
@Before
public void setup() throws IOException, InterruptedException {
server = AsyncEchoServer2.start();
client = AsyncEchoClient.getInstance();
}
@Test
public void givenServerClient_whenServerEchosMessage_thenCorrect() {
String resp1 = client.sendMessage("hello");
String resp2 = client.sendMessage("world");
assertEquals("hello", resp1);
assertEquals("world", resp2);
}
@After
public void teardown() throws IOException {
server.destroy();
client.stop();
}
}

View File

@ -0,0 +1,130 @@
package com.baeldung.java.nio2.async;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.net.URI;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.UUID;
import java.util.concurrent.Future;
import org.junit.Test;
public class AsyncFileTest {
@Test
public void givenPath_whenReadsContentWithFuture_thenCorrect() throws IOException {
Path path = Paths.get(URI.create(new AsyncFileTest().getClass().getResource("/file.txt").toString()));
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ);
ByteBuffer buffer = ByteBuffer.allocate(1024);
Future<Integer> operation = fileChannel.read(buffer, 0);
while (!operation.isDone())
;
String fileContent = new String(buffer.array()).trim();
buffer.clear();
assertEquals(fileContent, "baeldung.com");
}
@Test
public void givenPath_whenReadsContentWithCompletionHandler_thenCorrect() throws IOException {
Path path = Paths.get(URI.create(new AsyncFileTest().getClass().getResource("/file.txt").toString()));
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ);
ByteBuffer buffer = ByteBuffer.allocate(1024);
fileChannel.read(buffer, 0, buffer, new CompletionHandler<Integer, ByteBuffer>() {
@Override
public void completed(Integer result, ByteBuffer attachment) {
// result is number of bytes read
// attachment is the buffer
}
@Override
public void failed(Throwable exc, ByteBuffer attachment) {
}
});
}
@Test
public void givenPathAndContent_whenWritesToFileWithFuture_thenCorrect() throws IOException {
String fileName = UUID.randomUUID().toString();
Path path = Paths.get(fileName);
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE, StandardOpenOption.CREATE,StandardOpenOption.DELETE_ON_CLOSE);
ByteBuffer buffer = ByteBuffer.allocate(1024);
long position = 0;
buffer.put("hello world".getBytes());
buffer.flip();
Future<Integer> operation = fileChannel.write(buffer, position);
buffer.clear();
while (!operation.isDone()) {
}
String content = readContent(path);
assertEquals("hello world", content);
}
@Test
public void givenPathAndContent_whenWritesToFileWithHandler_thenCorrect() throws IOException {
String fileName = UUID.randomUUID().toString();
Path path = Paths.get(fileName);
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE, StandardOpenOption.CREATE,StandardOpenOption.DELETE_ON_CLOSE);
ByteBuffer buffer = ByteBuffer.allocate(1024);
buffer.put("hello world".getBytes());
buffer.flip();
fileChannel.write(buffer, 0, buffer, new CompletionHandler<Integer, ByteBuffer>() {
@Override
public void completed(Integer result, ByteBuffer attachment) {
// result is number of bytes written
// attachment is the buffer
}
@Override
public void failed(Throwable exc, ByteBuffer attachment) {
}
});
}
public static String readContent(Path file) {
AsynchronousFileChannel fileChannel = null;
try {
fileChannel = AsynchronousFileChannel.open(file, StandardOpenOption.READ);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ByteBuffer buffer = ByteBuffer.allocate(1024);
Future<Integer> operation = fileChannel.read(buffer, 0);
while (!operation.isDone())
;
String fileContent = new String(buffer.array()).trim();
buffer.clear();
return fileContent;
}
}

View File

@ -0,0 +1,68 @@
package com.baeldung.java.nio2.attributes;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributeView;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import org.junit.Before;
import org.junit.Test;
public class BasicAttribsTest {
private static final String HOME = System.getProperty("user.home");
BasicFileAttributes basicAttribs;
@Before
public void setup() throws IOException {
Path home = Paths.get(HOME);
BasicFileAttributeView basicView = Files.getFileAttributeView(home, BasicFileAttributeView.class);
basicAttribs = basicView.readAttributes();
}
@Test
public void givenFileTimes_whenComparesThem_ThenCorrect() {
FileTime created = basicAttribs.creationTime();
FileTime modified = basicAttribs.lastModifiedTime();
FileTime accessed = basicAttribs.lastAccessTime();
assertTrue(0 > created.compareTo(accessed));
assertTrue(0 < modified.compareTo(created));
assertTrue(0 == created.compareTo(created));
}
@Test
public void givenPath_whenGetsFileSize_thenCorrect() {
long size = basicAttribs.size();
assertTrue(size > 0);
}
@Test
public void givenPath_whenChecksIfDirectory_thenCorrect() {
boolean isDir = basicAttribs.isDirectory();
assertTrue(isDir);
}
@Test
public void givenPath_whenChecksIfFile_thenCorrect() {
boolean isFile = basicAttribs.isRegularFile();
assertFalse(isFile);
}
@Test
public void givenPath_whenChecksIfSymLink_thenCorrect() {
boolean isSymLink = basicAttribs.isSymbolicLink();
assertFalse(isSymLink);
}
@Test
public void givenPath_whenChecksIfOther_thenCorrect() {
boolean isOther = basicAttribs.isOther();
assertFalse(isOther);
}
}