Skip to content

Instantly share code, notes, and snippets.

@poluektik
Created December 24, 2018 11:30
Show Gist options
  • Save poluektik/dd6b5f47b5c90558e983adc2c3208287 to your computer and use it in GitHub Desktop.
Save poluektik/dd6b5f47b5c90558e983adc2c3208287 to your computer and use it in GitHub Desktop.
example that register bucket notifications to some pub/sub topic in GCP
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.api.services.storage.Storage;
import com.google.api.services.storage.StorageScopes;
import com.google.api.services.storage.model.Notification;
import com.google.cloud.storage.Bucket;
import com.google.gson.JsonObject;
import java.io.FileInputStream;
import java.util.Collections;
public class GooglePubSubClient {
public static void main(String[] args) {
try {
String bucketName = "some-bucket";
String credentials = "your creds";
String topicId = "//pubsub.googleapis.com/projects/your-project/topics/your-topic";
final GoogleCredential googleCredential = GoogleCredential
.fromStream(new FileInputStream(pathToFileWithCredentials))
.createScoped(Collections.singletonList(StorageScopes.DEVSTORAGE_FULL_CONTROL));
final Storage storage = new Storage.Builder(new NetHttpTransport(), new JacksonFactory(), googleCredential).build();
Notification notification = new Notification();
notification.setTopic(topicId);
notification.setPayloadFormat("JSON_API_V1");
Notification v = storage.notifications().insert(bucketName, notification).execute();
System.out.println(v);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment