BAEL-20869 Move remaining spring boot modules

This commit is contained in:
mikr
2020-02-02 20:44:54 +01:00
parent 80a2cfec65
commit 56a9403564
704 changed files with 1303 additions and 1501 deletions

View File

@@ -0,0 +1,74 @@
package com.baeldung.springbootmvc;
import static org.springframework.web.servlet.function.RouterFunctions.route;
import static org.springframework.web.servlet.function.ServerResponse.notFound;
import static org.springframework.web.servlet.function.ServerResponse.status;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.function.RequestPredicates;
import org.springframework.web.servlet.function.RouterFunction;
import org.springframework.web.servlet.function.ServerResponse;
import com.baeldung.springbootmvc.ctrl.ProductController;
import com.baeldung.springbootmvc.svc.ProductService;
@SpringBootApplication
public class SpringBootMvcFnApplication {
private static final Logger LOG = LoggerFactory.getLogger(SpringBootMvcFnApplication.class);
public static void main(String[] args) {
SpringApplication.run(SpringBootMvcFnApplication.class, args);
}
@Bean
RouterFunction<ServerResponse> productListing(ProductController pc, ProductService ps) {
return pc.productListing(ps);
}
@Bean
RouterFunction<ServerResponse> allApplicationRoutes(ProductController pc, ProductService ps) {
return route().add(pc.remainingProductRoutes(ps))
.before(req -> {
LOG.info("Found a route which matches " + req.uri()
.getPath());
return req;
})
.after((req, res) -> {
if (res.statusCode() == HttpStatus.OK) {
LOG.info("Finished processing request " + req.uri()
.getPath());
} else {
LOG.info("There was an error while processing request" + req.uri());
}
return res;
})
.onError(Throwable.class, (e, res) -> {
LOG.error("Fatal exception has occurred", e);
return status(HttpStatus.INTERNAL_SERVER_ERROR).build();
})
.build()
.and(route(RequestPredicates.all(), req -> notFound().build()));
}
public static class Error {
private String errorMessage;
public Error(String message) {
this.errorMessage = message;
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
}
}

View File

@@ -0,0 +1,59 @@
package com.baeldung.springbootmvc.ctrl;
import static org.springframework.web.servlet.function.RouterFunctions.route;
import static org.springframework.web.servlet.function.ServerResponse.ok;
import static org.springframework.web.servlet.function.ServerResponse.status;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.function.EntityResponse;
import org.springframework.web.servlet.function.RequestPredicates;
import org.springframework.web.servlet.function.RouterFunction;
import org.springframework.web.servlet.function.ServerRequest;
import org.springframework.web.servlet.function.ServerResponse;
import com.baeldung.springbootmvc.SpringBootMvcFnApplication.Error;
import com.baeldung.springbootmvc.model.Product;
import com.baeldung.springbootmvc.svc.ProductService;
@Component
public class ProductController {
public RouterFunction<ServerResponse> productListing(ProductService ps) {
return route().GET("/product", req -> ok().body(ps.findAll()))
.build();
}
public RouterFunction<ServerResponse> productSearch(ProductService ps) {
return route().nest(RequestPredicates.path("/product"), builder -> {
builder.GET("/name/{name}", req -> ok().body(ps.findByName(req.pathVariable("name"))))
.GET("/id/{id}", req -> ok().body(ps.findById(Integer.parseInt(req.pathVariable("id")))));
})
.onError(ProductService.ItemNotFoundException.class, (e, req) -> EntityResponse.fromObject(new Error(e.getMessage()))
.status(HttpStatus.NOT_FOUND)
.build())
.build();
}
public RouterFunction<ServerResponse> adminFunctions(ProductService ps) {
return route().POST("/product", req -> ok().body(ps.save(req.body(Product.class))))
.filter((req, next) -> authenticate(req) ? next.handle(req) : status(HttpStatus.UNAUTHORIZED).build())
.onError(IllegalArgumentException.class, (e, req) -> EntityResponse.fromObject(new Error(e.getMessage()))
.status(HttpStatus.BAD_REQUEST)
.build())
.build();
}
public RouterFunction<ServerResponse> remainingProductRoutes(ProductService ps) {
return route().add(productSearch(ps))
.add(adminFunctions(ps))
.build();
}
private boolean authenticate(ServerRequest req) {
return Boolean.TRUE;
}
}

View File

@@ -0,0 +1,72 @@
package com.baeldung.springbootmvc.model;
public class Product {
private String name;
private double price;
private int id;
public Product(String name, double price, int id) {
super();
this.name = name;
this.price = price;
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
result = prime * result + ((name == null) ? 0 : name.hashCode());
long temp;
temp = Double.doubleToLongBits(price);
result = prime * result + (int) (temp ^ (temp >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Product other = (Product) obj;
if (id != other.id)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (Double.doubleToLongBits(price) != Double.doubleToLongBits(other.price))
return false;
return true;
}
}

View File

@@ -0,0 +1,63 @@
package com.baeldung.springbootmvc.svc;
import java.util.HashSet;
import java.util.Set;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import com.baeldung.springbootmvc.model.Product;
@Service
public class ProductService {
private final Set<Product> products = new HashSet<>();
{
products.add(new Product("Book", 23.90, 1));
products.add(new Product("Pen", 44.34, 2));
}
public Product findById(int id) {
return products.stream()
.filter(obj -> obj.getId() == id)
.findFirst()
.orElseThrow(() -> new ItemNotFoundException("Product not found"));
}
public Product findByName(String name) {
return products.stream()
.filter(obj -> obj.getName()
.equalsIgnoreCase(name))
.findFirst()
.orElseThrow(() -> new ItemNotFoundException("Product not found"));
}
public Set<Product> findAll() {
return products;
}
public Product save(Product product) {
if (StringUtils.isEmpty(product.getName()) || product.getPrice() == 0.0) {
throw new IllegalArgumentException();
}
int newId = products.stream()
.mapToInt(Product::getId)
.max()
.getAsInt() + 1;
product.setId(newId);
products.add(product);
return product;
}
public static class ItemNotFoundException extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = 1L;
public ItemNotFoundException(String msg) {
super(msg);
}
}
}

View File

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

View File

@@ -0,0 +1,34 @@
package com.baeldung.swagger2boot.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;
@Configuration
@EnableSwagger2WebMvc
public class Swagger2Config {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2).select()
.apis(RequestHandlerSelectors.basePackage("com.baeldung.swagger2boot.controller"))
.paths(PathSelectors.regex("/.*"))
.build()
.apiInfo(apiEndPointsInfo());
}
private ApiInfo apiEndPointsInfo() {
return new ApiInfoBuilder().title("Swagger Array")
.description("This is a sample Swagger description for an Array server")
.license("Apache 2.0")
.licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html")
.version("1.0.0")
.build();
}
}

