Merge branches 'gcasanova-master', 'master' and 'nguyennamthai-master' of https://github.com/eugenp/tutorials

This commit is contained in:
Alex Theedom 2016-07-12 21:18:07 +01:00
commit a2c12b060d
57 changed files with 1546 additions and 58644 deletions

View File

@ -0,0 +1,53 @@
<?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>
<skipTests>true</skipTests>
<cxf.version>3.1.6</cxf.version>
</properties>
<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>
<profiles>
<profile>
<id>server</id>
<build>
<defaultGoal>test</defaultGoal>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<executions>
<execution>
<phase>test</phase>
<goals>
<goal>java</goal>
</goals>
<configuration>
<mainClass>com.baeldung.cxf.introduction.Server</mainClass>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>

View File

@ -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();
}

View File

@ -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;
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.cxf.introduction;
import javax.xml.ws.Endpoint;
public class Server {
private Server() {
BaeldungImpl implementor = new BaeldungImpl();
String address = "http://localhost:8080/baeldung";
Endpoint.publish(address, implementor);
}
public static void main(String args[]) throws InterruptedException {
new Server();
System.out.println("Server ready");
Thread.sleep(60 * 1000);
System.out.println("Server exiting");
System.exit(0);
}
}

View File

@ -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();
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}
}

View File

@ -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;
}
}

View File

@ -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 Baeldung 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());
}
}

40
apache-cxf/pom.xml Normal file
View File

@ -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>

View File

@ -23,7 +23,7 @@
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.4.1</version>
<version>3.5.1</version>
<scope>test</scope>
</dependency>
<dependency>

View File

@ -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 {

View File

@ -1,11 +1,11 @@
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.Sets;
import com.google.common.collect.Table;
import com.google.common.collect.TreeRangeMap;
import com.google.common.io.Files;
@ -14,6 +14,7 @@ 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;
@ -22,17 +23,17 @@ public class AssertJGuavaTest {
@Test
public void givenTwoEmptyFiles_whenComparingContent_thenEqual() throws Exception {
final File temp = File.createTempFile("bael", "dung");
final File temp1 = File.createTempFile("bael", "dung1");
final File temp2 = File.createTempFile("bael", "dung2");
assertThat(Files.asByteSource(temp))
assertThat(Files.asByteSource(temp1))
.hasSize(0)
.hasSameContentAs(Files.asByteSource(temp2));
}
@Test
public void givenMultimap_whenVerifying_thenCorrect() throws Exception {
final Multimap<Integer, String> mmap = Multimaps.newMultimap(new HashMap<>(), Sets::newHashSet);
final Multimap<Integer, String> mmap = ArrayListMultimap.create();
mmap.put(1, "one");
mmap.put(1, "1");
@ -43,6 +44,30 @@ public class AssertJGuavaTest {
.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");

View File

@ -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());
}
}

View File

@ -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>

View File

@ -1,4 +0,0 @@
/**
*
*/
window.Todos = Ember.Application.create();

File diff suppressed because it is too large Load Diff

View File

@ -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 + "]";
}
}

View File

@ -3,6 +3,6 @@ package com.baeldung.jackson.dtos;
import com.fasterxml.jackson.annotation.JsonIgnoreType;
@JsonIgnoreType
public class MyMixInForString {
public class MyMixInForIgnoreType {
//
}

View File

@ -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

View File

@ -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);

View File

@ -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));
}

View File

@ -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);
}

View File

@ -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());
}

View File

@ -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);

View File

@ -31,6 +31,13 @@
<version>${javax.el.version}</version>
</dependency>
<!-- JSTL -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- Spring -->

View File

@ -1,38 +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">
<!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>
<title>Baeldung | The EL Intro</title>
</h:head>
</h:head>
<h:body>
<h:form id="elForm">
<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>
</h:form>
</h:body>
<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>

25
json/pom.xml Normal file
View File

@ -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>

View File

@ -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);
}
}

View File

@ -0,0 +1,5 @@
{
"id": 1,
"name": "Lampshade",
"price": 0
}

View File

@ -0,0 +1,5 @@
{
"id": 1,
"name": "Lampshade",
"price": 10
}

View File

@ -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"]
}

View File

