Skip to content

Commit

Permalink
chore: transfer to mac
Browse files Browse the repository at this point in the history
Signed-off-by: pierresomny <[email protected]>
  • Loading branch information
pierresomny committed Mar 27, 2024
1 parent e0b0a93 commit 43d50d1
Show file tree
Hide file tree
Showing 13 changed files with 270 additions and 5 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ target/
!**/src/main/**/target/
!**/src/test/**/target/
.env
src/main/resources/gcp.json

### STS ###
.apt_generated
Expand Down
31 changes: 29 additions & 2 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.2</version>
<version>3.2.3</version>
<relativePath/>
</parent>
<groupId>com.sfeir-open-source</groupId>
Expand All @@ -20,6 +20,10 @@
<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>
</properties>
<dependencies>
<dependency>
Expand Down Expand Up @@ -52,6 +56,16 @@
</dependency>

<!-- TOOLS -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-storage</artifactId>
<version>${google-cloud-storage.version}</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
Expand Down Expand Up @@ -85,6 +99,19 @@
<scope>test</scope>
</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 Expand Up @@ -124,7 +151,7 @@
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.11</version>
<version>${jacoco-maven-plugin.version}</version>
<executions>
<execution>
<goals>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
antMatcher("/swagger-ui/**")
).permitAll()
// And other requests authenticated.
.anyRequest().authenticated()
.anyRequest().permitAll()
)
.oauth2ResourceServer((oauth2) -> oauth2.jwt(Customizer.withDefaults()));

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import com.sfeiropensource.schoolapp.model.CreateSchoolDTO;
import com.sfeiropensource.schoolapp.model.SchoolDTO;
import com.sfeiropensource.schoolapp.model.SearchSchoolDTO;
import com.sfeiropensource.schoolapp.service.GcpBucketService;
import com.sfeiropensource.schoolapp.service.SchoolService;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
Expand All @@ -13,8 +14,10 @@
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

Expand All @@ -28,6 +31,7 @@
public class SchoolController implements ExceptionInterceptor {

private final SchoolService schoolService;
private final GcpBucketService gcpBucketService;

/**
* Retrieve all schools from database
Expand Down Expand Up @@ -90,4 +94,17 @@ public ResponseEntity<SchoolDTO> update(@PathVariable("id") String id, @RequestB
public ResponseEntity<HttpStatus> delete(@PathVariable String id) {
return schoolService.delete(id);
}

/**
* Update image attach to a school
*
* @param file - MultipartFile
* @return String
*/
@PostMapping(value = "/image", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
public ResponseEntity<String> addFile(@RequestParam("file") MultipartFile file) {
log.info("Call addFile API");
gcpBucketService.uploadFiles(file);
return ResponseEntity.ok("yeah my boi");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public UserController(UserService userService) {
*
* @return List<User>
*/
@GetMapping("/")
@GetMapping({"/", ""})
public ResponseEntity<List<UserDTO>> getAll() {
return userService.getAll();
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.sfeiropensource.schoolapp.exception;

import lombok.Data;

@Data
public class BadRequestException extends RuntimeException {

private final String message;

public BadRequestException(String message) {
super(message);
this.message = message;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.sfeiropensource.schoolapp.exception;

import lombok.Data;

@Data
public class FileWriteException extends RuntimeException {

private final String message;

public FileWriteException(String message) {
super(message);
this.message = message;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.sfeiropensource.schoolapp.exception;

import lombok.Data;

@Data
public class GCPFileUploadException extends RuntimeException {

private final String message;

public GCPFileUploadException(String message) {
super(message);
this.message = message;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.sfeiropensource.schoolapp.exception;

import lombok.Data;

@Data
public class InvalidFileTypeException extends RuntimeException {

private final String message;

public InvalidFileTypeException(String message) {
super(message);
this.message = message;
}
}
11 changes: 11 additions & 0 deletions src/main/java/com/sfeiropensource/schoolapp/model/FileDto.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package com.sfeiropensource.schoolapp.model;

import lombok.AllArgsConstructor;
import lombok.Data;

@Data
@AllArgsConstructor
public class FileDto {
private String fileName;
private String fileUrl;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package com.sfeiropensource.schoolapp.service;

import com.sfeiropensource.schoolapp.exception.BadRequestException;
import com.sfeiropensource.schoolapp.exception.GCPFileUploadException;
import com.sfeiropensource.schoolapp.model.FileDto;
import com.sfeiropensource.schoolapp.utils.DataBucketUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;

@Slf4j
@Service
@Transactional
@RequiredArgsConstructor
public class GcpBucketService {

private final DataBucketUtil dataBucketUtil;

public void uploadFiles(MultipartFile file) {

log.info("Start file uploading service");

String originalFileName = file.getOriginalFilename();
if (originalFileName == null) {
throw new BadRequestException("Original file name is null");
}
Path path = new File(originalFileName).toPath();

try {
String contentType = Files.probeContentType(path);
FileDto fileDto = dataBucketUtil.uploadFile(file, originalFileName, contentType);

if (fileDto != null) {
log.info("File uploaded successfully, file name: {} and url: {}", fileDto.getFileName(), fileDto.getFileUrl());
}
} catch (Exception e) {
log.error("Error occurred while uploading. Error: ", e);
throw new GCPFileUploadException("Error occurred while uploading");
}

// fileRepository.saveAll(inputFiles);
log.info("File details successfully saved in the database");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ public ResponseEntity<Page<SchoolDTO>> search(int pageNumber, int pageSize, Sear
*
* @param id int
* @param createSchoolDTO CreateSchoolDTO
* @return ResponseEntity<SchoolDTO>D
* @return ResponseEntity<SchoolDTO>
*/
public ResponseEntity<SchoolDTO> update(String id, CreateSchoolDTO createSchoolDTO) throws NotFoundException {
Optional<School> request = schoolRepository.findById(id);
Expand Down
103 changes: 103 additions & 0 deletions src/main/java/com/sfeiropensource/schoolapp/utils/DataBucketUtil.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
package com.sfeiropensource.schoolapp.utils;

import com.google.auth.oauth2.GoogleCredentials;
import com.google.cloud.storage.Blob;
import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import com.sfeiropensource.schoolapp.exception.FileWriteException;
import com.sfeiropensource.schoolapp.exception.GCPFileUploadException;
import com.sfeiropensource.schoolapp.exception.InvalidFileTypeException;
import com.sfeiropensource.schoolapp.model.FileDto;
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;

@Component
public class DataBucketUtil {

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

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

@Value("${gcp.project.id}")
private String gcpProjectId;

@Value("${gcp.bucket.id}")
private String gcpBucketId;

@Value("${gcp.dir.name}")
private String gcpDirectoryName;


public FileDto uploadFile(MultipartFile multipartFile, String fileName, String contentType) {

try {

LOGGER.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();

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);

if (blob != null) {
LOGGER.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);
throw new GCPFileUploadException("An error occurred while storing data to GCS");
}
throw new GCPFileUploadException("An error occurred while storing data to GCS");
}

private File convertFile(MultipartFile file) {

try {
if (file.getOriginalFilename() == null) {
throw new BadRequestException("Original file name is null");
}
File convertedFile = new File(file.getOriginalFilename());
FileOutputStream outputStream = new FileOutputStream(convertedFile);
outputStream.write(file.getBytes());
outputStream.close();
LOGGER.debug("Converting multipart file : {}", convertedFile);
return convertedFile;
} catch (Exception e) {
throw new FileWriteException("An error has occurred while converting the file");
}
}

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

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

0 comments on commit 43d50d1

Please sign in to comment.