commit
fd2791233b
84
core-java-8/src/main/java/com/baeldung/enums/Pizza.java
Normal file
84
core-java-8/src/main/java/com/baeldung/enums/Pizza.java
Normal file
@ -0,0 +1,84 @@
|
|||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
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> 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) {
|
||||||
|
EnumMap<PizzaStatusEnum, List<Pizza>> map = pzList.stream().collect(
|
||||||
|
Collectors.groupingBy(Pizza::getStatus,
|
||||||
|
() -> new EnumMap<PizzaStatusEnum, List<Pizza>>(PizzaStatusEnum.class), Collectors.toList()));
|
||||||
|
return map;
|
||||||
|
}
|
||||||
|
|
||||||
|
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,21 @@
|
|||||||
|
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,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
|
||||||
|
}
|
||||||
|
}
|
78
core-java-8/src/test/java/com/baeldung/enums/PizzaTest.java
Normal file
78
core-java-8/src/test/java/com/baeldung/enums/PizzaTest.java
Normal file
@ -0,0 +1,78 @@
|
|||||||
|
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>();
|
||||||
|
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>();
|
||||||
|
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>
|
<dependencies>
|
||||||
|
|
||||||
<!-- utils -->
|
<!-- utils -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>net.sourceforge.collections</groupId>
|
||||||
|
<artifactId>collections-generic</artifactId>
|
||||||
|
<version>4.01</version>
|
||||||
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.google.guava</groupId>
|
<groupId>com.google.guava</groupId>
|
||||||
<artifactId>guava</artifactId>
|
<artifactId>guava</artifactId>
|
||||||
|
117
core-java/src/main/java/com/baeldung/enums/Pizza.java
Normal file
117
core-java/src/main/java/com/baeldung/enums/Pizza.java
Normal file
@ -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);
|
||||||
|
}
|
||||||
|
}
|
2
jsf/.gitignore
vendored
Normal file
2
jsf/.gitignore
vendored
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
/target
|
||||||
|
*.iml
|
116
jsf/pom.xml
Normal file
116
jsf/pom.xml
Normal file
@ -0,0 +1,116 @@
|
|||||||
|
<?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>3.5.1</version>
|
||||||
|
<configuration>
|
||||||
|
<source>1.8</source>
|
||||||
|
<target>1.8</target>
|
||||||
|
</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>
|
||||||
|
</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() {
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
14
jsf/src/main/resources/logback.xml
Normal file
14
jsf/src/main/resources/logback.xml
Normal file
@ -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>
|
3
jsf/src/main/resources/messages.properties
Normal file
3
jsf/src/main/resources/messages.properties
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
message.valueRequired = This value is required
|
||||||
|
message.welcome = Baeldung | Register
|
||||||
|
label.saveButton = Save
|
2
jsf/src/main/webapp/META-INF/context.xml
Normal file
2
jsf/src/main/webapp/META-INF/context.xml
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<Context antiJARLocking="true" path="/Baeldung"/>
|
39
jsf/src/main/webapp/WEB-INF/faces-config.xml
Normal file
39
jsf/src/main/webapp/WEB-INF/faces-config.xml
Normal file
@ -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>
|
28
jsf/src/main/webapp/index.xhtml
Normal file
28
jsf/src/main/webapp/index.xhtml
Normal file
@ -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>
|
||||||
|
|
1
pom.xml
1
pom.xml
@ -64,6 +64,7 @@
|
|||||||
<module>spring-security-rest-full</module>
|
<module>spring-security-rest-full</module>
|
||||||
<module>spring-thymeleaf</module>
|
<module>spring-thymeleaf</module>
|
||||||
<module>spring-zuul</module>
|
<module>spring-zuul</module>
|
||||||
|
<module>jsf</module>
|
||||||
|
|
||||||
</modules>
|
</modules>
|
||||||
|
|
||||||
|
@ -4,7 +4,7 @@
|
|||||||
<classpathentry kind="src" path="src/main/java"/>
|
<classpathentry kind="src" path="src/main/java"/>
|
||||||
<classpathentry kind="src" output="target/test-classes" path="src/test/java"/>
|
<classpathentry kind="src" output="target/test-classes" path="src/test/java"/>
|
||||||
<classpathentry kind="src" path="src/test/resources"/>
|
<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="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER"/>
|
||||||
<classpathentry kind="output" path="target/classes"/>
|
<classpathentry kind="output" path="target/classes"/>
|
||||||
</classpath>
|
</classpath>
|
||||||
|
@ -3,9 +3,13 @@ package org.baeldung.spring.data.couchbase;
|
|||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
import org.springframework.context.annotation.Configuration;
|
import org.springframework.context.annotation.Configuration;
|
||||||
import org.springframework.data.couchbase.config.AbstractCouchbaseConfiguration;
|
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.data.couchbase.repository.config.EnableCouchbaseRepositories;
|
||||||
|
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
|
||||||
|
|
||||||
@Configuration
|
@Configuration
|
||||||
@EnableCouchbaseRepositories(basePackages={"org.baeldung.spring.data.couchbase"})
|
@EnableCouchbaseRepositories(basePackages={"org.baeldung.spring.data.couchbase"})
|
||||||
@ -29,4 +33,19 @@ public class MyCouchbaseConfig extends AbstractCouchbaseConfiguration {
|
|||||||
protected String getBucketPassword() {
|
protected String getBucketPassword() {
|
||||||
return BUCKET_PASSWORD;
|
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);
|
||||||
|
}
|
@ -0,0 +1,25 @@
|
|||||||
|
package org.baeldung.spring.data.couchbase.repos;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.baeldung.spring.data.couchbase.model.Student;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.data.couchbase.core.CouchbaseTemplate;
|
||||||
|
|
||||||
|
import com.couchbase.client.java.view.Stale;
|
||||||
|
import com.couchbase.client.java.view.ViewQuery;
|
||||||
|
|
||||||
|
public class CustomStudentRepositoryImpl implements CustomStudentRepository {
|
||||||
|
|
||||||
|
private static final String DESIGN_DOC = "student";
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private CouchbaseTemplate template;
|
||||||
|
|
||||||
|
public List<Student> findByFirstNameStartsWith(String s) {
|
||||||
|
return template.findByView(ViewQuery.from(DESIGN_DOC, "byFirstName")
|
||||||
|
.startKey(s)
|
||||||
|
.stale(Stale.FALSE),
|
||||||
|
Student.class);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,11 @@
|
|||||||
|
package org.baeldung.spring.data.couchbase.repos;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.baeldung.spring.data.couchbase.model.Student;
|
||||||
|
import org.springframework.data.repository.CrudRepository;
|
||||||
|
|
||||||
|
public interface StudentRepository extends CrudRepository<Student, String>, CustomStudentRepository {
|
||||||
|
List<Student> findByFirstName(String firstName);
|
||||||
|
List<Student> findByLastName(String lastName);
|
||||||
|
}
|
@ -0,0 +1,58 @@
|
|||||||
|
package org.baeldung.spring.data.couchbase.service;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Iterator;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.baeldung.spring.data.couchbase.model.Student;
|
||||||
|
import org.baeldung.spring.data.couchbase.repos.StudentRepository;
|
||||||
|
import org.joda.time.DateTime;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.beans.factory.annotation.Qualifier;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
@Qualifier("StudentRepositoryService")
|
||||||
|
public class StudentRepositoryService implements StudentService {
|
||||||
|
|
||||||
|
private StudentRepository repo;
|
||||||
|
@Autowired
|
||||||
|
public void setStudentRepository(StudentRepository repo) {
|
||||||
|
this.repo = repo;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Student findOne(String id) {
|
||||||
|
return repo.findOne(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<Student> findAll() {
|
||||||
|
List<Student> people = new ArrayList<Student>();
|
||||||
|
Iterator<Student> it = repo.findAll().iterator();
|
||||||
|
while(it.hasNext()) {
|
||||||
|
people.add(it.next());
|
||||||
|
}
|
||||||
|
return people;
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<Student> findByFirstName(String firstName) {
|
||||||
|
return repo.findByFirstName(firstName);
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<Student> findByLastName(String lastName) {
|
||||||
|
return repo.findByLastName(lastName);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void create(Student student) {
|
||||||
|
student.setCreated(DateTime.now());
|
||||||
|
repo.save(student);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void update(Student student) {
|
||||||
|
student.setUpdated(DateTime.now());
|
||||||
|
repo.save(student);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void delete(Student student) {
|
||||||
|
repo.delete(student);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,22 @@
|
|||||||
|
package org.baeldung.spring.data.couchbase.service;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.baeldung.spring.data.couchbase.model.Student;
|
||||||
|
|
||||||
|
public interface StudentService {
|
||||||
|
|
||||||
|
Student findOne(String id);
|
||||||
|
|
||||||
|
List<Student> findAll();
|
||||||
|
|
||||||
|
List<Student> findByFirstName(String firstName);
|
||||||
|
|
||||||
|
List<Student> findByLastName(String lastName);
|
||||||
|
|
||||||
|
void create(Student student);
|
||||||
|
|
||||||
|
void update(Student student);
|
||||||
|
|
||||||
|
void delete(Student student);
|
||||||
|
}
|
@ -0,0 +1,55 @@
|
|||||||
|
package org.baeldung.spring.data.couchbase.service;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.baeldung.spring.data.couchbase.model.Student;
|
||||||
|
import org.joda.time.DateTime;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.beans.factory.annotation.Qualifier;
|
||||||
|
import org.springframework.data.couchbase.core.CouchbaseTemplate;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import com.couchbase.client.java.view.ViewQuery;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
@Qualifier("StudentTemplateService")
|
||||||
|
public class StudentTemplateService implements StudentService {
|
||||||
|
|
||||||
|
private static final String DESIGN_DOC = "student";
|
||||||
|
|
||||||
|
private CouchbaseTemplate template;
|
||||||
|
@Autowired
|
||||||
|
public void setCouchbaseTemplate(CouchbaseTemplate template) {
|
||||||
|
this.template = template;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Student findOne(String id) {
|
||||||
|
return template.findById(id, Student.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<Student> findAll() {
|
||||||
|
return template.findByView(ViewQuery.from(DESIGN_DOC, "all"), Student.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<Student> findByFirstName(String firstName) {
|
||||||
|
return template.findByView(ViewQuery.from(DESIGN_DOC, "byFirstName"), Student.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<Student> findByLastName(String lastName) {
|
||||||
|
return template.findByView(ViewQuery.from(DESIGN_DOC, "byLastName"), Student.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void create(Student student) {
|
||||||
|
student.setCreated(DateTime.now());
|
||||||
|
template.insert(student);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void update(Student student) {
|
||||||
|
student.setUpdated(DateTime.now());
|
||||||
|
template.update(student);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void delete(Student student) {
|
||||||
|
template.remove(student);
|
||||||
|
}
|
||||||
|
}
|
@ -1,6 +1,7 @@
|
|||||||
package org.baeldung.spring.data.couchbase;
|
package org.baeldung.spring.data.couchbase;
|
||||||
|
|
||||||
import org.springframework.data.couchbase.core.convert.MappingCouchbaseConverter;
|
import org.springframework.data.couchbase.core.convert.MappingCouchbaseConverter;
|
||||||
|
import org.springframework.data.couchbase.core.query.Consistency;
|
||||||
|
|
||||||
public class TestCouchbaseConfig extends MyCouchbaseConfig {
|
public class TestCouchbaseConfig extends MyCouchbaseConfig {
|
||||||
|
|
||||||
@ -8,4 +9,9 @@ public class TestCouchbaseConfig extends MyCouchbaseConfig {
|
|||||||
public String typeKey() {
|
public String typeKey() {
|
||||||
return MappingCouchbaseConverter.TYPEKEY_SYNCGATEWAY_COMPATIBLE;
|
return MappingCouchbaseConverter.TYPEKEY_SYNCGATEWAY_COMPATIBLE;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Consistency getDefaultConsistency() {
|
||||||
|
return Consistency.READ_YOUR_OWN_WRITES;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -0,0 +1,13 @@
|
|||||||
|
package org.baeldung.spring.data.couchbase.service;
|
||||||
|
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.beans.factory.annotation.Qualifier;
|
||||||
|
|
||||||
|
public class StudentRepositoryServiceTest extends StudentServiceTest {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
@Qualifier("StudentRepositoryService")
|
||||||
|
public void setStudentService(StudentService service) {
|
||||||
|
this.studentService = service;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,166 @@
|
|||||||
|
package org.baeldung.spring.data.couchbase.service;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
import static org.junit.Assert.assertNotNull;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import javax.validation.ConstraintViolationException;
|
||||||
|
|
||||||
|
import org.baeldung.spring.data.couchbase.IntegrationTest;
|
||||||
|
import org.baeldung.spring.data.couchbase.MyCouchbaseConfig;
|
||||||
|
import org.baeldung.spring.data.couchbase.model.Student;
|
||||||
|
import org.joda.time.DateTime;
|
||||||
|
import org.junit.BeforeClass;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.couchbase.client.java.Bucket;
|
||||||
|
import com.couchbase.client.java.Cluster;
|
||||||
|
import com.couchbase.client.java.CouchbaseCluster;
|
||||||
|
import com.couchbase.client.java.document.JsonDocument;
|
||||||
|
import com.couchbase.client.java.document.json.JsonObject;
|
||||||
|
|
||||||
|
public abstract class StudentServiceTest extends IntegrationTest {
|
||||||
|
|
||||||
|
static final String typeField = "_class";
|
||||||
|
static final String joe = "Joe";
|
||||||
|
static final String college = "College";
|
||||||
|
static final String joeCollegeId = "student:" + joe + ":" + college;
|
||||||
|
static final DateTime joeCollegeDob = DateTime.now().minusYears(21);
|
||||||
|
static final Student joeCollege = new Student(joeCollegeId, joe, college, joeCollegeDob);
|
||||||
|
static final JsonObject jsonJoeCollege = JsonObject.empty()
|
||||||
|
.put(typeField, Student.class.getName())
|
||||||
|
.put("firstName", joe)
|
||||||
|
.put("lastName", college)
|
||||||
|
.put("created", DateTime.now().getMillis())
|
||||||
|
.put("version", 1);
|
||||||
|
|
||||||
|
static final String judy = "Judy";
|
||||||
|
static final String jetson = "Jetson";
|
||||||
|
static final String judyJetsonId = "student:" + judy + ":" + jetson;
|
||||||
|
static final DateTime judyJetsonDob = DateTime.now().minusYears(19).minusMonths(5).minusDays(3);
|
||||||
|
static final Student judyJetson = new Student(judyJetsonId, judy, jetson, judyJetsonDob);
|
||||||
|
static final JsonObject jsonJudyJetson = JsonObject.empty()
|
||||||
|
.put(typeField, Student.class.getName())
|
||||||
|
.put("firstName", judy)
|
||||||
|
.put("lastName", jetson)
|
||||||
|
.put("created", DateTime.now().getMillis())
|
||||||
|
.put("version", 1);
|
||||||
|
|
||||||
|
StudentService studentService;
|
||||||
|
|
||||||
|
@BeforeClass
|
||||||
|
public static void setupBeforeClass() {
|
||||||
|
Cluster cluster = CouchbaseCluster.create(MyCouchbaseConfig.NODE_LIST);
|
||||||
|
Bucket bucket = cluster.openBucket(MyCouchbaseConfig.BUCKET_NAME, MyCouchbaseConfig.BUCKET_PASSWORD);
|
||||||
|
bucket.upsert(JsonDocument.create(joeCollegeId, jsonJoeCollege));
|
||||||
|
bucket.upsert(JsonDocument.create(judyJetsonId, jsonJudyJetson));
|
||||||
|
bucket.close();
|
||||||
|
cluster.disconnect();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenCreatingStudent_thenDocumentIsPersisted() {
|
||||||
|
String firstName = "Eric";
|
||||||
|
String lastName = "Stratton";
|
||||||
|
DateTime dateOfBirth = DateTime.now().minusYears(25);
|
||||||
|
String id = "student:" + firstName + ":" + lastName;
|
||||||
|
Student expectedStudent = new Student(id, firstName, lastName, dateOfBirth);
|
||||||
|
studentService.create(expectedStudent);
|
||||||
|
Student actualStudent = studentService.findOne(id);
|
||||||
|
assertNotNull(actualStudent.getCreated());
|
||||||
|
assertNotNull(actualStudent);
|
||||||
|
assertEquals(expectedStudent.getId(), actualStudent.getId());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected=ConstraintViolationException.class)
|
||||||
|
public void whenCreatingStudentWithInvalidFirstName_thenConstraintViolationException() {
|
||||||
|
String firstName = "Er+ic";
|
||||||
|
String lastName = "Stratton";
|
||||||
|
DateTime dateOfBirth = DateTime.now().minusYears(25);
|
||||||
|
String id = "student:" + firstName + ":" + lastName;
|
||||||
|
Student student = new Student(id, firstName, lastName, dateOfBirth);
|
||||||
|
studentService.create(student);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected=ConstraintViolationException.class)
|
||||||
|
public void whenCreatingStudentWithFutureDob_thenConstraintViolationException() {
|
||||||
|
String firstName = "Jane";
|
||||||
|
String lastName = "Doe";
|
||||||
|
DateTime dateOfBirth = DateTime.now().plusDays(1);
|
||||||
|
String id = "student:" + firstName + ":" + lastName;
|
||||||
|
Student student = new Student(id, firstName, lastName, dateOfBirth);
|
||||||
|
studentService.create(student);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenFindingStudentByJohnSmithId_thenReturnsJohnSmith() {
|
||||||
|
Student actualStudent = studentService.findOne(joeCollegeId);
|
||||||
|
assertNotNull(actualStudent);
|
||||||
|
assertNotNull(actualStudent.getCreated());
|
||||||
|
assertEquals(joeCollegeId, actualStudent.getId());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenFindingAllStudents_thenReturnsTwoOrMoreStudentsIncludingJoeCollegeAndJudyJetson() {
|
||||||
|
List<Student> resultList = studentService.findAll();
|
||||||
|
assertNotNull(resultList);
|
||||||
|
assertFalse(resultList.isEmpty());
|
||||||
|
assertTrue(resultContains(resultList, joeCollege));
|
||||||
|
assertTrue(resultContains(resultList, judyJetson));
|
||||||
|
assertTrue(resultList.size() >= 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenFindingByFirstNameJohn_thenReturnsOnlyStudentsNamedJohn() {
|
||||||
|
String expectedFirstName = joe;
|
||||||
|
List<Student> resultList = studentService.findByFirstName(expectedFirstName);
|
||||||
|
assertNotNull(resultList);
|
||||||
|
assertFalse(resultList.isEmpty());
|
||||||
|
assertTrue(allResultsContainExpectedFirstName(resultList, expectedFirstName));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenFindingByLastNameSmith_thenReturnsOnlyStudentsNamedSmith() {
|
||||||
|
String expectedLastName = college;
|
||||||
|
List<Student> resultList = studentService.findByLastName(expectedLastName);
|
||||||
|
assertNotNull(resultList);
|
||||||
|
assertFalse(resultList.isEmpty());
|
||||||
|
assertTrue(allResultsContainExpectedLastName(resultList, expectedLastName));
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean resultContains(List<Student> resultList, Student student) {
|
||||||
|
boolean found = false;
|
||||||
|
for(Student p : resultList) {
|
||||||
|
if(p.getId().equals(student.getId())) {
|
||||||
|
found = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return found;
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean allResultsContainExpectedFirstName(List<Student> resultList, String firstName) {
|
||||||
|
boolean found = false;
|
||||||
|
for(Student p : resultList) {
|
||||||
|
if(p.getFirstName().equals(firstName)) {
|
||||||
|
found = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return found;
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean allResultsContainExpectedLastName(List<Student> resultList, String lastName) {
|
||||||
|
boolean found = false;
|
||||||
|
for(Student p : resultList) {
|
||||||
|
if(p.getLastName().equals(lastName)) {
|
||||||
|
found = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return found;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,13 @@
|
|||||||
|
package org.baeldung.spring.data.couchbase.service;
|
||||||
|
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.beans.factory.annotation.Qualifier;
|
||||||
|
|
||||||
|
public class StudentTemplateServiceTest extends StudentServiceTest {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
@Qualifier("StudentTemplateService")
|
||||||
|
public void setStudentService(StudentService service) {
|
||||||
|
this.studentService = service;
|
||||||
|
}
|
||||||
|
}
|
31
spring-data-elasticsearch/.classpath
Normal file
31
spring-data-elasticsearch/.classpath
Normal file
@ -0,0 +1,31 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<classpath>
|
||||||
|
<classpathentry kind="src" output="target/classes" path="src/main/java">
|
||||||
|
<attributes>
|
||||||
|
<attribute name="optional" value="true"/>
|
||||||
|
<attribute name="maven.pomderived" value="true"/>
|
||||||
|
</attributes>
|
||||||
|
</classpathentry>
|
||||||
|
<classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources">
|
||||||
|
<attributes>
|
||||||
|
<attribute name="maven.pomderived" value="true"/>
|
||||||
|
</attributes>
|
||||||
|
</classpathentry>
|
||||||
|
<classpathentry kind="src" output="target/test-classes" path="src/test/java">
|
||||||
|
<attributes>
|
||||||
|
<attribute name="optional" value="true"/>
|
||||||
|
<attribute name="maven.pomderived" value="true"/>
|
||||||
|
</attributes>
|
||||||
|
</classpathentry>
|
||||||
|
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8">
|
||||||
|
<attributes>
|
||||||
|
<attribute name="maven.pomderived" value="true"/>
|
||||||
|
</attributes>
|
||||||
|
</classpathentry>
|
||||||
|
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
|
||||||
|
<attributes>
|
||||||
|
<attribute name="maven.pomderived" value="true"/>
|
||||||
|
</attributes>
|
||||||
|
</classpathentry>
|
||||||
|
<classpathentry kind="output" path="target/classes"/>
|
||||||
|
</classpath>
|
29
spring-data-elasticsearch/.project
Normal file
29
spring-data-elasticsearch/.project
Normal file
@ -0,0 +1,29 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<projectDescription>
|
||||||
|
<name>spring-data-elasticsearch</name>
|
||||||
|
<comment></comment>
|
||||||
|
<projects>
|
||||||
|
</projects>
|
||||||
|
<buildSpec>
|
||||||
|
<buildCommand>
|
||||||
|
<name>org.eclipse.jdt.core.javabuilder</name>
|
||||||
|
<arguments>
|
||||||
|
</arguments>
|
||||||
|
</buildCommand>
|
||||||
|
<buildCommand>
|
||||||
|
<name>org.eclipse.m2e.core.maven2Builder</name>
|
||||||
|
<arguments>
|
||||||
|
</arguments>
|
||||||
|
</buildCommand>
|
||||||
|
<buildCommand>
|
||||||
|
<name>org.springframework.ide.eclipse.core.springbuilder</name>
|
||||||
|
<arguments>
|
||||||
|
</arguments>
|
||||||
|
</buildCommand>
|
||||||
|
</buildSpec>
|
||||||
|
<natures>
|
||||||
|
<nature>org.springframework.ide.eclipse.core.springnature</nature>
|
||||||
|
<nature>org.eclipse.jdt.core.javanature</nature>
|
||||||
|
<nature>org.eclipse.m2e.core.maven2Nature</nature>
|
||||||
|
</natures>
|
||||||
|
</projectDescription>
|
@ -18,7 +18,7 @@
|
|||||||
<junit.version>4.11</junit.version>
|
<junit.version>4.11</junit.version>
|
||||||
<org.slf4j.version>1.7.12</org.slf4j.version>
|
<org.slf4j.version>1.7.12</org.slf4j.version>
|
||||||
<logback.version>1.1.3</logback.version>
|
<logback.version>1.1.3</logback.version>
|
||||||
<elasticsearch.version>1.3.2.RELEASE</elasticsearch.version>
|
<elasticsearch.version>2.0.1.RELEASE</elasticsearch.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
@ -44,6 +44,11 @@
|
|||||||
<artifactId>spring-data-elasticsearch</artifactId>
|
<artifactId>spring-data-elasticsearch</artifactId>
|
||||||
<version>${elasticsearch.version}</version>
|
<version>${elasticsearch.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency> <groupId>net.java.dev.jna</groupId>
|
||||||
|
<artifactId>jna</artifactId>
|
||||||
|
<version>4.1.0</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.slf4j</groupId>
|
<groupId>org.slf4j</groupId>
|
||||||
<artifactId>slf4j-api</artifactId>
|
<artifactId>slf4j-api</artifactId>
|
||||||
|
@ -1,10 +1,16 @@
|
|||||||
package com.baeldung.spring.data.es.config;
|
package com.baeldung.spring.data.es.config;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.Paths;
|
||||||
|
|
||||||
import org.elasticsearch.client.Client;
|
import org.elasticsearch.client.Client;
|
||||||
import org.elasticsearch.common.settings.ImmutableSettings;
|
import org.elasticsearch.common.settings.Settings;
|
||||||
import org.elasticsearch.node.NodeBuilder;
|
import org.elasticsearch.node.NodeBuilder;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
import org.springframework.context.annotation.Bean;
|
import org.springframework.context.annotation.Bean;
|
||||||
import org.springframework.context.annotation.ComponentScan;
|
import org.springframework.context.annotation.ComponentScan;
|
||||||
import org.springframework.context.annotation.Configuration;
|
import org.springframework.context.annotation.Configuration;
|
||||||
@ -12,35 +18,33 @@ import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
|
|||||||
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
|
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
|
||||||
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;
|
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.nio.file.Files;
|
|
||||||
import java.nio.file.Path;
|
|
||||||
import java.nio.file.Paths;
|
|
||||||
|
|
||||||
@Configuration
|
@Configuration
|
||||||
@EnableElasticsearchRepositories(basePackages = "com.baeldung.spring.data.es.repository")
|
@EnableElasticsearchRepositories(basePackages = "com.baeldung.spring.data.es.repository")
|
||||||
@ComponentScan(basePackages = {"com.baeldung.spring.data.es.service"})
|
@ComponentScan(basePackages = { "com.baeldung.spring.data.es.service" })
|
||||||
public class Config {
|
public class Config {
|
||||||
|
|
||||||
|
@Value("${elasticsearch.home:/usr/local/Cellar/elasticsearch/2.3.2}")
|
||||||
|
private String elasticsearchHome;
|
||||||
|
|
||||||
private static Logger logger = LoggerFactory.getLogger(Config.class);
|
private static Logger logger = LoggerFactory.getLogger(Config.class);
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
public Client client() {
|
public Client client() {
|
||||||
try {
|
try {
|
||||||
Path tmpDir = Files.createTempDirectory(Paths.get(System.getProperty("java.io.tmpdir")), "elasticsearch_data");
|
final Path tmpDir = Files.createTempDirectory(Paths.get(System.getProperty("java.io.tmpdir")), "elasticsearch_data");
|
||||||
|
|
||||||
ImmutableSettings.Builder elasticsearchSettings = ImmutableSettings.settingsBuilder()
|
// @formatter:off
|
||||||
.put("http.enabled", "false")
|
|
||||||
.put("path.data", tmpDir.toAbsolutePath().toString());
|
final Settings.Builder elasticsearchSettings =
|
||||||
|
Settings.settingsBuilder().put("http.enabled", "false")
|
||||||
|
.put("path.data", tmpDir.toAbsolutePath().toString())
|
||||||
|
.put("path.home", elasticsearchHome);
|
||||||
|
// @formatter:on
|
||||||
|
|
||||||
logger.debug(tmpDir.toAbsolutePath().toString());
|
logger.debug(tmpDir.toAbsolutePath().toString());
|
||||||
|
|
||||||
return new NodeBuilder()
|
return new NodeBuilder().local(true).settings(elasticsearchSettings.build()).node().client();
|
||||||
.local(true)
|
} catch (final IOException ioex) {
|
||||||
.settings(elasticsearchSettings.build())
|
|
||||||
.node()
|
|
||||||
.client();
|
|
||||||
} catch (IOException ioex) {
|
|
||||||
logger.error("Cannot create temp dir", ioex);
|
logger.error("Cannot create temp dir", ioex);
|
||||||
throw new RuntimeException();
|
throw new RuntimeException();
|
||||||
}
|
}
|
||||||
|
@ -1,27 +1,25 @@
|
|||||||
package com.baeldung.spring.data.es.model;
|
package com.baeldung.spring.data.es.model;
|
||||||
|
|
||||||
import org.springframework.data.annotation.Id;
|
|
||||||
import org.springframework.data.elasticsearch.annotations.*;
|
|
||||||
|
|
||||||
import java.util.Arrays;
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
import static org.springframework.data.elasticsearch.annotations.FieldIndex.not_analyzed;
|
import static org.springframework.data.elasticsearch.annotations.FieldIndex.not_analyzed;
|
||||||
import static org.springframework.data.elasticsearch.annotations.FieldType.Nested;
|
import static org.springframework.data.elasticsearch.annotations.FieldType.Nested;
|
||||||
import static org.springframework.data.elasticsearch.annotations.FieldType.String;
|
import static org.springframework.data.elasticsearch.annotations.FieldType.String;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.springframework.data.annotation.Id;
|
||||||
|
import org.springframework.data.elasticsearch.annotations.Document;
|
||||||
|
import org.springframework.data.elasticsearch.annotations.Field;
|
||||||
|
import org.springframework.data.elasticsearch.annotations.InnerField;
|
||||||
|
import org.springframework.data.elasticsearch.annotations.MultiField;
|
||||||
|
|
||||||
@Document(indexName = "blog", type = "article")
|
@Document(indexName = "blog", type = "article")
|
||||||
public class Article {
|
public class Article {
|
||||||
|
|
||||||
@Id
|
@Id
|
||||||
private String id;
|
private String id;
|
||||||
|
|
||||||
@MultiField(
|
@MultiField(mainField = @Field(type = String), otherFields = { @InnerField(index = not_analyzed, suffix = "verbatim", type = String) })
|
||||||
mainField = @Field(type = String),
|
|
||||||
otherFields = {
|
|
||||||
@NestedField(index = not_analyzed, dotSuffix = "verbatim", type = String)
|
|
||||||
}
|
|
||||||
)
|
|
||||||
private String title;
|
private String title;
|
||||||
|
|
||||||
@Field(type = Nested)
|
@Field(type = Nested)
|
||||||
@ -71,11 +69,6 @@ public class Article {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return "Article{" +
|
return "Article{" + "id='" + id + '\'' + ", title='" + title + '\'' + ", authors=" + authors + ", tags=" + Arrays.toString(tags) + '}';
|
||||||
"id='" + id + '\'' +
|
|
||||||
", title='" + title + '\'' +
|
|
||||||
", authors=" + authors +
|
|
||||||
", tags=" + Arrays.toString(tags) +
|
|
||||||
'}';
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -21,8 +21,6 @@ public class Author {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return "Author{" +
|
return "Author{" + "name='" + name + '\'' + '}';
|
||||||
"name='" + name + '\'' +
|
|
||||||
'}';
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -6,10 +6,16 @@ import org.springframework.data.domain.Pageable;
|
|||||||
|
|
||||||
public interface ArticleService {
|
public interface ArticleService {
|
||||||
Article save(Article article);
|
Article save(Article article);
|
||||||
|
|
||||||
Article findOne(String id);
|
Article findOne(String id);
|
||||||
|
|
||||||
Iterable<Article> findAll();
|
Iterable<Article> findAll();
|
||||||
|
|
||||||
Page<Article> findByAuthorName(String name, Pageable pageable);
|
Page<Article> findByAuthorName(String name, Pageable pageable);
|
||||||
|
|
||||||
Page<Article> findByAuthorNameUsingCustomQuery(String name, Pageable pageable);
|
Page<Article> findByAuthorNameUsingCustomQuery(String name, Pageable pageable);
|
||||||
|
|
||||||
long count();
|
long count();
|
||||||
|
|
||||||
void delete(Article article);
|
void delete(Article article);
|
||||||
}
|
}
|
||||||
|
@ -49,6 +49,6 @@ public class ArticleServiceImpl implements ArticleService {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void delete(Article article) {
|
public void delete(Article article) {
|
||||||
articleRepository.delete(article);
|
articleRepository.delete(article);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,12 +1,20 @@
|
|||||||
package com.baeldung.spring.data.es;
|
package com.baeldung.spring.data.es;
|
||||||
|
|
||||||
import com.baeldung.spring.data.es.config.Config;
|
import static java.util.Arrays.asList;
|
||||||
import com.baeldung.spring.data.es.model.Article;
|
import static java.util.stream.Collectors.toList;
|
||||||
import com.baeldung.spring.data.es.model.Author;
|
import static org.elasticsearch.index.query.MatchQueryBuilder.Operator.AND;
|
||||||
import com.baeldung.spring.data.es.service.ArticleService;
|
import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
|
||||||
import org.elasticsearch.action.ActionFuture;
|
import static org.elasticsearch.index.query.QueryBuilders.matchPhraseQuery;
|
||||||
import org.elasticsearch.action.index.IndexRequest;
|
import static org.elasticsearch.index.query.QueryBuilders.matchQuery;
|
||||||
import org.elasticsearch.action.index.IndexResponse;
|
import static org.elasticsearch.index.query.QueryBuilders.multiMatchQuery;
|
||||||
|
import static org.elasticsearch.index.query.QueryBuilders.nestedQuery;
|
||||||
|
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
import org.elasticsearch.action.search.SearchResponse;
|
import org.elasticsearch.action.search.SearchResponse;
|
||||||
import org.elasticsearch.client.Client;
|
import org.elasticsearch.client.Client;
|
||||||
import org.elasticsearch.common.unit.Fuzziness;
|
import org.elasticsearch.common.unit.Fuzziness;
|
||||||
@ -28,19 +36,13 @@ import org.springframework.test.context.ContextConfiguration;
|
|||||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||||
import org.springframework.test.context.support.AnnotationConfigContextLoader;
|
import org.springframework.test.context.support.AnnotationConfigContextLoader;
|
||||||
|
|
||||||
import java.util.Collections;
|
import com.baeldung.spring.data.es.config.Config;
|
||||||
import java.util.List;
|
import com.baeldung.spring.data.es.model.Article;
|
||||||
import java.util.Map;
|
import com.baeldung.spring.data.es.model.Author;
|
||||||
import java.util.concurrent.TimeUnit;
|
import com.baeldung.spring.data.es.service.ArticleService;
|
||||||
|
|
||||||
import static java.util.Arrays.asList;
|
|
||||||
import static java.util.stream.Collectors.toList;
|
|
||||||
import static org.elasticsearch.index.query.MatchQueryBuilder.Operator.AND;
|
|
||||||
import static org.elasticsearch.index.query.QueryBuilders.*;
|
|
||||||
import static org.junit.Assert.assertEquals;
|
|
||||||
|
|
||||||
@RunWith(SpringJUnit4ClassRunner.class)
|
@RunWith(SpringJUnit4ClassRunner.class)
|
||||||
@ContextConfiguration(classes = {Config.class}, loader = AnnotationConfigContextLoader.class)
|
@ContextConfiguration(classes = { Config.class }, loader = AnnotationConfigContextLoader.class)
|
||||||
public class ElasticSearchQueryTest {
|
public class ElasticSearchQueryTest {
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
@ -60,7 +62,7 @@ public class ElasticSearchQueryTest {
|
|||||||
elasticsearchTemplate.deleteIndex(Article.class);
|
elasticsearchTemplate.deleteIndex(Article.class);
|
||||||
elasticsearchTemplate.createIndex(Article.class);
|
elasticsearchTemplate.createIndex(Article.class);
|
||||||
elasticsearchTemplate.putMapping(Article.class);
|
elasticsearchTemplate.putMapping(Article.class);
|
||||||
elasticsearchTemplate.refresh(Article.class, true);
|
elasticsearchTemplate.refresh(Article.class);
|
||||||
|
|
||||||
Article article = new Article("Spring Data Elasticsearch");
|
Article article = new Article("Spring Data Elasticsearch");
|
||||||
article.setAuthors(asList(johnSmith, johnDoe));
|
article.setAuthors(asList(johnSmith, johnDoe));
|
||||||
@ -85,127 +87,92 @@ public class ElasticSearchQueryTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenFullTitle_whenRunMatchQuery_thenDocIsFound() {
|
public void givenFullTitle_whenRunMatchQuery_thenDocIsFound() {
|
||||||
SearchQuery searchQuery = new NativeSearchQueryBuilder()
|
final SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery("title", "Search engines").operator(AND)).build();
|
||||||
.withQuery(matchQuery("title", "Search engines").operator(AND))
|
final List<Article> articles = elasticsearchTemplate.queryForList(searchQuery, Article.class);
|
||||||
.build();
|
|
||||||
List<Article> articles = elasticsearchTemplate
|
|
||||||
.queryForList(searchQuery, Article.class);
|
|
||||||
assertEquals(1, articles.size());
|
assertEquals(1, articles.size());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenOneTermFromTitle_whenRunMatchQuery_thenDocIsFound() {
|
public void givenOneTermFromTitle_whenRunMatchQuery_thenDocIsFound() {
|
||||||
SearchQuery searchQuery = new NativeSearchQueryBuilder()
|
final SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery("title", "Engines Solutions")).build();
|
||||||
.withQuery(matchQuery("title", "Engines Solutions"))
|
final List<Article> articles = elasticsearchTemplate.queryForList(searchQuery, Article.class);
|
||||||
.build();
|
|
||||||
List<Article> articles = elasticsearchTemplate
|
|
||||||
.queryForList(searchQuery, Article.class);
|
|
||||||
assertEquals(1, articles.size());
|
assertEquals(1, articles.size());
|
||||||
assertEquals("Search engines", articles.get(0).getTitle());
|
assertEquals("Search engines", articles.get(0).getTitle());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenPartTitle_whenRunMatchQuery_thenDocIsFound() {
|
public void givenPartTitle_whenRunMatchQuery_thenDocIsFound() {
|
||||||
SearchQuery searchQuery = new NativeSearchQueryBuilder()
|
final SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery("title", "elasticsearch data")).build();
|
||||||
.withQuery(matchQuery("title", "elasticsearch data"))
|
final List<Article> articles = elasticsearchTemplate.queryForList(searchQuery, Article.class);
|
||||||
.build();
|
|
||||||
List<Article> articles = elasticsearchTemplate
|
|
||||||
.queryForList(searchQuery, Article.class);
|
|
||||||
assertEquals(3, articles.size());
|
assertEquals(3, articles.size());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenFullTitle_whenRunMatchQueryOnVerbatimField_thenDocIsFound() {
|
public void givenFullTitle_whenRunMatchQueryOnVerbatimField_thenDocIsFound() {
|
||||||
SearchQuery searchQuery = new NativeSearchQueryBuilder()
|
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery("title.verbatim", "Second Article About Elasticsearch")).build();
|
||||||
.withQuery(matchQuery("title.verbatim", "Second Article About Elasticsearch"))
|
List<Article> articles = elasticsearchTemplate.queryForList(searchQuery, Article.class);
|
||||||
.build();
|
|
||||||
List<Article> articles = elasticsearchTemplate
|
|
||||||
.queryForList(searchQuery, Article.class);
|
|
||||||
assertEquals(1, articles.size());
|
assertEquals(1, articles.size());
|
||||||
|
|
||||||
searchQuery = new NativeSearchQueryBuilder()
|
searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery("title.verbatim", "Second Article About")).build();
|
||||||
.withQuery(matchQuery("title.verbatim", "Second Article About"))
|
articles = elasticsearchTemplate.queryForList(searchQuery, Article.class);
|
||||||
.build();
|
|
||||||
articles = elasticsearchTemplate
|
|
||||||
.queryForList(searchQuery, Article.class);
|
|
||||||
assertEquals(0, articles.size());
|
assertEquals(0, articles.size());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenNestedObject_whenQueryByAuthorsName_thenFoundArticlesByThatAuthor() {
|
public void givenNestedObject_whenQueryByAuthorsName_thenFoundArticlesByThatAuthor() {
|
||||||
QueryBuilder builder = nestedQuery("authors",
|
final QueryBuilder builder = nestedQuery("authors", boolQuery().must(termQuery("authors.name", "smith")));
|
||||||
boolQuery().must(termQuery("authors.name", "smith")));
|
|
||||||
|
|
||||||
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(builder).build();
|
final SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(builder).build();
|
||||||
List<Article> articles = elasticsearchTemplate.queryForList(searchQuery, Article.class);
|
final List<Article> articles = elasticsearchTemplate.queryForList(searchQuery, Article.class);
|
||||||
|
|
||||||
assertEquals(2, articles.size());
|
assertEquals(2, articles.size());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenAnalyzedQuery_whenMakeAggregationOnTermCount_thenEachTokenCountsSeparately() {
|
public void givenAnalyzedQuery_whenMakeAggregationOnTermCount_thenEachTokenCountsSeparately() {
|
||||||
TermsBuilder aggregation = AggregationBuilders.terms("top_tags").field("title");
|
final TermsBuilder aggregation = AggregationBuilders.terms("top_tags").field("title");
|
||||||
SearchResponse response = client.prepareSearch("blog").setTypes("article")
|
final SearchResponse response = client.prepareSearch("blog").setTypes("article").addAggregation(aggregation).execute().actionGet();
|
||||||
.addAggregation(aggregation).execute().actionGet();
|
|
||||||
|
|
||||||
Map<String, Aggregation> results = response.getAggregations().asMap();
|
final Map<String, Aggregation> results = response.getAggregations().asMap();
|
||||||
StringTerms topTags = (StringTerms) results.get("top_tags");
|
final StringTerms topTags = (StringTerms) results.get("top_tags");
|
||||||
|
|
||||||
List<String> keys = topTags.getBuckets().stream().map(b -> b.getKey()).collect(toList());
|
final List<String> keys = topTags.getBuckets().stream().map(b -> b.getKeyAsString()).collect(toList());
|
||||||
Collections.sort(keys);
|
Collections.sort(keys);
|
||||||
assertEquals(asList("about", "article", "data", "elasticsearch",
|
assertEquals(asList("about", "article", "data", "elasticsearch", "engines", "search", "second", "spring", "tutorial"), keys);
|
||||||
"engines", "search", "second", "spring", "tutorial"), keys);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenNotAnalyzedQuery_whenMakeAggregationOnTermCount_thenEachTermCountsIndividually() {
|
public void givenNotAnalyzedQuery_whenMakeAggregationOnTermCount_thenEachTermCountsIndividually() {
|
||||||
TermsBuilder aggregation = AggregationBuilders.terms("top_tags").field("tags")
|
final TermsBuilder aggregation = AggregationBuilders.terms("top_tags").field("tags").order(Terms.Order.aggregation("_count", false));
|
||||||
.order(Terms.Order.aggregation("_count", false));
|
final SearchResponse response = client.prepareSearch("blog").setTypes("article").addAggregation(aggregation).execute().actionGet();
|
||||||
SearchResponse response = client.prepareSearch("blog").setTypes("article")
|
|
||||||
.addAggregation(aggregation).execute().actionGet();
|
|
||||||
|
|
||||||
Map<String, Aggregation> results = response.getAggregations().asMap();
|
final Map<String, Aggregation> results = response.getAggregations().asMap();
|
||||||
StringTerms topTags = (StringTerms) results.get("top_tags");
|
final StringTerms topTags = (StringTerms) results.get("top_tags");
|
||||||
|
|
||||||
List<String> keys = topTags.getBuckets().stream().map(b -> b.getKey()).collect(toList());
|
final List<String> keys = topTags.getBuckets().stream().map(b -> b.getKeyAsString()).collect(toList());
|
||||||
assertEquals(asList("elasticsearch", "spring data", "search engines", "tutorial"), keys);
|
assertEquals(asList("elasticsearch", "spring data", "search engines", "tutorial"), keys);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenNotExactPhrase_whenUseSlop_thenQueryMatches() {
|
public void givenNotExactPhrase_whenUseSlop_thenQueryMatches() {
|
||||||
SearchQuery searchQuery = new NativeSearchQueryBuilder()
|
final SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchPhraseQuery("title", "spring elasticsearch").slop(1)).build();
|
||||||
.withQuery(matchPhraseQuery("title", "spring elasticsearch").slop(1))
|
final List<Article> articles = elasticsearchTemplate.queryForList(searchQuery, Article.class);
|
||||||
.build();
|
|
||||||
List<Article> articles = elasticsearchTemplate
|
|
||||||
.queryForList(searchQuery, Article.class);
|
|
||||||
assertEquals(1, articles.size());
|
assertEquals(1, articles.size());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenPhraseWithType_whenUseFuzziness_thenQueryMatches() {
|
public void givenPhraseWithType_whenUseFuzziness_thenQueryMatches() {
|
||||||
SearchQuery searchQuery = new NativeSearchQueryBuilder()
|
final SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery("title", "spring date elasticserch").operator(AND).fuzziness(Fuzziness.ONE).prefixLength(3)).build();
|
||||||
.withQuery(matchQuery("title", "spring date elasticserch")
|
|
||||||
.operator(AND)
|
|
||||||
.fuzziness(Fuzziness.ONE)
|
|
||||||
.prefixLength(3))
|
|
||||||
.build();
|
|
||||||
|
|
||||||
List<Article> articles = elasticsearchTemplate
|
final List<Article> articles = elasticsearchTemplate.queryForList(searchQuery, Article.class);
|
||||||
.queryForList(searchQuery, Article.class);
|
|
||||||
assertEquals(1, articles.size());
|
assertEquals(1, articles.size());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenMultimatchQuery_whenDoSearch_thenAllProvidedFieldsMatch() {
|
public void givenMultimatchQuery_whenDoSearch_thenAllProvidedFieldsMatch() {
|
||||||
SearchQuery searchQuery = new NativeSearchQueryBuilder()
|
final SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(multiMatchQuery("tutorial").field("title").field("tags").type(MultiMatchQueryBuilder.Type.BEST_FIELDS)).build();
|
||||||
.withQuery(multiMatchQuery("tutorial")
|
|
||||||
.field("title")
|
|
||||||
.field("tags")
|
|
||||||
.type(MultiMatchQueryBuilder.Type.BEST_FIELDS))
|
|
||||||
.build();
|
|
||||||
|
|
||||||
List<Article> articles = elasticsearchTemplate
|
final List<Article> articles = elasticsearchTemplate.queryForList(searchQuery, Article.class);
|
||||||
.queryForList(searchQuery, Article.class);
|
|
||||||
assertEquals(2, articles.size());
|
assertEquals(2, articles.size());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,9 +1,15 @@
|
|||||||
package com.baeldung.spring.data.es;
|
package com.baeldung.spring.data.es;
|
||||||
|
|
||||||
import com.baeldung.spring.data.es.config.Config;
|
import static java.util.Arrays.asList;
|
||||||
import com.baeldung.spring.data.es.model.Article;
|
import static org.elasticsearch.index.query.MatchQueryBuilder.Operator.AND;
|
||||||
import com.baeldung.spring.data.es.model.Author;
|
import static org.elasticsearch.index.query.QueryBuilders.fuzzyQuery;
|
||||||
import com.baeldung.spring.data.es.service.ArticleService;
|
import static org.elasticsearch.index.query.QueryBuilders.matchQuery;
|
||||||
|
import static org.elasticsearch.index.query.QueryBuilders.regexpQuery;
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertNotNull;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
import org.junit.runner.RunWith;
|
import org.junit.runner.RunWith;
|
||||||
@ -17,17 +23,13 @@ import org.springframework.test.context.ContextConfiguration;
|
|||||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||||
import org.springframework.test.context.support.AnnotationConfigContextLoader;
|
import org.springframework.test.context.support.AnnotationConfigContextLoader;
|
||||||
|
|
||||||
import java.util.List;
|
import com.baeldung.spring.data.es.config.Config;
|
||||||
|
import com.baeldung.spring.data.es.model.Article;
|
||||||
import static java.util.Arrays.asList;
|
import com.baeldung.spring.data.es.model.Author;
|
||||||
import static org.elasticsearch.index.query.FilterBuilders.regexpFilter;
|
import com.baeldung.spring.data.es.service.ArticleService;
|
||||||
import static org.elasticsearch.index.query.MatchQueryBuilder.Operator.AND;
|
|
||||||
import static org.elasticsearch.index.query.QueryBuilders.*;
|
|
||||||
import static org.junit.Assert.assertEquals;
|
|
||||||
import static org.junit.Assert.assertNotNull;
|
|
||||||
|
|
||||||
@RunWith(SpringJUnit4ClassRunner.class)
|
@RunWith(SpringJUnit4ClassRunner.class)
|
||||||
@ContextConfiguration(classes = {Config.class}, loader = AnnotationConfigContextLoader.class)
|
@ContextConfiguration(classes = { Config.class }, loader = AnnotationConfigContextLoader.class)
|
||||||
public class ElasticSearchTest {
|
public class ElasticSearchTest {
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
@ -59,8 +61,7 @@ public class ElasticSearchTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenArticleService_whenSaveArticle_thenIdIsAssigned() {
|
public void givenArticleService_whenSaveArticle_thenIdIsAssigned() {
|
||||||
List<Author> authors = asList(
|
final List<Author> authors = asList(new Author("John Smith"), johnDoe);
|
||||||
new Author("John Smith"), johnDoe);
|
|
||||||
|
|
||||||
Article article = new Article("Making Search Elastic");
|
Article article = new Article("Making Search Elastic");
|
||||||
article.setAuthors(authors);
|
article.setAuthors(authors);
|
||||||
@ -72,39 +73,34 @@ public class ElasticSearchTest {
|
|||||||
@Test
|
@Test
|
||||||
public void givenPersistedArticles_whenSearchByAuthorsName_thenRightFound() {
|
public void givenPersistedArticles_whenSearchByAuthorsName_thenRightFound() {
|
||||||
|
|
||||||
Page<Article> articleByAuthorName = articleService.findByAuthorName(johnSmith.getName(), new PageRequest(0, 10));
|
final Page<Article> articleByAuthorName = articleService.findByAuthorName(johnSmith.getName(), new PageRequest(0, 10));
|
||||||
assertEquals(2L, articleByAuthorName.getTotalElements());
|
assertEquals(2L, articleByAuthorName.getTotalElements());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenCustomQuery_whenSearchByAuthorsName_thenArticleIsFound() {
|
public void givenCustomQuery_whenSearchByAuthorsName_thenArticleIsFound() {
|
||||||
|
|
||||||
Page<Article> articleByAuthorName = articleService.findByAuthorNameUsingCustomQuery("John Smith", new PageRequest(0, 10));
|
final Page<Article> articleByAuthorName = articleService.findByAuthorNameUsingCustomQuery("John Smith", new PageRequest(0, 10));
|
||||||
assertEquals(3L, articleByAuthorName.getTotalElements());
|
assertEquals(3L, articleByAuthorName.getTotalElements());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenPersistedArticles_whenUseRegexQuery_thenRightArticlesFound() {
|
public void givenPersistedArticles_whenUseRegexQuery_thenRightArticlesFound() {
|
||||||
|
|
||||||
SearchQuery searchQuery = new NativeSearchQueryBuilder()
|
final SearchQuery searchQuery = new NativeSearchQueryBuilder().withFilter(regexpQuery("title", ".*data.*")).build();
|
||||||
.withFilter(regexpFilter("title", ".*data.*"))
|
final List<Article> articles = elasticsearchTemplate.queryForList(searchQuery, Article.class);
|
||||||
.build();
|
|
||||||
List<Article> articles = elasticsearchTemplate.queryForList(searchQuery, Article.class);
|
|
||||||
|
|
||||||
assertEquals(1, articles.size());
|
assertEquals(1, articles.size());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenSavedDoc_whenTitleUpdated_thenCouldFindByUpdatedTitle() {
|
public void givenSavedDoc_whenTitleUpdated_thenCouldFindByUpdatedTitle() {
|
||||||
SearchQuery searchQuery = new NativeSearchQueryBuilder()
|
final SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(fuzzyQuery("title", "serch")).build();
|
||||||
.withQuery(fuzzyQuery("title", "serch"))
|
final List<Article> articles = elasticsearchTemplate.queryForList(searchQuery, Article.class);
|
||||||
.build();
|
|
||||||
List<Article> articles = elasticsearchTemplate.queryForList(searchQuery, Article.class);
|
|
||||||
|
|
||||||
assertEquals(1, articles.size());
|
assertEquals(1, articles.size());
|
||||||
|
|
||||||
Article article = articles.get(0);
|
final Article article = articles.get(0);
|
||||||
final String newTitle = "Getting started with Search Engines";
|
final String newTitle = "Getting started with Search Engines";
|
||||||
article.setTitle(newTitle);
|
article.setTitle(newTitle);
|
||||||
articleService.save(article);
|
articleService.save(article);
|
||||||
@ -117,10 +113,8 @@ public class ElasticSearchTest {
|
|||||||
|
|
||||||
final String articleTitle = "Spring Data Elasticsearch";
|
final String articleTitle = "Spring Data Elasticsearch";
|
||||||
|
|
||||||
SearchQuery searchQuery = new NativeSearchQueryBuilder()
|
final SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery("title", articleTitle).minimumShouldMatch("75%")).build();
|
||||||
.withQuery(matchQuery("title", articleTitle).minimumShouldMatch("75%"))
|
final List<Article> articles = elasticsearchTemplate.queryForList(searchQuery, Article.class);
|
||||||
.build();
|
|
||||||
List<Article> articles = elasticsearchTemplate.queryForList(searchQuery, Article.class);
|
|
||||||
assertEquals(1, articles.size());
|
assertEquals(1, articles.size());
|
||||||
final long count = articleService.count();
|
final long count = articleService.count();
|
||||||
|
|
||||||
@ -131,10 +125,8 @@ public class ElasticSearchTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenSavedDoc_whenOneTermMatches_thenFindByTitle() {
|
public void givenSavedDoc_whenOneTermMatches_thenFindByTitle() {
|
||||||
SearchQuery searchQuery = new NativeSearchQueryBuilder()
|
final SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery("title", "Search engines").operator(AND)).build();
|
||||||
.withQuery(matchQuery("title", "Search engines").operator(AND))
|
final List<Article> articles = elasticsearchTemplate.queryForList(searchQuery, Article.class);
|
||||||
.build();
|
|
||||||
List<Article> articles = elasticsearchTemplate.queryForList(searchQuery, Article.class);
|
|
||||||
assertEquals(1, articles.size());
|
assertEquals(1, articles.size());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -213,13 +213,13 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>io.springfox</groupId>
|
<groupId>io.springfox</groupId>
|
||||||
<artifactId>springfox-swagger2</artifactId>
|
<artifactId>springfox-swagger2</artifactId>
|
||||||
<version>${springfox.version}</version>
|
<version>${springfox-swagger.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>io.springfox</groupId>
|
<groupId>io.springfox</groupId>
|
||||||
<artifactId>springfox-swagger-ui</artifactId>
|
<artifactId>springfox-swagger-ui</artifactId>
|
||||||
<version>${springfox.version}</version>
|
<version>${springfox-swagger.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
</dependencies>
|
</dependencies>
|
||||||
@ -309,7 +309,6 @@
|
|||||||
<javax.validation.version>1.1.0.Final</javax.validation.version>
|
<javax.validation.version>1.1.0.Final</javax.validation.version>
|
||||||
<jstl.version>1.2</jstl.version>
|
<jstl.version>1.2</jstl.version>
|
||||||
<jackson.version>2.2.2</jackson.version>
|
<jackson.version>2.2.2</jackson.version>
|
||||||
<springfox.version>2.2.2</springfox.version>
|
|
||||||
|
|
||||||
<!-- util -->
|
<!-- util -->
|
||||||
<guava.version>19.0</guava.version>
|
<guava.version>19.0</guava.version>
|
||||||
@ -322,8 +321,7 @@
|
|||||||
<rest-assured.version>2.9.0</rest-assured.version>
|
<rest-assured.version>2.9.0</rest-assured.version>
|
||||||
|
|
||||||
<!-- swagger -->
|
<!-- swagger -->
|
||||||
<springfox-swagger.version>2.2.2</springfox-swagger.version>
|
<springfox-swagger.version>2.4.0</springfox-swagger.version>
|
||||||
<springfox-swagger-ui.version>2.2.2</springfox-swagger-ui.version>
|
|
||||||
|
|
||||||
<httpcore.version>4.4.1</httpcore.version>
|
<httpcore.version>4.4.1</httpcore.version>
|
||||||
<httpclient.version>4.5</httpclient.version>
|
<httpclient.version>4.5</httpclient.version>
|
||||||
|
@ -44,7 +44,7 @@ public class SecurityJavaConfig extends WebSecurityConfigurerAdapter {
|
|||||||
.authorizeRequests()
|
.authorizeRequests()
|
||||||
.antMatchers("/api/csrfAttacker*").permitAll()
|
.antMatchers("/api/csrfAttacker*").permitAll()
|
||||||
.antMatchers("/api/customer/**").permitAll()
|
.antMatchers("/api/customer/**").permitAll()
|
||||||
.antMatchers("/api/**").authenticated()
|
.antMatchers("/api/foos/**").authenticated()
|
||||||
.and()
|
.and()
|
||||||
.formLogin()
|
.formLogin()
|
||||||
.successHandler(authenticationSuccessHandler)
|
.successHandler(authenticationSuccessHandler)
|
||||||
|
@ -0,0 +1,20 @@
|
|||||||
|
package org.baeldung.web;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.jayway.restassured.RestAssured;
|
||||||
|
import com.jayway.restassured.response.Response;
|
||||||
|
|
||||||
|
public class SwaggerLiveTest {
|
||||||
|
private static final String URL_PREFIX = "http://localhost:8080/spring-security-rest/api";
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenVerifySpringFoxIsWorking_thenOK() {
|
||||||
|
final Response response = RestAssured.get(URL_PREFIX + "/v2/api-docs");
|
||||||
|
assertEquals(200, response.statusCode());
|
||||||
|
System.out.println(response.asString());
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
Loading…
x
Reference in New Issue
Block a user