com.google.api.services.pubsub.Pubsub Java Examples

The following examples show how to use com.google.api.services.pubsub.Pubsub. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PubsubJsonClient.java    From beam with Apache License 2.0 6 votes vote down vote up
@Override
public PubsubClient newClient(
    @Nullable String timestampAttribute, @Nullable String idAttribute, PubsubOptions options)
    throws IOException {
  Pubsub pubsub =
      new Builder(
              Transport.getTransport(),
              Transport.getJsonFactory(),
              chainHttpRequestInitializer(
                  options.getGcpCredential(),
                  // Do not log 404. It clutters the output and is possibly even required by the
                  // caller.
                  new RetryHttpRequestInitializer(ImmutableList.of(404))))
          .setRootUrl(options.getPubsubRootUrl())
          .setApplicationName(options.getAppName())
          .setGoogleClientRequestInitializer(options.getGoogleApiTrace())
          .build();
  return new PubsubJsonClient(timestampAttribute, idAttribute, pubsub);
}
 
Example #2
Source File: PubsubUtils.java    From cloud-pubsub-samples-java with Apache License 2.0 6 votes vote down vote up
/**
 * Builds a new Pubsub client and returns it.
 *
 * @param httpTransport HttpTransport for Pubsub client.
 * @param jsonFactory JsonFactory for Pubsub client.
 * @return Pubsub client.
 * @throws IOException when we can not get the default credentials.
 */
public static Pubsub getClient(final HttpTransport httpTransport,
                               final JsonFactory jsonFactory)
        throws IOException {
    Preconditions.checkNotNull(httpTransport);
    Preconditions.checkNotNull(jsonFactory);
    GoogleCredential credential = GoogleCredential.getApplicationDefault();
    if (credential.createScopedRequired()) {
        credential = credential.createScoped(PubsubScopes.all());
    }
    // Please use custom HttpRequestInitializer for automatic
    // retry upon failures.
    HttpRequestInitializer initializer =
            new RetryHttpInitializerWrapper(credential);
    return new Pubsub.Builder(httpTransport, jsonFactory, initializer)
            .setApplicationName(APPLICATION_NAME)
            .build();
}
 
Example #3
Source File: PubSubWrapper.java    From eip with MIT License 6 votes vote down vote up
/**
     * Setup authorization for local app based on private key.
     * See <a href="https://cloud.google.com/pubsub/configure">cloud.google.com/pubsub/configure</a>
     */
    private void createClient(String private_key_file, String email) throws IOException, GeneralSecurityException {
        HttpTransport transport = GoogleNetHttpTransport.newTrustedTransport();
        GoogleCredential credential = new GoogleCredential.Builder()
                .setTransport(transport)
                .setJsonFactory(JSON_FACTORY)
                .setServiceAccountScopes(PubsubScopes.all())
                .setServiceAccountId(email)
                .setServiceAccountPrivateKeyFromP12File(new File(private_key_file))
                .build();
        // Please use custom HttpRequestInitializer for automatic retry upon failures.
//        HttpRequestInitializer initializer = new RetryHttpInitializerWrapper(credential);
        pubsub = new Pubsub.Builder(transport, JSON_FACTORY, credential)
                .setApplicationName("eaipubsub")
                .build();
    }
 
Example #4
Source File: InjectorUtils.java    From beam with Apache License 2.0 6 votes vote down vote up
/** Builds a new Pubsub client and returns it. */
public static Pubsub getClient(final HttpTransport httpTransport, final JsonFactory jsonFactory)
    throws IOException {
  checkNotNull(httpTransport);
  checkNotNull(jsonFactory);
  GoogleCredential credential =
      GoogleCredential.getApplicationDefault(httpTransport, jsonFactory);
  if (credential.createScopedRequired()) {
    credential = credential.createScoped(PubsubScopes.all());
  }
  if (credential.getClientAuthentication() != null) {
    System.out.println(
        "\n***Warning! You are not using service account credentials to "
            + "authenticate.\nYou need to use service account credentials for this example,"
            + "\nsince user-level credentials do not have enough pubsub quota,\nand so you will run "
            + "out of PubSub quota very quickly.\nSee "
            + "https://developers.google.com/identity/protocols/application-default-credentials.");
    System.exit(1);
  }
  HttpRequestInitializer initializer = new RetryHttpInitializerWrapper(credential);
  return new Pubsub.Builder(httpTransport, jsonFactory, initializer)
      .setApplicationName(APP_NAME)
      .build();
}
 
