Merge remote-tracking branch 'upstream/master'
This commit is contained in:
commit
b228144788
|
@ -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;
|
||||
}
|
||||
}
|
|
@ -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 <kwajeanthony@gmail.com>
|
||||
*/
|
||||
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();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
|
|
@ -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 {
|
||||
|
|
|
@ -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());
|
||||
}
|
||||
}
|
|
@ -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;
|
||||
}
|
||||
}
|
|
@ -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();
|
||||
}
|
|
@ -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<ProcessHandle> 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());
|
||||
}
|
||||
}
|
|
@ -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<ProcessHandle> 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);
|
||||
}
|
||||
}
|
|
@ -1,7 +1,6 @@
|
|||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>java-streams</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
|
@ -15,17 +14,17 @@
|
|||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<!-- https://mvnrepository.com/artifact/org.openjdk.jmh/jmh-core -->
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-core</artifactId>
|
||||
<version>${jmh.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-generator-annprocess</artifactId>
|
||||
<version>${jmh.version}</version>
|
||||
<scope>provided</scope>
|
||||
<!-- https://mvnrepository.com/artifact/org.openjdk.jmh/jmh-core -->
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-core</artifactId>
|
||||
<version>${jmh.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-generator-annprocess</artifactId>
|
||||
<version>${jmh.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
|
|
|
@ -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<Integer> evenInts = IntStream.rangeClosed(1, 10)
|
||||
.filter(i -> i % 2 == 0)
|
||||
.boxed()
|
||||
.collect(Collectors.toList());
|
||||
List<Integer> evenInts = IntStream.rangeClosed(1, 10).filter(i -> i % 2 == 0).boxed().collect(Collectors.toList());
|
||||
|
||||
List<Integer> expected = IntStream.of(2, 4, 6, 8, 10).boxed().collect(Collectors.toList());
|
||||
|
||||
|
|
|
@ -44,6 +44,23 @@
|
|||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- security taglib -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-taglibs</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- JSTL -->
|
||||
<dependency>
|
||||
<groupId>org.apache.tomcat.embed</groupId>
|
||||
<artifactId>tomcat-embed-jasper</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>jstl</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
|
|
|
@ -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";
|
||||
}
|
||||
}
|
|
@ -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 {
|
||||
}
|
|
@ -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
|
||||
}
|
||||
}
|
|
@ -0,0 +1,3 @@
|
|||
#jsp config
|
||||
spring.mvc.view.prefix: /WEB-INF/views/
|
||||
spring.mvc.view.suffix: .jsp
|
|
@ -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
|
|
@ -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"%>
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
|
||||
<sec:csrfMetaTags />
|
||||
<title>Home Page</title>
|
||||
</head>
|
||||
<body>
|
||||
<sec:authorize access="!isAuthenticated()">
|
||||
Login
|
||||
</sec:authorize>
|
||||
|
||||
<sec:authorize access="isAuthenticated()">
|
||||
Logout
|
||||
</sec:authorize>
|
||||
|
||||
<sec:authorize access="isAuthenticated()">
|
||||
<h2>
|
||||
Welcome back, <sec:authentication property="name" />
|
||||
</h2>
|
||||
<sec:authorize access="hasRole('ADMIN')">
|
||||
Manage Users
|
||||
</sec:authorize>
|
||||
<form method="post">
|
||||
<sec:csrfInput />
|
||||
Text Field: <br /> <input type="text" name="textField" />
|
||||
<input type="submit" value="Submit form with CSRF input">
|
||||
</form>
|
||||
<sec:authorize url="/userManagement">
|
||||
<a href="/userManagement">Manage Users</a>
|
||||
</sec:authorize>
|
||||
</sec:authorize>
|
||||
</body>
|
||||
</html>
|
|
@ -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 <sec:authorize access="!isAuthenticated()">
|
||||
assertFalse(body.contains("Login"));
|
||||
|
||||
// test <sec:authorize access="isAuthenticated()">
|
||||
assertTrue(body.contains("Logout"));
|
||||
|
||||
// test <sec:authorize access="hasRole('ADMIN')">
|
||||
assertTrue(body.contains("Manage Users"));
|
||||
|
||||
// test <sec:authentication property="principal.username" />
|
||||
assertTrue(body.contains("testUser"));
|
||||
|
||||
// test <sec:authorize url="/adminOnlyURL">
|
||||
assertTrue(body.contains("<a href=\"/userManagement\">"));
|
||||
|
||||
// test <sec:csrfInput />
|
||||
assertTrue(body.contains("<input type=\"hidden\" name=\"_csrf\" value=\""));
|
||||
|
||||
// test <sec:csrfMetaTags />
|
||||
assertTrue(body.contains("<meta name=\"_csrf_parameter\" content=\"_csrf\" />"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUserIsNotAuthenticatedThenOnlyAnonymousSectionsShowOnSite() throws Exception {
|
||||
String body = this.restTemplate.getForEntity("/", String.class)
|
||||
.getBody();
|
||||
|
||||
// test <sec:authorize access="!isAuthenticated()">
|
||||
assertTrue(body.contains("Login"));
|
||||
|
||||
// test <sec:authorize access="isAuthenticated()">
|
||||
assertFalse(body.contains("Logout"));
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue