Merge remote-tracking branch 'upstream/master'
This commit is contained in:
commit
6d61497eec
|
@ -0,0 +1,47 @@
|
|||
<?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/maven-v4_0_0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>cxf-introduction</artifactId>
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>apache-cxf</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
<properties>
|
||||
<cxf.version>3.1.6</cxf.version>
|
||||
</properties>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
<configuration>
|
||||
<mainClass>com.baeldung.cxf.introduction.Server</mainClass>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>2.19.1</version>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>**/StudentTest.java</exclude>
|
||||
</excludes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.cxf</groupId>
|
||||
<artifactId>cxf-rt-frontend-jaxws</artifactId>
|
||||
<version>${cxf.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.cxf</groupId>
|
||||
<artifactId>cxf-rt-transports-http-jetty</artifactId>
|
||||
<version>${cxf.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
|
@ -0,0 +1,16 @@
|
|||
package com.baeldung.cxf.introduction;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import javax.jws.WebService;
|
||||
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
|
||||
|
||||
@WebService
|
||||
public interface Baeldung {
|
||||
public String hello(String name);
|
||||
|
||||
public String helloStudent(Student student);
|
||||
|
||||
@XmlJavaTypeAdapter(StudentMapAdapter.class)
|
||||
public Map<Integer, Student> getStudents();
|
||||
}
|
|
@ -0,0 +1,24 @@
|
|||
package com.baeldung.cxf.introduction;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.jws.WebService;
|
||||
|
||||
@WebService(endpointInterface = "com.baeldung.cxf.introduction.Baeldung")
|
||||
public class BaeldungImpl implements Baeldung {
|
||||
private Map<Integer, Student> students = new LinkedHashMap<Integer, Student>();
|
||||
|
||||
public String hello(String name) {
|
||||
return "Hello " + name;
|
||||
}
|
||||
|
||||
public String helloStudent(Student student) {
|
||||
students.put(students.size() + 1, student);
|
||||
return "Hello " + student.getName();
|
||||
}
|
||||
|
||||
public Map<Integer, Student> getStudents() {
|
||||
return students;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
package com.baeldung.cxf.introduction;
|
||||
|
||||
import javax.xml.ws.Endpoint;
|
||||
|
||||
public class Server {
|
||||
public static void main(String args[]) throws InterruptedException {
|
||||
BaeldungImpl implementor = new BaeldungImpl();
|
||||
String address = "http://localhost:8080/baeldung";
|
||||
Endpoint.publish(address, implementor);
|
||||
System.out.println("Server ready...");
|
||||
Thread.sleep(60 * 1000);
|
||||
System.out.println("Server exiting");
|
||||
System.exit(0);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,8 @@
|
|||
package com.baeldung.cxf.introduction;
|
||||
|
||||
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
|
||||
|
||||
@XmlJavaTypeAdapter(StudentAdapter.class)
|
||||
public interface Student {
|
||||
public String getName();
|
||||
}
|
|
@ -0,0 +1,16 @@
|
|||
package com.baeldung.cxf.introduction;
|
||||
|
||||
import javax.xml.bind.annotation.adapters.XmlAdapter;
|
||||
|
||||
public class StudentAdapter extends XmlAdapter<StudentImpl, Student> {
|
||||
public StudentImpl marshal(Student student) throws Exception {
|
||||
if (student instanceof StudentImpl) {
|
||||
return (StudentImpl) student;
|
||||
}
|
||||
return new StudentImpl(student.getName());
|
||||
}
|
||||
|
||||
public Student unmarshal(StudentImpl student) throws Exception {
|
||||
return student;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,23 @@
|
|||
package com.baeldung.cxf.introduction;
|
||||
|
||||
import javax.xml.bind.annotation.XmlType;
|
||||
|
||||
@XmlType(name = "Student")
|
||||
public class StudentImpl implements Student {
|
||||
private String name;
|
||||
|
||||
StudentImpl() {
|
||||
}
|
||||
|
||||
public StudentImpl(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,39 @@
|
|||
package com.baeldung.cxf.introduction;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import javax.xml.bind.annotation.XmlElement;
|
||||
import javax.xml.bind.annotation.XmlType;
|
||||
|
||||
@XmlType(name = "StudentMap")
|
||||
public class StudentMap {
|
||||
private List<StudentEntry> entries = new ArrayList<StudentEntry>();
|
||||
|
||||
@XmlElement(nillable = false, name = "entry")
|
||||
public List<StudentEntry> getEntries() {
|
||||
return entries;
|
||||
}
|
||||
|
||||
@XmlType(name = "StudentEntry")
|
||||
public static class StudentEntry {
|
||||
private Integer id;
|
||||
private Student student;
|
||||
|
||||
public void setId(Integer id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Integer getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setStudent(Student student) {
|
||||
this.student = student;
|
||||
}
|
||||
|
||||
public Student getStudent() {
|
||||
return student;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,27 @@
|
|||
package com.baeldung.cxf.introduction;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.xml.bind.annotation.adapters.XmlAdapter;
|
||||
|
||||
public class StudentMapAdapter extends XmlAdapter<StudentMap, Map<Integer, Student>> {
|
||||
public StudentMap marshal(Map<Integer, Student> boundMap) throws Exception {
|
||||
StudentMap valueMap = new StudentMap();
|
||||
for (Map.Entry<Integer, Student> boundEntry : boundMap.entrySet()) {
|
||||
StudentMap.StudentEntry valueEntry = new StudentMap.StudentEntry();
|
||||
valueEntry.setStudent(boundEntry.getValue());
|
||||
valueEntry.setId(boundEntry.getKey());
|
||||
valueMap.getEntries().add(valueEntry);
|
||||
}
|
||||
return valueMap;
|
||||
}
|
||||
|
||||
public Map<Integer, Student> unmarshal(StudentMap valueMap) throws Exception {
|
||||
Map<Integer, Student> boundMap = new LinkedHashMap<Integer, Student>();
|
||||
for (StudentMap.StudentEntry studentEntry : valueMap.getEntries()) {
|
||||
boundMap.put(studentEntry.getId(), studentEntry.getStudent());
|
||||
}
|
||||
return boundMap;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,65 @@
|
|||
package com.baeldung.cxf.introduction;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import javax.xml.namespace.QName;
|
||||
import javax.xml.ws.Service;
|
||||
import javax.xml.ws.soap.SOAPBinding;
|
||||
|
||||
import com.baeldung.cxf.introduction.Baeldung;
|
||||
import com.baeldung.cxf.introduction.Student;
|
||||
import com.baeldung.cxf.introduction.StudentImpl;
|
||||
|
||||
public class StudentTest {
|
||||
private static QName SERVICE_NAME = new QName("http://introduction.cxf.baeldung.com/", "Baeldung");
|
||||
private static QName PORT_NAME = new QName("http://introduction.cxf.baeldung.com/", "BaeldungPort");
|
||||
|
||||
private Service service;
|
||||
private Baeldung baeldungProxy;
|
||||
private BaeldungImpl baeldungImpl;
|
||||
|
||||
{
|
||||
service = Service.create(SERVICE_NAME);
|
||||
String endpointAddress = "http://localhost:8080/baeldung";
|
||||
service.addPort(PORT_NAME, SOAPBinding.SOAP11HTTP_BINDING, endpointAddress);
|
||||
}
|
||||
|
||||
@Before
|
||||
public void reinstantiateBaeldungInstances() {
|
||||
baeldungImpl = new BaeldungImpl();
|
||||
baeldungProxy = service.getPort(PORT_NAME, Baeldung.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingHelloMethod_thenCorrect() {
|
||||
String endpointResponse = baeldungProxy.hello("Baeldung");
|
||||
String localResponse = baeldungImpl.hello("Baeldung");
|
||||
assertEquals(localResponse, endpointResponse);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingHelloStudentMethod_thenCorrect() {
|
||||
Student student = new StudentImpl("John Doe");
|
||||
String endpointResponse = baeldungProxy.helloStudent(student);
|
||||
String localResponse = baeldungImpl.helloStudent(student);
|
||||
assertEquals(localResponse, endpointResponse);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void usingGetStudentsMethod_thenCorrect() {
|
||||
Student student1 = new StudentImpl("Adam");
|
||||
baeldungProxy.helloStudent(student1);
|
||||
|
||||
Student student2 = new StudentImpl("Eve");
|
||||
baeldungProxy.helloStudent(student2);
|
||||
|
||||
Map<Integer, Student> students = baeldungProxy.getStudents();
|
||||
assertEquals("Adam", students.get(1).getName());
|
||||
assertEquals("Eve", students.get(2).getName());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,40 @@
|
|||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>apache-cxf</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<packaging>pom</packaging>
|
||||
<modules>
|
||||
<module>cxf-introduction</module>
|
||||
</modules>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.12</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<build>
|
||||
<defaultGoal>install</defaultGoal>
|
||||
<pluginManagement>
|
||||
<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>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
<version>1.5.0</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</pluginManagement>
|
||||
</build>
|
||||
</project>
|
|
@ -9,17 +9,28 @@
|
|||
<version>1.0.0-SNAPSHOT</version>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>19.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.12</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>3.4.1</version>
|
||||
<version>3.5.1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-guava</artifactId>
|
||||
<version>3.0.0</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
|
|
@ -14,9 +14,7 @@ import java.util.List;
|
|||
import java.util.Map;
|
||||
import java.util.NoSuchElementException;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.entry;
|
||||
import static org.assertj.core.api.Assertions.withPrecision;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
public class AssertJCoreTest {
|
||||
|
||||
|
|
|
@ -0,0 +1,121 @@
|
|||
package com.baeldung.assertj.introduction;
|
||||
|
||||
import com.google.common.base.Optional;
|
||||
import com.google.common.collect.ArrayListMultimap;
|
||||
import com.google.common.collect.HashBasedTable;
|
||||
import com.google.common.collect.Multimap;
|
||||
import com.google.common.collect.Multimaps;
|
||||
import com.google.common.collect.Range;
|
||||
import com.google.common.collect.Table;
|
||||
import com.google.common.collect.TreeRangeMap;
|
||||
import com.google.common.io.Files;
|
||||
import org.assertj.guava.data.MapEntry;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
|
||||
import static org.assertj.guava.api.Assertions.assertThat;
|
||||
import static org.assertj.guava.api.Assertions.entry;
|
||||
|
||||
public class AssertJGuavaTest {
|
||||
|
||||
@Test
|
||||
public void givenTwoEmptyFiles_whenComparingContent_thenEqual() throws Exception {
|
||||
final File temp1 = File.createTempFile("bael", "dung1");
|
||||
final File temp2 = File.createTempFile("bael", "dung2");
|
||||
|
||||
assertThat(Files.asByteSource(temp1))
|
||||
.hasSize(0)
|
||||
.hasSameContentAs(Files.asByteSource(temp2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultimap_whenVerifying_thenCorrect() throws Exception {
|
||||
final Multimap<Integer, String> mmap = ArrayListMultimap.create();
|
||||
mmap.put(1, "one");
|
||||
mmap.put(1, "1");
|
||||
|
||||
assertThat(mmap)
|
||||
.hasSize(2)
|
||||
.containsKeys(1)
|
||||
.contains(entry(1, "one"))
|
||||
.contains(entry(1, "1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultimaps_whenVerifyingContent_thenCorrect() throws Exception {
|
||||
final Multimap<Integer, String> mmap1 = ArrayListMultimap.create();
|
||||
mmap1.put(1, "one");
|
||||
mmap1.put(1, "1");
|
||||
mmap1.put(2, "two");
|
||||
mmap1.put(2, "2");
|
||||
|
||||
final Multimap<Integer, String> mmap1_clone = Multimaps.newSetMultimap(new HashMap<>(), HashSet::new);
|
||||
mmap1_clone.put(1, "one");
|
||||
mmap1_clone.put(1, "1");
|
||||
mmap1_clone.put(2, "two");
|
||||
mmap1_clone.put(2, "2");
|
||||
|
||||
final Multimap<Integer, String> mmap2 = Multimaps.newSetMultimap(new HashMap<>(), HashSet::new);
|
||||
mmap2.put(1, "one");
|
||||
mmap2.put(1, "1");
|
||||
|
||||
assertThat(mmap1)
|
||||
.containsAllEntriesOf(mmap2)
|
||||
.containsAllEntriesOf(mmap1_clone)
|
||||
.hasSameEntriesAs(mmap1_clone);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOptional_whenVerifyingContent_thenShouldBeEqual() throws Exception {
|
||||
final Optional<String> something = Optional.of("something");
|
||||
|
||||
assertThat(something)
|
||||
.isPresent()
|
||||
.extractingValue()
|
||||
.isEqualTo("something");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRange_whenVerifying_thenShouldBeCorrect() throws Exception {
|
||||
final Range<String> range = Range.openClosed("a", "g");
|
||||
|
||||
assertThat(range)
|
||||
.hasOpenedLowerBound()
|
||||
.isNotEmpty()
|
||||
.hasClosedUpperBound()
|
||||
.contains("b");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRangeMap_whenVerifying_thenShouldBeCorrect() throws Exception {
|
||||
final TreeRangeMap<Integer, String> map = TreeRangeMap.create();
|
||||
|
||||
map.put(Range.closed(0, 60), "F");
|
||||
map.put(Range.closed(61, 70), "D");
|
||||
|
||||
assertThat(map)
|
||||
.isNotEmpty()
|
||||
.containsKeys(0)
|
||||
.contains(MapEntry.entry(34, "F"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTable_whenVerifying_thenShouldBeCorrect() throws Exception {
|
||||
final Table<Integer, String, String> table = HashBasedTable.create(2, 2);
|
||||
|
||||
table.put(1, "A", "PRESENT");
|
||||
table.put(1, "B", "ABSENT");
|
||||
|
||||
assertThat(table)
|
||||
.hasRowCount(1)
|
||||
.containsValues("ABSENT")
|
||||
.containsCell(1, "B", "ABSENT");
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
|
@ -0,0 +1,132 @@
|
|||
package com.baeldung.assertj.introduction;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.LocalTime;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
import static java.time.LocalDate.ofYearDay;
|
||||
import static java.util.Arrays.asList;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class AssertJJava8Test {
|
||||
|
||||
@Test
|
||||
public void givenOptional_shouldAssert() throws Exception {
|
||||
final Optional<String> givenOptional = Optional.of("something");
|
||||
|
||||
assertThat(givenOptional)
|
||||
.isPresent()
|
||||
.hasValue("something");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPredicate_shouldAssert() throws Exception {
|
||||
final Predicate<String> predicate = s -> s.length() > 4;
|
||||
|
||||
assertThat(predicate)
|
||||
.accepts("aaaaa", "bbbbb")
|
||||
.rejects("a", "b")
|
||||
.acceptsAll(asList("aaaaa", "bbbbb"))
|
||||
.rejectsAll(asList("a", "b"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLocalDate_shouldAssert() throws Exception {
|
||||
final LocalDate givenLocalDate = LocalDate.of(2016, 7, 8);
|
||||
final LocalDate todayDate = LocalDate.now();
|
||||
|
||||
assertThat(givenLocalDate)
|
||||
.isBefore(LocalDate.of(2020, 7, 8))
|
||||
.isAfterOrEqualTo(LocalDate.of(1989, 7, 8));
|
||||
|
||||
assertThat(todayDate)
|
||||
.isAfter(LocalDate.of(1989, 7, 8))
|
||||
.isToday();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLocalDateTime_shouldAssert() throws Exception {
|
||||
final LocalDateTime givenLocalDate = LocalDateTime.of(2016, 7, 8, 12, 0);
|
||||
|
||||
assertThat(givenLocalDate)
|
||||
.isBefore(LocalDateTime.of(2020, 7, 8, 11, 2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLocalTime_shouldAssert() throws Exception {
|
||||
final LocalTime givenLocalTime = LocalTime.of(12, 15);
|
||||
|
||||
assertThat(givenLocalTime)
|
||||
.isAfter(LocalTime.of(1, 0))
|
||||
.hasSameHourAs(LocalTime.of(12, 0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenList_shouldAssertFlatExtracting() throws Exception {
|
||||
final List<LocalDate> givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6));
|
||||
|
||||
assertThat(givenList)
|
||||
.flatExtracting(LocalDate::getYear)
|
||||
.contains(2015);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenList_shouldAssertFlatExtractingLeapYear() throws Exception {
|
||||
final List<LocalDate> givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6));
|
||||
|
||||
assertThat(givenList)
|
||||
.flatExtracting(LocalDate::isLeapYear)
|
||||
.contains(true);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenList_shouldAssertFlatExtractingClass() throws Exception {
|
||||
final List<LocalDate> givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6));
|
||||
|
||||
assertThat(givenList)
|
||||
.flatExtracting(Object::getClass)
|
||||
.contains(LocalDate.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenList_shouldAssertMultipleFlatExtracting() throws Exception {
|
||||
final List<LocalDate> givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6));
|
||||
|
||||
assertThat(givenList)
|
||||
.flatExtracting(LocalDate::getYear, LocalDate::getDayOfMonth)
|
||||
.contains(2015, 6);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_shouldSatisfy() throws Exception {
|
||||
final String givenString = "someString";
|
||||
|
||||
assertThat(givenString)
|
||||
.satisfies(s -> {
|
||||
assertThat(s).isNotEmpty();
|
||||
assertThat(s).hasSize(10);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_shouldMatch() throws Exception {
|
||||
final String emptyString = "";
|
||||
|
||||
assertThat(emptyString)
|
||||
.matches(String::isEmpty);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenList_shouldHasOnlyOneElementSatisfying() throws Exception {
|
||||
final List<String> givenList = Arrays.asList("");
|
||||
|
||||
assertThat(givenList)
|
||||
.hasOnlyOneElementSatisfying(s -> assertThat(s).isEmpty());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,33 @@
|
|||
package org.baeldung.hamcrest;
|
||||
|
||||
public class Animal {
|
||||
String name;
|
||||
boolean wild;
|
||||
String sound;
|
||||
|
||||
public Animal(String name, boolean wild, String sound) {
|
||||
super();
|
||||
this.name = name;
|
||||
this.wild = wild;
|
||||
this.sound = sound;
|
||||
}
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
public boolean isWild() {
|
||||
return wild;
|
||||
}
|
||||
public void setWild(boolean wild) {
|
||||
this.wild = wild;
|
||||
}
|
||||
public String getSound() {
|
||||
return sound;
|
||||
}
|
||||
public void setSound(String sound) {
|
||||
this.sound = sound;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
package org.baeldung.hamcrest;
|
||||
|
||||
public class Cat extends Animal {
|
||||
|
||||
public Cat() {
|
||||
super("cat", false, "meow");
|
||||
}
|
||||
|
||||
public String makeSound() {
|
||||
return getSound();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,331 @@
|
|||
package org.baeldung.hamcrest;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
import static org.baeldung.hamcrest.IsPositiveInteger.isAPositiveInteger;
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.hamcrest.beans.HasProperty.hasProperty;
|
||||
import static org.hamcrest.beans.HasPropertyWithValue.hasProperty;
|
||||
import static org.hamcrest.beans.SamePropertyValuesAs.samePropertyValuesAs;
|
||||
import static org.hamcrest.collection.IsArrayContaining.hasItemInArray;
|
||||
import static org.hamcrest.collection.IsArrayContainingInAnyOrder.arrayContainingInAnyOrder;
|
||||
import static org.hamcrest.collection.IsArrayContainingInOrder.arrayContaining;
|
||||
import static org.hamcrest.collection.IsArrayWithSize.arrayWithSize;
|
||||
import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
|
||||
import static org.hamcrest.collection.IsEmptyCollection.empty;
|
||||
import static org.hamcrest.collection.IsIn.isIn;
|
||||
import static org.hamcrest.collection.IsIn.isOneOf;
|
||||
import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder;
|
||||
import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
|
||||
import static org.hamcrest.collection.IsMapContaining.hasEntry;
|
||||
import static org.hamcrest.collection.IsMapContaining.hasKey;
|
||||
import static org.hamcrest.collection.IsMapContaining.hasValue;
|
||||
import static org.hamcrest.core.AllOf.allOf;
|
||||
import static org.hamcrest.core.AnyOf.anyOf;
|
||||
import static org.hamcrest.core.Every.everyItem;
|
||||
import static org.hamcrest.core.Is.is;
|
||||
import static org.hamcrest.core.IsInstanceOf.instanceOf;
|
||||
import static org.hamcrest.core.IsNot.not;
|
||||
import static org.hamcrest.core.IsNull.notNullValue;
|
||||
import static org.hamcrest.core.IsSame.sameInstance;
|
||||
import static org.hamcrest.core.StringContains.containsString;
|
||||
import static org.hamcrest.core.StringEndsWith.endsWith;
|
||||
import static org.hamcrest.core.StringStartsWith.startsWith;
|
||||
import static org.hamcrest.object.HasToString.hasToString;
|
||||
import static org.hamcrest.object.IsCompatibleType.typeCompatibleWith;
|
||||
import static org.hamcrest.text.IsEmptyString.isEmptyOrNullString;
|
||||
import static org.hamcrest.text.IsEmptyString.isEmptyString;
|
||||
import static org.hamcrest.text.IsEqualIgnoringCase.equalToIgnoringCase;
|
||||
import static org.hamcrest.text.IsEqualIgnoringWhiteSpace.equalToIgnoringWhiteSpace;
|
||||
import static org.hamcrest.text.StringContainsInOrder.stringContainsInOrder;
|
||||
|
||||
public class HamcrestMatcherTest {
|
||||
@Test
|
||||
public void given2Strings_whenEqual_thenCorrect() {
|
||||
String a = "foo";
|
||||
String b = "FOO";
|
||||
assertThat(a, equalToIgnoringCase(b));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBean_whenHasValue_thenCorrect() {
|
||||
Person person = new Person("Baeldung", "New York");
|
||||
assertThat(person, hasProperty("name"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBean_whenHasCorrectValue_thenCorrect() {
|
||||
Person person = new Person("Baeldung", "New York");
|
||||
assertThat(person, hasProperty("address", equalTo("New York")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given2Beans_whenHavingSameValues_thenCorrect() {
|
||||
Person person1 = new Person("Baeldung", "New York");
|
||||
Person person2 = new Person("Baeldung", "New York");
|
||||
assertThat(person1, samePropertyValuesAs(person2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAList_whenChecksSize_thenCorrect() {
|
||||
List<String> hamcrestMatchers = Arrays.asList("collections", "beans",
|
||||
"text", "number");
|
||||
assertThat(hamcrestMatchers, hasSize(4));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArray_whenChecksSize_thenCorrect() {
|
||||
String[] hamcrestMatchers = { "collections", "beans", "text", "number" };
|
||||
assertThat(hamcrestMatchers, arrayWithSize(4));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListAndValues_whenChecksListForGivenValues_thenCorrect() {
|
||||
List<String> hamcrestMatchers = Arrays.asList("collections", "beans",
|
||||
"text", "number");
|
||||
assertThat(hamcrestMatchers,
|
||||
containsInAnyOrder("beans", "text", "collections", "number"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListAndValues_whenChecksListForGivenValuesWithOrder_thenCorrect() {
|
||||
List<String> hamcrestMatchers = Arrays.asList("collections", "beans",
|
||||
"text", "number");
|
||||
assertThat(hamcrestMatchers,
|
||||
contains("collections", "beans", "text", "number"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArrayAndValue_whenValueFoundInArray_thenCorrect() {
|
||||
String[] hamcrestMatchers = { "collections", "beans", "text", "number" };
|
||||
assertThat(hamcrestMatchers, hasItemInArray("text"));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenValueAndArray_whenValueIsOneOfArrayElements_thenCorrect() {
|
||||
String[] hamcrestMatchers = { "collections", "beans", "text", "number" };
|
||||
assertThat("text", isOneOf(hamcrestMatchers));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArrayAndValues_whenValuesFoundInArray_thenCorrect() {
|
||||
String[] hamcrestMatchers = { "collections", "beans", "text", "number" };
|
||||
assertThat(
|
||||
hamcrestMatchers,
|
||||
arrayContainingInAnyOrder("beans", "collections", "number",
|
||||
"text"));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArrayAndValues_whenValuesFoundInArrayInOrder_thenCorrect() {
|
||||
String[] hamcrestMatchers = { "collections", "beans", "text", "number" };
|
||||
assertThat(hamcrestMatchers,
|
||||
arrayContaining("collections", "beans", "text", "number"));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCollection_whenEmpty_thenCorrect() {
|
||||
List<String> emptyList = new ArrayList<>();
|
||||
assertThat(emptyList, empty());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenValueAndArray_whenValueFoundInArray_thenCorrect() {
|
||||
String[] array = new String[] { "collections", "beans", "text",
|
||||
"number" };
|
||||
assertThat("beans", isIn(array));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMapAndKey_whenKeyFoundInMap_thenCorrect() {
|
||||
Map<String, String> map = new HashMap<>();
|
||||
map.put("blogname", "baeldung");
|
||||
assertThat(map, hasKey("blogname"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMapAndEntry_whenEntryFoundInMap_thenCorrect() {
|
||||
Map<String, String> map = new HashMap<>();
|
||||
map.put("blogname", "baeldung");
|
||||
assertThat(map, hasEntry("blogname", "baeldung"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMapAndValue_whenValueFoundInMap_thenCorrect() {
|
||||
Map<String, String> map = new HashMap<>();
|
||||
map.put("blogname", "baeldung");
|
||||
assertThat(map, hasValue("baeldung"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenEmpty_thenCorrect() {
|
||||
String str = "";
|
||||
assertThat(str, isEmptyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenEmptyOrNull_thenCorrect() {
|
||||
String str = null;
|
||||
assertThat(str, isEmptyOrNullString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given2Strings_whenEqualRegardlessWhiteSpace_thenCorrect() {
|
||||
String str1 = "text";
|
||||
String str2 = " text ";
|
||||
assertThat(str1, equalToIgnoringWhiteSpace(str2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenContainsGivenSubstring_thenCorrect() {
|
||||
String str = "calligraphy";
|
||||
assertThat(str, stringContainsInOrder(Arrays.asList("call", "graph")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBean_whenToStringReturnsRequiredString_thenCorrect() {
|
||||
Person person = new Person("Barrack", "Washington");
|
||||
String str = person.toString();
|
||||
assertThat(person, hasToString(str));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given2Classes_whenOneInheritsFromOther_thenCorrect() {
|
||||
assertThat(Cat.class, typeCompatibleWith(Animal.class));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void given2Strings_whenIsEqualRegardlessWhiteSpace_thenCorrect() {
|
||||
String str1 = "text";
|
||||
String str2 = " text ";
|
||||
assertThat(str1, is(equalToIgnoringWhiteSpace(str2)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given2Strings_whenIsNotEqualRegardlessWhiteSpace_thenCorrect() {
|
||||
String str1 = "text";
|
||||
String str2 = " texts ";
|
||||
assertThat(str1, not(equalToIgnoringWhiteSpace(str2)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given2Strings_whenNotEqual_thenCorrect() {
|
||||
String str1 = "text";
|
||||
String str2 = "texts";
|
||||
assertThat(str1, not(str2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given2Strings_whenIsEqual_thenCorrect() {
|
||||
String str1 = "text";
|
||||
String str2 = "text";
|
||||
assertThat(str1, is(str2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAStrings_whenContainsAnotherGivenString_thenCorrect() {
|
||||
String str1 = "calligraphy";
|
||||
String str2 = "call";
|
||||
assertThat(str1, containsString(str2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAString_whenEndsWithAnotherGivenString_thenCorrect() {
|
||||
String str1 = "calligraphy";
|
||||
String str2 = "phy";
|
||||
assertThat(str1, endsWith(str2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAString_whenStartsWithAnotherGivenString_thenCorrect() {
|
||||
String str1 = "calligraphy";
|
||||
String str2 = "call";
|
||||
assertThat(str1, startsWith(str2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given2Objects_whenSameInstance_thenCorrect() {
|
||||
Cat cat = new Cat();
|
||||
assertThat(cat, sameInstance(cat));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnObject_whenInstanceOfGivenClass_thenCorrect() {
|
||||
Cat cat = new Cat();
|
||||
assertThat(cat, instanceOf(Cat.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenList_whenEachElementGreaterThan0_thenCorrect() {
|
||||
List<Integer> list = Arrays.asList(1, 2, 3);
|
||||
int baseCase = 0;
|
||||
assertThat(list, everyItem(greaterThan(baseCase)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenNotNull_thenCorrect() {
|
||||
String str = "notnull";
|
||||
assertThat(str, notNullValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenMeetsAnyOfGivenConditions_thenCorrect() {
|
||||
String str = "calligraphy";
|
||||
String start = "call";
|
||||
String end = "foo";
|
||||
assertThat(str, anyOf(startsWith(start), containsString(end)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenMeetsAllOfGivenConditions_thenCorrect() {
|
||||
String str = "calligraphy";
|
||||
String start = "call";
|
||||
String end = "phy";
|
||||
assertThat(str, allOf(startsWith(start), endsWith(end)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInteger_whenAPositiveValue_thenCorrect() {
|
||||
int num = 1;
|
||||
assertThat(num, isAPositiveInteger());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnInteger_whenGreaterThan0_thenCorrect() {
|
||||
int num = 1;
|
||||
assertThat(num, greaterThan(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnInteger_whenGreaterThanOrEqTo5_thenCorrect() {
|
||||
int num = 5;
|
||||
assertThat(num, greaterThanOrEqualTo(5));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnInteger_whenLessThan0_thenCorrect() {
|
||||
int num = -1;
|
||||
assertThat(num, lessThan(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnInteger_whenLessThanOrEqTo5_thenCorrect() {
|
||||
assertThat(-1, lessThanOrEqualTo(5));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenADouble_whenCloseTo_thenCorrect() {
|
||||
assertThat(1.2, closeTo(1, 0.5));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,24 @@
|
|||
package org.baeldung.hamcrest;
|
||||
|
||||
import org.hamcrest.Description;
|
||||
import org.hamcrest.Factory;
|
||||
import org.hamcrest.Matcher;
|
||||
import org.hamcrest.TypeSafeMatcher;
|
||||
|
||||
public class IsPositiveInteger extends TypeSafeMatcher<Integer> {
|
||||
|
||||
public void describeTo(Description description) {
|
||||
description.appendText("a positive integer");
|
||||
}
|
||||
|
||||
@Factory
|
||||
public static Matcher<Integer> isAPositiveInteger() {
|
||||
return new IsPositiveInteger();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean matchesSafely(Integer integer) {
|
||||
return integer > 0;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,37 @@
|
|||
package org.baeldung.hamcrest;
|
||||
|
||||
public class Person {
|
||||
String name;
|
||||
String address;
|
||||
|
||||
public Person(String personName, String personAddress) {
|
||||
name = personName;
|
||||
address = personAddress;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getAddress() {
|
||||
return address;
|
||||
}
|
||||
|
||||
public void setAddress(String address) {
|
||||
this.address = address;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
String str="[address:"+address+",name:"+name+"]";
|
||||
return str;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
|
@ -170,6 +170,39 @@
|
|||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>net.alchim31.maven</groupId>
|
||||
<artifactId>yuicompressor-maven-plugin</artifactId>
|
||||
<version>1.5.1</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>compress</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
<configuration>
|
||||
<nosuffix>true</nosuffix>
|
||||
<webappDirectory>${project.build.directory}/min</webappDirectory>
|
||||
<excludes>
|
||||
<exclude>**/*.min.js</exclude>
|
||||
<exclude>**/handlebars-3133af2.js</exclude>
|
||||
<exclude>**/require.js</exclude>
|
||||
</excludes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-war-plugin</artifactId>
|
||||
<configuration>
|
||||
<webResources>
|
||||
<resource>
|
||||
<directory>${project.build.directory}/min</directory>
|
||||
</resource>
|
||||
</webResources>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
|
|
|
@ -1,4 +0,0 @@
|
|||
/**
|
||||
*
|
||||
*/
|
||||
window.Todos = Ember.Application.create();
|
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1,54 @@
|
|||
package com.baeldung.jackson.dtos;
|
||||
|
||||
public class MyDtoWithSpecialField {
|
||||
|
||||
private String[] stringValue;
|
||||
private int intValue;
|
||||
private boolean booleanValue;
|
||||
|
||||
public MyDtoWithSpecialField() {
|
||||
super();
|
||||
}
|
||||
|
||||
public MyDtoWithSpecialField(final String[] stringValue, final int intValue, final boolean booleanValue) {
|
||||
super();
|
||||
|
||||
this.stringValue = stringValue;
|
||||
this.intValue = intValue;
|
||||
this.booleanValue = booleanValue;
|
||||
}
|
||||
|
||||
// API
|
||||
|
||||
public String[] getStringValue() {
|
||||
return stringValue;
|
||||
}
|
||||
|
||||
public void setStringValue(final String[] stringValue) {
|
||||
this.stringValue = stringValue;
|
||||
}
|
||||
|
||||
public int getIntValue() {
|
||||
return intValue;
|
||||
}
|
||||
|
||||
public void setIntValue(final int intValue) {
|
||||
this.intValue = intValue;
|
||||
}
|
||||
|
||||
public boolean isBooleanValue() {
|
||||
return booleanValue;
|
||||
}
|
||||
|
||||
public void setBooleanValue(final boolean booleanValue) {
|
||||
this.booleanValue = booleanValue;
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "MyDto [stringValue=" + stringValue + ", intValue=" + intValue + ", booleanValue=" + booleanValue + "]";
|
||||
}
|
||||
|
||||
}
|
|
@ -3,6 +3,6 @@ package com.baeldung.jackson.dtos;
|
|||
import com.fasterxml.jackson.annotation.JsonIgnoreType;
|
||||
|
||||
@JsonIgnoreType
|
||||
public class MyMixInForString {
|
||||
public class MyMixInForIgnoreType {
|
||||
//
|
||||
}
|
|
@ -12,11 +12,8 @@ import java.text.SimpleDateFormat;
|
|||
import java.util.Date;
|
||||
import java.util.TimeZone;
|
||||
|
||||
import com.baeldung.jackson.bidirection.ItemWithIdentity;
|
||||
import com.baeldung.jackson.bidirection.ItemWithRef;
|
||||
import com.baeldung.jackson.bidirection.UserWithRef;
|
||||
import com.baeldung.jackson.dtos.User;
|
||||
import com.baeldung.jackson.dtos.withEnum.TypeEnumWithValue;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.jackson.annotation.BeanWithCreator;
|
||||
import com.baeldung.jackson.annotation.BeanWithCustomAnnotation;
|
||||
import com.baeldung.jackson.annotation.BeanWithFilter;
|
||||
|
@ -30,16 +27,17 @@ import com.baeldung.jackson.annotation.RawBean;
|
|||
import com.baeldung.jackson.annotation.UnwrappedUser;
|
||||
import com.baeldung.jackson.annotation.UserWithIgnoreType;
|
||||
import com.baeldung.jackson.annotation.Zoo;
|
||||
import com.baeldung.jackson.bidirection.ItemWithIdentity;
|
||||
import com.baeldung.jackson.bidirection.ItemWithRef;
|
||||
import com.baeldung.jackson.bidirection.UserWithIdentity;
|
||||
import com.baeldung.jackson.bidirection.UserWithRef;
|
||||
import com.baeldung.jackson.date.EventWithFormat;
|
||||
import com.baeldung.jackson.date.EventWithSerializer;
|
||||
import com.baeldung.jackson.dtos.MyMixInForString;
|
||||
import com.baeldung.jackson.dtos.MyMixInForIgnoreType;
|
||||
import com.baeldung.jackson.dtos.withEnum.TypeEnumWithValue;
|
||||
import com.baeldung.jackson.exception.UserWithRoot;
|
||||
import com.baeldung.jackson.jsonview.Item;
|
||||
import com.baeldung.jackson.jsonview.Views;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonParseException;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.InjectableValues;
|
||||
|
@ -127,7 +125,7 @@ public class JacksonAnnotationTest {
|
|||
public void whenDeserializingUsingJsonCreator_thenCorrect() throws JsonProcessingException, IOException {
|
||||
final String json = "{\"id\":1,\"theName\":\"My bean\"}";
|
||||
|
||||
final BeanWithCreator bean = new ObjectMapper().reader(BeanWithCreator.class).readValue(json);
|
||||
final BeanWithCreator bean = new ObjectMapper().readerFor(BeanWithCreator.class).readValue(json);
|
||||
assertEquals("My bean", bean.name);
|
||||
}
|
||||
|
||||
|
@ -136,7 +134,7 @@ public class JacksonAnnotationTest {
|
|||
final String json = "{\"name\":\"My bean\"}";
|
||||
final InjectableValues inject = new InjectableValues.Std().addValue(int.class, 1);
|
||||
|
||||
final BeanWithInject bean = new ObjectMapper().reader(inject).withType(BeanWithInject.class).readValue(json);
|
||||
final BeanWithInject bean = new ObjectMapper().reader(inject).forType(BeanWithInject.class).readValue(json);
|
||||
assertEquals("My bean", bean.name);
|
||||
assertEquals(1, bean.id);
|
||||
}
|
||||
|
@ -145,7 +143,7 @@ public class JacksonAnnotationTest {
|
|||
public void whenDeserializingUsingJsonAnySetter_thenCorrect() throws JsonProcessingException, IOException {
|
||||
final String json = "{\"name\":\"My bean\",\"attr2\":\"val2\",\"attr1\":\"val1\"}";
|
||||
|
||||
final ExtendableBean bean = new ObjectMapper().reader(ExtendableBean.class).readValue(json);
|
||||
final ExtendableBean bean = new ObjectMapper().readerFor(ExtendableBean.class).readValue(json);
|
||||
assertEquals("My bean", bean.name);
|
||||
assertEquals("val2", bean.getProperties().get("attr2"));
|
||||
}
|
||||
|
@ -154,7 +152,7 @@ public class JacksonAnnotationTest {
|
|||
public void whenDeserializingUsingJsonSetter_thenCorrect() throws JsonProcessingException, IOException {
|
||||
final String json = "{\"id\":1,\"name\":\"My bean\"}";
|
||||
|
||||
final BeanWithGetter bean = new ObjectMapper().reader(BeanWithGetter.class).readValue(json);
|
||||
final BeanWithGetter bean = new ObjectMapper().readerFor(BeanWithGetter.class).readValue(json);
|
||||
assertEquals("My bean", bean.getTheName());
|
||||
}
|
||||
|
||||
|
@ -164,7 +162,7 @@ public class JacksonAnnotationTest {
|
|||
|
||||
final SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
|
||||
|
||||
final EventWithSerializer event = new ObjectMapper().reader(EventWithSerializer.class).readValue(json);
|
||||
final EventWithSerializer event = new ObjectMapper().readerFor(EventWithSerializer.class).readValue(json);
|
||||
assertEquals("20-12-2014 02:30:00", df.format(event.eventDate));
|
||||
}
|
||||
|
||||
|
@ -235,7 +233,7 @@ public class JacksonAnnotationTest {
|
|||
public void whenDeserializingPolymorphic_thenCorrect() throws JsonProcessingException, IOException {
|
||||
final String json = "{\"animal\":{\"name\":\"lacy\",\"type\":\"cat\"}}";
|
||||
|
||||
final Zoo zoo = new ObjectMapper().reader().withType(Zoo.class).readValue(json);
|
||||
final Zoo zoo = new ObjectMapper().readerFor(Zoo.class).readValue(json);
|
||||
|
||||
assertEquals("lacy", zoo.animal.name);
|
||||
assertEquals(Zoo.Cat.class, zoo.animal.getClass());
|
||||
|
@ -250,7 +248,7 @@ public class JacksonAnnotationTest {
|
|||
assertThat(result, containsString("My bean"));
|
||||
assertThat(result, containsString("1"));
|
||||
|
||||
final BeanWithGetter resultBean = new ObjectMapper().reader(BeanWithGetter.class).readValue(result);
|
||||
final BeanWithGetter resultBean = new ObjectMapper().readerFor(BeanWithGetter.class).readValue(result);
|
||||
assertEquals("My bean", resultBean.getTheName());
|
||||
}
|
||||
|
||||
|
@ -338,19 +336,19 @@ public class JacksonAnnotationTest {
|
|||
assertThat(result, not(containsString("dateCreated")));
|
||||
}
|
||||
|
||||
@Ignore("Jackson 2.7.1-1 seems to have changed the API regarding mixins")
|
||||
// @Ignore("Jackson 2.7.1-1 seems to have changed the API regarding mixins")
|
||||
@Test
|
||||
public void whenSerializingUsingMixInAnnotation_thenCorrect() throws JsonProcessingException {
|
||||
final User user = new User(1, "John");
|
||||
final com.baeldung.jackson.dtos.Item item = new com.baeldung.jackson.dtos.Item(1, "book", null);
|
||||
|
||||
String result = new ObjectMapper().writeValueAsString(user);
|
||||
assertThat(result, containsString("John"));
|
||||
String result = new ObjectMapper().writeValueAsString(item);
|
||||
assertThat(result, containsString("owner"));
|
||||
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
mapper.addMixIn(String.class, MyMixInForString.class);
|
||||
mapper.addMixIn(com.baeldung.jackson.dtos.User.class, MyMixInForIgnoreType.class);
|
||||
|
||||
result = mapper.writeValueAsString(user);
|
||||
assertThat(result, not(containsString("John")));
|
||||
result = mapper.writeValueAsString(item);
|
||||
assertThat(result, not(containsString("owner")));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
|
|
@ -7,6 +7,8 @@ import static org.junit.Assert.assertThat;
|
|||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.jackson.bidirection.Item;
|
||||
import com.baeldung.jackson.bidirection.ItemWithIdentity;
|
||||
import com.baeldung.jackson.bidirection.ItemWithIgnore;
|
||||
|
@ -20,8 +22,6 @@ import com.baeldung.jackson.bidirection.UserWithRef;
|
|||
import com.baeldung.jackson.bidirection.UserWithSerializer;
|
||||
import com.baeldung.jackson.bidirection.UserWithView;
|
||||
import com.baeldung.jackson.jsonview.Views;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonMappingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
@ -93,7 +93,7 @@ public class JacksonBidirectionRelationTest {
|
|||
public void givenBidirectionRelation_whenDeserializingUsingIdentity_thenCorrect() throws JsonProcessingException, IOException {
|
||||
final String json = "{\"id\":2,\"itemName\":\"book\",\"owner\":{\"id\":1,\"name\":\"John\",\"userItems\":[2]}}";
|
||||
|
||||
final ItemWithIdentity item = new ObjectMapper().reader(ItemWithIdentity.class).readValue(json);
|
||||
final ItemWithIdentity item = new ObjectMapper().readerFor(ItemWithIdentity.class).readValue(json);
|
||||
|
||||
assertEquals(2, item.id);
|
||||
assertEquals("book", item.itemName);
|
||||
|
@ -104,7 +104,7 @@ public class JacksonBidirectionRelationTest {
|
|||
public void givenBidirectionRelation_whenUsingCustomDeserializer_thenCorrect() throws JsonProcessingException, IOException {
|
||||
final String json = "{\"id\":2,\"itemName\":\"book\",\"owner\":{\"id\":1,\"name\":\"John\",\"userItems\":[2]}}";
|
||||
|
||||
final ItemWithSerializer item = new ObjectMapper().reader(ItemWithSerializer.class).readValue(json);
|
||||
final ItemWithSerializer item = new ObjectMapper().readerFor(ItemWithSerializer.class).readValue(json);
|
||||
assertEquals(2, item.id);
|
||||
assertEquals("book", item.itemName);
|
||||
assertEquals("John", item.owner.name);
|
||||
|
|
|
@ -11,15 +11,15 @@ import java.time.LocalDateTime;
|
|||
import java.util.Date;
|
||||
import java.util.TimeZone;
|
||||
|
||||
import com.baeldung.jackson.date.EventWithLocalDateTime;
|
||||
import com.baeldung.jackson.date.Event;
|
||||
import com.baeldung.jackson.date.EventWithFormat;
|
||||
import com.baeldung.jackson.date.EventWithJodaTime;
|
||||
import com.baeldung.jackson.date.EventWithSerializer;
|
||||
import org.joda.time.DateTime;
|
||||
import org.joda.time.DateTimeZone;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.jackson.date.Event;
|
||||
import com.baeldung.jackson.date.EventWithFormat;
|
||||
import com.baeldung.jackson.date.EventWithJodaTime;
|
||||
import com.baeldung.jackson.date.EventWithLocalDateTime;
|
||||
import com.baeldung.jackson.date.EventWithSerializer;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.SerializationFeature;
|
||||
|
@ -128,7 +128,7 @@ public class JacksonDateTest {
|
|||
final ObjectMapper mapper = new ObjectMapper();
|
||||
mapper.setDateFormat(df);
|
||||
|
||||
final Event event = mapper.reader(Event.class).readValue(json);
|
||||
final Event event = mapper.readerFor(Event.class).readValue(json);
|
||||
assertEquals("20-12-2014 02:30:00", df.format(event.eventDate));
|
||||
}
|
||||
|
||||
|
@ -139,7 +139,7 @@ public class JacksonDateTest {
|
|||
final SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
final EventWithSerializer event = mapper.reader(EventWithSerializer.class).readValue(json);
|
||||
final EventWithSerializer event = mapper.readerFor(EventWithSerializer.class).readValue(json);
|
||||
assertEquals("20-12-2014 02:30:00", df.format(event.eventDate));
|
||||
}
|
||||
|
||||
|
|
|
@ -7,9 +7,13 @@ import static org.junit.Assert.assertThat;
|
|||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
import com.baeldung.jackson.exception.*;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.jackson.exception.User;
|
||||
import com.baeldung.jackson.exception.UserWithPrivateFields;
|
||||
import com.baeldung.jackson.exception.UserWithRoot;
|
||||
import com.baeldung.jackson.exception.Zoo;
|
||||
import com.baeldung.jackson.exception.ZooConfigured;
|
||||
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
|
||||
import com.fasterxml.jackson.annotation.PropertyAccessor;
|
||||
import com.fasterxml.jackson.core.JsonFactory;
|
||||
|
@ -30,7 +34,7 @@ public class JacksonExceptionsTest {
|
|||
final String json = "{\"animal\":{\"name\":\"lacy\"}}";
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
mapper.reader().withType(Zoo.class).readValue(json);
|
||||
mapper.reader().forType(Zoo.class).readValue(json);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -38,7 +42,7 @@ public class JacksonExceptionsTest {
|
|||
final String json = "{\"animal\":{\"name\":\"lacy\"}}";
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
mapper.reader().withType(ZooConfigured.class).readValue(json);
|
||||
mapper.reader().forType(ZooConfigured.class).readValue(json);
|
||||
}
|
||||
|
||||
// JsonMappingException: No serializer found for class
|
||||
|
@ -67,7 +71,7 @@ public class JacksonExceptionsTest {
|
|||
final String json = "{\"id\":1,\"name\":\"John\"}";
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
mapper.reader().withType(User.class).readValue(json);
|
||||
mapper.reader().forType(User.class).readValue(json);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -75,7 +79,7 @@ public class JacksonExceptionsTest {
|
|||
final String json = "{\"id\":1,\"name\":\"John\"}";
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
final com.baeldung.jackson.dtos.User user = mapper.reader().withType(com.baeldung.jackson.dtos.User.class).readValue(json);
|
||||
final com.baeldung.jackson.dtos.User user = mapper.reader().forType(com.baeldung.jackson.dtos.User.class).readValue(json);
|
||||
assertEquals("John", user.name);
|
||||
}
|
||||
|
||||
|
@ -87,7 +91,7 @@ public class JacksonExceptionsTest {
|
|||
final ObjectMapper mapper = new ObjectMapper();
|
||||
mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
|
||||
|
||||
mapper.reader().withType(com.baeldung.jackson.dtos.User.class).readValue(json);
|
||||
mapper.reader().forType(com.baeldung.jackson.dtos.User.class).readValue(json);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -97,7 +101,7 @@ public class JacksonExceptionsTest {
|
|||
final ObjectMapper mapper = new ObjectMapper();
|
||||
mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
|
||||
|
||||
final UserWithRoot user = mapper.reader().withType(UserWithRoot.class).readValue(json);
|
||||
final UserWithRoot user = mapper.reader().forType(UserWithRoot.class).readValue(json);
|
||||
assertEquals("John", user.name);
|
||||
}
|
||||
|
||||
|
@ -107,7 +111,7 @@ public class JacksonExceptionsTest {
|
|||
final String json = "[{\"id\":1,\"name\":\"John\"},{\"id\":2,\"name\":\"Adam\"}]";
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
mapper.reader().withType(com.baeldung.jackson.dtos.User.class).readValue(json);
|
||||
mapper.reader().forType(com.baeldung.jackson.dtos.User.class).readValue(json);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -115,7 +119,7 @@ public class JacksonExceptionsTest {
|
|||
final String json = "[{\"id\":1,\"name\":\"John\"},{\"id\":2,\"name\":\"Adam\"}]";
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
final List<com.baeldung.jackson.dtos.User> users = mapper.reader().withType(new TypeReference<List<com.baeldung.jackson.dtos.User>>() {
|
||||
final List<com.baeldung.jackson.dtos.User> users = mapper.reader().forType(new TypeReference<List<com.baeldung.jackson.dtos.User>>() {
|
||||
}).readValue(json);
|
||||
|
||||
assertEquals(2, users.size());
|
||||
|
@ -127,7 +131,7 @@ public class JacksonExceptionsTest {
|
|||
final String json = "{\"id\":1,\"name\":\"John\", \"checked\":true}";
|
||||
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
mapper.reader().withType(com.baeldung.jackson.dtos.User.class).readValue(json);
|
||||
mapper.reader().forType(com.baeldung.jackson.dtos.User.class).readValue(json);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -137,7 +141,7 @@ public class JacksonExceptionsTest {
|
|||
final ObjectMapper mapper = new ObjectMapper();
|
||||
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
|
||||
|
||||
final com.baeldung.jackson.dtos.User user = mapper.reader().withType(com.baeldung.jackson.dtos.User.class).readValue(json);
|
||||
final com.baeldung.jackson.dtos.User user = mapper.reader().forType(com.baeldung.jackson.dtos.User.class).readValue(json);
|
||||
assertEquals("John", user.name);
|
||||
}
|
||||
|
||||
|
@ -147,7 +151,7 @@ public class JacksonExceptionsTest {
|
|||
final String json = "{'id':1,'name':'John'}";
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
mapper.reader().withType(com.baeldung.jackson.dtos.User.class).readValue(json);
|
||||
mapper.reader().forType(com.baeldung.jackson.dtos.User.class).readValue(json);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -158,7 +162,7 @@ public class JacksonExceptionsTest {
|
|||
factory.enable(JsonParser.Feature.ALLOW_SINGLE_QUOTES);
|
||||
final ObjectMapper mapper = new ObjectMapper(factory);
|
||||
|
||||
final com.baeldung.jackson.dtos.User user = mapper.reader().withType(com.baeldung.jackson.dtos.User.class).readValue(json);
|
||||
final com.baeldung.jackson.dtos.User user = mapper.reader().forType(com.baeldung.jackson.dtos.User.class).readValue(json);
|
||||
assertEquals("John", user.name);
|
||||
}
|
||||
|
||||
|
|
|
@ -7,12 +7,12 @@ import static org.junit.Assert.assertThat;
|
|||
|
||||
import java.io.IOException;
|
||||
|
||||
import com.baeldung.jackson.jsonview.Item;
|
||||
import com.baeldung.jackson.jsonview.User;
|
||||
import com.baeldung.jackson.jsonview.MyBeanSerializerModifier;
|
||||
import com.baeldung.jackson.jsonview.Views;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.jackson.jsonview.Item;
|
||||
import com.baeldung.jackson.jsonview.MyBeanSerializerModifier;
|
||||
import com.baeldung.jackson.jsonview.User;
|
||||
import com.baeldung.jackson.jsonview.Views;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.MapperFeature;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
@ -66,7 +66,7 @@ public class JacksonJsonViewTest {
|
|||
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
final User user = mapper.readerWithView(Views.Public.class).withType(User.class).readValue(json);
|
||||
final User user = mapper.readerWithView(Views.Public.class).forType(User.class).readValue(json);
|
||||
assertEquals(1, user.getId());
|
||||
assertEquals("John", user.getName());
|
||||
}
|
||||
|
|
|
@ -8,17 +8,17 @@ import java.io.IOException;
|
|||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import com.baeldung.jackson.dtos.MyDtoIncludeNonDefault;
|
||||
import com.baeldung.jackson.dtos.MyDtoWithFilter;
|
||||
import com.baeldung.jackson.dtos.ignore.MyDtoIgnoreNull;
|
||||
import com.baeldung.jackson.dtos.MyDto;
|
||||
import com.baeldung.jackson.dtos.MyMixInForString;
|
||||
import com.baeldung.jackson.dtos.ignore.MyDtoIgnoreField;
|
||||
import com.baeldung.jackson.dtos.ignore.MyDtoIgnoreFieldByName;
|
||||
import com.baeldung.jackson.serialization.MyDtoNullKeySerializer;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.jackson.dtos.MyDto;
|
||||
import com.baeldung.jackson.dtos.MyDtoIncludeNonDefault;
|
||||
import com.baeldung.jackson.dtos.MyDtoWithFilter;
|
||||
import com.baeldung.jackson.dtos.MyDtoWithSpecialField;
|
||||
import com.baeldung.jackson.dtos.MyMixInForIgnoreType;
|
||||
import com.baeldung.jackson.dtos.ignore.MyDtoIgnoreField;
|
||||
import com.baeldung.jackson.dtos.ignore.MyDtoIgnoreFieldByName;
|
||||
import com.baeldung.jackson.dtos.ignore.MyDtoIgnoreNull;
|
||||
import com.baeldung.jackson.serialization.MyDtoNullKeySerializer;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude.Include;
|
||||
import com.fasterxml.jackson.core.JsonGenerator;
|
||||
import com.fasterxml.jackson.core.JsonParseException;
|
||||
|
@ -85,12 +85,12 @@ public class JacksonSerializationIgnoreUnitTest {
|
|||
System.out.println(dtoAsString);
|
||||
}
|
||||
|
||||
@Ignore("Jackson 2.7.1-1 seems to have changed the API for this case")
|
||||
// @Ignore("Jackson 2.7.1-1 seems to have changed the API for this case")
|
||||
@Test
|
||||
public final void givenFieldTypeIsIgnored_whenDtoIsSerialized_thenCorrect() throws JsonParseException, IOException {
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
mapper.addMixIn(String.class, MyMixInForString.class);
|
||||
final MyDto dtoObject = new MyDto();
|
||||
mapper.addMixIn(String[].class, MyMixInForIgnoreType.class);
|
||||
final MyDtoWithSpecialField dtoObject = new MyDtoWithSpecialField();
|
||||
dtoObject.setBooleanValue(true);
|
||||
|
||||
final String dtoAsString = mapper.writeValueAsString(dtoObject);
|
||||
|
|
14
jsf/pom.xml
14
jsf/pom.xml
|
@ -25,6 +25,19 @@
|
|||
<artifactId>jsf-impl</artifactId>
|
||||
<version>${com.sun.faces.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.el</groupId>
|
||||
<artifactId>el-api</artifactId>
|
||||
<version>${javax.el.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- JSTL -->
|
||||
|
||||
<dependency>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>jstl</artifactId>
|
||||
<version>1.2</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Spring -->
|
||||
|
||||
|
@ -114,6 +127,7 @@
|
|||
|
||||
<!-- JSF -->
|
||||
<com.sun.faces.version>2.1.7</com.sun.faces.version>
|
||||
<javax.el.version>2.2</javax.el.version>
|
||||
|
||||
<!-- logging -->
|
||||
<org.slf4j.version>1.7.13</org.slf4j.version>
|
||||
|
|
|
@ -0,0 +1,110 @@
|
|||
package com.baeldung.springintegration.controllers;
|
||||
|
||||
import java.util.Random;
|
||||
import javax.annotation.PostConstruct;
|
||||
import javax.faces.application.Application;
|
||||
import javax.faces.application.FacesMessage;
|
||||
import javax.faces.bean.ManagedBean;
|
||||
import javax.faces.bean.ViewScoped;
|
||||
import javax.faces.component.html.HtmlInputText;
|
||||
import javax.faces.context.FacesContext;
|
||||
|
||||
@ManagedBean(name = "ELBean")
|
||||
@ViewScoped
|
||||
public class ELSampleBean {
|
||||
|
||||
private String firstName;
|
||||
private String lastName;
|
||||
private String pageDescription = "This page demos JSF EL Basics";
|
||||
private int pageCounter;
|
||||
private Random randomIntGen = new Random();
|
||||
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
pageCounter = randomIntGen.nextInt();
|
||||
}
|
||||
|
||||
public void save() {
|
||||
|
||||
}
|
||||
|
||||
public void saveFirstName(String firstName) {
|
||||
this.firstName = firstName;
|
||||
}
|
||||
|
||||
|
||||
public void saveByELEvaluation() {
|
||||
firstName = (String) evaluateEL("#{firstName.value}", String.class);
|
||||
FacesContext ctx = FacesContext.getCurrentInstance();
|
||||
FacesMessage theMessage = new FacesMessage("Name component Evaluated: " + firstName);
|
||||
theMessage.setSeverity(FacesMessage.SEVERITY_INFO);
|
||||
ctx.addMessage(null, theMessage);
|
||||
|
||||
}
|
||||
|
||||
private Object evaluateEL(String elExpression, Class<?> clazz) {
|
||||
Object toReturn = null;
|
||||
FacesContext ctx = FacesContext.getCurrentInstance();
|
||||
Application app = ctx.getApplication();
|
||||
toReturn = app.evaluateExpressionGet(ctx, elExpression, clazz);
|
||||
|
||||
return toReturn;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the firstName
|
||||
*/
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param firstName the firstName to set
|
||||
*/
|
||||
public void setFirstName(String firstName) {
|
||||
this.firstName = firstName;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the lastName
|
||||
*/
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param lastName the lastName to set
|
||||
*/
|
||||
public void setLastName(String lastName) {
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the pageDescription
|
||||
*/
|
||||
public String getPageDescription() {
|
||||
return pageDescription;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param pageDescription the pageDescription to set
|
||||
*/
|
||||
public void setPageDescription(String pageDescription) {
|
||||
this.pageDescription = pageDescription;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the pageCounter
|
||||
*/
|
||||
public int getPageCounter() {
|
||||
return pageCounter;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param pageCounter the pageCounter to set
|
||||
*/
|
||||
public void setPageCounter(int pageCounter) {
|
||||
this.pageCounter = pageCounter;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,52 @@
|
|||
<?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"
|
||||
xmlns:c="http://java.sun.com/jsp/jstl/core"
|
||||
xmlns:f="http://java.sun.com/jsf/core">
|
||||
<h:head>
|
||||
<title>Baeldung | The EL Intro</title>
|
||||
</h:head>
|
||||
|
||||
<h:body>
|
||||
<h:form id="elForm">
|
||||
|
||||
|
||||
<h:messages/>
|
||||
<h:panelGrid columns="2">
|
||||
<h:outputText value="First Name"/>
|
||||
<h:inputText id="firstName" binding="#{firstName}" required="true" value="#{ELBean.firstName}"/>
|
||||
<h:outputText value="Last Name"/>
|
||||
<h:inputText id="lastName" required="true" value="#{ELBean.lastName}"/>
|
||||
<h:outputText value="Save by value binding"/>
|
||||
<h:commandButton value="Save" action="#{ELBean.save}">
|
||||
|
||||
</h:commandButton>
|
||||
<h:outputText value="Evaluate backing bean EL"/>
|
||||
<h:commandButton value="Save" action="#{ELBean.saveByELEvaluation}">
|
||||
</h:commandButton>
|
||||
<h:outputText value="Save by passing value to method"/>
|
||||
<h:commandButton value="Save"
|
||||
action="#{ELBean.saveFirstName(firstName.value.toString().concat('(passed)'))}"/>
|
||||
<h:outputText value="JavaScript (click after saving First Name)"/>
|
||||
<h:button value="Alert" onclick="alert('Hello #{ELBean.firstName}')"/>
|
||||
</h:panelGrid>
|
||||
|
||||
<br/>
|
||||
<h:outputText value="Current Request HTTP Headers:"/>
|
||||
<table border="1">
|
||||
<th>Key</th>
|
||||
<th>Value</th>
|
||||
<c:forEach items="#{header}" var="header">
|
||||
<tr>
|
||||
<td>#{header.key}</td>
|
||||
<td>#{header.value}</td>
|
||||
</tr>
|
||||
</c:forEach>
|
||||
</table>
|
||||
|
||||
</h:form>
|
||||
</h:body>
|
||||
</html>
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>org.baeldung</groupId>
|
||||
<artifactId>json</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
|
||||
<dependencies>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.everit.json</groupId>
|
||||
<artifactId>org.everit.json.schema</artifactId>
|
||||
<version>1.3.0</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.12</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,31 @@
|
|||
package org.baeldung.json.schema;
|
||||
|
||||
import org.everit.json.schema.Schema;
|
||||
import org.everit.json.schema.loader.SchemaLoader;
|
||||
|
||||
import org.json.JSONObject;
|
||||
import org.json.JSONTokener;
|
||||
import org.junit.Test;
|
||||
|
||||
public class JSONSchemaTest {
|
||||
|
||||
@Test
|
||||
public void givenInvalidInput_whenValidating_thenInvalid() {
|
||||
|
||||
JSONObject jsonSchema = new JSONObject(new JSONTokener(JSONSchemaTest.class.getResourceAsStream("/schema.json")));
|
||||
JSONObject jsonSubject = new JSONObject(new JSONTokener(JSONSchemaTest.class.getResourceAsStream("/product_invalid.json")));
|
||||
|
||||
Schema schema = SchemaLoader.load(jsonSchema);
|
||||
schema.validate(jsonSubject);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenValidInput_whenValidating_thenValid() {
|
||||
|
||||
JSONObject jsonSchema = new JSONObject(new JSONTokener(JSONSchemaTest.class.getResourceAsStream("/schema.json")));
|
||||
JSONObject jsonSubject = new JSONObject(new JSONTokener(JSONSchemaTest.class.getResourceAsStream("/product_valid.json")));
|
||||
|
||||
Schema schema = SchemaLoader.load(jsonSchema);
|
||||
schema.validate(jsonSubject);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,5 @@
|
|||
{
|
||||
"id": 1,
|
||||
"name": "Lampshade",
|
||||
"price": 0
|
||||
}
|
|
@ -0,0 +1,5 @@
|
|||
{
|
||||
"id": 1,
|
||||
"name": "Lampshade",
|
||||
"price": 10
|
||||
}
|
|
@ -0,0 +1,22 @@
|
|||
{
|
||||
"$schema": "http://json-schema.org/draft-04/schema#",
|
||||
"title": "Product",
|
||||
"description": "A product from the catalog",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {
|
||||
"description": "The unique identifier for a product",
|
||||
"type": "integer"
|
||||
},
|
||||
"name": {
|
||||
"description": "Name of the product",
|
||||
"type": "string"
|
||||
},
|
||||
"price": {
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"exclusiveMinimum": true
|
||||
}
|
||||
},
|
||||
"required": ["id", "name", "price"]
|
||||
}
|
|
@ -0,0 +1,66 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>log4j</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
|
||||
<dependencies>
|
||||
<!--log4j dependencies-->
|
||||
<dependency>
|
||||
<groupId>log4j</groupId>
|
||||
<artifactId>log4j</artifactId>
|
||||
<version>1.2.17</version>
|
||||
</dependency>
|
||||
|
||||
|
||||
<!--log4j2 dependencies-->
|
||||
<dependency>
|
||||
<groupId>org.apache.logging.log4j</groupId>
|
||||
<artifactId>log4j-api</artifactId>
|
||||
<version>2.6</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.logging.log4j</groupId>
|
||||
<artifactId>log4j-core</artifactId>
|
||||
<version>2.6</version>
|
||||
</dependency>
|
||||
|
||||
<!--disruptor for log4j2 async logging-->
|
||||
<dependency>
|
||||
<groupId>com.lmax</groupId>
|
||||
<artifactId>disruptor</artifactId>
|
||||
<version>3.3.4</version>
|
||||
</dependency>
|
||||
|
||||
|
||||
<!--logback dependencies-->
|
||||
|
||||
<dependency>
|
||||
<groupId>ch.qos.logback</groupId>
|
||||
<artifactId>logback-classic</artifactId>
|
||||
<version>1.1.7</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.3</version>
|
||||
<configuration>
|
||||
<debug>true</debug>
|
||||
<optimize>true</optimize>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
<encoding>UTF-8</encoding>
|
||||
<showDeprecation>true</showDeprecation>
|
||||
<showWarnings>true</showWarnings>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,17 @@
|
|||
package com.baeldung.log4j;
|
||||
|
||||
|
||||
import org.apache.log4j.Logger;
|
||||
|
||||
public class Log4jExample {
|
||||
|
||||
private final static Logger logger = Logger.getLogger(Log4jExample.class);
|
||||
|
||||
public static void main(String[] args) {
|
||||
logger.trace("Trace log message");
|
||||
logger.debug("Debug log message");
|
||||
logger.info("Info log message");
|
||||
logger.error("Error log message");
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,16 @@
|
|||
package com.baeldung.log4j2;
|
||||
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
|
||||
public class Log4j2Example {
|
||||
|
||||
private static final Logger logger = LogManager.getLogger(Log4j2Example.class);
|
||||
|
||||
public static void main(String[] args) {
|
||||
logger.debug("Debug log message");
|
||||
logger.info("Info log message");
|
||||
logger.error("Error log message");
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,16 @@
|
|||
package com.baeldung.logback;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class LogbackExample {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(LogbackExample.class);
|
||||
|
||||
public static void main(String[] args) {
|
||||
logger.debug("Debug log message");
|
||||
logger.info("Info log message");
|
||||
logger.error("Error log message");
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,32 @@
|
|||
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd" >
|
||||
<log4j:configuration debug="false">
|
||||
|
||||
<!--Console appender-->
|
||||
<appender name="stdout" class="org.apache.log4j.ConsoleAppender">
|
||||
<layout class="org.apache.log4j.PatternLayout">
|
||||
<param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %p %m%n"/>
|
||||
</layout>
|
||||
</appender>
|
||||
|
||||
<!-- File appender-->
|
||||
<appender name="fout" class="org.apache.log4j.FileAppender">
|
||||
<param name="file" value="log4j/target/baeldung-log4j.log"/>
|
||||
<param name="append" value="false"/>
|
||||
<layout class="org.apache.log4j.PatternLayout">
|
||||
<param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5p %m%n"/>
|
||||
<param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %p %m%n"/>
|
||||
</layout>
|
||||
</appender>
|
||||
|
||||
<!--Override log level for specified package-->
|
||||
<category name="com.baeldung.log4j">
|
||||
<priority value="TRACE"/>
|
||||
</category>
|
||||
|
||||
<root>
|
||||
<level value="DEBUG"/>
|
||||
<appender-ref ref="stdout"/>
|
||||
<appender-ref ref="fout"/>
|
||||
</root>
|
||||
|
||||
</log4j:configuration>
|
|
@ -0,0 +1,26 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Configuration status="INFO">
|
||||
<Appenders>
|
||||
# Console appender
|
||||
<Console name="stdout" target="SYSTEM_OUT">
|
||||
# Pattern of log message for console appender
|
||||
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} %p %m%n"/>
|
||||
</Console>
|
||||
|
||||
# File appender
|
||||
<File name="fout" fileName="log4j/target/baeldung-log4j2.log" immediateFlush="false" append="false">
|
||||
# Pattern of log message for file appender
|
||||
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} %p %m%n"/>
|
||||
</File>
|
||||
</Appenders>
|
||||
|
||||
<Loggers>
|
||||
# Override log level for specified package
|
||||
<Logger name="com.baeldung.log4j2" level="TRACE"/>
|
||||
|
||||
<AsyncRoot level="DEBUG">
|
||||
<AppenderRef ref="stdout"/>
|
||||
<AppenderRef ref="fout"/>
|
||||
</AsyncRoot>
|
||||
</Loggers>
|
||||
</Configuration>
|
|
@ -0,0 +1,28 @@
|
|||
<configuration>
|
||||
# Console appender
|
||||
<appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<layout class="ch.qos.logback.classic.PatternLayout">
|
||||
# Pattern of log message for console appender
|
||||
<Pattern>%d{yyyy-MM-dd HH:mm:ss} %p %m%n</Pattern>
|
||||
</layout>
|
||||
</appender>
|
||||
|
||||
# File appender
|
||||
<appender name="fout" class="ch.qos.logback.core.FileAppender">
|
||||
# Name of a log file
|
||||
<file>log4j/target/baeldung-logback.log</file>
|
||||
<append>false</append>
|
||||
<encoder>
|
||||
# Pattern of log message for file appender
|
||||
<pattern>%d{yyyy-MM-dd HH:mm:ss} %p %m%n</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
# Override log level for specified package
|
||||
<logger name="com.baeldung.logback" level="TRACE"/>
|
||||
|
||||
<root level="DEBUG">
|
||||
<appender-ref ref="stdout"/>
|
||||
<appender-ref ref="fout"/>
|
||||
</root>
|
||||
</configuration>
|
|
@ -0,0 +1,7 @@
|
|||
=========
|
||||
|
||||
## JMockit related tutorials
|
||||
|
||||
|
||||
### Relevant Articles:
|
||||
- [JMockit 101](http://www.baeldung.com/jmockit-101)
|
|
@ -0,0 +1,68 @@
|
|||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>mocks</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
<artifactId>jmockit</artifactId>
|
||||
<name>jmockit</name>
|
||||
|
||||
<properties>
|
||||
<junit.version>4.12</junit.version>
|
||||
<jmockit.version>1.24</jmockit.version>
|
||||
|
||||
<!-- maven plugins -->
|
||||
<maven-compiler-plugin.version>3.3</maven-compiler-plugin.version>
|
||||
<maven-surefire-plugin.version>2.18.1</maven-surefire-plugin.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.jmockit</groupId>
|
||||
<artifactId>jmockit</artifactId>
|
||||
<version>${jmockit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>jmockit</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${maven-surefire-plugin.version}</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,10 @@
|
|||
package org.baeldung.mocks.jmockit;
|
||||
|
||||
public class Collaborator {
|
||||
public boolean collaborate(String string){
|
||||
return false;
|
||||
}
|
||||
public void receive(boolean bool){
|
||||
//NOOP
|
||||
}
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
package org.baeldung.mocks.jmockit;
|
||||
|
||||
public class Model {
|
||||
public String getInfo(){
|
||||
return "info";
|
||||
}
|
||||
}
|
|
@ -0,0 +1,10 @@
|
|||
package org.baeldung.mocks.jmockit;
|
||||
|
||||
public class Performer {
|
||||
private Collaborator collaborator;
|
||||
|
||||
public void perform(Model model){
|
||||
boolean value = collaborator.collaborate(model.getInfo());
|
||||
collaborator.receive(value);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,30 @@
|
|||
package org.baeldung.mocks.jmockit;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
import mockit.*;
|
||||
import mockit.integration.junit4.JMockit;
|
||||
|
||||
@RunWith(JMockit.class)
|
||||
public class PerformerTest {
|
||||
|
||||
@Injectable
|
||||
private Collaborator collaborator;
|
||||
|
||||
@Tested
|
||||
private Performer performer;
|
||||
|
||||
@Test
|
||||
public void testThePerformMethod(@Mocked Model model) {
|
||||
new Expectations() {{
|
||||
model.getInfo();result = "bar";
|
||||
collaborator.collaborate("bar"); result = true;
|
||||
}};
|
||||
performer.perform(model);
|
||||
new Verifications() {{
|
||||
collaborator.receive(true);
|
||||
}};
|
||||
}
|
||||
|
||||
}
|
|
@ -1,11 +1,16 @@
|
|||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>org.baeldung</groupId>
|
||||
<artifactId>mock-comparisons</artifactId>
|
||||
<version>0.1-SNAPSHOT</version>
|
||||
|
||||
<name>mockito</name>
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>mocks</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
<artifactId>mock-comparisons</artifactId>
|
||||
<name>mock-comparisons</name>
|
||||
|
||||
<properties>
|
||||
<junit.version>4.12</junit.version>
|
|
@ -0,0 +1,20 @@
|
|||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
<artifactId>mocks</artifactId>
|
||||
<name>mocks</name>
|
||||
<packaging>pom</packaging>
|
||||
|
||||
<modules>
|
||||
<module>mock-comparisons</module>
|
||||
<module>jmockit</module>
|
||||
</modules>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,6 @@
|
|||
=========
|
||||
|
||||
## Mutation Testing
|
||||
|
||||
### Relevant Articles:
|
||||
- [Introduction to Mutation Testing Using the PITest Library](http://www.baeldung.com/introduction-to-mutation-testing-with-pitest)
|
|
@ -0,0 +1,38 @@
|
|||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>mutation-testing</artifactId>
|
||||
<version>0.1-SNAPSHOT</version>
|
||||
<name>mutation-testing</name>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.pitest</groupId>
|
||||
<artifactId>pitest-parent</artifactId>
|
||||
<version>1.1.10</version>
|
||||
<type>pom</type>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.9</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.pitest</groupId>
|
||||
<artifactId>pitest-maven</artifactId>
|
||||
<version>1.1.10</version>
|
||||
<configuration>
|
||||
<targetClasses>
|
||||
<param>com.baeldung.testing.mutation.*</param>
|
||||
</targetClasses>
|
||||
<targetTests>
|
||||
<param>com.baeldung.mutation.test.*</param>
|
||||
</targetTests>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
|
@ -0,0 +1,15 @@
|
|||
package com.baeldung.testing.mutation;
|
||||
|
||||
public class Palindrome {
|
||||
|
||||
public boolean isPalindrome(String inputString) {
|
||||
if (inputString.length() == 0) {
|
||||
return true;
|
||||
} else {
|
||||
char firstChar = inputString.charAt(0);
|
||||
char lastChar = inputString.charAt(inputString.length() - 1);
|
||||
String mid = inputString.substring(1, inputString.length() - 1);
|
||||
return (firstChar == lastChar) && isPalindrome(mid);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,29 @@
|
|||
package com.baeldung.mutation.test;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.testing.mutation.Palindrome;
|
||||
|
||||
public class TestPalindrome {
|
||||
|
||||
@Test
|
||||
public void acceptsPalindrome() {
|
||||
Palindrome palindromeTester = new Palindrome();
|
||||
assertTrue(palindromeTester.isPalindrome("noon"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void rejectsNonPalindrome(){
|
||||
Palindrome palindromeTester = new Palindrome();
|
||||
assertFalse(palindromeTester.isPalindrome("box"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void rejectsNearPalindrome(){
|
||||
Palindrome palindromeTester = new Palindrome();
|
||||
assertFalse(palindromeTester.isPalindrome("neon"));
|
||||
}
|
||||
}
|
16
pom.xml
16
pom.xml
|
@ -7,10 +7,14 @@
|
|||
<name>parent-modules</name>
|
||||
<packaging>pom</packaging>
|
||||
|
||||
<modules>
|
||||
<module>apache-fop</module>
|
||||
<module>assertj</module>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
</properties>
|
||||
|
||||
<modules>
|
||||
<module>assertj</module>
|
||||
<module>apache-cxf</module>
|
||||
<module>core-java</module>
|
||||
<module>core-java-8</module>
|
||||
<module>gson</module>
|
||||
|
@ -25,13 +29,14 @@
|
|||
<module>jooq-spring</module>
|
||||
<module>json-path</module>
|
||||
<module>mockito</module>
|
||||
<module>mock-comparisons</module>
|
||||
<module>mocks</module>
|
||||
<module>jee7schedule</module>
|
||||
<!-- <module>jpa-storedprocedure</module> -->
|
||||
<module>querydsl</module>
|
||||
<!-- <module>raml</module> -->
|
||||
<module>rest-testing</module>
|
||||
<module>resteasy</module>
|
||||
<module>log4j</module>
|
||||
|
||||
<module>spring-all</module>
|
||||
<module>spring-apache-camel</module>
|
||||
|
@ -74,6 +79,9 @@
|
|||
<module>xml</module>
|
||||
|
||||
<module>lombok</module>
|
||||
<module>redis</module>
|
||||
|
||||
<module>mutation-testing</module>
|
||||
</modules>
|
||||
|
||||
</project>
|
||||
|
|
|
@ -14,30 +14,25 @@
|
|||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<java.version>1.6</java.version>
|
||||
<junit.version>4.10</junit.version>
|
||||
<spring.version>3.1.0.RELEASE</spring.version>
|
||||
<hibernate.version>4.3.11.Final</hibernate.version>
|
||||
<querydsl.version>2.5.0</querydsl.version>
|
||||
<slf4j.version>1.5.10</slf4j.version>
|
||||
<java.version>1.8</java.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
<spring.version>4.3.1.RELEASE</spring.version>
|
||||
<hibernate.version>5.2.1.Final</hibernate.version>
|
||||
<querydsl.version>4.1.3</querydsl.version>
|
||||
<slf4j.version>1.7.21</slf4j.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<!-- QueryDSL -->
|
||||
<dependency>
|
||||
<groupId>com.mysema.querydsl</groupId>
|
||||
<artifactId>querydsl-core</artifactId>
|
||||
<version>${querydsl.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.mysema.querydsl</groupId>
|
||||
<groupId>com.querydsl</groupId>
|
||||
<artifactId>querydsl-jpa</artifactId>
|
||||
<version>${querydsl.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.mysema.querydsl</groupId>
|
||||
<groupId>com.querydsl</groupId>
|
||||
<artifactId>querydsl-apt</artifactId>
|
||||
<version>${querydsl.version}</version>
|
||||
<scope>provided</scope>
|
||||
|
@ -53,7 +48,7 @@
|
|||
|
||||
<dependency>
|
||||
<groupId>org.hibernate.javax.persistence</groupId>
|
||||
<artifactId>hibernate-jpa-2.0-api</artifactId>
|
||||
<artifactId>hibernate-jpa-2.1-api</artifactId>
|
||||
<version>1.0.0.Final</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
|
@ -69,7 +64,7 @@
|
|||
<dependency>
|
||||
<groupId>commons-pool</groupId>
|
||||
<artifactId>commons-pool</artifactId>
|
||||
<version>1.5.5</version>
|
||||
<version>1.6</version>
|
||||
<type>jar</type>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
|
@ -77,8 +72,8 @@
|
|||
<!-- HSQLDB Dependencies -->
|
||||
<dependency>
|
||||
<groupId>org.hsqldb</groupId>
|
||||
<artifactId>hsqldb-j5</artifactId>
|
||||
<version>2.2.4</version>
|
||||
<artifactId>hsqldb</artifactId>
|
||||
<version>2.3.4</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Spring Dependencies -->
|
||||
|
@ -118,9 +113,9 @@
|
|||
|
||||
<!-- Logging -->
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-api</artifactId>
|
||||
<version>${slf4j.version}</version>
|
||||
<groupId>ch.qos.logback</groupId>
|
||||
<artifactId>logback-classic</artifactId>
|
||||
<version>1.1.7</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
|
@ -128,17 +123,6 @@
|
|||
<version>${slf4j.version}</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-log4j12</artifactId>
|
||||
<version>${slf4j.version}</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>log4j</groupId>
|
||||
<artifactId>log4j</artifactId>
|
||||
<version>1.2.16</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Test Dependencies -->
|
||||
<dependency>
|
||||
|
@ -157,7 +141,7 @@
|
|||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>2.3.2</version>
|
||||
<version>3.5.1</version>
|
||||
<configuration>
|
||||
<source>${java.version}</source>
|
||||
<target>${java.version}</target>
|
||||
|
@ -168,16 +152,16 @@
|
|||
<!-- QueryDSL plugin -->
|
||||
<plugin>
|
||||
<groupId>com.mysema.maven</groupId>
|
||||
<artifactId>maven-apt-plugin</artifactId>
|
||||
<version>1.0.3</version>
|
||||
<artifactId>apt-maven-plugin</artifactId>
|
||||
<version>1.1.3</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>process</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<outputDirectory>target/metamodel</outputDirectory>
|
||||
<processor>com.mysema.query.apt.jpa.JPAAnnotationProcessor</processor>
|
||||
<outputDirectory>target/generated-sources/java</outputDirectory>
|
||||
<processor>com.querydsl.apt.jpa.JPAAnnotationProcessor</processor>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
|
|
|
@ -10,8 +10,8 @@ import org.baeldung.entity.Person;
|
|||
import org.baeldung.entity.QPerson;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import com.mysema.query.group.GroupBy;
|
||||
import com.mysema.query.jpa.impl.JPAQuery;
|
||||
import com.querydsl.core.group.GroupBy;
|
||||
import com.querydsl.jpa.impl.JPAQuery;
|
||||
|
||||
@Repository
|
||||
public class PersonDaoImpl implements PersonDao {
|
||||
|
@ -27,39 +27,39 @@ public class PersonDaoImpl implements PersonDao {
|
|||
|
||||
@Override
|
||||
public List<Person> findPersonsByFirstnameQueryDSL(final String firstname) {
|
||||
final JPAQuery query = new JPAQuery(em);
|
||||
final JPAQuery<Person> query = new JPAQuery<>(em);
|
||||
final QPerson person = QPerson.person;
|
||||
|
||||
return query.from(person).where(person.firstname.eq(firstname)).list(person);
|
||||
return query.from(person).where(person.firstname.eq(firstname)).fetch();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Person> findPersonsByFirstnameAndSurnameQueryDSL(final String firstname, final String surname) {
|
||||
final JPAQuery query = new JPAQuery(em);
|
||||
final JPAQuery<Person> query = new JPAQuery<>(em);
|
||||
final QPerson person = QPerson.person;
|
||||
|
||||
return query.from(person).where(person.firstname.eq(firstname).and(person.surname.eq(surname))).list(person);
|
||||
return query.from(person).where(person.firstname.eq(firstname).and(person.surname.eq(surname))).fetch();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Person> findPersonsByFirstnameInDescendingOrderQueryDSL(final String firstname) {
|
||||
final JPAQuery query = new JPAQuery(em);
|
||||
final JPAQuery<Person> query = new JPAQuery<>(em);
|
||||
final QPerson person = QPerson.person;
|
||||
|
||||
return query.from(person).where(person.firstname.eq(firstname)).orderBy(person.surname.desc()).list(person);
|
||||
return query.from(person).where(person.firstname.eq(firstname)).orderBy(person.surname.desc()).fetch();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int findMaxAge() {
|
||||
final JPAQuery query = new JPAQuery(em);
|
||||
final JPAQuery<Person> query = new JPAQuery<>(em);
|
||||
final QPerson person = QPerson.person;
|
||||
|
||||
return query.from(person).list(person.age.max()).get(0);
|
||||
return query.from(person).select(person.age.max()).fetchFirst();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Integer> findMaxAgeByName() {
|
||||
final JPAQuery query = new JPAQuery(em);
|
||||
final JPAQuery<Person> query = new JPAQuery<>(em);
|
||||
final QPerson person = QPerson.person;
|
||||
|
||||
return query.from(person).transform(GroupBy.groupBy(person.firstname).as(GroupBy.max(person.age)));
|
||||
|
|
|
@ -0,0 +1,56 @@
|
|||
/*
|
||||
* (c) Центр ИТ, 2016. Все права защищены.
|
||||
*/
|
||||
package org.baeldung.querydsl.intro.entities;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.ManyToOne;
|
||||
|
||||
@Entity
|
||||
public class BlogPost {
|
||||
|
||||
@Id
|
||||
@GeneratedValue
|
||||
private Long id;
|
||||
|
||||
private String title;
|
||||
|
||||
private String body;
|
||||
|
||||
@ManyToOne
|
||||
private User user;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public void setTitle(String code) {
|
||||
this.title = code;
|
||||
}
|
||||
|
||||
public String getBody() {
|
||||
return body;
|
||||
}
|
||||
|
||||
public void setBody(String body) {
|
||||
this.body = body;
|
||||
}
|
||||
|
||||
public User getUser() {
|
||||
return user;
|
||||
}
|
||||
|
||||
public void setUser(User user) {
|
||||
this.user = user;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,55 @@
|
|||
/*
|
||||
* (c) Центр ИТ, 2016. Все права защищены.
|
||||
*/
|
||||
package org.baeldung.querydsl.intro.entities;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import javax.persistence.*;
|
||||
|
||||
@Entity
|
||||
public class User {
|
||||
|
||||
@Id
|
||||
@GeneratedValue
|
||||
private Long id;
|
||||
|
||||
private String login;
|
||||
|
||||
private Boolean disabled;
|
||||
|
||||
@OneToMany(cascade = CascadeType.PERSIST, mappedBy = "user")
|
||||
private Set<BlogPost> blogPosts = new HashSet<>(0);
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getLogin() {
|
||||
return login;
|
||||
}
|
||||
|
||||
public void setLogin(String name) {
|
||||
this.login = name;
|
||||
}
|
||||
|
||||
public Set<BlogPost> getBlogPosts() {
|
||||
return blogPosts;
|
||||
}
|
||||
|
||||
public void setBlogPosts(Set<BlogPost> blogPosts) {
|
||||
this.blogPosts = blogPosts;
|
||||
}
|
||||
|
||||
public Boolean getDisabled() {
|
||||
return disabled;
|
||||
}
|
||||
|
||||
public void setDisabled(Boolean disabled) {
|
||||
this.disabled = disabled;
|
||||
}
|
||||
}
|
|
@ -16,4 +16,17 @@
|
|||
</properties>
|
||||
</persistence-unit>
|
||||
|
||||
<!-- PersistenceUnit for Intro to QueryDSL -->
|
||||
<persistence-unit name="org.baeldung.querydsl.intro">
|
||||
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
|
||||
<properties>
|
||||
<property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
|
||||
<property name="hibernate.connection.url" value="jdbc:hsqldb:mem:test"/>
|
||||
<property name="hibernate.connection.username" value="sa"/>
|
||||
<property name="hibernate.connection.password" value=""/>
|
||||
<property name="hibernate.hbm2ddl.auto" value="update"/>
|
||||
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect" />
|
||||
</properties>
|
||||
</persistence-unit>
|
||||
|
||||
</persistence>
|
|
@ -1,12 +1,9 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd" >
|
||||
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
|
||||
<configuration>
|
||||
|
||||
<!-- Appenders -->
|
||||
<appender name="console" class="org.apache.log4j.ConsoleAppender">
|
||||
<param name="Target" value="System.out" />
|
||||
<layout class="org.apache.log4j.PatternLayout">
|
||||
<param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} [%t] %-5p: %c - %m%n" />
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<layout class="ch.qos.logback.classic.PatternLayout">
|
||||
<Pattern>%d{yyyy-MM-dd HH:mm:ss} [%t] %-5p: %c - %m%n</Pattern>
|
||||
</layout>
|
||||
</appender>
|
||||
|
||||
|
@ -33,10 +30,8 @@
|
|||
<level value="warn" />
|
||||
</logger>
|
||||
|
||||
<!-- Root Logger -->
|
||||
<root>
|
||||
<priority value="warn" />
|
||||
<appender-ref ref="console" />
|
||||
<root level="warn">
|
||||
<appender-ref ref="STDOUT"/>
|
||||
</root>
|
||||
|
||||
</log4j:configuration>
|
||||
</configuration>
|
|
@ -0,0 +1,215 @@
|
|||
/*
|
||||
* (c) Центр ИТ, 2016. Все права защищены.
|
||||
*/
|
||||
package org.baeldung.querydsl.intro;
|
||||
|
||||
import java.util.List;
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.EntityManagerFactory;
|
||||
import javax.persistence.Persistence;
|
||||
|
||||
import org.baeldung.querydsl.intro.entities.BlogPost;
|
||||
import org.baeldung.querydsl.intro.entities.QBlogPost;
|
||||
import org.baeldung.querydsl.intro.entities.QUser;
|
||||
import org.baeldung.querydsl.intro.entities.User;
|
||||
import com.querydsl.core.Tuple;
|
||||
import com.querydsl.core.types.dsl.Expressions;
|
||||
import com.querydsl.core.types.dsl.NumberPath;
|
||||
import com.querydsl.jpa.JPAExpressions;
|
||||
import com.querydsl.jpa.impl.JPAQueryFactory;
|
||||
import org.junit.*;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class QueryDSLTest {
|
||||
|
||||
private static EntityManagerFactory emf;
|
||||
|
||||
private EntityManager em;
|
||||
|
||||
private JPAQueryFactory queryFactory;
|
||||
|
||||
@BeforeClass
|
||||
public static void populateDatabase() {
|
||||
emf = Persistence.createEntityManagerFactory("org.baeldung.querydsl.intro");
|
||||
EntityManager em = emf.createEntityManager();
|
||||
|
||||
em.getTransaction().begin();
|
||||
User user1 = new User();
|
||||
user1.setLogin("David");
|
||||
em.persist(user1);
|
||||
|
||||
User user2 = new User();
|
||||
user2.setLogin("Ash");
|
||||
em.persist(user2);
|
||||
|
||||
User user3 = new User();
|
||||
user3.setLogin("Call");
|
||||
em.persist(user3);
|
||||
|
||||
User user4 = new User();
|
||||
user4.setLogin("Bishop");
|
||||
em.persist(user4);
|
||||
|
||||
BlogPost blogPost1 = new BlogPost();
|
||||
blogPost1.setTitle("Hello World!");
|
||||
blogPost1.setUser(user1);
|
||||
em.persist(blogPost1);
|
||||
|
||||
BlogPost blogPost2 = new BlogPost();
|
||||
blogPost2.setTitle("My Second Post");
|
||||
blogPost2.setUser(user1);
|
||||
em.persist(blogPost2);
|
||||
|
||||
BlogPost blogPost3 = new BlogPost();
|
||||
blogPost3.setTitle("Hello World!");
|
||||
blogPost3.setUser(user3);
|
||||
em.persist(blogPost3);
|
||||
|
||||
em.getTransaction().commit();
|
||||
|
||||
em.close();
|
||||
|
||||
}
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
em = emf.createEntityManager();
|
||||
em.getTransaction().begin();
|
||||
queryFactory = new JPAQueryFactory(em);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFindByLogin_thenShouldReturnUser() {
|
||||
|
||||
QUser user = QUser.user;
|
||||
User aUser = queryFactory.selectFrom(user)
|
||||
.where(user.login.eq("David"))
|
||||
.fetchOne();
|
||||
|
||||
assertNotNull(aUser);
|
||||
assertEquals(aUser.getLogin(), "David");
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingOrderBy_thenResultsShouldBeOrdered() {
|
||||
|
||||
QUser user = QUser.user;
|
||||
List<User> users = queryFactory.selectFrom(user)
|
||||
.orderBy(user.login.asc())
|
||||
.fetch();
|
||||
|
||||
assertEquals(users.size(), 4);
|
||||
assertEquals(users.get(0).getLogin(), "Ash");
|
||||
assertEquals(users.get(1).getLogin(), "Bishop");
|
||||
assertEquals(users.get(2).getLogin(), "Call");
|
||||
assertEquals(users.get(3).getLogin(), "David");
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGroupingByTitle_thenReturnsTuples() {
|
||||
|
||||
QBlogPost blogPost = QBlogPost.blogPost;
|
||||
|
||||
NumberPath<Long> count = Expressions.numberPath(Long.class, "c");
|
||||
|
||||
List<Tuple> userTitleCounts = queryFactory.select(blogPost.title, blogPost.id.count().as(count))
|
||||
.from(blogPost)
|
||||
.groupBy(blogPost.title)
|
||||
.orderBy(count.desc())
|
||||
.fetch();
|
||||
|
||||
assertEquals("Hello World!", userTitleCounts.get(0).get(blogPost.title));
|
||||
assertEquals(new Long(2), userTitleCounts.get(0).get(count));
|
||||
|
||||
assertEquals("My Second Post", userTitleCounts.get(1).get(blogPost.title));
|
||||
assertEquals(new Long(1), userTitleCounts.get(1).get(count));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenJoiningWithCondition_thenResultCountShouldMatch() {
|
||||
|
||||
QUser user = QUser.user;
|
||||
QBlogPost blogPost = QBlogPost.blogPost;
|
||||
|
||||
List<User> users = queryFactory.selectFrom(user)
|
||||
.innerJoin(user.blogPosts, blogPost)
|
||||
.on(blogPost.title.eq("Hello World!"))
|
||||
.fetch();
|
||||
|
||||
assertEquals(2, users.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRefiningWithSubquery_thenResultCountShouldMatch() {
|
||||
|
||||
QUser user = QUser.user;
|
||||
QBlogPost blogPost = QBlogPost.blogPost;
|
||||
|
||||
List<User> users = queryFactory.selectFrom(user)
|
||||
.where(user.id.in(
|
||||
JPAExpressions.select(blogPost.user.id)
|
||||
.from(blogPost)
|
||||
.where(blogPost.title.eq("Hello World!"))))
|
||||
.fetch();
|
||||
|
||||
assertEquals(2, users.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUpdating_thenTheRecordShouldChange() {
|
||||
|
||||
QUser user = QUser.user;
|
||||
|
||||
queryFactory.update(user)
|
||||
.where(user.login.eq("Ash"))
|
||||
.set(user.login, "Ash2")
|
||||
.set(user.disabled, true)
|
||||
.execute();
|
||||
|
||||
em.getTransaction().commit();
|
||||
|
||||
em.getTransaction().begin();
|
||||
|
||||
assertEquals(Boolean.TRUE,
|
||||
queryFactory.select(user.disabled)
|
||||
.from(user)
|
||||
.where(user.login.eq("Ash2"))
|
||||
.fetchOne());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDeleting_thenTheRecordShouldBeAbsent() {
|
||||
|
||||
QUser user = QUser.user;
|
||||
|
||||
queryFactory.delete(user)
|
||||
.where(user.login.eq("Bishop"))
|
||||
.execute();
|
||||
|
||||
em.getTransaction().commit();
|
||||
|
||||
em.getTransaction().begin();
|
||||
|
||||
assertNull(queryFactory.selectFrom(user)
|
||||
.where(user.login.eq("Bishop"))
|
||||
.fetchOne());
|
||||
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() {
|
||||
em.getTransaction().commit();
|
||||
em.close();
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void afterClass() {
|
||||
emf.close();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,57 @@
|
|||
<?xml version="1.0"?>
|
||||
<project
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
|
||||
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>redis</artifactId>
|
||||
<version>0.1-SNAPSHOT</version>
|
||||
|
||||
<name>redis</name>
|
||||
<url>http://maven.apache.org</url>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>redis.clients</groupId>
|
||||
<artifactId>jedis</artifactId>
|
||||
<version>2.8.1</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.github.kstyrc</groupId>
|
||||
<artifactId>embedded-redis</artifactId>
|
||||
<version>0.6</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<pluginManagement>
|
||||
<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>
|
||||
</pluginManagement>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
|
||||
<!-- testing -->
|
||||
<junit.version>4.12</junit.version>
|
||||
</properties>
|
||||
</project>
|
|
@ -0,0 +1,225 @@
|
|||
package com.baeldung;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.time.Duration;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.Assert;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import redis.clients.jedis.Jedis;
|
||||
import redis.clients.jedis.JedisPool;
|
||||
import redis.clients.jedis.JedisPoolConfig;
|
||||
import redis.clients.jedis.Pipeline;
|
||||
import redis.clients.jedis.Response;
|
||||
import redis.clients.jedis.Transaction;
|
||||
import redis.embedded.RedisServer;
|
||||
|
||||
/**
|
||||
* Unit test for Redis Java library - Jedis.
|
||||
*/
|
||||
public class JedisTest {
|
||||
|
||||
private Jedis jedis;
|
||||
private static RedisServer redisServer;
|
||||
|
||||
public JedisTest() {
|
||||
jedis = new Jedis();
|
||||
}
|
||||
|
||||
@BeforeClass
|
||||
public static void setUp() throws IOException {
|
||||
redisServer = new RedisServer(6379);
|
||||
redisServer.start();
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void destroy() {
|
||||
redisServer.stop();
|
||||
}
|
||||
|
||||
@After
|
||||
public void flush() {
|
||||
jedis.flushAll();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAString_thenSaveItAsRedisStrings() {
|
||||
String key = "key";
|
||||
String value = "value";
|
||||
|
||||
jedis.set(key, value);
|
||||
String value2 = jedis.get(key);
|
||||
|
||||
Assert.assertEquals(value, value2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListElements_thenSaveThemInRedisList() {
|
||||
String queue = "queue#tasks";
|
||||
|
||||
String taskOne = "firstTask";
|
||||
String taskTwo = "secondTask";
|
||||
String taskThree = "thirdTask";
|
||||
|
||||
jedis.lpush(queue, taskOne, taskTwo);
|
||||
|
||||
String taskReturnedOne = jedis.rpop(queue);
|
||||
|
||||
jedis.lpush(queue, taskThree);
|
||||
Assert.assertEquals(taskOne, taskReturnedOne);
|
||||
|
||||
String taskReturnedTwo = jedis.rpop(queue);
|
||||
String taskReturnedThree = jedis.rpop(queue);
|
||||
|
||||
Assert.assertEquals(taskTwo, taskReturnedTwo);
|
||||
Assert.assertEquals(taskThree, taskReturnedThree);
|
||||
|
||||
String taskReturnedFour = jedis.rpop(queue);
|
||||
Assert.assertNull(taskReturnedFour);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSetElements_thenSaveThemInRedisSet() {
|
||||
String countries = "countries";
|
||||
|
||||
String countryOne = "Spain";
|
||||
String countryTwo = "Ireland";
|
||||
String countryThree = "Ireland";
|
||||
|
||||
jedis.sadd(countries, countryOne);
|
||||
|
||||
Set<String> countriesSet = jedis.smembers(countries);
|
||||
Assert.assertEquals(1, countriesSet.size());
|
||||
|
||||
jedis.sadd(countries, countryTwo);
|
||||
countriesSet = jedis.smembers(countries);
|
||||
Assert.assertEquals(2, countriesSet.size());
|
||||
|
||||
jedis.sadd(countries, countryThree);
|
||||
countriesSet = jedis.smembers(countries);
|
||||
Assert.assertEquals(2, countriesSet.size());
|
||||
|
||||
boolean exists = jedis.sismember(countries, countryThree);
|
||||
Assert.assertTrue(exists);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenObjectFields_thenSaveThemInRedisHash() {
|
||||
String key = "user#1";
|
||||
|
||||
String field = "name";
|
||||
String value = "William";
|
||||
|
||||
String field2 = "job";
|
||||
String value2 = "politician";
|
||||
|
||||
jedis.hset(key, field, value);
|
||||
jedis.hset(key, field2, value2);
|
||||
|
||||
String value3 = jedis.hget(key, field);
|
||||
Assert.assertEquals(value, value3);
|
||||
|
||||
Map<String, String> fields = jedis.hgetAll(key);
|
||||
String value4 = fields.get(field2);
|
||||
Assert.assertEquals(value2, value4);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenARanking_thenSaveItInRedisSortedSet() {
|
||||
String key = "ranking";
|
||||
|
||||
Map<String, Double> scores = new HashMap<>();
|
||||
|
||||
scores.put("PlayerOne", 3000.0);
|
||||
scores.put("PlayerTwo", 1500.0);
|
||||
scores.put("PlayerThree", 8200.0);
|
||||
|
||||
for (String player : scores.keySet()) {
|
||||
jedis.zadd(key, scores.get(player), player);
|
||||
}
|
||||
|
||||
Set<String> players = jedis.zrevrange(key, 0, 1);
|
||||
Assert.assertEquals("PlayerThree", players.iterator().next());
|
||||
|
||||
long rank = jedis.zrevrank(key, "PlayerOne");
|
||||
Assert.assertEquals(1, rank);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultipleOperationsThatNeedToBeExecutedAtomically_thenWrapThemInATransaction() {
|
||||
String friendsPrefix = "friends#";
|
||||
|
||||
String userOneId = "4352523";
|
||||
String userTwoId = "5552321";
|
||||
|
||||
Transaction t = jedis.multi();
|
||||
t.sadd(friendsPrefix + userOneId, userTwoId);
|
||||
t.sadd(friendsPrefix + userTwoId, userOneId);
|
||||
t.exec();
|
||||
|
||||
boolean exists = jedis.sismember(friendsPrefix + userOneId, userTwoId);
|
||||
Assert.assertTrue(exists);
|
||||
|
||||
exists = jedis.sismember(friendsPrefix + userTwoId, userOneId);
|
||||
Assert.assertTrue(exists);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultipleIndependentOperations_whenNetworkOptimizationIsImportant_thenWrapThemInAPipeline() {
|
||||
String userOneId = "4352523";
|
||||
String userTwoId = "4849888";
|
||||
|
||||
Pipeline p = jedis.pipelined();
|
||||
p.sadd("searched#" + userOneId, "paris");
|
||||
p.zadd("ranking", 126, userOneId);
|
||||
p.zadd("ranking", 325, userTwoId);
|
||||
Response<Boolean> pipeExists = p.sismember("searched#" + userOneId, "paris");
|
||||
Response<Set<String>> pipeRanking = p.zrange("ranking", 0, -1);
|
||||
p.sync();
|
||||
|
||||
Assert.assertTrue(pipeExists.get());
|
||||
Assert.assertEquals(2, pipeRanking.get().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAPoolConfiguration_thenCreateAJedisPool() {
|
||||
final JedisPoolConfig poolConfig = buildPoolConfig();
|
||||
|
||||
try (JedisPool jedisPool = new JedisPool(poolConfig, "localhost"); Jedis jedis = jedisPool.getResource()) {
|
||||
|
||||
// do simple operation to verify that the Jedis resource is working
|
||||
// properly
|
||||
String key = "key";
|
||||
String value = "value";
|
||||
|
||||
jedis.set(key, value);
|
||||
String value2 = jedis.get(key);
|
||||
|
||||
Assert.assertEquals(value, value2);
|
||||
|
||||
// flush Redis
|
||||
jedis.flushAll();
|
||||
}
|
||||
}
|
||||
|
||||
private JedisPoolConfig buildPoolConfig() {
|
||||
final JedisPoolConfig poolConfig = new JedisPoolConfig();
|
||||
poolConfig.setMaxTotal(128);
|
||||
poolConfig.setMaxIdle(128);
|
||||
poolConfig.setMinIdle(16);
|
||||
poolConfig.setTestOnBorrow(true);
|
||||
poolConfig.setTestOnReturn(true);
|
||||
poolConfig.setTestWhileIdle(true);
|
||||
poolConfig.setMinEvictableIdleTimeMillis(Duration.ofSeconds(60).toMillis());
|
||||
poolConfig.setTimeBetweenEvictionRunsMillis(Duration.ofSeconds(30).toMillis());
|
||||
poolConfig.setNumTestsPerEvictionRun(3);
|
||||
poolConfig.setBlockWhenExhausted(true);
|
||||
return poolConfig;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,22 @@
|
|||
package org.baeldung.properties.spring;
|
||||
|
||||
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
public class PropertiesWithPlaceHolderConfigurer {
|
||||
|
||||
public PropertiesWithPlaceHolderConfigurer() {
|
||||
super();
|
||||
}
|
||||
|
||||
|
||||
@Bean
|
||||
public PropertyPlaceholderConfigurer propertyConfigurer() {
|
||||
final PropertyPlaceholderConfigurer props = new PropertyPlaceholderConfigurer();
|
||||
props.setSystemPropertiesMode(PropertyPlaceholderConfigurer.SYSTEM_PROPERTIES_MODE_FALLBACK);
|
||||
return props;
|
||||
}
|
||||
|
||||
}
|
|
@ -1,32 +0,0 @@
|
|||
<?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.m2e.MAVEN2_CLASSPATH_CONTAINER">
|
||||
<attributes>
|
||||
<attribute name="maven.pomderived" value="true"/>
|
||||
<attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
|
||||
</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="output" path="target/classes"/>
|
||||
</classpath>
|
|
@ -1 +1,4 @@
|
|||
/target/
|
||||
.settings/
|
||||
.classpath
|
||||
.project
|
||||
|
|
|
@ -1,48 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<projectDescription>
|
||||
<name>spring-boot</name>
|
||||
<comment></comment>
|
||||
<projects>
|
||||
</projects>
|
||||
<buildSpec>
|
||||
<buildCommand>
|
||||
<name>org.eclipse.wst.jsdt.core.javascriptValidator</name>
|
||||
<arguments>
|
||||
</arguments>
|
||||
</buildCommand>
|
||||
<buildCommand>
|
||||
<name>org.eclipse.jdt.core.javabuilder</name>
|
||||
<arguments>
|
||||
</arguments>
|
||||
</buildCommand>
|
||||
<buildCommand>
|
||||
<name>org.eclipse.wst.common.project.facet.core.builder</name>
|
||||
<arguments>
|
||||
</arguments>
|
||||
</buildCommand>
|
||||
<buildCommand>
|
||||
<name>org.eclipse.wst.validation.validationbuilder</name>
|
||||
<arguments>
|
||||
</arguments>
|
||||
</buildCommand>
|
||||
<buildCommand>
|
||||
<name>org.springframework.ide.eclipse.core.springbuilder</name>
|
||||
<arguments>
|
||||
</arguments>
|
||||
</buildCommand>
|
||||
<buildCommand>
|
||||
<name>org.eclipse.m2e.core.maven2Builder</name>
|
||||
<arguments>
|
||||
</arguments>
|
||||
</buildCommand>
|
||||
</buildSpec>
|
||||
<natures>
|
||||
<nature>org.springframework.ide.eclipse.core.springnature</nature>
|
||||
<nature>org.eclipse.jem.workbench.JavaEMFNature</nature>
|
||||
<nature>org.eclipse.wst.common.modulecore.ModuleCoreNature</nature>
|
||||
<nature>org.eclipse.jdt.core.javanature</nature>
|
||||
<nature>org.eclipse.m2e.core.maven2Nature</nature>
|
||||
<nature>org.eclipse.wst.common.project.facet.core.nature</nature>
|
||||
<nature>org.eclipse.wst.jsdt.core.jsNature</nature>
|
||||
</natures>
|
||||
</projectDescription>
|
|
@ -1,4 +1,5 @@
|
|||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>spring-boot</artifactId>
|
||||
|
@ -11,15 +12,29 @@
|
|||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>1.3.3.RELEASE</version>
|
||||
<version>1.3.6.RELEASE</version>
|
||||
<relativePath /> <!-- lookup parent from repository -->
|
||||
</parent>
|
||||
|
||||
<properties>
|
||||
<!-- The main class to start by executing java -jar -->
|
||||
<start-class>org.baeldung.boot.DemoApplication</start-class>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<java.version>1.8</java.version>
|
||||
<!-- <spring.version>4.3.0.RELEASE</spring.version> -->
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-jpa</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-actuator</artifactId>
|
||||
|
@ -34,6 +49,17 @@
|
|||
<groupId>io.dropwizard.metrics</groupId>
|
||||
<artifactId>metrics-core</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
|
|
@ -0,0 +1,14 @@
|
|||
package org.baeldung.boot;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class DemoApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
System.setProperty("spring.config.name", "demo");
|
||||
SpringApplication.run(DemoApplication.class, args);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,39 @@
|
|||
package org.baeldung.boot.model;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.Id;
|
||||
|
||||
@Entity
|
||||
public class Foo implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
@Id
|
||||
@GeneratedValue
|
||||
private Integer id;
|
||||
private String name;
|
||||
|
||||
public Foo() {
|
||||
}
|
||||
|
||||
public Foo(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Integer getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Integer id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,8 @@
|
|||
package org.baeldung.boot.repository;
|
||||
|
||||
import org.baeldung.boot.model.Foo;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface FooRepository extends JpaRepository<Foo, Integer> {
|
||||
public Foo findByName(String name);
|
||||
}
|
|
@ -0,0 +1,6 @@
|
|||
spring.output.ansi.enabled=never
|
||||
server.port=7070
|
||||
|
||||
# Security
|
||||
security.user.name=admin
|
||||
security.user.password=password
|
|
@ -0,0 +1,17 @@
|
|||
package org.baeldung.boot;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.boot.test.SpringApplicationConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.test.context.web.WebAppConfiguration;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@SpringApplicationConfiguration(classes = DemoApplication.class)
|
||||
@WebAppConfiguration
|
||||
public class DemoApplicationTests {
|
||||
|
||||
@Test
|
||||
public void contextLoads() {
|
||||
}
|
||||
}
|
|
@ -0,0 +1,34 @@
|
|||
package org.baeldung.boot.repository;
|
||||
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import org.baeldung.boot.DemoApplicationTests;
|
||||
import org.baeldung.boot.model.Foo;
|
||||
|
||||
import static org.hamcrest.Matchers.notNullValue;
|
||||
import static org.hamcrest.Matchers.is;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@Transactional
|
||||
public class FooRepositoryTest extends DemoApplicationTests {
|
||||
@Autowired
|
||||
private FooRepository fooRepository;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
fooRepository.save(new Foo("Foo"));
|
||||
fooRepository.save(new Foo("Bar"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testFindByName() {
|
||||
Foo foo = fooRepository.findByName("Bar");
|
||||
assertThat(foo, notNullValue());
|
||||
assertThat(foo.getId(), is(2));
|
||||
}
|
||||
|
||||
}
|
|
@ -8,7 +8,8 @@
|
|||
- [Hibernate Pagination](http://www.baeldung.com/hibernate-pagination)
|
||||
- [Sorting with Hibernate](http://www.baeldung.com/hibernate-sort)
|
||||
- [Auditing with JPA, Hibernate, and Spring Data JPA](http://www.baeldung.com/database-auditing-jpa)
|
||||
|
||||
- [Stored Procedures with Hibernate](http://www.baeldung.com/stored-procedures-with-hibernate-tutorial)
|
||||
- [Hibernate: save, persist, update, merge, saveOrUpdate](http://www.baeldung.com/hibernate-save-persist-update-merge-saveorupdate/)
|
||||
|
||||
### Quick Start
|
||||
|
||||
|
|
|
@ -149,6 +149,13 @@
|
|||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.hsqldb</groupId>
|
||||
<artifactId>hsqldb</artifactId>
|
||||
<version>2.3.4</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
|
|
@ -11,93 +11,97 @@ import javax.persistence.GenerationType;
|
|||
import javax.persistence.Id;
|
||||
import javax.persistence.JoinColumn;
|
||||
import javax.persistence.ManyToOne;
|
||||
import javax.persistence.NamedNativeQueries;
|
||||
import javax.persistence.NamedNativeQuery;
|
||||
|
||||
import org.hibernate.envers.Audited;
|
||||
|
||||
@NamedNativeQueries({
|
||||
@NamedNativeQuery(name = "callGetAllFoos", query = "CALL GetAllFoos()", resultClass = Foo.class),
|
||||
@NamedNativeQuery(name = "callGetFoosByName", query = "CALL GetFoosByName(:fooName)", resultClass = Foo.class) })
|
||||
@Entity
|
||||
@Audited
|
||||
// @Proxy(lazy = false)
|
||||
public class Foo implements Serializable {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
@Column(name = "id")
|
||||
private long id;
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
@Column(name = "id")
|
||||
private long id;
|
||||
|
||||
@Column(name = "name")
|
||||
private String name;
|
||||
@Column(name = "name")
|
||||
private String name;
|
||||
|
||||
@ManyToOne(targetEntity = Bar.class, cascade = CascadeType.ALL, fetch = FetchType.EAGER)
|
||||
@JoinColumn(name = "BAR_ID")
|
||||
private Bar bar = new Bar();
|
||||
@ManyToOne(targetEntity = Bar.class, cascade = CascadeType.ALL, fetch = FetchType.EAGER)
|
||||
@JoinColumn(name = "BAR_ID")
|
||||
private Bar bar = new Bar();
|
||||
|
||||
public Foo() {
|
||||
super();
|
||||
}
|
||||
public Foo() {
|
||||
super();
|
||||
}
|
||||
|
||||
public Foo(final String name) {
|
||||
super();
|
||||
this.name = name;
|
||||
}
|
||||
public Foo(final String name) {
|
||||
super();
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
//
|
||||
//
|
||||
|
||||
public Bar getBar() {
|
||||
return bar;
|
||||
}
|
||||
public Bar getBar() {
|
||||
return bar;
|
||||
}
|
||||
|
||||
public void setBar(final Bar bar) {
|
||||
this.bar = bar;
|
||||
}
|
||||
public void setBar(final Bar bar) {
|
||||
this.bar = bar;
|
||||
}
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(final long id) {
|
||||
this.id = id;
|
||||
}
|
||||
public void setId(final long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(final String name) {
|
||||
this.name = name;
|
||||
}
|
||||
public void setName(final String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
//
|
||||
//
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result + ((name == null) ? 0 : name.hashCode());
|
||||
return result;
|
||||
}
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result + ((name == null) ? 0 : name.hashCode());
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(final Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null)
|
||||
return false;
|
||||
if (getClass() != obj.getClass())
|
||||
return false;
|
||||
final Foo other = (Foo) obj;
|
||||
if (name == null) {
|
||||
if (other.name != null)
|
||||
return false;
|
||||
} else if (!name.equals(other.name))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
final StringBuilder builder = new StringBuilder();
|
||||
builder.append("Foo [name=").append(name).append("]");
|
||||
return builder.toString();
|
||||
}
|
||||
@Override
|
||||
public boolean equals(final Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null)
|
||||
return false;
|
||||
if (getClass() != obj.getClass())
|
||||
return false;
|
||||
final Foo other = (Foo) obj;
|
||||
if (name == null) {
|
||||
if (other.name != null)
|
||||
return false;
|
||||
} else if (!name.equals(other.name))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
final StringBuilder builder = new StringBuilder();
|
||||
builder.append("Foo [name=").append(name).append("]");
|
||||
return builder.toString();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,31 @@
|
|||
package com.baeldung.persistence.model;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.Id;
|
||||
|
||||
@Entity
|
||||
public class Person {
|
||||
|
||||
@Id
|
||||
@GeneratedValue
|
||||
private Long id;
|
||||
|
||||
private String name;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,20 @@
|
|||
DELIMITER //
|
||||
CREATE PROCEDURE GetFoosByName(IN fooName VARCHAR(255))
|
||||
LANGUAGE SQL
|
||||
DETERMINISTIC
|
||||
SQL SECURITY DEFINER
|
||||
BEGIN
|
||||
SELECT * FROM foo WHERE name = fooName;
|
||||
END //
|
||||
DELIMITER ;
|
||||
|
||||
|
||||
DELIMITER //
|
||||
CREATE PROCEDURE GetAllFoos()
|
||||
LANGUAGE SQL
|
||||
DETERMINISTIC
|
||||
SQL SECURITY DEFINER
|
||||
BEGIN
|
||||
SELECT * FROM foo;
|
||||
END //
|
||||
DELIMITER ;
|
|
@ -0,0 +1,272 @@
|
|||
package com.baeldung.persistence.save;
|
||||
|
||||
|
||||
import com.baeldung.persistence.model.Person;
|
||||
import org.hibernate.HibernateException;
|
||||
import org.hibernate.Session;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
|
||||
import org.hibernate.cfg.Configuration;
|
||||
import org.hibernate.dialect.HSQLDialect;
|
||||
import org.hibernate.service.ServiceRegistry;
|
||||
import org.junit.*;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
/**
|
||||
* Testing specific implementation details for different methods:
|
||||
* persist, save, merge, update, saveOrUpdate.
|
||||
*/
|
||||
public class SaveMethodsTest {
|
||||
|
||||
private static SessionFactory sessionFactory;
|
||||
|
||||
private Session session;
|
||||
|
||||
@BeforeClass
|
||||
public static void beforeTests() {
|
||||
Configuration configuration = new Configuration()
|
||||
.addAnnotatedClass(Person.class)
|
||||
.setProperty("hibernate.dialect", HSQLDialect.class.getName())
|
||||
.setProperty("hibernate.connection.driver_class", org.hsqldb.jdbcDriver.class.getName())
|
||||
.setProperty("hibernate.connection.url", "jdbc:hsqldb:mem:test")
|
||||
.setProperty("hibernate.connection.username", "sa")
|
||||
.setProperty("hibernate.connection.password", "")
|
||||
.setProperty("hibernate.hbm2ddl.auto", "update");
|
||||
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
|
||||
configuration.getProperties()).build();
|
||||
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
|
||||
}
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
session = sessionFactory.openSession();
|
||||
session.beginTransaction();
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void whenPersistTransient_thenSavedToDatabaseOnCommit() {
|
||||
|
||||
Person person = new Person();
|
||||
person.setName("John");
|
||||
session.persist(person);
|
||||
|
||||
session.getTransaction().commit();
|
||||
session.close();
|
||||
|
||||
session = sessionFactory.openSession();
|
||||
session.beginTransaction();
|
||||
|
||||
assertNotNull(session.get(Person.class, person.getId()));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPersistPersistent_thenNothingHappens() {
|
||||
|
||||
Person person = new Person();
|
||||
person.setName("John");
|
||||
|
||||
session.persist(person);
|
||||
Long id1 = person.getId();
|
||||
|
||||
session.persist(person);
|
||||
Long id2 = person.getId();
|
||||
|
||||
assertEquals(id1, id2);
|
||||
}
|
||||
|
||||
@Test(expected = HibernateException.class)
|
||||
public void whenPersistDetached_thenThrowsException() {
|
||||
|
||||
Person person = new Person();
|
||||
person.setName("John");
|
||||
session.persist(person);
|
||||
session.evict(person);
|
||||
|
||||
session.persist(person);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSaveTransient_thenIdGeneratedImmediately() {
|
||||
|
||||
Person person = new Person();
|
||||
person.setName("John");
|
||||
|
||||
assertNull(person.getId());
|
||||
|
||||
Long id = (Long) session.save(person);
|
||||
|
||||
assertNotNull(id);
|
||||
|
||||
session.getTransaction().commit();
|
||||
session.close();
|
||||
|
||||
assertEquals(id, person.getId());
|
||||
|
||||
session = sessionFactory.openSession();
|
||||
session.beginTransaction();
|
||||
|
||||
assertNotNull(session.get(Person.class, person.getId()));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSavePersistent_thenNothingHappens() {
|
||||
|
||||
Person person = new Person();
|
||||
person.setName("John");
|
||||
Long id1 = (Long) session.save(person);
|
||||
Long id2 = (Long) session.save(person);
|
||||
assertEquals(id1, id2);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSaveDetached_thenNewInstancePersisted() {
|
||||
|
||||
Person person = new Person();
|
||||
person.setName("John");
|
||||
Long id1 = (Long) session.save(person);
|
||||
session.evict(person);
|
||||
|
||||
Long id2 = (Long) session.save(person);
|
||||
assertNotEquals(id1, id2);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenMergeDetached_thenEntityUpdatedFromDatabase() {
|
||||
|
||||
Person person = new Person();
|
||||
person.setName("John");
|
||||
session.save(person);
|
||||
session.evict(person);
|
||||
|
||||
person.setName("Mary");
|
||||
Person mergedPerson = (Person) session.merge(person);
|
||||
|
||||
assertNotSame(person, mergedPerson);
|
||||
assertEquals("Mary", mergedPerson.getName());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenMergeTransient_thenNewEntitySavedToDatabase() {
|
||||
|
||||
Person person = new Person();
|
||||
person.setName("John");
|
||||
Person mergedPerson = (Person) session.merge(person);
|
||||
|
||||
session.getTransaction().commit();
|
||||
session.beginTransaction();
|
||||
|
||||
assertNull(person.getId());
|
||||
assertNotNull(mergedPerson.getId());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenMergePersistent_thenReturnsSameObject() {
|
||||
|
||||
Person person = new Person();
|
||||
person.setName("John");
|
||||
session.save(person);
|
||||
|
||||
Person mergedPerson = (Person) session.merge(person);
|
||||
|
||||
assertSame(person, mergedPerson);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUpdateDetached_thenEntityUpdatedFromDatabase() {
|
||||
|
||||
Person person = new Person();
|
||||
person.setName("John");
|
||||
session.save(person);
|
||||
session.evict(person);
|
||||
|
||||
person.setName("Mary");
|
||||
session.update(person);
|
||||
assertEquals("Mary", person.getName());
|
||||
|
||||
}
|
||||
|
||||
@Test(expected = HibernateException.class)
|
||||
public void whenUpdateTransient_thenThrowsException() {
|
||||
|
||||
Person person = new Person();
|
||||
person.setName("John");
|
||||
session.update(person);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUpdatePersistent_thenNothingHappens() {
|
||||
|
||||
Person person = new Person();
|
||||
person.setName("John");
|
||||
session.save(person);
|
||||
|
||||
session.update(person);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSaveOrUpdateDetached_thenEntityUpdatedFromDatabase() {
|
||||
|
||||
Person person = new Person();
|
||||
person.setName("John");
|
||||
session.save(person);
|
||||
session.evict(person);
|
||||
|
||||
person.setName("Mary");
|
||||
session.saveOrUpdate(person);
|
||||
assertEquals("Mary", person.getName());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSaveOrUpdateTransient_thenSavedToDatabaseOnCommit() {
|
||||
|
||||
Person person = new Person();
|
||||
person.setName("John");
|
||||
session.saveOrUpdate(person);
|
||||
|
||||
session.getTransaction().commit();
|
||||
session.close();
|
||||
|
||||
session = sessionFactory.openSession();
|
||||
session.beginTransaction();
|
||||
|
||||
assertNotNull(session.get(Person.class, person.getId()));
|
||||
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSaveOrUpdatePersistent_thenNothingHappens() {
|
||||
|
||||
Person person = new Person();
|
||||
person.setName("John");
|
||||
session.save(person);
|
||||
|
||||
session.saveOrUpdate(person);
|
||||
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() {
|
||||
session.getTransaction().commit();
|
||||
session.close();
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void afterTests() {
|
||||
sessionFactory.close();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,126 @@
|
|||
package com.baeldung.persistence.service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.hibernate.Query;
|
||||
import org.hibernate.Session;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.hibernate.exception.SQLGrammarException;
|
||||
import org.junit.After;
|
||||
import org.junit.Assume;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.test.context.support.AnnotationConfigContextLoader;
|
||||
|
||||
import com.baeldung.persistence.model.Foo;
|
||||
import com.baeldung.spring.PersistenceConfig;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = {PersistenceConfig.class}, loader = AnnotationConfigContextLoader.class)
|
||||
public class FooStoredProceduresIntegrationTest {
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(FooStoredProceduresIntegrationTest.class);
|
||||
|
||||
@Autowired
|
||||
private SessionFactory sessionFactory;
|
||||
|
||||
@Autowired
|
||||
private IFooService fooService;
|
||||
|
||||
private Session session;
|
||||
|
||||
@Before
|
||||
public final void before() {
|
||||
session = sessionFactory.openSession();
|
||||
Assume.assumeTrue(getAllFoosExists());
|
||||
Assume.assumeTrue(getFoosByNameExists());
|
||||
}
|
||||
|
||||
private boolean getFoosByNameExists() {
|
||||
try {
|
||||
Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()")
|
||||
.addEntity(Foo.class);
|
||||
sqlQuery.list();
|
||||
return true;
|
||||
} catch (SQLGrammarException e) {
|
||||
LOGGER.error("WARNING : GetFoosByName() Procedure is may be missing ", e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private boolean getAllFoosExists() {
|
||||
try {
|
||||
Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()")
|
||||
.addEntity(Foo.class);
|
||||
sqlQuery.list();
|
||||
return true;
|
||||
} catch (SQLGrammarException e) {
|
||||
LOGGER.error("WARNING : GetAllFoos() Procedure is may be missing ", e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@After
|
||||
public final void after() {
|
||||
session.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void getAllFoosUsingStoredProcedures() {
|
||||
|
||||
fooService.create(new Foo(randomAlphabetic(6)));
|
||||
|
||||
// Stored procedure getAllFoos using createSQLQuery
|
||||
Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity(
|
||||
Foo.class);
|
||||
@SuppressWarnings("unchecked")
|
||||
List<Foo> allFoos = sqlQuery.list();
|
||||
for (Foo foo : allFoos) {
|
||||
LOGGER.info("getAllFoos() SQL Query result : {}", foo.getName());
|
||||
}
|
||||
assertEquals(allFoos.size(), fooService.findAll().size());
|
||||
|
||||
// Stored procedure getAllFoos using a Named Query
|
||||
Query namedQuery = session.getNamedQuery("callGetAllFoos");
|
||||
@SuppressWarnings("unchecked")
|
||||
List<Foo> allFoos2 = namedQuery.list();
|
||||
for (Foo foo : allFoos2) {
|
||||
LOGGER.info("getAllFoos() NamedQuery result : {}", foo.getName());
|
||||
}
|
||||
assertEquals(allFoos2.size(), fooService.findAll().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void getFoosByNameUsingStoredProcedures() {
|
||||
|
||||
fooService.create(new Foo("NewFooName"));
|
||||
|
||||
// Stored procedure getFoosByName using createSQLQuery()
|
||||
Query sqlQuery = session.createSQLQuery("CALL GetFoosByName(:fooName)")
|
||||
.addEntity(Foo.class).setParameter("fooName", "NewFooName");
|
||||
@SuppressWarnings("unchecked")
|
||||
List<Foo> allFoosByName = sqlQuery.list();
|
||||
for (Foo foo : allFoosByName) {
|
||||
LOGGER.info("getFoosByName() using SQL Query : found => {}", foo.toString());
|
||||
}
|
||||
|
||||
// Stored procedure getFoosByName using getNamedQuery()
|
||||
Query namedQuery = session.getNamedQuery("callGetFoosByName")
|
||||
.setParameter("fooName", "NewFooName");
|
||||
@SuppressWarnings("unchecked")
|
||||
List<Foo> allFoosByName2 = namedQuery.list();
|
||||
for (Foo foo : allFoosByName2) {
|
||||
LOGGER.info("getFoosByName() using Native Query : found => {}", foo.toString());
|
||||
}
|
||||
|
||||
}
|
||||
}
|
|
@ -151,11 +151,10 @@
|
|||
<artifactId>protobuf-java</artifactId>
|
||||
<version>2.6.1</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.esotericsoftware.kryo</groupId>
|
||||
<groupId>com.esotericsoftware</groupId>
|
||||
<artifactId>kryo</artifactId>
|
||||
<version>2.24.0</version>
|
||||
<version>4.0.0</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
|
|
|
@ -0,0 +1,63 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>webjarsdemo</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<name>webjarsdemo</name>
|
||||
<description>Demo project for webjars using Spring Boot</description>
|
||||
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>1.3.5.RELEASE</version>
|
||||
<relativePath /> <!-- lookup parent from repository -->
|
||||
</parent>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<java.version>1.8</java.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-thymeleaf</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.webjars</groupId>
|
||||
<artifactId>bootstrap</artifactId>
|
||||
<version>3.3.4</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.webjars</groupId>
|
||||
<artifactId>jquery</artifactId>
|
||||
<version>2.1.4</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
|
||||
</project>
|
|
@ -0,0 +1,15 @@
|
|||
package com.baeldung;
|
||||
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
|
||||
@Controller
|
||||
public class TestController {
|
||||
|
||||
@RequestMapping(value="/")
|
||||
public String welcome(Model model){
|
||||
return "index";
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,12 @@
|
|||
package com.baeldung;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class WebjarsdemoApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(WebjarsdemoApplication.class, args);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,19 @@
|
|||
<html>
|
||||
<head>
|
||||
<title>WebJars Demo</title>
|
||||
<link rel="stylesheet" href="/webjars/bootstrap/3.3.4/css/bootstrap.min.css" />
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<div class="container"><br/>
|
||||
<div class="alert alert-success">
|
||||
<a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
|
||||
<strong>Success!</strong> It is working as we expected.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="/webjars/jquery/2.1.4/jquery.min.js"></script>
|
||||
<script src="/webjars/bootstrap/3.3.4/js/bootstrap.min.js"></script>
|
||||
|
||||
</body>
|
||||
</html>
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue