JAVA-3520: Moved spring-mvc-basics-3 inside spring-web-modules
This commit is contained in:
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.boot;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
|
||||
@SpringBootApplication
|
||||
public class Application {
|
||||
private static ApplicationContext applicationContext;
|
||||
|
||||
public static void main(String[] args) {
|
||||
applicationContext = SpringApplication.run(Application.class, args);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.baeldung.boot.config;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.baeldung.boot.converter.GenericBigDecimalConverter;
|
||||
import com.baeldung.boot.converter.StringToAbstractEntityConverterFactory;
|
||||
import com.baeldung.boot.converter.StringToEmployeeConverter;
|
||||
import com.baeldung.boot.converter.StringToEnumConverter;
|
||||
import com.baeldung.boot.web.resolver.HeaderVersionArgumentResolver;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.format.FormatterRegistry;
|
||||
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
@Configuration
|
||||
public class WebConfig implements WebMvcConfigurer {
|
||||
|
||||
@Override
|
||||
public void addArgumentResolvers(final List<HandlerMethodArgumentResolver> argumentResolvers) {
|
||||
argumentResolvers.add(new HeaderVersionArgumentResolver());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addFormatters(FormatterRegistry registry) {
|
||||
registry.addConverter(new StringToEmployeeConverter());
|
||||
registry.addConverter(new StringToEnumConverter());
|
||||
registry.addConverterFactory(new StringToAbstractEntityConverterFactory());
|
||||
registry.addConverter(new GenericBigDecimalConverter());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.baeldung.boot.controller;
|
||||
|
||||
import com.baeldung.boot.domain.GenericEntity;
|
||||
import com.baeldung.boot.domain.Modes;
|
||||
import com.baeldung.boot.web.resolver.Version;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
public class GenericEntityController {
|
||||
private List<GenericEntity> entityList = new ArrayList<>();
|
||||
|
||||
{
|
||||
entityList.add(new GenericEntity(1l, "entity_1"));
|
||||
entityList.add(new GenericEntity(2l, "entity_2"));
|
||||
entityList.add(new GenericEntity(3l, "entity_3"));
|
||||
entityList.add(new GenericEntity(4l, "entity_4"));
|
||||
}
|
||||
|
||||
@GetMapping("/entity/all")
|
||||
public List<GenericEntity> findAll() {
|
||||
return entityList;
|
||||
}
|
||||
|
||||
@PostMapping("/entity")
|
||||
public GenericEntity addEntity(GenericEntity entity) {
|
||||
entityList.add(entity);
|
||||
return entity;
|
||||
}
|
||||
|
||||
@GetMapping("/entity/findby/{id}")
|
||||
public GenericEntity findById(@PathVariable Long id) {
|
||||
return entityList.stream().filter(entity -> entity.getId().equals(id)).findFirst().get();
|
||||
}
|
||||
|
||||
@GetMapping("/entity/findbydate/{date}")
|
||||
public GenericEntity findByDate(@PathVariable("date") LocalDateTime date) {
|
||||
return entityList.stream().findFirst().get();
|
||||
}
|
||||
|
||||
@GetMapping("/entity/findbymode/{mode}")
|
||||
public GenericEntity findByEnum(@PathVariable("mode") Modes mode) {
|
||||
return entityList.stream().findFirst().get();
|
||||
}
|
||||
|
||||
@GetMapping("/entity/findbyversion")
|
||||
public ResponseEntity findByVersion(@Version String version) {
|
||||
return version != null ? new ResponseEntity(entityList.stream().findFirst().get(), HttpStatus.OK) : new ResponseEntity(HttpStatus.NOT_FOUND);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.baeldung.boot.converter;
|
||||
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import org.springframework.core.convert.TypeDescriptor;
|
||||
import org.springframework.core.convert.converter.GenericConverter;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Set;
|
||||
|
||||
public class GenericBigDecimalConverter implements GenericConverter {
|
||||
@Override
|
||||
public Set<ConvertiblePair> getConvertibleTypes() {
|
||||
|
||||
ConvertiblePair[] pairs = new ConvertiblePair[] { new ConvertiblePair(Number.class, BigDecimal.class), new ConvertiblePair(String.class, BigDecimal.class) };
|
||||
|
||||
return ImmutableSet.copyOf(pairs);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
|
||||
if (sourceType.getType() == BigDecimal.class) {
|
||||
return source;
|
||||
}
|
||||
|
||||
if (sourceType.getType() == String.class) {
|
||||
String number = (String) source;
|
||||
return new BigDecimal(number);
|
||||
} else {
|
||||
Number number = (Number) source;
|
||||
BigDecimal converted = new BigDecimal(number.doubleValue());
|
||||
return converted.setScale(2, BigDecimal.ROUND_HALF_EVEN);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.baeldung.boot.converter;
|
||||
|
||||
import com.baeldung.boot.domain.AbstractEntity;
|
||||
import com.baeldung.boot.domain.Bar;
|
||||
import com.baeldung.boot.domain.Foo;
|
||||
import org.springframework.core.convert.converter.Converter;
|
||||
import org.springframework.core.convert.converter.ConverterFactory;
|
||||
|
||||
public class StringToAbstractEntityConverterFactory implements ConverterFactory<String, AbstractEntity>{
|
||||
|
||||
@Override
|
||||
public <T extends AbstractEntity> Converter<String, T> getConverter(Class<T> targetClass) {
|
||||
|
||||
return new StringToAbstractEntityConverter<>(targetClass);
|
||||
}
|
||||
|
||||
|
||||
private static class StringToAbstractEntityConverter<T extends AbstractEntity> implements Converter<String, T> {
|
||||
|
||||
private Class<T> targetClass;
|
||||
|
||||
public StringToAbstractEntityConverter(Class<T> targetClass) {
|
||||
this.targetClass = targetClass;
|
||||
}
|
||||
|
||||
@Override
|
||||
public T convert(String source) {
|
||||
long id = Long.parseLong(source);
|
||||
if(this.targetClass == Foo.class) {
|
||||
return (T) new Foo(id);
|
||||
}
|
||||
else if(this.targetClass == Bar.class) {
|
||||
return (T) new Bar(id);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.boot.converter;
|
||||
|
||||
import com.baeldung.boot.domain.Employee;
|
||||
import org.springframework.core.convert.converter.Converter;
|
||||
|
||||
public class StringToEmployeeConverter implements Converter<String, Employee> {
|
||||
|
||||
@Override
|
||||
public Employee convert(String from) {
|
||||
String[] data = from.split(",");
|
||||
return new Employee(Long.parseLong(data[0]), Double.parseDouble(data[1]));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.baeldung.boot.converter;
|
||||
|
||||
import com.baeldung.boot.domain.Modes;
|
||||
import org.springframework.core.convert.converter.Converter;
|
||||
|
||||
public class StringToEnumConverter implements Converter<String, Modes> {
|
||||
|
||||
@Override
|
||||
public Modes convert(String from) {
|
||||
return Modes.valueOf(from);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.baeldung.boot.converter;
|
||||
|
||||
import org.springframework.core.convert.converter.Converter;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
|
||||
@Component
|
||||
public class StringToLocalDateTimeConverter implements Converter<String, LocalDateTime> {
|
||||
|
||||
@Override
|
||||
public LocalDateTime convert(final String source) {
|
||||
return LocalDateTime.parse(source, DateTimeFormatter.ISO_LOCAL_DATE_TIME);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.boot.converter.controller;
|
||||
|
||||
import com.baeldung.boot.domain.Bar;
|
||||
import com.baeldung.boot.domain.Foo;
|
||||
import com.baeldung.boot.domain.Modes;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/string-to-abstract")
|
||||
public class AbstractEntityController {
|
||||
|
||||
@GetMapping("/foo/{foo}")
|
||||
public ResponseEntity<Object> getStringToFoo(@PathVariable Foo foo) {
|
||||
return ResponseEntity.ok(foo);
|
||||
}
|
||||
|
||||
@GetMapping("/bar/{bar}")
|
||||
public ResponseEntity<Object> getStringToBar(@PathVariable Bar bar) {
|
||||
return ResponseEntity.ok(bar);
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public ResponseEntity<Object> getStringToMode(@RequestParam("mode") Modes mode) {
|
||||
return ResponseEntity.ok(mode);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.boot.converter.controller;
|
||||
|
||||
import com.baeldung.boot.domain.Employee;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/string-to-employee")
|
||||
public class StringToEmployeeConverterController {
|
||||
|
||||
@GetMapping
|
||||
public ResponseEntity<Object> getStringToEmployee(@RequestParam("employee") Employee employee) {
|
||||
return ResponseEntity.ok(employee);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.baeldung.boot.domain;
|
||||
|
||||
public abstract class AbstractEntity {
|
||||
|
||||
long id;
|
||||
public AbstractEntity(long id){
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.baeldung.boot.domain;
|
||||
|
||||
public class Bar extends AbstractEntity {
|
||||
|
||||
private int value;
|
||||
|
||||
public Bar(long id) {
|
||||
super(id);
|
||||
}
|
||||
|
||||
public Bar(long id, int value) {
|
||||
super(id);
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public int getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
public void setValue(int value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Bar [value=" + value + ", id=" + id + "]";
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.baeldung.boot.domain;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.Id;
|
||||
|
||||
@Entity
|
||||
public class Employee {
|
||||
|
||||
@Id
|
||||
private long id;
|
||||
private double salary;
|
||||
|
||||
public Employee() {
|
||||
}
|
||||
|
||||
public Employee(long id, double salary) {
|
||||
this.id = id;
|
||||
this.salary = salary;
|
||||
}
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public double getSalary() {
|
||||
return salary;
|
||||
}
|
||||
|
||||
public void setSalary(double salary) {
|
||||
this.salary = salary;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.boot.domain;
|
||||
|
||||
import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
|
||||
public class Foo extends AbstractEntity {
|
||||
|
||||
private String name;
|
||||
|
||||
public Foo(long id) {
|
||||
super(id);
|
||||
name = randomAlphanumeric(4);
|
||||
}
|
||||
|
||||
public Foo(long id, String name) {
|
||||
super(id);
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Foo [name=" + name + ", id=" + id + "]";
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.baeldung.boot.domain;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
|
||||
@Entity
|
||||
public class GenericEntity {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private Long id;
|
||||
private String value;
|
||||
|
||||
public GenericEntity() {
|
||||
}
|
||||
|
||||
public GenericEntity(String value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public GenericEntity(Long id, String value) {
|
||||
this.id = id;
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
public void setValue(String value) {
|
||||
this.value = value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.baeldung.boot.domain;
|
||||
|
||||
public enum Modes {
|
||||
|
||||
ALPHA, BETA;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.baeldung.boot.repository;
|
||||
|
||||
import com.baeldung.boot.domain.GenericEntity;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface GenericEntityRepository extends JpaRepository<GenericEntity, Long> {
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.baeldung.boot.web.resolver;
|
||||
|
||||
import org.springframework.core.MethodParameter;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.bind.support.WebDataBinderFactory;
|
||||
import org.springframework.web.context.request.NativeWebRequest;
|
||||
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
|
||||
import org.springframework.web.method.support.ModelAndViewContainer;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
@Component
|
||||
public class HeaderVersionArgumentResolver implements HandlerMethodArgumentResolver {
|
||||
|
||||
@Override
|
||||
public boolean supportsParameter(final MethodParameter methodParameter) {
|
||||
return methodParameter.getParameterAnnotation(Version.class) != null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object resolveArgument(final MethodParameter methodParameter, final ModelAndViewContainer modelAndViewContainer, final NativeWebRequest nativeWebRequest, final WebDataBinderFactory webDataBinderFactory) throws Exception {
|
||||
HttpServletRequest request = (HttpServletRequest) nativeWebRequest.getNativeRequest();
|
||||
|
||||
return request.getHeader("Version");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.baeldung.boot.web.resolver;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.PARAMETER)
|
||||
public @interface Version {
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.baeldung.cachedrequest;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
|
||||
import javax.servlet.ServletInputStream;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletRequestWrapper;
|
||||
|
||||
import org.springframework.util.StreamUtils;
|
||||
|
||||
public class CachedBodyHttpServletRequest extends HttpServletRequestWrapper {
|
||||
|
||||
private byte[] cachedBody;
|
||||
|
||||
public CachedBodyHttpServletRequest(HttpServletRequest request) throws IOException {
|
||||
super(request);
|
||||
InputStream requestInputStream = request.getInputStream();
|
||||
this.cachedBody = StreamUtils.copyToByteArray(requestInputStream);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ServletInputStream getInputStream() throws IOException {
|
||||
return new CachedBodyServletInputStream(this.cachedBody);
|
||||
}
|
||||
|
||||
@Override
|
||||
public BufferedReader getReader() throws IOException {
|
||||
// Create a reader from cachedContent
|
||||
// and return it
|
||||
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(this.cachedBody);
|
||||
return new BufferedReader(new InputStreamReader(byteArrayInputStream));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.baeldung.cachedrequest;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
|
||||
import javax.servlet.ReadListener;
|
||||
import javax.servlet.ServletInputStream;
|
||||
|
||||
public class CachedBodyServletInputStream extends ServletInputStream {
|
||||
|
||||
private InputStream cachedBodyInputStream;
|
||||
|
||||
public CachedBodyServletInputStream(byte[] cachedBody) {
|
||||
this.cachedBodyInputStream = new ByteArrayInputStream(cachedBody);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isFinished() {
|
||||
try {
|
||||
return cachedBodyInputStream.available() == 0;
|
||||
} catch (IOException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isReady() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setReadListener(ReadListener readListener) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int read() throws IOException {
|
||||
return cachedBodyInputStream.read();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.baeldung.cachedrequest;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import javax.servlet.FilterChain;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.annotation.WebFilter;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.springframework.core.Ordered;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
@Order(value = Ordered.HIGHEST_PRECEDENCE)
|
||||
@Component
|
||||
@WebFilter(filterName = "ContentCachingFilter", urlPatterns = "/*")
|
||||
public class ContentCachingFilter extends OncePerRequestFilter {
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
|
||||
System.out.println("IN ContentCachingFilter ");
|
||||
CachedBodyHttpServletRequest cachedBodyHttpServletRequest = new CachedBodyHttpServletRequest(httpServletRequest);
|
||||
filterChain.doFilter(cachedBodyHttpServletRequest, httpServletResponse);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.baeldung.cachedrequest;
|
||||
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
/**
|
||||
* To initialize the WebApplication, Please see
|
||||
* {@link com.baeldung.spring.config.MainWebAppInitializer}
|
||||
*/
|
||||
|
||||
@EnableWebMvc
|
||||
@Configuration
|
||||
@ComponentScan(basePackages = "com.baeldung.cachedrequest")
|
||||
public class HttpRequestDemoConfig implements WebMvcConfigurer {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.baeldung.cachedrequest;
|
||||
|
||||
public class Person {
|
||||
private String firstName;
|
||||
|
||||
private String lastName;
|
||||
|
||||
private int age;
|
||||
|
||||
public Person() {
|
||||
}
|
||||
|
||||
public Person(String firstName, String lastName, int age) {
|
||||
this.firstName = firstName;
|
||||
this.lastName = lastName;
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public void setFirstName(String firstName) {
|
||||
this.firstName = firstName;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public void setLastName(String lastName) {
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public int getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public void setAge(int age) {
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Person{" + "firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", age=" + age + '}';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.baeldung.cachedrequest;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
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 PersonController {
|
||||
|
||||
@PostMapping(value = "/person")
|
||||
@ResponseStatus(value = HttpStatus.NO_CONTENT)
|
||||
public void printPerson(@RequestBody Person person) {
|
||||
|
||||
System.out.println("In Demo Controller. Person " + "is : " + person);
|
||||
}
|
||||
|
||||
@GetMapping(value = "/person")
|
||||
@ResponseStatus(value = HttpStatus.NO_CONTENT)
|
||||
public void getPerson() {
|
||||
|
||||
System.out.println("In Demo Controller get method.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.cachedrequest;
|
||||
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
|
||||
import javax.servlet.FilterChain;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.annotation.WebFilter;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.springframework.core.Ordered;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StreamUtils;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
@Order(Ordered.LOWEST_PRECEDENCE)
|
||||
@Component
|
||||
@WebFilter(filterName = "printRequestContentFilter", urlPatterns = "/*")
|
||||
public class PrintRequestContentFilter extends OncePerRequestFilter {
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
|
||||
System.out.println("IN PrintRequestContentFilter ");
|
||||
InputStream inputStream = httpServletRequest.getInputStream();
|
||||
byte[] body = StreamUtils.copyToByteArray(inputStream);
|
||||
System.out.println("In PrintRequestContentFilter. Request body is: " + new String(body));
|
||||
filterChain.doFilter(httpServletRequest, httpServletResponse);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.baeldung.exclude_urls_filter;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@ComponentScan(basePackages = "com.baeldung.exclude_urls_filter")
|
||||
@Configuration
|
||||
@SpringBootApplication
|
||||
public class Application {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(Application.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.baeldung.exclude_urls_filter.controller;
|
||||
|
||||
import com.baeldung.exclude_urls_filter.service.FAQService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
public class FAQController {
|
||||
|
||||
private final FAQService faqService;
|
||||
|
||||
@Autowired
|
||||
public FAQController(FAQService faqService) {
|
||||
this.faqService = faqService;
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/faq/helpline", method = RequestMethod.GET)
|
||||
public ResponseEntity<String> getHelpLineNumber() {
|
||||
String helplineNumber = faqService.getHelpLineNumber();
|
||||
if (helplineNumber != null) {
|
||||
return new ResponseEntity<String>(helplineNumber, HttpStatus.OK);
|
||||
} else {
|
||||
return new ResponseEntity<String>("Unavailable", HttpStatus.NOT_FOUND);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.baeldung.exclude_urls_filter.controller;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
public class Ping {
|
||||
|
||||
@RequestMapping(value = "/health", method = RequestMethod.GET)
|
||||
public ResponseEntity<String> pingGet() {
|
||||
return new ResponseEntity<String>("pong", HttpStatus.OK);
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/health", method = RequestMethod.POST)
|
||||
public ResponseEntity<String> pingPost() {
|
||||
return new ResponseEntity<String>("pong", HttpStatus.OK);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.baeldung.exclude_urls_filter.filter;
|
||||
|
||||
import org.springframework.boot.web.servlet.FilterRegistrationBean;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
public class FilterRegistrationConfig {
|
||||
|
||||
@Bean
|
||||
public FilterRegistrationBean<LogFilter> logFilter() {
|
||||
FilterRegistrationBean<LogFilter> registrationBean = new FilterRegistrationBean<>();
|
||||
registrationBean.setFilter(new LogFilter());
|
||||
registrationBean.addUrlPatterns("/health", "/faq/*");
|
||||
return registrationBean;
|
||||
}
|
||||
|
||||
|
||||
@Bean
|
||||
public FilterRegistrationBean<HeaderValidatorFilter> headerValidatorFilter() {
|
||||
FilterRegistrationBean<HeaderValidatorFilter> registrationBean = new FilterRegistrationBean<>();
|
||||
registrationBean.setFilter(new HeaderValidatorFilter());
|
||||
registrationBean.addUrlPatterns("*");
|
||||
return registrationBean;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.baeldung.exclude_urls_filter.filter;
|
||||
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import javax.servlet.*;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
|
||||
@Order(1)
|
||||
public class HeaderValidatorFilter extends OncePerRequestFilter {
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
|
||||
throws ServletException, IOException {
|
||||
String path = request.getRequestURI();
|
||||
if ("/health".equals(path)) {
|
||||
filterChain.doFilter(request, response);
|
||||
return;
|
||||
}
|
||||
String countryCode = request.getHeader("X-Country-Code");
|
||||
if (!"US".equals(countryCode)) {
|
||||
response.sendError(HttpStatus.BAD_REQUEST.value(), "Invalid Locale");
|
||||
return;
|
||||
}
|
||||
|
||||
filterChain.doFilter(request, response);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.baeldung.exclude_urls_filter.filter;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import javax.servlet.*;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
|
||||
@Order(1)
|
||||
public class LogFilter extends OncePerRequestFilter {
|
||||
private final Logger logger = LoggerFactory.getLogger(LogFilter.class);
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
|
||||
FilterChain filterChain) throws ServletException, IOException {
|
||||
String path = request.getRequestURI();
|
||||
String contentType = request.getContentType();
|
||||
logger.info("Request URL path : {}, Request content type: {}", path, contentType);
|
||||
filterChain.doFilter(request, response);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.baeldung.exclude_urls_filter.service;
|
||||
|
||||
public interface FAQService {
|
||||
String getHelpLineNumber();
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.exclude_urls_filter.service;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class FAQServiceImpl implements FAQService {
|
||||
|
||||
private static final String HELPLINE_NUMBER = "+1 888-777-66";
|
||||
|
||||
@Override
|
||||
public String getHelpLineNumber() {
|
||||
return HELPLINE_NUMBER;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.flash_attributes;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
|
||||
|
||||
@SpringBootApplication
|
||||
public class Application extends SpringBootServletInitializer {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(Application.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.baeldung.flash_attributes.controllers;
|
||||
|
||||
import com.baeldung.flash_attributes.model.Poem;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
|
||||
import org.springframework.web.servlet.support.RequestContextUtils;
|
||||
import org.springframework.web.servlet.view.RedirectView;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
@Controller
|
||||
public class PoemSubmission {
|
||||
|
||||
@GetMapping("/poem/success")
|
||||
public String getSuccess(HttpServletRequest request) {
|
||||
Map<String, ?> inputFlashMap = RequestContextUtils.getInputFlashMap(request);
|
||||
if (inputFlashMap != null) {
|
||||
Poem poem = (Poem) inputFlashMap.get("poem");
|
||||
return "success";
|
||||
} else {
|
||||
return "redirect:/poem/submit";
|
||||
}
|
||||
}
|
||||
|
||||
@PostMapping("/poem/submit")
|
||||
public RedirectView submitPost(
|
||||
HttpServletRequest request,
|
||||
@ModelAttribute Poem poem,
|
||||
RedirectAttributes redirectAttributes) {
|
||||
if (Poem.isValidPoem(poem)) {
|
||||
redirectAttributes.addFlashAttribute("poem", poem);
|
||||
return new RedirectView("/poem/success", true);
|
||||
} else {
|
||||
return new RedirectView("/poem/submit", true);
|
||||
}
|
||||
}
|
||||
|
||||
@GetMapping("/poem/submit")
|
||||
public String submitGet(Model model) {
|
||||
model.addAttribute("poem", new Poem());
|
||||
return "submit";
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.baeldung.flash_attributes.model;
|
||||
|
||||
import org.apache.logging.log4j.util.Strings;
|
||||
|
||||
public class Poem {
|
||||
private String title;
|
||||
private String author;
|
||||
private String body;
|
||||
|
||||
public static boolean isValidPoem(Poem poem) {
|
||||
return poem != null && Strings.isNotBlank(poem.getAuthor()) && Strings.isNotBlank(poem.getBody())
|
||||
&& Strings.isNotBlank(poem.getTitle());
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return this.title;
|
||||
}
|
||||
|
||||
public void setTitle(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public String getBody() {
|
||||
return this.body;
|
||||
}
|
||||
|
||||
public void setBody(String body) {
|
||||
this.body = body;
|
||||
}
|
||||
|
||||
public String getAuthor() {
|
||||
return this.author;
|
||||
}
|
||||
|
||||
public void setAuthor(String author) {
|
||||
this.author = author;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.form_submission;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
|
||||
|
||||
@SpringBootApplication
|
||||
public class Application extends SpringBootServletInitializer {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(Application.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.baeldung.form_submission.controllers;
|
||||
|
||||
import com.baeldung.form_submission.model.Feedback;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.util.MultiValueMap;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@Controller
|
||||
public class FeedbackForm {
|
||||
|
||||
@GetMapping(path = "/feedback")
|
||||
public String getFeedbackForm(Model model) {
|
||||
Feedback feedback = new Feedback();
|
||||
model.addAttribute("feedback", feedback);
|
||||
return "feedback";
|
||||
}
|
||||
|
||||
@PostMapping(
|
||||
path = "/web/feedback",
|
||||
consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE})
|
||||
public String handleBrowserSubmissions(Feedback feedback) throws Exception {
|
||||
// Save feedback data
|
||||
return "redirect:/feedback/success";
|
||||
}
|
||||
|
||||
@GetMapping("/feedback/success")
|
||||
public ResponseEntity<String> getSuccess() {
|
||||
return new ResponseEntity<String>("Thank you for submitting feedback.", HttpStatus.OK);
|
||||
}
|
||||
|
||||
@PostMapping(
|
||||
path = "/feedback",
|
||||
consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE})
|
||||
public ResponseEntity<String> handleNonBrowserSubmissions(@RequestParam MultiValueMap paramMap) throws Exception {
|
||||
// Save feedback data
|
||||
return new ResponseEntity<String>("Thank you for submitting feedback", HttpStatus.OK);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.form_submission.model;
|
||||
|
||||
public class Feedback {
|
||||
private String emailId;
|
||||
private String comment;
|
||||
|
||||
public String getEmailId() {
|
||||
return this.emailId;
|
||||
}
|
||||
|
||||
public void setEmailId(String emailId) {
|
||||
this.emailId = emailId;
|
||||
}
|
||||
|
||||
public String getComment() {
|
||||
return this.comment;
|
||||
}
|
||||
|
||||
public void setComment(String comment) {
|
||||
this.comment = comment;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.baeldung.interpolation;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import javax.validation.MessageInterpolator;
|
||||
import java.util.Locale;
|
||||
|
||||
public class MyMessageInterpolator implements MessageInterpolator {
|
||||
|
||||
private static Logger logger = LoggerFactory.getLogger(MyMessageInterpolator.class);
|
||||
|
||||
private final MessageInterpolator defaultInterpolator;
|
||||
|
||||
public MyMessageInterpolator(MessageInterpolator interpolator) {
|
||||
this.defaultInterpolator = interpolator;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String interpolate(String messageTemplate, Context context) {
|
||||
messageTemplate = messageTemplate.toUpperCase();
|
||||
return defaultInterpolator.interpolate(messageTemplate, context, Locale.getDefault());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String interpolate(String messageTemplate, Context context, Locale locale) {
|
||||
messageTemplate = messageTemplate.toUpperCase();
|
||||
return defaultInterpolator.interpolate(messageTemplate, context, locale);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.baeldung.interpolation;
|
||||
|
||||
import javax.validation.constraints.NotNull;
|
||||
|
||||
public class NotNullRequest {
|
||||
|
||||
@NotNull(message = "stringValue has to be present")
|
||||
private String stringValue;
|
||||
|
||||
public String getStringValue() {
|
||||
return stringValue;
|
||||
}
|
||||
|
||||
public void setStringValue(String stringValue) {
|
||||
this.stringValue = stringValue;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.interpolation;
|
||||
|
||||
import javax.validation.Valid;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
public class ValidationController {
|
||||
|
||||
@PostMapping("/test-not-null")
|
||||
public void testNotNull(@Valid @RequestBody NotNullRequest request) {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.interpolation;
|
||||
|
||||
import java.util.Formatter;
|
||||
import javax.validation.constraints.Size;
|
||||
import javax.validation.constraints.Min;
|
||||
import javax.validation.constraints.DecimalMin;
|
||||
|
||||
public class ValidationExamples {
|
||||
|
||||
private static final Formatter formatter = new Formatter();
|
||||
|
||||
@Size(
|
||||
min = 5,
|
||||
max = 14,
|
||||
message = "The author email '${validatedValue}' must be between {min} and {max} characters long"
|
||||
)
|
||||
private String authorEmail;
|
||||
|
||||
@Min(
|
||||
value = 1,
|
||||
message = "There must be at least {value} test{value > 1 ? 's' : ''} in the test case"
|
||||
)
|
||||
private int testCount;
|
||||
|
||||
@DecimalMin(
|
||||
value = "50",
|
||||
message = "The code coverage ${formatter.format('%1$.2f', validatedValue)} must be higher than {value}%"
|
||||
)
|
||||
private double codeCoverage;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.baeldung.spring;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class Application {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(Application.class, args);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.baeldung.spring.config;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.format.FormatterRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
import com.baeldung.spring.config.converter.StringToEnumConverter;
|
||||
|
||||
@Configuration
|
||||
@EnableWebMvc
|
||||
public class MvcConfig implements WebMvcConfigurer {
|
||||
|
||||
public MvcConfig() {
|
||||
super();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addFormatters(FormatterRegistry registry) {
|
||||
registry.addConverter(new StringToEnumConverter());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.spring.config.converter;
|
||||
|
||||
import org.springframework.core.convert.converter.Converter;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.baeldung.spring.model.Modes;
|
||||
|
||||
@Component
|
||||
public class StringToEnumConverter implements Converter<String, Modes> {
|
||||
@Override
|
||||
public Modes convert(String source) {
|
||||
// Remove the try-catch block if we want to handle the exception globally in GlobalControllerExceptionHandler
|
||||
try {
|
||||
return Modes.valueOf(source.toUpperCase());
|
||||
} catch (IllegalArgumentException e) {
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.baeldung.spring.enums;
|
||||
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.baeldung.spring.model.Modes;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/enums")
|
||||
public class EnumController {
|
||||
|
||||
@GetMapping("/mode2str")
|
||||
public String getStringToMode(@RequestParam("mode") Modes mode) {
|
||||
return "good";
|
||||
}
|
||||
|
||||
@GetMapping("/findbymode/{mode}")
|
||||
public String findByEnum(@PathVariable Modes mode) {
|
||||
return "good";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.baeldung.spring.exceptions;
|
||||
|
||||
import org.springframework.core.convert.ConversionFailedException;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.ControllerAdvice;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
|
||||
@ControllerAdvice
|
||||
public class GlobalControllerExceptionHandler {
|
||||
@ExceptionHandler(ConversionFailedException.class)
|
||||
public ResponseEntity<String> handleConflict(RuntimeException ex) {
|
||||
// Remove the try-catch block in the StringToEnumConverter if we want to handle the exception here
|
||||
return new ResponseEntity<>(ex.getMessage(), HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package com.baeldung.spring.headers.controller;
|
||||
|
||||
import java.net.InetSocketAddress;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.util.MultiValueMap;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestHeader;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
public class ReadHeaderRestController {
|
||||
private static final Log LOG = LogFactory.getLog(ReadHeaderRestController.class);
|
||||
|
||||
@GetMapping("/")
|
||||
public ResponseEntity<String> index() {
|
||||
return new ResponseEntity<String>("Index", HttpStatus.OK);
|
||||
}
|
||||
|
||||
@GetMapping("/greeting")
|
||||
public ResponseEntity<String> greeting(@RequestHeader(value = "accept-language") String language) {
|
||||
String greeting = "";
|
||||
String firstLanguage = (language.length() > 1 ? language.substring(0, 2) : language);
|
||||
switch (firstLanguage) {
|
||||
case "es":
|
||||
greeting = "Hola!";
|
||||
break;
|
||||
case "de":
|
||||
greeting = "Hallo!";
|
||||
break;
|
||||
case "fr":
|
||||
greeting = "Bonjour!";
|
||||
break;
|
||||
case "en":
|
||||
default:
|
||||
greeting = "Hello!";
|
||||
break;
|
||||
}
|
||||
|
||||
return new ResponseEntity<String>(greeting, HttpStatus.OK);
|
||||
}
|
||||
|
||||
@GetMapping("/double")
|
||||
public ResponseEntity<String> doubleNumber(@RequestHeader("my-number") int myNumber) {
|
||||
return new ResponseEntity<String>(
|
||||
String.format("%d * 2 = %d", myNumber, (myNumber * 2)),
|
||||
HttpStatus.OK);
|
||||
}
|
||||
|
||||
@GetMapping("/listHeaders")
|
||||
public ResponseEntity<String> listAllHeaders(@RequestHeader Map<String, String> headers) {
|
||||
|
||||
headers.forEach((key, value) -> {
|
||||
LOG.info(String.format("Header '%s' = %s", key, value));
|
||||
});
|
||||
|
||||
return new ResponseEntity<String>(String.format("Listed %d headers", headers.size()), HttpStatus.OK);
|
||||
}
|
||||
|
||||
@GetMapping("/multiValue")
|
||||
public ResponseEntity<String> multiValue(@RequestHeader MultiValueMap<String, String> headers) {
|
||||
headers.forEach((key, value) -> {
|
||||
LOG.info(String.format("Header '%s' = %s", key, value.stream().collect(Collectors.joining("|"))));
|
||||
});
|
||||
|
||||
return new ResponseEntity<String>(String.format("Listed %d headers", headers.size()), HttpStatus.OK);
|
||||
}
|
||||
|
||||
@GetMapping("/getBaseUrl")
|
||||
public ResponseEntity<String> getBaseUrl(@RequestHeader HttpHeaders headers) {
|
||||
InetSocketAddress host = headers.getHost();
|
||||
String url = "http://" + host.getHostName() + ":" + host.getPort();
|
||||
return new ResponseEntity<String>(String.format("Base URL = %s", url), HttpStatus.OK);
|
||||
}
|
||||
|
||||
@GetMapping("/nonRequiredHeader")
|
||||
public ResponseEntity<String> evaluateNonRequiredHeader(
|
||||
@RequestHeader(value = "optional-header", required = false) String optionalHeader) {
|
||||
|
||||
return new ResponseEntity<String>(
|
||||
String.format("Was the optional header present? %s!", (optionalHeader == null ? "No" : "Yes")),
|
||||
HttpStatus.OK);
|
||||
}
|
||||
|
||||
@GetMapping("/default")
|
||||
public ResponseEntity<String> evaluateDefaultHeaderValue(
|
||||
@RequestHeader(value = "optional-header", defaultValue = "3600") int optionalHeader) {
|
||||
|
||||
return new ResponseEntity<String>(String.format("Optional Header is %d", optionalHeader), HttpStatus.OK);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.baeldung.spring.model;
|
||||
|
||||
public enum Modes {
|
||||
ALPHA, BETA;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.spring.slash;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
@SpringBootApplication
|
||||
public class Application implements WebMvcConfigurer {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(Application.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.spring.slash;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("slash")
|
||||
public class SlashParsingController {
|
||||
|
||||
@GetMapping("mypaths/{anything}")
|
||||
public String pathVariable(@PathVariable("anything") String anything) {
|
||||
return anything;
|
||||
}
|
||||
|
||||
@GetMapping("all/**")
|
||||
public String allDirectories(HttpServletRequest request) {
|
||||
return request.getRequestURI()
|
||||
.split(request.getContextPath() + "/all/")[1];
|
||||
}
|
||||
|
||||
@GetMapping("all")
|
||||
public String queryParameter(@RequestParam("param") String param) {
|
||||
return param;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.baeldung.validation.listvalidation;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@ComponentScan(basePackages = "com.baeldung.validation.listvalidation")
|
||||
@Configuration
|
||||
@SpringBootApplication
|
||||
public class SpringListValidationApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(SpringListValidationApplication.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.validation.listvalidation.constraint;
|
||||
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
|
||||
import javax.validation.Constraint;
|
||||
import javax.validation.Payload;
|
||||
|
||||
@Constraint(validatedBy = MaxSizeConstraintValidator.class)
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface MaxSizeConstraint {
|
||||
|
||||
String message() default "The input list cannot contain more than 4 movies.";
|
||||
|
||||
Class<?>[] groups() default {};
|
||||
|
||||
Class<? extends Payload>[] payload() default {};
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.baeldung.validation.listvalidation.constraint;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import javax.validation.ConstraintValidator;
|
||||
import javax.validation.ConstraintValidatorContext;
|
||||
|
||||
import com.baeldung.validation.listvalidation.model.Movie;
|
||||
|
||||
public class MaxSizeConstraintValidator implements ConstraintValidator<MaxSizeConstraint, List<Movie>> {
|
||||
|
||||
@Override
|
||||
public boolean isValid(List<Movie> values, ConstraintValidatorContext context) {
|
||||
return values.size() <= 4;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.validation.listvalidation.controller;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import javax.validation.Valid;
|
||||
import javax.validation.constraints.NotEmpty;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.baeldung.validation.listvalidation.constraint.MaxSizeConstraint;
|
||||
import com.baeldung.validation.listvalidation.model.Movie;
|
||||
import com.baeldung.validation.listvalidation.service.MovieService;
|
||||
|
||||
@Validated
|
||||
@RestController
|
||||
@RequestMapping("/movies")
|
||||
public class MovieController {
|
||||
|
||||
@Autowired
|
||||
private MovieService movieService;
|
||||
|
||||
@PostMapping
|
||||
public void addAll(@RequestBody @NotEmpty(message = "Input movie list cannot be empty.") @MaxSizeConstraint List<@Valid Movie> movies) {
|
||||
movieService.addAll(movies);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.baeldung.validation.listvalidation.exception;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
import javax.validation.ConstraintViolation;
|
||||
import javax.validation.ConstraintViolationException;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
|
||||
@RestControllerAdvice
|
||||
public class ConstraintViolationExceptionHandler {
|
||||
|
||||
private final Logger logger = LoggerFactory.getLogger(ConstraintViolationExceptionHandler.class);
|
||||
|
||||
@ExceptionHandler(ConstraintViolationException.class)
|
||||
public ResponseEntity<String> handle(ConstraintViolationException constraintViolationException) {
|
||||
Set<ConstraintViolation<?>> violations = constraintViolationException.getConstraintViolations();
|
||||
String errorMessage = "";
|
||||
if (!violations.isEmpty()) {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
violations.forEach(violation -> builder.append("\n" + violation.getMessage()));
|
||||
errorMessage = builder.toString();
|
||||
} else {
|
||||
errorMessage = "ConstraintViolationException occured.";
|
||||
}
|
||||
|
||||
logger.error(errorMessage);
|
||||
return new ResponseEntity<>(errorMessage, HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.baeldung.validation.listvalidation.model;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
import javax.validation.constraints.NotEmpty;
|
||||
|
||||
public class Movie {
|
||||
|
||||
private String id;
|
||||
|
||||
@NotEmpty(message = "Movie name cannot be empty.")
|
||||
private String name;
|
||||
|
||||
public Movie(String name) {
|
||||
this.id = UUID.randomUUID()
|
||||
.toString();
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Movie(){
|
||||
|
||||
}
|
||||
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package com.baeldung.validation.listvalidation.service;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.baeldung.validation.listvalidation.model.Movie;
|
||||
|
||||
@Service
|
||||
public class MovieService {
|
||||
|
||||
private final Logger logger = LoggerFactory.getLogger(MovieService.class);
|
||||
|
||||
private static List<Movie> moviesData;
|
||||
|
||||
static {
|
||||
moviesData = new ArrayList<>();
|
||||
|
||||
Movie m1 = new Movie("MovieABC");
|
||||
moviesData.add(m1);
|
||||
|
||||
Movie m2 = new Movie("MovieDEF");
|
||||
moviesData.add(m2);
|
||||
|
||||
}
|
||||
|
||||
public Movie get(String name) {
|
||||
Movie movie = null;
|
||||
for (Movie m : moviesData) {
|
||||
if (name.equalsIgnoreCase(m.getName())) {
|
||||
movie = m;
|
||||
logger.info("Found movie with name {} : {} ", name, movie);
|
||||
}
|
||||
}
|
||||
|
||||
return movie;
|
||||
}
|
||||
|
||||
public void add(Movie movie) {
|
||||
if (get(movie.getName()) == null) {
|
||||
moviesData.add(movie);
|
||||
logger.info("Added new movie - {}", movie.getName());
|
||||
}
|
||||
}
|
||||
|
||||
public void addAll(List<Movie> movies) {
|
||||
for (Movie movie : movies) {
|
||||
add(movie);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
spring.main.allow-bean-definition-overriding=true
|
||||
|
||||
spring.mail.host=localhost
|
||||
spring.mail.port=8025
|
||||
|
||||
spring.thymeleaf.cache=false
|
||||
spring.thymeleaf.enabled=true
|
||||
spring.thymeleaf.prefix=classpath:/templates/
|
||||
spring.thymeleaf.suffix=.html
|
||||
@@ -0,0 +1,41 @@
|
||||
<!DOCTYPE HTML>
|
||||
<html xmlns:th="http://www.thymeleaf.org">
|
||||
<head>
|
||||
<title>Poetry Contest: Submission</title>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<form action="#" method="post" th:action="@{/web/feedback}" th:object="${feedback}">
|
||||
|
||||
<table border='0' cellpadding='2' cellspacing='2' width='480px'>
|
||||
|
||||
<tr>
|
||||
<td align='center'>
|
||||
<label for="email">Email:</label>
|
||||
</td>
|
||||
<td>
|
||||
<input th:field=*{emailId} type="text"/>
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td align='center'>
|
||||
<label for="comment">Comment:</label>
|
||||
</td>
|
||||
<td>
|
||||
<textarea cols="30" rows="30" th:field=*{comment}/>
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td align='center'>
|
||||
<input type="submit" value="Submit Feedback">
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
|
||||
</table>
|
||||
</form>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,50 @@
|
||||
<!DOCTYPE HTML>
|
||||
<html xmlns:th="http://www.thymeleaf.org">
|
||||
<head>
|
||||
<title>Poetry Contest: Submission</title>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<form action="#" method="post" th:action="@{/poem/submit}" th:object="${poem}">
|
||||
|
||||
<table border='0' cellpadding='2' cellspacing='2' width='480px'>
|
||||
|
||||
<tr>
|
||||
<td align='center'>
|
||||
<label for="author">Author:</label>
|
||||
</td>
|
||||
<td>
|
||||
<input th:field="*{author}" type="text"/>
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td align='center'>
|
||||
<label for="title">Poem Title:</label>
|
||||
</td>
|
||||
<td>
|
||||
<input th:field="*{title}" type="text"/>
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td align='center'>
|
||||
<label for="body">Poem:</label>
|
||||
</td>
|
||||
<td>
|
||||
<textarea cols="30" rows="30" th:field="*{body}"/>
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td align='center'>
|
||||
<input type="submit" value="Submit Poem">
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
|
||||
</table>
|
||||
</form>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,15 @@
|
||||
<!DOCTYPE HTML>
|
||||
<html xmlns:th="http://www.thymeleaf.org">
|
||||
<head>
|
||||
<title>Poetry Contest: Thank You</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1 th:if="${poem}">
|
||||
<p th:text="${'You have successfully submitted poem titled - '+ poem?.title}"/>
|
||||
Click <a th:href="@{/poem/submit}"> here</a> to submit more.
|
||||
</h1>
|
||||
<h1 th:unless="${poem}">
|
||||
Click <a th:href="@{/poem/submit}"> here</a> to submit a poem.
|
||||
</h1>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.baeldung;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
import com.baeldung.spring.Application;
|
||||
|
||||
@SpringBootTest(classes = Application.class)
|
||||
public class AppContextIntegrationTest {
|
||||
@Test
|
||||
public void contextLoads() {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package com.baeldung;
|
||||
|
||||
import com.baeldung.boot.Application;
|
||||
import com.baeldung.boot.domain.Modes;
|
||||
import org.junit.Before;
|
||||
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.http.MediaType;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.test.context.web.WebAppConfiguration;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
|
||||
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
import org.springframework.web.context.WebApplicationContext;
|
||||
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.hasSize;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@SpringBootTest(classes = Application.class)
|
||||
@WebAppConfiguration
|
||||
public class SpringBootApplicationIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private WebApplicationContext webApplicationContext;
|
||||
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@Before
|
||||
public void setupMockMvc() {
|
||||
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRequestHasBeenMade_whenMeetsAllOfGivenConditions_thenCorrect() throws Exception {
|
||||
mockMvc.perform(MockMvcRequestBuilders.get("/entity/all")).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON)).andExpect(jsonPath("$", hasSize(4)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRequestHasBeenMade_whenMeetsFindByDateOfGivenConditions_thenCorrect() throws Exception {
|
||||
mockMvc.perform(MockMvcRequestBuilders.get("/entity/findbydate/{date}", "2011-12-03T10:15:30")).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(jsonPath("$.id", equalTo(1)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRequestHasBeenMade_whenMeetsFindByModeOfGivenConditions_thenCorrect() throws Exception {
|
||||
mockMvc.perform(MockMvcRequestBuilders.get("/entity/findbymode/{mode}", Modes.ALPHA.name())).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON)).andExpect(jsonPath("$.id", equalTo(1)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRequestHasBeenMade_whenMeetsFindByVersionOfGivenConditions_thenCorrect() throws Exception {
|
||||
mockMvc.perform(MockMvcRequestBuilders.get("/entity/findbyversion").header("Version", "1.0.0")).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(jsonPath("$.id", equalTo(1)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.baeldung;
|
||||
|
||||
import com.baeldung.boot.Application;
|
||||
import com.baeldung.boot.domain.GenericEntity;
|
||||
import com.baeldung.boot.repository.GenericEntityRepository;
|
||||
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.test.context.junit4.SpringRunner;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = Application.class)
|
||||
public class SpringBootJPAIntegrationTest {
|
||||
@Autowired
|
||||
private GenericEntityRepository genericEntityRepository;
|
||||
|
||||
@Test
|
||||
public void givenGenericEntityRepository_whenSaveAndRetreiveEntity_thenOK() {
|
||||
GenericEntity genericEntity = genericEntityRepository.save(new GenericEntity("test"));
|
||||
GenericEntity foundEntity = genericEntityRepository.findById(genericEntity.getId()).orElse(null);
|
||||
assertNotNull(foundEntity);
|
||||
assertEquals(genericEntity.getValue(), foundEntity.getValue());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package com.baeldung;
|
||||
|
||||
import com.baeldung.boot.Application;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
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.mail.SimpleMailMessage;
|
||||
import org.springframework.mail.javamail.JavaMailSender;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.subethamail.wiser.Wiser;
|
||||
import org.subethamail.wiser.WiserMessage;
|
||||
|
||||
import javax.mail.MessagingException;
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
import static org.hamcrest.Matchers.hasSize;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@SpringBootTest(classes = Application.class)
|
||||
public class SpringBootMailIntegrationTest {
|
||||
@Autowired
|
||||
private JavaMailSender javaMailSender;
|
||||
|
||||
private Wiser wiser;
|
||||
|
||||
private String userTo = "user2@localhost";
|
||||
private String userFrom = "user1@localhost";
|
||||
private String subject = "Test subject";
|
||||
private String textMail = "Text subject mail";
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
final int TEST_PORT = 8025;
|
||||
wiser = new Wiser(TEST_PORT);
|
||||
wiser.start();
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() throws Exception {
|
||||
wiser.stop();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMail_whenSendAndReceived_thenCorrect() throws Exception {
|
||||
SimpleMailMessage message = composeEmailMessage();
|
||||
javaMailSender.send(message);
|
||||
List<WiserMessage> messages = wiser.getMessages();
|
||||
|
||||
assertThat(messages, hasSize(1));
|
||||
WiserMessage wiserMessage = messages.get(0);
|
||||
assertEquals(userFrom, wiserMessage.getEnvelopeSender());
|
||||
assertEquals(userTo, wiserMessage.getEnvelopeReceiver());
|
||||
assertEquals(subject, getSubject(wiserMessage));
|
||||
assertEquals(textMail, getMessage(wiserMessage));
|
||||
}
|
||||
|
||||
private String getMessage(WiserMessage wiserMessage) throws MessagingException, IOException {
|
||||
return wiserMessage.getMimeMessage().getContent().toString().trim();
|
||||
}
|
||||
|
||||
private String getSubject(WiserMessage wiserMessage) throws MessagingException {
|
||||
return wiserMessage.getMimeMessage().getSubject();
|
||||
}
|
||||
|
||||
private SimpleMailMessage composeEmailMessage() {
|
||||
SimpleMailMessage mailMessage = new SimpleMailMessage();
|
||||
mailMessage.setTo(userTo);
|
||||
mailMessage.setReplyTo(userFrom);
|
||||
mailMessage.setFrom(userFrom);
|
||||
mailMessage.setSubject(subject);
|
||||
mailMessage.setText(textMail);
|
||||
return mailMessage;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.baeldung.cachedrequest;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.util.StreamUtils;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class CachedBodyHttpServletRequestUnitTest extends TestCase {
|
||||
|
||||
private CachedBodyServletInputStream servletInputStream;
|
||||
|
||||
@After
|
||||
public void cleanUp() throws IOException {
|
||||
if (null != servletInputStream) {
|
||||
servletInputStream.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGivenHttpServletRequestWithBody_whenCalledGetInputStream_ThenGetsServletInputStreamWithSameBody() throws IOException {
|
||||
// Given
|
||||
byte[] cachedBody = "{\"firstName\" :\"abc\",\"lastName\" : \"xyz\",\"age\" : 30\"}".getBytes();
|
||||
MockHttpServletRequest mockeddHttpServletRequest = new MockHttpServletRequest();
|
||||
mockeddHttpServletRequest.setContent(cachedBody);
|
||||
CachedBodyHttpServletRequest request = new CachedBodyHttpServletRequest(mockeddHttpServletRequest);
|
||||
|
||||
// when
|
||||
InputStream inputStream = request.getInputStream();
|
||||
|
||||
// then
|
||||
assertEquals(new String(cachedBody), new String(StreamUtils.copyToByteArray(inputStream)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGivenHttpServletRequestWithBody_whenCalledGetReader_ThenGetBufferedReaderWithSameBody() throws IOException {
|
||||
// Given
|
||||
byte[] cachedBody = "{\"firstName\" :\"abc\",\"lastName\" : \"xyz\",\"age\" : 30\"}".getBytes();
|
||||
MockHttpServletRequest mockeddHttpServletRequest = new MockHttpServletRequest();
|
||||
mockeddHttpServletRequest.setContent(cachedBody);
|
||||
CachedBodyHttpServletRequest request = new CachedBodyHttpServletRequest(mockeddHttpServletRequest);
|
||||
|
||||
// when
|
||||
BufferedReader bufferedReader = request.getReader();
|
||||
|
||||
// then
|
||||
String line = "";
|
||||
StringBuilder builder = new StringBuilder();
|
||||
while ((line = bufferedReader.readLine()) != null) {
|
||||
builder.append(line);
|
||||
}
|
||||
assertEquals(new String(cachedBody), builder.toString());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package com.baeldung.cachedrequest;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
|
||||
import javax.servlet.ReadListener;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.springframework.util.StreamUtils;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class CachedBodyServletInputStreamUnitTest extends TestCase {
|
||||
|
||||
private CachedBodyServletInputStream servletInputStream;
|
||||
|
||||
@After
|
||||
public void cleanUp() throws IOException {
|
||||
if (null != servletInputStream) {
|
||||
servletInputStream.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGivenServletInputStreamCreated_whenCalledisFinished_Thenfalse() {
|
||||
// Given
|
||||
byte[] cachedBody = "{\"firstName\" :\"abc\",\"lastName\" : \"xyz\",\"age\" : 30\"}".getBytes();
|
||||
servletInputStream = new CachedBodyServletInputStream(cachedBody);
|
||||
|
||||
// when
|
||||
boolean finished = servletInputStream.isFinished();
|
||||
|
||||
// then
|
||||
assertFalse(finished);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGivenServletInputStreamCreatedAndBodyRead_whenCalledisFinished_ThenTrue() throws IOException {
|
||||
// Given
|
||||
byte[] cachedBody = "{\"firstName\" :\"abc\",\"lastName\" : \"xyz\",\"age\" : 30\"}".getBytes();
|
||||
servletInputStream = new CachedBodyServletInputStream(cachedBody);
|
||||
StreamUtils.copyToByteArray(servletInputStream);
|
||||
|
||||
// when
|
||||
boolean finished = servletInputStream.isFinished();
|
||||
|
||||
// then
|
||||
assertTrue(finished);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGivenServletInputStreamCreatedAndBodyRead_whenCalledIsReady_ThenTrue() throws IOException {
|
||||
// Given
|
||||
byte[] cachedBody = "{\"firstName\" :\"abc\",\"lastName\" : \"xyz\",\"age\" : 30\"}".getBytes();
|
||||
servletInputStream = new CachedBodyServletInputStream(cachedBody);
|
||||
|
||||
// when
|
||||
boolean ready = servletInputStream.isReady();
|
||||
|
||||
// then
|
||||
assertTrue(ready);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGivenServletInputStreamCreated_whenCalledIsRead_ThenReturnsBody() throws IOException {
|
||||
// Given
|
||||
byte[] cachedBody = "{\"firstName\" :\"abc\",\"lastName\" : \"xyz\",\"age\" : 30\"}".getBytes();
|
||||
servletInputStream = new CachedBodyServletInputStream(cachedBody);
|
||||
|
||||
// when
|
||||
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
|
||||
int len = 0;
|
||||
byte[] buffer = new byte[1024];
|
||||
while ((len = servletInputStream.read(buffer)) != -1) {
|
||||
byteArrayOutputStream.write(buffer, 0, len);
|
||||
}
|
||||
|
||||
// then
|
||||
assertEquals(new String(cachedBody), new String(byteArrayOutputStream.toByteArray()));
|
||||
}
|
||||
|
||||
@Test(expected = UnsupportedOperationException.class)
|
||||
public void testGivenServletInputStreamCreated_whenCalledIsRead_ThenThrowsException() throws IOException {
|
||||
// Given
|
||||
byte[] cachedBody = "{\"firstName\" :\"abc\",\"lastName\" : \"xyz\",\"age\" : 30\"}".getBytes();
|
||||
servletInputStream = new CachedBodyServletInputStream(cachedBody);
|
||||
|
||||
// when
|
||||
servletInputStream.setReadListener(Mockito.mock(ReadListener.class));
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.baeldung.cachedrequest;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import javax.servlet.FilterChain;
|
||||
import javax.servlet.ServletException;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class ContentCachingFilterUnitTest extends TestCase {
|
||||
|
||||
@InjectMocks
|
||||
private ContentCachingFilter filterToTest;
|
||||
|
||||
@Test
|
||||
public void testGivenHttpRequest_WhenDoFilter_thenCreatesRequestWrapperObject() throws IOException, ServletException {
|
||||
// Given
|
||||
MockHttpServletRequest mockedRequest = new MockHttpServletRequest();
|
||||
MockHttpServletResponse mockedResponse = new MockHttpServletResponse();
|
||||
FilterChain mockedFilterChain = Mockito.mock(FilterChain.class);
|
||||
|
||||
// when
|
||||
filterToTest.doFilter(mockedRequest, mockedResponse, mockedFilterChain);
|
||||
|
||||
// then
|
||||
Mockito.verify(mockedFilterChain, Mockito.times(1))
|
||||
.doFilter(Mockito.any(CachedBodyHttpServletRequest.class), Mockito.any(MockHttpServletResponse.class));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package com.baeldung.cachedrequest;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.test.context.web.AnnotationConfigWebContextLoader;
|
||||
import org.springframework.test.context.web.WebAppConfiguration;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.ResultActions;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
import org.springframework.web.context.WebApplicationContext;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@ContextConfiguration(loader = AnnotationConfigWebContextLoader.class, classes = { HttpRequestDemoConfig.class, ContentCachingFilter.class, PrintRequestContentFilter.class, PersonController.class })
|
||||
@WebAppConfiguration
|
||||
public class PersonControllerIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private WebApplicationContext wac;
|
||||
|
||||
private MockMvc mockMvc;
|
||||
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
@Autowired
|
||||
private ContentCachingFilter contentCachingFilter;
|
||||
|
||||
@Autowired
|
||||
private PrintRequestContentFilter printRequestContentFilter;
|
||||
|
||||
@Before
|
||||
public void setup() throws Exception {
|
||||
|
||||
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac)
|
||||
.addFilter(contentCachingFilter, "/**")
|
||||
.addFilter(printRequestContentFilter, "/**")
|
||||
.build();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenValidInput_thenCreateBook() throws IOException, Exception {
|
||||
// assign - given
|
||||
Person person = new Person("sumit", "abc", 100);
|
||||
|
||||
// act - when
|
||||
ResultActions result = mockMvc.perform(post("/person").accept(MediaType.APPLICATION_JSON)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(person)));
|
||||
|
||||
// assert - then
|
||||
result.andExpect(status().isNoContent());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.baeldung.cachedrequest;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import javax.servlet.FilterChain;
|
||||
import javax.servlet.ServletException;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class PrintRequestContentFilterUnitTest extends TestCase {
|
||||
|
||||
@InjectMocks
|
||||
private PrintRequestContentFilter filterToTest;
|
||||
|
||||
@Test
|
||||
public void testGivenHttpRequest_WhenDoFilter_thenReadsBody() throws IOException, ServletException {
|
||||
// Given
|
||||
MockHttpServletRequest mockedRequest = new MockHttpServletRequest();
|
||||
MockHttpServletResponse mockedResponse = new MockHttpServletResponse();
|
||||
FilterChain mockedFilterChain = Mockito.mock(FilterChain.class);
|
||||
CachedBodyHttpServletRequest cachedBodyHttpServletRequest = new CachedBodyHttpServletRequest(mockedRequest);
|
||||
|
||||
// when
|
||||
filterToTest.doFilter(cachedBodyHttpServletRequest, mockedResponse, mockedFilterChain);
|
||||
|
||||
// then
|
||||
Mockito.verify(mockedFilterChain, Mockito.times(1))
|
||||
.doFilter(cachedBodyHttpServletRequest, mockedResponse);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package com.baeldung.headers.controller;
|
||||
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.test.context.junit.jupiter.SpringExtension;
|
||||
import org.springframework.test.context.junit.jupiter.web.SpringJUnitWebConfig;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
|
||||
import com.baeldung.spring.headers.controller.ReadHeaderRestController;
|
||||
|
||||
@SpringJUnitWebConfig(ReadHeaderRestControllerIntegrationTest.Config.class)
|
||||
@ExtendWith(SpringExtension.class)
|
||||
public class ReadHeaderRestControllerIntegrationTest {
|
||||
private static final Log LOG = LogFactory.getLog(ReadHeaderRestControllerIntegrationTest.class);
|
||||
|
||||
@Configuration
|
||||
static class Config {
|
||||
|
||||
}
|
||||
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@BeforeEach
|
||||
public void setUp() {
|
||||
mockMvc = MockMvcBuilders.standaloneSetup(new ReadHeaderRestController())
|
||||
.build();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetRequestSentToAllHeaders_thenStatusOkAndTextReturned() throws Exception {
|
||||
mockMvc.perform(get("/listHeaders").header("my-header", "Test"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string("Listed 1 headers"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetRequestSentToMultiValue_thenStatusOkAndTextReturned() throws Exception {
|
||||
mockMvc.perform(get("/multiValue").header("my-header", "ABC", "DEF", "GHI"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string("Listed 1 headers"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetRequestSentToGreeting_thenStatusOKAndGreetingReturned() throws Exception {
|
||||
mockMvc.perform(get("/greeting").header("accept-language", "de"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string("Hallo!"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetRequestSentToDouble_thenStatusOKAndCorrectResultReturned() throws Exception {
|
||||
mockMvc.perform(get("/double").header("my-number", 2))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string("2 * 2 = 4"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetRequestSentToGetBaseUrl_thenStatusOkAndHostReturned() throws Exception {
|
||||
mockMvc.perform(get("/getBaseUrl").header("host", "localhost:8080"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string("Base URL = http://localhost:8080"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetRequestSentToNonRequiredHeaderWithoutHeader_thenStatusOKAndMessageReturned() throws Exception {
|
||||
mockMvc.perform(get("/nonRequiredHeader"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string("Was the optional header present? No!"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetRequestSentToDefaultWithoutHeader_thenStatusOKAndMessageReturned() throws Exception {
|
||||
mockMvc.perform(get("/default"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string("Optional Header is 3600"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package com.baeldung.spring.slash;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
import java.net.URI;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.junit.jupiter.SpringExtension;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.MvcResult;
|
||||
|
||||
@AutoConfigureMockMvc
|
||||
@ExtendWith(SpringExtension.class)
|
||||
@SpringBootTest
|
||||
public class SlashParsingControllerIntTest {
|
||||
|
||||
@Autowired
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@Test
|
||||
public void whenUsingPathVariablemWithoutSlashes_thenStatusOk() throws Exception {
|
||||
final String stringWithoutSlashes = "noslash";
|
||||
|
||||
MvcResult mvcResult = mockMvc.perform(get("/slash/mypaths/" + stringWithoutSlashes))
|
||||
.andExpect(status().isOk())
|
||||
.andReturn();
|
||||
|
||||
assertEquals(stringWithoutSlashes, mvcResult.getResponse()
|
||||
.getContentAsString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingPathVariableWithSlashes_thenStatusNotFound() throws Exception {
|
||||
final String stringWithSlashes = "url/with/slashes";
|
||||
|
||||
mockMvc.perform(get("/slash/mypaths/" + stringWithSlashes))
|
||||
.andExpect(status().isNotFound());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAllFallbackEndpoint_whenUsingPathWithSlashes_thenStatusOk() throws Exception {
|
||||
final String stringWithSlashes = "url/for/testing/purposes";
|
||||
|
||||
MvcResult mvcResult = mockMvc.perform(get("/slash/all/" + stringWithSlashes))
|
||||
.andExpect(status().isOk())
|
||||
.andReturn();
|
||||
|
||||
assertEquals(stringWithSlashes, mvcResult.getResponse()
|
||||
.getContentAsString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAllFallbackEndpoint_whenUsingConsecutiveSlashes_thenPathNormalized() throws Exception {
|
||||
final String stringWithSlashes = "http://myurl.com";
|
||||
|
||||
MvcResult mvcResult = mockMvc.perform(get("/slash/all/" + stringWithSlashes))
|
||||
.andExpect(status().isOk())
|
||||
.andReturn();
|
||||
|
||||
String stringWithSlashesNormalized = URI.create("/slash/all/" + stringWithSlashes)
|
||||
.normalize()
|
||||
.toString()
|
||||
.split("/slash/all/")[1];
|
||||
|
||||
assertEquals(stringWithSlashesNormalized, mvcResult.getResponse()
|
||||
.getContentAsString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingSlashesInQueryParam_thenParameterAccepted() throws Exception {
|
||||
final String stringWithSlashes = "url/for////testing/purposes";
|
||||
|
||||
MvcResult mvcResult = mockMvc.perform(get("/slash/all").param("param", stringWithSlashes))
|
||||
.andExpect(status().isOk())
|
||||
.andReturn();
|
||||
|
||||
assertEquals(stringWithSlashes, mvcResult.getResponse()
|
||||
.getContentAsString());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package com.baeldung.validation.listvalidation;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
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.context.SpringBootTest;
|
||||
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;
|
||||
|
||||
import com.baeldung.validation.listvalidation.model.Movie;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = SpringListValidationApplication.class)
|
||||
@AutoConfigureMockMvc
|
||||
public class MovieControllerIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private MockMvc mvc;
|
||||
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
@Test
|
||||
public void givenValidMovieList_whenAddingMovieList_thenIsOK() throws Exception {
|
||||
List<Movie> movies = new ArrayList<>();
|
||||
Movie movie = new Movie("Movie3");
|
||||
movies.add(movie);
|
||||
mvc.perform(MockMvcRequestBuilders.post("/movies")
|
||||
.contentType(MediaType.APPLICATION_JSON_UTF8)
|
||||
.content(objectMapper.writeValueAsString(movies)))
|
||||
.andExpect(MockMvcResultMatchers.status()
|
||||
.isOk());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmptyMovieList_whenAddingMovieList_thenThrowBadRequest() throws Exception {
|
||||
List<Movie> movies = new ArrayList<>();
|
||||
mvc.perform(MockMvcRequestBuilders.post("/movies")
|
||||
.contentType(MediaType.APPLICATION_JSON_UTF8)
|
||||
.content(objectMapper.writeValueAsString(movies)))
|
||||
.andExpect(MockMvcResultMatchers.status()
|
||||
.isBadRequest());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmptyMovieName_whenAddingMovieList_thenThrowBadRequest() throws Exception {
|
||||
Movie movie = new Movie("");
|
||||
mvc.perform(MockMvcRequestBuilders.post("/movies")
|
||||
.contentType(MediaType.APPLICATION_JSON_UTF8)
|
||||
.content(objectMapper.writeValueAsString(Arrays.asList(movie))))
|
||||
.andExpect(MockMvcResultMatchers.status()
|
||||
.isBadRequest());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given5MoviesInputList_whenAddingMovieList_thenThrowBadRequest() throws Exception {
|
||||
Movie movie1 = new Movie("Movie1");
|
||||
Movie movie2 = new Movie("Movie2");
|
||||
Movie movie3 = new Movie("Movie3");
|
||||
Movie movie4 = new Movie("Movie4");
|
||||
Movie movie5 = new Movie("Movie5");
|
||||
List<Movie> movies = new ArrayList<>();
|
||||
movies.add(movie1);
|
||||
movies.add(movie2);
|
||||
movies.add(movie3);
|
||||
movies.add(movie4);
|
||||
movies.add(movie5);
|
||||
mvc.perform(MockMvcRequestBuilders.post("/movies")
|
||||
.contentType(MediaType.APPLICATION_JSON_UTF8)
|
||||
.content(objectMapper.writeValueAsString(movies)))
|
||||
.andExpect(MockMvcResultMatchers.status()
|
||||
.isBadRequest());
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user