1
|
|
|
package com.osomapps.pt.exercises; |
2
|
|
|
|
3
|
|
|
import com.osomapps.pt.ResourceNotFoundException; |
4
|
|
|
import java.io.IOException; |
5
|
|
|
import java.io.OutputStream; |
6
|
|
|
import java.util.Base64; |
7
|
|
|
import org.springframework.stereotype.Service; |
8
|
|
|
|
9
|
|
|
@Service |
10
|
|
|
class ExerciseImageService { |
11
|
|
|
private static final String BASE64_PREFIX = ";base64,"; |
12
|
|
|
private static final int BASE64_PREFIX_LENGTH = 8; |
13
|
|
|
private final ExerciseFileRepository exerciseFileRepository; |
14
|
|
|
|
15
|
|
|
ExerciseImageService(ExerciseFileRepository exerciseFileRepository) { |
16
|
|
|
this.exerciseFileRepository = exerciseFileRepository; |
17
|
|
|
} |
18
|
|
|
|
19
|
|
|
ExerciseImageDTO findOne(Long id, String fileName, OutputStream outputStream) |
|
|
|
|
20
|
|
|
throws IOException { |
21
|
|
|
final ExerciseFile exerciseFile = exerciseFileRepository.findById(id).orElse(null); |
22
|
|
|
if (exerciseFile == null) { |
23
|
|
|
throw new ResourceNotFoundException("File with id " + id + " not found"); |
24
|
|
|
} |
25
|
|
|
dataUrlToOutputStream(exerciseFile.getData_url(), outputStream); |
26
|
|
|
return new ExerciseImageDTO() |
27
|
|
|
.setId(exerciseFile.getId()) |
28
|
|
|
.setFileName(exerciseFile.getFile_name()) |
29
|
|
|
.setFileType(exerciseFile.getFile_type()); |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
void dataUrlToOutputStream(String dataUrl, OutputStream outputStream) throws IOException { |
33
|
|
|
final String encodedString = |
34
|
|
|
dataUrl.substring(dataUrl.indexOf(BASE64_PREFIX) + BASE64_PREFIX_LENGTH); |
35
|
|
|
outputStream.write(Base64.getDecoder().decode(encodedString)); |
36
|
|
|
} |
37
|
|
|
} |
38
|
|
|
|