Example #5
Source File: InjectorUtils.java    From deployment-examples with MIT License 6 votes vote down vote up
/** Builds a new Pubsub client and returns it. */
public static Pubsub getClient(final HttpTransport httpTransport, final JsonFactory jsonFactory)
    throws IOException {
  checkNotNull(httpTransport);
  checkNotNull(jsonFactory);
  GoogleCredential credential =
      GoogleCredential.getApplicationDefault(httpTransport, jsonFactory);
  if (credential.createScopedRequired()) {
    credential = credential.createScoped(PubsubScopes.all());
  }
  if (credential.getClientAuthentication() != null) {
    System.out.println(
        "\n***Warning! You are not using service account credentials to "
            + "authenticate.\nYou need to use service account credentials for this example,"
            + "\nsince user-level credentials do not have enough pubsub quota,\nand so you will run "
            + "out of PubSub quota very quickly.\nSee "
            + "https://developers.google.com/identity/protocols/application-default-credentials.");
    System.exit(1);
  }
  HttpRequestInitializer initializer = new RetryHttpInitializerWrapper(credential);
  return new Pubsub.Builder(httpTransport, jsonFactory, initializer)
      .setApplicationName(APP_NAME)
      .build();
}
 
Example #6
Source File: InitServlet.java    From cloud-pubsub-samples-java with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a Cloud Pub/Sub topic if it doesn't exist.
 *
 * @param client Pubsub client object.
 * @throws IOException when API calls to Cloud Pub/Sub fails.
 */
private void setupTopic(final Pubsub client) throws IOException {
    String fullName = String.format("projects/%s/topics/%s",
            PubsubUtils.getProjectId(),
            PubsubUtils.getAppTopicName());

    try {
        client.projects().topics().get(fullName).execute();
    } catch (GoogleJsonResponseException e) {
        if (e.getStatusCode() == HttpStatusCodes.STATUS_CODE_NOT_FOUND) {
            // Create the topic if it doesn't exist
            client.projects().topics()
                    .create(fullName, new Topic())
                    .execute();
        } else {
            throw e;
        }
    }
}
 
Example #7
Source File: InitServlet.java    From cloud-pubsub-samples-java with Apache License 2.0 6 votes vote down vote up
@Override
public final void doGet(final HttpServletRequest req,
                        final HttpServletResponse resp)
        throws IOException {
    Pubsub client = PubsubUtils.getClient();
    String projectId = PubsubUtils.getProjectId();
    req.setAttribute("project", projectId);

    setupTopic(client);
    setupSubscription(client);

    req.setAttribute("topic", PubsubUtils.getAppTopicName());
    req.setAttribute("subscription", PubsubUtils.getAppSubscriptionName());
    req.setAttribute("subscriptionEndpoint",
            PubsubUtils.getAppEndpointUrl()
                    .replaceAll("token=[^&]*", "token=REDACTED"));
    RequestDispatcher rd = req.getRequestDispatcher("/WEB-INF/main.jsp");
    try {
        rd.forward(req, resp);
    } catch (ServletException e) {
        throw new IOException(e);
    }
}
 
