· 4 years ago · Apr 14, 2021, 08:30 PM
1import com.backblaze.b2.client.B2StorageClient
2import com.backblaze.b2.client.B2StorageClientFactory
3import com.backblaze.b2.client.contentHandlers.B2ContentMemoryWriter
4import com.backblaze.b2.client.contentSources.B2ContentTypes
5import com.backblaze.b2.client.contentSources.B2FileContentSource
6import com.backblaze.b2.client.contentSources.B2Headers
7import com.backblaze.b2.client.structures.B2DownloadByNameRequest
8import com.backblaze.b2.client.structures.B2UploadFileRequest
9import java.io.ByteArrayInputStream
10import java.io.File
11import java.io.FileOutputStream
12
13open class StorageGatewayImp {
14 private val accessKey = System.getenv("B2_ACCESS_KEY")
15 private val secretKey = System.getenv("B2_SECRET_KEY")
16 private var b2Client: B2StorageClient = B2StorageClientFactory
17 .createDefaultFactory()
18 .create(accessKey, secretKey, B2Headers.USER_AGENT)
19
20 fun putObject(bucketName: String, objectName: String, file: File) {
21 val bucket = b2Client.getBucketOrNullByName(bucketName)
22 val source = B2FileContentSource.build(file)
23 val request = B2UploadFileRequest.builder(bucket.bucketId, objectName, B2ContentTypes.B2_AUTO, source).build()
24 b2Client.uploadSmallFile(request)
25 }
26
27 fun getObject(bucketName: String, objectName: String): File {
28 try {
29 val downloadRequest = B2DownloadByNameRequest
30 .builder(bucketName, objectName)
31 .build()
32 val downloadHandler = B2ContentMemoryWriter.build()
33 b2Client.downloadByName(downloadRequest, downloadHandler)
34 val byteArrayInputStream = ByteArrayInputStream(downloadHandler.bytes)
35 return byteArrayInputStreamToFile(byteArrayInputStream)
36 } catch (e: Exception) {
37 throw e
38 }
39 }
40
41 private fun byteArrayInputStreamToFile(byteArrayInputStream: ByteArrayInputStream): File {
42 val newFile = File.createTempFile("b2-", "")
43 val fos = FileOutputStream(newFile)
44 var data: Int
45 while (byteArrayInputStream.read().also { data = it } != -1) {
46 val ch = data.toChar()
47 fos.write(ch.toInt())
48 }
49 fos.flush()
50 fos.close()
51 return newFile
52 }
53}