View File

@@ -0,0 +1,35 @@
package com.baeldung.swagger2boot.controller;
import static org.apache.commons.lang3.RandomStringUtils.randomNumeric;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import com.baeldung.swagger2boot.model.Foo;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
@Controller
public class FooController {
public FooController() {
super();
}
// API - write
@RequestMapping(method = RequestMethod.POST, value = "/foos")
@ResponseStatus(HttpStatus.CREATED)
@ResponseBody
@ApiImplicitParams({ @ApiImplicitParam(name = "foo", value = "List of strings", paramType = "body", dataType = "Foo") })
public Foo create(@RequestBody final Foo foo) {
foo.setId(Long.parseLong(randomNumeric(2)));
return foo;
}
}

View File

@@ -0,0 +1,44 @@
package com.baeldung.swagger2boot.model;
import java.util.List;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ApiModel
public class Foo {
private long id;
@ApiModelProperty(name = "name", dataType = "List", example = "[\"str1\", \"str2\", \"str3\"]")
private List<String> name;
public Foo() {
super();
}
public Foo(final long id, final List<String> name) {
super();
this.id = id;
this.name = name;
}
//
public long getId() {
return id;
}
public void setId(final long id) {
this.id = id;
}
public List<String> getName() {
return name;
}
public void setName(final List<String> name) {
this.name = name;
}
}

View File

@@ -0,0 +1 @@
spring.main.allow-bean-definition-overriding=true

View File

@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@@ -0,0 +1,33 @@
swagger: "2.0"
info:
description: "This is a sample Swagger description for an Array server"
version: "1.0.0"
title: "Swagger Array"
license:
name: "Apache 2.0"
url: "http://www.apache.org/licenses/LICENSE-2.0.html"
basePath: "/localhost:8080/"
tags:
- name: "foo-controller"
description: "Foo controller"
paths:
/foos:
post:
tags:
- "foo-controller"
summary: "create"
description: ""
parameters:
- in: body
description: ""
required: true
name: name
schema:
type: array
items:
type: string
example: ["str1", "str2", "str3"]
responses:
default:
description: OK