Example #8
Source File: SendMessageServlet.java    From cloud-pubsub-samples-java with Apache License 2.0 6 votes vote down vote up
@Override
public final void doPost(final HttpServletRequest req,
                         final HttpServletResponse resp)
        throws IOException {
    Pubsub client = PubsubUtils.getClient();
    String message = req.getParameter("message");
    if (!"".equals(message)) {
        String fullTopicName = String.format("projects/%s/topics/%s",
                PubsubUtils.getProjectId(),
                PubsubUtils.getAppTopicName());
        PubsubMessage pubsubMessage = new PubsubMessage();
        pubsubMessage.encodeData(message.getBytes("UTF-8"));
        PublishRequest publishRequest = new PublishRequest();
        publishRequest.setMessages(ImmutableList.of(pubsubMessage));

        client.projects().topics()
                .publish(fullTopicName, publishRequest)
                .execute();
    }
    resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
    resp.getWriter().close();
}
 
Example #9
Source File: GcloudPubsub.java    From cloud-pubsub-mqtt-proxy with Apache License 2.0 6 votes vote down vote up
/**
 * Constructor that will automatically instantiate a Google Cloud Pub/Sub instance.
 *
 * @throws IOException when the initialization of the Google Cloud Pub/Sub client fails.
 */
public GcloudPubsub() throws IOException {
  if (CLOUD_PUBSUB_PROJECT_ID == null) {
    throw new IllegalStateException(GCLOUD_PUBSUB_PROJECT_ID_NOT_SET_ERROR);
  }
  try {
    serverName = InetAddress.getLocalHost().getCanonicalHostName();
  } catch (UnknownHostException e) {
    throw new IllegalStateException("Unable to retrieve the hostname of the system");
  }
  HttpTransport httpTransport = checkNotNull(Utils.getDefaultTransport());
  JsonFactory jsonFactory = checkNotNull(Utils.getDefaultJsonFactory());
  GoogleCredential credential = GoogleCredential.getApplicationDefault(
      httpTransport, jsonFactory);
  if (credential.createScopedRequired()) {
    credential = credential.createScoped(PubsubScopes.all());
  }
  HttpRequestInitializer initializer =
      new RetryHttpInitializerWrapper(credential);
  pubsub = new Pubsub.Builder(httpTransport, jsonFactory, initializer).build();
  logger.info("Google Cloud Pub/Sub Initialization SUCCESS");
}
 
Example #10
Source File: PubSubClient.java    From components with Apache License 2.0 6 votes vote down vote up
public PubSubClient(PubSubDatastoreProperties datastore, boolean runOnDataflow) {

        Credentials credentials = null;
        if (runOnDataflow || datastore.serviceAccountFile.getValue() == null) {
            try {
                credentials = GoogleCredentials.getApplicationDefault().createScoped(PubsubScopes.all());
            } catch (IOException e) {
                throw TalendRuntimeException.createUnexpectedException(e);
            }
        } else {
            credentials = createCredentials(datastore);
        }
        this.PROJECT_NAME = datastore.projectName.getValue();
        this.client = new Pubsub.Builder(Transport.getTransport(), Transport.getJsonFactory(),
                chainHttpRequestInitializer(credentials,
                        // Do not log 404. It clutters the output and is possibly even required by the caller.
                        new RetryHttpRequestInitializer(ImmutableList.of(404)))).build();
    }
 
Example #11
Source File: PubsubUtils.java    From cloud-pubsub-samples-java with Apache License 2.0 6 votes vote down vote up
/**
 * Builds a new Pubsub client and returns it.
 *
 * @param httpTransport HttpTransport for Pubsub client.
 * @param jsonFactory JsonFactory for Pubsub client.
 * @return Pubsub client.
 * @throws IOException when we can not get the default credentials.
 */
