Last active
July 20, 2020 23:17
-
-
Save Ikhiloya/cf58acaa61aea440a22542c48c251580 to your computer and use it in GitHub Desktop.
Storage Strategy for firebase upload and download with Admin SDK initialization in code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Service | |
public class FirebaseStorageStrategy implements StorageStrategy { | |
private final Logger log = LoggerFactory.getLogger(FirebaseStorageStrategy.class); | |
private final Environment environment; | |
private StorageOptions storageOptions; | |
private String bucketName; | |
private String projectId; | |
public FirebaseStorageStrategy(Environment environment) { | |
this.environment = environment; | |
} | |
@PostConstruct | |
private void initializeFirebase() throws Exception { | |
bucketName = environment.getRequiredProperty("FIREBASE_BUCKET_NAME"); | |
projectId = environment.getRequiredProperty("FIREBASE_PROJECT_ID"); | |
InputStream firebaseCredential = createFirebaseCredential(); | |
this.storageOptions = StorageOptions.newBuilder() | |
.setProjectId(projectId) | |
.setCredentials(GoogleCredentials.fromStream(firebaseCredential)).build(); | |
} | |
public String[] uploadFile(MultipartFile multipartFile) throws IOException { | |
System.out.println("bucket name====" + bucketName); | |
File file = convertMultiPartToFile(multipartFile); | |
Path filePath = file.toPath(); | |
String objectName = generateFileName(multipartFile); | |
Storage storage = storageOptions.getService(); | |
BlobId blobId = BlobId.of(bucketName, objectName); | |
BlobInfo blobInfo = BlobInfo.newBuilder(blobId).build(); | |
Blob blob = storage.create(blobInfo, Files.readAllBytes(filePath)); | |
log.info("File " + filePath + " uploaded to bucket " + bucketName + " as " + objectName); | |
return new String[]{"fileUrl", objectName}; | |
} | |
@Override | |
public ResponseEntity<Object> downloadFile(String fileName, HttpServletRequest request) throws Exception { | |
Storage storage = storageOptions.getService(); | |
Blob blob = storage.get(BlobId.of(bucketName, fileName)); | |
ReadChannel reader = blob.reader(); | |
InputStream inputStream = Channels.newInputStream(reader); | |
byte[] content = null; | |
log.info("File downloaded successfully."); | |
content = IOUtils.toByteArray(inputStream); | |
final ByteArrayResource byteArrayResource = new ByteArrayResource(content); | |
return ResponseEntity | |
.ok() | |
.contentLength(content.length) | |
.header("Content-type", "application/octet-stream") | |
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"") | |
.body(byteArrayResource); | |
} | |
private File convertMultiPartToFile(MultipartFile file) throws IOException { | |
File convertedFile = new File(Objects.requireNonNull(file.getOriginalFilename())); | |
FileOutputStream fos = new FileOutputStream(convertedFile); | |
fos.write(file.getBytes()); | |
fos.close(); | |
return convertedFile; | |
} | |
private String generateFileName(MultipartFile multiPart) { | |
return new Date().getTime() + "-" + Objects.requireNonNull(multiPart.getOriginalFilename()).replace(" ", "_"); | |
} | |
private InputStream createFirebaseCredential() throws Exception { | |
FirebaseCredential firebaseCredential = new FirebaseCredential(); | |
//private key | |
String privateKey = environment.getRequiredProperty("FIREBASE_PRIVATE_KEY").replace("\\n", "\n"); | |
firebaseCredential.setType(environment.getRequiredProperty("FIREBASE_TYPE")); | |
firebaseCredential.setProject_id(projectId); | |
firebaseCredential.setPrivate_key_id("FIREBASE_PRIVATE_KEY_ID"); | |
firebaseCredential.setPrivate_key(privateKey); | |
firebaseCredential.setClient_email(environment.getRequiredProperty("FIREBASE_CLIENT_EMAIL")); | |
firebaseCredential.setClient_id(environment.getRequiredProperty("FIREBASE_CLIENT_ID")); | |
firebaseCredential.setAuth_uri(environment.getRequiredProperty("FIREBASE_AUTH_URI")); | |
firebaseCredential.setToken_uri(environment.getRequiredProperty("FIREBASE_TOKEN_URI")); | |
firebaseCredential.setAuth_provider_x509_cert_url(environment.getRequiredProperty("FIREBASE_AUTH_PROVIDER_X509_CERT_URL")); | |
firebaseCredential.setClient_x509_cert_url(environment.getRequiredProperty("FIREBASE_CLIENT_X509_CERT_URL")); | |
ObjectMapper mapper = new ObjectMapper(); | |
String jsonString = mapper.writeValueAsString(firebaseCredential); | |
//convert jsonString string to InputStream using Apache Commons | |
return IOUtils.toInputStream(jsonString); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment