Implements Better Error Handling in Micro Services

This commit is contained in:
2023-10-24 01:01:37 -03:00
parent 117986c466
commit 8cc2dcddf7
3 changed files with 85 additions and 85 deletions

View File

@@ -155,9 +155,10 @@ public class AuthServiceImpl implements AuthService {
user.setProvider(Provider.LOCAL); user.setProvider(Provider.LOCAL);
UserDTO authenticatedUser = this.userService.saveUser(user); UserDTO authenticatedUser = this.userService.saveUser(user);
authenticatedUser.setProfilePictureUrl(
this.storageService.getFileUrl(authenticatedUser.getUsername(), "profile") var profilePicture = this.storageService.getFileUrl(authenticatedUser.getUsername(), "profile");
.getPresignedUrl() profilePicture.ifPresent(
storageServiceDownloadResponse -> authenticatedUser.setProfilePictureUrl(storageServiceDownloadResponse.getPresignedUrl())
); );
return this.generateUserWithTokens( return this.generateUserWithTokens(
@@ -169,9 +170,9 @@ public class AuthServiceImpl implements AuthService {
@Override @Override
public void loginUser(HttpServletRequest request, HttpServletResponse response, @Valid UserDTO user) throws IOException { public void loginUser(HttpServletRequest request, HttpServletResponse response, @Valid UserDTO user) throws IOException {
user.setProfilePictureUrl( var profilePicture = this.storageService.getFileUrl(user.getUsername(), "profile");
this.storageService.getFileUrl(user.getUsername(), "profile") profilePicture.ifPresent(
.getPresignedUrl() storageServiceDownloadResponse -> user.setProfilePictureUrl(storageServiceDownloadResponse.getPresignedUrl())
); );
AuthDTO authObject = this.generateUserWithTokens( AuthDTO authObject = this.generateUserWithTokens(
@@ -202,9 +203,10 @@ public class AuthServiceImpl implements AuthService {
DecodedJWT decodedJWT = verifier.verify(refreshToken); DecodedJWT decodedJWT = verifier.verify(refreshToken);
UserDTO user = this.userService.getUser(decodedJWT.getSubject()); UserDTO user = this.userService.getUser(decodedJWT.getSubject());
user.setProfilePictureUrl(
this.storageService.getFileUrl(user.getUsername(), "profile") var profilePicture = this.storageService.getFileUrl(user.getUsername(), "profile");
.getPresignedUrl() profilePicture.ifPresent(
storageServiceDownloadResponse -> user.setProfilePictureUrl(storageServiceDownloadResponse.getPresignedUrl())
); );
HttpSession httpSession = request.getSession(); HttpSession httpSession = request.getSession();

View File

@@ -8,6 +8,7 @@ import com.hideyoshi.backendportfolio.base.user.service.UserService;
import com.hideyoshi.backendportfolio.microservice.storageService.enums.FileTypeEnum; import com.hideyoshi.backendportfolio.microservice.storageService.enums.FileTypeEnum;
import com.hideyoshi.backendportfolio.microservice.storageService.model.StorageServiceUploadResponse; import com.hideyoshi.backendportfolio.microservice.storageService.model.StorageServiceUploadResponse;
import com.hideyoshi.backendportfolio.microservice.storageService.service.StorageService; import com.hideyoshi.backendportfolio.microservice.storageService.service.StorageService;
import com.hideyoshi.backendportfolio.util.exception.BadRequestException;
import com.hideyoshi.backendportfolio.util.guard.UserResourceGuard; import com.hideyoshi.backendportfolio.util.guard.UserResourceGuard;
import com.hideyoshi.backendportfolio.util.guard.UserResourceGuardEnum; import com.hideyoshi.backendportfolio.util.guard.UserResourceGuardEnum;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
@@ -95,7 +96,7 @@ public class UserController {
user.getUsername(), user.getUsername(),
"profile", "profile",
fileType fileType
); ).orElseThrow(() -> new BadRequestException("File not found"));
} }
@DeleteMapping("/profile-picture") @DeleteMapping("/profile-picture")

View File

@@ -1,6 +1,7 @@
package com.hideyoshi.backendportfolio.microservice.storageService.service; package com.hideyoshi.backendportfolio.microservice.storageService.service;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import com.hideyoshi.backendportfolio.microservice.storageService.config.StorageServiceConfig; import com.hideyoshi.backendportfolio.microservice.storageService.config.StorageServiceConfig;
import com.hideyoshi.backendportfolio.microservice.storageService.enums.FileTypeEnum; import com.hideyoshi.backendportfolio.microservice.storageService.enums.FileTypeEnum;
@@ -24,6 +25,7 @@ import java.io.UnsupportedEncodingException;
import java.net.URI; import java.net.URI;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.util.HashMap; import java.util.HashMap;
import java.util.Optional;
@Log4j2 @Log4j2
@Service @Service
@@ -40,49 +42,28 @@ public class StorageService {
private final String PARAMETER_FILE_TYPE = "file_type"; private final String PARAMETER_FILE_TYPE = "file_type";
private final String PARAMETER_KEY_STRING = "string_url"; public Optional<StorageServiceUploadResponse> getNewFileUrl(String username, String filePostfix, FileTypeEnum fileTypeEnum) {
public StorageServiceUploadResponse getNewFileUrl(String username, String filePostfix, FileTypeEnum fileTypeEnum) {
HashMap<String, String> values = new HashMap<>() {{ HashMap<String, String> values = new HashMap<>() {{
put(PARAMETER_USERNAME, username); put(PARAMETER_USERNAME, username);
put(PARAMETER_FILE_POSTFIX, filePostfix); put(PARAMETER_FILE_POSTFIX, filePostfix);
put(PARAMETER_FILE_TYPE, fileTypeEnum.getFileExtension()); put(PARAMETER_FILE_TYPE, fileTypeEnum.getFileExtension());
}}; }};
String requestBody = null; URI uri = URI.create(storageServiceConfig.getFileServicePath() + "/file");
String requestBody = this.writeToRequestBody(values);
StorageServiceUploadResponse uploadResponse = null;
try { try {
requestBody = objectMapper var response = this.postRequest(uri, requestBody);
.writeValueAsString(values); uploadResponse = objectMapper.readValue(response, StorageServiceUploadResponse.class);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
HttpPost request = new HttpPost(URI.create(storageServiceConfig.getFileServicePath() + "/file"));
request.setHeader("Content-Type", "application/json");
try {
request.setEntity(new ByteArrayEntity(requestBody.getBytes("UTF-8")));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
CloseableHttpClient httpClient = HttpClientBuilder.create()
.setRedirectStrategy(new LaxRedirectStrategy()).build();
try {
return httpClient.execute(
request,
response -> {
String responseString = EntityUtils.toString(response.getEntity(), "UTF-8");
return objectMapper.readValue(responseString, StorageServiceUploadResponse.class);
}
);
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException(e); log.warn("File not found: " + username + "/" + filePostfix);
}
} }
public StorageServiceDownloadResponse getFileUrl(String username, String filePostfix) { return Optional.ofNullable(uploadResponse);
}
public Optional<StorageServiceDownloadResponse> getFileUrl(String username, String filePostfix) {
URI uri = null; URI uri = null;
try { try {
uri = new URIBuilder(storageServiceConfig.getFileServicePath() + "/file") uri = new URIBuilder(storageServiceConfig.getFileServicePath() + "/file")
@@ -90,26 +71,20 @@ public class StorageService {
.addParameter(PARAMETER_FILE_POSTFIX, filePostfix) .addParameter(PARAMETER_FILE_POSTFIX, filePostfix)
.build(); .build();
} catch (URISyntaxException e) { } catch (URISyntaxException e) {
throw new RuntimeException(e); log.warn("Invalid File: " + username + "/" + filePostfix);
return Optional.empty();
} }
HttpGet request = new HttpGet(uri);
request.setHeader("Content-Type", "application/json");
CloseableHttpClient httpClient = HttpClientBuilder.create()
.setRedirectStrategy(new LaxRedirectStrategy()).build();
StorageServiceDownloadResponse downloadResponse = null;
try { try {
return httpClient.execute( var responseString = this.getRequest(uri);
request, downloadResponse = objectMapper.readValue(responseString, StorageServiceDownloadResponse.class);
response -> {
String responseString = EntityUtils.toString(response.getEntity(), "UTF-8");
return objectMapper.readValue(responseString, StorageServiceDownloadResponse.class);
}
);
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException(e); log.warn("File not found: " + username + "/" + filePostfix);
} }
return Optional.ofNullable(downloadResponse);
} }
public void deleteFile(String username, String filePostfix) { public void deleteFile(String username, String filePostfix) {
@@ -120,24 +95,13 @@ public class StorageService {
.addParameter(PARAMETER_FILE_POSTFIX, filePostfix) .addParameter(PARAMETER_FILE_POSTFIX, filePostfix)
.build(); .build();
} catch (URISyntaxException e) { } catch (URISyntaxException e) {
throw new RuntimeException(e); log.warn("File not found: " + username + "/" + filePostfix);
} }
HttpDelete request = new HttpDelete(uri);
request.setHeader("Content-Type", "application/json");
CloseableHttpClient httpClient = HttpClientBuilder.create()
.setRedirectStrategy(new LaxRedirectStrategy()).build();
try { try {
httpClient.execute( this.deleteRequest(uri);
request,
response -> {
return null;
}
);
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException(e); log.warn("File not found: " + username + "/" + filePostfix);
} }
} }
@@ -147,17 +111,31 @@ public class StorageService {
put(PARAMETER_FILE_POSTFIX, filePostfix); put(PARAMETER_FILE_POSTFIX, filePostfix);
}}; }};
ObjectMapper objectMapper = new ObjectMapper(); URI uri = URI.create(storageServiceConfig.getFileServicePath() + "/file/process");
String requestBody = this.writeToRequestBody(values);
String requestBody = null;
try { try {
requestBody = objectMapper this.postRequest(uri, requestBody);
.writeValueAsString(values); } catch (IOException e) {
} catch (JsonProcessingException e) { log.warn("File not found: " + username + "/" + filePostfix);
throw new RuntimeException(e); }
} }
HttpPost request = new HttpPost(URI.create(storageServiceConfig.getFileServicePath() + "/file/process")); private String getRequest(URI requestURI) throws IOException {
HttpGet request = new HttpGet(requestURI);
request.setHeader("Content-Type", "application/json");
CloseableHttpClient httpClient = HttpClientBuilder.create()
.setRedirectStrategy(new LaxRedirectStrategy()).build();
return httpClient.execute(
request,
response -> EntityUtils.toString(response.getEntity(), "UTF-8")
);
}
private String postRequest(URI requestURI, String requestBody) throws IOException {
HttpPost request = new HttpPost(requestURI);
request.setHeader("Content-Type", "application/json"); request.setHeader("Content-Type", "application/json");
try { try {
@@ -169,17 +147,36 @@ public class StorageService {
CloseableHttpClient httpClient = HttpClientBuilder.create() CloseableHttpClient httpClient = HttpClientBuilder.create()
.setRedirectStrategy(new LaxRedirectStrategy()).build(); .setRedirectStrategy(new LaxRedirectStrategy()).build();
try { return httpClient.execute(
request,
response -> EntityUtils.toString(response.getEntity(), "UTF-8")
);
}
private void deleteRequest(URI requestURI) throws IOException {
HttpDelete request = new HttpDelete(requestURI);
request.setHeader("Content-Type", "application/json");
CloseableHttpClient httpClient = HttpClientBuilder.create()
.setRedirectStrategy(new LaxRedirectStrategy()).build();
httpClient.execute( httpClient.execute(
request, request,
response -> { response -> {
String responseString = EntityUtils.toString(response.getEntity(), "UTF-8"); return null;
return objectMapper.readValue(responseString, StorageServiceUploadResponse.class);
} }
); );
} catch (IOException e) { }
private String writeToRequestBody(HashMap<String, String> values) {
String requestBody = null;
try {
requestBody = objectMapper
.writeValueAsString(values);
} catch (JsonProcessingException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
return requestBody;
} }
} }