Skip to content

Commit

Permalink
fix(bucket-gcs): upload image working
Browse files Browse the repository at this point in the history
Signed-off-by: Pierre SOMNY <[email protected]>
  • Loading branch information
pierresomny committed Apr 5, 2024
1 parent 43d50d1 commit 14c0a2b
Show file tree
Hide file tree
Showing 6 changed files with 32 additions and 33 deletions.
22 changes: 8 additions & 14 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.3</version>
<version>3.2.4</version>
<relativePath/>
</parent>
<groupId>com.sfeir-open-source</groupId>
Expand All @@ -20,7 +20,6 @@
<maven-compiler-plugin.version>3.11.0</maven-compiler-plugin.version>
<lombok.version>1.18.30</lombok.version>
<lombok-mapstruct-binding.version>0.2.0</lombok-mapstruct-binding.version>
<librairies-bom.version>26.0.0</librairies-bom.version>
<commons-io.version>2.13.0</commons-io.version>
<jacoco-maven-plugin.version>0.8.11</jacoco-maven-plugin.version>
<google-cloud-storage.version>2.35.0</google-cloud-storage.version>
Expand Down Expand Up @@ -61,6 +60,13 @@
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/net.bytebuddy/byte-buddy -->
<dependency>
<groupId>net.bytebuddy</groupId>
<artifactId>byte-buddy</artifactId>
<version>1.14.13</version>
</dependency>

<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-storage</artifactId>
Expand Down Expand Up @@ -100,18 +106,6 @@
</dependency>
</dependencies>

<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>libraries-bom</artifactId>
<version>${librairies-bom.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

<build>
<finalName>school-app-docker</finalName>
<plugins>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package com.sfeiropensource.schoolapp.exception;

import lombok.Data;
import lombok.EqualsAndHashCode;

@EqualsAndHashCode(callSuper = true)
@Data
public class BadRequestException extends RuntimeException {

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package com.sfeiropensource.schoolapp.exception;

import lombok.Data;
import lombok.EqualsAndHashCode;

@EqualsAndHashCode(callSuper = true)
@Data
public class FileWriteException extends RuntimeException {

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package com.sfeiropensource.schoolapp.exception;

import lombok.Data;
import lombok.EqualsAndHashCode;

@EqualsAndHashCode(callSuper = true)
@Data
public class GCPFileUploadException extends RuntimeException {

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package com.sfeiropensource.schoolapp.exception;

import lombok.Data;
import lombok.EqualsAndHashCode;

@EqualsAndHashCode(callSuper = true)
@Data
public class InvalidFileTypeException extends RuntimeException {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,24 +9,23 @@
import com.sfeiropensource.schoolapp.exception.GCPFileUploadException;
import com.sfeiropensource.schoolapp.exception.InvalidFileTypeException;
import com.sfeiropensource.schoolapp.model.FileDto;
import lombok.extern.slf4j.Slf4j;
import net.bytebuddy.utility.RandomString;
import org.apache.commons.io.FileUtils;
import org.apache.coyote.BadRequestException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.concurrent.ThreadLocalRandom;

@Slf4j
@Component
public class DataBucketUtil {

private static final Logger LOGGER = LoggerFactory.getLogger(DataBucketUtil.class);

@Value("${gcp.config.file}")
private String gcpConfigFile;

Expand All @@ -44,26 +43,24 @@ public FileDto uploadFile(MultipartFile multipartFile, String fileName, String c

try {

LOGGER.debug("Start file uploading process on GCS");
log.debug("Start file uploading process on GCS");
byte[] fileData = FileUtils.readFileToByteArray(convertFile(multipartFile));

InputStream inputStream = new ClassPathResource(gcpConfigFile).getInputStream();

StorageOptions options = StorageOptions.newBuilder().setProjectId(gcpProjectId)
.setCredentials(GoogleCredentials.fromStream(inputStream)).build();
GoogleCredentials credentials = GoogleCredentials.fromStream(new ClassPathResource(gcpConfigFile).getInputStream());
Storage storage = StorageOptions.newBuilder().setCredentials(credentials).setProjectId(gcpProjectId).build().getService();
Bucket bucket = storage.get(gcpBucketId);

Storage storage = options.getService();
Bucket bucket = storage.get(gcpBucketId, Storage.BucketGetOption.fields());

Blob blob = bucket.create(gcpDirectoryName + "/" + fileName + "-[replace by random ID]" + checkFileExtension(fileName), fileData, contentType);
RandomString id = new RandomString(6, ThreadLocalRandom.current());
Blob blob = bucket.create(gcpDirectoryName + "/" + id.nextString() + checkFileExtension(fileName), fileData, contentType);

if (blob != null) {
LOGGER.debug("File successfully uploaded to GCS");
log.debug("File successfully uploaded to GCS");
return new FileDto(blob.getName(), blob.getMediaLink());
}

} catch (Exception e) {
LOGGER.error("An error occurred while uploading data. Exception: ", e);
log.error("An error occurred while uploading data. Exception: ", e);
throw new GCPFileUploadException("An error occurred while storing data to GCS");
}
throw new GCPFileUploadException("An error occurred while storing data to GCS");
Expand All @@ -79,7 +76,7 @@ private File convertFile(MultipartFile file) {
FileOutputStream outputStream = new FileOutputStream(convertedFile);
outputStream.write(file.getBytes());
outputStream.close();
LOGGER.debug("Converting multipart file : {}", convertedFile);
log.debug("Converting multipart file : {}", convertedFile);
return convertedFile;
} catch (Exception e) {
throw new FileWriteException("An error has occurred while converting the file");
Expand All @@ -88,16 +85,16 @@ private File convertFile(MultipartFile file) {

private String checkFileExtension(String fileName) {
if (fileName != null && fileName.contains(".")) {
String[] extensionList = {".png", ".jpeg", ".pdf", ".doc", ".mp3"};
String[] extensionList = {".png", ".jpeg", ".jpg", ".pdf", ".doc", ".mp3"};

for (String extension : extensionList) {
if (fileName.endsWith(extension)) {
LOGGER.debug("Accepted file type : {}", extension);
log.debug("Accepted file type : {}", extension);
return extension;
}
}
}
LOGGER.error("Not a permitted file type");
log.error("Not a permitted file type");
throw new InvalidFileTypeException("Not a permitted file type");
}
}

0 comments on commit 14c0a2b

Please sign in to comment.