当前位置: 首页>>代码示例>>Java>>正文


Java Pubsub类代码示例

本文整理汇总了Java中com.google.api.services.pubsub.Pubsub的典型用法代码示例。如果您正苦于以下问题:Java Pubsub类的具体用法?Java Pubsub怎么用?Java Pubsub使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


Pubsub类属于com.google.api.services.pubsub包,在下文中一共展示了Pubsub类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: getClient

import com.google.api.services.pubsub.Pubsub; //导入依赖的package包/类
/** 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();
}
 
开发者ID:mdvorsky,项目名称:DataflowSME,代码行数:25,代码来源:InjectorUtils.java

示例2: createClient

import com.google.api.services.pubsub.Pubsub; //导入依赖的package包/类
/**
     * 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();
    }
 
开发者ID:spac3lord,项目名称:eip,代码行数:20,代码来源:PubSubWrapper.java

示例3: getClient

import com.google.api.services.pubsub.Pubsub; //导入依赖的package包/类
/**
 * 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();
}
 
开发者ID:davorbonaci,项目名称:beam-portability-demo,代码行数:28,代码来源:InjectorUtils.java

示例4: newClient

import com.google.api.services.pubsub.Pubsub; //导入依赖的package包/类
@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);
}
 
开发者ID:apache,项目名称:beam,代码行数:18,代码来源:PubsubJsonClient.java

示例5: GcloudPubsub

import com.google.api.services.pubsub.Pubsub; //导入依赖的package包/类
/**
 * 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");
}
 
开发者ID:GoogleCloudPlatform,项目名称:cloud-pubsub-mqtt-proxy,代码行数:27,代码来源:GcloudPubsub.java

示例6: PubSubClient

import com.google.api.services.pubsub.Pubsub; //导入依赖的package包/类
public PubSubClient(PubSubDatastoreProperties datastore) {

        Credentials credentials = null;
        if (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();
    }
 
开发者ID:Talend,项目名称:components,代码行数:19,代码来源:PubSubClient.java

示例7: getClient

import com.google.api.services.pubsub.Pubsub; //导入依赖的package包/类
/**
 * 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();
}
 
开发者ID:GoogleCloudPlatform,项目名称:cloud-pubsub-samples-java,代码行数:27,代码来源:PubsubUtils.java

示例8: createSubscription

import com.google.api.services.pubsub.Pubsub; //导入依赖的package包/类
/**
 * 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());
}
 
开发者ID:GoogleCloudPlatform,项目名称:cloud-pubsub-samples-java,代码行数:28,代码来源:SubscriptionMethods.java

示例9: publishMessage

import com.google.api.services.pubsub.Pubsub; //导入依赖的package包/类
/**
 * 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);
        }
    }
}
 
开发者ID:GoogleCloudPlatform,项目名称:cloud-pubsub-samples-java,代码行数:29,代码来源:TopicMethods.java

示例10: listTopics

import com.google.api.services.pubsub.Pubsub; //导入依赖的package包/类
/**
 * 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]));
    }
}
 
开发者ID:GoogleCloudPlatform,项目名称:cloud-pubsub-samples-java,代码行数:32,代码来源:TopicMethods.java

示例11: doPost

import com.google.api.services.pubsub.Pubsub; //导入依赖的package包/类
@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();
}
 
开发者ID:GoogleCloudPlatform,项目名称:cloud-pubsub-samples-java,代码行数:23,代码来源:SendMessageServlet.java

示例12: doGet

import com.google.api.services.pubsub.Pubsub; //导入依赖的package包/类
@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);
    }
}
 
开发者ID:GoogleCloudPlatform,项目名称:cloud-pubsub-samples-java,代码行数:24,代码来源:InitServlet.java

示例13: setupTopic

import com.google.api.services.pubsub.Pubsub; //导入依赖的package包/类
/**
 * 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;
        }
    }
}
 
开发者ID:GoogleCloudPlatform,项目名称:cloud-pubsub-samples-java,代码行数:25,代码来源:InitServlet.java

示例14: getClient

import com.google.api.services.pubsub.Pubsub; //导入依赖的package包/类
/**
 * 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();
}
 
开发者ID:GoogleCloudPlatform,项目名称:cloud-pubsub-samples-java,代码行数:26,代码来源:PubsubUtils.java

示例15: createTopic

import com.google.api.services.pubsub.Pubsub; //导入依赖的package包/类
/** Create a topic if it doesn't exist. */
public static void createTopic(Pubsub client, String fullTopicName) throws IOException {
  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());
    }
  }
}
 
开发者ID:mdvorsky,项目名称:DataflowSME,代码行数:12,代码来源:InjectorUtils.java


注:本文中的com.google.api.services.pubsub.Pubsub类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。