public static Pubsub getClient(final HttpTransport httpTransport,
                               final JsonFactory jsonFactory)
         throws IOException {
    Preconditions.checkNotNull(httpTransport);
    Preconditions.checkNotNull(jsonFactory);
    GoogleCredential credential =
        GoogleCredential.getApplicationDefault(httpTransport, jsonFactory);
    if (credential.createScopedRequired()) {
        credential = credential.createScoped(PubsubScopes.all());
    }
    // Please use custom HttpRequestInitializer for automatic
    // retry upon failures.
    HttpRequestInitializer initializer =
        new RetryHttpInitializerWrapper(credential);
    return new Pubsub.Builder(httpTransport, jsonFactory, initializer)
            .setApplicationName(APP_NAME)
            .build();
}
 
Example #12
Source File: TopicMethods.java    From cloud-pubsub-samples-java with Apache License 2.0 6 votes vote down vote up
/**
 * Lists existing topics in the project.
 *
 * @param client Cloud Pub/Sub client.
 * @param args Command line arguments.
 * @throws IOException when Cloud Pub/Sub API calls fail.
 */
public static void listTopics(final Pubsub client, final String[] args)
        throws IOException {
    String nextPageToken = null;
    boolean hasTopics = false;
    Pubsub.Projects.Topics.List listMethod =
            client.projects().topics().list("projects/" + args[0]);
    do {
        if (nextPageToken != null) {
            listMethod.setPageToken(nextPageToken);
        }
        ListTopicsResponse response = listMethod.execute();
        if (!response.isEmpty()) {
            for (Topic topic : response.getTopics()) {
                hasTopics = true;
                System.out.println(topic.getName());
            }
        }
        nextPageToken = response.getNextPageToken();
    } while (nextPageToken != null);
    if (!hasTopics) {
        System.out.println(String.format(
                "There are no topics in the project '%s'.", args[0]));
    }
}
 
Example #13
Source File: TopicMethods.java    From cloud-pubsub-samples-java with Apache License 2.0 6 votes vote down vote up
/**
 * Publishes the given message to the given topic.
 *
 * @param client Cloud Pub/Sub client.
 * @param args Command line arguments.
 * @throws IOException when Cloud Pub/Sub API calls fail.
 */
public static void publishMessage(final Pubsub client, final String[] args)
        throws IOException {
    Main.checkArgsLength(args, 4);
    String topic = PubsubUtils.getFullyQualifiedResourceName(
            PubsubUtils.ResourceType.TOPIC, args[0], args[2]);
    String message = args[3];
    PubsubMessage pubsubMessage = new PubsubMessage()
            .encodeData(message.getBytes("UTF-8"));
    List<PubsubMessage> messages = ImmutableList.of(pubsubMessage);
    PublishRequest publishRequest = new PublishRequest();
    publishRequest.setMessages(messages);
    PublishResponse publishResponse = client.projects().topics()
            .publish(topic, publishRequest)
            .execute();
    List<String> messageIds = publishResponse.getMessageIds();
    if (messageIds != null) {
        for (String messageId : messageIds) {
            System.out.println("Published with a message id: " + messageId);
        }
    }
}
 
Example #14
Source File: SubscriptionMethods.java    From cloud-pubsub-samples-java with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new subscription.
 *
 * @param client Cloud Pub/Sub client.
 * @param args Arguments as an array of String.
 * @throws IOException when Cloud Pub/Sub API calls fail.
 */
public static void createSubscription(final Pubsub client,
                                      final String[] args)
        throws IOException {
    Main.checkArgsLength(args, 4);
    String subscriptionName = PubsubUtils.getFullyQualifiedResourceName(
            PubsubUtils.ResourceType.SUBSCRIPTION, args[0], args[2]);
    Subscription subscription = new Subscription()
            .setTopic(PubsubUtils.getFullyQualifiedResourceName(
                    PubsubUtils.ResourceType.TOPIC, args[0], args[3]));
    if (args.length == 5) {
        subscription = subscription.setPushConfig(
            new PushConfig().setPushEndpoint(args[4]));
    }
    subscription = client.projects().subscriptions()
            .create(subscriptionName, subscription)
            .execute();
    System.out.printf(
            "Subscription %s was created.\n", subscription.getName());
    System.out.println(subscription.toPrettyString());
}
 
