Initial Changes for Creating new Module-2

This commit is contained in:
Amitabh Tiwari
2022-07-22 16:38:10 +05:30
parent 3574fa6fa2
commit 911620c676
19 changed files with 499 additions and 0 deletions
@@ -0,0 +1,16 @@
package com.baeldung.cloud.openfeign;
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,21 @@
package com.baeldung.cloud.openfeign.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import feign.Logger;
import feign.codec.ErrorDecoder;
@Configuration
public class ClientConfiguration {
@Bean
public Logger.Level feignLoggerLevel() {
return Logger.Level.FULL;
}
@Bean
public ErrorDecoder errorDecoder() {
return new ErrorDecoder.Default();
}
}
@@ -0,0 +1,21 @@
package com.baeldung.cloud.openfeign.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.cloud.openfeign.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.cloud.openfeign.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,28 @@
package com.baeldung.cloud.openfeign.fileupload.config;
import org.springframework.beans.factory.ObjectFactory;
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 ObjectFactory<HttpMessageConverters>() {
@Override
public HttpMessageConverters getObject() {
return new HttpMessageConverters(new RestTemplate().getMessageConverters());
}
}));
}
@Bean
public ErrorDecoder errorDecoder() {
return new RetreiveMessageErrorDecoder();
}
}
@@ -0,0 +1,35 @@
package com.baeldung.cloud.openfeign.fileupload.config;
import java.io.IOException;
import java.io.InputStream;
import com.baeldung.cloud.openfeign.exception.BadRequestException;
import com.baeldung.cloud.openfeign.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 = null;
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,34 @@
package com.baeldung.cloud.openfeign.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.cloud.openfeign.exception.NotFoundException;
import com.baeldung.cloud.openfeign.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) throws NotFoundException {
return service.uploadFileWithCause(file);
}
}
@@ -0,0 +1,15 @@
package com.baeldung.cloud.openfeign.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.cloud.openfeign.fileupload.config.FeignSupportConfig;
@FeignClient(name = "file", url = "http://localhost:8081", configuration = FeignSupportConfig.class, fallbackFactory = FileUploadClientFallbackFactory.class)
public interface FileUploadClient {
@PostMapping(value = "/upload-file", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
String fileUpload(@RequestPart(value = "file") MultipartFile file);
}
@@ -0,0 +1,30 @@
package com.baeldung.cloud.openfeign.fileupload.service;
import org.springframework.cloud.openfeign.FallbackFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import com.baeldung.cloud.openfeign.exception.BadRequestException;
import com.baeldung.cloud.openfeign.exception.NotFoundException;
@Component
public class FileUploadClientFallbackFactory implements FallbackFactory<FileUploadClient> {
@Override
public FileUploadClient create(Throwable cause) {
return new FileUploadClient() {
@Override
public String fileUpload(MultipartFile file) {
if (cause instanceof BadRequestException) {
return "Bad Request!!!";
}
if (cause instanceof NotFoundException) {
return "Not Found!!!";
}
if (cause instanceof Exception) {
return "Exception!!!";
}
return "Successfully Uploaded file!!!";
}
};
}
}
@@ -0,0 +1,18 @@
package com.baeldung.cloud.openfeign.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.cloud.openfeign.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.cloud.openfeign.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,36 @@
package com.baeldung.cloud.openfeign.fileupload.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.baeldung.cloud.openfeign.exception.NotFoundException;
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;
@Autowired
private FileUploadClient fileUploadClient;
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 uploadFileWithCause(MultipartFile file) throws NotFoundException {
return fileUploadClient.fileUpload(file);
}
}
@@ -0,0 +1,10 @@
server.port=8085
spring.main.allow-bean-definition-overriding=true
spring.application.name= openfeign
logging.level.com.baeldung.cloud.openfeign.client: DEBUG
feign.hystrix.enabled=true
spring.security.oauth2.client.registration.keycloak.authorization-grant-type=client_credentials
spring.security.oauth2.client.registration.keycloak.client-id=payment-app
spring.security.oauth2.client.registration.keycloak.client-secret=863e9de4-33d4-4471-b35e-f8d2434385bb
spring.security.oauth2.client.provider.keycloak.token-uri=http://localhost:8083/auth/realms/master/protocol/openid-connect/token
@@ -0,0 +1,50 @@
package com.baeldung.cloud.openfeign;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.commons.io.IOUtils;
import org.junit.Assert;
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.mock.web.MockMultipartFile;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.multipart.MultipartFile;
import com.baeldung.cloud.openfeign.fileupload.service.UploadService;
@RunWith(SpringRunner.class)
@SpringBootTest
public class OpenFeignFileUploadLiveTest {
@Autowired
private UploadService uploadService;
private static String FILE_NAME = "fileupload.txt";
@Test
public void whenFeignBuilder_thenFileUploadSuccess() throws IOException {
ClassLoader classloader = Thread.currentThread().getContextClassLoader();
File file = new File(classloader.getResource(FILE_NAME).getFile());
Assert.assertTrue(file.exists());
FileInputStream input = new FileInputStream(file);
MultipartFile multipartFile = new MockMultipartFile("file", file.getName(), "text/plain",
IOUtils.toByteArray(input));
Assert.assertTrue(uploadService.uploadFileWithManualClient(multipartFile));
}
@Test
public void whenAnnotatedFeignClient_thenFileUploadSuccess() throws IOException {
ClassLoader classloader = Thread.currentThread().getContextClassLoader();
File file = new File(classloader.getResource(FILE_NAME).getFile());
Assert.assertTrue(file.exists());
FileInputStream input = new FileInputStream(file);
MultipartFile multipartFile = new MockMultipartFile("file", file.getName(), "text/plain",
IOUtils.toByteArray(input));
String uploadFile = uploadService.uploadFile(multipartFile);
Assert.assertNotNull(uploadFile);
}
}
@@ -0,0 +1,16 @@
package com.baeldung.cloud.openfeign;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ExampleApplication.class)
public class SpringContextTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}