@ -14,7 +14,7 @@
<modules>
<module>assertj</module>
<module>apache-cxf</module>
<module>core-java</module>
<module>core-java-8</module>
<module>gson</module>

View File

@ -25,201 +25,201 @@ import redis.embedded.RedisServer;
*/
public class JedisTest {
private Jedis jedis;
private static RedisServer redisServer;
private Jedis jedis;
private static RedisServer redisServer;
public JedisTest() {
jedis = new Jedis();
}
public JedisTest() {
jedis = new Jedis();
}
@BeforeClass
public static void setUp() throws IOException {
redisServer = new RedisServer(6379);
redisServer.start();
}
@BeforeClass
public static void setUp() throws IOException {
redisServer = new RedisServer(6379);
redisServer.start();
}
@AfterClass
public static void destroy() {
redisServer.stop();
}
@AfterClass
public static void destroy() {
redisServer.stop();
}
@After
public void flush() {
jedis.flushAll();
}
@After
public void flush() {
jedis.flushAll();
}
@Test
public void givenAStringThenSaveItAsRedisStrings() {
String key = "key";
String value = "value";
@Test
public void givenAString_thenSaveItAsRedisStrings() {
String key = "key";
String value = "value";
jedis.set(key, value);
String value2 = jedis.get(key);
jedis.set(key, value);
String value2 = jedis.get(key);
Assert.assertEquals(value, value2);
}
Assert.assertEquals(value, value2);
}
@Test
public void givenListElementsThenSaveThemInRedisList() {
String queue = "queue#tasks";
@Test
public void givenListElements_thenSaveThemInRedisList() {
String queue = "queue#tasks";
String taskOne = "firstTask";
String taskTwo = "secondTask";
String taskThree = "thirdTask";
String taskOne = "firstTask";
String taskTwo = "secondTask";
String taskThree = "thirdTask";
jedis.lpush(queue, taskOne, taskTwo);
jedis.lpush(queue, taskOne, taskTwo);
String taskReturnedOne = jedis.rpop(queue);
String taskReturnedOne = jedis.rpop(queue);
jedis.lpush(queue, taskThree);
Assert.assertEquals(taskOne, taskReturnedOne);
jedis.lpush(queue, taskThree);
Assert.assertEquals(taskOne, taskReturnedOne);
String taskReturnedTwo = jedis.rpop(queue);
String taskReturnedThree = jedis.rpop(queue);
String taskReturnedTwo = jedis.rpop(queue);
String taskReturnedThree = jedis.rpop(queue);
Assert.assertEquals(taskTwo, taskReturnedTwo);
Assert.assertEquals(taskThree, taskReturnedThree);
Assert.assertEquals(taskTwo, taskReturnedTwo);
Assert.assertEquals(taskThree, taskReturnedThree);
String taskReturnedFour = jedis.rpop(queue);
Assert.assertNull(taskReturnedFour);
}
String taskReturnedFour = jedis.rpop(queue);
Assert.assertNull(taskReturnedFour);
}
@Test
public void givenSetElementsThenSaveThemInRedisSet() {
String countries = "countries";
@Test
public void givenSetElements_thenSaveThemInRedisSet() {
String countries = "countries";
String countryOne = "Spain";
String countryTwo = "Ireland";
String countryThree = "Ireland";
String countryOne = "Spain";
String countryTwo = "Ireland";
String countryThree = "Ireland";
jedis.sadd(countries, countryOne);
jedis.sadd(countries, countryOne);
Set<String> countriesSet = jedis.smembers(countries);
Assert.assertEquals(1, countriesSet.size());
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, countryTwo);
countriesSet = jedis.smembers(countries);
Assert.assertEquals(2, countriesSet.size());
jedis.sadd(countries, countryThree);
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);
}
boolean exists = jedis.sismember(countries, countryThree);
Assert.assertTrue(exists);
}
@Test
public void givenObjectFieldsThenSaveThemInRedisHash() {
String key = "user#1";
@Test
public void givenObjectFields_thenSaveThemInRedisHash() {
String key = "user#1";
String field = "name";
String value = "William";
String field = "name";
String value = "William";
String field2 = "job";
String value2 = "politician";
String field2 = "job";
String value2 = "politician";
jedis.hset(key, field, value);
jedis.hset(key, field2, value2);
jedis.hset(key, field, value);
jedis.hset(key, field2, value2);
String value3 = jedis.hget(key, field);
Assert.assertEquals(value, value3);
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);
}
Map<String, String> fields = jedis.hgetAll(key);
String value4 = fields.get(field2);
Assert.assertEquals(value2, value4);
}
@Test
public void givenARankingThenSaveItInRedisSortedSet() {
String key = "ranking";
@Test
public void givenARanking_thenSaveItInRedisSortedSet() {
String key = "ranking";
Map<String, Double> scores = new HashMap<>();
Map<String, Double> scores = new HashMap<>();
scores.put("PlayerOne", 3000.0);
scores.put("PlayerTwo", 1500.0);
scores.put("PlayerThree", 8200.0);
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);
}
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());
Set<String> players = jedis.zrevrange(key, 0, 1);
Assert.assertEquals("PlayerThree", players.iterator().next());
long rank = jedis.zrevrank(key, "PlayerOne");
Assert.assertEquals(1, rank);
}
long rank = jedis.zrevrank(key, "PlayerOne");
Assert.assertEquals(1, rank);
}
@Test
public void givenMultipleOperationsThatNeedToBeExecutedAtomicallyThenWrapThemInATransaction() {
String friendsPrefix = "friends#";
@Test
public void givenMultipleOperationsThatNeedToBeExecutedAtomically_thenWrapThemInATransaction() {
String friendsPrefix = "friends#";
String userOneId = "4352523";
String userTwoId = "5552321";
String userOneId = "4352523";
String userTwoId = "5552321";
Transaction t = jedis.multi();
t.sadd(friendsPrefix + userOneId, userTwoId);
t.sadd(friendsPrefix + userTwoId, userOneId);
t.exec();
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);
boolean exists = jedis.sismember(friendsPrefix + userOneId, userTwoId);
Assert.assertTrue(exists);
exists = jedis.sismember(friendsPrefix + userTwoId, userOneId);
Assert.assertTrue(exists);
}
exists = jedis.sismember(friendsPrefix + userTwoId, userOneId);
Assert.assertTrue(exists);
}
@Test
public void givenMultipleIndependentOperationsWhenNetworkOptimizationIsImportantThenWrapThemInAPipeline() {
String userOneId = "4352523";
String userTwoId = "4849888";
@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();
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());
}
Assert.assertTrue(pipeExists.get());
Assert.assertEquals(2, pipeRanking.get().size());
}
@Test
public void givenAPoolConfigurationThenCreateAJedisPool() {
final JedisPoolConfig poolConfig = buildPoolConfig();
@Test
public void givenAPoolConfiguration_thenCreateAJedisPool() {
final JedisPoolConfig poolConfig = buildPoolConfig();
try (JedisPool jedisPool = new JedisPool(poolConfig, "localhost"); Jedis jedis = jedisPool.getResource()) {
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";
// 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);
jedis.set(key, value);
String value2 = jedis.get(key);
Assert.assertEquals(value, value2);
Assert.assertEquals(value, value2);
// flush Redis
jedis.flushAll();
}
}
// 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;
}
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;
}
}

View File

@ -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;
}
}

View File

@ -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>

View File

@ -1 +1,4 @@
/target/
.settings/
.classpath
.project

View File

@ -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>

View File

@ -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>
@ -70,4 +96,4 @@
</build>
</project>
</project>

View File

@ -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);
}
}

View File

@ -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;
}
}

View File

@ -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);
}

View File

@ -0,0 +1,6 @@
spring.output.ansi.enabled=never
server.port=7070
# Security
security.user.name=admin
security.user.password=password

View File

@ -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() {
}
}

View File

@ -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));
}
}

View File

@ -9,6 +9,7 @@
- [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

View File

@ -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>

View File

@ -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;
}
}

View File

@ -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();
}
}

View File

@ -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>

View File

@ -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>

View File

@ -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";
}
}

View File

@ -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);
}
}

View File

@ -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>

View File

@ -0,0 +1,18 @@
package com.baeldung;
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 = WebjarsdemoApplication.class)
@WebAppConfiguration
public class WebjarsdemoApplicationTests {
@Test
public void contextLoads() {
}
}