Merge branch 'master' of https://github.com/eugenp/tutorials into BAEL-2550
This commit is contained in:
commit
5f23e39332
@ -0,0 +1,34 @@
|
||||
package com.baeldung.java8.lambda.methodreference;
|
||||
|
||||
public class Bicycle {
|
||||
|
||||
private String brand;
|
||||
private Integer frameSize;
|
||||
|
||||
public Bicycle(String brand) {
|
||||
this.brand = brand;
|
||||
this.frameSize = 0;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
@ -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());
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,78 @@
|
||||
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 referenceToConstructorSimpleExample() {
|
||||
List<String> bikeBrands = Arrays.asList("Giant", "Scott", "Trek", "GT");
|
||||
bikeBrands.stream()
|
||||
.map(Bicycle::new)
|
||||
.toArray(Bicycle[]::new);
|
||||
}
|
||||
|
||||
@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) -> MethodReferenceExamples.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;
|
||||
}
|
||||
|
||||
}
|
@ -36,6 +36,22 @@
|
||||
<version>${lombok.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>net.sf.trove4j</groupId>
|
||||
<artifactId>trove4j</artifactId>
|
||||
<version>3.0.2</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>it.unimi.dsi</groupId>
|
||||
<artifactId>fastutil</artifactId>
|
||||
<version>8.1.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>colt</groupId>
|
||||
<artifactId>colt</artifactId>
|
||||
<version>1.2.0</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
|
@ -0,0 +1,52 @@
|
||||
package com.baeldung.list.primitive;
|
||||
|
||||
import com.google.common.primitives.ImmutableIntArray;
|
||||
import com.google.common.primitives.Ints;
|
||||
import gnu.trove.list.array.TIntArrayList;
|
||||
import it.unimi.dsi.fastutil.ints.IntArrayList;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.OptionalDouble;
|
||||
import java.util.function.IntPredicate;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
public class PrimitiveCollections {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
int[] primitives = new int[] {5, 10, 0, 2, -8};
|
||||
|
||||
guavaPrimitives(primitives);
|
||||
|
||||
intStream(primitives);
|
||||
|
||||
TIntArrayList tList = new TIntArrayList(primitives);
|
||||
|
||||
cern.colt.list.IntArrayList coltList = new cern.colt.list.IntArrayList(primitives);
|
||||
|
||||
IntArrayList fastUtilList = new IntArrayList(primitives);
|
||||
|
||||
System.out.println(tList);
|
||||
|
||||
System.out.println(coltList);
|
||||
|
||||
System.out.println(fastUtilList);
|
||||
}
|
||||
|
||||
private static void intStream(int[] primitives) {
|
||||
|
||||
IntStream stream = IntStream.of(5, 10, 0, 2, -8);
|
||||
|
||||
IntStream newStream = IntStream.of(primitives);
|
||||
|
||||
OptionalDouble average = stream.filter(i -> i > 0).average();
|
||||
}
|
||||
|
||||
|
||||
private static void guavaPrimitives(int[] primitives) {
|
||||
|
||||
ImmutableIntArray immutableIntArray = ImmutableIntArray.builder().addAll(primitives).build();
|
||||
System.out.println(immutableIntArray);
|
||||
}
|
||||
}
|
@ -37,3 +37,4 @@
|
||||
- [Guide to BufferedReader](https://www.baeldung.com/java-buffered-reader)
|
||||
- [How to Get the File Extension of a File in Java](http://www.baeldung.com/java-file-extension)
|
||||
- [Getting a File’s Mime Type in Java](http://www.baeldung.com/java-file-mime-type)
|
||||
- [Create a Directory in Java](https://www.baeldung.com/java-create-directory)
|
||||
|
64
core-java-io/src/main/java/com/baeldung/files/ListFiles.java
Normal file
64
core-java-io/src/main/java/com/baeldung/files/ListFiles.java
Normal 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;
|
||||
}
|
||||
|
||||
}
|
@ -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));
|
||||
}
|
||||
}
|
@ -0,0 +1 @@
|
||||
This is a sample txt file for unit test ListFilesUnitTest
|
@ -0,0 +1 @@
|
||||
{}
|
@ -0,0 +1 @@
|
||||
{}
|
@ -0,0 +1 @@
|
||||
<xml></xml>
|
@ -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++;
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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);
|
||||
}
|
||||
}
|
@ -46,3 +46,4 @@
|
||||
- [Graphs in Java](https://www.baeldung.com/java-graphs)
|
||||
- [Console I/O in Java](http://www.baeldung.com/java-console-input-output)
|
||||
- [Formatting with printf() in Java](https://www.baeldung.com/java-printstream-printf)
|
||||
- [Retrieve Fields from a Java Class Using Reflection](https://www.baeldung.com/java-reflection-class-fields)
|
||||
|
@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -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");
|
||||
}
|
||||
|
||||
|
||||
}
|
@ -15,3 +15,4 @@
|
||||
- [Stream Ordering in Java](https://www.baeldung.com/java-stream-ordering)
|
||||
- [Introduction to Protonpack](https://www.baeldung.com/java-protonpack)
|
||||
- [Java Stream Filter with Lambda Expression](https://www.baeldung.com/java-stream-filter-lambda)
|
||||
- [Counting Matches on a Stream Filter](https://www.baeldung.com/java-stream-filter-count)
|
||||
|
@ -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>
|
||||
|
@ -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);
|
||||
}
|
||||
}
|
@ -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();
|
||||
}
|
||||
}
|
@ -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)
|
||||
|
||||
|
@ -1,4 +1,4 @@
|
||||
package com.baeldung.lombok.builder;
|
||||
package com.baeldung.lombok.builder.inheritance.buildermethodname;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Getter;
|
@ -1,4 +1,4 @@
|
||||
package com.baeldung.lombok.builder;
|
||||
package com.baeldung.lombok.builder.inheritance.buildermethodname;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Getter;
|
@ -0,0 +1,16 @@
|
||||
package com.baeldung.lombok.builder.inheritance.buildermethodname;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
public class Student extends Child {
|
||||
|
||||
private final String schoolName;
|
||||
|
||||
@Builder(builderMethodName = "studentBuilder")
|
||||
public Student(String parentName, int parentAge, String childName, int childAge, String schoolName) {
|
||||
super(parentName, parentAge, childName, childAge);
|
||||
this.schoolName = schoolName;
|
||||
}
|
||||
}
|
@ -0,0 +1,11 @@
|
||||
package com.baeldung.lombok.builder.inheritance.superbuilder;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.experimental.SuperBuilder;
|
||||
|
||||
@Getter
|
||||
@SuperBuilder(toBuilder = true)
|
||||
public class Child extends Parent {
|
||||
private final String childName;
|
||||
private final int childAge;
|
||||
}
|
@ -0,0 +1,11 @@
|
||||
package com.baeldung.lombok.builder.inheritance.superbuilder;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.experimental.SuperBuilder;
|
||||
|
||||
@Getter
|
||||
@SuperBuilder(toBuilder = true)
|
||||
public class Parent {
|
||||
private final String parentName;
|
||||
private final int parentAge;
|
||||
}
|
@ -0,0 +1,10 @@
|
||||
package com.baeldung.lombok.builder.inheritance.superbuilder;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.experimental.SuperBuilder;
|
||||
|
||||
@Getter
|
||||
@SuperBuilder(toBuilder = true)
|
||||
public class Student extends Child {
|
||||
private final String schoolName;
|
||||
}
|
@ -40,20 +40,4 @@ public class BuilderUnitTest {
|
||||
assertThat(testImmutableClient.getName()).isEqualTo("foo");
|
||||
assertThat(testImmutableClient.getId()).isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBuilderAtMethodLevel_ChildInheritingParentIsBuilt() {
|
||||
Child child = Child.childBuilder()
|
||||
.parentName("Andrea")
|
||||
.parentAge(38)
|
||||
.childName("Emma")
|
||||
.childAge(6)
|
||||
.build();
|
||||
|
||||
assertThat(child.getChildName()).isEqualTo("Emma");
|
||||
assertThat(child.getChildAge()).isEqualTo(6);
|
||||
assertThat(child.getParentName()).isEqualTo("Andrea");
|
||||
assertThat(child.getParentAge()).isEqualTo(38);
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -0,0 +1,40 @@
|
||||
package com.baeldung.lombok.builder.inheritance.buildermethodname;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class BuilderInheritanceUsingMethodNameUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenBuilderAtMethodLevel_ChildInheritingParentIsBuilt() {
|
||||
Child child = Child.childBuilder()
|
||||
.parentName("Andrea")
|
||||
.parentAge(38)
|
||||
.childName("Emma")
|
||||
.childAge(6)
|
||||
.build();
|
||||
|
||||
assertThat(child.getChildName()).isEqualTo("Emma");
|
||||
assertThat(child.getChildAge()).isEqualTo(6);
|
||||
assertThat(child.getParentName()).isEqualTo("Andrea");
|
||||
assertThat(child.getParentAge()).isEqualTo(38);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSuperBuilderOnAllThreeLevels_StudentInheritingChildAndParentIsBuilt() {
|
||||
Student student = Student.studentBuilder()
|
||||
.parentName("Andrea")
|
||||
.parentAge(38)
|
||||
.childName("Emma")
|
||||
.childAge(6)
|
||||
.schoolName("Baeldung High School")
|
||||
.build();
|
||||
|
||||
assertThat(student.getChildName()).isEqualTo("Emma");
|
||||
assertThat(student.getChildAge()).isEqualTo(6);
|
||||
assertThat(student.getParentName()).isEqualTo("Andrea");
|
||||
assertThat(student.getParentAge()).isEqualTo(38);
|
||||
assertThat(student.getSchoolName()).isEqualTo("Baeldung High School");
|
||||
}
|
||||
}
|
@ -0,0 +1,96 @@
|
||||
package com.baeldung.lombok.builder.inheritance.superbuilder;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class BuilderInheritanceUsingSuperBuilderUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenSuperBuilderOnParentAndOnChild_ChildInheritingParentIsBuilt() {
|
||||
Child child = Child.builder()
|
||||
.parentName("Andrea")
|
||||
.parentAge(38)
|
||||
.childName("Emma")
|
||||
.childAge(6)
|
||||
.build();
|
||||
|
||||
assertThat(child.getChildName()).isEqualTo("Emma");
|
||||
assertThat(child.getChildAge()).isEqualTo(6);
|
||||
assertThat(child.getParentName()).isEqualTo("Andrea");
|
||||
assertThat(child.getParentAge()).isEqualTo(38);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSuperBuilderOnParent_StandardBuilderIsBuilt() {
|
||||
Parent parent = Parent.builder()
|
||||
.parentName("Andrea")
|
||||
.parentAge(38)
|
||||
.build();
|
||||
|
||||
assertThat(parent.getParentName()).isEqualTo("Andrea");
|
||||
assertThat(parent.getParentAge()).isEqualTo(38);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenToBuilderIsSetToTrueOnParentAndChild_DeepCopyViaBuilderIsPossible() {
|
||||
Child child1 = Child.builder()
|
||||
.parentName("Andrea")
|
||||
.parentAge(38)
|
||||
.childName("Emma")
|
||||
.childAge(6)
|
||||
.build();
|
||||
|
||||
Child child2 = child1.toBuilder()
|
||||
.childName("Anna")
|
||||
.build();
|
||||
|
||||
assertThat(child2.getChildName()).isEqualTo("Anna");
|
||||
assertThat(child2.getChildAge()).isEqualTo(6);
|
||||
assertThat(child2.getParentName()).isEqualTo("Andrea");
|
||||
assertThat(child2.getParentAge()).isEqualTo(38);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSuperBuilderOnAllThreeLevels_StudentInheritingChildAndParentIsBuilt() {
|
||||
Student student = Student.builder()
|
||||
.parentName("Andrea")
|
||||
.parentAge(38)
|
||||
.childName("Emma")
|
||||
.childAge(6)
|
||||
.schoolName("Baeldung High School")
|
||||
.build();
|
||||
|
||||
assertThat(student.getChildName()).isEqualTo("Emma");
|
||||
assertThat(student.getChildAge()).isEqualTo(6);
|
||||
assertThat(student.getParentName()).isEqualTo("Andrea");
|
||||
assertThat(student.getParentAge()).isEqualTo(38);
|
||||
assertThat(student.getSchoolName()).isEqualTo("Baeldung High School");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenToBuilderIsSetToTrueOnParentChildAndStudent_DeepCopyViaBuilderIsPossible() {
|
||||
Student student1 = Student.builder()
|
||||
.parentName("Andrea")
|
||||
.parentAge(38)
|
||||
.childName("Emma")
|
||||
.childAge(6)
|
||||
.schoolName("School 1")
|
||||
.build();
|
||||
|
||||
Student student2 = student1.toBuilder()
|
||||
.childName("Anna")
|
||||
.schoolName("School 2")
|
||||
.build();
|
||||
|
||||
assertThat(student2.getChildName()).isEqualTo("Anna");
|
||||
assertThat(student2.getChildAge()).isEqualTo(6);
|
||||
assertThat(student2.getParentName()).isEqualTo("Andrea");
|
||||
assertThat(student2.getParentAge()).isEqualTo(38);
|
||||
assertThat(student2.getSchoolName()).isEqualTo("School 2");
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
@ -30,6 +30,11 @@
|
||||
<version>${springframework.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>${org.projectlombok.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
@ -48,6 +53,11 @@
|
||||
<artifactId>mapstruct-processor</artifactId>
|
||||
<version>${org.mapstruct.version}</version>
|
||||
</path>
|
||||
<path>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>${org.projectlombok.version}</version>
|
||||
</path>
|
||||
</annotationProcessorPaths>
|
||||
</configuration>
|
||||
</plugin>
|
||||
@ -55,10 +65,11 @@
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<org.mapstruct.version>1.1.0.Final</org.mapstruct.version>
|
||||
<org.mapstruct.version>1.3.0.Beta2</org.mapstruct.version>
|
||||
<springframework.version>4.3.4.RELEASE</springframework.version>
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
<org.projectlombok.version>1.18.4</org.projectlombok.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
11
mapstruct/src/main/java/com/baeldung/dto/CarDTO.java
Normal file
11
mapstruct/src/main/java/com/baeldung/dto/CarDTO.java
Normal file
@ -0,0 +1,11 @@
|
||||
package com.baeldung.dto;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public class CarDTO {
|
||||
private int id;
|
||||
private String name;
|
||||
}
|
33
mapstruct/src/main/java/com/baeldung/dto/PersonDTO.java
Normal file
33
mapstruct/src/main/java/com/baeldung/dto/PersonDTO.java
Normal file
@ -0,0 +1,33 @@
|
||||
package com.baeldung.dto;
|
||||
|
||||
public class PersonDTO {
|
||||
|
||||
private String id;
|
||||
private String name;
|
||||
|
||||
public PersonDTO() {
|
||||
|
||||
}
|
||||
|
||||
public PersonDTO(String id, String name) {
|
||||
super();
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
11
mapstruct/src/main/java/com/baeldung/entity/Car.java
Normal file
11
mapstruct/src/main/java/com/baeldung/entity/Car.java
Normal file
@ -0,0 +1,11 @@
|
||||
package com.baeldung.entity;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public class Car {
|
||||
private int id;
|
||||
private String name;
|
||||
}
|
33
mapstruct/src/main/java/com/baeldung/entity/Person.java
Normal file
33
mapstruct/src/main/java/com/baeldung/entity/Person.java
Normal file
@ -0,0 +1,33 @@
|
||||
package com.baeldung.entity;
|
||||
|
||||
public class Person {
|
||||
|
||||
private String id;
|
||||
private String name;
|
||||
|
||||
public Person() {
|
||||
|
||||
}
|
||||
|
||||
public Person(String id, String name) {
|
||||
super();
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
15
mapstruct/src/main/java/com/baeldung/mapper/CarMapper.java
Normal file
15
mapstruct/src/main/java/com/baeldung/mapper/CarMapper.java
Normal file
@ -0,0 +1,15 @@
|
||||
package com.baeldung.mapper;
|
||||
|
||||
import org.mapstruct.Mapper;
|
||||
import org.mapstruct.factory.Mappers;
|
||||
|
||||
import com.baeldung.dto.CarDTO;
|
||||
import com.baeldung.entity.Car;
|
||||
|
||||
@Mapper
|
||||
public interface CarMapper {
|
||||
|
||||
CarMapper INSTANCE = Mappers.getMapper(CarMapper.class);
|
||||
|
||||
CarDTO carToCarDTO(Car car);
|
||||
}
|
@ -0,0 +1,17 @@
|
||||
package com.baeldung.mapper;
|
||||
|
||||
import org.mapstruct.Mapper;
|
||||
import org.mapstruct.Mapping;
|
||||
import org.mapstruct.factory.Mappers;
|
||||
|
||||
import com.baeldung.dto.PersonDTO;
|
||||
import com.baeldung.entity.Person;
|
||||
|
||||
@Mapper
|
||||
public interface PersonMapper {
|
||||
|
||||
PersonMapper INSTANCE = Mappers.getMapper(PersonMapper.class);
|
||||
|
||||
@Mapping(target = "id", source = "person.id", defaultExpression = "java(java.util.UUID.randomUUID().toString())")
|
||||
PersonDTO personToPersonDTO(Person person);
|
||||
}
|
@ -0,0 +1,24 @@
|
||||
package com.baeldung.mapper;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.dto.CarDTO;
|
||||
import com.baeldung.entity.Car;
|
||||
|
||||
public class CarMapperUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenCarEntitytoCar_whenMaps_thenCorrect() {
|
||||
|
||||
Car entity = new Car();
|
||||
entity.setId(1);
|
||||
entity.setName("Toyota");
|
||||
|
||||
CarDTO carDto = CarMapper.INSTANCE.carToCarDTO(entity);
|
||||
|
||||
assertEquals(carDto.getId(), entity.getId());
|
||||
assertEquals(carDto.getName(), entity.getName());
|
||||
}
|
||||
}
|
@ -0,0 +1,26 @@
|
||||
package com.baeldung.mapper;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertNull;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.dto.PersonDTO;
|
||||
import com.baeldung.entity.Person;
|
||||
|
||||
public class PersonMapperUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenPersonEntitytoPersonWithExpression_whenMaps_thenCorrect() {
|
||||
|
||||
Person entity = new Person();
|
||||
entity.setName("Micheal");
|
||||
|
||||
PersonDTO personDto = PersonMapper.INSTANCE.personToPersonDTO(entity);
|
||||
|
||||
assertNull(entity.getId());
|
||||
assertNotNull(personDto.getId());
|
||||
assertEquals(personDto.getName(), entity.getName());
|
||||
}
|
||||
}
|
23
patterns/principles/solid/pom.xml
Normal file
23
patterns/principles/solid/pom.xml
Normal 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>
|
@ -0,0 +1,4 @@
|
||||
package com.baeldung.d;
|
||||
|
||||
public class Keyboard {
|
||||
}
|
@ -0,0 +1,6 @@
|
||||
package com.baeldung.d;
|
||||
|
||||
public class Monitor {
|
||||
|
||||
|
||||
}
|
@ -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();
|
||||
|
||||
}
|
||||
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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..
|
||||
}
|
||||
}
|
@ -0,0 +1,5 @@
|
||||
package com.baeldung.i;
|
||||
|
||||
public interface BearCleaner {
|
||||
void washTheBear();
|
||||
}
|
@ -0,0 +1,5 @@
|
||||
package com.baeldung.i;
|
||||
|
||||
public interface BearFeeder {
|
||||
void feedTheBear();
|
||||
}
|
@ -0,0 +1,9 @@
|
||||
package com.baeldung.i;
|
||||
|
||||
public interface BearKeeper {
|
||||
|
||||
void washTheBear();
|
||||
void feedTheBear();
|
||||
void petTheBear();
|
||||
|
||||
}
|
@ -0,0 +1,5 @@
|
||||
package com.baeldung.i;
|
||||
|
||||
public interface BearPetter {
|
||||
void petTheBear();
|
||||
}
|
@ -0,0 +1,8 @@
|
||||
package com.baeldung.i;
|
||||
|
||||
public class CrazyPerson implements BearPetter {
|
||||
|
||||
public void petTheBear() {
|
||||
//Good luck with that!
|
||||
}
|
||||
}
|
@ -0,0 +1,8 @@
|
||||
package com.baeldung.l;
|
||||
|
||||
public interface Car {
|
||||
|
||||
void turnOnEngine();
|
||||
void accelerate();
|
||||
|
||||
}
|
@ -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!
|
||||
}
|
||||
}
|
@ -0,0 +1,13 @@
|
||||
package com.baeldung.l;
|
||||
|
||||
public class Engine {
|
||||
|
||||
public void on(){
|
||||
//vroom.
|
||||
}
|
||||
|
||||
public void powerOn(int amount){
|
||||
//do something
|
||||
}
|
||||
|
||||
}
|
@ -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);
|
||||
}
|
||||
}
|
@ -0,0 +1,10 @@
|
||||
package com.baeldung.o;
|
||||
|
||||
public class Guitar {
|
||||
|
||||
private String make;
|
||||
private String model;
|
||||
private int volume;
|
||||
|
||||
//Constructors, getters & setters
|
||||
}
|
@ -0,0 +1,9 @@
|
||||
package com.baeldung.o;
|
||||
|
||||
public class SuperCoolGuitarWithFlames extends Guitar {
|
||||
|
||||
private String flameColour;
|
||||
|
||||
//constructor, getters + setters
|
||||
|
||||
}
|
@ -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
|
||||
}
|
||||
|
||||
|
||||
}
|
@ -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..
|
||||
}
|
||||
}
|
@ -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);
|
||||
}
|
||||
|
||||
}
|
@ -29,3 +29,4 @@
|
||||
- [Hibernate Named Query](https://www.baeldung.com/hibernate-named-query)
|
||||
- [Using c3p0 with Hibernate](https://www.baeldung.com/hibernate-c3p0)
|
||||
- [Persist a JSON Object Using Hibernate](https://www.baeldung.com/hibernate-persist-json-object)
|
||||
- [Common Hibernate Exceptions](https://www.baeldung.com/hibernate-exceptions)
|
||||
|
@ -9,15 +9,43 @@ import javax.persistence.Id;
|
||||
public class Student {
|
||||
|
||||
@Id
|
||||
@GeneratedValue (strategy = GenerationType.SEQUENCE)
|
||||
@GeneratedValue(strategy = GenerationType.SEQUENCE)
|
||||
private long studentId;
|
||||
|
||||
private String name;
|
||||
|
||||
private int age;
|
||||
|
||||
public Student() {
|
||||
}
|
||||
|
||||
public Student(String name, int age) {
|
||||
this.name = name;
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public long getStudentId() {
|
||||
return studentId;
|
||||
}
|
||||
|
||||
public void setStudent_id(long studentId) {
|
||||
public void setStudentId(long studentId) {
|
||||
this.studentId = studentId;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public int getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public void setAge(int age) {
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -0,0 +1,87 @@
|
||||
package com.baeldung.hibernate.aggregatefunctions;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.hibernate.HibernateException;
|
||||
import org.hibernate.Session;
|
||||
import org.hibernate.Transaction;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.hibernate.HibernateUtil;
|
||||
import com.baeldung.hibernate.pojo.Student;
|
||||
|
||||
public class AggregateFunctionsIntegrationTest {
|
||||
|
||||
private static Session session;
|
||||
private static Transaction transaction;
|
||||
|
||||
@BeforeClass
|
||||
public static final void setup() throws HibernateException, IOException {
|
||||
session = HibernateUtil.getSessionFactory()
|
||||
.openSession();
|
||||
transaction = session.beginTransaction();
|
||||
|
||||
Student jonas = new Student("Jonas", 22);
|
||||
session.save(jonas);
|
||||
|
||||
Student sally = new Student("Sally", 20);
|
||||
session.save(sally);
|
||||
|
||||
Student simon = new Student("Simon", 25);
|
||||
session.save(simon);
|
||||
|
||||
Student raven = new Student("Raven", 21);
|
||||
session.save(raven);
|
||||
|
||||
Student sam = new Student("Sam", 23);
|
||||
session.save(sam);
|
||||
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static final void teardown() {
|
||||
if (session != null) {
|
||||
transaction.rollback();
|
||||
session.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenMaxAge_ThenReturnValue() {
|
||||
int maxAge = (int) session.createQuery("SELECT MAX(age) from Student")
|
||||
.getSingleResult();
|
||||
assertThat(maxAge).isEqualTo(25);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenMinAge_ThenReturnValue() {
|
||||
int minAge = (int) session.createQuery("SELECT MIN(age) from Student")
|
||||
.getSingleResult();
|
||||
assertThat(minAge).isEqualTo(20);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAverageAge_ThenReturnValue() {
|
||||
Double avgAge = (Double) session.createQuery("SELECT AVG(age) from Student")
|
||||
.getSingleResult();
|
||||
assertThat(avgAge).isEqualTo(22.2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCountAll_ThenReturnValue() {
|
||||
Long totalStudents = (Long) session.createQuery("SELECT COUNT(*) from Student")
|
||||
.getSingleResult();
|
||||
assertThat(totalStudents).isEqualTo(5);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSumOfAllAges_ThenReturnValue() {
|
||||
Long sumOfAllAges = (Long) session.createQuery("SELECT SUM(age) from Student")
|
||||
.getSingleResult();
|
||||
assertThat(sumOfAllAges).isEqualTo(111);
|
||||
}
|
||||
}
|
@ -4,3 +4,4 @@
|
||||
- [A Guide to Stored Procedures with JPA](http://www.baeldung.com/jpa-stored-procedures)
|
||||
- [Fixing the JPA error “java.lang.String cannot be cast to Ljava.lang.String;”](https://www.baeldung.com/jpa-error-java-lang-string-cannot-be-cast)
|
||||
- [JPA Entity Graph](https://www.baeldung.com/jpa-entity-graph)
|
||||
- [JPA 2.2 Support for Java 8 Date/Time Types](https://www.baeldung.com/jpa-java-time)
|
||||
|
@ -0,0 +1,19 @@
|
||||
package com.baeldung;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.test.context.support.AnnotationConfigContextLoader;
|
||||
import org.springframework.test.context.web.WebAppConfiguration;
|
||||
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(loader = AnnotationConfigContextLoader.class)
|
||||
@WebAppConfiguration
|
||||
public class SpringContextIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
|
||||
}
|
||||
}
|
@ -0,0 +1,19 @@
|
||||
package com.baeldung;
|
||||
|
||||
import org.baeldung.config.PersistenceJPAConfigL2Cache;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.test.context.support.AnnotationConfigContextLoader;
|
||||
import org.springframework.test.context.web.WebAppConfiguration;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = { PersistenceJPAConfigL2Cache.class }, loader = AnnotationConfigContextLoader.class)
|
||||
@WebAppConfiguration
|
||||
public class SpringContextIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
|
||||
}
|
||||
}
|
2
pom.xml
2
pom.xml
@ -568,6 +568,7 @@
|
||||
<module>rsocket</module>
|
||||
<module>rxjava</module>
|
||||
<module>rxjava-2</module>
|
||||
<module>software-security/sql-injection-samples</module>
|
||||
|
||||
</modules>
|
||||
|
||||
@ -732,6 +733,7 @@
|
||||
<module>spring-security-mvc-boot</module>
|
||||
<module>spring-security-mvc-custom</module>
|
||||
<module>spring-security-mvc-digest-auth</module>
|
||||
<module>spring-security-mvc-jsonview</module>
|
||||
<module>spring-security-mvc-ldap</module>
|
||||
<module>spring-security-mvc-login</module>
|
||||
<module>spring-security-mvc-persisted-remember-me</module>
|
||||
|
25
software-security/sql-injection-samples/.gitignore
vendored
Normal file
25
software-security/sql-injection-samples/.gitignore
vendored
Normal file
@ -0,0 +1,25 @@
|
||||
/target/
|
||||
!.mvn/wrapper/maven-wrapper.jar
|
||||
|
||||
### STS ###
|
||||
.apt_generated
|
||||
.classpath
|
||||
.factorypath
|
||||
.project
|
||||
.settings
|
||||
.springBeans
|
||||
.sts4-cache
|
||||
|
||||
### IntelliJ IDEA ###
|
||||
.idea
|
||||
*.iws
|
||||
*.iml
|
||||
*.ipr
|
||||
|
||||
### NetBeans ###
|
||||
/nbproject/private/
|
||||
/build/
|
||||
/nbbuild/
|
||||
/dist/
|
||||
/nbdist/
|
||||
/.nb-gradle/
|
61
software-security/sql-injection-samples/pom.xml
Normal file
61
software-security/sql-injection-samples/pom.xml
Normal file
@ -0,0 +1,61 @@
|
||||
<?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>
|
||||
|
||||
<parent>
|
||||
<artifactId>parent-boot-2</artifactId>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-boot-2</relativePath>
|
||||
</parent>
|
||||
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>sql-injection-samples</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>sql-injection-samples</name>
|
||||
<description>Sample SQL Injection tests</description>
|
||||
|
||||
<properties>
|
||||
<java.version>1.8</java.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-jdbc</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.derby</groupId>
|
||||
<artifactId>derby</artifactId>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-configuration-processor</artifactId>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
@ -0,0 +1,169 @@
|
||||
/**
|
||||
*
|
||||
*/
|
||||
package com.baeldung.examples.security.sql;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* @author Philippe
|
||||
*
|
||||
*/
|
||||
@Component
|
||||
public class AccountDAO {
|
||||
|
||||
private final DataSource dataSource;
|
||||
|
||||
public AccountDAO(DataSource dataSource) {
|
||||
this.dataSource = dataSource;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return all accounts owned by a given customer,given his/her external id
|
||||
*
|
||||
* @param customerId
|
||||
* @return
|
||||
*/
|
||||
public List<AccountDTO> unsafeFindAccountsByCustomerId(String customerId) {
|
||||
|
||||
String sql = "select " + "customer_id,acc_number,branch_id,balance from Accounts where customer_id = '" + customerId + "'";
|
||||
|
||||
try (Connection c = dataSource.getConnection();
|
||||
ResultSet rs = c.createStatement()
|
||||
.executeQuery(sql)) {
|
||||
List<AccountDTO> accounts = new ArrayList<>();
|
||||
while (rs.next()) {
|
||||
AccountDTO acc = AccountDTO.builder()
|
||||
.customerId(rs.getString("customer_id"))
|
||||
.branchId(rs.getString("branch_id"))
|
||||
.accNumber(rs.getString("acc_number"))
|
||||
.balance(rs.getBigDecimal("balance"))
|
||||
.build();
|
||||
|
||||
accounts.add(acc);
|
||||
}
|
||||
|
||||
return accounts;
|
||||
} catch (SQLException ex) {
|
||||
throw new RuntimeException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Return all accounts owned by a given customer,given his/her external id
|
||||
*
|
||||
* @param customerId
|
||||
* @return
|
||||
*/
|
||||
public List<AccountDTO> safeFindAccountsByCustomerId(String customerId) {
|
||||
|
||||
String sql = "select " + "customer_id,acc_number,branch_id,balance from Accounts where customer_id = ?";
|
||||
|
||||
try (Connection c = dataSource.getConnection(); PreparedStatement p = c.prepareStatement(sql)) {
|
||||
p.setString(1, customerId);
|
||||
ResultSet rs = p.executeQuery();
|
||||
List<AccountDTO> accounts = new ArrayList<>();
|
||||
while (rs.next()) {
|
||||
AccountDTO acc = AccountDTO.builder()
|
||||
.customerId(rs.getString("customerId"))
|
||||
.branchId(rs.getString("branch_id"))
|
||||
.accNumber(rs.getString("acc_number"))
|
||||
.balance(rs.getBigDecimal("balance"))
|
||||
.build();
|
||||
|
||||
accounts.add(acc);
|
||||
}
|
||||
return accounts;
|
||||
} catch (SQLException ex) {
|
||||
throw new RuntimeException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
private static final Set<String> VALID_COLUMNS_FOR_ORDER_BY = Stream.of("acc_number", "branch_id", "balance")
|
||||
.collect(Collectors.toCollection(HashSet::new));
|
||||
|
||||
/**
|
||||
* Return all accounts owned by a given customer,given his/her external id
|
||||
*
|
||||
* @param customerId
|
||||
* @return
|
||||
*/
|
||||
public List<AccountDTO> safeFindAccountsByCustomerId(String customerId, String orderBy) {
|
||||
|
||||
String sql = "select " + "customer_id,acc_number,branch_id,balance from Accounts where customer_id = ? ";
|
||||
|
||||
if (VALID_COLUMNS_FOR_ORDER_BY.contains(orderBy)) {
|
||||
sql = sql + " order by " + orderBy;
|
||||
}
|
||||
else {
|
||||
throw new IllegalArgumentException("Nice try!");
|
||||
}
|
||||
|
||||
try (Connection c = dataSource.getConnection(); PreparedStatement p = c.prepareStatement(sql)) {
|
||||
|
||||
p.setString(1, customerId);
|
||||
ResultSet rs = p.executeQuery();
|
||||
List<AccountDTO> accounts = new ArrayList<>();
|
||||
while (rs.next()) {
|
||||
AccountDTO acc = AccountDTO.builder()
|
||||
.customerId(rs.getString("customerId"))
|
||||
.branchId(rs.getString("branch_id"))
|
||||
.accNumber(rs.getString("acc_number"))
|
||||
.balance(rs.getBigDecimal("balance"))
|
||||
.build();
|
||||
|
||||
accounts.add(acc);
|
||||
}
|
||||
|
||||
return accounts;
|
||||
} catch (SQLException ex) {
|
||||
throw new RuntimeException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Invalid placeholder usage example
|
||||
*
|
||||
* @param tableName
|
||||
* @return
|
||||
*/
|
||||
public List<AccountDTO> wrongCountRecordsByTableName(String tableName) {
|
||||
|
||||
try (Connection c = dataSource.getConnection();
|
||||
PreparedStatement p = c.prepareStatement("select count(*) from ?")) {
|
||||
|
||||
p.setString(1, tableName);
|
||||
ResultSet rs = p.executeQuery();
|
||||
List<AccountDTO> accounts = new ArrayList<>();
|
||||
while (rs.next()) {
|
||||
AccountDTO acc = AccountDTO.builder()
|
||||
.customerId(rs.getString("customerId"))
|
||||
.branchId(rs.getString("branch_id"))
|
||||
.accNumber(rs.getString("acc_number"))
|
||||
.balance(rs.getBigDecimal("balance"))
|
||||
.build();
|
||||
|
||||
accounts.add(acc);
|
||||
}
|
||||
|
||||
return accounts;
|
||||
} catch (SQLException ex) {
|
||||
throw new RuntimeException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,16 @@
|
||||
package com.baeldung.examples.security.sql;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
public class AccountDTO {
|
||||
|
||||
private String customerId;
|
||||
private String accNumber;
|
||||
private String branchId;
|
||||
private BigDecimal balance;
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
package com.baeldung.examples.security.sql;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class SqlInjectionSamplesApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(SqlInjectionSamplesApplication.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -0,0 +1,19 @@
|
||||
<databaseChangeLog
|
||||
xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog
|
||||
http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd">
|
||||
|
||||
<changeSet id="create-tables" author="baeldung">
|
||||
<createTable tableName="Accounts" >
|
||||
<column name="id" autoIncrement="true" type="BIGINT" remarks="Internal account PK" >
|
||||
<constraints primaryKey="true"/>
|
||||
</column>
|
||||
<column name="customer_id" type="java.sql.Types.VARCHAR(32)" remarks="External Customer Id"></column>
|
||||
<column name="acc_number" type="java.sql.Types.VARCHAR(128)" remarks="External Account Number"></column>
|
||||
<column name="branch_id" type="java.sql.Types.VARCHAR(32)"></column>
|
||||
<column name="balance" type="CURRENCY"></column>
|
||||
|
||||
</createTable>
|
||||
</changeSet>
|
||||
</databaseChangeLog>
|
@ -0,0 +1,8 @@
|
||||
<databaseChangeLog
|
||||
xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog
|
||||
http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd">
|
||||
|
||||
<include file="changelog/create-tables.xml" relativeToChangelogFile="true"/>
|
||||
</databaseChangeLog>
|
@ -0,0 +1,60 @@
|
||||
package com.baeldung.examples.security.sql;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
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.test.context.ActiveProfiles;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import com.baeldung.examples.security.sql.AccountDAO;
|
||||
import com.baeldung.examples.security.sql.AccountDTO;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest
|
||||
@ActiveProfiles({ "test" })
|
||||
public class SqlInjectionSamplesApplicationUnitTest {
|
||||
|
||||
@Autowired
|
||||
private AccountDAO target;
|
||||
|
||||
@Test
|
||||
public void givenAVulnerableMethod_whenValidCustomerId_thenReturnSingleAccount() {
|
||||
|
||||
List<AccountDTO> accounts = target.unsafeFindAccountsByCustomerId("C1");
|
||||
assertThat(accounts).isNotNull();
|
||||
assertThat(accounts).isNotEmpty();
|
||||
assertThat(accounts).hasSize(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAVulnerableMethod_whenHackedCustomerId_thenReturnAllAccounts() {
|
||||
|
||||
List<AccountDTO> accounts = target.unsafeFindAccountsByCustomerId("C1' or '1'='1");
|
||||
assertThat(accounts).isNotNull();
|
||||
assertThat(accounts).isNotEmpty();
|
||||
assertThat(accounts).hasSize(3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenASafeMethod_whenHackedCustomerId_thenReturnNoAccounts() {
|
||||
|
||||
List<AccountDTO> accounts = target.safeFindAccountsByCustomerId("C1' or '1'='1");
|
||||
assertThat(accounts).isNotNull();
|
||||
assertThat(accounts).isEmpty();
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void givenASafeMethod_whenInvalidOrderBy_thenThroweException() {
|
||||
target.safeFindAccountsByCustomerId("C1", "INVALID");
|
||||
}
|
||||
|
||||
@Test(expected = RuntimeException.class)
|
||||
public void givenWrongPlaceholderUsageMethod_whenNormalCall_thenThrowsException() {
|
||||
target.wrongCountRecordsByTableName("Accounts");
|
||||
}
|
||||
}
|
@ -0,0 +1,6 @@
|
||||
#
|
||||
# Test profile configuration
|
||||
#
|
||||
spring:
|
||||
datasource:
|
||||
initialization-mode: always
|
@ -0,0 +1,4 @@
|
||||
insert into Accounts(customer_id,acc_number,branch_id,balance) values ('C1','0001',1,1000.00);
|
||||
insert into Accounts(customer_id,acc_number,branch_id,balance) values ('C2','0002',1,500.00);
|
||||
insert into Accounts(customer_id,acc_number,branch_id,balance) values ('C3','0003',1,501.00);
|
||||
|
@ -0,0 +1,6 @@
|
||||
create table Accounts (
|
||||
customer_id varchar(16) not null,
|
||||
acc_number varchar(16) not null,
|
||||
branch_id decimal(8,0),
|
||||
balance decimal(16,4)
|
||||
);
|
@ -2,13 +2,16 @@ package org.baeldung;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.test.context.web.WebAppConfiguration;
|
||||
|
||||
import com.baeldung.flips.ApplicationConfig;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = ApplicationConfig.class)
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = ApplicationConfig.class)
|
||||
@WebAppConfiguration
|
||||
public class SpringContextIntegrationTest {
|
||||
|
||||
@Test
|
||||
|
@ -0,0 +1,19 @@
|
||||
package com.baeldung;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.test.context.web.WebAppConfiguration;
|
||||
|
||||
import com.baeldung.autoconfiguration.MySQLAutoconfiguration;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = MySQLAutoconfiguration.class)
|
||||
@WebAppConfiguration
|
||||
public class SpringContextLiveTest {
|
||||
|
||||
@Test
|
||||
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
|
||||
}
|
||||
}
|
@ -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");
|
||||
|
@ -72,6 +72,16 @@
|
||||
<version>${spring.fox.version}</version>
|
||||
</dependency>
|
||||
|
||||
<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>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
@ -0,0 +1,13 @@
|
||||
package com.baeldung.accessparamsjs;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class App {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(App.class, args);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,32 @@
|
||||
package com.baeldung.accessparamsjs;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.servlet.ModelAndView;
|
||||
|
||||
/**
|
||||
* Sample rest controller for the tutorial article
|
||||
* "Access Spring MVC Model object in JavaScript".
|
||||
*
|
||||
* @author Andrew Shcherbakov
|
||||
*
|
||||
*/
|
||||
@RestController
|
||||
public class Controller {
|
||||
|
||||
/**
|
||||
* Define two model objects (one integer and one string) and pass them to the view.
|
||||
*
|
||||
* @param model
|
||||
* @return
|
||||
*/
|
||||
@RequestMapping("/index")
|
||||
public ModelAndView index(Map<String, Object> model) {
|
||||
model.put("number", 1234);
|
||||
model.put("message", "Hello from Spring MVC");
|
||||
return new ModelAndView("/index");
|
||||
}
|
||||
|
||||
}
|
@ -1 +1,3 @@
|
||||
spring.main.allow-bean-definition-overriding=true
|
||||
spring.mvc.view.prefix=/WEB-INF/jsp/
|
||||
spring.mvc.view.suffix=.jsp
|
27
spring-boot-mvc/src/main/webapp/WEB-INF/jsp/index.jsp
Normal file
27
spring-boot-mvc/src/main/webapp/WEB-INF/jsp/index.jsp
Normal file
@ -0,0 +1,27 @@
|
||||
<!DOCTYPE html>
|
||||
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<title>Access Spring MVC params</title>
|
||||
<script src="/js/jquery.js"></script>
|
||||
<script src="/js/script-async.js"></script>
|
||||
<script src="/js/script-async-jquery.js"></script>
|
||||
<script>
|
||||
var number = <c:out value="${number}"></c:out>;
|
||||
var message = "<c:out value="${message}"></c:out>";
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
<h2>Data from the external JS file (due to loading order)</h2>
|
||||
<div id="number-ext"></div>
|
||||
<div id="message-ext"></div>
|
||||
<h2>Asynchronous loading from external JS file (plain JS)</h2>
|
||||
<div id="number-async"></div>
|
||||
<div id="message-async"></div>
|
||||
<h2>Asynchronous loading from external JS file (jQuery)</h2>
|
||||
<div id="number-async-jquery"></div>
|
||||
<div id="message-async-jquery"></div>
|
||||
|
||||
</body>
|
||||
<script src="/js/script.js"></script>
|
||||
</html>
|
2
spring-boot-mvc/src/main/webapp/js/jquery.js
vendored
Normal file
2
spring-boot-mvc/src/main/webapp/js/jquery.js
vendored
Normal file
File diff suppressed because one or more lines are too long
@ -0,0 +1,6 @@
|
||||
$(function() {
|
||||
var node1 = document.createTextNode("message = " + message);
|
||||
var node2 = document.createTextNode("number = " + number);
|
||||
document.getElementById('message-async-jquery').append(node1);
|
||||
document.getElementById('number-async-jquery').append(node2);
|
||||
});
|
6
spring-boot-mvc/src/main/webapp/js/script-async.js
Normal file
6
spring-boot-mvc/src/main/webapp/js/script-async.js
Normal file
@ -0,0 +1,6 @@
|
||||
window.onload = function() {
|
||||
var node1 = document.createTextNode("message = " + message);
|
||||
var node2 = document.createTextNode("number = " + number);
|
||||
document.getElementById('message-async').append(node1);
|
||||
document.getElementById('number-async').append(node2);
|
||||
};
|
4
spring-boot-mvc/src/main/webapp/js/script.js
Normal file
4
spring-boot-mvc/src/main/webapp/js/script.js
Normal file
@ -0,0 +1,4 @@
|
||||
var node1 = document.createTextNode("message = " + message);
|
||||
var node2 = document.createTextNode("number = " + number);
|
||||
document.getElementById('message-ext').append(node1);
|
||||
document.getElementById('number-ext').append(node2);
|
@ -0,0 +1,28 @@
|
||||
package com.baeldung.accessparamsjs;
|
||||
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
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.context.SpringBootTest;
|
||||
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;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest
|
||||
@AutoConfigureMockMvc
|
||||
public class ControllerUnitTest {
|
||||
@Autowired
|
||||
private MockMvc mvc;
|
||||
|
||||
@Test
|
||||
public void whenRequestIndex_thenStatusOk() throws Exception {
|
||||
mvc.perform(MockMvcRequestBuilders.get("/index")
|
||||
.accept(MediaType.APPLICATION_JSON))
|
||||
.andExpect(status().isOk());
|
||||
}
|
||||
}
|
@ -3,3 +3,4 @@ Module for the articles that are part of the Spring REST E-book:
|
||||
1. [Bootstrap a Web Application with Spring 5](https://www.baeldung.com/bootstraping-a-web-application-with-spring-and-java-based-configuration)
|
||||
2. [Error Handling for REST with Spring](http://www.baeldung.com/exception-handling-for-rest-with-spring)
|
||||
3. [REST Pagination in Spring](http://www.baeldung.com/rest-api-pagination-in-spring)
|
||||
4. [Build a REST API with Spring and Java Config](http://www.baeldung.com/building-a-restful-web-service-with-spring-and-java-based-configuration)
|
||||
|
@ -51,7 +51,6 @@
|
||||
<dependency>
|
||||
<groupId>net.sourceforge.htmlunit</groupId>
|
||||
<artifactId>htmlunit</artifactId>
|
||||
<version>${htmlunit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
@ -67,7 +66,6 @@
|
||||
|
||||
<properties>
|
||||
<start-class>com.baeldung.SpringBootRestApplication</start-class>
|
||||
<htmlunit.version>2.32</htmlunit.version>
|
||||
<guava.version>27.0.1-jre</guava.version>
|
||||
</properties>
|
||||
</project>
|
||||
|
@ -1,16 +1,29 @@
|
||||
package com.baeldung.persistence;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
|
||||
public interface IOperations<T extends Serializable> {
|
||||
|
||||
// read - one
|
||||
|
||||
T findOne(final long id);
|
||||
|
||||
// read - all
|
||||
|
||||
List<T> findAll();
|
||||
|
||||
Page<T> findPaginated(int page, int size);
|
||||
|
||||
// write
|
||||
|
||||
T create(final T entity);
|
||||
|
||||
T update(final T entity);
|
||||
|
||||
void delete(final T entity);
|
||||
|
||||
void deleteById(final long entityId);
|
||||
}
|
||||
|
@ -1,6 +1,7 @@
|
||||
package com.baeldung.persistence.service.common;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
@ -8,12 +9,28 @@ import org.springframework.data.repository.PagingAndSortingRepository;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.baeldung.persistence.IOperations;
|
||||
import com.google.common.collect.Lists;
|
||||
|
||||
@Transactional
|
||||
public abstract class AbstractService<T extends Serializable> implements IOperations<T> {
|
||||
|
||||
// read - one
|
||||
|
||||
@Override
|
||||
@Transactional(readOnly = true)
|
||||
public T findOne(final long id) {
|
||||
return getDao().findById(id)
|
||||
.get();
|
||||
}
|
||||
|
||||
// read - all
|
||||
|
||||
@Override
|
||||
@Transactional(readOnly = true)
|
||||
public List<T> findAll() {
|
||||
return Lists.newArrayList(getDao().findAll());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Page<T> findPaginated(final int page, final int size) {
|
||||
return getDao().findAll(PageRequest.of(page, size));
|
||||
@ -26,6 +43,21 @@ public abstract class AbstractService<T extends Serializable> implements IOperat
|
||||
return getDao().save(entity);
|
||||
}
|
||||
|
||||
@Override
|
||||
public T update(final T entity) {
|
||||
return getDao().save(entity);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(final T entity) {
|
||||
getDao().delete(entity);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deleteById(final long entityId) {
|
||||
getDao().deleteById(entityId);
|
||||
}
|
||||
|
||||
protected abstract PagingAndSortingRepository<T, Long> getDao();
|
||||
|
||||
}
|
||||
|
@ -1,5 +1,7 @@
|
||||
package com.baeldung.persistence.service.impl;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
@ -11,6 +13,7 @@ import com.baeldung.persistence.dao.IFooDao;
|
||||
import com.baeldung.persistence.model.Foo;
|
||||
import com.baeldung.persistence.service.IFooService;
|
||||
import com.baeldung.persistence.service.common.AbstractService;
|
||||
import com.google.common.collect.Lists;
|
||||
|
||||
@Service
|
||||
@Transactional
|
||||
@ -37,4 +40,12 @@ public class FooService extends AbstractService<Foo> implements IFooService {
|
||||
return dao.findAll(pageable);
|
||||
}
|
||||
|
||||
// overridden to be secured
|
||||
|
||||
@Override
|
||||
@Transactional(readOnly = true)
|
||||
public List<Foo> findAll() {
|
||||
return Lists.newArrayList(getDao().findAll());
|
||||
}
|
||||
|
||||
}
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user