diff --git a/core-java/src/main/java/com/baeldung/java/nio2/visitor/FileSearchExample.java b/core-java/src/main/java/com/baeldung/java/nio2/visitor/FileSearchExample.java new file mode 100644 index 0000000000..15910abf9b --- /dev/null +++ b/core-java/src/main/java/com/baeldung/java/nio2/visitor/FileSearchExample.java @@ -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 { + 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); + } + +} diff --git a/core-java/src/main/java/com/baeldung/java/nio2/visitor/FileVisitorImpl.java b/core-java/src/main/java/com/baeldung/java/nio2/visitor/FileVisitorImpl.java new file mode 100644 index 0000000000..360d6d0689 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/java/nio2/visitor/FileVisitorImpl.java @@ -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 { + + @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; + } +} diff --git a/core-java/src/main/java/com/baeldung/java/nio2/watcher/DirectoryWatcherExample.java b/core-java/src/main/java/com/baeldung/java/nio2/watcher/DirectoryWatcherExample.java new file mode 100644 index 0000000000..ffc58a1c50 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/java/nio2/watcher/DirectoryWatcherExample.java @@ -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(); + } + } +} diff --git a/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoClient.java b/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoClient.java new file mode 100644 index 0000000000..ea35130f49 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoClient.java @@ -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 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 writeResult = client.write(buffer); + + while (!writeResult.isDone()) { + // do nothing + } + buffer.flip(); + Future 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:"); + } + } + +} diff --git a/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoServer.java b/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoServer.java new file mode 100644 index 0000000000..0e58cb5f10 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoServer.java @@ -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 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 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 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(); + } +} diff --git a/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoServer2.java b/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoServer2.java new file mode 100644 index 0000000000..03ce233ce9 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoServer2.java @@ -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() { + + @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 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> { + + @Override + public void completed(Integer result, Map attachment) { + Map 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 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(); + } +} diff --git a/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoTest.java b/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoTest.java new file mode 100644 index 0000000000..7ac388fb09 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoTest.java @@ -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(); + } + +} diff --git a/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncFileTest.java b/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncFileTest.java new file mode 100644 index 0000000000..db30d32210 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncFileTest.java @@ -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 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() { + + @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 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() { + + @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 operation = fileChannel.read(buffer, 0); + + while (!operation.isDone()) + ; + + String fileContent = new String(buffer.array()).trim(); + buffer.clear(); + return fileContent; + } +} diff --git a/core-java/src/test/java/com/baeldung/java/nio2/attributes/BasicAttribsTest.java b/core-java/src/test/java/com/baeldung/java/nio2/attributes/BasicAttribsTest.java new file mode 100644 index 0000000000..dcc24c6415 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/nio2/attributes/BasicAttribsTest.java @@ -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); + } +}