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/file/FileOperationsUnitTest.java b/core-java/src/test/java/com/baeldung/file/FileOperationsUnitTest.java index 3319716dc6..16d0cb570b 100644 --- a/core-java/src/test/java/com/baeldung/file/FileOperationsUnitTest.java +++ b/core-java/src/test/java/com/baeldung/file/FileOperationsUnitTest.java @@ -1,11 +1,12 @@ package com.baeldung.file; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; +import org.apache.commons.io.FileUtils; +import org.hamcrest.CoreMatchers; +import org.hamcrest.Matchers; +import org.junit.Assert; +import org.junit.Test; + +import java.io.*; import java.net.URISyntaxException; import java.net.URL; import java.net.URLConnection; @@ -14,12 +15,6 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.stream.Stream; -import org.apache.commons.io.FileUtils; -import org.hamcrest.CoreMatchers; -import org.hamcrest.Matchers; -import org.junit.Assert; -import org.junit.Test; - public class FileOperationsUnitTest { @Test @@ -58,9 +53,9 @@ public class FileOperationsUnitTest { @Test public void givenURLName_whenUsingURL_thenFileData() throws IOException { - String expectedData = "Baeldung"; + String expectedData = "Example Domain"; - URL urlObject = new URL("http://www.baeldung.com/"); + URL urlObject = new URL("http://www.example.com/"); URLConnection urlConnection = urlObject.openConnection(); 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..172d8036de --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncEchoServer2.java @@ -0,0 +1,99 @@ +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) { + String action = (String) attachment.get("action"); + if ("read".equals(action)) { + ByteBuffer buffer = (ByteBuffer) attachment.get("buffer"); + buffer.flip(); + attachment.put("action", "write"); + clientChannel.write(buffer, attachment, this); + buffer.clear(); + } else if ("write".equals(action)) { + ByteBuffer buffer = ByteBuffer.allocate(32); + attachment.put("action", "read"); + attachment.put("buffer", buffer); + clientChannel.read(buffer, attachment, 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..b03acf83ca --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/nio2/async/AsyncFileTest.java @@ -0,0 +1,127 @@ +package com.baeldung.java.nio2.async; + +import org.junit.Test; + +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.ExecutionException; +import java.util.concurrent.Future; + +import static org.junit.Assert.assertEquals; + +public class AsyncFileTest { + @Test + public void givenPath_whenReadsContentWithFuture_thenCorrect() throws IOException, ExecutionException, InterruptedException { + Path path = Paths.get(URI.create(this.getClass().getClassLoader().getResource("file.txt").toString())); + AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ); + + ByteBuffer buffer = ByteBuffer.allocate(1024); + + Future operation = fileChannel.read(buffer, 0); + + operation.get(); + + 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(AsyncFileTest.class.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, ExecutionException, InterruptedException { + String fileName = "temp"; + Path path = Paths.get(fileName); + AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE, StandardOpenOption.CREATE); + + ByteBuffer buffer = ByteBuffer.allocate(1024); + long position = 0; + + buffer.put("hello world".getBytes()); + buffer.flip(); + + Future operation = fileChannel.write(buffer, position); + buffer.clear(); + + operation.get(); + + 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) throws ExecutionException, InterruptedException { + 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); + + operation.get(); + + 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..05686e79c0 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/nio2/attributes/BasicAttribsTest.java @@ -0,0 +1,69 @@ +package com.baeldung.java.nio2.attributes; + +import org.junit.BeforeClass; +import org.junit.Test; + +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 static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class BasicAttribsTest { + private static final String HOME = System.getProperty("user.home"); + private static BasicFileAttributes basicAttribs; + + @BeforeClass + public static 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(); + + System.out.println("Created: " + created); + System.out.println("Modified: " + modified); + System.out.println("Accessed: " + accessed); + + } + + @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); + } +} diff --git a/core-java/src/test/java/org/baeldung/java/collections/CollectionsConcatenateUnitTest.java b/core-java/src/test/java/org/baeldung/java/collections/CollectionsConcatenateUnitTest.java index 3ee08767bd..0d913db1bd 100644 --- a/core-java/src/test/java/org/baeldung/java/collections/CollectionsConcatenateUnitTest.java +++ b/core-java/src/test/java/org/baeldung/java/collections/CollectionsConcatenateUnitTest.java @@ -1,21 +1,15 @@ package org.baeldung.java.collections; -import static java.util.Arrays.asList; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.NoSuchElementException; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import org.junit.Assert; -import org.junit.Test; - import com.google.common.collect.Iterables; import com.google.common.collect.Lists; +import org.junit.Assert; +import org.junit.Test; + +import java.util.*; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static java.util.Arrays.asList; public class CollectionsConcatenateUnitTest { @@ -63,16 +57,16 @@ public class CollectionsConcatenateUnitTest { Assert.assertEquals(Arrays.asList("S", "T", "U", "V"), collectionCombined); } - public static Iterable concat(Iterable list1, Iterable list2) { + public static Iterable concat(Iterable i1, Iterable i2) { return new Iterable() { public Iterator iterator() { return new Iterator() { - protected Iterator listIterator = list1.iterator(); - protected Boolean checkedHasNext; - protected E nextValue; + Iterator listIterator = i1.iterator(); + Boolean checkedHasNext; + E nextValue; private boolean startTheSecond; - public void theNext() { + void theNext() { if (listIterator.hasNext()) { checkedHasNext = true; nextValue = listIterator.next(); @@ -80,7 +74,7 @@ public class CollectionsConcatenateUnitTest { checkedHasNext = false; else { startTheSecond = true; - listIterator = list2.iterator(); + listIterator = i2.iterator(); theNext(); } } @@ -107,7 +101,7 @@ public class CollectionsConcatenateUnitTest { } public static List makeListFromIterable(Iterable iter) { - List list = new ArrayList(); + List list = new ArrayList<>(); for (E item : iter) { list.add(item); } diff --git a/core-java/src/test/resources/file.txt b/core-java/src/test/resources/file.txt new file mode 100644 index 0000000000..558d8bbf35 --- /dev/null +++ b/core-java/src/test/resources/file.txt @@ -0,0 +1 @@ +baeldung.com \ No newline at end of file diff --git a/pom.xml b/pom.xml index b8d0303160..77cf615a98 100644 --- a/pom.xml +++ b/pom.xml @@ -109,6 +109,7 @@ spring-katharsis spring-mockito spring-mvc-java + spring-mvc-forms spring-mvc-no-xml spring-mvc-tiles spring-mvc-velocity diff --git a/spring-core/src/main/java/com/baeldung/factorybean/FactoryBeanAppConfig.java b/spring-core/src/main/java/com/baeldung/factorybean/FactoryBeanAppConfig.java index 40e181b7a7..02eef57e3d 100644 --- a/spring-core/src/main/java/com/baeldung/factorybean/FactoryBeanAppConfig.java +++ b/spring-core/src/main/java/com/baeldung/factorybean/FactoryBeanAppConfig.java @@ -7,20 +7,15 @@ import org.springframework.context.annotation.Configuration; public class FactoryBeanAppConfig { @Bean - public ToolFactory tool() { + public ToolFactory toolFactory() { ToolFactory factory = new ToolFactory(); factory.setFactoryId(7070); factory.setToolId(2); - factory.setToolName("wrench"); - factory.setToolPrice(3.7); return factory; } @Bean - public Worker worker() throws Exception { - Worker worker = new Worker(); - worker.setNumber("1002"); - worker.setTool(tool().getObject()); - return worker; + public Tool tool() throws Exception { + return toolFactory().getObject(); } } diff --git a/spring-core/src/main/java/com/baeldung/factorybean/InitializationToolFactory.java b/spring-core/src/main/java/com/baeldung/factorybean/InitializationToolFactory.java deleted file mode 100644 index 15e2b01f49..0000000000 --- a/spring-core/src/main/java/com/baeldung/factorybean/InitializationToolFactory.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.baeldung.factorybean; - -import static com.google.common.base.Preconditions.checkArgument; - -import org.springframework.beans.factory.FactoryBean; -import org.springframework.beans.factory.InitializingBean; -import org.springframework.util.StringUtils; - -public class InitializationToolFactory implements FactoryBean, InitializingBean { - - private int factoryId; - private int toolId; - private String toolName; - private double toolPrice; - - @Override - public void afterPropertiesSet() throws Exception { - checkArgument(!StringUtils.isEmpty(toolName), "tool name cannot be empty"); - checkArgument(toolPrice >= 0, "tool price should not be less than 0"); - } - - @Override - public Tool getObject() throws Exception { - return new Tool(toolId, toolName, toolPrice); - } - - @Override - public Class getObjectType() { - return Tool.class; - } - - @Override - public boolean isSingleton() { - return false; - } - - public int getFactoryId() { - return factoryId; - } - - public void setFactoryId(int factoryId) { - this.factoryId = factoryId; - } - - public int getToolId() { - return toolId; - } - - public void setToolId(int toolId) { - this.toolId = toolId; - } - - public String getToolName() { - return toolName; - } - - public void setToolName(String toolName) { - this.toolName = toolName; - } - - public double getToolPrice() { - return toolPrice; - } - - public void setToolPrice(double toolPrice) { - this.toolPrice = toolPrice; - } -} diff --git a/spring-core/src/main/java/com/baeldung/factorybean/NonSingleToolFactory.java b/spring-core/src/main/java/com/baeldung/factorybean/NonSingleToolFactory.java index 158318649c..981df2206f 100644 --- a/spring-core/src/main/java/com/baeldung/factorybean/NonSingleToolFactory.java +++ b/spring-core/src/main/java/com/baeldung/factorybean/NonSingleToolFactory.java @@ -6,8 +6,6 @@ public class NonSingleToolFactory extends AbstractFactoryBean { private int factoryId; private int toolId; - private String toolName; - private double toolPrice; public NonSingleToolFactory() { setSingleton(false); @@ -20,7 +18,7 @@ public class NonSingleToolFactory extends AbstractFactoryBean { @Override protected Tool createInstance() throws Exception { - return new Tool(toolId, toolName, toolPrice); + return new Tool(toolId); } public int getFactoryId() { @@ -38,20 +36,4 @@ public class NonSingleToolFactory extends AbstractFactoryBean { public void setToolId(int toolId) { this.toolId = toolId; } - - public String getToolName() { - return toolName; - } - - public void setToolName(String toolName) { - this.toolName = toolName; - } - - public double getToolPrice() { - return toolPrice; - } - - public void setToolPrice(double toolPrice) { - this.toolPrice = toolPrice; - } } diff --git a/spring-core/src/main/java/com/baeldung/factorybean/PostConstructToolFactory.java b/spring-core/src/main/java/com/baeldung/factorybean/PostConstructToolFactory.java deleted file mode 100644 index 696545a70a..0000000000 --- a/spring-core/src/main/java/com/baeldung/factorybean/PostConstructToolFactory.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.baeldung.factorybean; - -import static com.google.common.base.Preconditions.checkArgument; - -import javax.annotation.PostConstruct; - -import org.springframework.beans.factory.FactoryBean; -import org.springframework.util.StringUtils; - -public class PostConstructToolFactory implements FactoryBean { - - private int factoryId; - private int toolId; - private String toolName; - private double toolPrice; - - @Override - public Tool getObject() throws Exception { - return new Tool(toolId, toolName, toolPrice); - } - - @Override - public Class getObjectType() { - return Tool.class; - } - - @Override - public boolean isSingleton() { - return false; - } - - @PostConstruct - public void checkParams() { - checkArgument(!StringUtils.isEmpty(toolName), "tool name cannot be empty"); - checkArgument(toolPrice >= 0, "tool price should not be less than 0"); - } - - public int getFactoryId() { - return factoryId; - } - - public void setFactoryId(int factoryId) { - this.factoryId = factoryId; - } - - public int getToolId() { - return toolId; - } - - public void setToolId(int toolId) { - this.toolId = toolId; - } - - public String getToolName() { - return toolName; - } - - public void setToolName(String toolName) { - this.toolName = toolName; - } - - public double getToolPrice() { - return toolPrice; - } - - public void setToolPrice(double toolPrice) { - this.toolPrice = toolPrice; - } -} diff --git a/spring-core/src/main/java/com/baeldung/factorybean/SingleToolFactory.java b/spring-core/src/main/java/com/baeldung/factorybean/SingleToolFactory.java index 37fd978a3c..76b87bbbbf 100644 --- a/spring-core/src/main/java/com/baeldung/factorybean/SingleToolFactory.java +++ b/spring-core/src/main/java/com/baeldung/factorybean/SingleToolFactory.java @@ -7,8 +7,6 @@ public class SingleToolFactory extends AbstractFactoryBean { private int factoryId; private int toolId; - private String toolName; - private double toolPrice; @Override public Class getObjectType() { @@ -17,7 +15,7 @@ public class SingleToolFactory extends AbstractFactoryBean { @Override protected Tool createInstance() throws Exception { - return new Tool(toolId, toolName, toolPrice); + return new Tool(toolId); } public int getFactoryId() { @@ -35,20 +33,4 @@ public class SingleToolFactory extends AbstractFactoryBean { public void setToolId(int toolId) { this.toolId = toolId; } - - public String getToolName() { - return toolName; - } - - public void setToolName(String toolName) { - this.toolName = toolName; - } - - public double getToolPrice() { - return toolPrice; - } - - public void setToolPrice(double toolPrice) { - this.toolPrice = toolPrice; - } } diff --git a/spring-core/src/main/java/com/baeldung/factorybean/Tool.java b/spring-core/src/main/java/com/baeldung/factorybean/Tool.java index 2a69cbaf2a..be56745b3d 100644 --- a/spring-core/src/main/java/com/baeldung/factorybean/Tool.java +++ b/spring-core/src/main/java/com/baeldung/factorybean/Tool.java @@ -1,15 +1,13 @@ package com.baeldung.factorybean; public class Tool { - private int id; - private String name; - private double price; - public Tool(int id, String name, double price) { + public Tool() { + } + + public Tool(int id) { this.id = id; - this.name = name; - this.price = price; } public int getId() { @@ -19,20 +17,4 @@ public class Tool { public void setId(int id) { this.id = id; } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public double getPrice() { - return price; - } - - public void setPrice(double price) { - this.price = price; - } } diff --git a/spring-core/src/main/java/com/baeldung/factorybean/ToolFactory.java b/spring-core/src/main/java/com/baeldung/factorybean/ToolFactory.java index 5e6385c679..2a17574f8e 100644 --- a/spring-core/src/main/java/com/baeldung/factorybean/ToolFactory.java +++ b/spring-core/src/main/java/com/baeldung/factorybean/ToolFactory.java @@ -6,12 +6,10 @@ public class ToolFactory implements FactoryBean { private int factoryId; private int toolId; - private String toolName; - private double toolPrice; @Override public Tool getObject() throws Exception { - return new Tool(toolId, toolName, toolPrice); + return new Tool(toolId); } @Override @@ -39,20 +37,4 @@ public class ToolFactory implements FactoryBean { public void setToolId(int toolId) { this.toolId = toolId; } - - public String getToolName() { - return toolName; - } - - public void setToolName(String toolName) { - this.toolName = toolName; - } - - public double getToolPrice() { - return toolPrice; - } - - public void setToolPrice(double toolPrice) { - this.toolPrice = toolPrice; - } } diff --git a/spring-core/src/main/java/com/baeldung/factorybean/Worker.java b/spring-core/src/main/java/com/baeldung/factorybean/Worker.java deleted file mode 100644 index 0d1dc5d7d6..0000000000 --- a/spring-core/src/main/java/com/baeldung/factorybean/Worker.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.baeldung.factorybean; - -public class Worker { - - private String number; - private Tool tool; - - public Worker() {} - - public Worker(String number, Tool tool) { - this.number = number; - this.tool = tool; - } - - public String getNumber() { - return number; - } - - public void setNumber(String number) { - this.number = number; - } - - public Tool getTool() { - return tool; - } - - public void setTool(Tool tool) { - this.tool = tool; - } -} diff --git a/spring-core/src/main/resources/factorybean-abstract-spring-ctx.xml b/spring-core/src/main/resources/factorybean-abstract-spring-ctx.xml index 33b3051cae..a82b884ee5 100644 --- a/spring-core/src/main/resources/factorybean-abstract-spring-ctx.xml +++ b/spring-core/src/main/resources/factorybean-abstract-spring-ctx.xml @@ -6,34 +6,10 @@ - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/spring-core/src/main/resources/factorybean-init-spring-ctx.xml b/spring-core/src/main/resources/factorybean-init-spring-ctx.xml deleted file mode 100644 index 1ff492e5df..0000000000 --- a/spring-core/src/main/resources/factorybean-init-spring-ctx.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/spring-core/src/main/resources/factorybean-postconstruct-spring-ctx.xml b/spring-core/src/main/resources/factorybean-postconstruct-spring-ctx.xml deleted file mode 100644 index f34325160f..0000000000 --- a/spring-core/src/main/resources/factorybean-postconstruct-spring-ctx.xml +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/spring-core/src/main/resources/factorybean-spring-ctx.xml b/spring-core/src/main/resources/factorybean-spring-ctx.xml index 2987b67d94..3231fda676 100644 --- a/spring-core/src/main/resources/factorybean-spring-ctx.xml +++ b/spring-core/src/main/resources/factorybean-spring-ctx.xml @@ -6,12 +6,5 @@ - - - - - - - \ No newline at end of file diff --git a/spring-core/src/test/java/com/baeldung/factorybean/AbstractFactoryBeanTest.java b/spring-core/src/test/java/com/baeldung/factorybean/AbstractFactoryBeanTest.java index a7ba6d9a68..aa6d7c2cd2 100644 --- a/spring-core/src/test/java/com/baeldung/factorybean/AbstractFactoryBeanTest.java +++ b/spring-core/src/test/java/com/baeldung/factorybean/AbstractFactoryBeanTest.java @@ -4,33 +4,36 @@ import static org.hamcrest.core.IsEqual.equalTo; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; -import org.junit.Test; -import org.springframework.context.ApplicationContext; -import org.springframework.context.support.ClassPathXmlApplicationContext; +import javax.annotation.Resource; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations = { "classpath:factorybean-abstract-spring-ctx.xml" }) public class AbstractFactoryBeanTest { - + + @Resource(name = "singleTool") + private Tool tool1; + @Resource(name = "singleTool") + private Tool tool2; + @Resource(name = "nonSingleTool") + private Tool tool3; + @Resource(name = "nonSingleTool") + private Tool tool4; + @Test public void testSingleToolFactory() { - ApplicationContext context = new ClassPathXmlApplicationContext("classpath:factorybean-abstract-spring-ctx.xml"); - - Worker worker1 = (Worker) context.getBean("worker1"); - Worker worker2 = (Worker) context.getBean("worker2"); - - assertThat(worker1.getNumber(), equalTo("50001")); - assertThat(worker2.getNumber(), equalTo("50002")); - assertTrue(worker1.getTool() == worker2.getTool()); + assertThat(tool1.getId(), equalTo(1)); + assertTrue(tool1 == tool2); } @Test public void testNonSingleToolFactory() { - ApplicationContext context = new ClassPathXmlApplicationContext("classpath:factorybean-abstract-spring-ctx.xml"); - - Worker worker3 = (Worker) context.getBean("worker3"); - Worker worker4 = (Worker) context.getBean("worker4"); - - assertThat(worker3.getNumber(), equalTo("50003")); - assertThat(worker4.getNumber(), equalTo("50004")); - assertTrue(worker3.getTool() != worker4.getTool()); + assertThat(tool3.getId(), equalTo(2)); + assertThat(tool4.getId(), equalTo(2)); + assertTrue(tool3 != tool4); } } diff --git a/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanInitializeTest.java b/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanInitializeTest.java deleted file mode 100644 index 87947b148a..0000000000 --- a/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanInitializeTest.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.baeldung.factorybean; - -import org.junit.Test; -import org.springframework.beans.factory.BeanCreationException; -import org.springframework.context.support.ClassPathXmlApplicationContext; - -public class FactoryBeanInitializeTest { - - @Test(expected = BeanCreationException.class) - public void testInitializationToolFactory() { - new ClassPathXmlApplicationContext("classpath:factorybean-init-spring-ctx.xml"); - } - - @Test(expected = BeanCreationException.class) - public void testPostConstructToolFactory() { - new ClassPathXmlApplicationContext("classpath:factorybean-postconstruct-spring-ctx.xml"); - } -} diff --git a/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanJavaConfigTest.java b/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanJavaConfigTest.java new file mode 100644 index 0000000000..1bd1f3d234 --- /dev/null +++ b/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanJavaConfigTest.java @@ -0,0 +1,27 @@ +package com.baeldung.factorybean; + +import static org.hamcrest.core.IsEqual.equalTo; +import static org.junit.Assert.assertThat; + +import javax.annotation.Resource; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = FactoryBeanAppConfig.class) +public class FactoryBeanJavaConfigTest { + + @Resource + private Tool tool; + @Resource(name = "&toolFactory") + private ToolFactory toolFactory; + + @Test + public void testConstructWorkerByJava() { + assertThat(tool.getId(), equalTo(2)); + assertThat(toolFactory.getFactoryId(), equalTo(7070)); + } +} diff --git a/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanTest.java b/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanTest.java deleted file mode 100644 index f35503794a..0000000000 --- a/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanTest.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.baeldung.factorybean; - -import static org.hamcrest.core.IsEqual.equalTo; -import static org.junit.Assert.assertThat; - -import org.junit.Test; -import org.springframework.context.ApplicationContext; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.springframework.context.support.ClassPathXmlApplicationContext; - -public class FactoryBeanTest { - - @Test - public void testConstructWorkerByXml() { - ApplicationContext context = new ClassPathXmlApplicationContext("classpath:factorybean-spring-ctx.xml"); - - Worker worker = (Worker) context.getBean("worker"); - assertThat(worker.getNumber(), equalTo("1001")); - assertThat(worker.getTool().getId(), equalTo(1)); - assertThat(worker.getTool().getName(), equalTo("screwdriver")); - assertThat(worker.getTool().getPrice(), equalTo(1.5)); - - ToolFactory toolFactory = (ToolFactory) context.getBean("&tool"); - assertThat(toolFactory.getFactoryId(), equalTo(9090)); - } - - @Test - public void testConstructWorkerByJava() { - ApplicationContext context = new AnnotationConfigApplicationContext(FactoryBeanAppConfig.class); - - Worker worker = (Worker) context.getBean("worker"); - assertThat(worker.getNumber(), equalTo("1002")); - assertThat(worker.getTool().getId(), equalTo(2)); - assertThat(worker.getTool().getName(), equalTo("wrench")); - assertThat(worker.getTool().getPrice(), equalTo(3.7)); - - ToolFactory toolFactory = (ToolFactory) context.getBean("&tool"); - assertThat(toolFactory.getFactoryId(), equalTo(7070)); - } -} diff --git a/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanXmlConfigTest.java b/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanXmlConfigTest.java new file mode 100644 index 0000000000..b479b231d9 --- /dev/null +++ b/spring-core/src/test/java/com/baeldung/factorybean/FactoryBeanXmlConfigTest.java @@ -0,0 +1,27 @@ +package com.baeldung.factorybean; + +import static org.hamcrest.core.IsEqual.equalTo; +import static org.junit.Assert.assertThat; + +import javax.annotation.Resource; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations = { "classpath:factorybean-spring-ctx.xml" }) +public class FactoryBeanXmlConfigTest { + + @Resource + private Tool tool; + @Resource(name = "&tool") + private ToolFactory toolFactory; + + @Test + public void testConstructWorkerByXml() { + assertThat(tool.getId(), equalTo(1)); + assertThat(toolFactory.getFactoryId(), equalTo(9090)); + } +} diff --git a/spring-mvc-forms/pom.xml b/spring-mvc-forms/pom.xml new file mode 100644 index 0000000000..370fd7feb2 --- /dev/null +++ b/spring-mvc-forms/pom.xml @@ -0,0 +1,99 @@ + + + + 4.0.0 + com.baeldung + 0.1-SNAPSHOT + spring-mvc-forms + + spring-mvc-forms + war + + + + org.springframework + spring-webmvc + ${springframework.version} + + + + javax.servlet + javax.servlet-api + ${javax.servlet-api.version} + + + + javax.servlet.jsp + javax.servlet.jsp-api + ${javax.servlet.jsp-api.version} + + + + javax.servlet + jstl + ${jstl.version} + + + + org.hibernate + hibernate-validator + ${hibernate-validator.version} + + + + + + + + spring-mvc-forms + + true + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${maven-compiler-plugin.source} + ${maven-compiler-plugin.source} + + + + + org.apache.maven.plugins + maven-war-plugin + ${maven-war-plugin.version} + + src/main/webapp + spring-mvc-forms + false + ${deploy-path} + + + + + + spring-mvc-forms + + + + + + 4.0.6.RELEASE + 2.4 + 1.2 + 2.3.1 + 3.1.0 + 3.5.1 + 1.8 + 5.1.1.Final + enter-location-of-server + + + + diff --git a/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/configuration/ApplicationConfiguration.java b/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/configuration/ApplicationConfiguration.java new file mode 100644 index 0000000000..998f070c02 --- /dev/null +++ b/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/configuration/ApplicationConfiguration.java @@ -0,0 +1,29 @@ +package com.baeldung.springmvcforms.configuration; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.view.InternalResourceViewResolver; + +@Configuration +@EnableWebMvc +@ComponentScan(basePackages = "com.baeldung.springmvcforms") +class ApplicationConfiguration extends WebMvcConfigurerAdapter { + + @Override + public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { + configurer.enable(); + } + + @Bean + public InternalResourceViewResolver jspViewResolver() { + InternalResourceViewResolver bean = new InternalResourceViewResolver(); + bean.setPrefix("/WEB-INF/views/"); + bean.setSuffix(".jsp"); + return bean; + } + +} diff --git a/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/configuration/WebInitializer.java b/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/configuration/WebInitializer.java new file mode 100644 index 0000000000..c602ea6454 --- /dev/null +++ b/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/configuration/WebInitializer.java @@ -0,0 +1,47 @@ +package com.baeldung.springmvcforms.configuration; + +import org.springframework.web.WebApplicationInitializer; +import org.springframework.web.context.ContextLoaderListener; +import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; +import org.springframework.web.servlet.DispatcherServlet; + +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.ServletRegistration; + +public class WebInitializer implements WebApplicationInitializer { + + public void onStartup(ServletContext container) throws ServletException { + + AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext(); + ctx.register(ApplicationConfiguration.class); + ctx.setServletContext(container); + + // Manage the lifecycle of the root application context + container.addListener(new ContextLoaderListener(ctx)); + + ServletRegistration.Dynamic servlet = container.addServlet("dispatcher", new DispatcherServlet(ctx)); + + servlet.setLoadOnStartup(1); + servlet.addMapping("/"); + } +// @Override +// public void onStartup(ServletContext container) { +// // Create the 'root' Spring application context +// AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext(); +// rootContext.register(ServiceConfig.class, JPAConfig.class, SecurityConfig.class); +// +// // Manage the lifecycle of the root application context +// container.addListener(new ContextLoaderListener(rootContext)); +// +// // Create the dispatcher servlet's Spring application context +// AnnotationConfigWebApplicationContext dispatcherServlet = new AnnotationConfigWebApplicationContext(); +// dispatcherServlet.register(MvcConfig.class); +// +// // Register and map the dispatcher servlet +// ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(dispatcherServlet)); +// dispatcher.setLoadOnStartup(1); +// dispatcher.addMapping("/"); +// +// } +} diff --git a/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/controller/EmployeeController.java b/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/controller/EmployeeController.java new file mode 100644 index 0000000000..3ece77bb18 --- /dev/null +++ b/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/controller/EmployeeController.java @@ -0,0 +1,41 @@ +package com.baeldung.springmvcforms.controller; + +import com.baeldung.springmvcforms.domain.Employee; +import org.springframework.stereotype.Controller; +import org.springframework.ui.ModelMap; +import org.springframework.validation.BindingResult; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.servlet.ModelAndView; + +import javax.validation.Valid; +import java.util.HashMap; +import java.util.Map; + +@Controller +public class EmployeeController { + + Map employeeMap = new HashMap<>(); + + @RequestMapping(value = "/employee", method = RequestMethod.GET) + public ModelAndView showForm() { + return new ModelAndView("employeeHome", "employee", new Employee()); + } + + @RequestMapping(value = "/employee/{Id}", produces = { "application/json", "application/xml" }, method = RequestMethod.GET) + public @ResponseBody Employee getEmployeeById(@PathVariable final long Id) { + return employeeMap.get(Id); + } + + @RequestMapping(value = "/addEmployee", method = RequestMethod.POST) + public String submit(@Valid @ModelAttribute("employee") final Employee employee, final BindingResult result, final ModelMap model) { + if (result.hasErrors()) { + return "error"; + } + model.addAttribute("name", employee.getName()); + model.addAttribute("contactNumber", employee.getContactNumber()); + model.addAttribute("id", employee.getId()); + employeeMap.put(employee.getId(), employee); + return "employeeView"; + } + +} diff --git a/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/domain/Employee.java b/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/domain/Employee.java new file mode 100644 index 0000000000..23cb72b3dc --- /dev/null +++ b/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/domain/Employee.java @@ -0,0 +1,46 @@ +package com.baeldung.springmvcforms.domain; + +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; + +public class Employee { + + private long id; + + @NotNull + @Size(min = 5) + private String name; + + @NotNull + @Size(min = 7) + private String contactNumber; + + public Employee() { + super(); + } + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } + + public long getId() { + return id; + } + + public void setId(final long id) { + this.id = id; + } + + public String getContactNumber() { + return contactNumber; + } + + public void setContactNumber(final String contactNumber) { + this.contactNumber = contactNumber; + } + +} diff --git a/spring-mvc-forms/src/main/webapp/WEB-INF/views/employeeHome.jsp b/spring-mvc-forms/src/main/webapp/WEB-INF/views/employeeHome.jsp new file mode 100644 index 0000000000..5ed572000a --- /dev/null +++ b/spring-mvc-forms/src/main/webapp/WEB-INF/views/employeeHome.jsp @@ -0,0 +1,33 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> +<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> + + + +Form Example - Register an Employee + + +

Welcome, Enter The Employee Details

+ + + + + + + + + + + + + + + + + + +
Name
Id
Contact Number
+
+ + + + \ No newline at end of file diff --git a/spring-mvc-forms/src/main/webapp/WEB-INF/views/employeeView.jsp b/spring-mvc-forms/src/main/webapp/WEB-INF/views/employeeView.jsp new file mode 100644 index 0000000000..1457bc5fc8 --- /dev/null +++ b/spring-mvc-forms/src/main/webapp/WEB-INF/views/employeeView.jsp @@ -0,0 +1,24 @@ +<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%> + + +Spring MVC Form Handling + + + +

Submitted Employee Information

+ + + + + + + + + + + + + +
Name :${name}
ID :${id}
Contact Number :${contactNumber}
+ + \ No newline at end of file diff --git a/spring-mvc-forms/src/main/webapp/WEB-INF/views/error.jsp b/spring-mvc-forms/src/main/webapp/WEB-INF/views/error.jsp new file mode 100644 index 0000000000..8f3d83af17 --- /dev/null +++ b/spring-mvc-forms/src/main/webapp/WEB-INF/views/error.jsp @@ -0,0 +1,20 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> + + + + +SpringMVCExample + + + +

Pleas enter the correct details

+ + + + +
Retry
+ + + + \ No newline at end of file diff --git a/spring-mvc-java/src/main/webapp/WEB-INF/templates/message.html b/spring-mvc-java/src/main/webapp/WEB-INF/templates/message.html new file mode 100644 index 0000000000..291e8312ae --- /dev/null +++ b/spring-mvc-java/src/main/webapp/WEB-INF/templates/message.html @@ -0,0 +1,15 @@ + + + + + + +
+ Message: + +
+ + + + diff --git a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndJUnitTest.java b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndJUnitTest.java new file mode 100644 index 0000000000..8395a49581 --- /dev/null +++ b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndJUnitTest.java @@ -0,0 +1,31 @@ +package com.baeldung.htmlunit; + +import org.junit.Assert; +import org.junit.Test; + +import com.gargoylesoftware.htmlunit.WebClient; +import com.gargoylesoftware.htmlunit.html.HtmlPage; + +public class HtmlUnitAndJUnitTest { + + @Before + public void init() throws Exception { + webClient = new WebClient(); + } + + @After + public void close() throws Exception { + webClient.close(); + } + + @Test + public void givenAClient_whenEnteringBaeldung_thenPageTitleIsOk() + throws Exception { + webClient.getOptions().setThrowExceptionOnScriptError(false); + HtmlPage page = webClient.getPage("http://www.baeldung.com/"); + Assert.assertEquals( + "Baeldung | Java, Spring and Web Development tutorials", + page.getTitleText()); + } + +} diff --git a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndSpringIntegrationTest.java b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndSpringIntegrationTest.java deleted file mode 100644 index 406975b6cc..0000000000 --- a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndSpringIntegrationTest.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.baeldung.htmlunit; - -import java.io.IOException; -import java.net.MalformedURLException; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.WebAppConfiguration; -import org.springframework.test.web.servlet.htmlunit.MockMvcWebClientBuilder; -import org.springframework.web.context.WebApplicationContext; - -import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException; -import com.gargoylesoftware.htmlunit.WebClient; -import com.gargoylesoftware.htmlunit.html.HtmlForm; -import com.gargoylesoftware.htmlunit.html.HtmlPage; -import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput; -import com.gargoylesoftware.htmlunit.html.HtmlTextInput; - -@RunWith(SpringJUnit4ClassRunner.class) -@WebAppConfiguration -@ContextConfiguration(classes = { TestConfig.class }) -public class HtmlUnitAndSpringIntegrationTest { - - @Autowired - private WebApplicationContext wac; - - private WebClient webClient; - - @Before - public void setup() { - webClient = MockMvcWebClientBuilder.webAppContextSetup(wac).build(); - } - - // - - @Test - @Ignore("Related view message.html does not exist check MessageController") - public void givenAMessage_whenSent_thenItShows() throws FailingHttpStatusCodeException, MalformedURLException, IOException { - final String text = "Hello world!"; - final HtmlPage page = webClient.getPage("http://localhost/message/showForm"); - System.out.println(page.asXml()); - - final HtmlTextInput messageText = page.getHtmlElementById("message"); - messageText.setValueAttribute(text); - - final HtmlForm form = page.getForms().get(0); - final HtmlSubmitInput submit = form.getOneHtmlElementByAttribute("input", "type", "submit"); - final HtmlPage newPage = submit.click(); - - final String receivedText = newPage.getHtmlElementById("received").getTextContent(); - - Assert.assertEquals(receivedText, text); - System.out.println(newPage.asXml()); - } - - @Test - public void givenAClient_whenEnteringBaeldung_thenPageTitleIsCorrect() throws Exception { - try (final WebClient client = new WebClient()) { - webClient.getOptions().setThrowExceptionOnScriptError(false); - - final HtmlPage page = webClient.getPage("http://www.baeldung.com/"); - Assert.assertEquals("Baeldung | Java, Spring and Web Development tutorials", page.getTitleText()); - } - } - -} diff --git a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndSpringTest.java b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndSpringTest.java new file mode 100644 index 0000000000..45e441f47f --- /dev/null +++ b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndSpringTest.java @@ -0,0 +1,61 @@ +package com.baeldung.htmlunit; + +import java.io.IOException; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.servlet.htmlunit.MockMvcWebClientBuilder; +import org.springframework.web.context.WebApplicationContext; + +import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException; +import com.gargoylesoftware.htmlunit.WebClient; +import com.gargoylesoftware.htmlunit.html.HtmlForm; +import com.gargoylesoftware.htmlunit.html.HtmlPage; +import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput; +import com.gargoylesoftware.htmlunit.html.HtmlTextInput; + +@RunWith(SpringJUnit4ClassRunner.class) +@WebAppConfiguration +@ContextConfiguration(classes = { TestConfig.class }) +public class HtmlUnitAndSpringTest { + + @Autowired + private WebApplicationContext wac; + + private WebClient webClient; + + @Before + public void setup() { + webClient = MockMvcWebClientBuilder + .webAppContextSetup(wac).build(); + } + + @Test + public void givenAMessage_whenSent_thenItShows() throws Exception { + String text = "Hello world!"; + HtmlPage page; + + String url = "http://localhost/message/showForm"; + page = webClient.getPage(url); + + HtmlTextInput messageText = page.getHtmlElementById("message"); + messageText.setValueAttribute(text); + + HtmlForm form = page.getForms().get(0); + HtmlSubmitInput submit = form.getOneHtmlElementByAttribute( + "input", "type", "submit"); + HtmlPage newPage = submit.click(); + + String receivedText = newPage.getHtmlElementById("received") + .getTextContent(); + + Assert.assertEquals(receivedText, text); + } +} diff --git a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitTest.java b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitTest.java deleted file mode 100644 index 6a7e961eb1..0000000000 --- a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitTest.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.baeldung.htmlunit; - -import org.junit.Assert; -import org.junit.Test; - -import com.gargoylesoftware.htmlunit.WebClient; -import com.gargoylesoftware.htmlunit.html.HtmlPage; - -public class HtmlUnitTest { - - @Test - public void givenAClient_whenEnteringBaeldung_thenPageTitleIsCorrect() throws Exception { - try (final WebClient webClient = new WebClient()) { - webClient.getOptions().setThrowExceptionOnScriptError(false); - - final HtmlPage page = webClient.getPage("http://www.baeldung.com/"); - Assert.assertEquals("Baeldung | Java, Spring and Web Development tutorials", page.getTitleText()); - } - } - -} diff --git a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitWebScraping.java b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitWebScraping.java index 9919d7571d..f97bedddef 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitWebScraping.java +++ b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitWebScraping.java @@ -5,36 +5,38 @@ import java.util.List; import com.gargoylesoftware.htmlunit.WebClient; import com.gargoylesoftware.htmlunit.html.HtmlAnchor; import com.gargoylesoftware.htmlunit.html.HtmlHeading1; -import com.gargoylesoftware.htmlunit.html.HtmlHeading2; import com.gargoylesoftware.htmlunit.html.HtmlPage; public class HtmlUnitWebScraping { - public static void main(final String[] args) throws Exception { - try (final WebClient webClient = new WebClient()) { + private WebClient webClient; - webClient.getOptions().setCssEnabled(false); - webClient.getOptions().setJavaScriptEnabled(false); + @Before + public void init() throws Exception { + webClient = new WebClient(); + } - final HtmlPage page = webClient.getPage("http://www.baeldung.com/full_archive"); - final HtmlAnchor latestPostLink = (HtmlAnchor) page.getByXPath("(//ul[@class='car-monthlisting']/li)[1]/a").get(0); + @After + public void close() throws Exception { + webClient.close(); + } - System.out.println("Entering: " + latestPostLink.getHrefAttribute()); + @Test + public void givenBaeldungArchive_whenRetrievingArticle_thenHasH1() + throws Exception { + webClient.getOptions().setCssEnabled(false); + webClient.getOptions().setJavaScriptEnabled(false); - final HtmlPage postPage = latestPostLink.click(); + String url = "http://www.baeldung.com/full_archive"; + HtmlPage page = webClient.getPage(url); + String xpath = "(//ul[@class='car-monthlisting']/li)[1]/a"; + HtmlAnchor latestPostLink + = (HtmlAnchor) page.getByXPath(xpath).get(0); + HtmlPage postPage = latestPostLink.click(); - final HtmlHeading1 heading1 = (HtmlHeading1) postPage.getByXPath("//h1").get(0); - System.out.println("Title: " + heading1.getTextContent()); - - final List headings2 = (List) postPage.getByXPath("//h2"); - - final StringBuilder sb = new StringBuilder(heading1.getTextContent()); - for (final HtmlHeading2 h2 : headings2) { - sb.append("\n").append(h2.getTextContent()); - } - - System.out.println(sb.toString()); - } - } + List h1 + = (List) postPage.getByXPath("//h1"); + Assert.assertTrue(h1.size() > 0); + } } diff --git a/spring-mvc-xml/README.md b/spring-mvc-xml/README.md index 783bbb2ef4..e96a8d0392 100644 --- a/spring-mvc-xml/README.md +++ b/spring-mvc-xml/README.md @@ -12,3 +12,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Servlet Session Timeout](http://www.baeldung.com/servlet-session-timeout) - [Basic Forms with Spring MVC](http://www.baeldung.com/spring-mvc-form-tutorial) - [Returning Image/Media Data with Spring MVC](http://www.baeldung.com/spring-mvc-image-media-data) +- [Geolocation by IP in Java](http://www.baeldung.com/geolocation-by-ip-with-maxmind) diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/MyFooController.java b/spring-rest/src/main/java/org/baeldung/web/controller/MyFooController.java new file mode 100644 index 0000000000..f19ddca435 --- /dev/null +++ b/spring-rest/src/main/java/org/baeldung/web/controller/MyFooController.java @@ -0,0 +1,76 @@ +package org.baeldung.web.controller; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; + +import javax.servlet.http.HttpServletResponse; + +import org.baeldung.web.dto.Foo; +import org.baeldung.web.exception.ResourceNotFoundException; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; + +@Controller +@RequestMapping(value = "/myfoos") +public class MyFooController { + + private final Map myfoos; + + public MyFooController() { + super(); + myfoos = new HashMap(); + myfoos.put(1L, new Foo(1L, "sample foo")); + } + + // API - read + + @RequestMapping(method = RequestMethod.GET) + @ResponseBody + public Collection findAll() { + return myfoos.values(); + } + + @RequestMapping(method = RequestMethod.GET, value = "/{id}", produces = { "application/json" }) + @ResponseBody + public Foo findById(@PathVariable final long id) { + final Foo foo = myfoos.get(id); + if (foo == null) { + throw new ResourceNotFoundException(); + } + return foo; + } + + // API - write + + @RequestMapping(method = RequestMethod.PUT, value = "/{id}") + @ResponseStatus(HttpStatus.OK) + @ResponseBody + public Foo updateFoo(@PathVariable("id") final long id, @RequestBody final Foo foo) { + myfoos.put(id, foo); + return foo; + } + + @RequestMapping(method = RequestMethod.POST) + @ResponseStatus(HttpStatus.CREATED) + @ResponseBody + public Foo createFoo(@RequestBody final Foo foo, HttpServletResponse response) { + myfoos.put(foo.getId(), foo); + response.setHeader("Location", ServletUriComponentsBuilder.fromCurrentRequest().path("/" + foo.getId()).toUriString()); + return foo; + } + + @RequestMapping(method = RequestMethod.DELETE, value = "/{id}") + @ResponseStatus(HttpStatus.OK) + public void deleteById(@PathVariable final long id) { + myfoos.remove(id); + } + +} diff --git a/spring-rest/src/main/java/org/baeldung/web/dto/Foo.java b/spring-rest/src/main/java/org/baeldung/web/dto/Foo.java index 774d547464..240b368b50 100644 --- a/spring-rest/src/main/java/org/baeldung/web/dto/Foo.java +++ b/spring-rest/src/main/java/org/baeldung/web/dto/Foo.java @@ -11,6 +11,12 @@ public class Foo { super(); } + public Foo(final String name) { + super(); + + this.name = name; + } + public Foo(final long id, final String name) { super(); diff --git a/spring-rest/src/main/java/org/baeldung/web/exception/ResourceNotFoundException.java b/spring-rest/src/main/java/org/baeldung/web/exception/ResourceNotFoundException.java new file mode 100644 index 0000000000..aab737b6ec --- /dev/null +++ b/spring-rest/src/main/java/org/baeldung/web/exception/ResourceNotFoundException.java @@ -0,0 +1,8 @@ +package org.baeldung.web.exception; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +@ResponseStatus(value = HttpStatus.NOT_FOUND) +public class ResourceNotFoundException extends RuntimeException { +} diff --git a/spring-rest/src/main/webapp/WEB-INF/api-servlet.xml b/spring-rest/src/main/webapp/WEB-INF/api-servlet.xml index 21136b62c6..0f80990c16 100644 --- a/spring-rest/src/main/webapp/WEB-INF/api-servlet.xml +++ b/spring-rest/src/main/webapp/WEB-INF/api-servlet.xml @@ -8,7 +8,7 @@ - + + @@ -43,6 +44,11 @@ + + + + diff --git a/spring-rest/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java b/spring-rest/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java index e4321e163f..a47c60e9d8 100644 --- a/spring-rest/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java +++ b/spring-rest/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java @@ -1,28 +1,42 @@ package org.baeldung.client; +import static org.apache.commons.codec.binary.Base64.encodeBase64; import static org.baeldung.client.Consts.APPLICATION_PORT; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.MatcherAssert.assertThat; -import static org.mockito.Matchers.notNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; import java.io.IOException; +import java.net.URI; +import java.util.Arrays; +import java.util.Set; import org.baeldung.web.dto.Foo; import org.junit.Before; import org.junit.Test; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; +import org.springframework.http.client.ClientHttpRequestFactory; +import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.RequestCallback; import org.springframework.web.client.RestTemplate; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.base.Charsets; public class RestTemplateBasicLiveTest { private RestTemplate restTemplate; - private static final String fooResourceUrl = "http://localhost:" + APPLICATION_PORT + "/spring-rest/foos"; + private static final String fooResourceUrl = "http://localhost:" + APPLICATION_PORT + "/spring-rest/myfoos"; @Before public void beforeTest() { @@ -33,19 +47,19 @@ public class RestTemplateBasicLiveTest { @Test public void givenResourceUrl_whenSendGetForRequestEntity_thenStatusOk() throws IOException { - ResponseEntity response = restTemplate.getForEntity(fooResourceUrl + "/1", String.class); + final ResponseEntity response = restTemplate.getForEntity(fooResourceUrl + "/1", String.class); assertThat(response.getStatusCode(), equalTo(HttpStatus.OK)); } @Test public void givenResourceUrl_whenSendGetForRequestEntity_thenBodyCorrect() throws IOException { - ResponseEntity response = restTemplate.getForEntity(fooResourceUrl + "/1", String.class); + final ResponseEntity response = restTemplate.getForEntity(fooResourceUrl + "/1", String.class); - ObjectMapper mapper = new ObjectMapper(); - JsonNode root = mapper.readTree(response.getBody()); - JsonNode name = root.path("name"); - assertThat(name.asText(), is(notNull())); + final ObjectMapper mapper = new ObjectMapper(); + final JsonNode root = mapper.readTree(response.getBody()); + final JsonNode name = root.path("name"); + assertThat(name.asText(), notNullValue()); } @Test @@ -56,4 +70,147 @@ public class RestTemplateBasicLiveTest { assertThat(foo.getId(), is(1L)); } + // HEAD, OPTIONS + + @Test + public void givenFooService_whenCallHeadForHeaders_thenReceiveAllHeadersForThatResource() { + final HttpHeaders httpHeaders = restTemplate.headForHeaders(fooResourceUrl); + + assertTrue(httpHeaders.getContentType().includes(MediaType.APPLICATION_JSON)); + } + + // POST + + @Test + public void givenFooService_whenPostForObject_thenCreatedObjectIsReturned() { + final HttpEntity request = new HttpEntity<>(new Foo("bar")); + final Foo foo = restTemplate.postForObject(fooResourceUrl, request, Foo.class); + assertThat(foo, notNullValue()); + assertThat(foo.getName(), is("bar")); + } + + @Test + public void givenFooService_whenPostForLocation_thenCreatedLocationIsReturned() { + final HttpEntity request = new HttpEntity<>(new Foo("bar")); + final URI location = restTemplate.postForLocation(fooResourceUrl, request); + assertThat(location, notNullValue()); + } + + @Test + public void givenFooService_whenPostResource_thenResourceIsCreated() { + final RestTemplate template = new RestTemplate(); + + final HttpEntity request = new HttpEntity<>(new Foo("bar")); + + final ResponseEntity response = template.exchange(fooResourceUrl, HttpMethod.POST, request, Foo.class); + assertThat(response.getStatusCode(), is(HttpStatus.CREATED)); + final Foo foo = response.getBody(); + assertThat(foo, notNullValue()); + assertThat(foo.getName(), is("bar")); + } + + @Test + public void givenFooService_whenCallOptionsForAllow_thenReceiveValueOfAllowHeader() { + final Set optionsForAllow = restTemplate.optionsForAllow(fooResourceUrl); + final HttpMethod[] supportedMethods = { HttpMethod.GET, HttpMethod.POST, HttpMethod.HEAD }; + + assertTrue(optionsForAllow.containsAll(Arrays.asList(supportedMethods))); + } + + // PUT + + @Test + public void givenFooService_whenPutExistingEntity_thenItIsUpdated() { + final RestTemplate template = new RestTemplate(); + final HttpHeaders headers = prepareBasicAuthHeaders(); + final HttpEntity request = new HttpEntity<>(new Foo("bar"), headers); + + // Create Resource + final ResponseEntity createResponse = template.exchange(fooResourceUrl, HttpMethod.POST, request, Foo.class); + + // Update Resource + final Foo updatedInstance = new Foo("newName"); + updatedInstance.setId(createResponse.getBody().getId()); + final String resourceUrl = fooResourceUrl + '/' + createResponse.getBody().getId(); + final HttpEntity requestUpdate = new HttpEntity<>(updatedInstance, headers); + template.exchange(resourceUrl, HttpMethod.PUT, requestUpdate, Void.class); + + // Check that Resource was updated + final ResponseEntity updateResponse = template.exchange(resourceUrl, HttpMethod.GET, new HttpEntity<>(headers), Foo.class); + final Foo foo = updateResponse.getBody(); + assertThat(foo.getName(), is(updatedInstance.getName())); + } + + @Test + public void givenFooService_whenPutExistingEntityWithCallback_thenItIsUpdated() { + final RestTemplate template = new RestTemplate(); + final HttpHeaders headers = prepareBasicAuthHeaders(); + final HttpEntity request = new HttpEntity<>(new Foo("bar"), headers); + + // Create entity + ResponseEntity response = template.exchange(fooResourceUrl, HttpMethod.POST, request, Foo.class); + assertThat(response.getStatusCode(), is(HttpStatus.CREATED)); + + // Update entity + final Foo updatedInstance = new Foo("newName"); + updatedInstance.setId(response.getBody().getId()); + final String resourceUrl = fooResourceUrl + '/' + response.getBody().getId(); + template.execute(resourceUrl, HttpMethod.PUT, requestCallback(updatedInstance), clientHttpResponse -> null); + + // Check that entity was updated + response = template.exchange(resourceUrl, HttpMethod.GET, new HttpEntity<>(headers), Foo.class); + final Foo foo = response.getBody(); + assertThat(foo.getName(), is(updatedInstance.getName())); + } + + // DELETE + + @Test + public void givenFooService_whenCallDelete_thenEntityIsRemoved() { + final Foo foo = new Foo("remove me"); + final ResponseEntity response = restTemplate.postForEntity(fooResourceUrl, foo, Foo.class); + assertThat(response.getStatusCode(), is(HttpStatus.CREATED)); + + final String entityUrl = fooResourceUrl + "/" + response.getBody().getId(); + restTemplate.delete(entityUrl); + try { + restTemplate.getForEntity(entityUrl, Foo.class); + fail(); + } catch (final HttpClientErrorException ex) { + assertThat(ex.getStatusCode(), is(HttpStatus.NOT_FOUND)); + } + } + + // + + private HttpHeaders prepareBasicAuthHeaders() { + final HttpHeaders headers = new HttpHeaders(); + final String encodedLogPass = getBase64EncodedLogPass(); + headers.add(HttpHeaders.AUTHORIZATION, "Basic " + encodedLogPass); + return headers; + } + + private String getBase64EncodedLogPass() { + final String logPass = "user1:user1Pass"; + final byte[] authHeaderBytes = encodeBase64(logPass.getBytes(Charsets.US_ASCII)); + return new String(authHeaderBytes, Charsets.US_ASCII); + } + + private RequestCallback requestCallback(final Foo updatedInstance) { + return clientHttpRequest -> { + final ObjectMapper mapper = new ObjectMapper(); + mapper.writeValue(clientHttpRequest.getBody(), updatedInstance); + clientHttpRequest.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); + clientHttpRequest.getHeaders().add(HttpHeaders.AUTHORIZATION, "Basic " + getBase64EncodedLogPass()); + }; + } + + // Simply setting restTemplate timeout using ClientHttpRequestFactory + + ClientHttpRequestFactory getSimpleClientHttpRequestFactory() { + final int timeout = 5; + final HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(); + clientHttpRequestFactory.setConnectTimeout(timeout * 1000); + return clientHttpRequestFactory; + } } diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingLiveTest.java b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingLiveTest.java index d5765b9756..71fc755321 100644 --- a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingLiveTest.java +++ b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingLiveTest.java @@ -1,5 +1,6 @@ package org.baeldung.okhttp; +import static org.baeldung.client.Consts.APPLICATION_PORT; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; @@ -7,10 +8,6 @@ import static org.junit.Assert.assertThat; import java.io.File; import java.io.IOException; -import org.baeldung.okhttp.ProgressRequestWrapper; -import org.junit.Before; -import org.junit.Test; - import okhttp3.Call; import okhttp3.MediaType; import okhttp3.MultipartBody; @@ -19,33 +16,29 @@ import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; +import org.junit.Before; +import org.junit.Test; + public class OkHttpFileUploadingLiveTest { - private static final String BASE_URL = "http://localhost:8080/spring-rest"; + private static final String BASE_URL = "http://localhost:" + APPLICATION_PORT + "/spring-rest"; OkHttpClient client; @Before public void init() { - client = new OkHttpClient(); + client = new OkHttpClient(); } @Test public void whenUploadFile_thenCorrect() throws IOException { - RequestBody requestBody = new MultipartBody.Builder() - .setType(MultipartBody.FORM) - .addFormDataPart("file", "file.txt", - RequestBody.create(MediaType.parse("application/octet-stream"), new File("src/test/resources/test.txt"))) - .build(); + final RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("file", "file.txt", RequestBody.create(MediaType.parse("application/octet-stream"), new File("src/test/resources/test.txt"))).build(); - Request request = new Request.Builder() - .url(BASE_URL + "/users/upload") - .post(requestBody) - .build(); + final Request request = new Request.Builder().url(BASE_URL + "/users/upload").post(requestBody).build(); - Call call = client.newCall(request); - Response response = call.execute(); + final Call call = client.newCall(request); + final Response response = call.execute(); assertThat(response.code(), equalTo(200)); } @@ -53,25 +46,18 @@ public class OkHttpFileUploadingLiveTest { @Test public void whenGetUploadFileProgress_thenCorrect() throws IOException { - RequestBody requestBody = new MultipartBody.Builder() - .setType(MultipartBody.FORM) - .addFormDataPart("file", "file.txt", - RequestBody.create(MediaType.parse("application/octet-stream"), new File("src/test/resources/test.txt"))) - .build(); + final RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("file", "file.txt", RequestBody.create(MediaType.parse("application/octet-stream"), new File("src/test/resources/test.txt"))).build(); - ProgressRequestWrapper countingBody = new ProgressRequestWrapper(requestBody, (long bytesWritten, long contentLength) -> { + final ProgressRequestWrapper countingBody = new ProgressRequestWrapper(requestBody, (long bytesWritten, long contentLength) -> { - float percentage = 100f * bytesWritten / contentLength; + final float percentage = (100f * bytesWritten) / contentLength; assertFalse(Float.compare(percentage, 100) > 0); }); - Request request = new Request.Builder() - .url(BASE_URL + "/users/upload") - .post(countingBody) - .build(); + final Request request = new Request.Builder().url(BASE_URL + "/users/upload").post(countingBody).build(); - Call call = client.newCall(request); - Response response = call.execute(); + final Call call = client.newCall(request); + final Response response = call.execute(); assertThat(response.code(), equalTo(200)); diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetLiveTest.java b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetLiveTest.java index 034833da0d..fc78899da1 100644 --- a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetLiveTest.java +++ b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpGetLiveTest.java @@ -1,14 +1,12 @@ package org.baeldung.okhttp; +import static org.baeldung.client.Consts.APPLICATION_PORT; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import java.io.IOException; -import org.junit.Before; -import org.junit.Test; - import okhttp3.Call; import okhttp3.Callback; import okhttp3.HttpUrl; @@ -16,9 +14,12 @@ import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; +import org.junit.Before; +import org.junit.Test; + public class OkHttpGetLiveTest { - private static final String BASE_URL = "http://localhost:8080/spring-rest"; + private static final String BASE_URL = "http://localhost:" + APPLICATION_PORT + "/spring-rest"; OkHttpClient client; @@ -30,40 +31,42 @@ public class OkHttpGetLiveTest { @Test public void whenGetRequest_thenCorrect() throws IOException { - Request request = new Request.Builder().url(BASE_URL + "/date").build(); + final Request request = new Request.Builder().url(BASE_URL + "/date").build(); - Call call = client.newCall(request); - Response response = call.execute(); + final Call call = client.newCall(request); + final Response response = call.execute(); assertThat(response.code(), equalTo(200)); } @Test public void whenGetRequestWithQueryParameter_thenCorrect() throws IOException { - HttpUrl.Builder urlBuilder = HttpUrl.parse(BASE_URL + "/ex/bars").newBuilder(); + final HttpUrl.Builder urlBuilder = HttpUrl.parse(BASE_URL + "/ex/bars").newBuilder(); urlBuilder.addQueryParameter("id", "1"); - String url = urlBuilder.build().toString(); + final String url = urlBuilder.build().toString(); - Request request = new Request.Builder().url(url).build(); + final Request request = new Request.Builder().url(url).build(); - Call call = client.newCall(request); - Response response = call.execute(); + final Call call = client.newCall(request); + final Response response = call.execute(); assertThat(response.code(), equalTo(200)); } @Test public void whenAsynchronousGetRequest_thenCorrect() throws InterruptedException { - Request request = new Request.Builder().url(BASE_URL + "/date").build(); + final Request request = new Request.Builder().url(BASE_URL + "/date").build(); - Call call = client.newCall(request); + final Call call = client.newCall(request); call.enqueue(new Callback() { + @Override public void onResponse(Call call, Response response) throws IOException { System.out.println("OK"); } + @Override public void onFailure(Call call, IOException e) { fail(); } diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpMiscLiveTest.java b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpMiscLiveTest.java index 34e1554908..e6b3cc87b0 100644 --- a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpMiscLiveTest.java +++ b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpMiscLiveTest.java @@ -1,27 +1,27 @@ package org.baeldung.okhttp; -import okhttp3.*; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import static org.baeldung.client.Consts.APPLICATION_PORT; + import java.io.File; import java.io.IOException; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; -import org.junit.Before; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; + import okhttp3.Cache; import okhttp3.Call; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; +import org.junit.Before; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + public class OkHttpMiscLiveTest { - private static final String BASE_URL = "http://localhost:8080/spring-rest"; + private static final String BASE_URL = "http://localhost:" + APPLICATION_PORT + "/spring-rest"; private static Logger logger = LoggerFactory.getLogger(OkHttpMiscLiveTest.class); OkHttpClient client; @@ -29,31 +29,27 @@ public class OkHttpMiscLiveTest { @Before public void init() { - client = new OkHttpClient(); + client = new OkHttpClient(); } @Test public void whenSetRequestTimeout_thenFail() throws IOException { - OkHttpClient clientWithTimeout = new OkHttpClient.Builder() - .readTimeout(1, TimeUnit.SECONDS) - .build(); + final OkHttpClient clientWithTimeout = new OkHttpClient.Builder().readTimeout(1, TimeUnit.SECONDS).build(); - Request request = new Request.Builder() - .url(BASE_URL + "/delay/2") // This URL is served with a 2 second delay. - .build(); + final Request request = new Request.Builder().url(BASE_URL + "/delay/2") // This URL is served with a 2 second delay. + .build(); - Call call = clientWithTimeout.newCall(request); - Response response = call.execute(); + final Call call = clientWithTimeout.newCall(request); + final Response response = call.execute(); response.close(); } @Test(expected = IOException.class) public void whenCancelRequest_thenCorrect() throws IOException { - ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); + final ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); - Request request = new Request.Builder() - .url(BASE_URL + "/delay/2") // This URL is served with a 2 second delay. - .build(); + final Request request = new Request.Builder().url(BASE_URL + "/delay/2") // This URL is served with a 2 second delay. + .build(); final int seconds = 1; final long startNanos = System.nanoTime(); @@ -63,42 +59,38 @@ public class OkHttpMiscLiveTest { // Schedule a job to cancel the call in 1 second. executor.schedule(() -> { - logger.debug("Canceling call: " + (System.nanoTime() - startNanos) / 1e9f); + logger.debug("Canceling call: " + ((System.nanoTime() - startNanos) / 1e9f)); call.cancel(); - logger.debug("Canceled call: " + (System.nanoTime() - startNanos) / 1e9f); + logger.debug("Canceled call: " + ((System.nanoTime() - startNanos) / 1e9f)); }, seconds, TimeUnit.SECONDS); - logger.debug("Executing call: " + (System.nanoTime() - startNanos) / 1e9f); - Response response = call.execute(); - logger.debug("Call completed: " + (System.nanoTime() - startNanos) / 1e9f, response); + logger.debug("Executing call: " + ((System.nanoTime() - startNanos) / 1e9f)); + final Response response = call.execute(); + logger.debug("Call completed: " + ((System.nanoTime() - startNanos) / 1e9f), response); } @Test - public void whenSetResponseCache_thenCorrect() throws IOException { + public void whenSetResponseCache_thenCorrect() throws IOException { - int cacheSize = 10 * 1024 * 1024; // 10 MiB - File cacheDirectory = new File("src/test/resources/cache"); - Cache cache = new Cache(cacheDirectory, cacheSize); + final int cacheSize = 10 * 1024 * 1024; // 10 MiB + final File cacheDirectory = new File("src/test/resources/cache"); + final Cache cache = new Cache(cacheDirectory, cacheSize); - OkHttpClient clientCached = new OkHttpClient.Builder() - .cache(cache) - .build(); + final OkHttpClient clientCached = new OkHttpClient.Builder().cache(cache).build(); - Request request = new Request.Builder() - .url("http://publicobject.com/helloworld.txt") - .build(); + final Request request = new Request.Builder().url("http://publicobject.com/helloworld.txt").build(); - Response response1 = clientCached.newCall(request).execute(); + final Response response1 = clientCached.newCall(request).execute(); logResponse(response1); - Response response2 = clientCached.newCall(request).execute(); + final Response response2 = clientCached.newCall(request).execute(); logResponse(response2); } private void logResponse(Response response) throws IOException { - logger.debug("Response response: " + response); + logger.debug("Response response: " + response); logger.debug("Response cache response: " + response.cacheResponse()); logger.debug("Response network response: " + response.networkResponse()); logger.debug("Response responseBody: " + response.body().string()); diff --git a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpPostingLiveTest.java b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpPostingLiveTest.java index dce3bb174f..cbe5ff885c 100644 --- a/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpPostingLiveTest.java +++ b/spring-rest/src/test/java/org/baeldung/okhttp/OkHttpPostingLiveTest.java @@ -1,14 +1,12 @@ package org.baeldung.okhttp; +import static org.baeldung.client.Consts.APPLICATION_PORT; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; import java.io.File; import java.io.IOException; -import org.junit.Before; -import org.junit.Test; - import okhttp3.Call; import okhttp3.Credentials; import okhttp3.FormBody; @@ -19,9 +17,12 @@ import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; +import org.junit.Before; +import org.junit.Test; + public class OkHttpPostingLiveTest { - private static final String BASE_URL = "http://localhost:8080/spring-rest"; + private static final String BASE_URL = "http://localhost:" + APPLICATION_PORT + "/spring-rest"; private static final String URL_SECURED_BY_BASIC_AUTHENTICATION = "http://browserspy.dk/password-ok.php"; OkHttpClient client; @@ -29,77 +30,56 @@ public class OkHttpPostingLiveTest { @Before public void init() { - client = new OkHttpClient(); + client = new OkHttpClient(); } @Test public void whenSendPostRequest_thenCorrect() throws IOException { - RequestBody formBody = new FormBody.Builder() - .add("username", "test") - .add("password", "test") - .build(); + final RequestBody formBody = new FormBody.Builder().add("username", "test").add("password", "test").build(); - Request request = new Request.Builder() - .url(BASE_URL + "/users") - .post(formBody) - .build(); + final Request request = new Request.Builder().url(BASE_URL + "/users").post(formBody).build(); - Call call = client.newCall(request); - Response response = call.execute(); + final Call call = client.newCall(request); + final Response response = call.execute(); assertThat(response.code(), equalTo(200)); } @Test public void whenSendPostRequestWithAuthorization_thenCorrect() throws IOException { - String postBody = "test post"; + final String postBody = "test post"; - Request request = new Request.Builder() - .url(URL_SECURED_BY_BASIC_AUTHENTICATION) - .addHeader("Authorization", Credentials.basic("test", "test")) - .post(RequestBody.create(MediaType.parse("text/x-markdown; charset=utf-8"), postBody)) - .build(); + final Request request = new Request.Builder().url(URL_SECURED_BY_BASIC_AUTHENTICATION).addHeader("Authorization", Credentials.basic("test", "test")).post(RequestBody.create(MediaType.parse("text/x-markdown; charset=utf-8"), postBody)).build(); - Call call = client.newCall(request); - Response response = call.execute(); + final Call call = client.newCall(request); + final Response response = call.execute(); assertThat(response.code(), equalTo(200)); } @Test public void whenPostJson_thenCorrect() throws IOException { - String json = "{\"id\":1,\"name\":\"John\"}"; + final String json = "{\"id\":1,\"name\":\"John\"}"; - RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json); + final RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json); - Request request = new Request.Builder() - .url(BASE_URL + "/users/detail") - .post(body) - .build(); + final Request request = new Request.Builder().url(BASE_URL + "/users/detail").post(body).build(); - Call call = client.newCall(request); - Response response = call.execute(); + final Call call = client.newCall(request); + final Response response = call.execute(); assertThat(response.code(), equalTo(200)); } @Test public void whenSendMultipartRequest_thenCorrect() throws IOException { - RequestBody requestBody = new MultipartBody.Builder() - .setType(MultipartBody.FORM) - .addFormDataPart("username", "test") - .addFormDataPart("password", "test") - .addFormDataPart("file", "file.txt", - RequestBody.create(MediaType.parse("application/octet-stream"), new File("src/test/resources/test.txt"))) - .build(); + final RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("username", "test").addFormDataPart("password", "test") + .addFormDataPart("file", "file.txt", RequestBody.create(MediaType.parse("application/octet-stream"), new File("src/test/resources/test.txt"))).build(); - Request request = new Request.Builder() - .url(BASE_URL + "/users/multipart") - .post(requestBody) - .build(); + final Request request = new Request.Builder().url(BASE_URL + "/users/multipart").post(requestBody).build(); - Call call = client.newCall(request); - Response response = call.execute(); + final Call call = client.newCall(request); + final Response response = call.execute(); assertThat(response.code(), equalTo(200)); } diff --git a/spring-rest/src/test/java/org/baeldung/uribuilder/SpringUriBuilderTest.java b/spring-rest/src/test/java/org/baeldung/uribuilder/SpringUriBuilderTest.java new file mode 100644 index 0000000000..4b6a9ba312 --- /dev/null +++ b/spring-rest/src/test/java/org/baeldung/uribuilder/SpringUriBuilderTest.java @@ -0,0 +1,53 @@ +package org.baeldung.uribuilder; + +import static org.junit.Assert.assertEquals; + +import java.util.Collections; + +import org.junit.Test; +import org.springframework.web.util.UriComponents; +import org.springframework.web.util.UriComponentsBuilder; + +public class SpringUriBuilderTest { + + @Test + public void constructUri() { + UriComponents uriComponents = UriComponentsBuilder.newInstance().scheme("http").host("www.baeldung.com") + .path("/junit-5").build(); + + assertEquals("http://www.baeldung.com/junit-5", uriComponents.toUriString()); + } + + @Test + public void constructUriEncoded() { + UriComponents uriComponents = UriComponentsBuilder.newInstance().scheme("http").host("www.baeldung.com") + .path("/junit 5").build().encode(); + + assertEquals("http://www.baeldung.com/junit%205", uriComponents.toUriString()); + } + + @Test + public void constructUriFromTemplate() { + UriComponents uriComponents = UriComponentsBuilder.newInstance().scheme("http").host("www.baeldung.com") + .path("/{article-name}").buildAndExpand("junit-5"); + + assertEquals("http://www.baeldung.com/junit-5", uriComponents.toUriString()); + } + + @Test + public void constructUriWithQueryParameter() { + UriComponents uriComponents = UriComponentsBuilder.newInstance().scheme("http").host("www.google.com") + .path("/").query("q={keyword}").buildAndExpand("baeldung"); + + assertEquals("http://www.google.com/?q=baeldung", uriComponents.toUriString()); + } + + @Test + public void expandWithRegexVar() { + String template = "/myurl/{name:[a-z]{1,5}}/show"; + UriComponents uriComponents = UriComponentsBuilder.fromUriString(template).build(); + uriComponents = uriComponents.expand(Collections.singletonMap("name", "test")); + + assertEquals("/myurl/test/show", uriComponents.getPath()); + } +} diff --git a/spring-rest/src/test/java/org/baeldung/web/test/RequestMappingLiveTest.java b/spring-rest/src/test/java/org/baeldung/web/test/RequestMappingLiveTest.java index 3155b5cda9..7828df7304 100644 --- a/spring-rest/src/test/java/org/baeldung/web/test/RequestMappingLiveTest.java +++ b/spring-rest/src/test/java/org/baeldung/web/test/RequestMappingLiveTest.java @@ -1,5 +1,6 @@ package org.baeldung.web.test; +import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import org.junit.Test; @@ -31,7 +32,7 @@ public class RequestMappingLiveTest { @Test public void givenAcceptHeader_whenGetFoos_thenOk() { - RestAssured.given().accept("application/json").get(BASE_URI + "foos").then().assertThat().body(equalTo("Get some Foos with Header New")); + RestAssured.given().accept("application/json").get(BASE_URI + "foos").then().assertThat().body(containsString("Get some Foos with Header New")); } @Test diff --git a/spring-security-basic-auth/src/main/java/org/baeldung/security/filter/configuration/CustomWebSecurityConfigurerAdapter.java b/spring-security-basic-auth/src/main/java/org/baeldung/security/filter/configuration/CustomWebSecurityConfigurerAdapter.java index 1901489305..db304edb36 100644 --- a/spring-security-basic-auth/src/main/java/org/baeldung/security/filter/configuration/CustomWebSecurityConfigurerAdapter.java +++ b/spring-security-basic-auth/src/main/java/org/baeldung/security/filter/configuration/CustomWebSecurityConfigurerAdapter.java @@ -13,28 +13,27 @@ import org.springframework.security.web.authentication.www.BasicAuthenticationFi @Configuration @EnableWebSecurity public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter { + @Autowired private MyBasicAuthenticationEntryPoint authenticationEntryPoint; @Autowired - public void configureGlobal(AuthenticationManagerBuilder auth) - throws Exception { - auth - .inMemoryAuthentication() - .withUser("user1").password("user1Pass") - .authorities("ROLE_USER"); + public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { + auth.inMemoryAuthentication() + .withUser("user1").password("user1Pass") + .authorities("ROLE_USER"); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() - .antMatchers("/securityNone").permitAll() - .anyRequest().authenticated() - .and() - .httpBasic() - .authenticationEntryPoint(authenticationEntryPoint); + .antMatchers("/securityNone").permitAll() + .anyRequest().authenticated() + .and() + .httpBasic() + .authenticationEntryPoint(authenticationEntryPoint); http.addFilterAfter(new CustomFilter(), - BasicAuthenticationFilter.class); + BasicAuthenticationFilter.class); } } diff --git a/spring-security-rest/pom.xml b/spring-security-rest/pom.xml index 60f3ed41d1..df000d0df5 100644 --- a/spring-security-rest/pom.xml +++ b/spring-security-rest/pom.xml @@ -1,393 +1,400 @@ - 4.0.0 - com.baeldung - spring-security-rest - 0.1-SNAPSHOT + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 + com.baeldung + spring-security-rest + 0.1-SNAPSHOT - spring-security-rest - war + spring-security-rest + war - + - + - - org.springframework.security - spring-security-web - ${org.springframework.security.version} - - - org.springframework.security - spring-security-config - ${org.springframework.security.version} - + + org.springframework.security + spring-security-web + ${org.springframework.security.version} + + + org.springframework.security + spring-security-config + ${org.springframework.security.version} + - + - - org.springframework - spring-core - ${org.springframework.version} - - - commons-logging - commons-logging - - - - - org.springframework - spring-context - ${org.springframework.version} - - - org.springframework - spring-jdbc - ${org.springframework.version} - - - org.springframework - spring-beans - ${org.springframework.version} - - - org.springframework - spring-aop - ${org.springframework.version} - - - org.springframework - spring-tx - ${org.springframework.version} - - - org.springframework - spring-expression - ${org.springframework.version} - + + org.springframework + spring-core + ${org.springframework.version} + + + commons-logging + commons-logging + + + + + org.springframework + spring-context + ${org.springframework.version} + + + org.springframework + spring-jdbc + ${org.springframework.version} + + + org.springframework + spring-beans + ${org.springframework.version} + + + org.springframework + spring-aop + ${org.springframework.version} + + + org.springframework + spring-tx + ${org.springframework.version} + + + org.springframework + spring-expression + ${org.springframework.version} + - - org.springframework - spring-web - ${org.springframework.version} - - - org.springframework - spring-webmvc - ${org.springframework.version} - + + org.springframework + spring-web + ${org.springframework.version} + + + org.springframework + spring-webmvc + ${org.springframework.version} + - - - org.springframework.hateoas - spring-hateoas - ${org.springframework.hateoas.version} - + + + org.springframework.hateoas + spring-hateoas + ${org.springframework.hateoas.version} + - + - - javax.servlet - javax.servlet-api - ${javax.servlet-api.version} - provided - + + javax.servlet + javax.servlet-api + ${javax.servlet-api.version} + provided + - - javax.servlet - jstl - ${jstl.version} - runtime - + + javax.servlet + jstl + ${jstl.version} + runtime + - - javax.validation - validation-api - ${javax.validation.version} - + + javax.validation + validation-api + ${javax.validation.version} + - - - com.fasterxml.jackson.core - jackson-databind - ${jackson.version} - + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + - - - com.google.guava - guava - ${guava.version} - - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - - - - - org.slf4j - slf4j-api - ${org.slf4j.version} - - - ch.qos.logback - logback-classic - ${logback.version} - - - - org.slf4j - jcl-over-slf4j - ${org.slf4j.version} - - - - org.slf4j - log4j-over-slf4j - ${org.slf4j.version} - + + + com.google.guava + guava + ${guava.version} + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + - - - org.springframework - spring-test - ${org.springframework.version} - test - + + + org.slf4j + slf4j-api + ${org.slf4j.version} + + + ch.qos.logback + logback-classic + ${logback.version} + + + + org.slf4j + jcl-over-slf4j + ${org.slf4j.version} + + + + org.slf4j + log4j-over-slf4j + ${org.slf4j.version} + - - org.springframework.security - spring-security-test - ${org.springframework.security.version} - test - + + + org.springframework + spring-test + ${org.springframework.version} + test + + + + org.springframework.security + spring-security-test + ${org.springframework.security.version} + test + - - com.jayway.restassured - rest-assured - ${rest-assured.version} - test - - - commons-logging - commons-logging - - - + + com.jayway.restassured + rest-assured + ${rest-assured.version} + test + + + commons-logging + commons-logging + + + - - junit - junit - ${junit.version} - test - + + junit + junit + ${junit.version} + test + - - org.hamcrest - hamcrest-core - ${org.hamcrest.version} - test - - - org.hamcrest - hamcrest-library - ${org.hamcrest.version} - test - + + org.hamcrest + hamcrest-core + ${org.hamcrest.version} + test + + + org.hamcrest + hamcrest-library + ${org.hamcrest.version} + test + - - org.mockito - mockito-core - ${mockito.version} - test - + + org.mockito + mockito-core + ${mockito.version} + test + - - - io.springfox - springfox-swagger2 - ${springfox-swagger.version} - + + + io.springfox + springfox-swagger2 + ${springfox-swagger.version} + - - io.springfox - springfox-swagger-ui - ${springfox-swagger.version} - + + io.springfox + springfox-swagger-ui + ${springfox-swagger.version} + - + + + commons-fileupload + commons-fileupload + 1.3.2 + - - spring-security-rest - - - src/main/resources - true - - + - + + spring-security-rest + + + src/main/resources + true + + - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - 1.8 - 1.8 - - + - - org.apache.maven.plugins - maven-war-plugin - ${maven-war-plugin.version} - + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + 1.8 + 1.8 + + - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - - - **/*LiveTest.java - - - - - - + + org.apache.maven.plugins + maven-war-plugin + ${maven-war-plugin.version} + - - org.codehaus.cargo - cargo-maven2-plugin - ${cargo-maven2-plugin.version} - - - jetty8x - embedded - - - - - - - 8082 - - - - + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + **/*LiveTest.java + + + + + + - + + org.codehaus.cargo + cargo-maven2-plugin + ${cargo-maven2-plugin.version} + + + jetty8x + embedded + + + + + + + 8082 + + + + - + - - - live - - - - org.codehaus.cargo - cargo-maven2-plugin - - - start-server - pre-integration-test - - start - - - - stop-server - post-integration-test - - stop - - - - + - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - none - - - **/*LiveTest.java - - - cargo - - - - - + + + live + + + + org.codehaus.cargo + cargo-maven2-plugin + + + start-server + pre-integration-test + + start + + + + stop-server + post-integration-test + + stop + + + + - - - - - - - - - 4.2.5.RELEASE - 4.0.4.RELEASE - 0.19.0.RELEASE + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + none + + + **/*LiveTest.java + + + cargo + + + + + - - 4.3.11.Final - 5.1.38 + + + + - - 1.7.13 - 1.1.3 - - 5.2.2.Final - 3.0.1 - 1.1.0.Final - 1.2 - 2.7.8 + + + 4.2.5.RELEASE + 4.0.4.RELEASE + 0.19.0.RELEASE - - 19.0 - 3.4 + + 4.3.11.Final + 5.1.38 - - 1.3 - 4.12 - 1.10.19 - 2.9.0 + + 1.7.13 + 1.1.3 - - 2.4.0 + + 5.2.2.Final + 3.0.1 + 1.1.0.Final + 1.2 + 2.7.8 - 4.4.1 - 4.5 + + 19.0 + 3.4 - 2.9.0 + + 1.3 + 4.12 + 1.10.19 + 2.9.0 - - 3.5.1 - 2.6 - 2.19.1 - 1.4.18 + + 2.4.0 - + 4.4.1 + 4.5 + + 2.9.0 + + + 3.5.1 + 2.6 + 2.19.1 + 1.4.18 + + diff --git a/spring-security-rest/src/main/java/org/baeldung/web/controller/AsyncController.java b/spring-security-rest/src/main/java/org/baeldung/web/controller/AsyncController.java new file mode 100644 index 0000000000..bc59b4226a --- /dev/null +++ b/spring-security-rest/src/main/java/org/baeldung/web/controller/AsyncController.java @@ -0,0 +1,24 @@ +package org.baeldung.web.controller; + +import java.util.concurrent.Callable; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.multipart.MultipartFile; + +@Controller +public class AsyncController { + + @RequestMapping(method = RequestMethod.POST, value = "/upload") + public Callable processUpload(final MultipartFile file) { + + return new Callable() { + public Boolean call() throws Exception { + // ... + return true; + } + }; + } + +} diff --git a/spring-security-rest/src/main/webapp/WEB-INF/api-servlet.xml b/spring-security-rest/src/main/webapp/WEB-INF/api-servlet.xml index 4ba9642448..5a68371f6c 100644 --- a/spring-security-rest/src/main/webapp/WEB-INF/api-servlet.xml +++ b/spring-security-rest/src/main/webapp/WEB-INF/api-servlet.xml @@ -1,6 +1,10 @@ + xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd"> + + + \ No newline at end of file diff --git a/spring-security-rest/src/main/webapp/WEB-INF/web.xml b/spring-security-rest/src/main/webapp/WEB-INF/web.xml index 3af8709dab..c030a9dd63 100644 --- a/spring-security-rest/src/main/webapp/WEB-INF/web.xml +++ b/spring-security-rest/src/main/webapp/WEB-INF/web.xml @@ -1,54 +1,57 @@ - + http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" + id="WebApp_ID" version="3.0"> - Spring MVC Application + Spring MVC Application - - - contextClass - + + + contextClass + org.springframework.web.context.support.AnnotationConfigWebApplicationContext - - - contextConfigLocation - org.baeldung.spring - + + + contextConfigLocation + org.baeldung.spring + - - org.springframework.web.context.ContextLoaderListener - + + org.springframework.web.context.ContextLoaderListener + - - - api - org.springframework.web.servlet.DispatcherServlet - - throwExceptionIfNoHandlerFound - true - - - - api - /api/* - + + + api + org.springframework.web.servlet.DispatcherServlet + + throwExceptionIfNoHandlerFound + true + + + + api + /api/* + - - - springSecurityFilterChain - org.springframework.web.filter.DelegatingFilterProxy - - - springSecurityFilterChain - /* - + + + springSecurityFilterChain + org.springframework.web.filter.DelegatingFilterProxy + + + springSecurityFilterChain + /* + REQUEST + ASYNC + - - - + + + \ No newline at end of file diff --git a/spring-security-rest/src/test/java/org/baeldung/web/AsyncControllerTest.java b/spring-security-rest/src/test/java/org/baeldung/web/AsyncControllerTest.java new file mode 100644 index 0000000000..37122ed836 --- /dev/null +++ b/spring-security-rest/src/test/java/org/baeldung/web/AsyncControllerTest.java @@ -0,0 +1,51 @@ +package org.baeldung.web; + +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.baeldung.spring.ClientWebConfig; +import org.baeldung.spring.SecurityJavaConfig; +import org.baeldung.spring.WebConfig; +import org.baeldung.web.controller.AsyncController; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.mock.web.MockHttpSession; +import org.springframework.mock.web.MockMultipartFile; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +@RunWith(SpringJUnit4ClassRunner.class) +@WebAppConfiguration +@ContextConfiguration(classes = { ClientWebConfig.class, SecurityJavaConfig.class, WebConfig.class}) +public class AsyncControllerTest { + + @Autowired + WebApplicationContext wac; + @Autowired + MockHttpSession session; + + @Mock + AsyncController controller; + + private MockMvc mockMvc; + + @Before + public void setup() { + mockMvc = MockMvcBuilders.webAppContextSetup(wac).build(); + } + + @Test + public void testProcessUpload() throws Exception { + MockMultipartFile jsonFile = new MockMultipartFile("json", "", "application/json", + "{\"json\": \"someValue\"}".getBytes()); + mockMvc.perform(MockMvcRequestBuilders.fileUpload("/upload").file(jsonFile)).andExpect(status().isOk()); + } + +} diff --git a/spring-security-rest/src/test/java/org/baeldung/web/TestConfig.java b/spring-security-rest/src/test/java/org/baeldung/web/TestConfig.java index 8b55841508..bdce37dd10 100644 --- a/spring-security-rest/src/test/java/org/baeldung/web/TestConfig.java +++ b/spring-security-rest/src/test/java/org/baeldung/web/TestConfig.java @@ -1,10 +1,19 @@ package org.baeldung.web; +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; +import org.springframework.web.multipart.MultipartResolver; +import org.springframework.web.multipart.commons.CommonsMultipartResolver; @Configuration @ComponentScan({ "org.baeldung.web" }) public class TestConfig { + @Bean + public MultipartResolver multipartResolver() { + CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(); + return multipartResolver; + } + } \ No newline at end of file