Skip to content

Commit cdb6dfd

Browse files
Egima profilepivovarit
authored andcommitted
asyncronous channel apis (eugenp#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
1 parent cbd22b9 commit cdb6dfd

9 files changed

Lines changed: 610 additions & 0 deletions

File tree

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
package com.baeldung.java.nio2.visitor;
2+
3+
import static java.nio.file.FileVisitResult.CONTINUE;
4+
import static java.nio.file.FileVisitResult.TERMINATE;
5+
6+
import java.io.IOException;
7+
import java.nio.file.FileVisitResult;
8+
import java.nio.file.FileVisitor;
9+
import java.nio.file.Files;
10+
import java.nio.file.Path;
11+
import java.nio.file.Paths;
12+
import java.nio.file.attribute.BasicFileAttributes;
13+
14+
public class FileSearchExample implements FileVisitor<Path> {
15+
private static String FILE_NAME;
16+
private static Path START_DIR;
17+
18+
public FileSearchExample(String fileName, Path startingDir) {
19+
FILE_NAME = fileName;
20+
START_DIR = startingDir;
21+
}
22+
23+
@Override
24+
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
25+
return CONTINUE;
26+
}
27+
28+
@Override
29+
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
30+
String fileName = file.getFileName().toString();
31+
if (FILE_NAME.equals(fileName)) {
32+
System.out.println("File found: " + file.toString());
33+
return TERMINATE;
34+
}
35+
return CONTINUE;
36+
}
37+
38+
@Override
39+
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
40+
System.out.println("Failed to access file: " + file.toString());
41+
return CONTINUE;
42+
}
43+
44+
@Override
45+
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
46+
boolean finishedSearch = Files.isSameFile(dir, START_DIR);
47+
if (finishedSearch) {
48+
System.out.println("File:" + FILE_NAME + " not found");
49+
return TERMINATE;
50+
}
51+
return CONTINUE;
52+
}
53+
54+
public static void main(String[] args) throws IOException {
55+
Path startingDir = Paths.get("C:/Users/new/Desktop");
56+
FileSearchExample crawler = new FileSearchExample("hibernate.txt", startingDir);
57+
Files.walkFileTree(startingDir, crawler);
58+
}
59+
60+
}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package com.baeldung.java.nio2.visitor;
2+
3+
import java.io.IOException;
4+
import java.nio.file.FileVisitResult;
5+
import java.nio.file.FileVisitor;
6+
import java.nio.file.Path;
7+
import java.nio.file.attribute.BasicFileAttributes;
8+
9+
public class FileVisitorImpl implements FileVisitor<Path> {
10+
11+
@Override
12+
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
13+
return null;
14+
}
15+
16+
@Override
17+
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
18+
return null;
19+
}
20+
21+
@Override
22+
public FileVisitResult visitFileFailed(Path file, IOException exc) {
23+
return null;
24+
}
25+
26+
@Override
27+
public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
28+
return null;
29+
}
30+
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package com.baeldung.java.nio2.watcher;
2+
3+
import java.io.IOException;
4+
import java.nio.file.FileSystems;
5+
import java.nio.file.Path;
6+
import java.nio.file.Paths;
7+
import java.nio.file.StandardWatchEventKinds;
8+
import java.nio.file.WatchEvent;
9+
import java.nio.file.WatchKey;
10+
import java.nio.file.WatchService;
11+
12+
public class DirectoryWatcherExample {
13+
public static void main(String[] args) throws IOException, InterruptedException {
14+
WatchService watchService = FileSystems.getDefault().newWatchService();
15+
Path path = Paths.get(System.getProperty("user.home"));
16+
path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);
17+
WatchKey key;
18+
while ((key = watchService.take()) != null) {
19+
for (WatchEvent<?> event : key.pollEvents()) {
20+
System.out.println("Event kind:" + event.kind() + ". File affected: " + event.context() + ".");
21+
}
22+
key.reset();
23+
}
24+
}
25+
}
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
package com.baeldung.java.nio2.async;
2+
3+
import java.io.BufferedReader;
4+
import java.io.IOException;
5+
import java.io.InputStreamReader;
6+
import java.net.InetSocketAddress;
7+
import java.nio.ByteBuffer;
8+
import java.nio.channels.AsynchronousSocketChannel;
9+
import java.util.concurrent.ExecutionException;
10+
import java.util.concurrent.Future;
11+
12+
public class AsyncEchoClient {
13+
private AsynchronousSocketChannel client;
14+
private Future<Void> future;
15+
private static AsyncEchoClient instance;
16+
17+
private AsyncEchoClient() {
18+
try {
19+
client = AsynchronousSocketChannel.open();
20+
InetSocketAddress hostAddress = new InetSocketAddress("localhost", 4999);
21+
future = client.connect(hostAddress);
22+
start();
23+
24+
} catch (IOException e) {
25+
e.printStackTrace();
26+
}
27+
}
28+
29+
public static AsyncEchoClient getInstance() {
30+
if (instance == null)
31+
instance = new AsyncEchoClient();
32+
return instance;
33+
}
34+
35+
private void start() {
36+
try {
37+
future.get();
38+
} catch (InterruptedException | ExecutionException e) {
39+
e.printStackTrace();
40+
}
41+
}
42+
43+
public String sendMessage(String message) {
44+
byte[] byteMsg = new String(message).getBytes();
45+
ByteBuffer buffer = ByteBuffer.wrap(byteMsg);
46+
Future<Integer> writeResult = client.write(buffer);
47+
48+
while (!writeResult.isDone()) {
49+
// do nothing
50+
}
51+
buffer.flip();
52+
Future<Integer> readResult = client.read(buffer);
53+
while (!readResult.isDone()) {
54+
55+
}
56+
String echo = new String(buffer.array()).trim();
57+
buffer.clear();
58+
return echo;
59+
}
60+
61+
public void stop() {
62+
try {
63+
client.close();
64+
} catch (IOException e) {
65+
e.printStackTrace();
66+
}
67+
}
68+
69+
public static void main(String[] args) throws IOException {
70+
AsyncEchoClient client = AsyncEchoClient.getInstance();
71+
client.start();
72+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
73+
String line = null;
74+
System.out.println("Message to server:");
75+
while ((line = br.readLine()) != null) {
76+
String response = client.sendMessage(line);
77+
System.out.println("response from server: " + response);
78+
System.out.println("Message to server:");
79+
}
80+
}
81+
82+
}
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
package com.baeldung.java.nio2.async;
2+
3+
import java.io.File;
4+
import java.io.IOException;
5+
import java.net.InetSocketAddress;
6+
import java.nio.ByteBuffer;
7+
import java.nio.channels.AsynchronousServerSocketChannel;
8+
import java.nio.channels.AsynchronousSocketChannel;
9+
import java.util.concurrent.ExecutionException;
10+
import java.util.concurrent.Future;
11+
12+
public class AsyncEchoServer {
13+
private AsynchronousServerSocketChannel serverChannel;
14+
private Future<AsynchronousSocketChannel> acceptResult;
15+
private AsynchronousSocketChannel clientChannel;
16+
17+
public AsyncEchoServer() {
18+
try {
19+
serverChannel = AsynchronousServerSocketChannel.open();
20+
InetSocketAddress hostAddress = new InetSocketAddress("localhost", 4999);
21+
serverChannel.bind(hostAddress);
22+
acceptResult = serverChannel.accept();
23+
} catch (IOException e) {
24+
e.printStackTrace();
25+
}
26+
}
27+
28+
public void runServer() {
29+
try {
30+
clientChannel = acceptResult.get();
31+
if ((clientChannel != null) && (clientChannel.isOpen())) {
32+
while (true) {
33+
34+
ByteBuffer buffer = ByteBuffer.allocate(32);
35+
Future<Integer> readResult = clientChannel.read(buffer);
36+
37+
while (!readResult.isDone()) {
38+
// do nothing
39+
}
40+
41+
buffer.flip();
42+
String message = new String(buffer.array()).trim();
43+
if (message.equals("bye")) {
44+
break; // while loop
45+
}
46+
buffer = ByteBuffer.wrap(new String(message).getBytes());
47+
Future<Integer> writeResult = clientChannel.write(buffer);
48+
while (!writeResult.isDone()) {
49+
// do nothing
50+
}
51+
buffer.clear();
52+
53+
} // while()
54+
55+
clientChannel.close();
56+
serverChannel.close();
57+
58+
}
59+
} catch (InterruptedException | ExecutionException | IOException e) {
60+
e.printStackTrace();
61+
}
62+
63+
}
64+
65+
public static void main(String[] args) {
66+
AsyncEchoServer server = new AsyncEchoServer();
67+
server.runServer();
68+
}
69+
public static Process start() throws IOException, InterruptedException {
70+
String javaHome = System.getProperty("java.home");
71+
String javaBin = javaHome + File.separator + "bin" + File.separator + "java";
72+
String classpath = System.getProperty("java.class.path");
73+
String className = AsyncEchoServer.class.getCanonicalName();
74+
75+
ProcessBuilder builder = new ProcessBuilder(javaBin, "-cp", classpath, className);
76+
77+
return builder.start();
78+
}
79+
}
Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
package com.baeldung.java.nio2.async;
2+
3+
import java.io.File;
4+
import java.io.IOException;
5+
import java.net.InetSocketAddress;
6+
import java.nio.ByteBuffer;
7+
import java.nio.channels.AsynchronousServerSocketChannel;
8+
import java.nio.channels.AsynchronousSocketChannel;
9+
import java.nio.channels.CompletionHandler;
10+
import java.util.HashMap;
11+
import java.util.Map;
12+
13+
public class AsyncEchoServer2 {
14+
private AsynchronousServerSocketChannel serverChannel;
15+
private AsynchronousSocketChannel clientChannel;
16+
17+
public AsyncEchoServer2() {
18+
try {
19+
serverChannel = AsynchronousServerSocketChannel.open();
20+
InetSocketAddress hostAddress = new InetSocketAddress("localhost", 4999);
21+
serverChannel.bind(hostAddress);
22+
while (true) {
23+
24+
serverChannel.accept(null, new CompletionHandler<AsynchronousSocketChannel, Object>() {
25+
26+
@Override
27+
public void completed(AsynchronousSocketChannel result, Object attachment) {
28+
if (serverChannel.isOpen())
29+
serverChannel.accept(null, this);
30+
clientChannel = result;
31+
if ((clientChannel != null) && (clientChannel.isOpen())) {
32+
ReadWriteHandler handler = new ReadWriteHandler();
33+
ByteBuffer buffer = ByteBuffer.allocate(32);
34+
Map<String, Object> readInfo = new HashMap<>();
35+
readInfo.put("action", "read");
36+
readInfo.put("buffer", buffer);
37+
clientChannel.read(buffer, readInfo, handler);
38+
}
39+
}
40+
41+
@Override
42+
public void failed(Throwable exc, Object attachment) {
43+
// process error
44+
}
45+
});
46+
try {
47+
System.in.read();
48+
} catch (IOException e) {
49+
e.printStackTrace();
50+
}
51+
}
52+
} catch (IOException e) {
53+
e.printStackTrace();
54+
}
55+
}
56+
57+
class ReadWriteHandler implements CompletionHandler<Integer, Map<String, Object>> {
58+
59+
@Override
60+
public void completed(Integer result, Map<String, Object> attachment) {
61+
Map<String, Object> actionInfo = attachment;
62+
String action = (String) actionInfo.get("action");
63+
if ("read".equals(action)) {
64+
ByteBuffer buffer = (ByteBuffer) actionInfo.get("buffer");
65+
buffer.flip();
66+
actionInfo.put("action", "write");
67+
clientChannel.write(buffer, actionInfo, this);
68+
buffer.clear();
69+
} else if ("write".equals(action)) {
70+
ByteBuffer buffer = ByteBuffer.allocate(32);
71+
actionInfo.put("action", "read");
72+
actionInfo.put("buffer", buffer);
73+
clientChannel.read(buffer, actionInfo, this);
74+
}
75+
76+
}
77+
78+
@Override
79+
public void failed(Throwable exc, Map<String, Object> attachment) {
80+
81+
}
82+
83+
}
84+
85+
86+
public static void main(String[] args) {
87+
new AsyncEchoServer2();
88+
}
89+
90+
public static Process start() throws IOException, InterruptedException {
91+
String javaHome = System.getProperty("java.home");
92+
String javaBin = javaHome + File.separator + "bin" + File.separator + "java";
93+
String classpath = System.getProperty("java.class.path");
94+
String className = AsyncEchoServer2.class.getCanonicalName();
95+
96+
ProcessBuilder builder = new ProcessBuilder(javaBin, "-cp", classpath, className);
97+
98+
return builder.start();
99+
}
100+
}

0 commit comments

Comments
 (0)