Merge pull request #8125 from eugenp/revert-8119-BAEL-3275-2

Revert "BAEL-3275: Using blocking queue for pub-sub"
This commit is contained in:
Eric Martin
2019-10-31 20:43:47 -05:00
committed by GitHub
parent db85c8f275
commit 3225470df5
20543 changed files with 1642750 additions and 0 deletions
@@ -0,0 +1,13 @@
package com.baeldung;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Spring5Application {
public static void main(String[] args) {
SpringApplication.run(Spring5Application.class, args);
}
}
@@ -0,0 +1,8 @@
package com.baeldung.annotationconfigvscomponentscan.components;
import org.springframework.stereotype.Component;
@Component
public class AccountService {
}
@@ -0,0 +1,16 @@
package com.baeldung.annotationconfigvscomponentscan.components;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class UserService {
@Autowired
private AccountService accountService;
public AccountService getAccountService() {
return accountService;
}
}
@@ -0,0 +1,124 @@
package com.baeldung.assertions;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.util.Assert;
public class Car {
private String state = "stop";
public void drive(int speed) {
Assert.isTrue(speed > 0, "speed must be positive");
this.state = "drive";
// ...
if (!(speed > 0)) {
throw new IllegalArgumentException("speed must be >0");
}
}
public void stop() {
this.state = "stop";
}
public void fuel() {
Assert.state(this.state.equals("stop"), "car must be stopped");
// ...
}
public void fuelwithSupplier() {
Assert.state(this.state.equals("stop"), () -> "car must be stopped");
// ...
}
public void сhangeOil(String oil) {
Assert.notNull(oil, "oil mustn't be null");
// ...
}
public void replaceBattery(CarBattery carBattery) {
Assert.isNull(carBattery.getCharge(), "to replace battery the charge must be null");
// ...
}
public void сhangeEngine(Engine engine) {
Assert.isInstanceOf(ToyotaEngine.class, engine);
// ...
}
public void repairEngine(Engine engine) {
Assert.isAssignable(Engine.class, ToyotaEngine.class);
// ...
}
public void startWithHasLength(String key) {
Assert.hasLength(key, "key must not be null and must not the empty");
// ...
}
public void startWithHasText(String key) {
Assert.hasText(key, "key must not be null and must contain at least one non-whitespace character");
// ...
}
public void startWithNotContain(String key) {
Assert.doesNotContain(key, "123", "key must not contain 123");
// ...
}
public void repair(Collection<String> repairParts) {
Assert.notEmpty(repairParts, "collection of repairParts mustn't be empty");
// ...
}
public void repair(Map<String, String> repairParts) {
Assert.notEmpty(repairParts, "map of repairParts mustn't be empty");
// ...
}
public void repair(String[] repairParts) {
Assert.notEmpty(repairParts, "array of repairParts must not be empty");
// ...
}
public void repairWithNoNull(String[] repairParts) {
Assert.noNullElements(repairParts, "array of repairParts must not contain null elements");
// ...
}
public static void main(String[] args) {
Car car = new Car();
car.drive(50);
car.stop();
car.fuel();
car.сhangeOil("oil");
CarBattery carBattery = new CarBattery();
car.replaceBattery(carBattery);
car.сhangeEngine(new ToyotaEngine());
car.startWithHasLength(" ");
car.startWithHasText("t");
car.startWithNotContain("132");
List<String> repairPartsCollection = new ArrayList<String>();
repairPartsCollection.add("part");
car.repair(repairPartsCollection);
Map<String, String> repairPartsMap = new HashMap<String, String>();
repairPartsMap.put("1", "part");
car.repair(repairPartsMap);
String[] repairPartsArray = { "part" };
car.repair(repairPartsArray);
}
}
@@ -0,0 +1,13 @@
package com.baeldung.assertions;
public class CarBattery {
private String charge;
public String getCharge() {
return charge;
}
public void setCharge(String charge) {
this.charge = charge;
}
}
@@ -0,0 +1,4 @@
package com.baeldung.assertions;
public class Engine {
}
@@ -0,0 +1,5 @@
package com.baeldung.assertions;
public class ToyotaEngine extends Engine {
}
@@ -0,0 +1,12 @@
package com.baeldung.config;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@Configuration
@EnableJpaRepositories("com.baeldung.persistence")
@EntityScan("com.baeldung.web")
public class PersistenceConfig {
}
@@ -0,0 +1,41 @@
package com.baeldung.exception;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;
@RestController
public class ActorController {
@Autowired
ActorService actorService;
@GetMapping("/actor/{id}")
public String getActorName(@PathVariable("id") int id) {
try {
return actorService.getActor(id);
} catch (ActorNotFoundException ex) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Actor Not Found", ex);
}
}
@DeleteMapping("/actor/{id}")
public String getActor(@PathVariable("id") int id) {
return actorService.removeActor(id);
}
@PutMapping("/actor/{id}/{name}")
public String updateActorName(@PathVariable("id") int id, @PathVariable("name") String name) {
try {
return actorService.updateActor(id, name);
} catch (ActorNotFoundException ex) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Provide correct Actor Id", ex);
}
}
}
@@ -0,0 +1,13 @@
package com.baeldung.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(code = HttpStatus.NOT_FOUND, reason = "Actor Not Found")
public class ActorNotFoundException extends Exception {
private static final long serialVersionUID = 1L;
public ActorNotFoundException(String errorMessage) {
super(errorMessage);
}
}
@@ -0,0 +1,35 @@
package com.baeldung.exception;
import java.util.Arrays;
import java.util.List;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;
@Service
public class ActorService {
List<String> actors = Arrays.asList("Jack Nicholson", "Marlon Brando", "Robert De Niro", "Al Pacino", "Tom Hanks");
public String getActor(int index) throws ActorNotFoundException {
if (index >= actors.size()) {
throw new ActorNotFoundException("Actor Not Found in Repsoitory");
}
return actors.get(index);
}
public String updateActor(int index, String actorName) throws ActorNotFoundException {
if (index >= actors.size()) {
throw new ActorNotFoundException("Actor Not Found in Repsoitory");
}
actors.set(index, actorName);
return actorName;
}
public String removeActor(int index) {
if (index >= actors.size()) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Actor Not Found in Repsoitory");
}
return actors.remove(index);
}
}
@@ -0,0 +1,14 @@
package com.baeldung.exception;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication(exclude = SecurityAutoConfiguration.class)
@ComponentScan(basePackages = { "com.baeldung.exception" })
public class SpringExceptionApplication {
public static void main(String[] args) {
SpringApplication.run(SpringExceptionApplication.class, args);
}
}
@@ -0,0 +1,23 @@
package com.baeldung.functional;
class Actor {
private String firstname;
private String lastname;
public Actor() {
}
public Actor(String firstname, String lastname) {
this.firstname = firstname;
this.lastname = lastname;
}
public String getFirstname() {
return firstname;
}
public String getLastname() {
return lastname;
}
}
@@ -0,0 +1,11 @@
package com.baeldung.functional;
import java.util.Random;
public class MyService {
public int getRandomNumber() {
return (new Random().nextInt(10));
}
}
@@ -0,0 +1,38 @@
package com.baeldung.jdbc.autogenkey.repository;
import java.sql.PreparedStatement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;
@Repository
public class MessageRepositoryJDBCTemplate {
@Autowired
JdbcTemplate jdbcTemplate;
final String INSERT_MESSAGE_SQL = "insert into sys_message (message) values(?) ";
public long insert(final String message) {
KeyHolder keyHolder = new GeneratedKeyHolder();
jdbcTemplate.update(connection -> {
PreparedStatement ps = connection.prepareStatement(INSERT_MESSAGE_SQL);
ps.setString(1, message);
return ps;
}, keyHolder);
return (long) keyHolder.getKey();
}
final String SELECT_BY_ID = "select message from sys_message where id = ?";
public String getMessageById(long id) {
return this.jdbcTemplate.queryForObject(SELECT_BY_ID, String.class, new Object[] { id });
}
}
@@ -0,0 +1,29 @@
package com.baeldung.jdbc.autogenkey.repository;
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import org.springframework.stereotype.Repository;
@Repository
public class MessageRepositorySimpleJDBCInsert {
SimpleJdbcInsert messageInsert;
@Autowired
public MessageRepositorySimpleJDBCInsert(DataSource dataSource) {
messageInsert = new SimpleJdbcInsert(dataSource).withTableName("sys_message").usingGeneratedKeyColumns("id");
}
public long insert(String message) {
Map<String, Object> parameters = new HashMap<String, Object>(1);
parameters.put("message", message);
Number newId = messageInsert.executeAndReturnKey(parameters);
return (long) newId;
}
}
@@ -0,0 +1,127 @@
package com.baeldung.jsonb;
import java.math.BigDecimal;
import java.time.LocalDate;
import javax.json.bind.annotation.JsonbDateFormat;
import javax.json.bind.annotation.JsonbNumberFormat;
import javax.json.bind.annotation.JsonbProperty;
import javax.json.bind.annotation.JsonbTransient;
public class Person {
private int id;
@JsonbProperty("person-name")
private String name;
@JsonbProperty(nillable = true)
private String email;
@JsonbTransient
private int age;
@JsonbDateFormat("dd-MM-yyyy")
private LocalDate registeredDate;
private BigDecimal salary;
public Person() {
}
public Person(int id, String name, String email, int age, LocalDate registeredDate, BigDecimal salary) {
super();
this.id = id;
this.name = name;
this.email = email;
this.age = age;
this.registeredDate = registeredDate;
this.salary = salary;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@JsonbNumberFormat(locale = "en_US", value = "#0.0")
public BigDecimal getSalary() {
return salary;
}
public void setSalary(BigDecimal salary) {
this.salary = salary;
}
public LocalDate getRegisteredDate() {
return registeredDate;
}
public void setRegisteredDate(LocalDate registeredDate) {
this.registeredDate = registeredDate;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Person [id=");
builder.append(id);
builder.append(", name=");
builder.append(name);
builder.append(", email=");
builder.append(email);
builder.append(", age=");
builder.append(age);
builder.append(", registeredDate=");
builder.append(registeredDate);
builder.append(", salary=");
builder.append(salary);
builder.append("]");
return builder.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (id != other.id)
return false;
return true;
}
}
@@ -0,0 +1,58 @@
package com.baeldung.jsonb;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.annotation.PostConstruct;
import org.springframework.http.HttpStatus;
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.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
@RestController("/person")
public class PersonController {
List<Person> personRepository;
@PostConstruct
public void init() {
// @formatter:off
personRepository = new ArrayList<>(Arrays.asList(
new Person(1, "Jhon", "jhon@test.com", 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1000)),
new Person(2, "Jhon", "jhon1@test.com", 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1500)),
new Person(3, "Jhon", null, 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1000)),
new Person(4, "Tom", "tom@test.com", 21, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1500)),
new Person(5, "Mark", "mark@test.com", 21, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1200)),
new Person(6, "Julia", "jhon@test.com", 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1000))));
// @formatter:on
}
@GetMapping("/person/{id}")
@ResponseBody
public Person findById(@PathVariable final int id) {
return personRepository.get(id);
}
@PostMapping("/person")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public boolean insertPerson(@RequestBody final Person person) {
return personRepository.add(person);
}
@GetMapping("/person")
@ResponseBody
public List<Person> findAll() {
return personRepository;
}
}
@@ -0,0 +1,31 @@
package com.baeldung.jsonb;
import java.util.ArrayList;
import java.util.Collection;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.JsonbHttpMessageConverter;
@SpringBootApplication(exclude = SecurityAutoConfiguration.class)
@ComponentScan(basePackages = { "com.baeldung.jsonb" })
public class Spring5Application {
public static void main(String[] args) {
SpringApplication.run(Spring5Application.class, args);
}
@Bean
public HttpMessageConverters customConverters() {
Collection<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
JsonbHttpMessageConverter jsonbHttpMessageConverter = new JsonbHttpMessageConverter();
messageConverters.add(jsonbHttpMessageConverter);
return new HttpMessageConverters(true, messageConverters);
}
}
@@ -0,0 +1,46 @@
package com.baeldung.jupiter;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.SynthesizingMethodParameter;
import org.springframework.util.Assert;
import java.lang.reflect.Constructor;
import java.lang.reflect.Executable;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
abstract class MethodParameterFactory {
private MethodParameterFactory() {
}
public static MethodParameter createMethodParameter(Parameter parameter) {
Assert.notNull(parameter, "Parameter must not be null");
Executable executable = parameter.getDeclaringExecutable();
if (executable instanceof Method) {
return new MethodParameter((Method) executable, getIndex(parameter));
}
return new MethodParameter((Constructor<?>) executable, getIndex(parameter));
}
public static SynthesizingMethodParameter createSynthesizingMethodParameter(Parameter parameter) {
Assert.notNull(parameter, "Parameter must not be null");
Executable executable = parameter.getDeclaringExecutable();
if (executable instanceof Method) {
return new SynthesizingMethodParameter((Method) executable, getIndex(parameter));
}
throw new UnsupportedOperationException("Cannot create a SynthesizingMethodParameter for a constructor parameter: " + parameter);
}
private static int getIndex(Parameter parameter) {
Assert.notNull(parameter, "Parameter must not be null");
Executable executable = parameter.getDeclaringExecutable();
Parameter[] parameters = executable.getParameters();
for (int i = 0; i < parameters.length; i++) {
if (parameters[i] == parameter) {
return i;
}
}
throw new IllegalStateException(String.format("Failed to resolve index of parameter [%s] in executable [%s]", parameter, executable.toGenericString()));
}
}
@@ -0,0 +1,44 @@
package com.baeldung.jupiter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.DependencyDescriptor;
import org.springframework.context.ApplicationContext;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.AnnotatedElementUtils;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.Optional;
import static org.springframework.core.annotation.AnnotatedElementUtils.hasAnnotation;
abstract class ParameterAutowireUtils {
private ParameterAutowireUtils() {
}
public static boolean isAutowirable(Parameter parameter) {
return ApplicationContext.class.isAssignableFrom(parameter.getType()) || hasAnnotation(parameter, Autowired.class) || hasAnnotation(parameter, Qualifier.class) || hasAnnotation(parameter, Value.class);
}
public static Object resolveDependency(Parameter parameter, Class<?> containingClass, ApplicationContext applicationContext) {
boolean required = findMergedAnnotation(parameter, Autowired.class).map(Autowired::required)
.orElse(true);
MethodParameter methodParameter = (parameter.getDeclaringExecutable() instanceof Method ? MethodParameterFactory.createSynthesizingMethodParameter(parameter) : MethodParameterFactory.createMethodParameter(parameter));
DependencyDescriptor descriptor = new DependencyDescriptor(methodParameter, required);
descriptor.setContainingClass(containingClass);
return applicationContext.getAutowireCapableBeanFactory()
.resolveDependency(descriptor, null);
}
private static <A extends Annotation> Optional<A> findMergedAnnotation(AnnotatedElement element, Class<A> annotationType) {
return Optional.ofNullable(AnnotatedElementUtils.findMergedAnnotation(element, annotationType));
}
}
@@ -0,0 +1,94 @@
package com.baeldung.jupiter;
import java.lang.reflect.Constructor;
import java.lang.reflect.Executable;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import org.junit.jupiter.api.extension.AfterAllCallback;
import org.junit.jupiter.api.extension.AfterEachCallback;
import org.junit.jupiter.api.extension.BeforeAllCallback;
import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.ParameterContext;
import org.junit.jupiter.api.extension.ParameterResolutionException;
import org.junit.jupiter.api.extension.ParameterResolver;
import org.junit.jupiter.api.extension.TestInstancePostProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.test.context.TestContextManager;
import org.springframework.util.Assert;
public class SpringExtension implements BeforeAllCallback, AfterAllCallback, TestInstancePostProcessor, BeforeEachCallback, AfterEachCallback, ParameterResolver {
private static final ExtensionContext.Namespace namespace = ExtensionContext.Namespace.create(SpringExtension.class);
@Override
public void beforeAll(ExtensionContext context) throws Exception {
getTestContextManager(context).beforeTestClass();
}
@Override
public void afterAll(ExtensionContext context) throws Exception {
try {
getTestContextManager(context).afterTestClass();
} finally {
context.getStore(namespace)
.remove(context.getTestClass()
.get());
}
}
@Override
public void postProcessTestInstance(Object testInstance, ExtensionContext context) throws Exception {
getTestContextManager(context).prepareTestInstance(testInstance);
}
@Override
public void beforeEach(ExtensionContext context) throws Exception {
Object testInstance = context.getTestInstance();
Method testMethod = context.getTestMethod()
.get();
getTestContextManager(context).beforeTestMethod(testInstance, testMethod);
}
@Override
public void afterEach(ExtensionContext context) throws Exception {
Object testInstance = context.getTestInstance();
Method testMethod = context.getTestMethod()
.get();
Throwable testException = context.getExecutionException()
.orElse(null);
getTestContextManager(context).afterTestMethod(testInstance, testMethod, testException);
}
@Override
public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
Parameter parameter = parameterContext.getParameter();
Executable executable = parameter.getDeclaringExecutable();
return ((executable instanceof Constructor) && AnnotatedElementUtils.hasAnnotation(executable, Autowired.class)) || ParameterAutowireUtils.isAutowirable(parameter);
}
@Override
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
Parameter parameter = parameterContext.getParameter();
Class<?> testClass = extensionContext.getTestClass()
.get();
ApplicationContext applicationContext = getApplicationContext(extensionContext);
return ParameterAutowireUtils.resolveDependency(parameter, testClass, applicationContext);
}
private ApplicationContext getApplicationContext(ExtensionContext context) {
return getTestContextManager(context).getTestContext()
.getApplicationContext();
}
private TestContextManager getTestContextManager(ExtensionContext context) {
Assert.notNull(context, "ExtensionContext must not be null");
Class<?> testClass = context.getTestClass()
.get();
ExtensionContext.Store store = context.getStore(namespace);
return store.getOrComputeIfAbsent(testClass, TestContextManager::new, TestContextManager.class);
}
}
@@ -0,0 +1,39 @@
package com.baeldung.jupiter;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.annotation.AliasFor;
import org.springframework.test.context.ContextConfiguration;
import java.lang.annotation.*;
@ExtendWith(SpringExtension.class)
@ContextConfiguration
@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface SpringJUnit5Config {
@AliasFor(annotation = ContextConfiguration.class, attribute = "classes")
Class<?>[] value() default {};
@AliasFor(annotation = ContextConfiguration.class)
Class<?>[] classes() default {};
@AliasFor(annotation = ContextConfiguration.class)
String[] locations() default {};
@AliasFor(annotation = ContextConfiguration.class)
Class<? extends ApplicationContextInitializer<? extends ConfigurableApplicationContext>>[] initializers() default {};
@AliasFor(annotation = ContextConfiguration.class)
boolean inheritLocations() default true;
@AliasFor(annotation = ContextConfiguration.class)
boolean inheritInitializers() default true;
@AliasFor(annotation = ContextConfiguration.class)
String name() default "";
}
@@ -0,0 +1,28 @@
package com.baeldung.jupiter;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Task {
private final String name;
private final int id;
public Task(@JsonProperty("name") String name, @JsonProperty("id") int id) {
this.name = name;
this.id = id;
}
public String getName() {
return this.name;
}
public int getId() {
return this.id;
}
@Override
public String toString() {
return "Task{" + "name='" + name + '\'' + ", id=" + id + '}';
}
}
@@ -0,0 +1,19 @@
package com.baeldung.jupiter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
@Configuration
public class TestConfig {
@Bean
static PropertySourcesPlaceholderConfigurer placeholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
@Bean
Task taskName() {
return new Task("taskName", 1);
}
}
@@ -0,0 +1,27 @@
package com.baeldung.persistence;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import java.util.stream.IntStream;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.baeldung.web.Foo;
@Component
public class DataSetupBean implements InitializingBean {
@Autowired
private FooRepository repo;
//
@Override
public void afterPropertiesSet() throws Exception {
IntStream.range(1, 20)
.forEach(i -> repo.save(new Foo(randomAlphabetic(8))));
}
}
@@ -0,0 +1,9 @@
package com.baeldung.persistence;
import com.baeldung.web.Foo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
public interface FooRepository extends JpaRepository<Foo, Long>, JpaSpecificationExecutor<Foo> {
}
@@ -0,0 +1,61 @@
package com.baeldung.restdocs;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
import java.util.ArrayList;
import java.util.List;
import javax.validation.Valid;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/crud")
public class CRUDController {
@GetMapping
public List<CrudInput> read(@RequestBody @Valid CrudInput crudInput) {
List<CrudInput> returnList = new ArrayList<>();
returnList.add(crudInput);
return returnList;
}
@ResponseStatus(HttpStatus.CREATED)
@PostMapping
public HttpHeaders save(@RequestBody @Valid CrudInput crudInput) {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setLocation(linkTo(CRUDController.class).slash(crudInput.getId()).toUri());
return httpHeaders;
}
@DeleteMapping("/{id}")
@ResponseStatus(HttpStatus.OK)
HttpHeaders delete(@PathVariable("id") long id) {
return new HttpHeaders();
}
@PutMapping("/{id}")
@ResponseStatus(HttpStatus.ACCEPTED)
void put(@PathVariable("id") long id, @RequestBody CrudInput crudInput) {
}
@PatchMapping("/{id}")
public List<CrudInput> patch(@PathVariable("id") long id, @RequestBody CrudInput crudInput) {
List<CrudInput> returnList = new ArrayList<CrudInput>();
crudInput.setId(id);
returnList.add(crudInput);
return returnList;
}
}
@@ -0,0 +1,66 @@
package com.baeldung.restdocs;
import java.net.URI;
import java.util.Collections;
import java.util.List;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
public class CrudInput {
@NotNull
private long id;
@NotBlank
private String title;
private String body;
private List<URI> tagUris;
@JsonCreator
public CrudInput(@JsonProperty("id") long id, @JsonProperty("title") String title, @JsonProperty("body") String body, @JsonProperty("tags") List<URI> tagUris) {
this.id=id;
this.title = title;
this.body = body;
this.tagUris = tagUris == null ? Collections.<URI> emptyList() : tagUris;
}
public String getTitle() {
return title;
}
public String getBody() {
return body;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public void setTitle(String title) {
this.title = title;
}
public void setBody(String body) {
this.body = body;
}
public void setTagUris(List<URI> tagUris) {
this.tagUris = tagUris;
}
@JsonProperty("tags")
public List<URI> getTagUris() {
return this.tagUris;
}
}
@@ -0,0 +1,21 @@
package com.baeldung.restdocs;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
import org.springframework.hateoas.ResourceSupport;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/")
public class IndexController {
@GetMapping
public ResourceSupport index() {
ResourceSupport index = new ResourceSupport();
index.add(linkTo(CRUDController.class).withRel("crud"));
return index;
}
}
@@ -0,0 +1,13 @@
package com.baeldung.restdocs;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
@SpringBootApplication(exclude = SecurityAutoConfiguration.class)
public class SpringRestDocsApplication {
public static void main(String[] args) {
SpringApplication.run(SpringRestDocsApplication.class, args);
}
}
@@ -0,0 +1,84 @@
package com.baeldung.web;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Foo {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
public Foo() {
super();
}
public Foo(final String name) {
super();
this.name = name;
}
public Foo(final long id, final String name) {
super();
this.id = id;
this.name = name;
}
// API
public long getId() {
return id;
}
public void setId(final long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
//
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Foo other = (Foo) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
@Override
public String toString() {
return "Foo [name=" + name + "]";
}
}
@@ -0,0 +1,59 @@
package com.baeldung.web;
import com.baeldung.persistence.FooRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpStatus;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.PostConstruct;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import java.util.List;
@RestController("/foos")
public class FooController {
@PostConstruct
public void init(){
System.out.println("test");
}
@Autowired
private FooRepository repo;
// API - read
@GetMapping("/foos/{id}")
@ResponseBody
@Validated
public Foo findById(@PathVariable @Min(0) final long id) {
return repo.findById(id)
.orElse(null);
}
@GetMapping
@ResponseBody
public List<Foo> findAll() {
return repo.findAll();
}
@GetMapping(params = { "page", "size" })
@ResponseBody
@Validated
public List<Foo> findPaginated(@RequestParam("page") @Min(0) final int page, @Max(100) @RequestParam("size") final int size) {
return repo.findAll(PageRequest.of(page, size))
.getContent();
}
// API - write
@PutMapping("/foos/{id}")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public Foo update(@PathVariable("id") final String id, @RequestBody final Foo foo) {
return foo;
}
}