How to Receive a Notification from Google Cloud Pub/Sub with Java

import static java.lang.System.out;

import java.io.FileInputStream;
import java.util.List;

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.util.Utils;
import com.google.api.services.pubsub.Pubsub;
import com.google.api.services.pubsub.Pubsub.Projects.Subscriptions;
import com.google.api.services.pubsub.PubsubScopes;
import com.google.api.services.pubsub.model.AcknowledgeRequest;
import com.google.api.services.pubsub.model.PullRequest;
import com.google.api.services.pubsub.model.ReceivedMessage;
import com.google.common.collect.ImmutableList;

public final class PubsubSample {

  public static void main(final String[] args) throws Exception {
    final Subscriptions subscriptions = new Pubsub.Builder(Utils.getDefaultTransport(), Utils.getDefaultJsonFactory(), GoogleCredential.fromStream(new FileInputStream("projectid.json")).createScoped(PubsubScopes.all())).build().projects().subscriptions();

    final List<ReceivedMessage> msgLst = subscriptions.pull("projects/projectid/subscriptions/SampleSubscription", new PullRequest().setMaxMessages(1)).execute().getReceivedMessages().iterator();

    for (final ReceivedMessage msg : msgLst) {
      out.println(msg);

      subscriptions.acknowledge("projects/projectid/subscriptions/SampleSubscription", new AcknowledgeRequest().setAckIds(ImmutableList.of(msg.getAckId()))).execute();
    }

  }

}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s