Another thing you have to do is give your subscriber application access to your PubSub application. You need to go into 'APIs & auth' -> 'Credentials' and create a service account. Then, you need to use the service account email and the p12 or json file and use that to give your subscriber access to PubSub. Here is my code:
1. You need to create an instance of PubSub. Mine looks like this:
Pubsub pubsub = PubsubUtils.createPubsubClient();
That calls a couple of static methods that I created:
public static Pubsub createPubsubClient() throws GeneralSecurityException, IOException {
return createPubsubClient(Utils.getDefaultTransport(), Utils.getDefaultJsonFactory());
}
public static Pubsub createPubsubClient(HttpTransport httpTransport, JsonFactory jsonFactory) throws GeneralSecurityException, IOException {
Preconditions.checkNotNull(httpTransport, "HttpTransport cannot be null");
Preconditions.checkNotNull(jsonFactory, "JsonFactory cannot be null");
GoogleCredential credential = new GoogleCredential.Builder()
setTransport(httpTransport).setJsonFactory(jsonFactory)
.setServiceAccountPrivateKeyFromP12File(new File(PATH TO YOUR P12 FILE))
.build();
HttpRequestInitializer initializer = new RetryHttpInitializerWrapper(credential);
return new Pubsub.Builder(httpTransport, jsonFactory, initializer).setApplicationName(APPLICATION WHERE PUBSUB IS LOCATED).build();
}
2. Then you can use the PubSub instance to access PubSub, for example:
pubsub.projects().topics().get("projects/MyApp/topics/MyTopic").execute();
or
Subscription subscription = new Subscription().setTopic("projects/MyApp/topics/MyTopic").setPushConfig(pushConfig);
pubsub.projects().subscriptions().create("projects/MyApp/subscriptions/MySubscriptionName", ).execute();
Let me know how that works out.