Merge remote-tracking branch 'upstream/master'

This commit is contained in:
Philippe 2019-01-29 21:23:16 -02:00
commit 65a5783d01
86 changed files with 1548 additions and 293 deletions

View File

@ -0,0 +1,29 @@
package com.baeldung.java8.lambda.methodreference;
public class Bicycle {
private String brand;
private Integer frameSize;
public Bicycle(String brand, Integer frameSize) {
this.brand = brand;
this.frameSize = frameSize;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public Integer getFrameSize() {
return frameSize;
}
public void setFrameSize(Integer frameSize) {
this.frameSize = frameSize;
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.java8.lambda.methodreference;
import java.util.Comparator;
public class BicycleComparator implements Comparator<Bicycle> {
@Override
public int compare(Bicycle a, Bicycle b) {
return a.getFrameSize()
.compareTo(b.getFrameSize());
}
}

View File

@ -0,0 +1,70 @@
package com.baeldung.java8.lambda.methodreference;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.BiFunction;
import org.junit.Test;
public class MethodReferenceExamples {
private static <T> void doNothingAtAll(Object... o) {
}
;
@Test
public void referenceToStaticMethod() {
List<String> messages = Arrays.asList("Hello", "Baeldung", "readers!");
messages.forEach((word) -> {
System.out.println(word);
});
messages.forEach(System.out::println);
}
@Test
public void referenceToInstanceMethodOfParticularObject() {
BicycleComparator bikeFrameSizeComparator = new BicycleComparator();
createBicyclesList().stream()
.sorted((a, b) -> bikeFrameSizeComparator.compare(a, b));
createBicyclesList().stream()
.sorted(bikeFrameSizeComparator::compare);
}
@Test
public void referenceToInstanceMethodOfArbitratyObjectOfParticularType() {
List<Integer> numbers = Arrays.asList(5, 3, 50, 24, 40, 2, 9, 18);
numbers.stream()
.sorted((a, b) -> Integer.compare(a, b));
numbers.stream()
.sorted(Integer::compare);
}
@Test
public void referenceToConstructor() {
BiFunction<String, Integer, Bicycle> bikeCreator = (brand, frameSize) -> new Bicycle(brand, frameSize);
BiFunction<String, Integer, Bicycle> bikeCreatorMethodReference = Bicycle::new;
List<Bicycle> bikes = new ArrayList<>();
bikes.add(bikeCreator.apply("Giant", 50));
bikes.add(bikeCreator.apply("Scott", 20));
bikes.add(bikeCreatorMethodReference.apply("Trek", 35));
bikes.add(bikeCreatorMethodReference.apply("GT", 40));
}
@Test
public void limitationsAndAdditionalExamples() {
createBicyclesList().forEach(b -> System.out.printf("Bike brand is '%s' and frame size is '%d'%n", b.getBrand(), b.getFrameSize()));
createBicyclesList().forEach((o) -> this.doNothingAtAll(o));
}
private List<Bicycle> createBicyclesList() {
List<Bicycle> bikes = new ArrayList<>();
bikes.add(new Bicycle("Giant", 50));
bikes.add(new Bicycle("Scott", 20));
bikes.add(new Bicycle("Trek", 35));
bikes.add(new Bicycle("GT", 40));
return bikes;
}
}

View File

@ -0,0 +1,64 @@
package com.baeldung.files;
import java.io.File;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class ListFiles {
public static final int DEPTH = 1;
public Set<String> listFilesUsingJavaIO(String dir) {
return Stream.of(new File(dir).listFiles())
.filter(file -> !file.isDirectory())
.map(File::getName)
.collect(Collectors.toSet());
}
public Set<String> listFilesUsingFileWalk(String dir, int depth) throws IOException {
try (Stream<Path> stream = Files.walk(Paths.get(dir), depth)) {
return stream.filter(file -> !Files.isDirectory(file))
.map(Path::getFileName)
.map(Path::toString)
.collect(Collectors.toSet());
}
}
public Set<String> listFilesUsingFileWalkAndVisitor(String dir) throws IOException {
Set<String> fileList = new HashSet<>();
Files.walkFileTree(Paths.get(dir), new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (!Files.isDirectory(file)) {
fileList.add(file.getFileName()
.toString());
}
return FileVisitResult.CONTINUE;
}
});
return fileList;
}
public Set<String> listFilesUsingDirectoryStream(String dir) throws IOException {
Set<String> fileList = new HashSet<>();
try (DirectoryStream<Path> stream = Files.newDirectoryStream(Paths.get(dir))) {
for (Path path : stream) {
if (!Files.isDirectory(path)) {
fileList.add(path.getFileName()
.toString());
}
}
}
return fileList;
}
}

View File

@ -0,0 +1,46 @@
package com.baeldung.file;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import org.junit.Test;
import com.baeldung.files.ListFiles;
public class ListFilesUnitTest {
private ListFiles listFiles = new ListFiles();
private String DIRECTORY = "src/test/resources/listFilesUnitTestFolder";
private static final int DEPTH = 1;
private Set<String> EXPECTED_FILE_LIST = new HashSet<String>() {
{
add("test.xml");
add("employee.json");
add("students.json");
add("country.txt");
}
};
@Test
public void givenDir_whenUsingJAVAIO_thenListAllFiles() throws IOException {
assertEquals(EXPECTED_FILE_LIST, listFiles.listFilesUsingJavaIO(DIRECTORY));
}
@Test
public void givenDir_whenWalkingTree_thenListAllFiles() throws IOException {
assertEquals(EXPECTED_FILE_LIST, listFiles.listFilesUsingFileWalk(DIRECTORY,DEPTH));
}
@Test
public void givenDir_whenWalkingTreeWithVisitor_thenListAllFiles() throws IOException {
assertEquals(EXPECTED_FILE_LIST, listFiles.listFilesUsingFileWalkAndVisitor(DIRECTORY));
}
@Test
public void givenDir_whenUsingDirectoryStream_thenListAllFiles() throws IOException {
assertEquals(EXPECTED_FILE_LIST, listFiles.listFilesUsingDirectoryStream(DIRECTORY));
}
}

View File

@ -0,0 +1 @@
This is a sample txt file for unit test ListFilesUnitTest

View File

@ -0,0 +1 @@
<xml></xml>

View File

@ -0,0 +1,14 @@
package org.baeldung.variable.scope.examples;
public class BracketScopeExample {
public void mathOperationExample() {
Integer sum = 0;
{
Integer number = 2;
sum = sum + number;
}
// compiler error, number cannot be solved as a variable
// number++;
}
}

View File

@ -0,0 +1,14 @@
package org.baeldung.variable.scope.examples;
public class ClassScopeExample {
Integer amount = 0;
public void exampleMethod() {
amount++;
}
public void anotherExampleMethod() {
Integer anotherAmount = amount + 4;
}
}

View File

@ -0,0 +1,18 @@
package org.baeldung.variable.scope.examples;
import java.util.Arrays;
import java.util.List;
public class LoopScopeExample {
List<String> listOfNames = Arrays.asList("Joe", "Susan", "Pattrick");
public void iterationOfNames() {
String allNames = "";
for (String name : listOfNames) {
allNames = allNames + " " + name;
}
// compiler error, name cannot be resolved to a variable
// String lastNameUsed = name;
}
}

View File

@ -0,0 +1,13 @@
package org.baeldung.variable.scope.examples;
public class MethodScopeExample {
public void methodA() {
Integer area = 2;
}
public void methodB() {
// compiler error, area cannot be resolved to a variable
// area = area + 2;
}
}

View File

@ -0,0 +1,12 @@
package org.baeldung.variable.scope.examples;
public class NestedScopesExample {
String title = "Baeldung";
public void printTitle() {
System.out.println(title);
String title = "John Doe";
System.out.println(title);
}
}

View File

@ -10,7 +10,7 @@ public class BitwiseOperatorUnitTest {
int value1 = 6;
int value2 = 5;
int result = value1 & value2;
assertEquals(result, 4);
assertEquals(4, result);
}
@Test
@ -18,7 +18,7 @@ public class BitwiseOperatorUnitTest {
int value1 = 6;
int value2 = 5;
int result = value1 | value2;
assertEquals(result, 7);
assertEquals(7, result);
}
@Test
@ -26,7 +26,7 @@ public class BitwiseOperatorUnitTest {
int value1 = 6;
int value2 = 5;
int result = value1 ^ value2;
assertEquals(result, 3);
assertEquals(3, result);
}
@Test
@ -40,42 +40,42 @@ public class BitwiseOperatorUnitTest {
public void givenOnePositiveInteger_whenSignedRightShiftOperator_thenNewDecimalNumber() {
int value = 12;
int rightShift = value >> 2;
assertEquals(rightShift, 3);
assertEquals(3, rightShift);
}
@Test
public void givenOneNegativeInteger_whenSignedRightShiftOperator_thenNewDecimalNumber() {
int value = -12;
int rightShift = value >> 2;
assertEquals(rightShift, -3);
assertEquals(-3, rightShift);
}
@Test
public void givenOnePositiveInteger_whenLeftShiftOperator_thenNewDecimalNumber() {
int value = 12;
int leftShift = value << 2;
assertEquals(leftShift, 48);
assertEquals(48, leftShift);
}
@Test
public void givenOneNegativeInteger_whenLeftShiftOperator_thenNewDecimalNumber() {
int value = -12;
int leftShift = value << 2;
assertEquals(leftShift, -48);
assertEquals(-48, leftShift);
}
@Test
public void givenOnePositiveInteger_whenUnsignedRightShiftOperator_thenNewDecimalNumber() {
int value = 12;
int unsignedRightShift = value >>> 2;
assertEquals(unsignedRightShift, 3);
assertEquals(3, unsignedRightShift);
}
@Test
public void givenOneNegativeInteger_whenUnsignedRightShiftOperator_thenNewDecimalNumber() {
int value = -12;
int unsignedRightShift = value >>> 2;
assertEquals(unsignedRightShift, 1073741821);
assertEquals(1073741821, unsignedRightShift);
}
}

View File

@ -6,7 +6,19 @@ import kotlin.test.assertTrue
class VoidTypesUnitTest {
fun returnTypeAsVoid(): Void? {
// Un-commenting below methods will result into compilation error
// as the syntax used is incorrect and is used for explanation in tutorial.
// fun returnTypeAsVoidAttempt1(): Void {
// println("Trying with Void as return type")
// }
// fun returnTypeAsVoidAttempt2(): Void {
// println("Trying with Void as return type")
// return null
// }
fun returnTypeAsVoidSuccess(): Void? {
println("Function can have Void as return type")
return null
}
@ -36,7 +48,7 @@ class VoidTypesUnitTest {
@Test
fun givenVoidReturnType_thenReturnsNullOnly() {
assertNull(returnTypeAsVoid())
assertNull(returnTypeAsVoidSuccess())
}
@Test

View File

@ -0,0 +1,204 @@
package com.baeldung.java.map;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.collections4.MultiMapUtils;
import org.apache.commons.collections4.MultiValuedMap;
import org.apache.commons.collections4.multimap.ArrayListValuedHashMap;
import org.apache.commons.collections4.multimap.HashSetValuedHashMap;
import org.junit.Test;
public class MultiValuedMapUnitTest {
@Test
public void givenMultiValuesMap_whenPuttingMultipleValuesUsingPutMethod_thenReturningAllValues() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("key", "value1");
map.put("key", "value2");
map.put("key", "value2");
assertThat((Collection<String>) map.get("key")).containsExactly("value1", "value2", "value2");
}
@Test
public void givenMultiValuesMap_whenPuttingMultipleValuesUsingPutAllMethod_thenReturningAllValues() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.putAll("key", Arrays.asList("value1", "value2", "value2"));
assertThat((Collection<String>) map.get("key")).containsExactly("value1", "value2", "value2");
}
@Test
public void givenMultiValuesMap_whenGettingValueUsingGetMethod_thenReturningValue() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("key", "value");
assertThat((Collection<String>) map.get("key")).containsExactly("value");
}
@Test
public void givenMultiValuesMap_whenUsingEntriesMethod_thenReturningMappings() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("key", "value1");
map.put("key", "value2");
Collection<Entry<String, String>> entries = (Collection<Entry<String, String>>) map.entries();
for(Map.Entry<String,String> entry : entries) {
assertThat(entry.getKey()).contains("key");
assertTrue(entry.getValue().equals("value1") || entry.getValue().equals("value2") );
}
}
@Test
public void givenMultiValuesMap_whenUsingKeysMethod_thenReturningAllKeys() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("key", "value");
map.put("key1", "value1");
map.put("key2", "value2");
assertThat(((Collection<String>) map.keys())).contains("key", "key1", "key2");
}
@Test
public void givenMultiValuesMap_whenUsingKeySetMethod_thenReturningAllKeys() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("key", "value");
map.put("key1", "value1");
map.put("key2", "value2");
assertThat((Collection<String>) map.keySet()).contains("key", "key1", "key2");
}
@Test
public void givenMultiValuesMap_whenUsingValuesMethod_thenReturningAllValues() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("key", "value");
map.put("key1", "value1");
map.put("key2", "value2");
assertThat(((Collection<String>) map.values())).contains("value", "value1", "value2");
}
@Test
public void givenMultiValuesMap_whenUsingRemoveMethod_thenReturningUpdatedMap() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("key", "value");
map.put("key1", "value1");
map.put("key2", "value2");
assertThat(((Collection<String>) map.values())).contains("value", "value1", "value2");
map.remove("key");
assertThat(((Collection<String>) map.values())).contains("value1", "value2");
}
@Test
public void givenMultiValuesMap_whenUsingRemoveMappingMethod_thenReturningUpdatedMapAfterMappingRemoved() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("key", "value");
map.put("key1", "value1");
map.put("key2", "value2");
assertThat(((Collection<String>) map.values())).contains("value", "value1", "value2");
map.removeMapping("key", "value");
assertThat(((Collection<String>) map.values())).contains("value1", "value2");
}
@Test
public void givenMultiValuesMap_whenUsingClearMethod_thenReturningEmptyMap() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("key", "value");
map.put("key1", "value1");
map.put("key2", "value2");
assertThat(((Collection<String>) map.values())).contains("value", "value1", "value2");
map.clear();
assertTrue(map.isEmpty());
}
@Test
public void givenMultiValuesMap_whenUsingContainsKeyMethod_thenReturningTrue() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("key", "value");
map.put("key1", "value1");
map.put("key2", "value2");
assertTrue(map.containsKey("key"));
}
@Test
public void givenMultiValuesMap_whenUsingContainsValueMethod_thenReturningTrue() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("key", "value");
map.put("key1", "value1");
map.put("key2", "value2");
assertTrue(map.containsValue("value"));
}
@Test
public void givenMultiValuesMap_whenUsingIsEmptyMethod_thenReturningFalse() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("key", "value");
map.put("key1", "value1");
map.put("key2", "value2");
assertFalse(map.isEmpty());
}
@Test
public void givenMultiValuesMap_whenUsingSizeMethod_thenReturningElementCount() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("key", "value");
map.put("key1", "value1");
map.put("key2", "value2");
assertEquals(3, map.size());
}
@Test
public void givenArrayListValuedHashMap_whenPuttingDoubleValues_thenReturningAllValues() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("key", "value1");
map.put("key", "value2");
map.put("key", "value2");
assertThat((Collection<String>) map.get("key")).containsExactly("value1", "value2", "value2");
}
@Test
public void givenHashSetValuedHashMap_whenPuttingTwiceTheSame_thenReturningOneValue() {
MultiValuedMap<String, String> map = new HashSetValuedHashMap<>();
map.put("key1", "value1");
map.put("key1", "value1");
assertThat((Collection<String>) map.get("key1")).containsExactly("value1");
}
@Test(expected = UnsupportedOperationException.class)
public void givenUnmodifiableMultiValuedMap_whenInserting_thenThrowingException() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("key", "value1");
map.put("key", "value2");
MultiValuedMap<String, String> immutableMap = MultiMapUtils.unmodifiableMultiValuedMap(map);
immutableMap.put("key", "value3");
}
}