Example #15
Source File: ServiceAccountConfiguration.java    From play-work with Apache License 2.0 5 votes vote down vote up
public static Pubsub createPubsubClient(String serviceAccountEmail, String privateKeyFilePath)
    throws IOException, GeneralSecurityException {
  HttpTransport transport = GoogleNetHttpTransport.newTrustedTransport();
  GoogleCredential credential = new GoogleCredential.Builder()
      .setTransport(transport)
      .setJsonFactory(JSON_FACTORY)
      .setServiceAccountScopes(PubsubScopes.all())

      // Obtain this from the "APIs & auth" -> "Credentials"
      // section in the Google Developers Console:
      // https://console.developers.google.com/
      // (and put the e-mail address into your system property obviously)
      .setServiceAccountId(serviceAccountEmail)

      // Download this file from "APIs & auth" -> "Credentials"
      // section in the Google Developers Console:
      // https://console.developers.google.com/
      .setServiceAccountPrivateKeyFromP12File(new File(privateKeyFilePath))
      .build();


  // Please use custom HttpRequestInitializer for automatic
  // retry upon failures.  We provide a simple reference
  // implementation in the "Retry Handling" section.
  HttpRequestInitializer initializer =
      new RetryHttpInitializerWrapper(credential);
  return new Pubsub.Builder(transport, JSON_FACTORY, initializer)
      .setApplicationName("PubSub Example")
      .build();
}
 
Example #16
Source File: LocalController.java    From pubsub with Apache License 2.0 5 votes vote down vote up
/** Returns a LocalController using default application credentials. */
public static LocalController newLocalController(
    String projectName, Map<ClientParams, Integer> clients, ScheduledExecutorService executor) {
  try {
    HttpTransport transport = GoogleNetHttpTransport.newTrustedTransport();
    JsonFactory jsonFactory = new JacksonFactory();
    GoogleCredential credential = GoogleCredential.getApplicationDefault(transport, jsonFactory);
    if (credential.createScopedRequired()) {
      credential =
          credential.createScoped(
              Collections.singletonList("https://www.googleapis.com/auth/cloud-platform"));
    }
    Pubsub pubsub =
        new Pubsub.Builder(transport, jsonFactory, credential)
            .setApplicationName("Cloud Pub/Sub Loadtest Framework")
            .build();
    ArrayList<ResourceController> controllers = new ArrayList<>();
    ArrayList<ComputeResourceController> computeControllers = new ArrayList<>();
    clients.forEach(
        (params, numWorkers) -> {
          ComputeResourceController computeController =
              new LocalComputeResourceController(params, numWorkers, executor);
          controllers.add(computeController);
          computeControllers.add(computeController);
        });
    controllers.add(
        new PubsubResourceController(
            projectName, Client.TOPIC, ImmutableList.of(Client.SUBSCRIPTION), executor, pubsub));
    return new LocalController(executor, controllers, computeControllers);
  } catch (Throwable t) {
    log.error("Unable to initialize GCE: ", t);
    return null;
  }
}
 
Example #17
Source File: PubsubPublisher.java    From weatherstation with Apache License 2.0 5 votes vote down vote up
PubsubPublisher(Context context, String appname, String project, String topic,
                int credentialResourceId) throws IOException {
    mContext = context;
    mAppname = appname;
    mTopic = "projects/" + project + "/topics/" + topic;

    mHandlerThread = new HandlerThread("pubsubPublisherThread");
    mHandlerThread.start();
    mHandler = new Handler(mHandlerThread.getLooper());

    InputStream jsonCredentials = mContext.getResources().openRawResource(credentialResourceId);
    final GoogleCredential credentials;
    try {
        credentials = GoogleCredential.fromStream(jsonCredentials).createScoped(
                Collections.singleton(PubsubScopes.PUBSUB));
    } finally {
        try {
            jsonCredentials.close();
        } catch (IOException e) {
            Log.e(TAG, "Error closing input stream", e);
        }
    }
    mHandler.post(new Runnable() {
        @Override
        public void run() {
            mHttpTransport = AndroidHttp.newCompatibleTransport();
            JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
            mPubsub = new Pubsub.Builder(mHttpTransport, jsonFactory, credentials)
                    .setApplicationName(mAppname).build();
        }
    });
}
 
