Merge branch 'master' into wiremock_intro
This commit is contained in:
commit
a6e31c6947
|
@ -0,0 +1,91 @@
|
|||
package com.baeldung.enums;
|
||||
|
||||
import java.util.EnumMap;
|
||||
import java.util.EnumSet;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class Pizza {
|
||||
|
||||
private static EnumSet<PizzaStatusEnum> deliveredPizzaStatuses =
|
||||
EnumSet.of(PizzaStatusEnum.DELIVERED);
|
||||
|
||||
private PizzaStatusEnum status;
|
||||
|
||||
public enum PizzaStatusEnum {
|
||||
ORDERED(5) {
|
||||
@Override
|
||||
public boolean isOrdered() {
|
||||
return true;
|
||||
}
|
||||
},
|
||||
READY(2) {
|
||||
@Override
|
||||
public boolean isReady() {
|
||||
return true;
|
||||
}
|
||||
},
|
||||
DELIVERED(0) {
|
||||
@Override
|
||||
public boolean isDelivered() {
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
private int timeToDelivery;
|
||||
|
||||
public boolean isOrdered() {
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean isReady() {
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean isDelivered() {
|
||||
return false;
|
||||
}
|
||||
|
||||
public int getTimeToDelivery() {
|
||||
return timeToDelivery;
|
||||
}
|
||||
|
||||
PizzaStatusEnum(int timeToDelivery) {
|
||||
this.timeToDelivery = timeToDelivery;
|
||||
}
|
||||
}
|
||||
|
||||
public PizzaStatusEnum getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(PizzaStatusEnum status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public boolean isDeliverable() {
|
||||
return this.status.isReady();
|
||||
}
|
||||
|
||||
public void printTimeToDeliver() {
|
||||
System.out.println("Time to delivery is " + this.getStatus().getTimeToDelivery() + " days");
|
||||
}
|
||||
|
||||
public static List<Pizza> getAllUndeliveredPizzas(List<Pizza> input) {
|
||||
return input.stream().filter((s) -> !deliveredPizzaStatuses.contains(s.getStatus())).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public static EnumMap<PizzaStatusEnum, List<Pizza>> groupPizzaByStatus(List<Pizza> pzList) {
|
||||
return pzList.stream().collect(
|
||||
Collectors.groupingBy(Pizza::getStatus,
|
||||
() -> new EnumMap<>(PizzaStatusEnum.class), Collectors.toList()));
|
||||
}
|
||||
|
||||
public void deliver() {
|
||||
if (isDeliverable()) {
|
||||
PizzaDeliverySystemConfiguration.getInstance().getDeliveryStrategy().deliver(this);
|
||||
this.setStatus(PizzaStatusEnum.DELIVERED);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
package com.baeldung.enums;
|
||||
|
||||
public enum PizzaDeliveryStrategy {
|
||||
EXPRESS {
|
||||
@Override
|
||||
public void deliver(Pizza pz) {
|
||||
System.out.println("Pizza will be delivered in express mode");
|
||||
}
|
||||
},
|
||||
NORMAL {
|
||||
@Override
|
||||
public void deliver(Pizza pz) {
|
||||
System.out.println("Pizza will be delivered in normal mode");
|
||||
}
|
||||
};
|
||||
|
||||
public abstract void deliver(Pizza pz);
|
||||
}
|
|
@ -0,0 +1,22 @@
|
|||
package com.baeldung.enums;
|
||||
|
||||
|
||||
public enum PizzaDeliverySystemConfiguration {
|
||||
INSTANCE;
|
||||
|
||||
PizzaDeliverySystemConfiguration() {
|
||||
// Do the configuration initialization which
|
||||
// involves overriding defaults like delivery strategy
|
||||
}
|
||||
|
||||
private PizzaDeliveryStrategy deliveryStrategy = PizzaDeliveryStrategy.NORMAL;
|
||||
|
||||
public static PizzaDeliverySystemConfiguration getInstance() {
|
||||
return INSTANCE;
|
||||
}
|
||||
|
||||
public PizzaDeliveryStrategy getDeliveryStrategy() {
|
||||
return deliveryStrategy;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
package com.baeldung.java_8_features;
|
||||
|
||||
public class Address {
|
||||
|
||||
private String street;
|
||||
|
||||
public String getStreet() {
|
||||
return street;
|
||||
}
|
||||
|
||||
public void setStreet(String street) {
|
||||
this.street = street;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,4 @@
|
|||
package com.baeldung.java_8_features;
|
||||
|
||||
public class CustomException extends RuntimeException {
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
package com.baeldung.java_8_features;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
public class Detail {
|
||||
|
||||
private static final List<String> PARTS = Arrays.asList("turbine", "pump");
|
||||
|
||||
public List<String> getParts() {
|
||||
return PARTS;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,16 @@
|
|||
package com.baeldung.java_8_features;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public class OptionalAddress {
|
||||
|
||||
private String street;
|
||||
|
||||
public Optional<String> getStreet() {
|
||||
return Optional.ofNullable(street);
|
||||
}
|
||||
|
||||
public void setStreet(String street) {
|
||||
this.street = street;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,16 @@
|
|||
package com.baeldung.java_8_features;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public class OptionalUser {
|
||||
|
||||
private OptionalAddress address;
|
||||
|
||||
public Optional<OptionalAddress> getAddress() {
|
||||
return Optional.of(address);
|
||||
}
|
||||
|
||||
public void setAddress(OptionalAddress address) {
|
||||
this.address = address;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,40 @@
|
|||
package com.baeldung.java_8_features;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public class User {
|
||||
|
||||
private String name;
|
||||
|
||||
private Address address;
|
||||
|
||||
public Address getAddress() {
|
||||
return address;
|
||||
}
|
||||
|
||||
public void setAddress(Address address) {
|
||||
this.address = address;
|
||||
}
|
||||
|
||||
public User() {
|
||||
}
|
||||
|
||||
public User(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public static boolean isRealUser(User user) {
|
||||
return true;
|
||||
}
|
||||
|
||||
public String getOrThrow() {
|
||||
String value = null;
|
||||
Optional<String> valueOpt = Optional.ofNullable(value);
|
||||
String result = valueOpt.orElseThrow(CustomException::new).toUpperCase();
|
||||
return result;
|
||||
}
|
||||
|
||||
public boolean isLegalName(String name) {
|
||||
return name.length() > 3 && name.length() < 16;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
package com.baeldung.java_8_features;
|
||||
|
||||
public interface Vehicle {
|
||||
|
||||
void moveTo(long altitude, long longitude);
|
||||
|
||||
static String producer() {
|
||||
return "N&F Vehicles";
|
||||
}
|
||||
|
||||
default long[] startPosition() {
|
||||
return new long[]{23, 15};
|
||||
}
|
||||
|
||||
default String getOverview() {
|
||||
return "ATV made by " + producer();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
package com.baeldung.java_8_features;
|
||||
|
||||
public class VehicleImpl implements Vehicle {
|
||||
|
||||
@Override
|
||||
public void moveTo(long altitude, long longitude) {
|
||||
//do nothing
|
||||
}
|
||||
}
|
|
@ -0,0 +1,80 @@
|
|||
package com.baeldung.enums;
|
||||
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.EnumMap;
|
||||
import java.util.List;
|
||||
|
||||
import static junit.framework.TestCase.assertTrue;
|
||||
|
||||
public class PizzaTest {
|
||||
|
||||
@Test
|
||||
public void givenPizaOrder_whenReady_thenDeliverable() {
|
||||
Pizza testPz = new Pizza();
|
||||
testPz.setStatus(Pizza.PizzaStatusEnum.READY);
|
||||
assertTrue(testPz.isDeliverable());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPizaOrders_whenRetrievingUnDeliveredPzs_thenCorrectlyRetrieved() {
|
||||
List<Pizza> pzList = new ArrayList<>();
|
||||
Pizza pz1 = new Pizza();
|
||||
pz1.setStatus(Pizza.PizzaStatusEnum.DELIVERED);
|
||||
|
||||
Pizza pz2 = new Pizza();
|
||||
pz2.setStatus(Pizza.PizzaStatusEnum.ORDERED);
|
||||
|
||||
Pizza pz3 = new Pizza();
|
||||
pz3.setStatus(Pizza.PizzaStatusEnum.ORDERED);
|
||||
|
||||
Pizza pz4 = new Pizza();
|
||||
pz4.setStatus(Pizza.PizzaStatusEnum.READY);
|
||||
|
||||
pzList.add(pz1);
|
||||
pzList.add(pz2);
|
||||
pzList.add(pz3);
|
||||
pzList.add(pz4);
|
||||
|
||||
List<Pizza> undeliveredPzs = Pizza.getAllUndeliveredPizzas(pzList);
|
||||
assertTrue(undeliveredPzs.size() == 3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPizaOrders_whenGroupByStatusCalled_thenCorrectlyGrouped() {
|
||||
|
||||
List<Pizza> pzList = new ArrayList<>();
|
||||
Pizza pz1 = new Pizza();
|
||||
pz1.setStatus(Pizza.PizzaStatusEnum.DELIVERED);
|
||||
|
||||
Pizza pz2 = new Pizza();
|
||||
pz2.setStatus(Pizza.PizzaStatusEnum.ORDERED);
|
||||
|
||||
Pizza pz3 = new Pizza();
|
||||
pz3.setStatus(Pizza.PizzaStatusEnum.ORDERED);
|
||||
|
||||
Pizza pz4 = new Pizza();
|
||||
pz4.setStatus(Pizza.PizzaStatusEnum.READY);
|
||||
|
||||
pzList.add(pz1);
|
||||
pzList.add(pz2);
|
||||
pzList.add(pz3);
|
||||
pzList.add(pz4);
|
||||
|
||||
EnumMap<Pizza.PizzaStatusEnum, List<Pizza>> map = Pizza.groupPizzaByStatus(pzList);
|
||||
assertTrue(map.get(Pizza.PizzaStatusEnum.DELIVERED).size() == 1);
|
||||
assertTrue(map.get(Pizza.PizzaStatusEnum.ORDERED).size() == 2);
|
||||
assertTrue(map.get(Pizza.PizzaStatusEnum.READY).size() == 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPizaOrder_whenDelivered_thenPizzaGetsDeliveredAndStatusChanges() {
|
||||
Pizza pz = new Pizza();
|
||||
pz.setStatus(Pizza.PizzaStatusEnum.READY);
|
||||
pz.deliver();
|
||||
assertTrue(pz.getStatus() == Pizza.PizzaStatusEnum.DELIVERED);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,27 @@
|
|||
package com.baeldung.java8;
|
||||
|
||||
import com.baeldung.java_8_features.Vehicle;
|
||||
import com.baeldung.java_8_features.VehicleImpl;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class Java8DefaultStaticIntefaceMethodsTest {
|
||||
|
||||
@Test
|
||||
public void callStaticInterfaceMethdosMethods_whenExpectedResults_thenCorrect() {
|
||||
Vehicle vehicle = new VehicleImpl();
|
||||
String overview = vehicle.getOverview();
|
||||
long[] startPosition = vehicle.startPosition();
|
||||
|
||||
assertEquals(overview, "ATV made by N&F Vehicles");
|
||||
assertEquals(startPosition[0], 23);
|
||||
assertEquals(startPosition[1], 15);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void callDefaultInterfaceMethods_whenExpectedResults_thenCorrect() {
|
||||
String producer = Vehicle.producer();
|
||||
assertEquals(producer, "N&F Vehicles");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,67 @@
|
|||
package com.baeldung.java8;
|
||||
|
||||
import com.baeldung.java_8_features.User;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class Java8MethodReferenceTest {
|
||||
|
||||
private List<String> list;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
list = new ArrayList<>();
|
||||
list.add("One");
|
||||
list.add("OneAndOnly");
|
||||
list.add("Derek");
|
||||
list.add("Change");
|
||||
list.add("factory");
|
||||
list.add("justBefore");
|
||||
list.add("Italy");
|
||||
list.add("Italy");
|
||||
list.add("Thursday");
|
||||
list.add("");
|
||||
list.add("");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkStaticMethodReferences_whenWork_thenCorrect() {
|
||||
|
||||
List<User> users = new ArrayList<>();
|
||||
users.add(new User());
|
||||
users.add(new User());
|
||||
boolean isReal = users.stream().anyMatch(u -> User.isRealUser(u));
|
||||
boolean isRealRef = users.stream().anyMatch(User::isRealUser);
|
||||
assertTrue(isReal);
|
||||
assertTrue(isRealRef);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkInstanceMethodReferences_whenWork_thenCorrect() {
|
||||
User user = new User();
|
||||
boolean isLegalName = list.stream().anyMatch(user::isLegalName);
|
||||
assertTrue(isLegalName);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkParticularTypeReferences_whenWork_thenCorrect() {
|
||||
long count = list.stream().filter(String::isEmpty).count();
|
||||
assertEquals(count, 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkConstructorReferences_whenWork_thenCorrect() {
|
||||
Stream<User> stream = list.stream().map(User::new);
|
||||
List<User> userList = stream.collect(Collectors.toList());
|
||||
assertEquals(userList.size(), list.size());
|
||||
assertTrue(userList.get(0) instanceof User);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,118 @@
|
|||
package com.baeldung.java8;
|
||||
|
||||
import com.baeldung.java_8_features.*;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class Java8OptionalTest {
|
||||
|
||||
private List<String> list;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
list = new ArrayList<>();
|
||||
list.add("One");
|
||||
list.add("OneAndOnly");
|
||||
list.add("Derek");
|
||||
list.add("Change");
|
||||
list.add("factory");
|
||||
list.add("justBefore");
|
||||
list.add("Italy");
|
||||
list.add("Italy");
|
||||
list.add("Thursday");
|
||||
list.add("");
|
||||
list.add("");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkOptional_whenAsExpected_thenCorrect() {
|
||||
|
||||
Optional<String> optionalEmpty = Optional.empty();
|
||||
assertFalse(optionalEmpty.isPresent());
|
||||
|
||||
String str = "value";
|
||||
Optional<String> optional = Optional.of(str);
|
||||
assertEquals(optional.get(), "value");
|
||||
|
||||
Optional<String> optionalNullable = Optional.ofNullable(str);
|
||||
Optional<String> optionalNull = Optional.ofNullable(null);
|
||||
assertEquals(optionalNullable.get(), "value");
|
||||
assertFalse(optionalNull.isPresent());
|
||||
|
||||
List<String> listOpt = Optional.of(list).orElse(new ArrayList<>());
|
||||
List<String> listNull = null;
|
||||
List<String> listOptNull = Optional.ofNullable(listNull).orElse(new ArrayList<>());
|
||||
assertTrue(listOpt == list);
|
||||
assertTrue(listOptNull.isEmpty());
|
||||
|
||||
Optional<User> user = Optional.ofNullable(getUser());
|
||||
String result = user.map(User::getAddress)
|
||||
.map(Address::getStreet)
|
||||
.orElse("not specified");
|
||||
assertEquals(result, "1st Avenue");
|
||||
|
||||
Optional<OptionalUser> optionalUser = Optional.ofNullable(getOptionalUser());
|
||||
String resultOpt = optionalUser.flatMap(OptionalUser::getAddress)
|
||||
.flatMap(OptionalAddress::getStreet)
|
||||
.orElse("not specified");
|
||||
assertEquals(resultOpt, "1st Avenue");
|
||||
|
||||
Optional<User> userNull = Optional.ofNullable(getUserNull());
|
||||
String resultNull = userNull.map(User::getAddress)
|
||||
.map(Address::getStreet)
|
||||
.orElse("not specified");
|
||||
assertEquals(resultNull, "not specified");
|
||||
|
||||
Optional<OptionalUser> optionalUserNull = Optional.ofNullable(getOptionalUserNull());
|
||||
String resultOptNull = optionalUserNull.flatMap(OptionalUser::getAddress)
|
||||
.flatMap(OptionalAddress::getStreet)
|
||||
.orElse("not specified");
|
||||
assertEquals(resultOptNull, "not specified");
|
||||
|
||||
}
|
||||
|
||||
@Test(expected = CustomException.class)
|
||||
public void callMethod_whenCustomException_thenCorrect() {
|
||||
User user = new User();
|
||||
String result = user.getOrThrow();
|
||||
}
|
||||
|
||||
private User getUser() {
|
||||
User user = new User();
|
||||
Address address = new Address();
|
||||
address.setStreet("1st Avenue");
|
||||
user.setAddress(address);
|
||||
return user;
|
||||
}
|
||||
|
||||
private OptionalUser getOptionalUser() {
|
||||
OptionalUser user = new OptionalUser();
|
||||
OptionalAddress address = new OptionalAddress();
|
||||
address.setStreet("1st Avenue");
|
||||
user.setAddress(address);
|
||||
return user;
|
||||
}
|
||||
|
||||
private OptionalUser getOptionalUserNull() {
|
||||
OptionalUser user = new OptionalUser();
|
||||
OptionalAddress address = new OptionalAddress();
|
||||
address.setStreet(null);
|
||||
user.setAddress(address);
|
||||
return user;
|
||||
}
|
||||
|
||||
private User getUserNull() {
|
||||
User user = new User();
|
||||
Address address = new Address();
|
||||
address.setStreet(null);
|
||||
user.setAddress(address);
|
||||
return user;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,113 @@
|
|||
package com.baeldung.java8;
|
||||
|
||||
import com.baeldung.java_8_features.Detail;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class Java8StreamsTest {
|
||||
|
||||
private List<String> list;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
list = new ArrayList<>();
|
||||
list.add("One");
|
||||
list.add("OneAndOnly");
|
||||
list.add("Derek");
|
||||
list.add("Change");
|
||||
list.add("factory");
|
||||
list.add("justBefore");
|
||||
list.add("Italy");
|
||||
list.add("Italy");
|
||||
list.add("Thursday");
|
||||
list.add("");
|
||||
list.add("");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkStreamCount_whenCreating_givenDifferentSources() {
|
||||
String[] arr = new String[]{"a", "b", "c"};
|
||||
Stream<String> streamArr = Arrays.stream(arr);
|
||||
assertEquals(streamArr.count(), 3);
|
||||
|
||||
Stream<String> streamOf = Stream.of("a", "b", "c");
|
||||
assertEquals(streamOf.count(), 3);
|
||||
|
||||
long count = list.stream().distinct().count();
|
||||
assertEquals(count, 9);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void checkStreamCount_whenOperationFilter_thanCorrect() {
|
||||
Stream<String> streamFilter = list.stream().filter(element -> element.isEmpty());
|
||||
assertEquals(streamFilter.count(), 2);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void checkStreamCount_whenOperationMap_thanCorrect() {
|
||||
List<String> uris = new ArrayList<>();
|
||||
uris.add("C:\\My.txt");
|
||||
Stream<Path> streamMap = uris.stream().map(uri -> Paths.get(uri));
|
||||
assertEquals(streamMap.count(), 1);
|
||||
|
||||
List<Detail> details = new ArrayList<>();
|
||||
details.add(new Detail());
|
||||
details.add(new Detail());
|
||||
Stream<String> streamFlatMap = details.stream()
|
||||
.flatMap(detail -> detail.getParts().stream());
|
||||
assertEquals(streamFlatMap.count(), 4);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void checkStreamCount_whenOperationMatch_thenCorrect() {
|
||||
boolean isValid = list.stream().anyMatch(element -> element.contains("h"));
|
||||
boolean isValidOne = list.stream().allMatch(element -> element.contains("h"));
|
||||
boolean isValidTwo = list.stream().noneMatch(element -> element.contains("h"));
|
||||
assertTrue(isValid);
|
||||
assertFalse(isValidOne);
|
||||
assertFalse(isValidTwo);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void checkStreamReducedValue_whenOperationReduce_thenCorrect() {
|
||||
List<Integer> integers = new ArrayList<>();
|
||||
integers.add(1);
|
||||
integers.add(1);
|
||||
integers.add(1);
|
||||
Integer reduced = integers.stream().reduce(23, (a, b) -> a + b);
|
||||
assertTrue(reduced == 26);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkStreamContains_whenOperationCollect_thenCorrect() {
|
||||
List<String> resultList = list.stream()
|
||||
.map(element -> element.toUpperCase())
|
||||
.collect(Collectors.toList());
|
||||
assertEquals(resultList.size(), list.size());
|
||||
assertTrue(resultList.contains(""));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void checkParallelStream_whenDoWork() {
|
||||
list.parallelStream().forEach(element -> doWork(element));
|
||||
}
|
||||
|
||||
private void doWork(String string) {
|
||||
assertTrue(true); //just imitate an amount of work
|
||||
}
|
||||
}
|
|
@ -9,7 +9,11 @@
|
|||
<dependencies>
|
||||
|
||||
<!-- utils -->
|
||||
|
||||
<dependency>
|
||||
<groupId>net.sourceforge.collections</groupId>
|
||||
<artifactId>collections-generic</artifactId>
|
||||
<version>4.01</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
|
|
|
@ -0,0 +1,117 @@
|
|||
package com.baeldung.enums;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.apache.commons.collections15.CollectionUtils;
|
||||
import org.apache.commons.collections15.Predicate;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.EnumMap;
|
||||
import java.util.EnumSet;
|
||||
import java.util.List;
|
||||
|
||||
public class Pizza {
|
||||
|
||||
private static EnumSet<PizzaStatusEnum> undeliveredPizzaStatuses =
|
||||
EnumSet.of(PizzaStatusEnum.ORDERED, PizzaStatusEnum.READY);
|
||||
|
||||
private PizzaStatusEnum status;
|
||||
|
||||
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
|
||||
public enum PizzaStatusEnum {
|
||||
ORDERED (5){
|
||||
@Override
|
||||
public boolean isOrdered() {
|
||||
return true;
|
||||
}
|
||||
},
|
||||
READY (2){
|
||||
@Override
|
||||
public boolean isReady() {
|
||||
return true;
|
||||
}
|
||||
},
|
||||
DELIVERED (0){
|
||||
@Override
|
||||
public boolean isDelivered() {
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
private int timeToDelivery;
|
||||
|
||||
public boolean isOrdered() {return false;}
|
||||
|
||||
public boolean isReady() {return false;}
|
||||
|
||||
public boolean isDelivered(){return false;}
|
||||
@JsonProperty("timeToDelivery")
|
||||
public int getTimeToDelivery() {
|
||||
return timeToDelivery;
|
||||
}
|
||||
|
||||
private PizzaStatusEnum (int timeToDelivery) {
|
||||
this.timeToDelivery = timeToDelivery;
|
||||
}
|
||||
}
|
||||
|
||||
public PizzaStatusEnum getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(PizzaStatusEnum status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public boolean isDeliverable() {
|
||||
return this.status.isReady();
|
||||
}
|
||||
|
||||
public void printTimeToDeliver() {
|
||||
System.out.println("Time to delivery is " + this.getStatus().getTimeToDelivery() + " days");
|
||||
}
|
||||
|
||||
public static List<Pizza> getAllUndeliveredPizza(List<Pizza> input) {
|
||||
List<Pizza> undelivered = input;
|
||||
CollectionUtils.filter(undelivered, thatAreNotDelivered());
|
||||
return undelivered;
|
||||
}
|
||||
|
||||
public static EnumMap<PizzaStatusEnum, List<Pizza>> groupPizzaByStatus(List<Pizza> pizzaList) {
|
||||
EnumMap<PizzaStatusEnum, List<Pizza>> pzByStatus = new EnumMap<PizzaStatusEnum, List<Pizza>>(PizzaStatusEnum.class);
|
||||
for (Pizza pz : pizzaList) {
|
||||
PizzaStatusEnum status = pz.getStatus();
|
||||
|
||||
if (pzByStatus.containsKey(status)) {
|
||||
pzByStatus.get(status).add(pz);
|
||||
} else {
|
||||
List<Pizza> newPzList = new ArrayList<Pizza>();
|
||||
newPzList.add(pz);
|
||||
pzByStatus.put(status, newPzList);
|
||||
}
|
||||
}
|
||||
return pzByStatus;
|
||||
}
|
||||
|
||||
public void deliver() {
|
||||
if (isDeliverable()) {
|
||||
PizzaDeliverySystemConfiguration.getInstance().getDeliveryStrategy().deliver(this);
|
||||
this.setStatus(PizzaStatusEnum.DELIVERED);
|
||||
}
|
||||
}
|
||||
|
||||
public static String getJsonString(Pizza pz) throws IOException {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(pz);
|
||||
}
|
||||
|
||||
private static Predicate<Pizza> thatAreNotDelivered() {
|
||||
return new Predicate<Pizza>() {
|
||||
public boolean evaluate(Pizza entry) {
|
||||
return undeliveredPizzaStatuses.contains(entry.getStatus());
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
package com.baeldung.enums;
|
||||
|
||||
public enum PizzaDeliveryStrategy {
|
||||
EXPRESS {
|
||||
@Override
|
||||
public void deliver(Pizza pz) {
|
||||
System.out.println("Pizza will be delivered in express mode");
|
||||
}
|
||||
},
|
||||
NORMAL {
|
||||
@Override
|
||||
public void deliver(Pizza pz) {
|
||||
System.out.println("Pizza will be delivered in normal mode");
|
||||
}
|
||||
};
|
||||
|
||||
public abstract void deliver(Pizza pz);
|
||||
}
|
|
@ -0,0 +1,20 @@
|
|||
package com.baeldung.enums;
|
||||
|
||||
public enum PizzaDeliverySystemConfiguration {
|
||||
INSTANCE ;
|
||||
private PizzaDeliverySystemConfiguration() {
|
||||
//Do the configuration initialization which
|
||||
// involves overriding defaults like delivery strategy
|
||||
}
|
||||
|
||||
private PizzaDeliveryStrategy deliveryStrategy = PizzaDeliveryStrategy.NORMAL;
|
||||
|
||||
public static PizzaDeliverySystemConfiguration getInstance() {
|
||||
return INSTANCE;
|
||||
}
|
||||
|
||||
public PizzaDeliveryStrategy getDeliveryStrategy() {
|
||||
return deliveryStrategy;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,80 @@
|
|||
package org.baeldung.java.enums;
|
||||
|
||||
|
||||
import com.baeldung.enums.Pizza;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.EnumMap;
|
||||
import java.util.List;
|
||||
|
||||
import static junit.framework.TestCase.assertTrue;
|
||||
|
||||
|
||||
public class PizzaTest {
|
||||
@Test
|
||||
public void givenPizaOrder_whenReady_thenDeliverable() {
|
||||
Pizza testPz = new Pizza();
|
||||
testPz.setStatus(Pizza.PizzaStatusEnum.READY);
|
||||
assertTrue(testPz.isDeliverable());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPizaOrders_whenRetrievingUnDeliveredPzs_thenCorrectlyRetrieved() {
|
||||
List<Pizza> pzList = new ArrayList<Pizza>();
|
||||
Pizza pz1 = new Pizza();
|
||||
pz1.setStatus(Pizza.PizzaStatusEnum.DELIVERED);
|
||||
|
||||
Pizza pz2 = new Pizza();
|
||||
pz2.setStatus(Pizza.PizzaStatusEnum.ORDERED);
|
||||
|
||||
Pizza pz3 = new Pizza();
|
||||
pz3.setStatus(Pizza.PizzaStatusEnum.ORDERED);
|
||||
|
||||
Pizza pz4 = new Pizza();
|
||||
pz4.setStatus(Pizza.PizzaStatusEnum.READY);
|
||||
|
||||
pzList.add(pz1);
|
||||
pzList.add(pz2);
|
||||
pzList.add(pz3);
|
||||
pzList.add(pz4);
|
||||
|
||||
List<Pizza> undeliveredPzs = Pizza.getAllUndeliveredPizza(pzList);
|
||||
assertTrue(undeliveredPzs.size() == 3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPizaOrders_whenGroupByStatusCalled_thenCorrectlyGrouped() {
|
||||
|
||||
List<Pizza> pzList = new ArrayList<Pizza>();
|
||||
Pizza pz1 = new Pizza();
|
||||
pz1.setStatus(Pizza.PizzaStatusEnum.DELIVERED);
|
||||
|
||||
Pizza pz2 = new Pizza();
|
||||
pz2.setStatus(Pizza.PizzaStatusEnum.ORDERED);
|
||||
|
||||
Pizza pz3 = new Pizza();
|
||||
pz3.setStatus(Pizza.PizzaStatusEnum.ORDERED);
|
||||
|
||||
Pizza pz4 = new Pizza();
|
||||
pz4.setStatus(Pizza.PizzaStatusEnum.READY);
|
||||
|
||||
pzList.add(pz1);
|
||||
pzList.add(pz2);
|
||||
pzList.add(pz3);
|
||||
pzList.add(pz4);
|
||||
|
||||
EnumMap<Pizza.PizzaStatusEnum, List<Pizza>> map = Pizza.groupPizzaByStatus(pzList);
|
||||
assertTrue(map.get(Pizza.PizzaStatusEnum.DELIVERED).size() == 1);
|
||||
assertTrue(map.get(Pizza.PizzaStatusEnum.ORDERED).size() == 2);
|
||||
assertTrue(map.get(Pizza.PizzaStatusEnum.READY).size() == 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPizaOrder_whenDelivered_thenPizzaGetsDeliveredAndStatusChanges() {
|
||||
Pizza pz = new Pizza();
|
||||
pz.setStatus(Pizza.PizzaStatusEnum.READY);
|
||||
pz.deliver();
|
||||
assertTrue(pz.getStatus() == Pizza.PizzaStatusEnum.DELIVERED);
|
||||
}
|
||||
}
|
|
@ -79,18 +79,22 @@ public class HttpClientMultipartTest {
|
|||
@Test
|
||||
public final void givenFileandMultipleTextParts_whenUploadwithAddPart_thenNoExceptions() throws IOException {
|
||||
final URL url = Thread.currentThread().getContextClassLoader().getResource("uploads/" + TEXTFILENAME);
|
||||
|
||||
final File file = new File(url.getPath());
|
||||
final FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY);
|
||||
final StringBody stringBody1 = new StringBody("This is message 1", ContentType.MULTIPART_FORM_DATA);
|
||||
final StringBody stringBody2 = new StringBody("This is message 2", ContentType.MULTIPART_FORM_DATA);
|
||||
//
|
||||
final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
|
||||
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
|
||||
builder.addPart("upfile", fileBody);
|
||||
builder.addPart("text1", stringBody1);
|
||||
builder.addPart("text2", stringBody2);
|
||||
final HttpEntity entity = builder.build();
|
||||
//
|
||||
post.setEntity(entity);
|
||||
response = client.execute(post);
|
||||
|
||||
final int statusCode = response.getStatusLine().getStatusCode();
|
||||
final String responseString = getContent();
|
||||
final String contentTypeInHeader = getContentTypeHeader();
|
||||
|
@ -124,7 +128,7 @@ public class HttpClientMultipartTest {
|
|||
}
|
||||
|
||||
@Test
|
||||
public final void givenFileandInputStreamandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws ClientProtocolException, IOException {
|
||||
public final void givenFileAndInputStreamandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws ClientProtocolException, IOException {
|
||||
final URL url = Thread.currentThread().getContextClassLoader().getResource("uploads/" + ZIPFILENAME);
|
||||
final URL url2 = Thread.currentThread().getContextClassLoader().getResource("uploads/" + IMAGEFILENAME);
|
||||
final InputStream inputStream = new FileInputStream(url.getPath());
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
<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">
|
||||
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>jackson</artifactId>
|
||||
|
@ -22,6 +22,12 @@
|
|||
<artifactId>commons-io</artifactId>
|
||||
<version>2.4</version>
|
||||
</dependency>
|
||||
<!--jackson for xml-->
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.dataformat</groupId>
|
||||
<artifactId>jackson-dataformat-xml</artifactId>
|
||||
<version>2.7.4</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
|
@ -55,12 +61,12 @@
|
|||
<groupId>com.fasterxml.jackson.datatype</groupId>
|
||||
<artifactId>jackson-datatype-joda</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.module</groupId>
|
||||
<artifactId>jackson-module-jsonSchema</artifactId>
|
||||
<version>2.7.2</version>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.module</groupId>
|
||||
<artifactId>jackson-module-jsonSchema</artifactId>
|
||||
<version>2.7.2</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
|
|
|
@ -0,0 +1,86 @@
|
|||
package com.baeldung.jackson.xml;
|
||||
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
|
||||
|
||||
public class TestXMLSerializeDeserialize {
|
||||
|
||||
@Test
|
||||
public void whenJavaSerializedToXmlStr_thenCorrect() throws JsonProcessingException {
|
||||
XmlMapper xmlMapper = new XmlMapper();
|
||||
String xml = xmlMapper.writeValueAsString(new SimpleBean());
|
||||
assertNotNull(xml);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenJavaSerializedToXmlFile_thenCorrect() throws IOException {
|
||||
XmlMapper xmlMapper = new XmlMapper();
|
||||
xmlMapper.writeValue(new File("target/simple_bean.xml"), new SimpleBean());
|
||||
File file = new File("target/simple_bean.xml");
|
||||
assertNotNull(file);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenJavaGotFromXmlStr_thenCorrect() throws IOException {
|
||||
XmlMapper xmlMapper = new XmlMapper();
|
||||
SimpleBean value = xmlMapper.readValue(
|
||||
"<SimpleBean><x>1</x><y>2</y></SimpleBean>", SimpleBean.class);
|
||||
assertTrue(value.getX() == 1 && value.getY() == 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenJavaGotFromXmlFile_thenCorrect() throws IOException {
|
||||
File file = new File("src/test/resources/simple_bean.xml");
|
||||
XmlMapper xmlMapper = new XmlMapper();
|
||||
String xml = inputStreamToString(new FileInputStream(file));
|
||||
SimpleBean value = xmlMapper.readValue(xml, SimpleBean.class);
|
||||
assertTrue(value.getX() == 1 && value.getY() == 2);
|
||||
}
|
||||
|
||||
private static String inputStreamToString(InputStream is) throws IOException {
|
||||
BufferedReader br;
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
String line;
|
||||
br = new BufferedReader(new InputStreamReader(is));
|
||||
while ((line = br.readLine()) != null) {
|
||||
sb.append(line);
|
||||
}
|
||||
br.close();
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
|
||||
class SimpleBean {
|
||||
private int x = 1;
|
||||
private int y = 2;
|
||||
|
||||
public int getX() {
|
||||
return x;
|
||||
}
|
||||
|
||||
public void setX(int x) {
|
||||
this.x = x;
|
||||
}
|
||||
|
||||
public int getY() {
|
||||
return y;
|
||||
}
|
||||
|
||||
public void setY(int y) {
|
||||
this.y = y;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,4 @@
|
|||
<SimpleBean>
|
||||
<x>1</x>
|
||||
<y>2</y>
|
||||
</SimpleBean>
|
|
@ -0,0 +1,2 @@
|
|||
/target
|
||||
*.iml
|
|
@ -0,0 +1,130 @@
|
|||
<?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">
|
||||
<parent>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<artifactId>jsf</artifactId>
|
||||
<version>0.1-SNAPSHOT</version>
|
||||
<packaging>war</packaging>
|
||||
<dependencies>
|
||||
<!-- JSF -->
|
||||
|
||||
<dependency>
|
||||
<groupId>com.sun.faces</groupId>
|
||||
<artifactId>jsf-api</artifactId>
|
||||
<version>${com.sun.faces.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.sun.faces</groupId>
|
||||
<artifactId>jsf-impl</artifactId>
|
||||
<version>${com.sun.faces.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Spring -->
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-web</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-webmvc</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-websocket</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-messaging</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-web</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>javax.servlet-api</artifactId>
|
||||
<scope>provided</scope>
|
||||
<version>${javax.servlet.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- logging -->
|
||||
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-api</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>ch.qos.logback</groupId>
|
||||
<artifactId>logback-classic</artifactId>
|
||||
<version>${logback.version}</version>
|
||||
<!-- <scope>runtime</scope> -->
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>jcl-over-slf4j</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
<!-- <scope>runtime</scope> --> <!-- some spring dependencies need to compile against jcl -->
|
||||
</dependency>
|
||||
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>log4j-over-slf4j</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-war-plugin</artifactId>
|
||||
<version>${maven-war-plugin.version}</version>
|
||||
<configuration>
|
||||
<failOnMissingWebXml>false</failOnMissingWebXml>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<!-- Spring -->
|
||||
<org.springframework.version>4.2.5.RELEASE</org.springframework.version>
|
||||
|
||||
<!-- JSF -->
|
||||
<com.sun.faces.version>2.1.7</com.sun.faces.version>
|
||||
|
||||
<!-- logging -->
|
||||
<org.slf4j.version>1.7.13</org.slf4j.version>
|
||||
<logback.version>1.1.3</logback.version>
|
||||
|
||||
<!--Tomcat-->
|
||||
<javax.servlet.version>3.1.0</javax.servlet.version>
|
||||
|
||||
<!-- maven plugins -->
|
||||
<maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version>
|
||||
<maven-war-plugin.version>2.6</maven-war-plugin.version>
|
||||
|
||||
</properties>
|
||||
</project>
|
|
@ -0,0 +1,36 @@
|
|||
package com.baeldung.springintegration.config;
|
||||
|
||||
import com.sun.faces.config.FacesInitializer;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.web.WebApplicationInitializer;
|
||||
import org.springframework.web.context.ContextLoaderListener;
|
||||
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
|
||||
|
||||
import javax.servlet.ServletContext;
|
||||
import javax.servlet.ServletException;
|
||||
import java.util.Set;
|
||||
|
||||
public class MainWebAppInitializer extends FacesInitializer implements WebApplicationInitializer {
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(MainWebAppInitializer.class);
|
||||
|
||||
@Override
|
||||
public void onStartup(Set<Class<?>> classes, ServletContext servletContext) throws ServletException {
|
||||
super.onStartup(classes, servletContext);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register and configure all Servlet container components necessary to power the web application.
|
||||
*/
|
||||
@Override
|
||||
public void onStartup(final ServletContext sc) throws ServletException {
|
||||
LOGGER.info("MainWebAppInitializer.onStartup()");
|
||||
sc.setInitParameter("javax.faces.FACELETS_SKIP_COMMENTS", "true");
|
||||
|
||||
// Create the 'root' Spring application context
|
||||
final AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext();
|
||||
root.register(SpringCoreConfig.class);
|
||||
sc.addListener(new ContextLoaderListener(root));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
package com.baeldung.springintegration.config;
|
||||
|
||||
import com.baeldung.springintegration.dao.UserManagementDAO;
|
||||
import com.baeldung.springintegration.dao.UserManagementDAOImpl;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
public class SpringCoreConfig {
|
||||
|
||||
@Bean
|
||||
public UserManagementDAO userManagementDAO() {
|
||||
return new UserManagementDAOImpl();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,62 @@
|
|||
package com.baeldung.springintegration.controllers;
|
||||
|
||||
import com.baeldung.springintegration.dao.UserManagementDAO;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import javax.faces.bean.ManagedBean;
|
||||
import javax.faces.bean.ManagedProperty;
|
||||
import javax.faces.bean.ViewScoped;
|
||||
import javax.faces.context.FacesContext;
|
||||
import java.io.Serializable;
|
||||
|
||||
@ManagedBean(name = "registration")
|
||||
@ViewScoped
|
||||
public class RegistrationBean implements Serializable {
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(RegistrationBean.class);
|
||||
|
||||
@ManagedProperty(value = "#{userManagementDAO}")
|
||||
transient private UserManagementDAO userDao;
|
||||
private String userName;
|
||||
private String operationMessage;
|
||||
|
||||
public void createNewUser() {
|
||||
try {
|
||||
LOGGER.info("Creating new user");
|
||||
FacesContext context = FacesContext.getCurrentInstance();
|
||||
boolean operationStatus = userDao.createUser(userName);
|
||||
context.isValidationFailed();
|
||||
if (operationStatus) {
|
||||
operationMessage = "User " + userName + " created";
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
LOGGER.error("Error registering new user ");
|
||||
ex.printStackTrace();
|
||||
operationMessage = "Error " + userName + " not created";
|
||||
}
|
||||
}
|
||||
|
||||
public String getUserName() {
|
||||
return userName;
|
||||
}
|
||||
|
||||
public void setUserName(String userName) {
|
||||
this.userName = userName;
|
||||
}
|
||||
|
||||
public void setUserDao(UserManagementDAO userDao) {
|
||||
this.userDao = userDao;
|
||||
}
|
||||
|
||||
public UserManagementDAO getUserDao() {
|
||||
return this.userDao;
|
||||
}
|
||||
|
||||
public String getOperationMessage() {
|
||||
return operationMessage;
|
||||
}
|
||||
|
||||
public void setOperationMessage(String operationMessage) {
|
||||
this.operationMessage = operationMessage;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
package com.baeldung.springintegration.dao;
|
||||
|
||||
public interface UserManagementDAO {
|
||||
|
||||
boolean createUser(String newUserData);
|
||||
|
||||
}
|
|
@ -0,0 +1,38 @@
|
|||
package com.baeldung.springintegration.dao;
|
||||
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import javax.annotation.PostConstruct;
|
||||
|
||||
@Repository
|
||||
public class UserManagementDAOImpl implements UserManagementDAO {
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(UserManagementDAOImpl.class);
|
||||
|
||||
private List<String> users;
|
||||
|
||||
@PostConstruct
|
||||
public void initUserList() {
|
||||
users = new ArrayList<>();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean createUser(String newUserData) {
|
||||
if (newUserData != null) {
|
||||
users.add(newUserData);
|
||||
LOGGER.info("User {} successfully created", newUserData);
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public UserManagementDAOImpl() {
|
||||
}
|
||||
|
||||
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
<configuration>
|
||||
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>web - %date [%thread] %-5level %logger{36} - %message%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
|
||||
</configuration>
|
|
@ -0,0 +1,3 @@
|
|||
message.valueRequired = This value is required
|
||||
message.welcome = Baeldung | Register
|
||||
label.saveButton = Save
|
|
@ -0,0 +1,2 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Context antiJARLocking="true" path="/Baeldung"/>
|
|
@ -0,0 +1,39 @@
|
|||
<?xml version='1.0' encoding='UTF-8'?>
|
||||
|
||||
<!-- =========== FULL CONFIGURATION FILE ================================== -->
|
||||
|
||||
<faces-config version="2.1"
|
||||
xmlns="http://java.sun.com/xml/ns/javaee"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_1.xsd">
|
||||
|
||||
<application>
|
||||
<resource-bundle>
|
||||
<base-name>
|
||||
messages
|
||||
</base-name>
|
||||
<var>
|
||||
msg
|
||||
</var>
|
||||
</resource-bundle>
|
||||
<resource-bundle>
|
||||
<base-name>
|
||||
constraints
|
||||
</base-name>
|
||||
<var>
|
||||
constraints
|
||||
</var>
|
||||
</resource-bundle>
|
||||
<el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
|
||||
</application>
|
||||
|
||||
<navigation-rule>
|
||||
<from-view-id>/*</from-view-id>
|
||||
<navigation-case>
|
||||
<from-outcome>home</from-outcome>
|
||||
<to-view-id>/index.xhtml</to-view-id>
|
||||
<redirect/>
|
||||
</navigation-case>
|
||||
</navigation-rule>
|
||||
|
||||
</faces-config>
|
|
@ -0,0 +1,28 @@
|
|||
<?xml version='1.0' encoding='UTF-8' ?>
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
|
||||
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
|
||||
<html xmlns="http://www.w3.org/1999/xhtml"
|
||||
xmlns:h="http://java.sun.com/jsf/html">
|
||||
<h:head>
|
||||
<title><h:outputText value="#{msg['message.welcome']}"/></title>
|
||||
</h:head>
|
||||
<h:body>
|
||||
<h:form>
|
||||
<h:panelGrid id="theGrid" columns="3">
|
||||
<h:outputText value="Username"/>
|
||||
<h:inputText id="firstName" binding="#{userName}" required="true" requiredMessage="#{msg['message.valueRequired']}"
|
||||
value="#{registration.userName}"/>
|
||||
<h:message for="firstName" style="color:red;"/>
|
||||
<h:commandButton value="#{msg['label.saveButton']}" action="#{registration.createNewUser}"
|
||||
process="@this"/>
|
||||
<!--
|
||||
Accessing the Spring bean directly from the page
|
||||
<h:commandButton value="Save"
|
||||
action="#{registration.userDao.createUser(userName.value)}"/>
|
||||
-->
|
||||
<h:outputText value="#{registration.operationMessage}" style="color:green;"/>
|
||||
</h:panelGrid>
|
||||
</h:form>
|
||||
</h:body>
|
||||
</html>
|
||||
|
|
@ -0,0 +1,83 @@
|
|||
<?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>junit5</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
|
||||
<name>junit5</name>
|
||||
<description>Intro to JUnit 5</description>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<java.version>1.8</java.version>
|
||||
<!-- Due to a bug in surefire-junit5-5.0.0-ALPHA we use the latest snapshot instead -->
|
||||
<junit.gen5.version>5.0.0-SNAPSHOT</junit.gen5.version>
|
||||
</properties>
|
||||
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>snapshots-repo</id>
|
||||
<url>https://oss.sonatype.org/content/repositories/snapshots</url>
|
||||
<releases>
|
||||
<enabled>false</enabled>
|
||||
</releases>
|
||||
<snapshots>
|
||||
<!-- Do NOT cache JUnit 5 snapshot JARs. -->
|
||||
<updatePolicy>always</updatePolicy>
|
||||
<enabled>true</enabled>
|
||||
</snapshots>
|
||||
</repository>
|
||||
</repositories>
|
||||
|
||||
<pluginRepositories>
|
||||
<pluginRepository>
|
||||
<id>snapshots-repo</id>
|
||||
<url>https://oss.sonatype.org/content/repositories/snapshots</url>
|
||||
<releases>
|
||||
<enabled>false</enabled>
|
||||
</releases>
|
||||
<snapshots>
|
||||
<!-- Do NOT cache JUnit 5 snapshot JARs. -->
|
||||
<updatePolicy>always</updatePolicy>
|
||||
<enabled>true</enabled>
|
||||
</snapshots>
|
||||
</pluginRepository>
|
||||
</pluginRepositories>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.1</version>
|
||||
<configuration>
|
||||
<source>${java.version}</source>
|
||||
<target>${java.version}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>2.19</version>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.junit</groupId>
|
||||
<artifactId>surefire-junit5</artifactId>
|
||||
<version>${junit.gen5.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.junit</groupId>
|
||||
<artifactId>junit5-api</artifactId>
|
||||
<version>${junit.gen5.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
|
@ -0,0 +1,30 @@
|
|||
package com.baeldung;
|
||||
|
||||
import org.junit.gen5.api.Test;
|
||||
|
||||
import static org.junit.gen5.api.Assertions.assertEquals;
|
||||
import static org.junit.gen5.api.Assumptions.*;
|
||||
|
||||
public class AssumptionTest {
|
||||
|
||||
@Test
|
||||
void trueAssumption() {
|
||||
assumeTrue(5 > 1);
|
||||
assertEquals(5 + 2, 7);
|
||||
}
|
||||
|
||||
@Test
|
||||
void falseAssumption() {
|
||||
assumeFalse(5 < 1);
|
||||
assertEquals(5 + 2, 7);
|
||||
}
|
||||
|
||||
@Test
|
||||
void assumptionThat() {
|
||||
String someString = "Just a string";
|
||||
assumingThat(
|
||||
someString.equals("Just a string"),
|
||||
() -> assertEquals(2 + 2, 4)
|
||||
);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
package com.baeldung;
|
||||
|
||||
import org.junit.gen5.api.Test;
|
||||
|
||||
import static org.junit.gen5.api.Assertions.assertEquals;
|
||||
import static org.junit.gen5.api.Assertions.expectThrows;
|
||||
|
||||
public class ExceptionTest {
|
||||
|
||||
@Test
|
||||
void shouldThrowException() {
|
||||
Throwable exception = expectThrows(UnsupportedOperationException.class,
|
||||
() -> {
|
||||
throw new UnsupportedOperationException("Not supported");
|
||||
});
|
||||
assertEquals(exception.getMessage(), "Not supported");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,37 @@
|
|||
package com.baeldung;
|
||||
|
||||
import org.junit.gen5.api.Disabled;
|
||||
import org.junit.gen5.api.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.gen5.api.Assertions.*;
|
||||
|
||||
class FirstTest {
|
||||
|
||||
@Test
|
||||
void lambdaExpressions() {
|
||||
List<Integer> numbers = Arrays.asList(1, 2, 3);
|
||||
assertTrue(numbers
|
||||
.stream()
|
||||
.mapToInt(i -> i)
|
||||
.sum() > 5, "Sum should be greater than 5");
|
||||
}
|
||||
|
||||
@Test
|
||||
void groupAssertions() {
|
||||
int[] numbers = {0, 1, 2, 3, 4};
|
||||
assertAll("numbers",
|
||||
() -> assertEquals(numbers[0], 1),
|
||||
() -> assertEquals(numbers[3], 3),
|
||||
() -> assertEquals(numbers[4], 1)
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Disabled
|
||||
void disabledTest() {
|
||||
assertTrue(false);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,77 @@
|
|||
package com.baeldung;
|
||||
|
||||
import org.junit.gen5.api.*;
|
||||
|
||||
import java.util.EmptyStackException;
|
||||
import java.util.Stack;
|
||||
|
||||
public class NestedTest {
|
||||
Stack<Object> stack;
|
||||
boolean isRun = false;
|
||||
|
||||
@Test
|
||||
@DisplayName("is instantiated with new Stack()")
|
||||
void isInstantiatedWithNew() {
|
||||
new Stack<Object>();
|
||||
}
|
||||
|
||||
@Nested
|
||||
@DisplayName("when new")
|
||||
class WhenNew {
|
||||
|
||||
@BeforeEach
|
||||
void init() {
|
||||
stack = new Stack<Object>();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("is empty")
|
||||
void isEmpty() {
|
||||
Assertions.assertTrue(stack.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("throws EmptyStackException when popped")
|
||||
void throwsExceptionWhenPopped() {
|
||||
Assertions.expectThrows(EmptyStackException.class, () -> stack.pop());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("throws EmptyStackException when peeked")
|
||||
void throwsExceptionWhenPeeked() {
|
||||
Assertions.expectThrows(EmptyStackException.class, () -> stack.peek());
|
||||
}
|
||||
|
||||
@Nested
|
||||
@DisplayName("after pushing an element")
|
||||
class AfterPushing {
|
||||
|
||||
String anElement = "an element";
|
||||
|
||||
@BeforeEach
|
||||
void init() {
|
||||
stack.push(anElement);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("it is no longer empty")
|
||||
void isEmpty() {
|
||||
Assertions.assertFalse(stack.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("returns the element when popped and is empty")
|
||||
void returnElementWhenPopped() {
|
||||
Assertions.assertEquals(anElement, stack.pop());
|
||||
Assertions.assertTrue(stack.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("returns the element when peeked but remains not empty")
|
||||
void returnElementWhenPeeked() {
|
||||
Assertions.assertEquals(anElement, stack.peek());
|
||||
Assertions.assertFalse(stack.isEmpty());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,16 @@
|
|||
package com.baeldung;
|
||||
|
||||
import org.junit.gen5.api.Tag;
|
||||
import org.junit.gen5.api.Test;
|
||||
|
||||
import static org.junit.gen5.api.Assertions.assertEquals;
|
||||
|
||||
@Tag("Test case")
|
||||
public class TaggedTest {
|
||||
|
||||
@Test
|
||||
@Tag("Method")
|
||||
void testMethod() {
|
||||
assertEquals(2 + 2, 4);
|
||||
}
|
||||
}
|
|
@ -1,7 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<launchConfiguration type="org.eclipse.ant.AntBuilderLaunchConfigurationType">
|
||||
<booleanAttribute key="org.eclipse.ui.externaltools.ATTR_BUILDER_ENABLED" value="false"/>
|
||||
<stringAttribute key="org.eclipse.ui.externaltools.ATTR_DISABLED_BUILDER" value="org.eclipse.wst.jsdt.core.javascriptValidator"/>
|
||||
<mapAttribute key="org.eclipse.ui.externaltools.ATTR_TOOL_ARGUMENTS"/>
|
||||
<booleanAttribute key="org.eclipse.ui.externaltools.ATTR_TRIGGERS_CONFIGURED" value="true"/>
|
||||
</launchConfiguration>
|
|
@ -1,5 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<classpath>
|
||||
<classpathentry kind="src" path="src/main/webapp"/>
|
||||
<classpathentry kind="output" path=""/>
|
||||
</classpath>
|
|
@ -1,95 +0,0 @@
|
|||
eclipse.preferences.version=1
|
||||
org.eclipse.jdt.core.compiler.annotation.missingNonNullByDefaultAnnotation=ignore
|
||||
org.eclipse.jdt.core.compiler.annotation.nonnull=org.eclipse.jdt.annotation.NonNull
|
||||
org.eclipse.jdt.core.compiler.annotation.nonnullbydefault=org.eclipse.jdt.annotation.NonNullByDefault
|
||||
org.eclipse.jdt.core.compiler.annotation.nullable=org.eclipse.jdt.annotation.Nullable
|
||||
org.eclipse.jdt.core.compiler.annotation.nullanalysis=disabled
|
||||
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
|
||||
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
|
||||
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
|
||||
org.eclipse.jdt.core.compiler.compliance=1.8
|
||||
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
|
||||
org.eclipse.jdt.core.compiler.debug.localVariable=generate
|
||||
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
|
||||
org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning
|
||||
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
|
||||
org.eclipse.jdt.core.compiler.problem.autoboxing=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning
|
||||
org.eclipse.jdt.core.compiler.problem.deadCode=warning
|
||||
org.eclipse.jdt.core.compiler.problem.deprecation=warning
|
||||
org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled
|
||||
org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled
|
||||
org.eclipse.jdt.core.compiler.problem.discouragedReference=warning
|
||||
org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
|
||||
org.eclipse.jdt.core.compiler.problem.explicitlyClosedAutoCloseable=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.fatalOptionalError=disabled
|
||||
org.eclipse.jdt.core.compiler.problem.fieldHiding=error
|
||||
org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning
|
||||
org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning
|
||||
org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
|
||||
org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning
|
||||
org.eclipse.jdt.core.compiler.problem.includeNullInfoFromAsserts=disabled
|
||||
org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning
|
||||
org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.localVariableHiding=error
|
||||
org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning
|
||||
org.eclipse.jdt.core.compiler.problem.missingDefaultCase=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.missingEnumCaseDespiteDefault=disabled
|
||||
org.eclipse.jdt.core.compiler.problem.missingHashCodeMethod=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotationForInterfaceMethodImplementation=enabled
|
||||
org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning
|
||||
org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning
|
||||
org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning
|
||||
org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.nullAnnotationInferenceConflict=error
|
||||
org.eclipse.jdt.core.compiler.problem.nullReference=warning
|
||||
org.eclipse.jdt.core.compiler.problem.nullSpecViolation=error
|
||||
org.eclipse.jdt.core.compiler.problem.nullUncheckedConversion=warning
|
||||
org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning
|
||||
org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.potentialNullReference=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.potentiallyUnclosedCloseable=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning
|
||||
org.eclipse.jdt.core.compiler.problem.redundantNullAnnotation=warning
|
||||
org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.redundantSpecificationOfTypeArguments=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.reportMethodCanBePotentiallyStatic=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.reportMethodCanBeStatic=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled
|
||||
org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning
|
||||
org.eclipse.jdt.core.compiler.problem.suppressOptionalErrors=disabled
|
||||
org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled
|
||||
org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.typeParameterHiding=error
|
||||
org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems=enabled
|
||||
org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning
|
||||
org.eclipse.jdt.core.compiler.problem.unclosedCloseable=warning
|
||||
org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning
|
||||
org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled
|
||||
org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled
|
||||
org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled
|
||||
org.eclipse.jdt.core.compiler.problem.unusedImport=warning
|
||||
org.eclipse.jdt.core.compiler.problem.unusedLabel=warning
|
||||
org.eclipse.jdt.core.compiler.problem.unusedLocal=warning
|
||||
org.eclipse.jdt.core.compiler.problem.unusedObjectAllocation=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore
|
||||
org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled
|
||||
org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled
|
||||
org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled
|
||||
org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning
|
||||
org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning
|
||||
org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning
|
||||
org.eclipse.jdt.core.compiler.source=1.8
|
|
@ -1,55 +0,0 @@
|
|||
#Sat Jan 21 23:04:06 EET 2012
|
||||
eclipse.preferences.version=1
|
||||
editor_save_participant_org.eclipse.jdt.ui.postsavelistener.cleanup=true
|
||||
sp_cleanup.add_default_serial_version_id=true
|
||||
sp_cleanup.add_generated_serial_version_id=false
|
||||
sp_cleanup.add_missing_annotations=true
|
||||
sp_cleanup.add_missing_deprecated_annotations=true
|
||||
sp_cleanup.add_missing_methods=false
|
||||
sp_cleanup.add_missing_nls_tags=false
|
||||
sp_cleanup.add_missing_override_annotations=true
|
||||
sp_cleanup.add_missing_override_annotations_interface_methods=true
|
||||
sp_cleanup.add_serial_version_id=false
|
||||
sp_cleanup.always_use_blocks=true
|
||||
sp_cleanup.always_use_parentheses_in_expressions=true
|
||||
sp_cleanup.always_use_this_for_non_static_field_access=false
|
||||
sp_cleanup.always_use_this_for_non_static_method_access=false
|
||||
sp_cleanup.convert_to_enhanced_for_loop=true
|
||||
sp_cleanup.correct_indentation=true
|
||||
sp_cleanup.format_source_code=true
|
||||
sp_cleanup.format_source_code_changes_only=true
|
||||
sp_cleanup.make_local_variable_final=true
|
||||
sp_cleanup.make_parameters_final=true
|
||||
sp_cleanup.make_private_fields_final=false
|
||||
sp_cleanup.make_type_abstract_if_missing_method=false
|
||||
sp_cleanup.make_variable_declarations_final=true
|
||||
sp_cleanup.never_use_blocks=false
|
||||
sp_cleanup.never_use_parentheses_in_expressions=false
|
||||
sp_cleanup.on_save_use_additional_actions=true
|
||||
sp_cleanup.organize_imports=true
|
||||
sp_cleanup.qualify_static_field_accesses_with_declaring_class=false
|
||||
sp_cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true
|
||||
sp_cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true
|
||||
sp_cleanup.qualify_static_member_accesses_with_declaring_class=true
|
||||
sp_cleanup.qualify_static_method_accesses_with_declaring_class=false
|
||||
sp_cleanup.remove_private_constructors=true
|
||||
sp_cleanup.remove_trailing_whitespaces=true
|
||||
sp_cleanup.remove_trailing_whitespaces_all=true
|
||||
sp_cleanup.remove_trailing_whitespaces_ignore_empty=false
|
||||
sp_cleanup.remove_unnecessary_casts=true
|
||||
sp_cleanup.remove_unnecessary_nls_tags=false
|
||||
sp_cleanup.remove_unused_imports=true
|
||||
sp_cleanup.remove_unused_local_variables=false
|
||||
sp_cleanup.remove_unused_private_fields=true
|
||||
sp_cleanup.remove_unused_private_members=false
|
||||
sp_cleanup.remove_unused_private_methods=true
|
||||
sp_cleanup.remove_unused_private_types=true
|
||||
sp_cleanup.sort_members=false
|
||||
sp_cleanup.sort_members_all=false
|
||||
sp_cleanup.use_blocks=false
|
||||
sp_cleanup.use_blocks_only_for_return_and_throw=false
|
||||
sp_cleanup.use_parentheses_in_expressions=false
|
||||
sp_cleanup.use_this_for_non_static_field_access=true
|
||||
sp_cleanup.use_this_for_non_static_field_access_only_if_necessary=true
|
||||
sp_cleanup.use_this_for_non_static_method_access=true
|
||||
sp_cleanup.use_this_for_non_static_method_access_only_if_necessary=true
|
|
@ -1,4 +0,0 @@
|
|||
activeProfiles=
|
||||
eclipse.preferences.version=1
|
||||
resolveWorkspaceProjects=true
|
||||
version=1
|
|
@ -1,2 +0,0 @@
|
|||
eclipse.preferences.version=1
|
||||
org.eclipse.m2e.wtp.enabledProjectSpecificPrefs=false
|
|
@ -1,8 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?><project-modules id="moduleCoreId" project-version="1.5.0">
|
||||
<wb-module deploy-name="spring-rest">
|
||||
<wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/java"/>
|
||||
<wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/resources"/>
|
||||
<property name="context-root" value="spring-rest"/>
|
||||
<property name="java-output-path" value="/spring-rest/target/classes"/>
|
||||
</wb-module>
|
||||
</project-modules>
|
|
@ -1,4 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<faceted-project>
|
||||
<installed facet="java" version="1.8"/>
|
||||
</faceted-project>
|
|
@ -1 +0,0 @@
|
|||
org.eclipse.wst.jsdt.launching.baseBrowserLibrary
|
|
@ -1 +0,0 @@
|
|||
Window
|
|
@ -1,14 +0,0 @@
|
|||
DELEGATES_PREFERENCE=delegateValidatorList
|
||||
USER_BUILD_PREFERENCE=enabledBuildValidatorListorg.eclipse.jst.j2ee.internal.classpathdep.ClasspathDependencyValidator;
|
||||
USER_MANUAL_PREFERENCE=enabledManualValidatorListorg.eclipse.jst.j2ee.internal.classpathdep.ClasspathDependencyValidator;
|
||||
USER_PREFERENCE=overrideGlobalPreferencestruedisableAllValidationfalseversion1.2.303.v201202090300
|
||||
eclipse.preferences.version=1
|
||||
override=true
|
||||
suspend=false
|
||||
vals/org.eclipse.jst.jsf.ui.JSFAppConfigValidator/global=FF01
|
||||
vals/org.eclipse.jst.jsp.core.JSPBatchValidator/global=FF01
|
||||
vals/org.eclipse.jst.jsp.core.JSPContentValidator/global=FF01
|
||||
vals/org.eclipse.jst.jsp.core.TLDValidator/global=FF01
|
||||
vals/org.eclipse.wst.dtd.core.dtdDTDValidator/global=FF01
|
||||
vals/org.eclipse.wst.jsdt.web.core.JsBatchValidator/global=TF02
|
||||
vf.version=3
|
|
@ -1,2 +0,0 @@
|
|||
eclipse.preferences.version=1
|
||||
org.eclipse.wst.ws.service.policy.projectEnabled=false
|
|
@ -1,14 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beansProjectDescription>
|
||||
<version>1</version>
|
||||
<pluginVersion><![CDATA[3.3.0.201307091516-RELEASE]]></pluginVersion>
|
||||
<configSuffixes>
|
||||
<configSuffix><![CDATA[xml]]></configSuffix>
|
||||
</configSuffixes>
|
||||
<enableImports><![CDATA[false]]></enableImports>
|
||||
<configs>
|
||||
<config>src/main/webapp/WEB-INF/api-servlet.xml</config>
|
||||
</configs>
|
||||
<configSets>
|
||||
</configSets>
|
||||
</beansProjectDescription>
|
211
mockito/pom.xml
211
mockito/pom.xml
|
@ -1,124 +1,143 @@
|
|||
<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</artifactId>
|
||||
<version>0.1-SNAPSHOT</version>
|
||||
<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>org.baeldung</groupId>
|
||||
<artifactId>mockito</artifactId>
|
||||
<version>0.1-SNAPSHOT</version>
|
||||
|
||||
<name>mockito</name>
|
||||
<name>mockito</name>
|
||||
|
||||
<dependencies>
|
||||
<dependencies>
|
||||
|
||||
<!-- utils -->
|
||||
<!-- utils -->
|
||||
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- web -->
|
||||
<!-- web -->
|
||||
|
||||
<!-- test scoped -->
|
||||
<!-- test scoped -->
|
||||
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>hamcrest-core</artifactId>
|
||||
<version>${org.hamcrest.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>hamcrest-library</artifactId>
|
||||
<version>${org.hamcrest.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>hamcrest-core</artifactId>
|
||||
<version>${org.hamcrest.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>hamcrest-library</artifactId>
|
||||
<version>${org.hamcrest.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.mockito</groupId>
|
||||
<artifactId>mockito-core</artifactId>
|
||||
<version>${mockito.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.mockito</groupId>
|
||||
<artifactId>mockito-core</artifactId>
|
||||
<version>${mockito.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
<dependency>
|
||||
<groupId>org.powermock</groupId>
|
||||
<artifactId>powermock-module-junit4</artifactId>
|
||||
<version>${powermock.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.powermock</groupId>
|
||||
<artifactId>powermock-api-mockito</artifactId>
|
||||
<version>${powermock.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<build>
|
||||
<finalName>mockito</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</dependencies>
|
||||
|
||||
<plugins>
|
||||
<build>
|
||||
<finalName>mockito</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugins>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${maven-surefire-plugin.version}</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
</plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${maven-surefire-plugin.version}</version>
|
||||
</plugin>
|
||||
|
||||
</build>
|
||||
</plugins>
|
||||
|
||||
<properties>
|
||||
<!-- persistence -->
|
||||
<hibernate.version>4.3.11.Final</hibernate.version>
|
||||
<mysql-connector-java.version>5.1.38</mysql-connector-java.version>
|
||||
</build>
|
||||
|
||||
<!-- logging -->
|
||||
<org.slf4j.version>1.7.13</org.slf4j.version>
|
||||
<logback.version>1.1.3</logback.version>
|
||||
<properties>
|
||||
<!-- Spring -->
|
||||
<org.springframework.version>4.1.5.RELEASE</org.springframework.version>
|
||||
<org.springframework.security.version>3.2.5.RELEASE</org.springframework.security.version>
|
||||
|
||||
<!-- various -->
|
||||
<hibernate-validator.version>5.1.3.Final</hibernate-validator.version>
|
||||
<!-- persistence -->
|
||||
<hibernate.version>4.3.10.Final</hibernate.version>
|
||||
<mysql-connector-java.version>5.1.35</mysql-connector-java.version>
|
||||
|
||||
<!-- util -->
|
||||
<guava.version>19.0</guava.version>
|
||||
<commons-lang3.version>3.4</commons-lang3.version>
|
||||
<!-- logging -->
|
||||
<org.slf4j.version>1.7.13</org.slf4j.version>
|
||||
<logback.version>1.1.3</logback.version>
|
||||
|
||||
<!-- testing -->
|
||||
<org.hamcrest.version>1.3</org.hamcrest.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
<mockito.version>1.10.19</mockito.version>
|
||||
<!-- various -->
|
||||
<hibernate-validator.version>5.1.3.Final</hibernate-validator.version>
|
||||
|
||||
<httpcore.version>4.4.1</httpcore.version>
|
||||
<httpclient.version>4.5</httpclient.version>
|
||||
<!-- util -->
|
||||
<guava.version>19.0</guava.version>
|
||||
<commons-lang3.version>3.4</commons-lang3.version>
|
||||
|
||||
<rest-assured.version>2.9.0</rest-assured.version>
|
||||
<!-- testing -->
|
||||
<org.hamcrest.version>1.3</org.hamcrest.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
<mockito.version>1.10.19</mockito.version>
|
||||
<powermock.version>1.6.4</powermock.version>
|
||||
|
||||
<!-- maven plugins -->
|
||||
<maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version>
|
||||
<maven-war-plugin.version>2.6</maven-war-plugin.version>
|
||||
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||
<maven-resources-plugin.version>2.7</maven-resources-plugin.version>
|
||||
<cargo-maven2-plugin.version>1.4.18</cargo-maven2-plugin.version>
|
||||
<httpcore.version>4.4.1</httpcore.version>
|
||||
<httpclient.version>4.5</httpclient.version>
|
||||
|
||||
</properties>
|
||||
<rest-assured.version>2.4.1</rest-assured.version>
|
||||
|
||||
<!-- maven plugins -->
|
||||
<maven-compiler-plugin.version>3.3</maven-compiler-plugin.version>
|
||||
<maven-war-plugin.version>2.6</maven-war-plugin.version>
|
||||
<maven-surefire-plugin.version>2.18.1</maven-surefire-plugin.version>
|
||||
<maven-resources-plugin.version>2.7</maven-resources-plugin.version>
|
||||
<cargo-maven2-plugin.version>1.4.14</cargo-maven2-plugin.version>
|
||||
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,20 @@
|
|||
package com.baeldung.powermockito.introduction;
|
||||
|
||||
public class CollaboratorForPartialMocking {
|
||||
|
||||
public static String staticMethod() {
|
||||
return "Hello Baeldung!";
|
||||
}
|
||||
|
||||
public final String finalMethod() {
|
||||
return "Hello Baeldung!";
|
||||
}
|
||||
|
||||
private String privateMethod() {
|
||||
return "Hello Baeldung!";
|
||||
}
|
||||
|
||||
public String privateMethodCaller() {
|
||||
return privateMethod() + " Welcome to the Java world.";
|
||||
}
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
package com.baeldung.powermockito.introduction;
|
||||
|
||||
public class CollaboratorWithFinalMethods {
|
||||
|
||||
public final String helloMethod() {
|
||||
return "Hello World!";
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,16 @@
|
|||
package com.baeldung.powermockito.introduction;
|
||||
|
||||
public class CollaboratorWithStaticMethods {
|
||||
|
||||
public static String firstMethod(String name) {
|
||||
return "Hello " + name + " !";
|
||||
}
|
||||
|
||||
public static String secondMethod() {
|
||||
return "Hello no one!";
|
||||
}
|
||||
|
||||
public static String thirdMethod() {
|
||||
return "Hello no one again!";
|
||||
}
|
||||
}
|
|
@ -0,0 +1,78 @@
|
|||
package com.baeldung.powermockito.introduction;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mockito;
|
||||
import org.powermock.core.classloader.annotations.PrepareForTest;
|
||||
import org.powermock.modules.junit4.PowerMockRunner;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.powermock.api.mockito.PowerMockito.*;
|
||||
|
||||
@RunWith(PowerMockRunner.class)
|
||||
@PrepareForTest(fullyQualifiedNames = "com.baeldung.powermockito.introduction.*")
|
||||
public class PowerMockitoTest {
|
||||
|
||||
@Test
|
||||
public void givenFinalMethods_whenUsingPowerMockito_thenCorrect() throws Exception {
|
||||
CollaboratorWithFinalMethods mock = mock(CollaboratorWithFinalMethods.class);
|
||||
whenNew(CollaboratorWithFinalMethods.class).withNoArguments().thenReturn(mock);
|
||||
|
||||
CollaboratorWithFinalMethods collaborator = new CollaboratorWithFinalMethods();
|
||||
verifyNew(CollaboratorWithFinalMethods.class).withNoArguments();
|
||||
|
||||
when(collaborator.helloMethod()).thenReturn("Hello Baeldung!");
|
||||
String welcome = collaborator.helloMethod();
|
||||
Mockito.verify(collaborator).helloMethod();
|
||||
assertEquals("Hello Baeldung!", welcome);
|
||||
}
|
||||
|
||||
@Test(expected = RuntimeException.class)
|
||||
public void givenStaticMethods_whenUsingPowerMockito_thenCorrect() {
|
||||
mockStatic(CollaboratorWithStaticMethods.class);
|
||||
|
||||
when(CollaboratorWithStaticMethods.firstMethod(Mockito.anyString())).thenReturn("Hello Baeldung!");
|
||||
when(CollaboratorWithStaticMethods.secondMethod()).thenReturn("Nothing special");
|
||||
doThrow(new RuntimeException()).when(CollaboratorWithStaticMethods.class);
|
||||
CollaboratorWithStaticMethods.thirdMethod();
|
||||
|
||||
String firstWelcome = CollaboratorWithStaticMethods.firstMethod("Whoever");
|
||||
String secondWelcome = CollaboratorWithStaticMethods.firstMethod("Whatever");
|
||||
|
||||
assertEquals("Hello Baeldung!", firstWelcome);
|
||||
assertEquals("Hello Baeldung!", secondWelcome);
|
||||
|
||||
verifyStatic(Mockito.times(2));
|
||||
CollaboratorWithStaticMethods.firstMethod(Mockito.anyString());
|
||||
|
||||
verifyStatic(Mockito.never());
|
||||
CollaboratorWithStaticMethods.secondMethod();
|
||||
|
||||
CollaboratorWithStaticMethods.thirdMethod();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPartialMocking_whenUsingPowerMockito_thenCorrect() throws Exception {
|
||||
String returnValue;
|
||||
|
||||
spy(CollaboratorForPartialMocking.class);
|
||||
when(CollaboratorForPartialMocking.staticMethod()).thenReturn("I am a static mock method.");
|
||||
returnValue = CollaboratorForPartialMocking.staticMethod();
|
||||
verifyStatic();
|
||||
CollaboratorForPartialMocking.staticMethod();
|
||||
assertEquals("I am a static mock method.", returnValue);
|
||||
|
||||
CollaboratorForPartialMocking collaborator = new CollaboratorForPartialMocking();
|
||||
CollaboratorForPartialMocking mock = spy(collaborator);
|
||||
|
||||
when(mock.finalMethod()).thenReturn("I am a final mock method.");
|
||||
returnValue = mock.finalMethod();
|
||||
Mockito.verify(mock).finalMethod();
|
||||
assertEquals("I am a final mock method.", returnValue);
|
||||
|
||||
when(mock, "privateMethod").thenReturn("I am a private mock method.");
|
||||
returnValue = mock.privateMethodCaller();
|
||||
verifyPrivate(mock).invoke("privateMethod");
|
||||
assertEquals("I am a private mock method. Welcome to the Java world.", returnValue);
|
||||
}
|
||||
}
|
|
@ -1,20 +1,14 @@
|
|||
package org.baeldung.mockito;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.mockito.*;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Captor;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
import org.mockito.Spy;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
//@RunWith(MockitoJUnitRunner.class)
|
||||
public class MockitoAnnotationTest {
|
||||
|
|
|
@ -1,20 +1,17 @@
|
|||
package org.baeldung.mockito;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.invocation.InvocationOnMock;
|
||||
import org.mockito.stubbing.Answer;
|
||||
|
||||
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.mockito.Matchers.anyInt;
|
||||
import static org.mockito.Matchers.anyString;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.doReturn;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.invocation.InvocationOnMock;
|
||||
import org.mockito.stubbing.Answer;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
public class MockitoConfigExamplesTest {
|
||||
|
||||
|
|
|
@ -0,0 +1,69 @@
|
|||
package org.baeldung.mockito;
|
||||
|
||||
import static org.mockito.Mockito.*;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.hamcrest.Matchers.is;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.Rule;
|
||||
import org.junit.rules.ExpectedException;
|
||||
import org.mockito.MockSettings;
|
||||
import org.mockito.exceptions.verification.TooLittleActualInvocations;
|
||||
import org.mockito.invocation.InvocationOnMock;
|
||||
import org.mockito.stubbing.Answer;
|
||||
|
||||
public class MockitoMockTest {
|
||||
|
||||
private static class CustomAnswer implements Answer<Boolean> {
|
||||
@Override
|
||||
public Boolean answer(InvocationOnMock invocation) throws Throwable {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Rule
|
||||
public ExpectedException thrown = ExpectedException.none();
|
||||
|
||||
@Test
|
||||
public void whenUsingSimpleMock_thenCorrect() {
|
||||
MyList listMock = mock(MyList.class);
|
||||
when(listMock.add(anyString())).thenReturn(false);
|
||||
boolean added = listMock.add(randomAlphabetic(6));
|
||||
|
||||
verify(listMock).add(anyString());
|
||||
assertThat(added, is(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingMockWithName_thenCorrect() {
|
||||
MyList listMock = mock(MyList.class, "myMock");
|
||||
when(listMock.add(anyString())).thenReturn(false);
|
||||
listMock.add(randomAlphabetic(6));
|
||||
|
||||
thrown.expect(TooLittleActualInvocations.class);
|
||||
thrown.expectMessage(containsString("myMock.add"));
|
||||
|
||||
verify(listMock, times(2)).add(anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingMockWithAnswer_thenCorrect() {
|
||||
MyList listMock = mock(MyList.class, new CustomAnswer());
|
||||
boolean added = listMock.add(randomAlphabetic(6));
|
||||
|
||||
verify(listMock).add(anyString());
|
||||
assertThat(added, is(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingMockWithSettings_thenCorrect() {
|
||||
MockSettings customSettings = withSettings().defaultAnswer(new CustomAnswer());
|
||||
MyList listMock = mock(MyList.class, customSettings);
|
||||
boolean added = listMock.add(randomAlphabetic(6));
|
||||
|
||||
verify(listMock).add(anyString());
|
||||
assertThat(added, is(false));
|
||||
}
|
||||
}
|
|
@ -1,16 +1,16 @@
|
|||
package org.baeldung.mockito;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.Spy;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class MockitoSpyTest {
|
||||
|
||||
|
|
|
@ -1,26 +1,18 @@
|
|||
package org.baeldung.mockito;
|
||||
|
||||
import static org.hamcrest.Matchers.hasItem;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.mockito.Matchers.anyString;
|
||||
import static org.mockito.Mockito.atLeast;
|
||||
import static org.mockito.Mockito.atMost;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoMoreInteractions;
|
||||
import static org.mockito.Mockito.verifyZeroInteractions;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
import org.junit.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.InOrder;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.exceptions.verification.NoInteractionsWanted;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
import java.util.List;
|
||||
|
||||
import static org.hamcrest.Matchers.hasItem;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.mockito.Matchers.anyString;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
public class MockitoVerifyExamplesTest {
|
||||
|
||||
|
@ -115,10 +107,10 @@ public class MockitoVerifyExamplesTest {
|
|||
@Test
|
||||
public final void whenVerifyingAnInteractionWithArgumentCapture_thenCorrect() {
|
||||
final List<String> mockedList = mock(MyList.class);
|
||||
mockedList.addAll(Lists.<String> newArrayList("someElement"));
|
||||
mockedList.addAll(Lists.<String>newArrayList("someElement"));
|
||||
final ArgumentCaptor<List> argumentCaptor = ArgumentCaptor.forClass(List.class);
|
||||
verify(mockedList).addAll(argumentCaptor.capture());
|
||||
final List<String> capturedArgument = argumentCaptor.<List<String>> getValue();
|
||||
final List<String> capturedArgument = argumentCaptor.<List<String>>getValue();
|
||||
assertThat(capturedArgument, hasItem("someElement"));
|
||||
}
|
||||
|
||||
|
|
|
@ -4,6 +4,7 @@ import java.util.HashMap;
|
|||
import java.util.Map;
|
||||
|
||||
public class MyDictionary {
|
||||
|
||||
Map<String, String> wordMap;
|
||||
|
||||
public MyDictionary() {
|
||||
|
|
|
@ -1,13 +0,0 @@
|
|||
*.class
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
1
pom.xml
1
pom.xml
|
@ -64,6 +64,7 @@
|
|||
<module>spring-security-rest-full</module>
|
||||
<module>spring-thymeleaf</module>
|
||||
<module>spring-zuul</module>
|
||||
<module>jsf</module>
|
||||
|
||||
</modules>
|
||||
|
||||
|
|
|
@ -2,23 +2,19 @@ package org.baeldung.caching.config;
|
|||
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.baeldung.caching.example.CustomerDataService;
|
||||
import org.springframework.cache.CacheManager;
|
||||
import org.springframework.cache.annotation.EnableCaching;
|
||||
import org.springframework.cache.concurrent.ConcurrentMapCache;
|
||||
import org.springframework.cache.support.SimpleCacheManager;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
@EnableCaching
|
||||
@ComponentScan("org.baeldung.caching.example")
|
||||
public class CachingConfig {
|
||||
|
||||
@Bean
|
||||
public CustomerDataService customerDataService() {
|
||||
return new CustomerDataService();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public CacheManager cacheManager() {
|
||||
final SimpleCacheManager cacheManager = new SimpleCacheManager();
|
||||
|
|
|
@ -0,0 +1,76 @@
|
|||
package org.baeldung.caching.example;
|
||||
|
||||
import org.springframework.cache.annotation.CacheEvict;
|
||||
import org.springframework.cache.annotation.CachePut;
|
||||
import org.springframework.cache.annotation.Cacheable;
|
||||
import org.springframework.cache.annotation.Caching;
|
||||
|
||||
public abstract class AbstractService {
|
||||
|
||||
// this method configuration is equivalent to xml configuration
|
||||
@Cacheable(value = "addresses", key = "#customer.name")
|
||||
public String getAddress(final Customer customer) {
|
||||
return customer.getAddress();
|
||||
}
|
||||
|
||||
/**
|
||||
* The method returns the customer's address,
|
||||
only it doesn't find it the cache- addresses and directory.
|
||||
*
|
||||
* @param customer the customer
|
||||
* @return the address
|
||||
*/
|
||||
@Cacheable({ "addresses", "directory" })
|
||||
public String getAddress1(final Customer customer) {
|
||||
return customer.getAddress();
|
||||
}
|
||||
|
||||
/**
|
||||
* The method returns the customer's address,
|
||||
but refreshes all the entries in the cache to load new ones.
|
||||
*
|
||||
* @param customer the customer
|
||||
* @return the address
|
||||
*/
|
||||
@CacheEvict(value = "addresses", allEntries = true)
|
||||
public String getAddress2(final Customer customer) {
|
||||
return customer.getAddress();
|
||||
}
|
||||
|
||||
/**
|
||||
* The method returns the customer's address,
|
||||
but not before selectively evicting the cache as per specified paramters.
|
||||
*
|
||||
* @param customer the customer
|
||||
* @return the address
|
||||
*/
|
||||
@Caching(evict = { @CacheEvict("addresses"), @CacheEvict(value = "directory", key = "#customer.name") })
|
||||
public String getAddress3(final Customer customer) {
|
||||
return customer.getAddress();
|
||||
}
|
||||
|
||||
/**
|
||||
* The method uses the class level cache to look up for entries.
|
||||
*
|
||||
* @param customer the customer
|
||||
* @return the address
|
||||
*/
|
||||
@Cacheable
|
||||
// parameter not required as we have declared it using @CacheConfig
|
||||
public String getAddress4(final Customer customer) {
|
||||
return customer.getAddress();
|
||||
}
|
||||
|
||||
/**
|
||||
* The method selectively caches the results that meet the predefined criteria.
|
||||
*
|
||||
* @param customer the customer
|
||||
* @return the address
|
||||
*/
|
||||
@CachePut(value = "addresses", condition = "#customer.name=='Tom'")
|
||||
// @CachePut(value = "addresses", unless = "#result.length>64")
|
||||
public String getAddress5(final Customer customer) {
|
||||
return customer.getAddress();
|
||||
}
|
||||
|
||||
}
|
|
@ -1,7 +1,5 @@
|
|||
package org.baeldung.caching.example;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.cache.CacheManager;
|
||||
import org.springframework.cache.annotation.CacheConfig;
|
||||
import org.springframework.cache.annotation.CacheEvict;
|
||||
import org.springframework.cache.annotation.CachePut;
|
||||
|
@ -13,9 +11,6 @@ import org.springframework.stereotype.Component;
|
|||
@CacheConfig(cacheNames = { "addresses" })
|
||||
public class CustomerDataService {
|
||||
|
||||
@Autowired
|
||||
CacheManager cacheManager;
|
||||
|
||||
// this method configuration is equivalent to xml configuration
|
||||
@Cacheable(value = "addresses", key = "#customer.name")
|
||||
public String getAddress(final Customer customer) {
|
||||
|
|
|
@ -0,0 +1,10 @@
|
|||
package org.baeldung.caching.example;
|
||||
|
||||
import org.springframework.cache.annotation.CacheConfig;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
@CacheConfig(cacheNames = { "addresses" })
|
||||
public class CustomerServiceWithParent extends AbstractService {
|
||||
//
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
package org.baeldung.scopes;
|
||||
|
||||
public class HelloMessageGenerator {
|
||||
|
||||
private String message;
|
||||
|
||||
public String getMessage() {
|
||||
return message;
|
||||
}
|
||||
|
||||
public void setMessage(final String message) {
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,27 @@
|
|||
package org.baeldung.scopes;
|
||||
|
||||
public class Person {
|
||||
private String name;
|
||||
private int age;
|
||||
|
||||
public Person() {
|
||||
}
|
||||
|
||||
public Person(final String name, final int age) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(final String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Person [name=" + name + "]";
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,31 @@
|
|||
package org.baeldung.scopes;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
|
||||
import org.apache.log4j.Logger;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
|
||||
@Controller
|
||||
public class ScopesController {
|
||||
public static final Logger LOG = Logger.getLogger(ScopesController.class);
|
||||
|
||||
@Resource(name = "requestMessage")
|
||||
HelloMessageGenerator requestMessage;
|
||||
|
||||
@Resource(name = "sessionMessage")
|
||||
HelloMessageGenerator sessionMessage;
|
||||
|
||||
@RequestMapping("/scopes")
|
||||
public String getScopes(final Model model) {
|
||||
LOG.info("Request Message:" + requestMessage.getMessage());
|
||||
LOG.info("Session Message" + sessionMessage.getMessage());
|
||||
requestMessage.setMessage("Good morning!");
|
||||
sessionMessage.setMessage("Good afternoon!");
|
||||
model.addAttribute("requestMessage", requestMessage.getMessage());
|
||||
model.addAttribute("sessionMessage", sessionMessage.getMessage());
|
||||
return "scopesExample";
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,57 @@
|
|||
package org.baeldung.spring.config;
|
||||
|
||||
import org.baeldung.scopes.HelloMessageGenerator;
|
||||
import org.baeldung.scopes.Person;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Scope;
|
||||
import org.springframework.context.annotation.ScopedProxyMode;
|
||||
import org.springframework.web.context.WebApplicationContext;
|
||||
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
|
||||
import org.springframework.web.servlet.view.JstlView;
|
||||
import org.springframework.web.servlet.view.UrlBasedViewResolver;
|
||||
|
||||
@Configuration
|
||||
@ComponentScan("org.baeldung.scopes")
|
||||
@EnableWebMvc
|
||||
public class ScopesConfig {
|
||||
@Bean
|
||||
public UrlBasedViewResolver setupViewResolver() {
|
||||
final UrlBasedViewResolver resolver = new UrlBasedViewResolver();
|
||||
resolver.setPrefix("/WEB-INF/view/");
|
||||
resolver.setSuffix(".jsp");
|
||||
resolver.setViewClass(JstlView.class);
|
||||
return resolver;
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
|
||||
public HelloMessageGenerator requestMessage() {
|
||||
return new HelloMessageGenerator();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS)
|
||||
public HelloMessageGenerator sessionMessage() {
|
||||
return new HelloMessageGenerator();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Scope(value = WebApplicationContext.SCOPE_GLOBAL_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS)
|
||||
public HelloMessageGenerator globalSessionMessage() {
|
||||
return new HelloMessageGenerator();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Scope("prototype")
|
||||
public Person personPrototype() {
|
||||
return new Person();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Scope("singleton")
|
||||
public Person personSingleton() {
|
||||
return new Person();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,10 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beans xmlns="http://www.springframework.org/schema/beans"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
|
||||
|
||||
<bean id="personSingleton" class="org.baeldung.scopes.Person" scope="singleton"/>
|
||||
|
||||
<bean id="personPrototype" class="org.baeldung.scopes.Person" scope="prototype"/>
|
||||
|
||||
</beans>
|
|
@ -0,0 +1,10 @@
|
|||
<html>
|
||||
<head></head>
|
||||
|
||||
<body>
|
||||
<h1>Bean Scopes Examples</h1>
|
||||
<br>
|
||||
Request Message: ${requestMessage }<br>
|
||||
Session Message: ${sessionMessage }
|
||||
</body>
|
||||
</html>
|
|
@ -1,30 +0,0 @@
|
|||
package org.baeldung.caching.test;
|
||||
|
||||
import org.baeldung.caching.config.CachingConfig;
|
||||
import org.baeldung.caching.example.Customer;
|
||||
import org.baeldung.caching.example.CustomerDataService;
|
||||
import org.junit.Test;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
|
||||
|
||||
@Component
|
||||
public class SpringCachingBehaviorTest {
|
||||
|
||||
@Test
|
||||
public void testCaching() {
|
||||
@SuppressWarnings("resource")
|
||||
final
|
||||
// final ApplicationContext context = new ClassPathXmlApplicationContext("config.xml");
|
||||
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
|
||||
context.register(CachingConfig.class);
|
||||
context.refresh();
|
||||
final CustomerDataService service = context.getBean(CustomerDataService.class);
|
||||
|
||||
final Customer cust = new Customer("Tom", "67-2, Downing Street, NY");
|
||||
service.getAddress(cust);
|
||||
service.getAddress(cust);
|
||||
|
||||
// fail("Unable to instantiate the CustomerDataService");
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,71 @@
|
|||
package org.baeldung.caching.test;
|
||||
|
||||
import org.baeldung.caching.config.CachingConfig;
|
||||
import org.baeldung.caching.example.Customer;
|
||||
import org.baeldung.caching.example.CustomerDataService;
|
||||
import org.baeldung.caching.example.CustomerServiceWithParent;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.test.context.support.AnnotationConfigContextLoader;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = { CachingConfig.class }, loader = AnnotationConfigContextLoader.class)
|
||||
public class SpringCachingIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private CustomerDataService service;
|
||||
|
||||
@Autowired
|
||||
private CustomerServiceWithParent serviceWithParent;
|
||||
|
||||
//
|
||||
|
||||
@Test
|
||||
public void whenGettingAddress_thenCorrect() {
|
||||
final Customer cust = new Customer("Tom", "67-2, Downing Street, NY");
|
||||
service.getAddress(cust);
|
||||
service.getAddress(cust);
|
||||
|
||||
service.getAddress1(cust);
|
||||
service.getAddress1(cust);
|
||||
|
||||
service.getAddress2(cust);
|
||||
service.getAddress2(cust);
|
||||
|
||||
service.getAddress3(cust);
|
||||
service.getAddress3(cust);
|
||||
|
||||
service.getAddress4(cust);
|
||||
service.getAddress4(cust);
|
||||
|
||||
service.getAddress5(cust);
|
||||
service.getAddress5(cust);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingServiceWithParent_whenGettingAddress_thenCorrect() {
|
||||
final Customer cust = new Customer("Tom", "67-2, Downing Street, NY");
|
||||
|
||||
serviceWithParent.getAddress(cust);
|
||||
serviceWithParent.getAddress(cust);
|
||||
|
||||
serviceWithParent.getAddress1(cust);
|
||||
serviceWithParent.getAddress1(cust);
|
||||
|
||||
serviceWithParent.getAddress2(cust);
|
||||
serviceWithParent.getAddress2(cust);
|
||||
|
||||
serviceWithParent.getAddress3(cust);
|
||||
serviceWithParent.getAddress3(cust);
|
||||
|
||||
// serviceWithParent.getAddress4(cust);
|
||||
// serviceWithParent.getAddress4(cust);
|
||||
|
||||
serviceWithParent.getAddress5(cust);
|
||||
serviceWithParent.getAddress5(cust);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,43 @@
|
|||
package org.baeldung.scopes;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.support.AbstractApplicationContext;
|
||||
import org.springframework.context.support.ClassPathXmlApplicationContext;
|
||||
|
||||
public class ScopesTest {
|
||||
|
||||
private static final String NAME = "John Smith";
|
||||
private static final String NAME_OTHER = "Anna Jones";
|
||||
|
||||
@Test
|
||||
public void testScopeSingleton() {
|
||||
final ApplicationContext applicationContext = new ClassPathXmlApplicationContext("scopes.xml");
|
||||
|
||||
final Person personSingletonA = (Person) applicationContext.getBean("personSingleton");
|
||||
final Person personSingletonB = (Person) applicationContext.getBean("personSingleton");
|
||||
|
||||
personSingletonA.setName(NAME);
|
||||
Assert.assertEquals(NAME, personSingletonB.getName());
|
||||
|
||||
((AbstractApplicationContext) applicationContext).close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testScopePrototype() {
|
||||
final ApplicationContext applicationContext = new ClassPathXmlApplicationContext("scopes.xml");
|
||||
|
||||
final Person personPrototypeA = (Person) applicationContext.getBean("personPrototype");
|
||||
final Person personPrototypeB = (Person) applicationContext.getBean("personPrototype");
|
||||
|
||||
personPrototypeA.setName(NAME);
|
||||
personPrototypeB.setName(NAME_OTHER);
|
||||
|
||||
Assert.assertEquals(NAME, personPrototypeA.getName());
|
||||
Assert.assertEquals(NAME_OTHER, personPrototypeB.getName());
|
||||
|
||||
((AbstractApplicationContext) applicationContext).close();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,63 @@
|
|||
<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>spring-autowire</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<name>spring-autowire</name>
|
||||
<url>http://maven.apache.org</url>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<org.springframework.version>4.2.5.RELEASE</org.springframework.version>
|
||||
<maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version>
|
||||
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.11</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-core</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-context</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-test</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>spring-autowire</finalName>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${maven-surefire-plugin.version}</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
|
@ -0,0 +1,11 @@
|
|||
package com.baeldung.autowire.sample;
|
||||
|
||||
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
|
||||
|
||||
public class App {
|
||||
public static void main(String[] args) {
|
||||
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
|
||||
FooService fooService = ctx.getBean(FooService.class);
|
||||
fooService.doStuff();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,10 @@
|
|||
package com.baeldung.autowire.sample;
|
||||
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
@ComponentScan("com.baeldung.autowire.sample")
|
||||
public class AppConfig {
|
||||
|
||||
}
|
|
@ -0,0 +1,5 @@
|
|||
package com.baeldung.autowire.sample;
|
||||
|
||||
public class Bar {
|
||||
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
package com.baeldung.autowire.sample;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@FormatterType("Bar")
|
||||
@Component
|
||||
public class BarFormatter implements Formatter {
|
||||
|
||||
public String format() {
|
||||
return "bar";
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,5 @@
|
|||
package com.baeldung.autowire.sample;
|
||||
|
||||
public class Foo {
|
||||
|
||||
}
|
|
@ -0,0 +1,5 @@
|
|||
package com.baeldung.autowire.sample;
|
||||
|
||||
public class FooDAO {
|
||||
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
package com.baeldung.autowire.sample;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@FormatterType("Foo")
|
||||
@Component
|
||||
public class FooFormatter implements Formatter {
|
||||
|
||||
public String format() {
|
||||
return "foo";
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
package com.baeldung.autowire.sample;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class FooService {
|
||||
|
||||
@Autowired
|
||||
@FormatterType("Foo")
|
||||
private Formatter formatter;
|
||||
|
||||
public String doStuff(){
|
||||
return formatter.format();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
package com.baeldung.autowire.sample;
|
||||
|
||||
public interface Formatter {
|
||||
|
||||
String format();
|
||||
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
package com.baeldung.autowire.sample;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
|
||||
@Qualifier
|
||||
@Target({ElementType.FIELD, ElementType.METHOD,ElementType.TYPE, ElementType.PARAMETER})
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface FormatterType {
|
||||
|
||||
String value();
|
||||
|
||||
}
|
|
@ -0,0 +1,22 @@
|
|||
package com.baeldung.autowire.sample;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.test.context.support.AnnotationConfigContextLoader;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes=AppConfig.class, loader=AnnotationConfigContextLoader.class)
|
||||
public class FooServiceTest {
|
||||
|
||||
@Autowired
|
||||
FooService fooService;
|
||||
|
||||
@Test
|
||||
public void whenFooFormatterType_thenReturnFoo(){
|
||||
Assert.assertEquals("foo", fooService.doStuff());
|
||||
}
|
||||
}
|
|
@ -4,7 +4,7 @@
|
|||
<classpathentry kind="src" path="src/main/java"/>
|
||||
<classpathentry kind="src" output="target/test-classes" path="src/test/java"/>
|
||||
<classpathentry kind="src" path="src/test/resources"/>
|
||||
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
|
||||
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7"/>
|
||||
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER"/>
|
||||
<classpathentry kind="output" path="target/classes"/>
|
||||
</classpath>
|
||||
|
|
|
@ -2,11 +2,12 @@
|
|||
|
||||
### Relevant Articles:
|
||||
- [Spring Data Couchbase](http://www.baeldung.com/spring-data-couchbase)
|
||||
- [Entity Validation, Query Consistency, and Optimistic Locking in Spring Data Couchbase](http://www.baeldung.com/entity-validation-locking-and-query-consistency-in-spring-data-couchbase)
|
||||
|
||||
### Overview
|
||||
This Maven project contains the Java code for Spring Data Couchbase
|
||||
entities, repositories, and template-based services
|
||||
as described in the tutorial, as well as a unit test
|
||||
as described in the tutorials, as well as a unit/integration test
|
||||
for each service implementation.
|
||||
|
||||
### Working with the Code
|
||||
|
@ -22,13 +23,16 @@ mvn clean install
|
|||
```
|
||||
|
||||
### Running the tests
|
||||
There are three test classes in src/test/java in the package
|
||||
The following test classes are in src/test/java in the package
|
||||
org.baeldung.spring.data.couchbase.service:
|
||||
- PersonServiceTest (abstract)
|
||||
- PersonRepositoryTest (concrete)
|
||||
- PersonTemplateServiceTest (concrete)
|
||||
- StudentServiceTest (abstract)
|
||||
- StudentRepositoryTest (concrete)
|
||||
- StudentTemplateServiceTest (concrete)
|
||||
|
||||
The latter two may be run as JUnit tests from your IDE
|
||||
The concrete test classes may be run as JUnit tests from your IDE
|
||||
or using the Maven command line:
|
||||
```
|
||||
mvn test
|
||||
|
|
|
@ -93,7 +93,7 @@
|
|||
<java.version>1.7</java.version>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<spring-framework.version>4.2.4.RELEASE</spring-framework.version>
|
||||
<spring-data-couchbase.version>2.0.0.RELEASE</spring-data-couchbase.version>
|
||||
<spring-data-couchbase.version>2.1.1.RELEASE</spring-data-couchbase.version>
|
||||
<hibernate-validator.version>5.2.4.Final</hibernate-validator.version>
|
||||
<joda-time.version>2.9.2</joda-time.version>
|
||||
<logback.version>1.1.3</logback.version>
|
||||
|
|
|
@ -3,9 +3,13 @@ package org.baeldung.spring.data.couchbase;
|
|||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.data.couchbase.config.AbstractCouchbaseConfiguration;
|
||||
import org.springframework.data.couchbase.core.mapping.event.ValidatingCouchbaseEventListener;
|
||||
import org.springframework.data.couchbase.core.query.Consistency;
|
||||
import org.springframework.data.couchbase.repository.config.EnableCouchbaseRepositories;
|
||||
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
|
||||
|
||||
@Configuration
|
||||
@EnableCouchbaseRepositories(basePackages={"org.baeldung.spring.data.couchbase"})
|
||||
|
@ -29,4 +33,19 @@ public class MyCouchbaseConfig extends AbstractCouchbaseConfiguration {
|
|||
protected String getBucketPassword() {
|
||||
return BUCKET_PASSWORD;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Consistency getDefaultConsistency() {
|
||||
return Consistency.READ_YOUR_OWN_WRITES;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public LocalValidatorFactoryBean localValidatorFactoryBean() {
|
||||
return new LocalValidatorFactoryBean();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ValidatingCouchbaseEventListener validatingCouchbaseEventListener() {
|
||||
return new ValidatingCouchbaseEventListener(localValidatorFactoryBean());
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,113 @@
|
|||
package org.baeldung.spring.data.couchbase.model;
|
||||
|
||||
import javax.validation.constraints.NotNull;
|
||||
import javax.validation.constraints.Past;
|
||||
import javax.validation.constraints.Pattern;
|
||||
import javax.validation.constraints.Size;
|
||||
|
||||
import org.joda.time.DateTime;
|
||||
import org.springframework.data.annotation.Id;
|
||||
import org.springframework.data.annotation.Version;
|
||||
import org.springframework.data.couchbase.core.mapping.Document;
|
||||
|
||||
import com.couchbase.client.java.repository.annotation.Field;
|
||||
|
||||
@Document
|
||||
public class Student {
|
||||
private static final String NAME_REGEX = "^[a-zA-Z .'-]+$";
|
||||
|
||||
@Id
|
||||
private String id;
|
||||
@Field
|
||||
@NotNull
|
||||
@Size(min=1, max=20)
|
||||
@Pattern(regexp=NAME_REGEX)
|
||||
private String firstName;
|
||||
@Field
|
||||
@NotNull
|
||||
@Size(min=1, max=20)
|
||||
@Pattern(regexp=NAME_REGEX)
|
||||
private String lastName;
|
||||
@Field
|
||||
@Past
|
||||
private DateTime dateOfBirth;
|
||||
@Field
|
||||
@NotNull
|
||||
private DateTime created;
|
||||
@Field
|
||||
private DateTime updated;
|
||||
@Version
|
||||
private long version;
|
||||
|
||||
public Student() {}
|
||||
|
||||
public Student(String id, String firstName, String lastName, DateTime dateOfBirth) {
|
||||
this.id = id;
|
||||
this.firstName = firstName;
|
||||
this.lastName = lastName;
|
||||
this.dateOfBirth = dateOfBirth;
|
||||
}
|
||||
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
public void setId(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
public void setFirstName(String firstName) {
|
||||
this.firstName = firstName;
|
||||
}
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
public void setLastName(String lastName) {
|
||||
this.lastName = lastName;
|
||||
}
|
||||
public DateTime getDateOfBirth() {
|
||||
return dateOfBirth;
|
||||
}
|
||||
public void setDateOfBirth(DateTime dateOfBirth) {
|
||||
this.dateOfBirth = dateOfBirth;
|
||||
}
|
||||
public DateTime getCreated() {
|
||||
return created;
|
||||
}
|
||||
public void setCreated(DateTime created) {
|
||||
this.created = created;
|
||||
}
|
||||
public DateTime getUpdated() {
|
||||
return updated;
|
||||
}
|
||||
public void setUpdated(DateTime updated) {
|
||||
this.updated = updated;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int hash = 1;
|
||||
if(id != null) {
|
||||
hash = hash * 31 + id.hashCode();
|
||||
}
|
||||
if(firstName != null) {
|
||||
hash = hash * 31 + firstName.hashCode();
|
||||
}
|
||||
if(lastName != null) {
|
||||
hash = hash * 31 + lastName.hashCode();
|
||||
}
|
||||
if(dateOfBirth != null) {
|
||||
hash = hash * 31 + dateOfBirth.hashCode();
|
||||
}
|
||||
return hash;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if((obj == null) || (obj.getClass() != this.getClass())) return false;
|
||||
if(obj == this) return true;
|
||||
Student other = (Student) obj;
|
||||
return this.hashCode() == other.hashCode();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
package org.baeldung.spring.data.couchbase.repos;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.baeldung.spring.data.couchbase.model.Student;
|
||||
|
||||
public interface CustomStudentRepository {
|
||||
List<Student> findByFirstNameStartsWith(String s);
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue