BAEL-20865 Move Spring Boot Data module to Spring Boot modules

This commit is contained in:
mikr
2020-01-26 23:51:19 +01:00
parent 9fd36e6fe8
commit dc13f06a5a
45 changed files with 2 additions and 3 deletions

View File

@@ -0,0 +1,11 @@
## Spring Boot Data
This module contains articles about Spring Boot with Spring Data
## Relevant Articles:
- [Formatting JSON Dates in Spring Boot](https://www.baeldung.com/spring-boot-formatting-json-dates)
- [Rendering Exceptions in JSON with Spring](https://www.baeldung.com/spring-exceptions-json)
- [Disable Spring Data Auto Configuration](https://www.baeldung.com/spring-data-disable-auto-config)
- [Repositories with Multiple Spring Data Modules](https://www.baeldung.com/spring-multiple-data-modules)
- [Spring Custom Property Editor](https://www.baeldung.com/spring-mvc-custom-property-editor)

View File

@@ -0,0 +1,175 @@
<?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>
<artifactId>spring-boot-data</artifactId>
<name>spring-boot-data</name>
<packaging>war</packaging>
<description>Spring Boot Data Module</description>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-boot-2</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.javers</groupId>
<artifactId>javers-spring-boot-starter-sql</artifactId>
<version>${javers.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>${h2.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>spring-boot-data</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
</plugin>
<plugin>
<groupId>pl.project13.maven</groupId>
<artifactId>git-commit-id-plugin</artifactId>
<version>${git-commit-id-plugin.version}</version>
<executions>
<execution>
<id>get-the-git-infos</id>
<goals>
<goal>revision</goal>
</goals>
<phase>initialize</phase>
</execution>
<execution>
<id>validate-the-git-infos</id>
<goals>
<goal>validateRevision</goal>
</goals>
<phase>package</phase>
</execution>
</executions>
<configuration>
<generateGitPropertiesFile>true</generateGitPropertiesFile>
<generateGitPropertiesFilename>${project.build.outputDirectory}/git.properties
</generateGitPropertiesFilename>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${source.version}</source>
<target>${target.version}</target>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>autoconfiguration</id>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<mainClass>com.baeldung.javers.SpringBootJaVersApplication</mainClass>
<layout>JAR</layout>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${source.version}</source>
<target>${target.version}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<executions>
<execution>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<excludes>
<exclude>**/*LiveTest.java</exclude>
<exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*IntTest.java</exclude>
</excludes>
<includes>
<include>**/AutoconfigurationTest.java</include>
</includes>
</configuration>
</execution>
</executions>
<configuration>
<systemPropertyVariables>
<test.mime>json</test.mime>
</systemPropertyVariables>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${source.version}</source>
<target>${target.version}</target>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<properties>
<javers.version>5.6.3</javers.version>
<git-commit-id-plugin.version>2.2.4</git-commit-id-plugin.version>
<source.version>1.8</source.version>
<target.version>1.8</target.version>
</properties>
</project>

View File

@@ -0,0 +1,13 @@
package com.baeldung;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootDataApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootDataApplication.class, args);
}
}

View File

@@ -0,0 +1,19 @@
package com.baeldung.disableautoconfig;
import org.javers.spring.boot.sql.JaversSqlAutoConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class,
JaversSqlAutoConfiguration.class, SpringDataWebAutoConfiguration.class,
DataSourceTransactionManagerAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
public class SpringDataJPA {
public static void main(String[] args) {
SpringApplication.run(SpringDataJPA.class, args);
}
}

View File

@@ -0,0 +1,16 @@
package com.baeldung.disableautoconfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration;
import org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration;
import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration;
@SpringBootApplication(exclude = {MongoAutoConfiguration.class, MongoDataAutoConfiguration.class,
SpringDataWebAutoConfiguration.class})
public class SpringDataMongoDB {
public static void main(String[] args) {
SpringApplication.run(SpringDataMongoDB.class, args);
}
}

View File

@@ -0,0 +1,16 @@
package com.baeldung.disableautoconfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration;
import org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration;
@SpringBootApplication(exclude = {RedisAutoConfiguration.class, RedisRepositoriesAutoConfiguration.class,
SpringDataWebAutoConfiguration.class})
public class SpringDataRedis {
public static void main(String[] args) {
SpringApplication.run(SpringDataRedis.class, args);
}
}

View File

@@ -0,0 +1,3 @@
### Relevant Articles
- [Using JaVers for Data Model Auditing in Spring Data](https://www.baeldung.com/spring-data-javers-audit)

View File

@@ -0,0 +1,31 @@
package com.baeldung.javers;
import com.baeldung.javers.domain.Address;
import com.baeldung.javers.domain.Product;
import com.baeldung.javers.domain.Store;
import com.baeldung.javers.repo.StoreRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
@SpringBootApplication
public class SpringBootJaVersApplication {
@Autowired
StoreRepository storeRepository;
public static void main(String[] args) {
SpringApplication.run(SpringBootJaVersApplication.class, args);
}
@EventListener
public void appReady(ApplicationReadyEvent event) {
Store store = new Store("Baeldung store", new Address("Some street", 22222));
for (int i = 1; i < 3; i++) {
Product product = new Product("Product #" + i, 100 * i);
store.addProduct(product);
}
storeRepository.save(store);
}
}

View File

@@ -0,0 +1,20 @@
package com.baeldung.javers.config;
import org.javers.spring.auditable.AuthorProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class JaversConfiguration {
@Bean
public AuthorProvider provideJaversAuthor() {
return new SimpleAuthorProvider();
}
private static class SimpleAuthorProvider implements AuthorProvider {
@Override
public String provide() {
return "Baeldung Author";
}
}
}

View File

@@ -0,0 +1,33 @@
package com.baeldung.javers.domain;
import javax.persistence.Embeddable;
@Embeddable
public class Address {
private String address;
private Integer zipCode;
public Address(String address, Integer zipCode) {
this.address = address;
this.zipCode = zipCode;
}
public Address() {
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Integer getZipCode() {
return zipCode;
}
public void setZipCode(Integer zipCode) {
this.zipCode = zipCode;
}
}

View File

@@ -0,0 +1,61 @@
package com.baeldung.javers.domain;
import javax.persistence.*;
@Entity
public class Product {
@Id
@GeneratedValue
private int id;
private String name;
private double price;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "store_id")
private Store store;
public Product(String name, double price) {
this.name = name;
this.price = price;
}
public Product() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Store getStore() {
return store;
}
public void setStore(Store store) {
this.store = store;
}
public void setNamePrefix(String prefix) {
this.name = prefix + this.name;
}
}

View File

@@ -0,0 +1,62 @@
package com.baeldung.javers.domain;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
@Entity
public class Store {
@Id
@GeneratedValue
private int id;
private String name;
@Embedded
private Address address;
@OneToMany(
mappedBy = "store",
cascade = CascadeType.ALL,
orphanRemoval = true
)
private List<Product> products = new ArrayList<>();
public Store(String name, Address address) {
this.name = name;
this.address = address;
}
public Store() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public void addProduct(Product product) {
product.setStore(this);
this.products.add(product);
}
public List<Product> getProducts() {
return this.products;
}
}

View File

@@ -0,0 +1,11 @@
package com.baeldung.javers.repo;
import com.baeldung.javers.domain.Product;
import org.javers.spring.annotation.JaversAuditable;
import org.springframework.data.repository.CrudRepository;
public interface ProductRepository extends CrudRepository<Product, Integer> {
@Override
@JaversAuditable
<S extends Product> S save(S s);
}

View File

@@ -0,0 +1,9 @@
package com.baeldung.javers.repo;
import com.baeldung.javers.domain.Store;
import org.javers.spring.annotation.JaversSpringDataAuditable;
import org.springframework.data.repository.CrudRepository;
@JaversSpringDataAuditable
public interface StoreRepository extends CrudRepository<Store, Integer> {
}

View File

@@ -0,0 +1,59 @@
package com.baeldung.javers.service;
import com.baeldung.javers.domain.Product;
import com.baeldung.javers.domain.Store;
import com.baeldung.javers.repo.ProductRepository;
import com.baeldung.javers.repo.StoreRepository;
import org.springframework.stereotype.Service;
import java.util.Optional;
import java.util.Random;
@Service
public class StoreService {
private final ProductRepository productRepository;
private final StoreRepository storeRepository;
public StoreService(ProductRepository productRepository, StoreRepository storeRepository) {
this.productRepository = productRepository;
this.storeRepository = storeRepository;
}
public void updateProductPrice(Integer productId, Double price) {
Optional<Product> productOpt = productRepository.findById(productId);
productOpt.ifPresent(product -> {
product.setPrice(price);
productRepository.save(product);
});
}
public void rebrandStore(int storeId, String updatedName) {
Optional<Store> storeOpt = storeRepository.findById(storeId);
storeOpt.ifPresent(store -> {
store.setName(updatedName);
store.getProducts().forEach(product -> {
product.setNamePrefix(updatedName);
});
storeRepository.save(store);
});
}
public void createRandomProduct(Integer storeId) {
Optional<Store> storeOpt = this.storeRepository.findById(storeId);
storeOpt.ifPresent(store -> {
Random random = new Random();
Product product = new Product("Product#" + random.nextInt(), random.nextDouble() * 100);
store.addProduct(product);
storeRepository.save(store);
});
}
public Store findStoreById(int storeId) {
return storeRepository.findById(storeId).get();
}
public Product findProductById(int id) {
return this.productRepository.findById(id).get();
}
}

View File

@@ -0,0 +1,5 @@
package com.baeldung.javers.web;
public class RebrandStoreDto {
public String name;
}

View File

@@ -0,0 +1,73 @@
package com.baeldung.javers.web;
import com.baeldung.javers.domain.Product;
import com.baeldung.javers.domain.Store;
import com.baeldung.javers.service.StoreService;
import org.javers.core.Changes;
import org.javers.core.Javers;
import org.javers.core.metamodel.object.CdoSnapshot;
import org.javers.repository.jql.JqlQuery;
import org.javers.repository.jql.QueryBuilder;
import org.javers.shadow.Shadow;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
public class StoreController {
private final StoreService storeService;
private final Javers javers;
public StoreController(StoreService customerService, Javers javers) {
this.storeService = customerService;
this.javers = javers;
}
@PostMapping("/stores/{storeId}/products/random")
public void createRandomProduct(@PathVariable final Integer storeId) {
storeService.createRandomProduct(storeId);
}
@PostMapping("/stores/{storeId}/rebrand")
public void rebrandStore(@PathVariable final Integer storeId, @RequestBody RebrandStoreDto rebrandStoreDto) {
storeService.rebrandStore(storeId, rebrandStoreDto.name);
}
@PostMapping(value = "/stores/{storeId}/products/{productId}/price", consumes = MediaType.APPLICATION_JSON_VALUE)
public void updateProductPrice(@PathVariable final Integer productId, @PathVariable String storeId, @RequestBody UpdatePriceDto priceDto) {
storeService.updateProductPrice(productId, priceDto.price);
}
@GetMapping("/products/{productId}/changes")
public String getProductChanges(@PathVariable int productId) {
Product product = storeService.findProductById(productId);
QueryBuilder jqlQuery = QueryBuilder.byInstance(product);
Changes changes = javers.findChanges(jqlQuery.build());
return javers.getJsonConverter().toJson(changes);
}
@GetMapping("/products/snapshots")
public String getProductSnapshots() {
QueryBuilder jqlQuery = QueryBuilder.byClass(Product.class);
List<CdoSnapshot> snapshots = javers.findSnapshots(jqlQuery.build());
return javers.getJsonConverter().toJson(snapshots);
}
@GetMapping("/stores/{storeId}/shadows")
public String getStoreShadows(@PathVariable int storeId) {
Store store = storeService.findStoreById(storeId);
JqlQuery jqlQuery = QueryBuilder.byInstance(store)
.withChildValueObjects().build();
List<Shadow<Store>> shadows = javers.findShadows(jqlQuery);
return javers.getJsonConverter().toJson(shadows.get(0));
}
@GetMapping("/stores/snapshots")
public String getStoresSnapshots() {
QueryBuilder jqlQuery = QueryBuilder.byClass(Store.class);
List<CdoSnapshot> snapshots = javers.findSnapshots(jqlQuery.build());
return javers.getJsonConverter().toJson(snapshots);
}
}

View File

@@ -0,0 +1,5 @@
package com.baeldung.javers.web;
public class UpdatePriceDto {
public double price;
}

View File

@@ -0,0 +1,70 @@
package com.baeldung.jsondateformat;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
public class Contact {
private String name;
private String address;
private String phone;
@JsonFormat(pattern="yyyy-MM-dd")
private LocalDate birthday;
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
private LocalDateTime lastUpdate;
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;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public LocalDate getBirthday() {
return birthday;
}
public void setBirthday(LocalDate birthday) {
this.birthday = birthday;
}
public LocalDateTime getLastUpdate() {
return lastUpdate;
}
public void setLastUpdate(LocalDateTime lastUpdate) {
this.lastUpdate = lastUpdate;
}
public Contact() {
}
public Contact(String name, String address, String phone, LocalDate birthday, LocalDateTime lastUpdate) {
this.name = name;
this.address = address;
this.phone = phone;
this.birthday = birthday;
this.lastUpdate = lastUpdate;
}
}

View File

@@ -0,0 +1,13 @@
package com.baeldung.jsondateformat;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ContactApp {
public static void main(String[] args) {
SpringApplication.run(ContactApp.class, args);
}
}

View File

@@ -0,0 +1,33 @@
package com.baeldung.jsondateformat;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import java.time.format.DateTimeFormatter;
@Configuration
public class ContactAppConfig {
private static final String dateFormat = "yyyy-MM-dd";
private static final String dateTimeFormat = "yyyy-MM-dd HH:mm:ss";
@Bean
@ConditionalOnProperty(value = "spring.jackson.date-format", matchIfMissing = true, havingValue = "none")
public Jackson2ObjectMapperBuilderCustomizer jsonCustomizer() {
return new Jackson2ObjectMapperBuilderCustomizer() {
@Override
public void customize(Jackson2ObjectMapperBuilder builder) {
builder.simpleDateFormat(dateTimeFormat);
builder.serializers(new LocalDateSerializer(DateTimeFormatter.ofPattern(dateFormat)));
builder.serializers(new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(dateTimeFormat)));
}
};
}
}

View File

@@ -0,0 +1,77 @@
package com.baeldung.jsondateformat;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@RestController
@RequestMapping(value = "/contacts")
public class ContactController {
@GetMapping
public List<Contact> getContacts() {
List<Contact> contacts = new ArrayList<>();
Contact contact1 = new Contact("John Doe", "123 Sesame Street", "123-456-789", LocalDate.now(), LocalDateTime.now());
Contact contact2 = new Contact("John Doe 2", "124 Sesame Street", "123-456-789", LocalDate.now(), LocalDateTime.now());
Contact contact3 = new Contact("John Doe 3", "125 Sesame Street", "123-456-789", LocalDate.now(), LocalDateTime.now());
contacts.add(contact1);
contacts.add(contact2);
contacts.add(contact3);
return contacts;
}
@GetMapping("/javaUtilDate")
public List<ContactWithJavaUtilDate> getContactsWithJavaUtilDate() {
List<ContactWithJavaUtilDate> contacts = new ArrayList<>();
ContactWithJavaUtilDate contact1 = new ContactWithJavaUtilDate("John Doe", "123 Sesame Street", "123-456-789", new Date(), new Date());
ContactWithJavaUtilDate contact2 = new ContactWithJavaUtilDate("John Doe 2", "124 Sesame Street", "123-456-789", new Date(), new Date());
ContactWithJavaUtilDate contact3 = new ContactWithJavaUtilDate("John Doe 3", "125 Sesame Street", "123-456-789", new Date(), new Date());
contacts.add(contact1);
contacts.add(contact2);
contacts.add(contact3);
return contacts;
}
@GetMapping("/plain")
public List<PlainContact> getPlainContacts() {
List<PlainContact> contacts = new ArrayList<>();
PlainContact contact1 = new PlainContact("John Doe", "123 Sesame Street", "123-456-789", LocalDate.now(), LocalDateTime.now());
PlainContact contact2 = new PlainContact("John Doe 2", "124 Sesame Street", "123-456-789", LocalDate.now(), LocalDateTime.now());
PlainContact contact3 = new PlainContact("John Doe 3", "125 Sesame Street", "123-456-789", LocalDate.now(), LocalDateTime.now());
contacts.add(contact1);
contacts.add(contact2);
contacts.add(contact3);
return contacts;
}
@GetMapping("/plainWithJavaUtilDate")
public List<PlainContactWithJavaUtilDate> getPlainContactsWithJavaUtilDate() {
List<PlainContactWithJavaUtilDate> contacts = new ArrayList<>();
PlainContactWithJavaUtilDate contact1 = new PlainContactWithJavaUtilDate("John Doe", "123 Sesame Street", "123-456-789", new Date(), new Date());
PlainContactWithJavaUtilDate contact2 = new PlainContactWithJavaUtilDate("John Doe 2", "124 Sesame Street", "123-456-789", new Date(), new Date());
PlainContactWithJavaUtilDate contact3 = new PlainContactWithJavaUtilDate("John Doe 3", "125 Sesame Street", "123-456-789", new Date(), new Date());
contacts.add(contact1);
contacts.add(contact2);
contacts.add(contact3);
return contacts;
}
}

View File

@@ -0,0 +1,69 @@
package com.baeldung.jsondateformat;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.util.Date;
public class ContactWithJavaUtilDate {
private String name;
private String address;
private String phone;
@JsonFormat(pattern="yyyy-MM-dd")
private Date birthday;
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
private Date lastUpdate;
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;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public Date getLastUpdate() {
return lastUpdate;
}
public void setLastUpdate(Date lastUpdate) {
this.lastUpdate = lastUpdate;
}
public ContactWithJavaUtilDate() {
}
public ContactWithJavaUtilDate(String name, String address, String phone, Date birthday, Date lastUpdate) {
this.name = name;
this.address = address;
this.phone = phone;
this.birthday = birthday;
this.lastUpdate = lastUpdate;
}
}

View File

@@ -0,0 +1,66 @@
package com.baeldung.jsondateformat;
import java.time.LocalDate;
import java.time.LocalDateTime;
public class PlainContact {
private String name;
private String address;
private String phone;
private LocalDate birthday;
private LocalDateTime lastUpdate;
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;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public LocalDate getBirthday() {
return birthday;
}
public void setBirthday(LocalDate birthday) {
this.birthday = birthday;
}
public LocalDateTime getLastUpdate() {
return lastUpdate;
}
public void setLastUpdate(LocalDateTime lastUpdate) {
this.lastUpdate = lastUpdate;
}
public PlainContact() {
}
public PlainContact(String name, String address, String phone, LocalDate birthday, LocalDateTime lastUpdate) {
this.name = name;
this.address = address;
this.phone = phone;
this.birthday = birthday;
this.lastUpdate = lastUpdate;
}
}

View File

@@ -0,0 +1,69 @@
package com.baeldung.jsondateformat;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.util.Date;
public class PlainContactWithJavaUtilDate {
private String name;
private String address;
private String phone;
@JsonFormat(pattern="yyyy-MM-dd")
private Date birthday;
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
private Date lastUpdate;
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;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public Date getLastUpdate() {
return lastUpdate;
}
public void setLastUpdate(Date lastUpdate) {
this.lastUpdate = lastUpdate;
}
public PlainContactWithJavaUtilDate() {
}
public PlainContactWithJavaUtilDate(String name, String address, String phone, Date birthday, Date lastUpdate) {
this.name = name;
this.address = address;
this.phone = phone;
this.birthday = birthday;
this.lastUpdate = lastUpdate;
}
}

View File

@@ -0,0 +1,11 @@
package com.baeldung.jsonexception;
public class CustomException extends RuntimeException {
private static final long serialVersionUID = 1L;
public CustomException() {
super("Custom exception message.");
}
}

View File

@@ -0,0 +1,17 @@
package com.baeldung.jsonexception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class ErrorHandler {
@ExceptionHandler(CustomException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public CustomException handleCustomException(CustomException ce) {
return ce;
}
}

View File

@@ -0,0 +1,14 @@
package com.baeldung.jsonexception;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class MainController {
@GetMapping("/")
public void index() throws CustomException {
throw new CustomException();
}
}

View File

@@ -0,0 +1,12 @@
package com.baeldung.propertyeditor;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class PropertyEditorApplication {
public static void main(String[] args) {
SpringApplication.run(PropertyEditorApplication.class, args);
}
}

View File

@@ -0,0 +1,36 @@
package com.baeldung.propertyeditor;
import org.springframework.http.MediaType;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.baeldung.propertyeditor.creditcard.CreditCard;
import com.baeldung.propertyeditor.exotictype.editor.CustomExoticTypeEditor;
import com.baeldung.propertyeditor.exotictype.model.ExoticType;
@RestController
@RequestMapping(value = "/property-editor")
public class PropertyEditorRestController {
@GetMapping(value = "/credit-card/{card-no}",
produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public CreditCard parseCreditCardNumber(@PathVariable("card-no") CreditCard creditCard) {
return creditCard;
}
@GetMapping(value = "/exotic-type/{value}",
produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ExoticType parseExoticType(@PathVariable("value") ExoticType exoticType) {
return exoticType;
}
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(ExoticType.class, new CustomExoticTypeEditor());
}
}

View File

@@ -0,0 +1,41 @@
package com.baeldung.propertyeditor.creditcard;
public class CreditCard {
private String rawCardNumber;
private Integer bankIdNo;
private Integer accountNo;
private Integer checkCode;
public String getRawCardNumber() {
return rawCardNumber;
}
public void setRawCardNumber(String rawCardNumber) {
this.rawCardNumber = rawCardNumber;
}
public Integer getBankIdNo() {
return bankIdNo;
}
public void setBankIdNo(Integer bankIdNo) {
this.bankIdNo = bankIdNo;
}
public Integer getAccountNo() {
return accountNo;
}
public void setAccountNo(Integer accountNo) {
this.accountNo = accountNo;
}
public Integer getCheckCode() {
return checkCode;
}
public void setCheckCode(Integer checkCode) {
this.checkCode = checkCode;
}
}

View File

@@ -0,0 +1,39 @@
package com.baeldung.propertyeditor.creditcard;
import java.beans.PropertyEditorSupport;
import org.springframework.util.StringUtils;
public class CreditCardEditor extends PropertyEditorSupport {
@Override
public String getAsText() {
CreditCard creditCard = (CreditCard) getValue();
return creditCard == null ? "" : creditCard.getRawCardNumber();
}
@Override
public void setAsText(String text) throws IllegalArgumentException {
if (StringUtils.isEmpty(text)) {
setValue(null);
} else {
CreditCard creditCard = new CreditCard();
creditCard.setRawCardNumber(text);
String cardNo = text.replaceAll("-", "");
if (cardNo.length() != 16)
throw new IllegalArgumentException("Credit card format should be xxxx-xxxx-xxxx-xxxx");
try {
creditCard.setBankIdNo( Integer.valueOf(cardNo.substring(0, 6)) );
creditCard.setAccountNo( Integer.valueOf(cardNo.substring(6, cardNo.length() - 1)) );
creditCard.setCheckCode( Integer.valueOf(cardNo.substring(cardNo.length() - 1)) );
} catch (NumberFormatException nfe) {
throw new IllegalArgumentException(nfe);
}
setValue(creditCard);
}
}
}

View File

@@ -0,0 +1,23 @@
package com.baeldung.propertyeditor.exotictype.editor;
import java.beans.PropertyEditorSupport;
import com.baeldung.propertyeditor.exotictype.model.ExoticType;
public class CustomExoticTypeEditor extends PropertyEditorSupport {
@Override
public String getAsText() {
ExoticType exoticType = (ExoticType) getValue();
return exoticType == null ? "" : exoticType.getName();
}
@Override
public void setAsText(String text) throws IllegalArgumentException {
ExoticType exoticType = new ExoticType();
exoticType.setName(text.toUpperCase());
setValue(exoticType);
}
}

View File

@@ -0,0 +1,14 @@
package com.baeldung.propertyeditor.exotictype.model;
public class ExoticType {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@@ -0,0 +1,25 @@
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=Europe/Zagreb
spring.h2.console.path=/h2
spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.main.allow-bean-definition-overriding=true
javers.mappingStyle=FIELD
javers.algorithm=SIMPLE
javers.commitIdGenerator=synchronized_sequence
javers.prettyPrint=true
javers.typeSafeValues=false
javers.newObjectSnapshot=true
javers.packagesToScan=
javers.auditableAspectEnabled=true
javers.springDataAuditableRepositoryAspectEnabled=true
javers.sqlSchema=
javers.sqlSchemaManagementEnabled=true
javers.prettyPrintDateFormats.localDateTime=dd MMM yyyy, HH:mm:ss
javers.prettyPrintDateFormats.zonedDateTime=dd MMM yyyy, HH:mm:ssZ
javers.prettyPrintDateFormats.localDate=dd MMM yyyy
javers.prettyPrintDateFormats.localTime=HH:mm:ss

View File

@@ -0,0 +1,26 @@
package com.baeldung.disableautoconfig;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.junit4.SpringRunner;
import javax.sql.DataSource;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringDataJPA.class)
public class SpringDataJPAIntegrationTest {
@Autowired
private ApplicationContext context;
@Test(expected = NoSuchBeanDefinitionException.class)
public void givenAutoConfigDisabled_whenStarting_thenNoAutoconfiguredBeansInContext() {
context.getBean(DataSource.class);
}
}

View File

@@ -0,0 +1,25 @@
package com.baeldung.disableautoconfig;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringDataMongoDB.class)
public class SpringDataMongoDBIntegrationTest {
@Autowired
private ApplicationContext context;
@Test(expected = NoSuchBeanDefinitionException.class)
public void givenAutoConfigDisabled_whenStarting_thenNoAutoconfiguredBeansInContext() {
context.getBean(MongoTemplate.class);
}
}

View File

@@ -0,0 +1,25 @@
package com.baeldung.disableautoconfig;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringDataRedis.class)
public class SpringDataRedisIntegrationTest {
@Autowired
private ApplicationContext context;
@Test(expected = NoSuchBeanDefinitionException.class)
public void givenAutoConfigDisabled_whenStarting_thenNoAutoconfiguredBeansInContext() {
context.getBean(RedisTemplate.class);
}
}

View File

@@ -0,0 +1,100 @@
package com.baeldung.jsondateformat;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.IOException;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = RANDOM_PORT, classes = ContactApp.class)
@TestPropertySource(properties = {
"spring.jackson.date-format=yyyy-MM-dd HH:mm:ss"
})
public class ContactAppIntegrationTest {
private final ObjectMapper mapper = new ObjectMapper();
@LocalServerPort
private int port;
@Autowired
private TestRestTemplate restTemplate;
@Test
public void givenJsonFormatAnnotationAndJava8DateType_whenGet_thenReturnExpectedDateFormat() throws IOException, ParseException {
ResponseEntity<String> response = restTemplate.getForEntity("http://localhost:" + port + "/contacts", String.class);
assertEquals(200, response.getStatusCodeValue());
List<Map<String, String>> respMap = mapper.readValue(response.getBody(), new TypeReference<List<Map<String, String>>>(){});
LocalDate birthdayDate = LocalDate.parse(respMap.get(0).get("birthday"), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
LocalDateTime lastUpdateTime = LocalDateTime.parse(respMap.get(0).get("lastUpdate"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
assertNotNull(birthdayDate);
assertNotNull(lastUpdateTime);
}
@Test
public void givenJsonFormatAnnotationAndLegacyDateType_whenGet_thenReturnExpectedDateFormat() throws IOException {
ResponseEntity<String> response = restTemplate.getForEntity("http://localhost:" + port + "/contacts/javaUtilDate", String.class);
assertEquals(200, response.getStatusCodeValue());
List<Map<String, String>> respMap = mapper.readValue(response.getBody(), new TypeReference<List<Map<String, String>>>(){});
LocalDate birthdayDate = LocalDate.parse(respMap.get(0).get("birthday"), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
LocalDateTime lastUpdateTime = LocalDateTime.parse(respMap.get(0).get("lastUpdate"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
assertNotNull(birthdayDate);
assertNotNull(lastUpdateTime);
}
@Test
public void givenDefaultDateFormatInAppPropertiesAndLegacyDateType_whenGet_thenReturnExpectedDateFormat() throws IOException {
ResponseEntity<String> response = restTemplate.getForEntity("http://localhost:" + port + "/contacts/plainWithJavaUtilDate", String.class);
assertEquals(200, response.getStatusCodeValue());
List<Map<String, String>> respMap = mapper.readValue(response.getBody(), new TypeReference<List<Map<String, String>>>(){});
LocalDate birthdayDate = LocalDate.parse(respMap.get(0).get("birthday"), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
LocalDateTime lastUpdateTime = LocalDateTime.parse(respMap.get(0).get("lastUpdate"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
assertNotNull(birthdayDate);
assertNotNull(lastUpdateTime);
}
@Test(expected = DateTimeParseException.class)
public void givenDefaultDateFormatInAppPropertiesAndJava8DateType_whenGet_thenNotApplyFormat() throws IOException {
ResponseEntity<String> response = restTemplate.getForEntity("http://localhost:" + port + "/contacts/plain", String.class);
assertEquals(200, response.getStatusCodeValue());
List<Map<String, String>> respMap = mapper.readValue(response.getBody(), new TypeReference<List<Map<String, String>>>(){});
LocalDate birthdayDate = LocalDate.parse(respMap.get(0).get("birthday"), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
LocalDateTime lastUpdateTime = LocalDateTime.parse(respMap.get(0).get("lastUpdate"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
}
}

View File

@@ -0,0 +1,67 @@
package com.baeldung.jsondateformat;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = RANDOM_PORT, classes = ContactApp.class)
public class ContactAppWithObjectMapperCustomizerIntegrationTest {
private final ObjectMapper mapper = new ObjectMapper();
@Autowired
private TestRestTemplate restTemplate;
@LocalServerPort
private int port;
@Test
public void givenDefaultDateFormatInAppPropertiesAndLegacyDateType_whenGet_thenReturnExpectedDateFormat() throws IOException {
ResponseEntity<String> response = restTemplate.getForEntity("http://localhost:" + this.port + "/contacts/plainWithJavaUtilDate", String.class);
assertEquals(200, response.getStatusCodeValue());
List<Map<String, String>> respMap = mapper.readValue(response.getBody(), new TypeReference<List<Map<String, String>>>(){});
LocalDate birthdayDate = LocalDate.parse(respMap.get(0).get("birthday"), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
LocalDateTime lastUpdateTime = LocalDateTime.parse(respMap.get(0).get("lastUpdate"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
assertNotNull(birthdayDate);
assertNotNull(lastUpdateTime);
}
@Test
public void givenDefaultDateFormatInAppPropertiesAndJava8DateType_whenGet_thenReturnExpectedDateFormat() throws IOException {
ResponseEntity<String> response = restTemplate.getForEntity("http://localhost:" + this.port + "/contacts/plain", String.class);
assertEquals(200, response.getStatusCodeValue());
List<Map<String, String>> respMap = mapper.readValue(response.getBody(), new TypeReference<List<Map<String, String>>>(){});
LocalDate birthdayDate = LocalDate.parse(respMap.get(0).get("birthday"), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
LocalDateTime lastUpdateTime = LocalDateTime.parse(respMap.get(0).get("lastUpdate"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
assertNotNull(birthdayDate);
assertNotNull(lastUpdateTime);
}
}

View File

@@ -0,0 +1,19 @@
package com.baeldung.jsonexception;
import org.junit.Test;
import com.baeldung.jsonexception.CustomException;
import com.baeldung.jsonexception.MainController;
public class MainControllerIntegrationTest {
@Test(expected = CustomException.class)
public void givenIndex_thenCustomException() throws CustomException {
MainController mainController = new MainController();
mainController.index();
}
}

View File

@@ -0,0 +1,41 @@
package com.baeldung.propertyeditor.creditcard;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class CreditCardEditorUnitTest {
private CreditCardEditor creditCardEditor;
@Before
public void setup() {
creditCardEditor = new CreditCardEditor();
}
@Test(expected=IllegalArgumentException.class)
public void whenInvalidCardNoWithLessDigits_thenThrowsException() {
creditCardEditor.setAsText("123-123-123-123");
}
@Test(expected=IllegalArgumentException.class)
public void whenInvalidCardNoWithNonDigits_thenThrowsException() {
creditCardEditor.setAsText("1234-1234-xxxx-yyyy");
}
@Test
public void whenCardNoWithNonDigits_parseCreditCard() {
creditCardEditor.setAsText("1234-5678-9123-4560");
CreditCard creditCard = (CreditCard) creditCardEditor.getValue();
Assert.assertNotNull(creditCard);
Assert.assertEquals(123456, creditCard.getBankIdNo().intValue());
Assert.assertEquals(789123456, creditCard.getAccountNo().intValue());
Assert.assertEquals(0, creditCard.getCheckCode().intValue());
}
}