Skip to content

Commit b998d34

Browse files
committed
Merge remote-tracking branch 'origin/master'
2 parents 5b73831 + cdb6dfd commit b998d34

57 files changed

Lines changed: 1899 additions & 73 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package com.baeldung.generics;
2+
3+
import java.util.ArrayList;
4+
import java.util.Arrays;
5+
import java.util.List;
6+
7+
public class Generics {
8+
9+
// definition of a generic method
10+
public static <T> List<T> fromArrayToList(T[] a) {
11+
List<T> list = new ArrayList<>();
12+
Arrays.stream(a).forEach(list::add);
13+
return list;
14+
}
15+
16+
// example of a generic method that has Number as an upper bound for T
17+
public static <T extends Number> List<T> fromArrayToListWithUpperBound(T[] a) {
18+
List<T> list = new ArrayList<>();
19+
Arrays.stream(a).forEach(list::add);
20+
return list;
21+
}
22+
23+
}
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: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package com.baeldung.generics;
2+
3+
import org.junit.Test;
4+
5+
import java.util.List;
6+
7+
import static org.hamcrest.CoreMatchers.hasItems;
8+
import static org.hamcrest.MatcherAssert.assertThat;
9+
10+
public class GenericsTest {
11+
12+
// testing the generic method with Integer
13+
@Test
14+
public void givenArrayOfIntegers_thanListOfIntegersReturnedOK() {
15+
Integer[] intArray = {1, 2, 3, 4, 5};
16+
List<Integer> list = Generics.fromArrayToList(intArray);
17+
18+
assertThat(list, hasItems(intArray));
19+
}
20+
21+
// testing the generic method with String
22+
@Test
23+
public void givenArrayOfStrings_thanListOfStringsReturnedOK() {
24+
String[] stringArray = {"hello1", "hello2", "hello3", "hello4", "hello5"};
25+
List<String> list = Generics.fromArrayToList(stringArray);
26+
27+
assertThat(list, hasItems(stringArray));
28+
}
29+
30+
// testing the generic method with Number as upper bound with Integer
31+
// if we test fromArrayToListWithUpperBound with any type that doesn't
32+
// extend Number it will fail to compile
33+
@Test
34+
public void givenArrayOfIntegersAndNumberUpperBound_thanListOfIntegersReturnedOK() {
35+
Integer[] intArray = {1, 2, 3, 4, 5};
36+
List<Integer> list = Generics.fromArrayToListWithUpperBound(intArray);
37+
38+
assertThat(list, hasItems(intArray));
39+
}
40+
41+
}
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+
}

0 commit comments

Comments
 (0)