[BAEL-2533] fix merge conflict

This commit is contained in:
mprevisic
2019-02-19 14:50:32 +01:00
1970 changed files with 31381 additions and 7602 deletions

View File

@@ -25,7 +25,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
- [Spring Boot: Configuring a Main Class](http://www.baeldung.com/spring-boot-main-class)
- [A Quick Intro to the SpringBootServletInitializer](http://www.baeldung.com/spring-boot-servlet-initializer)
- [How to Define a Spring Boot Filter?](http://www.baeldung.com/spring-boot-add-filter)
- [How to Change the Default Port in Spring Boot](http://www.baeldung.com/spring-boot-change-port)
- [Spring Boot Exit Codes](http://www.baeldung.com/spring-boot-exit-codes)
- [Guide to the Favicon in Spring Boot](http://www.baeldung.com/spring-boot-favicon)
- [Spring Shutdown Callbacks](http://www.baeldung.com/spring-shutdown-callbacks)
@@ -36,3 +35,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
- [Load Spring Boot Properties From a JSON File](https://www.baeldung.com/spring-boot-json-properties)
- [Display Auto-Configuration Report in Spring Boot](https://www.baeldung.com/spring-boot-auto-configuration-report)
- [Injecting Git Information Into Spring](https://www.baeldung.com/spring-git-information)
- [Validation in Spring Boot](https://www.baeldung.com/spring-boot-bean-validation)

View File

@@ -3,8 +3,8 @@
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</artifactId>
<packaging>war</packaging>
<name>spring-boot</name>
<packaging>war</packaging>
<description>This is simple boot application for Spring boot actuator test</description>
<parent>
@@ -162,6 +162,12 @@
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
</dependency>
<dependency>
<groupId>org.modelmapper</groupId>
<artifactId>modelmapper</artifactId>
<version>${modelmapper.version}</version>
</dependency>
</dependencies>
<build>
@@ -259,6 +265,7 @@
<graphql-java-tools.version>5.2.4</graphql-java-tools.version>
<guava.version>18.0</guava.version>
<git-commit-id-plugin.version>2.2.4</git-commit-id-plugin.version>
<modelmapper.version>2.3.2</modelmapper.version>
</properties>
</project>

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,20 @@
package com.baeldung.modelmapper;
import org.modelmapper.ModelMapper;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class PostApplication {
public static void main(String[] args) {
SpringApplication.run(PostApplication.class, args);
}
@Bean
public ModelMapper modelMapper() {
return new ModelMapper();
}
}

View File

@@ -0,0 +1,91 @@
package com.baeldung.modelmapper.controller;
import java.text.ParseException;
import java.util.List;
import java.util.stream.Collectors;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import com.baeldung.modelmapper.dto.PostDto;
import com.baeldung.modelmapper.model.Post;
import com.baeldung.modelmapper.service.IPostService;
import com.baeldung.modelmapper.service.IUserService;
@Controller
public class PostRestController {
@Autowired
private IPostService postService;
@Autowired
private IUserService userService;
@Autowired
private ModelMapper modelMapper;
@RequestMapping(method = RequestMethod.GET)
@ResponseBody
public List<PostDto> getPosts(
@PathVariable("page") int page,
@PathVariable("size") int size,
@PathVariable("sortDir") String sortDir,
@PathVariable("sort") String sort) {
List<Post> posts = postService.getPostsList(page, size, sortDir, sort);
return posts.stream()
.map(post -> convertToDto(post))
.collect(Collectors.toList());
}
@RequestMapping(method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
@ResponseBody
public PostDto createPost(@RequestBody PostDto postDto) throws ParseException {
Post post = convertToEntity(postDto);
Post postCreated = postService.createPost(post);
return convertToDto(postCreated);
}
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
@ResponseBody
public PostDto getPost(@PathVariable("id") Long id) {
return convertToDto(postService.getPostById(id));
}
@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
@ResponseStatus(HttpStatus.OK)
public void updatePost(@RequestBody PostDto postDto) throws ParseException {
Post post = convertToEntity(postDto);
postService.updatePost(post);
}
private PostDto convertToDto(Post post) {
PostDto postDto = modelMapper.map(post, PostDto.class);
postDto.setSubmissionDate(post.getSubmissionDate(),
userService.getCurrentUser().getPreference().getTimezone());
return postDto;
}
private Post convertToEntity(PostDto postDto) throws ParseException {
Post post = modelMapper.map(postDto, Post.class);
post.setSubmissionDate(postDto.getSubmissionDateConverted(
userService.getCurrentUser().getPreference().getTimezone()));
if (postDto.getId() != null) {
Post oldPost = postService.getPostById(postDto.getId());
post.setRedditID(oldPost.getRedditID());
post.setSent(oldPost.isSent());
}
return post;
}
}

View File

@@ -0,0 +1,71 @@
package com.baeldung.modelmapper.dto;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class PostDto {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
private Long id;
private String title;
private String url;
private String date;
private UserDto user;
public Date getSubmissionDateConverted(String timezone) throws ParseException {
dateFormat.setTimeZone(TimeZone.getTimeZone(timezone));
return dateFormat.parse(this.date);
}
public void setSubmissionDate(Date date, String timezone) {
dateFormat.setTimeZone(TimeZone.getTimeZone(timezone));
this.date = dateFormat.format(date);
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public UserDto getUser() {
return user;
}
public void setUser(UserDto user) {
this.user = user;
}
}

View File

@@ -0,0 +1,14 @@
package com.baeldung.modelmapper.dto;
public class UserDto {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@@ -0,0 +1,98 @@
package com.baeldung.modelmapper.model;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Post {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String title;
private String url;
private String date;
private String redditID;
private Date submissionDate;
private boolean sent;
private String userName;
public Post() {
}
public boolean isSent() {
return sent;
}
public void setSent(boolean sent) {
this.sent = sent;
}
public String getRedditID() {
return redditID;
}
public void setRedditID(String redditID) {
this.redditID = redditID;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public Date getSubmissionDate() {
return submissionDate;
}
public void setSubmissionDate(Date submissionDate) {
this.submissionDate = submissionDate;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}

View File

@@ -0,0 +1,32 @@
package com.baeldung.modelmapper.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Preference {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String timezone;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTimezone() {
return timezone;
}
public void setTimezone(String timezone) {
this.timezone = timezone;
}
}

View File

@@ -0,0 +1,44 @@
package com.baeldung.modelmapper.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
@OneToOne
Preference preference;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Preference getPreference() {
return preference;
}
public void setPreference(Preference preference) {
this.preference = preference;
}
}

View File

@@ -0,0 +1,21 @@
package com.baeldung.modelmapper.repository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import com.baeldung.modelmapper.model.Post;
import com.baeldung.modelmapper.model.User;
public interface PostRepository extends JpaRepository<Post, Long>, PagingAndSortingRepository<Post, Long> {
@Query("select u from Post u where u.userName=:userName")
Page<Post> findByUser(@Param("userName") String userName, Pageable pageReq);
default Page<Post> findByUser(User user, Pageable pageReq) {
return findByUser(user.getName(), pageReq);
}
}

View File

@@ -0,0 +1,17 @@
package com.baeldung.modelmapper.service;
import java.util.List;
import com.baeldung.modelmapper.model.Post;
public interface IPostService {
List<Post> getPostsList(int page, int size, String sortDir, String sort);
void updatePost(Post post);
Post createPost(Post post);
Post getPostById(Long id);
}

View File

@@ -0,0 +1,9 @@
package com.baeldung.modelmapper.service;
import com.baeldung.modelmapper.model.User;
public interface IUserService {
User getCurrentUser();
}

View File

@@ -0,0 +1,47 @@
package com.baeldung.modelmapper.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import com.baeldung.modelmapper.model.Post;
import com.baeldung.modelmapper.repository.PostRepository;
@Service
public class PostService implements IPostService {
@Autowired
private PostRepository postRepository;
@Autowired
private IUserService userService;
@Override
public List<Post> getPostsList(int page, int size, String sortDir, String sort) {
PageRequest pageReq
= PageRequest.of(page, size, Sort.Direction.fromString(sortDir), sort);
Page<Post> posts = postRepository.findByUser(userService.getCurrentUser(), pageReq);
return posts.getContent();
}
@Override
public void updatePost(Post post) {
postRepository.save(post);
}
@Override
public Post createPost(Post post) {
return postRepository.save(post);
}
@Override
public Post getPostById(Long id) {
return postRepository.getOne(id);
}
}

View File

@@ -0,0 +1,25 @@
package com.baeldung.modelmapper.service;
import org.springframework.stereotype.Service;
import com.baeldung.modelmapper.model.Preference;
import com.baeldung.modelmapper.model.User;
@Service
public class UserService implements IUserService {
@Override
public User getCurrentUser() {
Preference preference = new Preference();
preference.setId(1L);
preference.setTimezone("Asia/Calcutta");
User user = new User();
user.setId(1L);
user.setName("Micheal");
user.setPreference(preference);
return user;
}
}

View File

@@ -5,10 +5,10 @@ import java.util.Map;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotBlank;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

View File

@@ -0,0 +1,27 @@
package com.baeldung.validation.application;
import com.baeldung.validation.application.entities.User;
import com.baeldung.validation.application.repositories.UserRepository;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
public CommandLineRunner run(UserRepository userRepository) throws Exception {
return (String[] args) -> {
User user1 = new User("Bob", "bob@domain.com");
User user2 = new User("Jenny", "jenny@domain.com");
userRepository.save(user1);
userRepository.save(user2);
userRepository.findAll().forEach(System.out::println);
};
}
}

View File

@@ -0,0 +1,52 @@
package com.baeldung.validation.application.controllers;
import com.baeldung.validation.application.entities.User;
import com.baeldung.validation.application.repositories.UserRepository;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
private final UserRepository userRepository;
@Autowired
public UserController(UserRepository userRepository) {
this.userRepository = userRepository;
}
@GetMapping("/users")
public List<User> getUsers() {
return (List<User>) userRepository.findAll();
}
@PostMapping("/users")
ResponseEntity<String> addUser(@Valid @RequestBody User user) {
return ResponseEntity.ok("User is valid");
}
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MethodArgumentNotValidException.class)
public Map<String, String> handleValidationExceptions(MethodArgumentNotValidException ex) {
Map<String, String> errors = new HashMap<>();
ex.getBindingResult().getAllErrors().forEach((error) -> {
String fieldName = ((FieldError) error).getField();
String errorMessage = error.getDefaultMessage();
errors.put(fieldName, errorMessage);
});
return errors;
}
}

View File

@@ -0,0 +1,50 @@
package com.baeldung.validation.application.entities;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotBlank;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@NotBlank(message = "Name is mandatory")
private String name;
@NotBlank(message = "Email is mandatory")
private String email;
public User(){}
public User(String name, String email) {
this.name = name;
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "User{" + "id=" + id + ", name=" + name + ", email=" + email + '}';
}
}

View File

@@ -0,0 +1,8 @@
package com.baeldung.validation.application.repositories;
import com.baeldung.validation.application.entities.User;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends CrudRepository<User, Long> {}

View File

@@ -5,10 +5,9 @@ import java.util.Map;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotBlank;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
@@ -20,41 +19,8 @@ import org.springframework.validation.annotation.Validated;
@Validated
public class ConfigProperties {
@Validated
public static class Credentials {
@Length(max = 4, min = 1)
private String authMethod;
private String username;
private String password;
public String getAuthMethod() {
return authMethod;
}
public void setAuthMethod(String authMethod) {
this.authMethod = authMethod;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
@NotBlank
private String host;
private String hostName;
@Min(1025)
@Max(65536)
@@ -63,16 +29,16 @@ public class ConfigProperties {
@Pattern(regexp = "^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,6}$")
private String from;
private Credentials credentials;
private List<String> defaultRecipients;
private Map<String, String> additionalHeaders;
private Credentials credentials;
public String getHost() {
return host;
public String getHostName() {
return hostName;
}
public void setHost(String host) {
this.host = host;
public void setHostName(String hostName) {
this.hostName = hostName;
}
public int getPort() {
@@ -91,14 +57,6 @@ public class ConfigProperties {
this.from = from;
}
public Credentials getCredentials() {
return credentials;
}
public void setCredentials(Credentials credentials) {
this.credentials = credentials;
}
public List<String> getDefaultRecipients() {
return defaultRecipients;
}
@@ -114,4 +72,12 @@ public class ConfigProperties {
public void setAdditionalHeaders(Map<String, String> additionalHeaders) {
this.additionalHeaders = additionalHeaders;
}
public Credentials getCredentials() {
return credentials;
}
public void setCredentials(Credentials credentials) {
this.credentials = credentials;
}
}

View File

@@ -0,0 +1,37 @@
package org.baeldung.properties;
import org.hibernate.validator.constraints.Length;
import org.springframework.validation.annotation.Validated;
@Validated
public class Credentials {
@Length(max = 4, min = 1)
private String authMethod;
private String username;
private String password;
public String getAuthMethod() {
return authMethod;
}
public void setAuthMethod(String authMethod) {
this.authMethod = authMethod;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}

View File

@@ -71,4 +71,4 @@ chaos.monkey.watcher.service=true
#Repository watcher active
chaos.monkey.watcher.repository=false
#Component watcher active
chaos.monkey.watcher.component=false
chaos.monkey.watcher.component=false

View File

@@ -1,5 +1,5 @@
#Simple properties
mail.host=mailer@mail.com
mail.hostname=host@mail.com
mail.port=9000
mail.from=mailer@mail.com

View File

@@ -0,0 +1,96 @@
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.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.DEFINED_PORT;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = DEFINED_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();
@Autowired
TestRestTemplate restTemplate;
@Test
public void givenJsonFormatAnnotationAndJava8DateType_whenGet_thenReturnExpectedDateFormat() throws IOException, ParseException {
ResponseEntity<String> response = restTemplate.getForEntity("http://localhost:8080/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:8080/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:8080/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:8080/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,63 @@
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.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.DEFINED_PORT;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = DEFINED_PORT, classes = ContactApp.class)
public class ContactAppWithObjectMapperCustomizerIntegrationTest {
private final ObjectMapper mapper = new ObjectMapper();
@Autowired
TestRestTemplate restTemplate;
@Test
public void givenDefaultDateFormatInAppPropertiesAndLegacyDateType_whenGet_thenReturnExpectedDateFormat() throws IOException {
ResponseEntity<String> response = restTemplate.getForEntity("http://localhost:8080/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:8080/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,40 @@
package com.baeldung.modelmapper;
import static org.junit.Assert.assertEquals;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import org.junit.Test;
import org.modelmapper.ModelMapper;
import com.baeldung.modelmapper.dto.PostDto;
import com.baeldung.modelmapper.model.Post;
public class PostDtoUnitTest {
private ModelMapper modelMapper = new ModelMapper();
@Test
public void whenConvertPostEntityToPostDto_thenCorrect() {
Post post = new Post();
post.setId(Long.valueOf(1));
post.setTitle(randomAlphabetic(6));
post.setUrl("www.test.com");
PostDto postDto = modelMapper.map(post, PostDto.class);
assertEquals(post.getId(), postDto.getId());
assertEquals(post.getTitle(), postDto.getTitle());
assertEquals(post.getUrl(), postDto.getUrl());
}
@Test
public void whenConvertPostDtoToPostEntity_thenCorrect() {
PostDto postDto = new PostDto();
postDto.setId(Long.valueOf(1));
postDto.setTitle(randomAlphabetic(6));
postDto.setUrl("www.test.com");
Post post = modelMapper.map(postDto, Post.class);
assertEquals(postDto.getId(), post.getId());
assertEquals(postDto.getTitle(), post.getTitle());
assertEquals(postDto.getUrl(), post.getUrl());
}
}

View File

@@ -0,0 +1,69 @@
package com.baeldung.validation.tests;
import com.baeldung.validation.application.controllers.UserController;
import com.baeldung.validation.application.repositories.UserRepository;
import java.nio.charset.Charset;
import static org.assertj.core.api.Assertions.assertThat;
import org.hamcrest.core.Is;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
@RunWith(SpringRunner.class)
@WebMvcTest
@AutoConfigureMockMvc
public class UserControllerIntegrationTest {
@MockBean
private UserRepository userRepository;
@Autowired
UserController userController;
@Autowired
private MockMvc mockMvc;
@Test
public void whenUserControllerInjected_thenNotNull() throws Exception {
assertThat(userController).isNotNull();
}
@Test
public void whenGetRequestToUsers_thenCorrectResponse() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/users")
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON_UTF8));
}
@Test
public void whenPostRequestToUsersAndValidUser_thenCorrectResponse() throws Exception {
MediaType textPlainUtf8 = new MediaType(MediaType.TEXT_PLAIN, Charset.forName("UTF-8"));
String user = "{\"name\": \"bob\", \"email\" : \"bob@domain.com\"}";
mockMvc.perform(MockMvcRequestBuilders.post("/users")
.content(user)
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().contentType(textPlainUtf8));
}
@Test
public void whenPostRequestToUsersAndInValidUser_thenCorrectReponse() throws Exception {
String user = "{\"name\": \"\", \"email\" : \"bob@domain.com\"}";
mockMvc.perform(MockMvcRequestBuilders.post("/users")
.content(user)
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(MockMvcResultMatchers.status().isBadRequest())
.andExpect(MockMvcResultMatchers.jsonPath("$.name", Is.is("Name is mandatory")))
.andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON_UTF8));
}
}

View File

@@ -45,10 +45,10 @@ public class EmployeeControllerIntegrationTest {
@Test
public void whenPostEmployee_thenCreateEmployee() throws Exception {
Employee alex = new Employee("alex");
given(service.save(Mockito.anyObject())).willReturn(alex);
given(service.save(Mockito.any())).willReturn(alex);
mvc.perform(post("/api/employees").contentType(MediaType.APPLICATION_JSON).content(JsonUtil.toJson(alex))).andExpect(status().isCreated()).andExpect(jsonPath("$.name", is("alex")));
verify(service, VerificationModeFactory.times(1)).save(Mockito.anyObject());
verify(service, VerificationModeFactory.times(1)).save(Mockito.any());
reset(service);
}

View File

@@ -1,5 +1,8 @@
package org.baeldung.properties;
import java.util.List;
import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -18,26 +21,36 @@ public class ConfigPropertiesIntegrationTest {
@Test
public void whenSimplePropertyQueriedthenReturnsProperty() throws Exception {
Assert.assertTrue("From address is read as null!", properties.getFrom() != null);
Assert.assertEquals("Incorrectly bound hostName property", "host@mail.com", properties.getHostName());
Assert.assertEquals("Incorrectly bound port property", 9000, properties.getPort());
Assert.assertEquals("Incorrectly bound from property", "mailer@mail.com", properties.getFrom());
}
@Test
public void whenListPropertyQueriedthenReturnsProperty() throws Exception {
Assert.assertTrue("Couldn't bind list property!", properties.getDefaultRecipients().size() == 2);
Assert.assertTrue("Incorrectly bound list property. Expected 2 entries!", properties.getDefaultRecipients().size() == 2);
List<String> defaultRecipients = properties.getDefaultRecipients();
Assert.assertTrue("Couldn't bind list property!", defaultRecipients.size() == 2);
Assert.assertTrue("Incorrectly bound list property. Expected 2 entries!", defaultRecipients.size() == 2);
Assert.assertEquals("Incorrectly bound list[0] property", "admin@mail.com", defaultRecipients.get(0));
Assert.assertEquals("Incorrectly bound list[1] property", "owner@mail.com", defaultRecipients.get(1));
}
@Test
public void whenMapPropertyQueriedthenReturnsProperty() throws Exception {
Assert.assertTrue("Couldn't bind map property!", properties.getAdditionalHeaders() != null);
Assert.assertTrue("Incorrectly bound map property. Expected 3 Entries!", properties.getAdditionalHeaders().size() == 3);
Map<String, String> additionalHeaders = properties.getAdditionalHeaders();
Assert.assertTrue("Couldn't bind map property!", additionalHeaders != null);
Assert.assertTrue("Incorrectly bound map property. Expected 3 Entries!", additionalHeaders.size() == 3);
Assert.assertEquals("Incorrectly bound map[redelivery] property", "true", additionalHeaders.get("redelivery"));
Assert.assertEquals("Incorrectly bound map[secure] property", "true", additionalHeaders.get("secure"));
Assert.assertEquals("Incorrectly bound map[p3] property", "value", additionalHeaders.get("p3"));
}
@Test
public void whenObjectPropertyQueriedthenReturnsProperty() throws Exception {
Assert.assertTrue("Couldn't bind map property!", properties.getCredentials() != null);
Assert.assertTrue("Incorrectly bound object property!", properties.getCredentials().getAuthMethod().equals("SHA1"));
Assert.assertTrue("Incorrectly bound object property!", properties.getCredentials().getUsername().equals("john"));
Assert.assertTrue("Incorrectly bound object property!", properties.getCredentials().getPassword().equals("password"));
Credentials credentials = properties.getCredentials();
Assert.assertTrue("Couldn't bind map property!", credentials != null);
Assert.assertEquals("Incorrectly bound object property, authMethod", "SHA1", credentials.getAuthMethod());
Assert.assertEquals("Incorrectly bound object property, username", "john", credentials.getUsername());
Assert.assertEquals("Incorrectly bound object property, password", "password", credentials.getPassword());
}
}

View File

@@ -1,5 +1,5 @@
#Simple properties
mail.host=mailer@mail.com
mail.hostname=host@mail.com
mail.port=9000
mail.from=mailer@mail.com