I'm trying to put together a hello world program for testing out Google Cloud Storage. My goal is to have the simplest possible program that just uploads a hard-coded file to Cloud Storage.
I've been scouring the internet for a basic tutorial, but the closest I could find is this guide for using Cloud Storage from App Engine. I've put together this program:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import com.google.cloud.storage.Acl;
import com.google.cloud.storage.Acl.Role;
import com.google.cloud.storage.Acl.User;
import com.google.cloud.storage.BlobInfo;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
public class Main {
public static void main(String[] args) throws FileNotFoundException{
FileInputStream fileInputStream = new FileInputStream("my-file.txt");
Storage storage = StorageOptions.getDefaultInstance().getService();
BlobInfo blobInfo =
storage.create(
BlobInfo
.newBuilder("my-cloud-storage-bucket", "my-file.txt")
.setAcl(new ArrayList<>(Arrays.asList(Acl.of(User.ofAllUsers(), Role.READER))))
.build(),
fileInputStream);
String fileUrl = blobInfo.getMediaLink();
System.out.println("Uploaded URL: " + fileUrl);
}
}
When I run that code, I get a 401 Unauthorized
error when I call storage.create()
, and that's not surprising because I'm not providing a username or password. I gather that's because the example is running in App Engine, which provides the credentials that way.
I've tried passing in my credentials via a properties file:
Credential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.setServiceAccountId("accountId")
.setServiceAccountPrivateKeyFromP12File(
new File("PRIVATE_KEY_PATH"))
.setServiceAccountScopes(scopes).build();
Storage storage = new StorageOptions.DefaultStorageFactory().create(StorageOptions.newBuilder().setCredentials(credential).build());
But that doesn't compile because the setCredentials()
function needs a Credentials
instance, not a Credential
instance.
I've been Googling and reading through the Cloud Storage API, but I still can't figure out how I'm supposed to pass in the credentials without going through a convoluted setup process.
So, my question is: what is the simplest way to provide credentials to Google Cloud storage to upload a file?
For some background: I'm trying to compare and contrast Google Cloud Storage and Amazon S3. I can create a program like this in S3 no problem, but for some reason I'm hitting a brick wall with Cloud Storage. Definitely appreciate any insights or basic tutorials anybody can throw my way.