View File

@ -95,6 +95,12 @@
<version>1.4</version>
</dependency>
<dependency>
<groupId>org.ahocorasick</groupId>
<artifactId>ahocorasick</artifactId>
<version>0.4.0</version>
</dependency>
</dependencies>
<build>

View File

@ -0,0 +1,83 @@
package com.baeldung.string;
import org.ahocorasick.trie.Emit;
import org.ahocorasick.trie.Token;
import org.ahocorasick.trie.Trie;
import java.util.*;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class MatchWords {
public static boolean containsWordsIndexOf(String inputString, String[] words) {
boolean found = true;
for (String word : words) {
if (inputString.indexOf(word) == -1) {
found = false;
break;
}
}
return found;
}
public static boolean containsWords(String inputString, String[] items) {
boolean found = true;
for (String item : items) {
if (!inputString.contains(item)) {
found = false;
break;
}
}
return found;
}
public static boolean containsWordsAhoCorasick(String inputString, String[] words) {
Trie trie = Trie.builder()
.onlyWholeWords()
.addKeywords(words)
.build();
Collection<Emit> emits = trie.parseText(inputString);
emits.forEach(System.out::println);
boolean found = true;
for(String word : words) {
boolean contains = Arrays.toString(emits.toArray()).contains(word);
if (!contains) {
found = false;
break;
}
}
return found;
}
public static boolean containsWordsPatternMatch(String inputString, String[] words) {
StringBuilder regexp = new StringBuilder();
for (String word : words) {
regexp.append("(?=.*").append(word).append(")");
}
Pattern pattern = Pattern.compile(regexp.toString());
return pattern.matcher(inputString).find();
}
public static boolean containsWordsJava8(String inputString, String[] words) {
List<String> inputStringList = Arrays.asList(inputString.split(" "));
List<String> wordsList = Arrays.asList(words);
return wordsList.stream().allMatch(inputStringList::contains);
}
public static boolean containsWordsArray(String inputString, String[] words) {
List<String> inputStringList = Arrays.asList(inputString.split(" "));
List<String> wordsList = Arrays.asList(words);
return inputStringList.containsAll(wordsList);
}
}

View File

@ -0,0 +1,66 @@
package com.baeldung.string;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class MatchWordsUnitTest {
private final String[] words = {"hello", "Baeldung"};
private final String inputString = "hello there, Baeldung";
private final String wholeInput = "helloBaeldung";
@Test
public void givenText_whenCallingStringContains_shouldMatchWords() {
final boolean result = MatchWords.containsWords(inputString, words);
assertThat(result).isTrue();
}
@Test
public void givenText_whenCallingJava8_shouldMatchWords() {
final boolean result = MatchWords.containsWordsJava8(inputString, words);
assertThat(result).isTrue();
}
@Test
public void givenText_whenCallingJava8_shouldNotMatchWords() {
final boolean result = MatchWords.containsWordsJava8(wholeInput, words);
assertThat(result).isFalse();
}
@Test
public void givenText_whenCallingPattern_shouldMatchWords() {
final boolean result = MatchWords.containsWordsPatternMatch(inputString, words);
assertThat(result).isTrue();
}
@Test
public void givenText_whenCallingAhoCorasick_shouldMatchWords() {
final boolean result = MatchWords.containsWordsAhoCorasick(inputString, words);
assertThat(result).isTrue();
}
@Test
public void givenText_whenCallingAhoCorasick_shouldNotMatchWords() {
final boolean result = MatchWords.containsWordsAhoCorasick(wholeInput, words);
assertThat(result).isFalse();
}
@Test
public void givenText_whenCallingIndexOf_shouldMatchWords() {
final boolean result = MatchWords.containsWordsIndexOf(inputString, words);
assertThat(result).isTrue();
}
@Test
public void givenText_whenCallingArrayList_shouldMatchWords() {
final boolean result = MatchWords.containsWordsArray(inputString, words);
assertThat(result).isTrue();
}
@Test
public void givenText_whenCallingArrayList_shouldNotMatchWords() {
final boolean result = MatchWords.containsWordsArray(wholeInput, words);
assertThat(result).isFalse();
}
}

View File

