Merge branch 'master' of https://github.com/eugenp/tutorials
This commit is contained in:
@@ -6,12 +6,12 @@ import java.util.function.Function;
|
||||
public class AdderImpl implements Adder {
|
||||
|
||||
@Override
|
||||
public String addWithFunction(Function<String, String> f) {
|
||||
public String addWithFunction(final Function<String, String> f) {
|
||||
return f.apply("Something ");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addWithConsumer(Consumer<Integer> f) {
|
||||
public void addWithConsumer(final Consumer<Integer> f) {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
package com.baeldung.doublecolon;
|
||||
|
||||
public class Computer {
|
||||
|
||||
private Integer age;
|
||||
private String color;
|
||||
private Integer healty;
|
||||
|
||||
public Computer(final int age, final String color) {
|
||||
this.age = age;
|
||||
this.color = color;
|
||||
}
|
||||
|
||||
public Computer(final Integer age, final String color, final Integer healty) {
|
||||
this.age = age;
|
||||
this.color = color;
|
||||
this.healty = healty;
|
||||
}
|
||||
|
||||
public Computer() {
|
||||
}
|
||||
|
||||
public Integer getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public void setAge(final Integer age) {
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public String getColor() {
|
||||
return color;
|
||||
}
|
||||
|
||||
public void setColor(final String color) {
|
||||
this.color = color;
|
||||
}
|
||||
|
||||
public Integer getHealty() {
|
||||
return healty;
|
||||
}
|
||||
|
||||
public void setHealty(final Integer healty) {
|
||||
this.healty = healty;
|
||||
}
|
||||
|
||||
public void turnOnPc() {
|
||||
System.out.println("Computer turned on");
|
||||
}
|
||||
|
||||
public void turnOffPc() {
|
||||
System.out.println("Computer turned off");
|
||||
}
|
||||
|
||||
public Double calculateValue(Double initialValue) {
|
||||
return initialValue / 1.50;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Computer{" + "age=" + age + ", color='" + color + '\'' + ", healty=" + healty + '}';
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(final Object o) {
|
||||
if (this == o) {
|
||||
return true;
|
||||
}
|
||||
if (o == null || getClass() != o.getClass()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
final Computer computer = (Computer) o;
|
||||
|
||||
if (age != null ? !age.equals(computer.age) : computer.age != null) {
|
||||
return false;
|
||||
}
|
||||
return color != null ? color.equals(computer.color) : computer.color == null;
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int result = age != null ? age.hashCode() : 0;
|
||||
result = 31 * result + (color != null ? color.hashCode() : 0);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.baeldung.doublecolon;
|
||||
|
||||
import com.baeldung.doublecolon.function.ComputerPredicate;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class ComputerUtils {
|
||||
|
||||
public static final ComputerPredicate after2010Predicate = (c) -> (c.getAge() > 2010);
|
||||
public static final ComputerPredicate blackPredicate = (c) -> "black".equals(c.getColor());
|
||||
|
||||
public static List<Computer> filter(final List<Computer> inventory, final ComputerPredicate p) {
|
||||
|
||||
final List<Computer> result = new ArrayList<>();
|
||||
inventory.stream().filter(p::filter).forEach(result::add);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public static void repair(final Computer computer) {
|
||||
if (computer.getHealty() < 50) {
|
||||
computer.setHealty(100);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.baeldung.doublecolon;
|
||||
|
||||
import java.util.function.Function;
|
||||
|
||||
public class MacbookPro extends Computer {
|
||||
|
||||
public MacbookPro(int age, String color) {
|
||||
super(age, color);
|
||||
}
|
||||
|
||||
public MacbookPro(Integer age, String color, Integer healty) {
|
||||
super(age, color, healty);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void turnOnPc() {
|
||||
System.out.println("MacbookPro turned on");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void turnOffPc() {
|
||||
System.out.println("MacbookPro turned off");
|
||||
}
|
||||
|
||||
@Override
|
||||
public Double calculateValue(Double initialValue) {
|
||||
|
||||
Function<Double, Double> function = super::calculateValue;
|
||||
final Double pcValue = function.apply(initialValue);
|
||||
System.out.println("First value is:" + pcValue);
|
||||
return pcValue + (initialValue / 10);
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.baeldung.doublecolon.function;
|
||||
|
||||
import com.baeldung.doublecolon.Computer;
|
||||
|
||||
@FunctionalInterface
|
||||
public interface ComputerPredicate {
|
||||
|
||||
boolean filter(Computer c);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.doublecolon.function;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.function.Function;
|
||||
|
||||
@FunctionalInterface
|
||||
public interface TriFunction<A, B, C, R> {
|
||||
|
||||
R apply(A a, B b, C c);
|
||||
|
||||
default <V> TriFunction<A, B, C, V> andThen(final Function<? super R, ? extends V> after) {
|
||||
Objects.requireNonNull(after);
|
||||
return (final A a, final B b, final C c) -> after.apply(apply(a, b, c));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package com.baeldung.doublecolon;
|
||||
|
||||
import com.baeldung.doublecolon.function.TriFunction;
|
||||
import org.junit.After;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.function.BiFunction;
|
||||
|
||||
import static com.baeldung.doublecolon.ComputerUtils.*;
|
||||
|
||||
public class TestComputerUtils {
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testConstructorReference() {
|
||||
|
||||
Computer c1 = new Computer(2015, "white");
|
||||
Computer c2 = new Computer(2009, "black");
|
||||
Computer c3 = new Computer(2014, "black");
|
||||
|
||||
BiFunction<Integer, String, Computer> c4Function = Computer::new;
|
||||
Computer c4 = c4Function.apply(2013, "white");
|
||||
BiFunction<Integer, String, Computer> c5Function = Computer::new;
|
||||
Computer c5 = c5Function.apply(2010, "black");
|
||||
BiFunction<Integer, String, Computer> c6Function = Computer::new;
|
||||
Computer c6 = c6Function.apply(2008, "black");
|
||||
|
||||
List<Computer> inventory = Arrays.asList(c1, c2, c3, c4, c5, c6);
|
||||
|
||||
List<Computer> blackComputer = filter(inventory, blackPredicate);
|
||||
Assert.assertEquals("The black Computers are: ", blackComputer.size(), 4);
|
||||
|
||||
List<Computer> after2010Computer = filter(inventory, after2010Predicate);
|
||||
Assert.assertEquals("The Computer bought after 2010 are: ", after2010Computer.size(), 3);
|
||||
|
||||
List<Computer> before2011Computer = filter(inventory, c -> c.getAge() < 2011);
|
||||
Assert.assertEquals("The Computer bought before 2011 are: ", before2011Computer.size(), 3);
|
||||
|
||||
inventory.sort(Comparator.comparing(Computer::getAge));
|
||||
|
||||
Assert.assertEquals("Oldest Computer in inventory", c6, inventory.get(0));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testStaticMethodReference() {
|
||||
|
||||
Computer c1 = new Computer(2015, "white", 35);
|
||||
Computer c2 = new Computer(2009, "black", 65);
|
||||
TriFunction<Integer, String, Integer, Computer> c6Function = Computer::new;
|
||||
Computer c3 = c6Function.apply(2008, "black", 90);
|
||||
|
||||
List<Computer> inventory = Arrays.asList(c1, c2, c3);
|
||||
inventory.forEach(ComputerUtils::repair);
|
||||
|
||||
Assert.assertEquals("Computer repaired", new Integer(100), c1.getHealty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testInstanceMethodArbitraryObjectParticularType() {
|
||||
|
||||
Computer c1 = new Computer(2015, "white", 35);
|
||||
Computer c2 = new MacbookPro(2009, "black", 65);
|
||||
List<Computer> inventory = Arrays.asList(c1, c2);
|
||||
inventory.forEach(Computer::turnOnPc);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSuperMethodReference() {
|
||||
|
||||
final TriFunction<Integer, String, Integer, MacbookPro> integerStringIntegerObjectTriFunction = MacbookPro::new;
|
||||
final MacbookPro macbookPro = integerStringIntegerObjectTriFunction.apply(2010, "black", 100);
|
||||
Double initialValue = new Double(999.99);
|
||||
final Double actualValue = macbookPro.calculateValue(initialValue);
|
||||
Assert.assertEquals(766.659, actualValue, 0.0);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -30,6 +30,14 @@ public class Java8CollectionCleanupUnitTest {
|
||||
assertThat(listWithoutNulls, hasSize(3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListContainsNulls_whenRemovingNullsWithRemoveIf_thenCorrect() {
|
||||
final List<Integer> listWithoutNulls = Lists.newArrayList(null, 1, 2, null, 3, null);
|
||||
listWithoutNulls.removeIf(p -> p == null);
|
||||
|
||||
assertThat(listWithoutNulls, hasSize(3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListContainsDuplicates_whenRemovingDuplicatesWithJava8_thenCorrect() {
|
||||
final List<Integer> listWithDuplicates = Lists.newArrayList(1, 1, 2, 2, 3, 3);
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
package org.baeldung.java;
|
||||
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
|
||||
public class CollectionJavaPartitionUnitTest {
|
||||
|
||||
// java8 groupBy
|
||||
@Test
|
||||
public final void givenList_whenParitioningIntoNSublistsUsingGroupingBy_thenCorrect() {
|
||||
final List<Integer> intList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8);
|
||||
|
||||
final Map<Integer, List<Integer>> groups = intList.stream().collect(Collectors.groupingBy(s -> (s - 1) / 3));
|
||||
final List<List<Integer>> subSets = new ArrayList<List<Integer>>(groups.values());
|
||||
|
||||
// When
|
||||
final List<Integer> lastPartition = subSets.get(2);
|
||||
final List<Integer> expectedLastPartition = Lists.<Integer> newArrayList(7, 8);
|
||||
assertThat(subSets.size(), equalTo(3));
|
||||
assertThat(lastPartition, equalTo(expectedLastPartition));
|
||||
|
||||
// intList.add(9);
|
||||
// System.out.println(groups.values());
|
||||
}
|
||||
|
||||
// java8 partitionBy
|
||||
@Test
|
||||
public final void givenList_whenParitioningIntoSublistsUsingPartitionBy_thenCorrect() {
|
||||
final List<Integer> intList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8);
|
||||
|
||||
final Map<Boolean, List<Integer>> groups = intList.stream().collect(Collectors.partitioningBy(s -> s > 6));
|
||||
final List<List<Integer>> subSets = new ArrayList<List<Integer>>(groups.values());
|
||||
|
||||
// When
|
||||
final List<Integer> lastPartition = subSets.get(1);
|
||||
final List<Integer> expectedLastPartition = Lists.<Integer> newArrayList(7, 8);
|
||||
assertThat(subSets.size(), equalTo(2));
|
||||
assertThat(lastPartition, equalTo(expectedLastPartition));
|
||||
|
||||
// intList.add(9);
|
||||
// System.out.println(groups.values());
|
||||
}
|
||||
|
||||
// java8 split by separator
|
||||
@Test
|
||||
public final void givenList_whenSplittingBySeparator_thenCorrect() {
|
||||
final List<Integer> intList = Lists.newArrayList(1, 2, 3, 0, 4, 5, 6, 0, 7, 8);
|
||||
|
||||
final int[] indexes = Stream.of(IntStream.of(-1), IntStream.range(0, intList.size()).filter(i -> intList.get(i) == 0), IntStream.of(intList.size())).flatMapToInt(s -> s).toArray();
|
||||
final List<List<Integer>> subSets = IntStream.range(0, indexes.length - 1).mapToObj(i -> intList.subList(indexes[i] + 1, indexes[i + 1])).collect(Collectors.toList());
|
||||
|
||||
// When
|
||||
final List<Integer> lastPartition = subSets.get(2);
|
||||
final List<Integer> expectedLastPartition = Lists.<Integer> newArrayList(7, 8);
|
||||
assertThat(subSets.size(), equalTo(3));
|
||||
assertThat(lastPartition, equalTo(expectedLastPartition));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"name":
|
||||
{
|
||||
"first": "Tatu",
|
||||
"last": "Saloranta"
|
||||
},
|
||||
|
||||
"title": "Jackson founder",
|
||||
"company": "FasterXML"
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package org.baeldung.jackson.node;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
public class ExampleStructure {
|
||||
private static ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
static JsonNode getExampleRoot() throws IOException {
|
||||
InputStream exampleInput = ExampleStructure.class.getClassLoader().getResourceAsStream("node_example.json");
|
||||
JsonNode rootNode = mapper.readTree(exampleInput);
|
||||
return rootNode;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package org.baeldung.jackson.node;
|
||||
|
||||
public class NodeBean {
|
||||
private int id;
|
||||
private String name;
|
||||
|
||||
public NodeBean() {
|
||||
}
|
||||
|
||||
public NodeBean(int id, String name) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package org.baeldung.jackson.node;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.containsString;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.io.FileReader;
|
||||
import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
|
||||
public class NodeOperationTest {
|
||||
private static ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
@Test
|
||||
public void givenAnObject_whenConvertingIntoNode_thenCorrect() {
|
||||
final NodeBean fromValue = new NodeBean(2016, "baeldung.com");
|
||||
|
||||
final JsonNode node = mapper.valueToTree(fromValue);
|
||||
|
||||
assertEquals(2016, node.get("id").intValue());
|
||||
assertEquals("baeldung.com", node.get("name").textValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenANode_whenWritingOutAsAJsonString_thenCorrect() throws IOException {
|
||||
final String pathToTestFile = "node_to_json_test.json";
|
||||
final char[] characterBuffer = new char[50];
|
||||
|
||||
final JsonNode node = mapper.createObjectNode();
|
||||
((ObjectNode) node).put("id", 2016);
|
||||
((ObjectNode) node).put("name", "baeldung.com");
|
||||
|
||||
try (FileWriter outputStream = new FileWriter(pathToTestFile)) {
|
||||
mapper.writeValue(outputStream, node);
|
||||
}
|
||||
|
||||
try (FileReader inputStreamForAssertion = new FileReader(pathToTestFile)) {
|
||||
inputStreamForAssertion.read(characterBuffer);
|
||||
}
|
||||
final String textContentOfTestFile = new String(characterBuffer);
|
||||
|
||||
assertThat(textContentOfTestFile, containsString("2016"));
|
||||
assertThat(textContentOfTestFile, containsString("baeldung.com"));
|
||||
|
||||
Files.delete(Paths.get(pathToTestFile));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenANode_whenConvertingIntoAnObject_thenCorrect() throws JsonProcessingException {
|
||||
final JsonNode node = mapper.createObjectNode();
|
||||
((ObjectNode) node).put("id", 2016);
|
||||
((ObjectNode) node).put("name", "baeldung.com");
|
||||
|
||||
final NodeBean toValue = mapper.treeToValue(node, NodeBean.class);
|
||||
|
||||
assertEquals(2016, toValue.getId());
|
||||
assertEquals("baeldung.com", toValue.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenANode_whenAddingIntoATree_thenCorrect() throws IOException {
|
||||
final JsonNode rootNode = ExampleStructure.getExampleRoot();
|
||||
final ObjectNode addedNode = ((ObjectNode) rootNode).putObject("address");
|
||||
addedNode.put("city", "Seattle").put("state", "Washington").put("country", "United States");
|
||||
|
||||
assertFalse(rootNode.path("address").isMissingNode());
|
||||
assertEquals("Seattle", rootNode.path("address").path("city").textValue());
|
||||
assertEquals("Washington", rootNode.path("address").path("state").textValue());
|
||||
assertEquals("United States", rootNode.path("address").path("country").textValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenANode_whenModifyingIt_thenCorrect() throws IOException {
|
||||
final String newString = "{\"nick\": \"cowtowncoder\"}";
|
||||
final JsonNode newNode = mapper.readTree(newString);
|
||||
|
||||
final JsonNode rootNode = ExampleStructure.getExampleRoot();
|
||||
((ObjectNode) rootNode).set("name", newNode);
|
||||
|
||||
assertFalse(rootNode.path("name").path("nick").isMissingNode());
|
||||
assertEquals("cowtowncoder", rootNode.path("name").path("nick").textValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenANode_whenRemovingFromATree_thenCorrect() throws IOException {
|
||||
final JsonNode rootNode = ExampleStructure.getExampleRoot();
|
||||
((ObjectNode) rootNode).remove("company");
|
||||
|
||||
assertTrue(rootNode.path("company").isMissingNode());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
*.class
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
@@ -0,0 +1,54 @@
|
||||
<?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>mockito-mocks-spring-beans</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<name>mocks</name>
|
||||
<description>Injecting Mockito Mocks into Spring Beans</description>
|
||||
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>1.3.1.RELEASE</version>
|
||||
<relativePath/> <!-- lookup parent from repository -->
|
||||
</parent>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<java.version>1.8</java.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter</artifactId>
|
||||
<version>1.3.1.RELEASE</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<version>1.3.1.RELEASE</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.mockito</groupId>
|
||||
<artifactId>mockito-all</artifactId>
|
||||
<version>1.10.19</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.baeldung;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class MocksApplication {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(MocksApplication.class, args);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.baeldung;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class NameService {
|
||||
public String getUserName(String id) {
|
||||
return "Real user name";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.baeldung;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class UserService {
|
||||
|
||||
private NameService nameService;
|
||||
|
||||
@Autowired
|
||||
public UserService(NameService nameService) {
|
||||
this.nameService = nameService;
|
||||
}
|
||||
|
||||
public String getUserName(String id) {
|
||||
return nameService.getUserName(id);
|
||||
}
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package com.baeldung;
|
||||
|
||||
import org.mockito.Mockito;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Primary;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
|
||||
@Profile("test")
|
||||
@Configuration
|
||||
public class NameServiceTestConfiguration {
|
||||
@Bean
|
||||
@Primary
|
||||
public NameService nameService() {
|
||||
return Mockito.mock(NameService.class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.baeldung;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mockito;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.SpringApplicationConfiguration;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
|
||||
@ActiveProfiles("test")
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@SpringApplicationConfiguration(classes = MocksApplication.class)
|
||||
public class UserServiceTest {
|
||||
|
||||
@Autowired
|
||||
private UserService userService;
|
||||
|
||||
@Autowired
|
||||
private NameService nameService;
|
||||
|
||||
@Test
|
||||
public void whenUserIdIsProvided_thenRetrievedNameIsCorrect() {
|
||||
Mockito.when(nameService.getUserName("SomeId")).thenReturn("Mock user name");
|
||||
|
||||
String testName = userService.getUserName("SomeId");
|
||||
|
||||
Assert.assertEquals("Mock user name", testName);
|
||||
}
|
||||
}
|
||||
@@ -10,5 +10,5 @@ import java.lang.annotation.Target;
|
||||
@Target({ ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD })
|
||||
@Documented
|
||||
public @interface DataAccess {
|
||||
Class<?>entity();
|
||||
Class<?> entity();
|
||||
}
|
||||
|
||||
+2
-4
@@ -19,15 +19,13 @@ public class DataAccessAnnotationProcessor implements BeanPostProcessor {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object postProcessBeforeInitialization(Object bean, String beanName)
|
||||
throws BeansException {
|
||||
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
|
||||
scanDataAccessAnnotation(bean, beanName);
|
||||
return bean;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object postProcessAfterInitialization(Object bean, String beanName)
|
||||
throws BeansException {
|
||||
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
|
||||
return bean;
|
||||
}
|
||||
|
||||
|
||||
+7
-15
@@ -12,18 +12,14 @@ import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
|
||||
import org.springframework.util.ReflectionUtils;
|
||||
import org.springframework.util.ReflectionUtils.FieldCallback;
|
||||
|
||||
|
||||
public final class DataAccessFieldCallback implements FieldCallback {
|
||||
|
||||
private static Logger logger = LoggerFactory.getLogger(DataAccessFieldCallback.class);
|
||||
private static int AUTOWIRE_MODE = AutowireCapableBeanFactory.AUTOWIRE_BY_NAME;
|
||||
|
||||
private static String ERROR_ENTITY_VALUE_NOT_SAME = "@DataAccess(entity) "
|
||||
+ "value should have same type with injected generic type.";
|
||||
private static String WARN_NON_GENERIC_VALUE = "@DataAccess annotation assigned "
|
||||
+ "to raw (non-generic) declaration. This will make your code less type-safe.";
|
||||
private static String ERROR_CREATE_INSTANCE = "Cannot create instance of "
|
||||
+ "type '{}' or instance creation is failed because: {}";
|
||||
private static String ERROR_ENTITY_VALUE_NOT_SAME = "@DataAccess(entity) " + "value should have same type with injected generic type.";
|
||||
private static String WARN_NON_GENERIC_VALUE = "@DataAccess annotation assigned " + "to raw (non-generic) declaration. This will make your code less type-safe.";
|
||||
private static String ERROR_CREATE_INSTANCE = "Cannot create instance of " + "type '{}' or instance creation is failed because: {}";
|
||||
|
||||
private ConfigurableListableBeanFactory configurableListableBeanFactory;
|
||||
private Object bean;
|
||||
@@ -34,15 +30,14 @@ public final class DataAccessFieldCallback implements FieldCallback {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void doWith(final Field field)
|
||||
throws IllegalArgumentException, IllegalAccessException {
|
||||
public void doWith(final Field field) throws IllegalArgumentException, IllegalAccessException {
|
||||
if (!field.isAnnotationPresent(DataAccess.class)) {
|
||||
return;
|
||||
}
|
||||
ReflectionUtils.makeAccessible(field);
|
||||
final Type fieldGenericType = field.getGenericType();
|
||||
// In this example, get actual "GenericDAO' type.
|
||||
final Class<?> generic = field.getType();
|
||||
// In this example, get actual "GenericDAO' type.
|
||||
final Class<?> generic = field.getType();
|
||||
final Class<?> classValue = field.getDeclaredAnnotation(DataAccess.class).entity();
|
||||
|
||||
if (genericTypeIsValid(classValue, fieldGenericType)) {
|
||||
@@ -54,7 +49,6 @@ public final class DataAccessFieldCallback implements FieldCallback {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* For example, if user write:
|
||||
* <pre>
|
||||
@@ -75,8 +69,6 @@ public final class DataAccessFieldCallback implements FieldCallback {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
public final Object getBeanInstance(final String beanName, final Class<?> genericClass, final Class<?> paramClass) {
|
||||
Object daoInstance = null;
|
||||
if (!configurableListableBeanFactory.containsBean(beanName)) {
|
||||
@@ -90,7 +82,7 @@ public final class DataAccessFieldCallback implements FieldCallback {
|
||||
logger.error(ERROR_CREATE_INSTANCE, genericClass.getTypeName(), e);
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
|
||||
daoInstance = configurableListableBeanFactory.initializeBean(toRegister, beanName);
|
||||
configurableListableBeanFactory.autowireBeanProperties(daoInstance, AUTOWIRE_MODE, true);
|
||||
configurableListableBeanFactory.registerSingleton(beanName, daoInstance);
|
||||
|
||||
@@ -5,10 +5,11 @@ import org.springframework.stereotype.Repository;
|
||||
@Repository
|
||||
public class BeanWithGenericDAO {
|
||||
|
||||
@DataAccess(entity=Person.class)
|
||||
@DataAccess(entity = Person.class)
|
||||
private GenericDAO<Person> personGenericDAO;
|
||||
|
||||
public BeanWithGenericDAO() {}
|
||||
public BeanWithGenericDAO() {
|
||||
}
|
||||
|
||||
public GenericDAO<Person> getPersonGenericDAO() {
|
||||
return personGenericDAO;
|
||||
|
||||
+1
-3
@@ -15,7 +15,6 @@ import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = { CustomAnnotationConfiguration.class })
|
||||
public class DataAccessFieldCallbackTest {
|
||||
@@ -36,8 +35,7 @@ public class DataAccessFieldCallbackTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenMethodGenericTypeIsValidCalled_thenReturnCorrectValue()
|
||||
throws NoSuchFieldException, SecurityException {
|
||||
public void whenMethodGenericTypeIsValidCalled_thenReturnCorrectValue() throws NoSuchFieldException, SecurityException {
|
||||
final DataAccessFieldCallback callback = new DataAccessFieldCallback(configurableListableBeanFactory, beanWithGenericDAO);
|
||||
final Type fieldType = BeanWithGenericDAO.class.getDeclaredField("personGenericDAO").getGenericType();
|
||||
final boolean result = callback.genericTypeIsValid(Person.class, fieldType);
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
|
||||
@@ -40,8 +40,7 @@ public class SpringBatchConfig {
|
||||
private Resource outputXml;
|
||||
|
||||
@Bean
|
||||
public ItemReader<Transaction> itemReader()
|
||||
throws UnexpectedInputException, ParseException {
|
||||
public ItemReader<Transaction> itemReader() throws UnexpectedInputException, ParseException {
|
||||
FlatFileItemReader<Transaction> reader = new FlatFileItemReader<Transaction>();
|
||||
DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer();
|
||||
String[] tokens = { "username", "userid", "transactiondate", "amount" };
|
||||
@@ -61,8 +60,7 @@ public class SpringBatchConfig {
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ItemWriter<Transaction> itemWriter(Marshaller marshaller)
|
||||
throws MalformedURLException {
|
||||
public ItemWriter<Transaction> itemWriter(Marshaller marshaller) throws MalformedURLException {
|
||||
StaxEventItemWriter<Transaction> itemWriter = new StaxEventItemWriter<Transaction>();
|
||||
itemWriter.setMarshaller(marshaller);
|
||||
itemWriter.setRootTagName("transactionRecord");
|
||||
@@ -78,11 +76,8 @@ public class SpringBatchConfig {
|
||||
}
|
||||
|
||||
@Bean
|
||||
protected Step step1(ItemReader<Transaction> reader,
|
||||
ItemProcessor<Transaction, Transaction> processor,
|
||||
ItemWriter<Transaction> writer) {
|
||||
return steps.get("step1").<Transaction, Transaction> chunk(10)
|
||||
.reader(reader).processor(processor).writer(writer).build();
|
||||
protected Step step1(ItemReader<Transaction> reader, ItemProcessor<Transaction, Transaction> processor, ItemWriter<Transaction> writer) {
|
||||
return steps.get("step1").<Transaction, Transaction> chunk(10).reader(reader).processor(processor).writer(writer).build();
|
||||
}
|
||||
|
||||
@Bean(name = "firstBatchJob")
|
||||
|
||||
@@ -38,8 +38,7 @@ public class SpringConfig {
|
||||
}
|
||||
|
||||
@Bean
|
||||
public DataSourceInitializer dataSourceInitializer(DataSource dataSource)
|
||||
throws MalformedURLException {
|
||||
public DataSourceInitializer dataSourceInitializer(DataSource dataSource) throws MalformedURLException {
|
||||
ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator();
|
||||
|
||||
databasePopulator.addScript(dropReopsitoryTables);
|
||||
|
||||
@@ -48,9 +48,7 @@ public class Transaction {
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Transaction [username=" + username + ", userId=" + userId
|
||||
+ ", transactionDate=" + transactionDate + ", amount=" + amount
|
||||
+ "]";
|
||||
return "Transaction [username=" + username + ", userId=" + userId + ", transactionDate=" + transactionDate + ", amount=" + amount + "]";
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user