Example #18
Source File: PubsubResourceController.java    From pubsub with Apache License 2.0 5 votes vote down vote up
public PubsubResourceController(
    String project,
    String topic,
    List<String> subscriptions,
    ScheduledExecutorService executor,
    Pubsub pubsub) {
  super(executor);
  this.project = project;
  this.topic = topic;
  this.subscriptions = subscriptions;
  this.pubsub = pubsub;
}
 
Example #19
Source File: InitServlet.java    From cloud-pubsub-samples-java with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a Cloud Pub/Sub subscription if it doesn't exist.
 *
 * @param client Pubsub client object.
 * @throws IOException when API calls to Cloud Pub/Sub fails.
 */
private void setupSubscription(final Pubsub client) throws IOException {
    String fullName = String.format("projects/%s/subscriptions/%s",
            PubsubUtils.getProjectId(),
            PubsubUtils.getAppSubscriptionName());

    try {
        client.projects().subscriptions().get(fullName).execute();
    } catch (GoogleJsonResponseException e) {
        if (e.getStatusCode() == HttpStatusCodes.STATUS_CODE_NOT_FOUND) {
            // Create the subscription if it doesn't exist
            String fullTopicName = String.format("projects/%s/topics/%s",
                    PubsubUtils.getProjectId(),
                    PubsubUtils.getAppTopicName());
            PushConfig pushConfig = new PushConfig()
                    .setPushEndpoint(PubsubUtils.getAppEndpointUrl());
            Subscription subscription = new Subscription()
                    .setTopic(fullTopicName)
                    .setPushConfig(pushConfig);
            client.projects().subscriptions()
                    .create(fullName, subscription)
                    .execute();
        } else {
            throw e;
        }
    }
}
 
Example #20
Source File: WebSocketInjectorStub.java    From cloud-pubsub-samples-java with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a Cloud Pub/Sub client.
 */
public Pubsub createPubsubClient()
  throws IOException, GeneralSecurityException {
  HttpTransport transport = GoogleNetHttpTransport.newTrustedTransport();
  GoogleCredential credential = GoogleCredential.getApplicationDefault();
  HttpRequestInitializer initializer =
      new RetryHttpInitializerWrapper(credential);
  return new Pubsub.Builder(transport, JSON_FACTORY, initializer).build();
}
 
Example #21
Source File: NewsInjector.java    From cloud-pubsub-samples-java with Apache License 2.0 5 votes vote down vote up
/**
 * Fetches news and publishes them to the specified Cloud Pub/Sub topic.
 */
public static void main(String[] args) throws Exception {
  // Get options from command-line.
  if (args.length < 1) {
    System.out.println("Please specify the output Pubsub topic.");
    return;
  }

  String newsTopic = new String(args[0]);

  System.out.println("Output Pubsub topic: " + newsTopic);

  NewsInjector injector = new NewsInjector(null, "");
  // Create a Pubsub.
  Pubsub client = injector.createPubsubClient();

  injector = new NewsInjector(client, newsTopic);

  while (true) {
    // Fetch news.
    injector.publishNews();

    try {
      //thread to sleep for the specified number of milliseconds
      Thread.sleep(20000);
    } catch ( java.lang.InterruptedException ie) {
      ;
    }
  }
}
 
Example #22
Source File: NewsInjector.java    From cloud-pubsub-samples-java with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a Cloud Pub/Sub client.
 */
