JAVA-17818 Split or move spring-cloud-openfeign module (conti-2) (#13485)

Co-authored-by: timis1 <noreplay@yahoo.com>
This commit is contained in:
timis1
2023-02-20 18:18:26 +02:00
committed by GitHub
parent 639de9687e
commit 09382f545e
42 changed files with 269 additions and 140 deletions
@@ -0,0 +1,16 @@
package com.baeldung.core;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
@SpringBootApplication
@EnableFeignClients
public class ExampleApplication {
public static void main(String[] args) {
SpringApplication.run(ExampleApplication.class, args);
}
}
@@ -0,0 +1,13 @@
package com.baeldung.core.client;
import com.baeldung.core.model.Employee;
import feign.Headers;
import feign.Param;
import feign.RequestLine;
public interface EmployeeClient {
@RequestLine("GET /empployee/{id}?active={isActive}")
@Headers("Content-Type: application/json")
Employee getEmployee(@Param long id, @Param boolean isActive);
}
@@ -0,0 +1,13 @@
package com.baeldung.core.client;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import com.baeldung.core.config.FeignConfig;
@FeignClient(name = "user-client", url="https://jsonplaceholder.typicode.com", configuration = FeignConfig.class)
public interface UserClient {
@GetMapping(value = "/users")
String getUsers();
}
@@ -0,0 +1,13 @@
package com.baeldung.core.config;
import org.springframework.context.annotation.Bean;
import feign.Logger;
public class FeignConfig {
@Bean
Logger.Level feignLoggerLevel() {
return Logger.Level.FULL;
}
}
@@ -0,0 +1,24 @@
package com.baeldung.core.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.baeldung.core.client.EmployeeClient;
import com.baeldung.core.model.Employee;
import feign.Feign;
import feign.form.spring.SpringFormEncoder;
@RestController
public class EmployeeController {
private static final String HTTP_FILE_EMPLOYEE_URL = "http://localhost:8081";
@GetMapping("/employee/{id}")
public Employee getEmployee(@RequestParam("id") long id) {
EmployeeClient employeeResource = Feign.builder().encoder(new SpringFormEncoder())
.target(EmployeeClient.class, HTTP_FILE_EMPLOYEE_URL);
return employeeResource.getEmployee(id, true);
}
}
@@ -0,0 +1,17 @@
package com.baeldung.core.customizederrorhandling.client;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.baeldung.core.customizederrorhandling.config.FeignConfig;
import com.baeldung.core.defaulterrorhandling.model.Product;
@FeignClient(name = "product-client-2", url = "http://localhost:8081/product/", configuration = FeignConfig.class)
public interface ProductClient {
@RequestMapping(value = "{id}", method = RequestMethod.GET)
Product getProduct(@PathVariable(value = "id") String id);
}
@@ -0,0 +1,25 @@
package com.baeldung.core.customizederrorhandling.config;
import com.baeldung.core.customizederrorhandling.exception.ProductNotFoundException;
import com.baeldung.core.customizederrorhandling.exception.ProductServiceNotAvailableException;
import com.baeldung.core.exception.BadRequestException;
import feign.Response;
import feign.codec.ErrorDecoder;
public class CustomErrorDecoder implements ErrorDecoder {
@Override
public Exception decode(String methodKey, Response response) {
switch (response.status()){
case 400:
return new BadRequestException();
case 404:
return new ProductNotFoundException("Product not found");
case 503:
return new ProductServiceNotAvailableException("Product Api is unavailable");
default:
return new Exception("Exception while getting product details");
}
}
}
@@ -0,0 +1,19 @@
package com.baeldung.core.customizederrorhandling.config;
import org.springframework.context.annotation.Bean;
import feign.Logger;
import feign.codec.ErrorDecoder;
public class FeignConfig {
@Bean
Logger.Level feignLoggerLevel() {
return Logger.Level.FULL;
}
@Bean
ErrorDecoder errorDecoder() {
return new CustomErrorDecoder();
}
}
@@ -0,0 +1,28 @@
package com.baeldung.core.customizederrorhandling.controller;
import org.springframework.beans.factory.annotation.Autowired;
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.RestController;
import com.baeldung.core.customizederrorhandling.client.ProductClient;
import com.baeldung.core.defaulterrorhandling.model.Product;
@RestController("product_controller2")
@RequestMapping(value = "myapp2")
public class ProductController {
private final ProductClient productClient;
@Autowired
public ProductController(ProductClient productClient) {
this.productClient = productClient;
}
@GetMapping("/product/{id}")
public Product getProduct(@PathVariable String id) {
return productClient.getProduct(id);
}
}
@@ -0,0 +1,55 @@
package com.baeldung.core.customizederrorhandling.exception;
import java.util.Date;
import org.springframework.http.HttpStatus;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonProperty;
public class ErrorResponse {
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy hh:mm:ss")
private Date timestamp;
@JsonProperty(value = "code")
private int code;
@JsonProperty(value = "status")
private String status;
@JsonProperty(value = "message")
private String message;
@JsonProperty(value = "details")
private String details;
public ErrorResponse() {
}
public ErrorResponse(HttpStatus httpStatus, String message, String details) {
timestamp = new Date();
this.code = httpStatus.value();
this.status = httpStatus.name();
this.message = message;
this.details = details;
}
public Date getTimestamp() {
return timestamp;
}
public int getCode() {
return code;
}
public String getStatus() {
return status;
}
public String getMessage() {
return message;
}
public String getDetails() {
return details;
}
}
@@ -0,0 +1,39 @@
package com.baeldung.core.customizederrorhandling.exception;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
@RestControllerAdvice
public class ProductExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler({ProductServiceNotAvailableException.class})
public ResponseEntity<ErrorResponse> handleProductServiceNotAvailableException(ProductServiceNotAvailableException exception, WebRequest request) {
return new ResponseEntity<>(new ErrorResponse(
HttpStatus.INTERNAL_SERVER_ERROR,
exception.getMessage(),
request.getDescription(false)),
HttpStatus.INTERNAL_SERVER_ERROR);
}
@ExceptionHandler({ProductNotFoundException.class})
public ResponseEntity<ErrorResponse> handleProductNotFoundException(ProductNotFoundException exception, WebRequest request) {
return new ResponseEntity<>(new ErrorResponse(
HttpStatus.NOT_FOUND,
exception.getMessage(),
request.getDescription(false)),
HttpStatus.NOT_FOUND);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorResponse> handleGenericException(Exception exception, WebRequest request) {
return new ResponseEntity<>(new ErrorResponse(
HttpStatus.INTERNAL_SERVER_ERROR,
exception.getMessage(),
request.getDescription(false)),
HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@@ -0,0 +1,8 @@
package com.baeldung.core.customizederrorhandling.exception;
public class ProductNotFoundException extends RuntimeException {
public ProductNotFoundException(String message) {
super(message);
}
}
@@ -0,0 +1,8 @@
package com.baeldung.core.customizederrorhandling.exception;
public class ProductServiceNotAvailableException extends RuntimeException {
public ProductServiceNotAvailableException(String message) {
super(message);
}
}
@@ -0,0 +1,17 @@
package com.baeldung.core.defaulterrorhandling.client;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.baeldung.core.defaulterrorhandling.config.FeignConfig;
import com.baeldung.core.defaulterrorhandling.model.Product;
@FeignClient(name = "product-client", url = "http://localhost:8084/product/", configuration = FeignConfig.class)
public interface ProductClient {
@RequestMapping(value = "{id}", method = RequestMethod.GET)
Product getProduct(@PathVariable(value = "id") String id);
}
@@ -0,0 +1,13 @@
package com.baeldung.core.defaulterrorhandling.config;
import org.springframework.context.annotation.Bean;
import feign.Logger;
public class FeignConfig {
@Bean
Logger.Level feignLoggerLevel() {
return Logger.Level.FULL;
}
}
@@ -0,0 +1,27 @@
package com.baeldung.core.defaulterrorhandling.controller;
import org.springframework.beans.factory.annotation.Autowired;
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.RestController;
import com.baeldung.core.defaulterrorhandling.client.ProductClient;
import com.baeldung.core.defaulterrorhandling.model.Product;
@RestController("product_controller1")
@RequestMapping(value ="myapp1")
public class ProductController {
private final ProductClient productClient;
@Autowired
public ProductController(ProductClient productClient) {
this.productClient = productClient;
}
@GetMapping("/product/{id}")
public Product getProduct(@PathVariable String id) {
return productClient.getProduct(id);
}
}
@@ -0,0 +1,24 @@
package com.baeldung.core.defaulterrorhandling.model;
public class Product {
private String id;
private String productName;
private double price;
public String getId() {
return id;
}
public String getProductName() {
return productName;
}
public double getPrice() {
return price;
}
}
@@ -0,0 +1,21 @@
package com.baeldung.core.exception;
public class BadRequestException extends Exception {
public BadRequestException() {
}
public BadRequestException(String message) {
super(message);
}
public BadRequestException(Throwable cause) {
super(cause);
}
@Override
public String toString() {
return "BadRequestException: "+getMessage();
}
}
@@ -0,0 +1,18 @@
package com.baeldung.core.exception;
public class NotFoundException extends Exception {
public NotFoundException(String message) {
super(message);
}
public NotFoundException(Throwable cause) {
super(cause);
}
@Override
public String toString() {
return "NotFoundException: " + getMessage();
}
}
@@ -0,0 +1,55 @@
package com.baeldung.core.fileupload.config;
public class ExceptionMessage {
private String timestamp;
private int status;
private String error;
private String message;
private String path;
public String getTimestamp() {
return timestamp;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
@Override
public String toString() {
return "ExceptionMessage [timestamp=" + timestamp + ", status=" + status + ", error=" + error + ", message=" + message + ", path=" + path + "]";
}
}
@@ -0,0 +1,22 @@
package com.baeldung.core.fileupload.config;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.SpringEncoder;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
import feign.codec.Encoder;
import feign.codec.ErrorDecoder;
import feign.form.spring.SpringFormEncoder;
public class FeignSupportConfig {
@Bean
public Encoder multipartFormEncoder() {
return new SpringFormEncoder(new SpringEncoder(() -> new HttpMessageConverters(new RestTemplate().getMessageConverters())));
}
@Bean
public ErrorDecoder errorDecoder() {
return new RetreiveMessageErrorDecoder();
}
}
@@ -0,0 +1,35 @@
package com.baeldung.core.fileupload.config;
import java.io.IOException;
import java.io.InputStream;
import com.baeldung.core.exception.BadRequestException;
import com.baeldung.core.exception.NotFoundException;
import com.fasterxml.jackson.databind.ObjectMapper;
import feign.Response;
import feign.codec.ErrorDecoder;
public class RetreiveMessageErrorDecoder implements ErrorDecoder {
private final ErrorDecoder errorDecoder = new Default();
@Override
public Exception decode(String methodKey, Response response) {
ExceptionMessage message;
try (InputStream bodyIs = response.body()
.asInputStream()) {
ObjectMapper mapper = new ObjectMapper();
message = mapper.readValue(bodyIs, ExceptionMessage.class);
} catch (IOException e) {
return new Exception(e.getMessage());
}
switch (response.status()) {
case 400:
return new BadRequestException(message.getMessage() != null ? message.getMessage() : "Bad Request");
case 404:
return new NotFoundException(message.getMessage() != null ? message.getMessage() : "Not found");
default:
return errorDecoder.decode(methodKey, response);
}
}
}
@@ -0,0 +1,33 @@
package com.baeldung.core.fileupload.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.baeldung.core.fileupload.service.UploadService;
@RestController
public class FileController {
@Autowired
private UploadService service;
@PostMapping(value = "/upload")
public String handleFileUpload(@RequestPart(value = "file") MultipartFile file) {
return service.uploadFile(file);
}
@PostMapping(value = "/upload-mannual-client")
public boolean handleFileUploadWithManualClient(
@RequestPart(value = "file") MultipartFile file) {
return service.uploadFileWithManualClient(file);
}
@PostMapping(value = "/upload-error")
public String handleFileUploadError(@RequestPart(value = "file") MultipartFile file) {
return service.uploadFile(file);
}
}
@@ -0,0 +1,18 @@
package com.baeldung.core.fileupload.service;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;
import com.baeldung.core.fileupload.config.FeignSupportConfig;
@FeignClient(name = "file", url = "http://localhost:8081", configuration = FeignSupportConfig.class)
public interface UploadClient {
@PostMapping(value = "/upload-file", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
String fileUpload(@RequestPart(value = "file") MultipartFile file);
@PostMapping(value = "/upload-file-error", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
String fileUploadError(@RequestPart(value = "file") MultipartFile file);
}
@@ -0,0 +1,16 @@
package com.baeldung.core.fileupload.service;
import org.springframework.web.multipart.MultipartFile;
import feign.Headers;
import feign.Param;
import feign.RequestLine;
import feign.Response;
public interface UploadResource {
@RequestLine("POST /upload-file")
@Headers("Content-Type: multipart/form-data")
Response uploadFile(@Param("file") MultipartFile file);
}
@@ -0,0 +1,32 @@
package com.baeldung.core.fileupload.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import feign.Feign;
import feign.Response;
import feign.form.spring.SpringFormEncoder;
@Service
public class UploadService {
private static final String HTTP_FILE_UPLOAD_URL = "http://localhost:8081";
@Autowired
private UploadClient client;
public boolean uploadFileWithManualClient(MultipartFile file) {
UploadResource fileUploadResource = Feign.builder().encoder(new SpringFormEncoder())
.target(UploadResource.class, HTTP_FILE_UPLOAD_URL);
Response response = fileUploadResource.uploadFile(file);
return response.status() == 200;
}
public String uploadFile(MultipartFile file) {
return client.fileUpload(file);
}
public String uploadFileError(MultipartFile file) {
return client.fileUpload(file);
}
}
@@ -0,0 +1,15 @@
package com.baeldung.core.model;
public class Employee {
private Long id;
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
@@ -5,3 +5,5 @@ ws.port.type.name=UsersPort
ws.target.namespace=http://www.baeldung.com/springbootsoap/feignclient
ws.location.uri=http://localhost:${server.port}/ws/users/
debug=false
logging.level.com.baeldung.core=DEBUG
-14
View File
@@ -1,14 +0,0 @@
<?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>
<logger name="feign.Logger" level="DEBUG" />
</appender>
<root level="DEBUG">
<appender-ref ref="STDOUT" />
</root>
</configuration>
@@ -0,0 +1,45 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<property name="LOGS" value="./logs" />
<appender name="Console"
class="ch.qos.logback.core.ConsoleAppender">
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</layout>
</appender>
<appender name="RollingFile"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${LOGS}/spring-boot-logger.log</file>
<encoder
class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<Pattern>%d %p %C{1.} [%t] %m%n</Pattern>
</encoder>
<rollingPolicy
class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- rollover daily and when the file reaches 10 MegaBytes -->
<fileNamePattern>${LOGS}/archived/spring-boot-logger-%d{yyyy-MM-dd}.%i.log
</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy
class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>10MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
</appender>
<!-- LOG everything at INFO level -->
<root level="info">
<appender-ref ref="RollingFile" />
<appender-ref ref="Console" />
</root>
<!-- LOG "com.baeldung*" at TRACE level -->
<logger name="com.baeldung" level="trace" additivity="false">
<appender-ref ref="RollingFile" />
<appender-ref ref="Console" />
</logger>
</configuration>