· 6 years ago · Jul 11, 2019, 11:32 AM
1package com.example.bucket.bucketservice
2
3import com.amazonaws.auth.AWSCredentials
4import com.amazonaws.auth.BasicAWSCredentials
5import com.amazonaws.services.s3.AmazonS3
6import com.amazonaws.services.s3.AmazonS3Client
7import com.amazonaws.services.s3.model.CannedAccessControlList
8import com.amazonaws.services.s3.model.DeleteObjectRequest
9import com.amazonaws.services.s3.model.PutObjectRequest
10import com.example.bucket.model.url
11import com.example.bucket.repo.urlRepo
12import kotlinx.coroutines.asCoroutineDispatcher
13import kotlinx.coroutines.async
14import kotlinx.coroutines.runBlocking
15import kotlinx.coroutines.withContext
16import org.jetbrains.kotlin.types.typeUtil.isNullabilityMismatch
17import org.springframework.beans.factory.annotation.Autowired
18import org.springframework.stereotype.Component
19import org.springframework.stereotype.Service
20import org.springframework.web.multipart.MultipartFile
21import java.io.File
22import java.io.FileOutputStream
23import java.net.URL
24import java.util.*
25import java.util.concurrent.ExecutorService
26import java.util.concurrent.Executors
27
28
29class BucketServiceImpl() : BucketService {
30
31 @Autowired
32 var urlRepo : urlRepo? = null
33
34 @Autowired
35 private var urlObj = url()
36
37 var bucketName: String = "striker-bucket"
38 var endpointUrl: String = "s3.ap-south-1.amazonaws.com"
39 var s3client: AmazonS3? = null
40 var accessKey = "
41 var secretKey = "I"
42
43 init { // Constructor setting up client credentials using defined details.
44 val credentials: AWSCredentials = BasicAWSCredentials(accessKey, secretKey)
45 s3client = AmazonS3Client(credentials)
46 }
47
48
49 override fun uploadFileTos3bucket(fileName: String, file: File) {
50
51
52 s3client?.putObject(PutObjectRequest(bucketName, fileName, file)
53 .withCannedAcl(CannedAccessControlList.PublicRead)) // putObject puts the file in the bucket.
54
55
56 }
57
58
59 override fun generateFileName(multiPart : MultipartFile): String { // Adding timestamp to file name
60
61 return Date().time.toString() + "-" + multiPart.getOriginalFilename().replace(" ", "_")
62 }
63
64
65 override fun convertMultiPartToFile(file: MultipartFile): File { // Converting multipart file to java file type
66
67 val convFile: File = File(file.getOriginalFilename() as String)
68
69
70 val fos = FileOutputStream(convFile)
71 fos.write(file.getBytes())
72 fos.close()
73
74 return convFile
75
76 }
77
78
79 override fun uploadFile(multipartFile: MultipartFile): String = runBlocking {
80
81// var fileUrl: String = ""
82 val customDispatcher = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors())
83 .asCoroutineDispatcher() //Custom Dispatcher is defined.
84 try {
85 val file : File
86 val fileName : String
87
88 file = withContext(customDispatcher){ convertMultiPartToFile(multipartFile) } // Converting multipart to file
89 fileName = withContext(customDispatcher) { generateFileName(multipartFile) } // Generating file name
90
91 urlObj.fileUrl = endpointUrl + "/" + bucketName + "/" + fileName
92 println(urlObj.fileUrl)
93// println("Reaching save")
94 urlRepo?.save(urlObj)
95 println(urlObj.id)
96
97
98 val job = async{ uploadFileTos3bucket(fileName, file) } // Uplaoding to bucket using putObject
99 job.join()
100 file.delete() // Deleting local copy from the system.
101 (customDispatcher.executor as ExecutorService).shutdown() // Shutting down Executor services.
102
103
104 } catch (e: Exception) {
105 e.printStackTrace()
106 }
107 return@runBlocking urlObj.fileUrl.toString() // Returning file URL. Here runBlocking keeps a check whether all the threads completed their jobs or not
108 // if all the jobs are completed their results are combined using .join() and then the fianl result is return when Main thread is not blocked.
109 }
110
111
112 override fun deleteFileFromS3Bucket(fileName: String): String { // Deleting the file using file Url
113// println(fileName)
114 s3client?.deleteObject(DeleteObjectRequest(bucketName, fileName))
115 return "Successfully deleted"
116 }
117
118}