public Pubsub createPubsubClient()
  throws IOException, GeneralSecurityException {
  HttpTransport transport = GoogleNetHttpTransport.newTrustedTransport();
  GoogleCredential credential = GoogleCredential.getApplicationDefault();
  HttpRequestInitializer initializer =
      new RetryHttpInitializerWrapper(credential);
  return new Pubsub.Builder(transport, JSON_FACTORY, initializer).build();
}
 
Example #23
Source File: ExampleUtils.java    From deployment-examples with MIT License 5 votes vote down vote up
/** Returns a Pubsub client builder using the specified {@link PubsubOptions}. */
private static Pubsub.Builder newPubsubClient(PubsubOptions options) {
  return new Pubsub.Builder(
          Transport.getTransport(),
          Transport.getJsonFactory(),
          chainHttpRequestInitializer(
              options.getGcpCredential(),
              // Do not log 404. It clutters the output and is possibly even required by the
              // caller.
              new RetryHttpRequestInitializer(ImmutableList.of(404))))
      .setRootUrl(options.getPubsubRootUrl())
      .setApplicationName(options.getAppName())
      .setGoogleClientRequestInitializer(options.getGoogleApiTrace());
}
 
Example #24
Source File: TopicMethods.java    From cloud-pubsub-samples-java with Apache License 2.0 5 votes vote down vote up
/**
 * Deletes a topic with the given name.
 *
 * @param client Cloud Pub/Sub client.
 * @param args Command line arguments.
 * @throws IOException when Cloud Pub/Sub API calls fail.
 */
public static void deleteTopic(final Pubsub client, final String[] args)
        throws IOException {
    Main.checkArgsLength(args, 3);
    String topicName = PubsubUtils.getFullyQualifiedResourceName(
            PubsubUtils.ResourceType.TOPIC, args[0], args[2]);
    client.projects().topics().delete(topicName).execute();
    System.out.printf("Topic %s was deleted.\n", topicName);
}
 
Example #25
Source File: InjectorUtils.java    From deployment-examples with MIT License 5 votes vote down vote up
/** Create a topic if it doesn't exist. */
public static void createTopic(Pubsub client, String fullTopicName) throws IOException {
  System.out.println("fullTopicName " + fullTopicName);
  try {
    client.projects().topics().get(fullTopicName).execute();
  } catch (GoogleJsonResponseException e) {
    if (e.getStatusCode() == HttpStatusCodes.STATUS_CODE_NOT_FOUND) {
      Topic topic = client.projects().topics().create(fullTopicName, new Topic()).execute();
      System.out.printf("Topic %s was created.%n", topic.getName());
    }
  }
}
 
Example #26
Source File: TopicMethods.java    From cloud-pubsub-samples-java with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new topic with a given name.
 *
 * @param client Cloud Pub/Sub client.
 * @param args Command line arguments.
 * @throws IOException when Cloud Pub/Sub API calls fail.
 */
public static void createTopic(final Pubsub client, final String[] args)
        throws IOException {
    Main.checkArgsLength(args, 3);
    String topicName = PubsubUtils.getFullyQualifiedResourceName(
            PubsubUtils.ResourceType.TOPIC, args[0], args[2]);
    Topic topic = client.projects().topics()
            .create(topicName, new Topic())
            .execute();
    System.out.printf("Topic %s was created.\n", topic.getName());
}
 
Example #27
Source File: SubscriptionMethods.java    From cloud-pubsub-samples-java with Apache License 2.0 5 votes vote down vote up
/**
 * Deletes a subscription with a given name.
 *
 * @param client Cloud Pub/Sub client.
 * @param args Arguments as an array of String.
 * @throws IOException when Cloud Pub/Sub API calls fail.
 */
public static void deleteSubscription(final Pubsub client,
                                      final String[] args)
        throws IOException {
    Main.checkArgsLength(args, 3);
    String subscriptionName = PubsubUtils.getFullyQualifiedResourceName(
            PubsubUtils.ResourceType.SUBSCRIPTION, args[0], args[2]);
    client.projects().subscriptions().delete(subscriptionName).execute();
    System.out.printf("Subscription %s was deleted.\n", subscriptionName);
}
 
