diff --git a/cdi/src/test/java/com/baeldung/test/dependencyinjection/ImageProcessorUnitTest.java b/cdi/src/test/java/com/baeldung/test/dependencyinjection/ImageProcessorUnitTest.java index 8b5fa409c9..930e913109 100644 --- a/cdi/src/test/java/com/baeldung/test/dependencyinjection/ImageProcessorUnitTest.java +++ b/cdi/src/test/java/com/baeldung/test/dependencyinjection/ImageProcessorUnitTest.java @@ -1,70 +1,91 @@ package com.baeldung.test.dependencyinjection; -import com.baeldung.dependencyinjection.imagefileeditors.GifFileEditor; -import com.baeldung.dependencyinjection.imagefileeditors.JpgFileEditor; -import com.baeldung.dependencyinjection.imagefileeditors.PngFileEditor; -import com.baeldung.dependencyinjection.imageprocessors.ImageFileProcessor; -import com.baeldung.dependencyinjection.loggers.TimeLogger; -import java.text.SimpleDateFormat; -import java.util.Calendar; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.within; + +import java.text.ParseException; +import java.time.LocalTime; +import java.time.temporal.ChronoUnit; + import org.jboss.weld.environment.se.Weld; import org.jboss.weld.environment.se.WeldContainer; import org.junit.BeforeClass; import org.junit.Test; +import com.baeldung.dependencyinjection.imagefileeditors.PngFileEditor; +import com.baeldung.dependencyinjection.imageprocessors.ImageFileProcessor; +import com.baeldung.dependencyinjection.loggers.TimeLogger; + public class ImageProcessorUnitTest { - + private static ImageFileProcessor imageFileProcessor; - private static SimpleDateFormat dateFormat; - private static Calendar calendar; - - + @BeforeClass public static void setImageProcessorInstance() { Weld weld = new Weld(); WeldContainer container = weld.initialize(); - imageFileProcessor = container.select(ImageFileProcessor.class).get(); + imageFileProcessor = container.select(ImageFileProcessor.class) + .get(); container.shutdown(); } - - @BeforeClass - public static void setSimpleDateFormatInstance() { - dateFormat = new SimpleDateFormat("HH:mm"); - } - - @BeforeClass - public static void setCalendarInstance() { - calendar = Calendar.getInstance(); - } - + @Test public void givenImageProcessorInstance_whenInjectedPngFileEditorandTimeLoggerInstances_thenTwoAssertions() { assertThat(imageFileProcessor.getImageFileditor()).isInstanceOf(PngFileEditor.class); assertThat(imageFileProcessor.getTimeLogger()).isInstanceOf(TimeLogger.class); } - + @Test - public void givenImageProcessorInstance_whenCalledopenFile_thenOneAssertion() { - String currentTime = dateFormat.format(calendar.getTime()); - assertThat(imageFileProcessor.openFile("file1.png")).isEqualTo("Opening PNG file file1.png at: " + currentTime); + public void givenImageProcessorInstance_whenCalledopenFile_thenOneAssertion() throws ParseException { + LocalTime currentTime = LocalTime.now(); + + String openFileLog = imageFileProcessor.openFile("file1.png"); + assertThat(openFileLog).contains("Opening PNG file file1.png at: "); + + LocalTime loggedTime = getLoggedTime(openFileLog); + assertThat(loggedTime).isCloseTo(currentTime, within(2, ChronoUnit.MINUTES)); } - + @Test - public void givenImageProcessorInstance_whenCallededitFile_thenOneAssertion() { - String currentTime = dateFormat.format(calendar.getTime()); - assertThat(imageFileProcessor.editFile("file1.png")).isEqualTo("Editing PNG file file1.png at: " + currentTime); + public void givenImageProcessorInstance_whenCallededitFile_thenOneAssertion() throws ParseException { + LocalTime currentTime = LocalTime.now(); + + String editFileLog = imageFileProcessor.editFile("file1.png"); + assertThat(editFileLog).contains("Editing PNG file file1.png at: "); + + LocalTime loggedTime = getLoggedTime(editFileLog); + assertThat(loggedTime).isCloseTo(currentTime, within(2, ChronoUnit.MINUTES)); } - + @Test - public void givenImageProcessorInstance_whenCalledwriteFile_thenOneAssertion() { - String currentTime = dateFormat.format(calendar.getTime()); - assertThat(imageFileProcessor.writeFile("file1.png")).isEqualTo("Writing PNG file file1.png at: " + currentTime); + public void givenImageProcessorInstance_whenCalledwriteFile_thenOneAssertion() throws ParseException { + LocalTime currentTime = LocalTime.now(); + + String writeFileLog = imageFileProcessor.writeFile("file1.png"); + assertThat(writeFileLog).contains("Writing PNG file file1.png at: "); + + LocalTime loggedTime = getLoggedTime(writeFileLog); + assertThat(loggedTime).isCloseTo(currentTime, within(2, ChronoUnit.MINUTES)); } - + @Test - public void givenImageProcessorInstance_whenCalledsaveFile_thenOneAssertion() { - String currentTime = dateFormat.format(calendar.getTime()); - assertThat(imageFileProcessor.saveFile("file1.png")).isEqualTo("Saving PNG file file1.png at: " + currentTime); + public void givenImageProcessorInstance_whenCalledsaveFile_thenOneAssertion() throws ParseException { + LocalTime currentTime = LocalTime.now(); + + String saveFileLog = imageFileProcessor.saveFile("file1.png"); + assertThat(saveFileLog).contains("Saving PNG file file1.png at: "); + + LocalTime loggedTime = getLoggedTime(saveFileLog); + assertThat(loggedTime).isCloseTo(currentTime, within(2, ChronoUnit.MINUTES)); + } + + private LocalTime getLoggedTime(String log) throws ParseException { + String logTimeString = log.split("at: ")[1]; + + int hour = Integer.valueOf(logTimeString.split(":")[0]); + int minutes = Integer.valueOf(logTimeString.split(":")[1]); + + LocalTime loggedTime = LocalTime.of(hour, minutes); + return loggedTime; } } \ No newline at end of file diff --git a/core-java-8/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest.java b/core-java-8/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest.java index 4df3482633..df6c72d346 100644 --- a/core-java-8/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest.java +++ b/core-java-8/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest.java @@ -5,25 +5,22 @@ */ package com.baeldung.nullsafecollectionstreams; +import static org.junit.Assert.assertEquals; + import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.stream.Stream; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; + import org.junit.Test; -import static org.junit.Assert.*; /** * * @author Kwaje Anthony */ public class NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest { - - private final NullSafeCollectionStreamsUsingJava8OptionalContainer instance = - new NullSafeCollectionStreamsUsingJava8OptionalContainer(); + + private final NullSafeCollectionStreamsUsingJava8OptionalContainer instance = new NullSafeCollectionStreamsUsingJava8OptionalContainer(); @Test public void whenCollectionIsNull_thenExpectAnEmptyStream() { @@ -49,5 +46,5 @@ public class NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest { assertEquals(iter1.next(), iter2.next()); assert !iter1.hasNext() && !iter2.hasNext(); } - + } diff --git a/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeUnitTest.java b/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeUnitTest.java index 1689a5054d..ec20b7794b 100644 --- a/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeUnitTest.java +++ b/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeUnitTest.java @@ -1,7 +1,6 @@ package com.baeldung.util; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; import java.time.Clock; import java.time.Instant; @@ -10,8 +9,6 @@ import java.time.LocalTime; import java.time.ZoneId; import java.time.temporal.ChronoField; -import org.joda.time.DateTime; -import org.joda.time.DateTimeUtils; import org.junit.Test; public class CurrentDateTimeUnitTest { diff --git a/core-java-9/src/main/java/com/baeldung/java9/process/ChildProcess.java b/core-java-9/src/main/java/com/baeldung/java9/process/ChildProcess.java new file mode 100644 index 0000000000..46c2e688ce --- /dev/null +++ b/core-java-9/src/main/java/com/baeldung/java9/process/ChildProcess.java @@ -0,0 +1,15 @@ +package com.baeldung.java9.process; + +import java.util.Scanner; +import java.util.logging.Level; +import java.util.logging.Logger; + +public class ChildProcess { + + public static void main(String[] args) { + @SuppressWarnings("resource") + Scanner input = new Scanner(System.in); + Logger log = Logger.getLogger(ChildProcess.class.getName()); + log.log(Level.INFO, input.nextLine()); + } +} diff --git a/core-java-9/src/main/java/com/baeldung/java9/process/OutputStreamExample.java b/core-java-9/src/main/java/com/baeldung/java9/process/OutputStreamExample.java new file mode 100644 index 0000000000..443847916a --- /dev/null +++ b/core-java-9/src/main/java/com/baeldung/java9/process/OutputStreamExample.java @@ -0,0 +1,16 @@ +package com.baeldung.java9.process; + +import java.util.logging.Level; +import java.util.logging.Logger; + +public class OutputStreamExample { + + public static void main(String[] args) { + Logger log = Logger.getLogger(OutputStreamExample.class.getName()); + log.log(Level.INFO, Integer.toString(sum(1,2))); + } + + public static int sum(int a, int b) { + return a + b; + } +} diff --git a/core-java-9/src/main/java/com/baeldung/java9/process/ProcessCompilationError.java b/core-java-9/src/main/java/com/baeldung/java9/process/ProcessCompilationError.java new file mode 100644 index 0000000000..8b6ae0b441 --- /dev/null +++ b/core-java-9/src/main/java/com/baeldung/java9/process/ProcessCompilationError.java @@ -0,0 +1,7 @@ +package com.baeldung.java9.process; + +public class ProcessCompilationError { + //This method has been written to generate error to display + //how process errorStream() can consume error + public static void(); +} diff --git a/core-java-9/src/main/java/com/baeldung/java9/process/ProcessUnderstanding.java b/core-java-9/src/main/java/com/baeldung/java9/process/ProcessUnderstanding.java new file mode 100644 index 0000000000..74101ba3da --- /dev/null +++ b/core-java-9/src/main/java/com/baeldung/java9/process/ProcessUnderstanding.java @@ -0,0 +1,110 @@ +package com.baeldung.java9.process; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.io.Writer; +import java.util.Optional; +import java.util.logging.Level; +import java.util.logging.Logger; + +public class ProcessUnderstanding { + + public static int compileAndRunJavaProgram() throws IOException { + Process process = Runtime.getRuntime() + .exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\OutputStreamExample.java"); + process = Runtime.getRuntime() + .exec("java -cp src/main/java com.baeldung.java9.process.OutputStreamExample"); + BufferedReader output = new BufferedReader(new InputStreamReader(process.getInputStream())); + int value = Integer.parseInt(output.readLine()); + return value; + } + + public static String getErrorStreamExample() throws IOException { + Process process = Runtime.getRuntime() + .exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\ProcessCompilationError.java"); + BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream())); + String errorString = error.readLine(); + return errorString; + } + + public static void creatingNewProcess() throws IOException { + ProcessBuilder builder = new ProcessBuilder("notepad.exe"); + Process process = builder.start(); + } + + public static int filterProcessWithStreamsInSpecificRangeReturnCount() { + return (int) ProcessHandle.allProcesses() + .filter(ph -> (ph.pid() > 10000 && ph.pid() < 50000)) + .count(); + } + + public static void destroyingProcessCreatedBySameProcess() throws IOException, InterruptedException { + ProcessBuilder builder = new ProcessBuilder("notepad.exe"); + Process process = builder.start(); + Thread.sleep(10000); + process.destroy(); + } + + public static void destroyingProcessCreatedByDifferentProcess() { + // find out the process id of current running task by checking + // task manager in windows and enter the integer value + Optional optionalProcessHandle = ProcessHandle.of(5232); + ProcessHandle processHandle = optionalProcessHandle.get(); + processHandle.destroy(); + } + + public static int waitForExample() throws IOException, InterruptedException { + ProcessBuilder builder = new ProcessBuilder("notepad.exe"); + Process process = builder.start(); + return process.waitFor(); + } + + public static int exitValueExample() throws IOException { + ProcessBuilder builder = new ProcessBuilder("notepad.exe"); + Process process = builder.start(); + process.destroy(); + return process.exitValue(); + } + + public static void destroyExample() throws IOException, InterruptedException { + ProcessBuilder builder = new ProcessBuilder("notepad.exe"); + Process process = builder.start(); + Thread.sleep(10000); + process.destroy(); + } + + public static void destroyForciblyExample() throws IOException, InterruptedException { + ProcessBuilder builder = new ProcessBuilder("notepad.exe"); + Process process = builder.start(); + Thread.sleep(10000); + process.destroy(); + if (process.isAlive()) { + process.destroyForcibly(); + } + } + + public static void outputStreamDemo() throws IOException, InterruptedException { + Logger log = Logger.getLogger(ProcessUnderstanding.class.getName()); + Process pr = Runtime.getRuntime() + .exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\ChildProcess.java"); + final Process process = Runtime.getRuntime() + .exec("java -cp src/main/java com.baeldung.java9.process.ChildProcess"); + try (Writer w = new OutputStreamWriter(process.getOutputStream(), "UTF-8")) { + w.write("send to child\n"); + } + new Thread(() -> { + try { + int c; + while ((c = process.getInputStream() + .read()) != -1) + System.out.write((byte) c); + } catch (Exception e) { + e.printStackTrace(); + } + }).start(); + // send to child + log.log(Level.INFO, "rc=" + process.waitFor()); + } +} diff --git a/core-java-9/src/test/java/com/baeldung/java9/process/ProcessUnderstandingTest.java b/core-java-9/src/test/java/com/baeldung/java9/process/ProcessUnderstandingTest.java new file mode 100644 index 0000000000..2f61846c1c --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/process/ProcessUnderstandingTest.java @@ -0,0 +1,121 @@ +package com.baeldung.java9.process; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.lang.String; +import java.util.Optional; +import java.util.concurrent.TimeUnit; +import java.lang.Integer; + +import org.junit.jupiter.api.Test; + +class ProcessUnderstandingTest { + + @Test + public void givenSourceProgram_whenExecutedFromAnotherProgram_thenSourceProgramOutput3() throws IOException { + Process process = Runtime.getRuntime() + .exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\OutputStreamExample.java"); + process = Runtime.getRuntime() + .exec("java -cp src/main/java com.baeldung.java9.process.OutputStreamExample"); + BufferedReader output = new BufferedReader(new InputStreamReader(process.getInputStream())); + int value = Integer.parseInt(output.readLine()); + assertEquals(3, value); + } + + @Test + public void givenSourceProgram_whenReadingInputStream_thenFirstLineEquals3() throws IOException { + Process process = Runtime.getRuntime() + .exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\OutputStreamExample.java"); + process = Runtime.getRuntime() + .exec("java -cp src/main/java com.baeldung.java9.process.OutputStreamExample"); + BufferedReader output = new BufferedReader(new InputStreamReader(process.getInputStream())); + int value = Integer.parseInt(output.readLine()); + assertEquals(3, value); + } + + @Test + public void givenSubProcess_whenEncounteringError_thenErrorStreamNotNull() throws IOException { + Process process = Runtime.getRuntime() + .exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\ProcessCompilationError.java"); + BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream())); + String errorString = error.readLine(); + assertNotNull(errorString); + } + + //@Test - windows specific + public void givenSubProcess_thenStartSuccessIsAlive() throws IOException { + ProcessBuilder builder = new ProcessBuilder("notepad.exe"); + assertTrue(builder.start().isAlive()); + } + + //@Test - windows specific + public void givenSubProcess_whenDestroying_thenProcessNotAlive() throws IOException, InterruptedException { + ProcessBuilder builder = new ProcessBuilder("notepad.exe"); + Process process = builder.start(); + Thread.sleep(10000); + process.destroy(); + assertFalse(process.isAlive()); + } + + //@Test - windows specific + public void givenSubProcess_whenAlive_thenDestroyForcibly() throws IOException, InterruptedException { + ProcessBuilder builder = new ProcessBuilder("notepad.exe"); + Process process = builder.start(); + Thread.sleep(10000); + process.destroy(); + if (process.isAlive()) { + process.destroyForcibly(); + } + assertFalse(process.isAlive()); + } + + //@Test - windows specific + public void givenSubProcess_checkAlive() throws IOException, InterruptedException { + ProcessBuilder builder = new ProcessBuilder("notepad.exe"); + Process process = builder.start(); + Thread.sleep(10000); + process.destroy(); + assertFalse(process.isAlive()); + } + + @Test + public void givenProcessNotCreated_fromWithinJavaApplicationDestroying_thenProcessNotAlive() { + Optional optionalProcessHandle = ProcessHandle.of(5232); + ProcessHandle processHandle = optionalProcessHandle.get(); + processHandle.destroy(); + assertFalse(processHandle.isAlive()); + } + + //@Test - windows specific + public void givenSubProcess_whenCurrentThreadWaitsIndefinitelyuntilSubProcessEnds_thenProcessWaitForReturnsGrt0() throws IOException, InterruptedException { + ProcessBuilder builder = new ProcessBuilder("notepad.exe"); + Process process = builder.start(); + assertThat(process.waitFor() >= 0); + } + + //@Test - windows specific + public void givenSubProcess_whenCurrentThreadWaitsAndSubProcessNotTerminated_thenProcessWaitForReturnsFalse() throws IOException, InterruptedException { + ProcessBuilder builder = new ProcessBuilder("notepad.exe"); + Process process = builder.start(); + assertFalse(process.waitFor(1, TimeUnit.SECONDS)); + } + + //@Test - windows specific + public void givenSubProcess_whenCurrentThreadWillNotWaitIndefinitelyforSubProcessToEnd_thenProcessExitValueReturnsGrt0() throws IOException { + ProcessBuilder builder = new ProcessBuilder("notepad.exe"); + Process process = builder.start(); + assertThat(process.exitValue() >= 0); + } + + @Test + public void givenRunningProcesses_whenFilterOnProcessIdRange_thenGetSelectedProcessPid() { + assertThat(((int) ProcessHandle.allProcesses() + .filter(ph -> (ph.pid() > 10000 && ph.pid() < 50000)) + .count()) > 0); + } +} diff --git a/core-java/src/main/java/com/baeldung/linesintersection/LinesIntersectionService.java b/core-java/src/main/java/com/baeldung/linesintersection/LinesIntersectionService.java new file mode 100644 index 0000000000..a2cce53c8f --- /dev/null +++ b/core-java/src/main/java/com/baeldung/linesintersection/LinesIntersectionService.java @@ -0,0 +1,21 @@ +package com.baeldung.linesintersection; + +import java.awt.Point; +import java.util.Optional; + +public class LinesIntersectionService { + + public Optional calculateIntersectionPoint(double m1, double b1, double m2, double b2) { + + if (m1 == m2) { + return Optional.empty(); + } + + double x = (b2 - b1) / (m1 - m2); + double y = m1 * x + b1; + + Point point = new Point(); + point.setLocation(x, y); + return Optional.of(point); + } +} diff --git a/core-java/src/test/java/com/baeldung/linesintersection/LinesIntersectionServiceUnitTest.java b/core-java/src/test/java/com/baeldung/linesintersection/LinesIntersectionServiceUnitTest.java new file mode 100644 index 0000000000..47f1fd45a1 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/linesintersection/LinesIntersectionServiceUnitTest.java @@ -0,0 +1,40 @@ +package com.baeldung.linesintersection; + +import java.awt.Point; +import java.util.Optional; + +import org.junit.Test; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertEquals; + +public class LinesIntersectionServiceUnitTest { + private LinesIntersectionService service = new LinesIntersectionService(); + + @Test + public void givenNotParallelLines_whenCalculatePoint_thenPresent() { + + double m1 = 0; + double b1 = 0; + double m2 = 1; + double b2 = -1; + + Optional point = service.calculateIntersectionPoint(m1, b1, m2, b2); + + assertTrue(point.isPresent()); + assertEquals(point.get().getX(), 1, 0.001); + assertEquals(point.get().getX(), 1, 0.001); + } + + @Test + public void givenParallelLines_whenCalculatePoint_thenEmpty() { + double m1 = 1; + double b1 = 0; + double m2 = 1; + double b2 = -1; + + Optional point = service.calculateIntersectionPoint(m1, b1, m2, b2); + + assertFalse(point.isPresent()); + } +} diff --git a/java-streams/pom.xml b/java-streams/pom.xml index 75914f0247..4f8651a756 100644 --- a/java-streams/pom.xml +++ b/java-streams/pom.xml @@ -1,7 +1,6 @@ 4.0.0 - com.baeldung java-streams 0.1.0-SNAPSHOT jar @@ -15,17 +14,17 @@ - - - org.openjdk.jmh - jmh-core - ${jmh.version} - - - org.openjdk.jmh - jmh-generator-annprocess - ${jmh.version} - provided + + + org.openjdk.jmh + jmh-core + ${jmh.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${jmh.version} + provided org.apache.commons diff --git a/java-streams/src/test/java/com/baeldung/stream/PrimitiveStreamsUnitTest.java b/java-streams/src/test/java/com/baeldung/stream/PrimitiveStreamsUnitTest.java index 2c88dc5ec7..67954f0bba 100644 --- a/java-streams/src/test/java/com/baeldung/stream/PrimitiveStreamsUnitTest.java +++ b/java-streams/src/test/java/com/baeldung/stream/PrimitiveStreamsUnitTest.java @@ -1,15 +1,14 @@ package com.baeldung.stream; -import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; -import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import org.junit.Test; public class PrimitiveStreamsUnitTest { @@ -17,7 +16,7 @@ public class PrimitiveStreamsUnitTest { @Test public void givenAnArrayOfIntegersWhenMinIsCalledThenCorrectMinIsReturned() { - int[] integers = new int[] {20, 98, 12, 7, 35}; + int[] integers = new int[] { 20, 98, 12, 7, 35 }; int min = streams.min(integers); // returns 7 assertEquals(7, min); @@ -66,19 +65,14 @@ public class PrimitiveStreamsUnitTest { @Test public void givenAnArrayWhenSumIsCalledThenTheCorrectSumIsReturned() { - int sum = Stream.of(33,45) - .mapToInt(i -> i) - .sum(); + int sum = Stream.of(33, 45).mapToInt(i -> i).sum(); assertEquals(78, sum); } @Test public void givenAnIntStreamThenGetTheEvenIntegers() { - List evenInts = IntStream.rangeClosed(1, 10) - .filter(i -> i % 2 == 0) - .boxed() - .collect(Collectors.toList()); + List evenInts = IntStream.rangeClosed(1, 10).filter(i -> i % 2 == 0).boxed().collect(Collectors.toList()); List expected = IntStream.of(2, 4, 6, 8, 10).boxed().collect(Collectors.toList()); diff --git a/java-strings/src/main/java/com/baeldung/string/sorting/AnagramValidator.java b/java-strings/src/main/java/com/baeldung/string/sorting/AnagramValidator.java new file mode 100644 index 0000000000..c4f684383d --- /dev/null +++ b/java-strings/src/main/java/com/baeldung/string/sorting/AnagramValidator.java @@ -0,0 +1,29 @@ +package com.baeldung.string.sorting; + +import java.util.Arrays; + +public class AnagramValidator { + + public static boolean isValid(String text, String anagram) { + text = prepare(text); + anagram = prepare(anagram); + + String sortedText = sort(text); + String sortedAnagram = sort(anagram); + + return sortedText.equals(sortedAnagram); + } + + private static String sort(String text) { + char[] chars = prepare(text).toCharArray(); + + Arrays.sort(chars); + return new String(chars); + } + + private static String prepare(String text) { + return text.toLowerCase() + .trim() + .replaceAll("\\s+", ""); + } +} \ No newline at end of file diff --git a/java-strings/src/test/java/com/baeldung/string/sorting/AnagramValidatorUnitTest.java b/java-strings/src/test/java/com/baeldung/string/sorting/AnagramValidatorUnitTest.java new file mode 100644 index 0000000000..07d31c7187 --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/string/sorting/AnagramValidatorUnitTest.java @@ -0,0 +1,26 @@ +package com.baeldung.string.sorting; + + +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; + +import org.junit.jupiter.api.Test; + +import com.baeldung.string.sorting.AnagramValidator; + +class AnagramValidatorUnitTest { + + @Test + void givenValidAnagrams_whenSorted_thenEqual() { + boolean isValidAnagram = AnagramValidator.isValid("Avida Dollars", "Salvador Dali"); + + assertTrue(isValidAnagram); + } + + @Test + void givenNotValidAnagrams_whenSorted_thenNotEqual() { + boolean isValidAnagram = AnagramValidator.isValid("abc", "def"); + + assertFalse(isValidAnagram); + } +} diff --git a/java-strings/src/test/java/com/baeldung/string/sorting/SortStringUnitTest.java b/java-strings/src/test/java/com/baeldung/string/sorting/SortStringUnitTest.java new file mode 100644 index 0000000000..90d1dad554 --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/string/sorting/SortStringUnitTest.java @@ -0,0 +1,31 @@ +package com.baeldung.string.sorting; + +import java.util.Arrays; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class SortStringUnitTest { + + @Test + void givenString_whenSort_thenSorted() { + String abcd = "bdca"; + char[] chars = abcd.toCharArray(); + + Arrays.sort(chars); + String sorted = new String(chars); + + assertThat(sorted).isEqualTo("abcd"); + } + + @Test + void givenString_whenSortJava8_thenSorted() { + String sorted = "bdca".chars() + .sorted() + .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append) + .toString(); + + assertThat(sorted).isEqualTo("abcd"); + } +} diff --git a/jersey-client-rx/pom.xml b/jersey-client-rx/pom.xml deleted file mode 100644 index 24894869a5..0000000000 --- a/jersey-client-rx/pom.xml +++ /dev/null @@ -1,67 +0,0 @@ - - - 4.0.0 - com.baeldung.samples - jersey-client-rx - 1.0 - jar - - - org.glassfish.jersey.inject - jersey-hk2 - 2.27 - - - org.glassfish.jersey.core - jersey-client - 2.27 - - - org.glassfish.jersey.ext.rx - jersey-rx-client-rxjava - 2.27 - - - org.glassfish.jersey.ext.rx - jersey-rx-client-rxjava2 - 2.27 - - - com.github.tomakehurst - wiremock - 1.58 - test - - - org.junit.vintage - junit-vintage-engine - 5.2.0 - - - org.glassfish.jersey.media - jersey-media-json-jackson - 2.25 - - - com.fasterxml.jackson.jaxrs - jackson-jaxrs-json-provider - 2.4.1 - - - org.slf4j - slf4j-jdk14 - 1.7.25 - - - org.assertj - assertj-core - 3.10.0 - test - - - - UTF-8 - 1.8 - 1.8 - - \ No newline at end of file diff --git a/jersey-client-rx/readme.md b/jersey-client-rx/readme.md deleted file mode 100644 index d1bc4e950b..0000000000 --- a/jersey-client-rx/readme.md +++ /dev/null @@ -1,3 +0,0 @@ -# Fluent, Reactive Jersey Client Orchestration # - -### Sample code demonstrating the options for asynchronous, reactive RESTful service consumption with JAX-RS ### diff --git a/pom.xml b/pom.xml index 938315f5dc..92df840079 100644 --- a/pom.xml +++ b/pom.xml @@ -585,7 +585,6 @@ spring-security-thymeleaf persistence-modules/java-jdbi jersey - jersey-client-rx java-spi performance-tests twilio diff --git a/spring-boot-bootstrap/cloudfoundry/manifest.yml b/spring-boot-bootstrap/cloudfoundry/manifest.yml new file mode 100755 index 0000000000..80fce8ff4b --- /dev/null +++ b/spring-boot-bootstrap/cloudfoundry/manifest.yml @@ -0,0 +1,10 @@ +--- +applications: +- name: spring-boot-bootstrap + memory: 768M + random-route: true + path: ../target/spring-boot-bootstrap-cf.jar + env: + SPRING_PROFILES_ACTIVE: cloud,mysql + services: + - spring-bootstrap-db diff --git a/spring-boot-bootstrap/pom.xml b/spring-boot-bootstrap/pom.xml index 5868694e5b..c1ce4df6e2 100644 --- a/spring-boot-bootstrap/pom.xml +++ b/spring-boot-bootstrap/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 org.baeldung spring-boot-bootstrap @@ -14,6 +14,17 @@ 0.0.1-SNAPSHOT ../parent-boot-2 + + + + org.springframework.cloud + spring-cloud-dependencies + Finchley.SR1 + pom + import + + + @@ -28,10 +39,22 @@ org.springframework.boot spring-boot-starter-data-jpa + + org.springframework.cloud + spring-cloud-starter + + + org.springframework.boot + spring-boot-starter-cloud-connectors + com.h2database h2 + + mysql + mysql-connector-java + org.springframework.boot spring-boot-starter-security @@ -55,6 +78,47 @@ + + cloudfoundry + + + org.springframework.cloud + spring-cloud-starter + + + org.springframework.boot + spring-boot-starter-cloud-connectors + + + + + + src/main/resources + + **/logback.xml + + + + + + org.springframework.boot + spring-boot-maven-plugin + + ${project.name}-cf + + + + org.apache.maven.plugins + maven-compiler-plugin + + + **/cloud/config/*.java + + + + + + autoconfiguration @@ -112,7 +176,19 @@ - + + + + org.apache.maven.plugins + maven-compiler-plugin + + + **/cloud/*.java + + + + + 4.0.0 diff --git a/spring-boot-bootstrap/src/main/java/org/baeldung/cloud/config/CloudDataSourceConfig.java b/spring-boot-bootstrap/src/main/java/org/baeldung/cloud/config/CloudDataSourceConfig.java new file mode 100755 index 0000000000..b9f9598ca3 --- /dev/null +++ b/spring-boot-bootstrap/src/main/java/org/baeldung/cloud/config/CloudDataSourceConfig.java @@ -0,0 +1,19 @@ +package org.baeldung.cloud.config; + +import org.springframework.cloud.config.java.AbstractCloudConfig; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; + +import javax.sql.DataSource; + +@Configuration +@Profile("cloud") +public class CloudDataSourceConfig extends AbstractCloudConfig { + + @Bean + public DataSource dataSource() { + return connectionFactory().dataSource(); + } + +} diff --git a/spring-boot-bootstrap/src/main/resources/application-local.properties b/spring-boot-bootstrap/src/main/resources/application-local.properties new file mode 100644 index 0000000000..8c1c677988 --- /dev/null +++ b/spring-boot-bootstrap/src/main/resources/application-local.properties @@ -0,0 +1,20 @@ +server.port = 8081 + +spring.application.name = Bootstrap Spring Boot + +spring.thymeleaf.cache = false +spring.thymeleaf.enabled=true +spring.thymeleaf.prefix=classpath:/templates/ +spring.thymeleaf.suffix=.html + +spring.security.user.name=john +spring.security.user.password=123 + +spring.datasource.driver-class-name=org.h2.Driver +spring.datasource.url=jdbc:h2:mem:bootapp;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE +spring.datasource.username=sa +spring.datasource.password= +spring.jpa.database-platform=org.hibernate.dialect.H2Dialect + +server.error.path=/error +server.error.whitelabel.enabled=false \ No newline at end of file diff --git a/spring-boot-bootstrap/src/main/resources/application-mysql.properties b/spring-boot-bootstrap/src/main/resources/application-mysql.properties new file mode 100644 index 0000000000..a1823b5d7f --- /dev/null +++ b/spring-boot-bootstrap/src/main/resources/application-mysql.properties @@ -0,0 +1 @@ +spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect \ No newline at end of file diff --git a/spring-boot-bootstrap/src/main/resources/application.properties b/spring-boot-bootstrap/src/main/resources/application.properties index e50268d32c..eee89ca460 100644 --- a/spring-boot-bootstrap/src/main/resources/application.properties +++ b/spring-boot-bootstrap/src/main/resources/application.properties @@ -1,19 +1,11 @@ -server.port = 8081 - -spring.application.name = Bootstrap Spring Boot - +server.port=${port:8080} +spring.application.name = Bootstrap Spring Cloud spring.thymeleaf.cache = false spring.thymeleaf.enabled=true spring.thymeleaf.prefix=classpath:/templates/ spring.thymeleaf.suffix=.html -spring.security.user.name=john -spring.security.user.password=123 - -spring.datasource.driver-class-name=org.h2.Driver -spring.datasource.url=jdbc:h2:mem:bootapp;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE -spring.datasource.username=sa -spring.datasource.password= - server.error.path=/error -server.error.whitelabel.enabled=false \ No newline at end of file +server.error.whitelabel.enabled=false + +spring.jpa.generate-ddl=true \ No newline at end of file diff --git a/spring-boot-persistence/pom.xml b/spring-boot-persistence/pom.xml index a16d953581..08989edfa9 100644 --- a/spring-boot-persistence/pom.xml +++ b/spring-boot-persistence/pom.xml @@ -1,57 +1,75 @@ - - 4.0.0 + + + 4.0.0 + + com.baeldung + spring-boot-persistence + 0.1.0 + + + parent-boot-2 com.baeldung - spring-boot-persistence 0.0.1-SNAPSHOT - jar - spring-boot-persistence - This is a simple Spring Data Repositories test - - - parent-boot-2 - com.baeldung - 0.0.1-SNAPSHOT - ../parent-boot-2 - - - - - org.springframework.boot - spring-boot-starter-data-jpa - - - com.h2database - h2 - - - org.springframework.boot - spring-boot-starter - - - - - spring-boot-persistence - - - src/main/resources - true - - - - - org.apache.maven.plugins - maven-war-plugin - - - pl.project13.maven - git-commit-id-plugin - ${git-commit-id-plugin.version} - - - - - - 2.2.4 - - \ No newline at end of file + ../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + com.zaxxer + HikariCP + + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.apache.tomcat + tomcat-jdbc + ${tomcat-jdbc.version} + + + mysql + mysql-connector-java + ${mysql-connector-java.version} + + + com.h2database + h2 + ${h2database.version} + runtime + + + + + UTF-8 + 1.8 + 8.0.12 + 9.0.10 + 1.4.197 + + + + spring-boot-persistence + + + src/main/resources + true + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/SpringBootConsoleApplication.java b/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/SpringBootConsoleApplication.java new file mode 100644 index 0000000000..ff37442cd4 --- /dev/null +++ b/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/SpringBootConsoleApplication.java @@ -0,0 +1,22 @@ +package com.baeldung.tomcatconnectionpool.application; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.domain.EntityScan; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +@SpringBootApplication +@EnableAutoConfiguration +@ComponentScan(basePackages={"com.baeldung.tomcatconnectionpool.application"}) +@EnableJpaRepositories(basePackages="com.baeldung.tomcatconnectionpool.application.repositories") +@EnableTransactionManagement +@EntityScan(basePackages="com.baeldung.tomcatconnectionpool.application.entities") +public class SpringBootConsoleApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringBootConsoleApplication.class); + } +} diff --git a/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/entities/Customer.java b/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/entities/Customer.java new file mode 100644 index 0000000000..4003d5aca9 --- /dev/null +++ b/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/entities/Customer.java @@ -0,0 +1,53 @@ +package com.baeldung.tomcatconnectionpool.application.entities; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "customers") +public class Customer { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private long id; + @Column(name = "first_name") + private String firstName; + @Column(name = "last_name") + private String lastName; + + public Customer() {} + + public Customer(String firstName, String lastName) { + this.firstName = firstName; + this.lastName = lastName; + } + + public long getId() { + return id; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + @Override + public String toString() { + return "Customer{" + "id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + '}'; + } +} diff --git a/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/repositories/CustomerRepository.java b/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/repositories/CustomerRepository.java new file mode 100644 index 0000000000..770906439c --- /dev/null +++ b/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/repositories/CustomerRepository.java @@ -0,0 +1,12 @@ +package com.baeldung.tomcatconnectionpool.application.repositories; + +import com.baeldung.tomcatconnectionpool.application.entities.Customer; +import java.util.List; +import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface CustomerRepository extends CrudRepository { + + List findByLastName(String lastName); +} diff --git a/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/runners/CommandLineCrudRunner.java b/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/runners/CommandLineCrudRunner.java new file mode 100644 index 0000000000..9666bac5a5 --- /dev/null +++ b/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/runners/CommandLineCrudRunner.java @@ -0,0 +1,37 @@ +package com.baeldung.tomcatconnectionpool.application.runners; + +import com.baeldung.tomcatconnectionpool.application.entities.Customer; +import com.baeldung.tomcatconnectionpool.application.repositories.CustomerRepository; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.CommandLineRunner; +import org.springframework.stereotype.Component; + +@Component +public class CommandLineCrudRunner implements CommandLineRunner { + + private static final Logger logger = LoggerFactory.getLogger(CommandLineCrudRunner.class); + + @Autowired + private CustomerRepository customerRepository; + + @Override + public void run(String... args) throws Exception { + customerRepository.save(new Customer("John", "Doe")); + customerRepository.save(new Customer("Jennifer", "Wilson")); + + logger.info("Customers found with findAll():"); + customerRepository.findAll().forEach(c -> logger.info(c.toString())); + + logger.info("Customer found with findById(1L):"); + Customer customer = customerRepository.findById(1L) + .orElseGet(() -> new Customer("Non-existing customer", "")); + logger.info(customer.toString()); + + logger.info("Customer found with findByLastName('Wilson'):"); + customerRepository.findByLastName("Wilson").forEach(c -> { + logger.info(c.toString()); + }); + } +} diff --git a/spring-boot-persistence/src/main/resources/application.properties b/spring-boot-persistence/src/main/resources/application.properties index d0fb785fe8..303ce33c25 100644 --- a/spring-boot-persistence/src/main/resources/application.properties +++ b/spring-boot-persistence/src/main/resources/application.properties @@ -1,2 +1,16 @@ -spring.jpa.show-sql=true -spring.jpa.hibernate.ddl-auto=none \ No newline at end of file +spring.datasource.tomcat.initial-size=15 +spring.datasource.tomcat.max-wait=20000 +spring.datasource.tomcat.max-active=50 +spring.datasource.tomcat.max-idle=15 +spring.datasource.tomcat.min-idle=8 +spring.datasource.tomcat.default-auto-commit=true +spring.datasource.url=jdbc:h2:mem:test +spring.datasource.username=root +spring.datasource.password= +spring.datasource.driver-class-name=org.h2.Driver + +spring.jpa.show-sql=false +spring.jpa.hibernate.ddl-auto=update +spring.jpa.hibernate.naming-strategy=org.hibernate.cfg.ImprovedNamingStrategy +spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect +spring.jpa.properties.hibernate.id.new_generator_mappings=false diff --git a/spring-boot-persistence/src/test/java/com/baeldung/tomcatconnectionpool/test/application/SpringBootTomcatConnectionPoolIntegrationTest.java b/spring-boot-persistence/src/test/java/com/baeldung/tomcatconnectionpool/test/application/SpringBootTomcatConnectionPoolIntegrationTest.java new file mode 100644 index 0000000000..c68e137fb0 --- /dev/null +++ b/spring-boot-persistence/src/test/java/com/baeldung/tomcatconnectionpool/test/application/SpringBootTomcatConnectionPoolIntegrationTest.java @@ -0,0 +1,22 @@ +package com.baeldung.tomcatconnectionpool.test.application; + +import javax.sql.DataSource; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.junit4.SpringRunner; +import static org.assertj.core.api.Assertions.*; +import org.springframework.boot.test.context.SpringBootTest; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class SpringBootTomcatConnectionPoolIntegrationTest { + + @Autowired + private DataSource dataSource; + + @Test + public void givenTomcatConnectionPoolInstance_whenCheckedPoolClassName_thenCorrect() { + assertThat(dataSource.getClass().getName()).isEqualTo("org.apache.tomcat.jdbc.pool.DataSource"); + } +} diff --git a/spring-boot-security/pom.xml b/spring-boot-security/pom.xml index 5283a69c2d..18d292c8a1 100644 --- a/spring-boot-security/pom.xml +++ b/spring-boot-security/pom.xml @@ -44,6 +44,23 @@ org.springframework.boot spring-boot-starter-web + + + + org.springframework.security + spring-security-taglibs + + + + + org.apache.tomcat.embed + tomcat-embed-jasper + provided + + + javax.servlet + jstl + org.springframework.boot diff --git a/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/HomeController.java b/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/HomeController.java new file mode 100644 index 0000000000..eca093a76f --- /dev/null +++ b/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/HomeController.java @@ -0,0 +1,14 @@ +package com.baeldung.springsecuritytaglibs; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; + +@Controller +@RequestMapping("/") +public class HomeController { + + @RequestMapping + public String home() { + return "home"; + } +} diff --git a/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/SpringBootSecurityTagLibsApplication.java b/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/SpringBootSecurityTagLibsApplication.java new file mode 100644 index 0000000000..397ea47f96 --- /dev/null +++ b/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/SpringBootSecurityTagLibsApplication.java @@ -0,0 +1,9 @@ +package com.baeldung.springsecuritytaglibs; + +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.PropertySource; + +@SpringBootApplication +@PropertySource("classpath:application-taglibs.properties") +public class SpringBootSecurityTagLibsApplication { +} diff --git a/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/config/SpringBootSecurityTagLibsConfig.java b/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/config/SpringBootSecurityTagLibsConfig.java new file mode 100644 index 0000000000..665dd0bce9 --- /dev/null +++ b/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/config/SpringBootSecurityTagLibsConfig.java @@ -0,0 +1,31 @@ +package com.baeldung.springsecuritytaglibs.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@Configuration +@EnableWebSecurity +public class SpringBootSecurityTagLibsConfig extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + auth.inMemoryAuthentication() + .withUser("testUser") + .password("password") + .roles("ADMIN"); + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + // @formatter:off + http.csrf() + .and() + .authorizeRequests() + .antMatchers("/userManagement").hasRole("ADMIN") + .anyRequest().permitAll().and().httpBasic(); + // @formatter:on + } +} \ No newline at end of file diff --git a/spring-boot-security/src/main/resources/application-taglibs.properties b/spring-boot-security/src/main/resources/application-taglibs.properties new file mode 100644 index 0000000000..218868405f --- /dev/null +++ b/spring-boot-security/src/main/resources/application-taglibs.properties @@ -0,0 +1,3 @@ +#jsp config +spring.mvc.view.prefix: /WEB-INF/views/ +spring.mvc.view.suffix: .jsp diff --git a/spring-boot-security/src/main/resources/application.properties b/spring-boot-security/src/main/resources/application.properties index c2b8d70dc6..e776132359 100644 --- a/spring-boot-security/src/main/resources/application.properties +++ b/spring-boot-security/src/main/resources/application.properties @@ -1,4 +1,4 @@ #spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration #security.user.password=password #security.oauth2.client.client-id=client -#security.oauth2.client.client-secret=secret +#security.oauth2.client.client-secret=secret \ No newline at end of file diff --git a/spring-boot-security/src/main/webapp/WEB-INF/views/home.jsp b/spring-boot-security/src/main/webapp/WEB-INF/views/home.jsp new file mode 100644 index 0000000000..80ecd61cb5 --- /dev/null +++ b/spring-boot-security/src/main/webapp/WEB-INF/views/home.jsp @@ -0,0 +1,38 @@ +<%@ page language="java" contentType="text/html; charset=UTF-8" + pageEncoding="UTF-8"%> +<%@ taglib prefix="sec" + uri="http://www.springframework.org/security/tags"%> + + + + + +Home Page + + + + Login + + + + Logout + + + +

+ Welcome back, +

+ + Manage Users + +
+ + Text Field:
+ + + + Manage Users + +
+ + \ No newline at end of file diff --git a/spring-boot-security/src/test/java/com/baeldung/springsecuritytaglibs/HomeControllerUnitTest.java b/spring-boot-security/src/test/java/com/baeldung/springsecuritytaglibs/HomeControllerUnitTest.java new file mode 100644 index 0000000000..0585c06a59 --- /dev/null +++ b/spring-boot-security/src/test/java/com/baeldung/springsecuritytaglibs/HomeControllerUnitTest.java @@ -0,0 +1,60 @@ +package com.baeldung.springsecuritytaglibs; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = SpringBootSecurityTagLibsApplication.class) +public class HomeControllerUnitTest { + + @Autowired + private TestRestTemplate restTemplate; + + @Test + public void whenUserIsAuthenticatedThenAuthenticatedSectionsShowOnSite() throws Exception { + String body = this.restTemplate.withBasicAuth("testUser", "password") + .getForEntity("/", String.class) + .getBody(); + + // test + assertFalse(body.contains("Login")); + + // test + assertTrue(body.contains("Logout")); + + // test + assertTrue(body.contains("Manage Users")); + + // test + assertTrue(body.contains("testUser")); + + // test + assertTrue(body.contains("")); + + // test + assertTrue(body.contains(" + assertTrue(body.contains("")); + } + + @Test + public void whenUserIsNotAuthenticatedThenOnlyAnonymousSectionsShowOnSite() throws Exception { + String body = this.restTemplate.getForEntity("/", String.class) + .getBody(); + + // test + assertTrue(body.contains("Login")); + + // test + assertFalse(body.contains("Logout")); + } +} diff --git a/spring-jersey/pom.xml b/spring-jersey/pom.xml index 22adf265b1..40dc91a88d 100644 --- a/spring-jersey/pom.xml +++ b/spring-jersey/pom.xml @@ -76,6 +76,49 @@ test
+ + org.glassfish.jersey.inject + jersey-hk2 + ${jersey.version} + + + org.glassfish.jersey.ext.rx + jersey-rx-client-rxjava + ${jersey.version} + + + org.glassfish.jersey.ext.rx + jersey-rx-client-rxjava2 + ${jersey.version} + + + com.github.tomakehurst + wiremock + 1.58 + test + + + com.fasterxml.jackson.jaxrs + jackson-jaxrs-json-provider + 2.6.0 + + + com.fasterxml.jackson.core + jackson-databind + 2.6.0 + + + org.slf4j + slf4j-jdk14 + 1.7.25 + + + org.assertj + assertj-core + 3.10.0 + test + +
@@ -170,7 +213,7 @@ - 2.26 + 2.27 3.2.0 1.6.1 4.4.9 diff --git a/jersey-client-rx/src/test/java/com/baeldung/samples/jerseyrx/ClientOrchestrationIntegrationTest.java b/spring-jersey/src/test/java/com/baeldung/clientrx/ClientOrchestrationIntegrationTest.java similarity index 99% rename from jersey-client-rx/src/test/java/com/baeldung/samples/jerseyrx/ClientOrchestrationIntegrationTest.java rename to spring-jersey/src/test/java/com/baeldung/clientrx/ClientOrchestrationIntegrationTest.java index 88a8d67a7d..990279a481 100644 --- a/jersey-client-rx/src/test/java/com/baeldung/samples/jerseyrx/ClientOrchestrationIntegrationTest.java +++ b/spring-jersey/src/test/java/com/baeldung/clientrx/ClientOrchestrationIntegrationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.samples.jerseyrx; +package com.baeldung.clientrx; import static com.github.tomakehurst.wiremock.client.WireMock.*; import static org.assertj.core.api.Assertions.*;