@ -5,3 +5,5 @@
- [Lombok @Builder with Inheritance](https://www.baeldung.com/lombok-builder-inheritance)
- [Lombok Builder with Default Value](https://www.baeldung.com/lombok-builder-default-value)
- [Lombok Builder with Custom Setter](https://www.baeldung.com/lombok-builder-custom-setter)
- [Setting up Lombok with Eclipse and Intellij](https://www.baeldung.com/lombok-ide)

View File

@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<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>solid/artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,4 @@
package com.baeldung.d;
public class Keyboard {
}

View File

@ -0,0 +1,6 @@
package com.baeldung.d;
public class Monitor {
}

View File

@ -0,0 +1,15 @@
package com.baeldung.d;
public class Windows98Machine {
private final Keyboard keyboard;
private final Monitor monitor;
public Windows98Machine() {
monitor = new Monitor();
keyboard = new Keyboard();
}
}

View File

@ -0,0 +1,12 @@
package com.baeldung.d;
public class Windows98MachineDI {
private final Keyboard keyboard;
private final Monitor monitor;
public Windows98MachineDI(Keyboard keyboard, Monitor monitor) {
this.keyboard = keyboard;
this.monitor = monitor;
}
}

View File

@ -0,0 +1,12 @@
package com.baeldung.i;
public class BearCarer implements BearCleaner, BearFeeder {
public void washTheBear() {
//I think we missed a spot..
}
public void feedTheBear() {
//Tuna tuesdays..
}
}

View File

@ -0,0 +1,5 @@
package com.baeldung.i;
public interface BearCleaner {
void washTheBear();
}

View File

@ -0,0 +1,5 @@
package com.baeldung.i;
public interface BearFeeder {
void feedTheBear();
}

View File

@ -0,0 +1,9 @@
package com.baeldung.i;
public interface BearKeeper {
void washTheBear();
void feedTheBear();
void petTheBear();
}

View File

@ -0,0 +1,5 @@
package com.baeldung.i;
public interface BearPetter {
void petTheBear();
}

View File

@ -0,0 +1,8 @@
package com.baeldung.i;
public class CrazyPerson implements BearPetter {
public void petTheBear() {
//Good luck with that!
}
}

View File

@ -0,0 +1,8 @@
package com.baeldung.l;
public interface Car {
void turnOnEngine();
void accelerate();
}

View File

@ -0,0 +1,12 @@
package com.baeldung.l;
public class ElectricCar implements Car {
public void turnOnEngine() {
throw new AssertionError("I don't have an engine!");
}
public void accelerate() {
//this acceleration is crazy!
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.l;
public class Engine {
public void on(){
//vroom.
}
public void powerOn(int amount){
//do something
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.l;
public class MotorCar implements Car {
private Engine engine;
//Constructors, getters + setters
public void turnOnEngine() {
//turn on the engine!
engine.on();
}
public void accelerate() {
//move forward!
engine.powerOn(1000);
}
}

View File

@ -0,0 +1,10 @@
package com.baeldung.o;
public class Guitar {
private String make;
private String model;
private int volume;
//Constructors, getters & setters
}

View File

@ -0,0 +1,9 @@
package com.baeldung.o;
public class SuperCoolGuitarWithFlames extends Guitar {
private String flameColour;
//constructor, getters + setters
}

View File

@ -0,0 +1,27 @@
package com.baeldung.s;
public class BadBook {
private String name;
private String author;
private String text;
//constructor, getters and setters
//methods that directly relate to the book properties
public String replaceWordInText(String word){
return text.replaceAll(word, text);
}
public boolean isWordInText(String word){
return text.contains(word);
}
//methods for outputting text to console - should this really be here?
void printTextToConsole(){
//our code for formatting and printing the text
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.s;
public class BookPrinter {
//methods for outputting text
void printTextToConsole(String text){
//our code for formatting and printing the text
}
void printTextToAnotherMedium(String text){
//code for writing to any other location..
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.s;
public class GoodBook {
private String name;
private String author;
private String text;
//constructor, getters and setters
//methods that directly relate to the book properties
public String replaceWordInText(String word){
return text.replaceAll(word, text);
}
public boolean isWordInText(String word){
return text.contains(word);
}
}

View File

@ -25,15 +25,15 @@ class Passenger {
@Basic(optional = false)
@Column(nullable = false)
private int seatNumber;
private Integer seatNumber;
private Passenger(String firstName, String lastName, int seatNumber) {
private Passenger(String firstName, String lastName, Integer seatNumber) {
this.firstName = firstName;
this.lastName = lastName;
this.seatNumber = seatNumber;
}
static Passenger from(String firstName, String lastName, int seatNumber) {
static Passenger from(String firstName, String lastName, Integer seatNumber) {
return new Passenger(firstName, lastName, seatNumber);
}
@ -76,7 +76,7 @@ class Passenger {
return lastName;
}
int getSeatNumber() {
Integer getSeatNumber() {
return seatNumber;
}
}

View File

@ -1,23 +1,29 @@
package com.baeldung.passenger;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.core.IsNot.not;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.List;
import java.util.Optional;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.test.context.junit4.SpringRunner;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.junit.Assert.assertEquals;
@DataJpaTest
@RunWith(SpringRunner.class)
public class PassengerRepositoryIntegrationTest {
@ -45,7 +51,7 @@ public class PassengerRepositoryIntegrationTest {
assertEquals(1, passengers.size());
Passenger actual = passengers.get(0);
assertEquals(actual, expected);
assertEquals(expected, actual);
}
@Test
@ -54,16 +60,17 @@ public class PassengerRepositoryIntegrationTest {
Passenger actual = repository.findFirstByOrderBySeatNumberAsc();
assertEquals(actual, expected);
assertEquals(expected, actual);
}
@Test
public void givenSeveralPassengersWhenFindPageSortedByThenThePassengerInTheFirstFilledSeatIsReturned() {
Passenger expected = Passenger.from("Fred", "Bloggs", 22);
Page<Passenger> page = repository.findAll(PageRequest.of(0, 1, Sort.by(Sort.Direction.ASC, "seatNumber")));
Page<Passenger> page = repository.findAll(PageRequest.of(0, 1,
Sort.by(Sort.Direction.ASC, "seatNumber")));
assertEquals(page.getContent().size(), 1);
assertEquals(1, page.getContent().size());
Passenger actual = page.getContent().get(0);
assertEquals(expected, actual);
@ -95,4 +102,68 @@ public class PassengerRepositoryIntegrationTest {
assertThat(passengers, contains(fred, ricki, jill, siya, eve));
}
@Test
public void givenPassengers_whenFindByExampleDefaultMatcher_thenExpectedReturned() {
Example<Passenger> example = Example.of(Passenger.from("Fred", "Bloggs", null));
Optional<Passenger> actual = repository.findOne(example);
assertTrue(actual.isPresent());
assertEquals(Passenger.from("Fred", "Bloggs", 22), actual.get());
}
@Test
public void givenPassengers_whenFindByExampleCaseInsensitiveMatcher_thenExpectedReturned() {
ExampleMatcher caseInsensitiveExampleMatcher = ExampleMatcher.matchingAll().withIgnoreCase();
Example<Passenger> example = Example.of(Passenger.from("fred", "bloggs", null),
caseInsensitiveExampleMatcher);
Optional<Passenger> actual = repository.findOne(example);
assertTrue(actual.isPresent());
assertEquals(Passenger.from("Fred", "Bloggs", 22), actual.get());
}
@Test
public void givenPassengers_whenFindByExampleCustomMatcher_thenExpectedReturned() {
Passenger jill = Passenger.from("Jill", "Smith", 50);
Passenger eve = Passenger.from("Eve", "Jackson", 95);
Passenger fred = Passenger.from("Fred", "Bloggs", 22);
Passenger siya = Passenger.from("Siya", "Kolisi", 85);
Passenger ricki = Passenger.from("Ricki", "Bobbie", 36);
ExampleMatcher customExampleMatcher = ExampleMatcher.matchingAny().withMatcher("firstName",
ExampleMatcher.GenericPropertyMatchers.contains().ignoreCase()).withMatcher("lastName",
ExampleMatcher.GenericPropertyMatchers.contains().ignoreCase());
Example<Passenger> example = Example.of(Passenger.from("e", "s", null),
customExampleMatcher);
List<Passenger> passengers = repository.findAll(example);
assertThat(passengers, contains(jill, eve, fred, siya));
assertThat(passengers, not(contains(ricki)));
}
@Test
public void givenPassengers_whenFindByIgnoringMatcher_thenExpectedReturned() {
Passenger jill = Passenger.from("Jill", "Smith", 50);
Passenger eve = Passenger.from("Eve", "Jackson", 95);
Passenger fred = Passenger.from("Fred", "Bloggs", 22);
Passenger siya = Passenger.from("Siya", "Kolisi", 85);
Passenger ricki = Passenger.from("Ricki", "Bobbie", 36);
ExampleMatcher ignoringExampleMatcher = ExampleMatcher.matchingAny().withMatcher("lastName",
ExampleMatcher.GenericPropertyMatchers.startsWith().ignoreCase()).withIgnorePaths("firstName", "seatNumber");
Example<Passenger> example = Example.of(Passenger.from(null, "b", null),
ignoringExampleMatcher);
List<Passenger> passengers = repository.findAll(example);
assertThat(passengers, contains(fred, ricki));
assertThat(passengers, not(contains(jill)));
assertThat(passengers, not(contains(eve)));
assertThat(passengers, not(contains(siya)));
}
}

View File

@ -717,7 +717,6 @@
<module>spring-rest-simple</module>
<module>spring-resttemplate</module>
<module>spring-roo</module>
<module>spring-security-acl</module>
<module>spring-security-angular/server</module>
<module>spring-security-cache-control</module>

View File

@ -7,7 +7,7 @@ import org.springframework.stereotype.Component;
@Component
class TaskScheduler {
@Scheduled(cron = "*/15 * * * * *")
@Scheduled(cron = "*/15 * * * *")
@SchedulerLock(name = "TaskScheduler_scheduledTask", lockAtLeastForString = "PT5M", lockAtMostForString = "PT14M")
public void scheduledTask() {
System.out.println("Running ShedLock task");

View File

@ -0,0 +1,20 @@
package com.baeldung.scheduling;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
@Configuration
public class ScheduleJobsByProfile {
private final static Logger LOG = LoggerFactory.getLogger(ScheduleJobsByProfile.class);
@Profile("prod")
@Bean
public ScheduledJob scheduledJob()
{
return new ScheduledJob("@Profile");
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.scheduling;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
public class ScheduledJob {
private String source;
public ScheduledJob(String source) {
this.source = source;
}
private final static Logger LOG = LoggerFactory.getLogger(ScheduledJob.class);
@Scheduled(fixedDelay = 60000)
public void cleanTempDir() {
LOG.info("Cleaning temp directory via {}", source);
}
}

View File

@ -0,0 +1,28 @@
package com.baeldung.scheduling;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;
@Configuration
public class ScheduledJobsWithBoolean {
private final static Logger LOG = LoggerFactory.getLogger(ScheduledJobsWithBoolean.class);
@Value("${jobs.enabled:true}")
private boolean isEnabled;
/**
* A scheduled job controlled via application property. The job always
* executes, but the logic inside is protected by a configurable boolean
* flag.
*/
@Scheduled(fixedDelay = 60000)
public void cleanTempDirectory() {
if(isEnabled) {
LOG.info("Cleaning temp directory via boolean flag");
}
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.scheduling;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ScheduledJobsWithConditional
{
/**
* This uses @ConditionalOnProperty to conditionally create a bean, which itself
* is a scheduled job.
* @return ScheduledJob
*/
@Bean
@ConditionalOnProperty(value = "jobs.enabled", matchIfMissing = true, havingValue = "true")
public ScheduledJob runMyCronTask() {
return new ScheduledJob("@ConditionalOnProperty");
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.scheduling;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;
@Configuration
public class ScheduledJobsWithExpression
{
private final static Logger LOG =
LoggerFactory.getLogger(ScheduledJobsWithExpression.class);
/**
* A scheduled job controlled via application property. The job always
* executes, but the logic inside is protected by a configurable boolean
* flag.
*/
@Scheduled(cron = "${jobs.cronSchedule:-}")
public void cleanTempDirectory() {
LOG.info("Cleaning temp directory via placeholder");
}
}

View File

@ -0,0 +1,16 @@
package com.baeldung.scheduling;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class SchedulingApplication {
public static void main(String[] args) {
SpringApplication.run(SchedulingApplication.class, args);
}
}

View File

@ -25,29 +25,14 @@
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- util -->

View File

@ -25,7 +25,6 @@ import com.google.common.base.Preconditions;
@EnableTransactionManagement
@PropertySource({ "classpath:persistence-${envTarget:h2}.properties" })
@ComponentScan({ "com.baeldung.persistence" })
// @ImportResource("classpath*:springDataPersistenceConfig.xml")
@EnableJpaRepositories(basePackages = "com.baeldung.persistence.dao")
public class PersistenceConfig {

View File

@ -1,43 +1,10 @@
package com.baeldung.spring;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
@Configuration
@ComponentScan("com.baeldung.web")
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
public WebConfig() {
super();
}
@Bean
public ViewResolver viewResolver() {
final InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/view/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
// API
@Override
public void addViewControllers(final ViewControllerRegistry registry) {
registry.addViewController("/graph.html");
registry.addViewController("/homepage.html");
}
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.defaultContentType(MediaType.APPLICATION_JSON);
}
}

View File

@ -1,12 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd"
>
<jpa:repositories base-package="com.baeldung.persistence.dao"/>
</beans>

View File

@ -0,0 +1,27 @@
package com.baeldung.validation.application;
import com.baeldung.validation.application.entities.User;
import com.baeldung.validation.application.repositories.UserRepository;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
public CommandLineRunner run(UserRepository userRepository) throws Exception {
return (String[] args) -> {
User user1 = new User("Bob", "bob@domain.com");
User user2 = new User("Jenny", "jenny@domain.com");
userRepository.save(user1);
userRepository.save(user2);
userRepository.findAll().forEach(System.out::println);
};
}
}

View File

@ -0,0 +1,52 @@
package com.baeldung.validation.application.controllers;
import com.baeldung.validation.application.entities.User;
import com.baeldung.validation.application.repositories.UserRepository;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
private final UserRepository userRepository;
@Autowired
public UserController(UserRepository userRepository) {
this.userRepository = userRepository;
}
@GetMapping("/users")
public List<User> getUsers() {
return (List<User>) userRepository.findAll();
}
@PostMapping("/users")
ResponseEntity<String> addUser(@Valid @RequestBody User user) {
return ResponseEntity.ok("User is valid");
}
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MethodArgumentNotValidException.class)
public Map<String, String> handleValidationExceptions(MethodArgumentNotValidException ex) {
Map<String, String> errors = new HashMap<>();
ex.getBindingResult().getAllErrors().forEach((error) -> {
String fieldName = ((FieldError) error).getField();
String errorMessage = error.getDefaultMessage();
errors.put(fieldName, errorMessage);
});
return errors;
}
}

View File

@ -0,0 +1,50 @@
package com.baeldung.validation.application.entities;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotBlank;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@NotBlank(message = "Name is mandatory")
private String name;
@NotBlank(message = "Email is mandatory")
private String email;
public User(){}
public User(String name, String email) {
this.name = name;
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "User{" + "id=" + id + ", name=" + name + ", email=" + email + '}';
}
}

View File

@ -0,0 +1,8 @@
package com.baeldung.validation.application.repositories;
import com.baeldung.validation.application.entities.User;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends CrudRepository<User, Long> {}

View File

@ -8,7 +8,6 @@ import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
import org.hibernate.validator.constraints.Length;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
@ -20,41 +19,8 @@ import org.springframework.validation.annotation.Validated;
@Validated
public class ConfigProperties {
@Validated
public static class Credentials {
@Length(max = 4, min = 1)
private String authMethod;
private String username;
private String password;
public String getAuthMethod() {
return authMethod;
}
public void setAuthMethod(String authMethod) {
this.authMethod = authMethod;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
@NotBlank
private String host;
private String hostName;
@Min(1025)
@Max(65536)
@ -63,16 +29,16 @@ public class ConfigProperties {
@Pattern(regexp = "^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,6}$")
private String from;
private Credentials credentials;
private List<String> defaultRecipients;
private Map<String, String> additionalHeaders;
private Credentials credentials;
public String getHost() {
return host;
public String getHostName() {
return hostName;
}
public void setHost(String host) {
this.host = host;
public void setHostName(String hostName) {
this.hostName = hostName;
}
public int getPort() {
@ -91,14 +57,6 @@ public class ConfigProperties {
this.from = from;
}
public Credentials getCredentials() {
return credentials;
}
public void setCredentials(Credentials credentials) {
this.credentials = credentials;
}
public List<String> getDefaultRecipients() {
return defaultRecipients;
}
@ -114,4 +72,12 @@ public class ConfigProperties {
public void setAdditionalHeaders(Map<String, String> additionalHeaders) {
this.additionalHeaders = additionalHeaders;
}
public Credentials getCredentials() {
return credentials;
}
public void setCredentials(Credentials credentials) {
this.credentials = credentials;
}
}

View File

@ -0,0 +1,37 @@
package org.baeldung.properties;
import org.hibernate.validator.constraints.Length;
import org.springframework.validation.annotation.Validated;
@Validated
public class Credentials {
@Length(max = 4, min = 1)
private String authMethod;
private String username;
private String password;
public String getAuthMethod() {
return authMethod;
}
public void setAuthMethod(String authMethod) {
this.authMethod = authMethod;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}

View File

@ -1,5 +1,5 @@
#Simple properties
mail.host=mailer@mail.com
mail.hostname=host@mail.com
mail.port=9000
mail.from=mailer@mail.com

View File

@ -0,0 +1,69 @@
package com.baeldung.validation.tests;
import com.baeldung.validation.application.controllers.UserController;
import com.baeldung.validation.application.repositories.UserRepository;
import java.nio.charset.Charset;
import static org.assertj.core.api.Assertions.assertThat;
import org.hamcrest.core.Is;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
@RunWith(SpringRunner.class)
@WebMvcTest
@AutoConfigureMockMvc
public class UserControllerIntegrationTest {
@MockBean
private UserRepository userRepository;
@Autowired
UserController userController;
@Autowired
private MockMvc mockMvc;
@Test
public void whenUserControllerInjected_thenNotNull() throws Exception {
assertThat(userController).isNotNull();
}
@Test
public void whenGetRequestToUsers_thenCorrectResponse() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/users")
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON_UTF8));
}
@Test
public void whenPostRequestToUsersAndValidUser_thenCorrectResponse() throws Exception {
MediaType textPlainUtf8 = new MediaType(MediaType.TEXT_PLAIN, Charset.forName("UTF-8"));
String user = "{\"name\": \"bob\", \"email\" : \"bob@domain.com\"}";
mockMvc.perform(MockMvcRequestBuilders.post("/users")
.content(user)
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().contentType(textPlainUtf8));
}
@Test
public void whenPostRequestToUsersAndInValidUser_thenCorrectReponse() throws Exception {
String user = "{\"name\": \"\", \"email\" : \"bob@domain.com\"}";
mockMvc.perform(MockMvcRequestBuilders.post("/users")
.content(user)
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(MockMvcResultMatchers.status().isBadRequest())
.andExpect(MockMvcResultMatchers.jsonPath("$.name", Is.is("Name is mandatory")))
.andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON_UTF8));
}
}

View File

@ -1,5 +1,8 @@
package org.baeldung.properties;
import java.util.List;
import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
@ -18,26 +21,36 @@ public class ConfigPropertiesIntegrationTest {
@Test
public void whenSimplePropertyQueriedthenReturnsProperty() throws Exception {
Assert.assertTrue("From address is read as null!", properties.getFrom() != null);
Assert.assertEquals("Incorrectly bound hostName property", "host@mail.com", properties.getHostName());
Assert.assertEquals("Incorrectly bound port property", 9000, properties.getPort());
Assert.assertEquals("Incorrectly bound from property", "mailer@mail.com", properties.getFrom());
}
@Test
public void whenListPropertyQueriedthenReturnsProperty() throws Exception {
Assert.assertTrue("Couldn't bind list property!", properties.getDefaultRecipients().size() == 2);
Assert.assertTrue("Incorrectly bound list property. Expected 2 entries!", properties.getDefaultRecipients().size() == 2);
List<String> defaultRecipients = properties.getDefaultRecipients();
Assert.assertTrue("Couldn't bind list property!", defaultRecipients.size() == 2);
Assert.assertTrue("Incorrectly bound list property. Expected 2 entries!", defaultRecipients.size() == 2);
Assert.assertEquals("Incorrectly bound list[0] property", "admin@mail.com", defaultRecipients.get(0));
Assert.assertEquals("Incorrectly bound list[1] property", "owner@mail.com", defaultRecipients.get(1));
}
@Test
public void whenMapPropertyQueriedthenReturnsProperty() throws Exception {
Assert.assertTrue("Couldn't bind map property!", properties.getAdditionalHeaders() != null);
Assert.assertTrue("Incorrectly bound map property. Expected 3 Entries!", properties.getAdditionalHeaders().size() == 3);
Map<String, String> additionalHeaders = properties.getAdditionalHeaders();
Assert.assertTrue("Couldn't bind map property!", additionalHeaders != null);
Assert.assertTrue("Incorrectly bound map property. Expected 3 Entries!", additionalHeaders.size() == 3);
Assert.assertEquals("Incorrectly bound map[redelivery] property", "true", additionalHeaders.get("redelivery"));
Assert.assertEquals("Incorrectly bound map[secure] property", "true", additionalHeaders.get("secure"));
Assert.assertEquals("Incorrectly bound map[p3] property", "value", additionalHeaders.get("p3"));
}
@Test
public void whenObjectPropertyQueriedthenReturnsProperty() throws Exception {
Assert.assertTrue("Couldn't bind map property!", properties.getCredentials() != null);
Assert.assertTrue("Incorrectly bound object property!", properties.getCredentials().getAuthMethod().equals("SHA1"));
Assert.assertTrue("Incorrectly bound object property!", properties.getCredentials().getUsername().equals("john"));
Assert.assertTrue("Incorrectly bound object property!", properties.getCredentials().getPassword().equals("password"));
Credentials credentials = properties.getCredentials();
Assert.assertTrue("Couldn't bind map property!", credentials != null);
Assert.assertEquals("Incorrectly bound object property, authMethod", "SHA1", credentials.getAuthMethod());
Assert.assertEquals("Incorrectly bound object property, username", "john", credentials.getUsername());
Assert.assertEquals("Incorrectly bound object property, password", "password", credentials.getPassword());
}
}

View File

@ -1,5 +1,5 @@
#Simple properties
mail.host=mailer@mail.com
mail.hostname=host@mail.com
mail.port=9000
mail.from=mailer@mail.com

View File

@ -15,8 +15,6 @@
### Relevant Articles:
- [Intro to Spring Cloud Netflix - Hystrix](http://www.baeldung.com/spring-cloud-netflix-hystrix)
- [Dockerizing a Spring Boot Application](http://www.baeldung.com/dockerizing-spring-boot-application)
- [Using a Spring Cloud App Starter](http://www.baeldung.com/using-a-spring-cloud-app-starter)
- [Using a Spring Cloud App Starter](http://www.baeldung.com/spring-cloud-app-starter)
- [Instance Profile Credentials using Spring Cloud](http://www.baeldung.com/spring-cloud-instance-profiles)
- [Running Spring Boot Applications With Minikube](http://www.baeldung.com/spring-boot-minikube)

View File

@ -0,0 +1,3 @@
#Revelant Articles:
- [Using a Spring Cloud App Starter](http://www.baeldung.com/spring-cloud-app-starter)

View File

@ -20,7 +20,7 @@ import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
// @PropertySource("persistence-h2.properties")
// @PropertySource("persistence-hsqldb.properties")
// @PropertySource("persistence-derby.properties")
//@PropertySource("persistence-sqlite.properties")
// @PropertySource("persistence-sqlite.properties")
public class DbConfig {
@Autowired
@ -65,21 +65,23 @@ public class DbConfig {
@Configuration
@Profile("h2")
@PropertySource("classpath:persistence-h2.properties")
class H2Config {}
class H2Config {
}
@Configuration
@Profile("hsqldb")
@PropertySource("classpath:persistence-hsqldb.properties")
class HsqldbConfig {}
class HsqldbConfig {
}
@Configuration
@Profile("derby")
@PropertySource("classpath:persistence-derby.properties")
class DerbyConfig {}
class DerbyConfig {
}
@Configuration
@Profile("sqlite")
@PropertySource("classpath:persistence-sqlite.properties")
class SqliteConfig {}
class SqliteConfig {
}

View File

@ -12,7 +12,7 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@EnableWebMvc
public class MvcConfig implements WebMvcConfigurer {
public MvcConfig(){
public MvcConfig() {
super();
}
@ -27,7 +27,7 @@ public class MvcConfig implements WebMvcConfigurer {
}
@Bean
BookEventHandler bookEventHandler(){
BookEventHandler bookEventHandler() {
return new BookEventHandler();
}

View File

@ -12,10 +12,9 @@ import org.springframework.http.HttpMethod;
public class RestConfig implements RepositoryRestConfigurer {
@Override
public void configureRepositoryRestConfiguration(RepositoryRestConfiguration repositoryRestConfiguration){
public void configureRepositoryRestConfiguration(RepositoryRestConfiguration repositoryRestConfiguration) {
repositoryRestConfiguration.getProjectionConfiguration().addProjection(CustomBook.class);
ExposureConfiguration config = repositoryRestConfiguration.getExposureConfiguration();
config.forDomainType(WebsiteUser.class).withItemExposure((metadata, httpMethods) ->
httpMethods.disable(HttpMethod.PATCH));
config.forDomainType(WebsiteUser.class).withItemExposure((metadata, httpMethods) -> httpMethods.disable(HttpMethod.PATCH));
}
}

View File

@ -24,13 +24,7 @@ public class ValidatorEventRegister implements InitializingBean {
List<String> events = Arrays.asList("beforeCreate", "afterCreate", "beforeSave", "afterSave", "beforeLinkSave", "afterLinkSave", "beforeDelete", "afterDelete");
for (Map.Entry<String, Validator> entry : validators.entrySet()) {
events
.stream()
.filter(p -> entry
.getKey()
.startsWith(p))
.findFirst()
.ifPresent(p -> validatingRepositoryEventListener.addValidator(p, entry.getValue()));
events.stream().filter(p -> entry.getKey().startsWith(p)).findFirst().ifPresent(p -> validatingRepositoryEventListener.addValidator(p, entry.getValue()));
}
}
}

View File

@ -8,33 +8,34 @@ import java.util.logging.Logger;
@RepositoryEventHandler
public class AuthorEventHandler {
Logger logger = Logger.getLogger("Class AuthorEventHandler");
public AuthorEventHandler(){
super();
}
Logger logger = Logger.getLogger("Class AuthorEventHandler");
@HandleBeforeCreate
public void handleAuthorBeforeCreate(Author author){
logger.info("Inside Author Before Create....");
String name = author.getName();
}
public AuthorEventHandler() {
super();
}
@HandleAfterCreate
public void handleAuthorAfterCreate(Author author){
logger.info("Inside Author After Create ....");
String name = author.getName();
}
@HandleBeforeCreate
public void handleAuthorBeforeCreate(Author author) {
logger.info("Inside Author Before Create....");
String name = author.getName();
}
@HandleBeforeDelete
public void handleAuthorBeforeDelete(Author author){
logger.info("Inside Author Before Delete ....");
String name = author.getName();
}
@HandleAfterCreate
public void handleAuthorAfterCreate(Author author) {
logger.info("Inside Author After Create ....");
String name = author.getName();
}
@HandleAfterDelete
public void handleAuthorAfterDelete(Author author){
logger.info("Inside Author After Delete ....");
String name = author.getName();
}
@HandleBeforeDelete
public void handleAuthorBeforeDelete(Author author) {
logger.info("Inside Author Before Delete ....");
String name = author.getName();
}
@HandleAfterDelete
public void handleAuthorAfterDelete(Author author) {
logger.info("Inside Author After Delete ....");
String name = author.getName();
}
}

View File

@ -10,17 +10,18 @@ import org.springframework.data.rest.core.annotation.RepositoryEventHandler;
@RepositoryEventHandler
public class BookEventHandler {
Logger logger = Logger.getLogger("Class BookEventHandler");
@HandleBeforeCreate
public void handleBookBeforeCreate(Book book){
Logger logger = Logger.getLogger("Class BookEventHandler");
logger.info("Inside Book Before Create ....");
book.getAuthors();
}
@HandleBeforeCreate
public void handleBookBeforeCreate(Book book) {
@HandleBeforeCreate
public void handleAuthorBeforeCreate(Author author){
logger.info("Inside Author Before Create ....");
author.getBooks();
}
logger.info("Inside Book Before Create ....");
book.getAuthors();
}
@HandleBeforeCreate
public void handleAuthorBeforeCreate(Author author) {
logger.info("Inside Author Before Create ....");
author.getBooks();
}
}

View File

@ -19,12 +19,7 @@ public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionH
public ResponseEntity<Object> handleAccessDeniedException(Exception ex, WebRequest request) {
RepositoryConstraintViolationException nevEx = (RepositoryConstraintViolationException) ex;
String errors = nevEx
.getErrors()
.getAllErrors()
.stream()
.map(ObjectError::toString)
.collect(Collectors.joining("\n"));
String errors = nevEx.getErrors().getAllErrors().stream().map(ObjectError::toString).collect(Collectors.joining("\n"));
return new ResponseEntity<>(errors, new HttpHeaders(), HttpStatus.NOT_ACCEPTABLE);
}

View File

@ -11,7 +11,7 @@ import javax.persistence.OneToOne;
public class Address {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(nullable = false)

View File

@ -16,7 +16,7 @@ import javax.persistence.ManyToMany;
public class Author {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(nullable = false)

View File

@ -16,7 +16,7 @@ import javax.persistence.ManyToOne;
public class Book {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(nullable = false)
@ -63,7 +63,6 @@ public class Book {
this.isbn = isbn;
}
public Library getLibrary() {
return library;
}

View File

@ -17,7 +17,7 @@ import org.springframework.data.rest.core.annotation.RestResource;
public class Library {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column

View File

@ -10,7 +10,7 @@ import javax.persistence.Id;
public class Subject {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(nullable = false)

View File

@ -7,4 +7,5 @@ import com.baeldung.models.Book;
import com.baeldung.projections.CustomBook;
@RepositoryRestResource(excerptProjection = CustomBook.class)
public interface BookRepository extends CrudRepository<Book, Long> {}
public interface BookRepository extends CrudRepository<Book, Long> {
}

View File

@ -9,21 +9,21 @@ import static org.mockito.Mockito.mock;
public class AuthorEventHandlerUnitTest {
@Test
public void whenCreateAuthorThenSuccess() {
Author author = mock(Author.class);
AuthorEventHandler authorEventHandler = new AuthorEventHandler();
authorEventHandler.handleAuthorBeforeCreate(author);
Mockito.verify(author,Mockito.times(1)).getName();
@Test
public void whenCreateAuthorThenSuccess() {
Author author = mock(Author.class);
AuthorEventHandler authorEventHandler = new AuthorEventHandler();
authorEventHandler.handleAuthorBeforeCreate(author);
Mockito.verify(author, Mockito.times(1)).getName();
}
}
@Test
public void whenDeleteAuthorThenSuccess() {
Author author = mock(Author.class);
AuthorEventHandler authorEventHandler = new AuthorEventHandler();
authorEventHandler.handleAuthorAfterDelete(author);
Mockito.verify(author,Mockito.times(1)).getName();
@Test
public void whenDeleteAuthorThenSuccess() {
Author author = mock(Author.class);
AuthorEventHandler authorEventHandler = new AuthorEventHandler();
authorEventHandler.handleAuthorAfterDelete(author);
Mockito.verify(author, Mockito.times(1)).getName();
}
}
}

View File

@ -8,21 +8,21 @@ import org.mockito.Mockito;
import static org.mockito.Mockito.mock;
public class BookEventHandlerUnitTest {
@Test
public void whenCreateBookThenSuccess() {
Book book = mock(Book.class);
BookEventHandler bookEventHandler = new BookEventHandler();
bookEventHandler.handleBookBeforeCreate(book);
Mockito.verify(book,Mockito.times(1)).getAuthors();
@Test
public void whenCreateBookThenSuccess() {
Book book = mock(Book.class);
BookEventHandler bookEventHandler = new BookEventHandler();
bookEventHandler.handleBookBeforeCreate(book);
Mockito.verify(book, Mockito.times(1)).getAuthors();
}
}
@Test
public void whenCreateAuthorThenSuccess() {
Author author = mock(Author.class);
BookEventHandler bookEventHandler = new BookEventHandler();
bookEventHandler.handleAuthorBeforeCreate(author);
Mockito.verify(author,Mockito.times(1)).getBooks();
@Test
public void whenCreateAuthorThenSuccess() {
Author author = mock(Author.class);
BookEventHandler bookEventHandler = new BookEventHandler();
bookEventHandler.handleAuthorBeforeCreate(author);
Mockito.verify(author, Mockito.times(1)).getBooks();
}
}
}

View File

@ -29,7 +29,6 @@ public class SpringDataProjectionLiveTest {
private static final String BOOK_ENDPOINT = "http://localhost:8080/books";
private static final String AUTHOR_ENDPOINT = "http://localhost:8080/authors";
@Autowired
private BookRepository bookRepo;
@ -37,8 +36,8 @@ public class SpringDataProjectionLiveTest {
private AuthorRepository authorRepo;
@Before
public void setup(){
if(bookRepo.findById(1L) == null){
public void setup() {
if (bookRepo.findById(1L) == null) {
Book book = new Book("Animal Farm");
book.setIsbn("978-1943138425");
book = bookRepo.save(book);
@ -50,39 +49,38 @@ public class SpringDataProjectionLiveTest {
}
@Test
public void whenGetBook_thenOK(){
final Response response = RestAssured.get(BOOK_ENDPOINT+"/1");
public void whenGetBook_thenOK() {
final Response response = RestAssured.get(BOOK_ENDPOINT + "/1");
assertEquals(200, response.getStatusCode());
assertTrue(response.asString().contains("isbn"));
assertFalse(response.asString().contains("authorCount"));
// System.out.println(response.asString());
// System.out.println(response.asString());
}
@Test
public void whenGetBookProjection_thenOK(){
final Response response = RestAssured.get(BOOK_ENDPOINT+"/1?projection=customBook");
public void whenGetBookProjection_thenOK() {
final Response response = RestAssured.get(BOOK_ENDPOINT + "/1?projection=customBook");
assertEquals(200, response.getStatusCode());
assertFalse(response.asString().contains("isbn"));
assertTrue(response.asString().contains("authorCount"));
// System.out.println(response.asString());
// System.out.println(response.asString());
}
@Test
public void whenGetAllBooks_thenOK(){
public void whenGetAllBooks_thenOK() {
final Response response = RestAssured.get(BOOK_ENDPOINT);
assertEquals(200, response.getStatusCode());
assertFalse(response.asString().contains("isbn"));
assertTrue(response.asString().contains("authorCount"));
// System.out.println(response.asString());
// System.out.println(response.asString());
}
@Test
public void whenGetAuthorBooks_thenOK(){
final Response response = RestAssured.get(AUTHOR_ENDPOINT+"/1/books");
public void whenGetAuthorBooks_thenOK() {
final Response response = RestAssured.get(AUTHOR_ENDPOINT + "/1/books");
assertEquals(200, response.getStatusCode());
assertFalse(response.asString().contains("isbn"));

View File

@ -14,7 +14,9 @@
</http>
<beans:bean class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler" name="awareAuthenticationSuccessHandler"/>
<beans:bean class="org.baeldung.security.RefererAuthenticationSuccessHandler" name="refererHandler"/>
<beans:bean class="com.baeldung.security.RefererAuthenticationSuccessHandler" name="refererHandler"/>
<beans:bean class="com.baeldung.controller.SecuredResourceController" />
<beans:bean id ="passwordEncoder" class = "org.springframework.security.crypto.password.NoOpPasswordEncoder" factory-method = "getInstance" />
<authentication-manager>
<authentication-provider>
@ -26,4 +28,3 @@
</beans:beans>