Example #28
Source File: SubscriptionMethods.java    From cloud-pubsub-samples-java with Apache License 2.0 5 votes vote down vote up
/**
 * Keeps pulling messages from the given subscription.
 *
 * @param client Cloud Pub/Sub client.
 * @param args Arguments as an array of String.
 * @throws IOException when Cloud Pub/Sub API calls fail.
 */
public static void pullMessages(final Pubsub client, final String[] args)
        throws IOException {
    Main.checkArgsLength(args, 3);
    String subscriptionName = PubsubUtils.getFullyQualifiedResourceName(
            PubsubUtils.ResourceType.SUBSCRIPTION, args[0], args[2]);
    PullRequest pullRequest = new PullRequest()
            .setReturnImmediately(false)
            .setMaxMessages(Main.BATCH_SIZE);

    do {
        PullResponse pullResponse;
        pullResponse = client.projects().subscriptions()
                .pull(subscriptionName, pullRequest)
                .execute();
        List<String> ackIds = new ArrayList<>(Main.BATCH_SIZE);
        List<ReceivedMessage> receivedMessages =
                pullResponse.getReceivedMessages();
        if (receivedMessages != null) {
            for (ReceivedMessage receivedMessage : receivedMessages) {
                PubsubMessage pubsubMessage =
                        receivedMessage.getMessage();
                if (pubsubMessage != null
                        && pubsubMessage.decodeData() != null) {
                    System.out.println(
                            new String(pubsubMessage.decodeData(),
                                    "UTF-8"));
                }
                ackIds.add(receivedMessage.getAckId());
            }
            AcknowledgeRequest ackRequest = new AcknowledgeRequest();
            ackRequest.setAckIds(ackIds);
            client.projects().subscriptions()
                    .acknowledge(subscriptionName, ackRequest)
                    .execute();
        }
    } while (System.getProperty(Main.LOOP_ENV_NAME) != null);
}
 
Example #29
Source File: SubscriptionMethods.java    From cloud-pubsub-samples-java with Apache License 2.0 5 votes vote down vote up
/**
 * Lists existing subscriptions within a project.
 *
 * @param client Cloud Pub/Sub client.
 * @param args Arguments as an array of String.
 * @throws IOException when Cloud Pub/Sub API calls fail.
 */
public static void listSubscriptions(final Pubsub client,
                                     final String[] args)
        throws IOException {
    String nextPageToken = null;
    boolean hasSubscriptions = false;
    Pubsub.Projects.Subscriptions.List listMethod =
            client.projects().subscriptions().list("projects/" + args[0]);
    do {
        if (nextPageToken != null) {
            listMethod.setPageToken(nextPageToken);
        }
        ListSubscriptionsResponse response = listMethod.execute();
        if (!response.isEmpty()) {
            for (Subscription subscription : response.getSubscriptions()) {
                hasSubscriptions = true;
                System.out.println(subscription.toPrettyString());
            }
        }
        nextPageToken = response.getNextPageToken();
    } while (nextPageToken != null);
    if (!hasSubscriptions) {
        System.out.println(String.format(
                "There are no subscriptions in the project '%s'.",
                args[0]));
    }
}
 
Example #30
Source File: PubSubWrapper.java    From eip with MIT License 5 votes vote down vote up
/**
 * Creates a topic <code>/projects/</code>appName<code>/topics/</code>topicName if it does not already exist.
 */
Topic createTopic(String topicName) throws IOException {
    String topic = getTopic(topicName);
    Pubsub.Projects.Topics topics = pubsub.projects().topics();
    ListTopicsResponse list = topics.list(project).execute();
    if (list.getTopics() == null || !list.getTopics().contains(new Topic().setName(topic))) {
        return topics.create(topic, new Topic()).execute();
    } else {
        return new Topic().setName(topic);
    }
}