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


Java PubsubMessage类代码示例

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


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

示例1: publishDataToPubSub

import com.google.api.services.pubsub.model.PubsubMessage; //导入依赖的package包/类
/**
 * Publish 'numMessages' arbitrary events from live users with the provided delay, to a
 * PubSub topic.
 */
public static void publishDataToPubSub(int numMessages, int delayInMillis)
    throws IOException {
  List<PubsubMessage> pubsubMessages = new ArrayList<>();

  for (int i = 0; i < Math.max(1, numMessages); i++) {
    Long currTime = System.currentTimeMillis();
    String message = generateEvent(currTime, delayInMillis);
    PubsubMessage pubsubMessage = new PubsubMessage()
        .encodeData(message.getBytes("UTF-8"));
    pubsubMessage.setAttributes(
        ImmutableMap.of(TIMESTAMP_ATTRIBUTE,
            Long.toString((currTime - delayInMillis) / 1000 * 1000)));
    if (delayInMillis != 0) {
      System.out.println(pubsubMessage.getAttributes());
      System.out.println("late data for: " + message);
    }
    pubsubMessages.add(pubsubMessage);
  }

  PublishRequest publishRequest = new PublishRequest();
  publishRequest.setMessages(pubsubMessages);
  pubsub.projects().topics().publish(topic, publishRequest).execute();
}
 
开发者ID:davorbonaci,项目名称:beam-portability-demo,代码行数:28,代码来源:Injector.java

示例2: publishData

import com.google.api.services.pubsub.model.PubsubMessage; //导入依赖的package包/类
/**
 * Publish 'numMessages' arbitrary events from live users with the provided delay, to a
 * PubSub topic.
 */
public static void publishData(int numMessages, int delayInMillis)
    throws IOException {
  List<PubsubMessage> pubsubMessages = new ArrayList<>();

  for (int i = 0; i < Math.max(1, numMessages); i++) {
    Long currTime = System.currentTimeMillis();
    String message = generateEvent(currTime, delayInMillis);
    PubsubMessage pubsubMessage = new PubsubMessage()
            .encodeData(message.getBytes("UTF-8"));
    pubsubMessage.setAttributes(
        ImmutableMap.of(TIMESTAMP_ATTRIBUTE,
            Long.toString((currTime - delayInMillis) / 1000 * 1000)));
    if (delayInMillis != 0) {
      System.out.println(pubsubMessage.getAttributes());
      System.out.println("late data for: " + message);
    }
    pubsubMessages.add(pubsubMessage);
  }

  PublishRequest publishRequest = new PublishRequest();
  publishRequest.setMessages(pubsubMessages);
  pubsub.projects().topics().publish(topic, publishRequest).execute();
}
 
开发者ID:apache,项目名称:beam,代码行数:28,代码来源:Injector.java

示例3: publish

import com.google.api.services.pubsub.model.PubsubMessage; //导入依赖的package包/类
@Override
public int publish(TopicPath topic, List<OutgoingMessage> outgoingMessages)
    throws IOException {
  List<PubsubMessage> pubsubMessages = new ArrayList<>(outgoingMessages.size());
  for (OutgoingMessage outgoingMessage : outgoingMessages) {
    PubsubMessage pubsubMessage = new PubsubMessage().encodeData(outgoingMessage.elementBytes);
    pubsubMessage.setAttributes(getMessageAttributes(outgoingMessage));
    pubsubMessages.add(pubsubMessage);
  }
  PublishRequest request = new PublishRequest().setMessages(pubsubMessages);
  PublishResponse response = pubsub.projects()
                                   .topics()
                                   .publish(topic.getPath(), request)
                                   .execute();
  return response.getMessageIds().size();
}
 
开发者ID:apache,项目名称:beam,代码行数:17,代码来源:PubsubJsonClient.java

示例4: publishOneMessage

import com.google.api.services.pubsub.model.PubsubMessage; //导入依赖的package包/类
@Test
public void publishOneMessage() throws IOException {
  String expectedTopic = TOPIC.getPath();
  PubsubMessage expectedPubsubMessage = new PubsubMessage()
      .encodeData(DATA.getBytes())
      .setAttributes(
          ImmutableMap.<String, String> builder()
                  .put(TIMESTAMP_ATTRIBUTE, String.valueOf(MESSAGE_TIME))
                  .put(ID_ATTRIBUTE, RECORD_ID)
                  .put("k", "v").build());
  PublishRequest expectedRequest = new PublishRequest()
      .setMessages(ImmutableList.of(expectedPubsubMessage));
  PublishResponse expectedResponse = new PublishResponse()
      .setMessageIds(ImmutableList.of(MESSAGE_ID));
  Mockito.when((Object) (mockPubsub.projects()
                              .topics()
                              .publish(expectedTopic, expectedRequest)
                              .execute()))
         .thenReturn(expectedResponse);
  Map<String, String> attrs = new HashMap<>();
  attrs.put("k", "v");
  OutgoingMessage actualMessage = new OutgoingMessage(
          DATA.getBytes(), attrs, MESSAGE_TIME, RECORD_ID);
  int n = client.publish(TOPIC, ImmutableList.of(actualMessage));
  assertEquals(1, n);
}
 
开发者ID:apache,项目名称:beam,代码行数:27,代码来源:PubsubJsonClientTest.java

示例5: publishOneMessageWithOnlyTimestampAndIdAttributes

import com.google.api.services.pubsub.model.PubsubMessage; //导入依赖的package包/类
@Test
public void publishOneMessageWithOnlyTimestampAndIdAttributes() throws IOException {
  String expectedTopic = TOPIC.getPath();
  PubsubMessage expectedPubsubMessage = new PubsubMessage()
      .encodeData(DATA.getBytes())
      .setAttributes(
          ImmutableMap.<String, String> builder()
                  .put(TIMESTAMP_ATTRIBUTE, String.valueOf(MESSAGE_TIME))
                  .put(ID_ATTRIBUTE, RECORD_ID).build());
  PublishRequest expectedRequest = new PublishRequest()
      .setMessages(ImmutableList.of(expectedPubsubMessage));
  PublishResponse expectedResponse = new PublishResponse()
      .setMessageIds(ImmutableList.of(MESSAGE_ID));
  Mockito.when((Object) (mockPubsub.projects()
                              .topics()
                              .publish(expectedTopic, expectedRequest)
                              .execute()))
         .thenReturn(expectedResponse);
  OutgoingMessage actualMessage = new OutgoingMessage(
      DATA.getBytes(), ImmutableMap.<String, String>of(), MESSAGE_TIME, RECORD_ID);
  int n = client.publish(TOPIC, ImmutableList.of(actualMessage));
  assertEquals(1, n);
}
 
开发者ID:apache,项目名称:beam,代码行数:24,代码来源:PubsubJsonClientTest.java

示例6: publishMessage

import com.google.api.services.pubsub.model.PubsubMessage; //导入依赖的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

示例7: publishMessage

import com.google.api.services.pubsub.model.PubsubMessage; //导入依赖的package包/类
/**
 * Publishes the given message to the given topic.
 */
public void publishMessage(String message, String outputTopic) {
  int maxLogMessageLength = 200;
  if (message.length() < maxLogMessageLength) {
    maxLogMessageLength = message.length();
  }
  logger.info("Received ...." + message.substring(0, maxLogMessageLength));

  // Publish message to Pubsub.
  PubsubMessage pubsubMessage = new PubsubMessage();
  pubsubMessage.encodeData(message.getBytes());

  PublishRequest publishRequest = new PublishRequest();
  publishRequest.setTopic(outputTopic).setMessage(pubsubMessage);
  try {
    this.pubsub.topics().publish(publishRequest).execute();
  } catch (java.io.IOException e) {
    logger.warning(e.getStackTrace().toString());
  }
}
 
开发者ID:GoogleCloudPlatform,项目名称:cloud-pubsub-samples-java,代码行数:23,代码来源:NewsInjector.java

示例8: publishMessage

import com.google.api.services.pubsub.model.PubsubMessage; //导入依赖的package包/类
/**
 * Publishes the given message to a Cloud Pub/Sub topic.
 */
public void publishMessage(String message, String outputTopic) {
  int maxLogMessageLength = 200;
  if (message.length() < maxLogMessageLength) {
    maxLogMessageLength = message.length();
  }
  logger.info("Received ...." + message.substring(0, maxLogMessageLength));

  // Publish message to Pubsub.
  PubsubMessage pubsubMessage = new PubsubMessage();
  pubsubMessage.encodeData(message.getBytes());

  PublishRequest publishRequest = new PublishRequest();
  publishRequest.setTopic(outputTopic).setMessage(pubsubMessage);
  try {
    this.pubsub.topics().publish(publishRequest).execute();
  } catch (java.io.IOException e) {
    ;
  }
}
 
开发者ID:GoogleCloudPlatform,项目名称:cloud-pubsub-samples-java,代码行数:23,代码来源:StockInjector.java

示例9: doPost

import com.google.api.services.pubsub.model.PubsubMessage; //导入依赖的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

示例10: publishDataToFile

import com.google.api.services.pubsub.model.PubsubMessage; //导入依赖的package包/类
/** Publish generated events to a file. */
public static void publishDataToFile(String fileName, int numMessages, int delayInMillis)
    throws IOException {
  List<PubsubMessage> pubsubMessages = new ArrayList<>();
  PrintWriter out =
      new PrintWriter(
          new OutputStreamWriter(
              new BufferedOutputStream(new FileOutputStream(fileName, true)), "UTF-8"));

  try {
    for (int i = 0; i < Math.max(1, numMessages); i++) {
      Long currTime = System.currentTimeMillis();
      StringBuilder user = new StringBuilder();
      String id = UUID.randomUUID().toString();
      String message = generateScoreEvent(currTime, delayInMillis, id, user);
      out.println(message);
    }
  } catch (Exception e) {
    e.printStackTrace();
  } finally {
    if (out != null) {
      out.flush();
      out.close();
    }
  }
}
 
开发者ID:mdvorsky,项目名称:DataflowSME,代码行数:27,代码来源:Injector.java

示例11: processElement

import com.google.api.services.pubsub.model.PubsubMessage; //导入依赖的package包/类
@Override
public void processElement(ProcessContext c) throws IOException {
  if (c.element().isEmpty()) {
    return;
  }
  PubsubMessage pubsubMessage = new PubsubMessage();
  pubsubMessage.encodeData(c.element().getBytes());
  if (timestampLabelKey != null) {
    pubsubMessage.setAttributes(
        ImmutableMap.of(timestampLabelKey, Long.toString(c.timestamp().getMillis())));
  }
  PublishRequest publishRequest = new PublishRequest();
  publishRequest.setMessages(Arrays.asList(pubsubMessage));
  this.pubsub.projects().topics().publish(outputTopic, publishRequest).execute();
}
 
开发者ID:sinmetal,项目名称:iron-hippo,代码行数:16,代码来源:PubsubFileInjector.java

示例12: pullOneMessage

import com.google.api.services.pubsub.model.PubsubMessage; //导入依赖的package包/类
@Test
public void pullOneMessage() throws IOException {
  String expectedSubscription = SUBSCRIPTION.getPath();
  PullRequest expectedRequest =
      new PullRequest().setReturnImmediately(true).setMaxMessages(10);
  PubsubMessage expectedPubsubMessage = new PubsubMessage()
      .setMessageId(MESSAGE_ID)
      .encodeData(DATA.getBytes())
      .setPublishTime(String.valueOf(PUB_TIME))
      .setAttributes(
          ImmutableMap.of(TIMESTAMP_ATTRIBUTE, String.valueOf(MESSAGE_TIME),
              ID_ATTRIBUTE, RECORD_ID));
  ReceivedMessage expectedReceivedMessage =
      new ReceivedMessage().setMessage(expectedPubsubMessage)
                           .setAckId(ACK_ID);
  PullResponse expectedResponse =
      new PullResponse().setReceivedMessages(ImmutableList.of(expectedReceivedMessage));
  Mockito.when((Object) (mockPubsub.projects()
                             .subscriptions()
                             .pull(expectedSubscription, expectedRequest)
                             .execute()))
         .thenReturn(expectedResponse);
  List<IncomingMessage> acutalMessages = client.pull(REQ_TIME, SUBSCRIPTION, 10, true);
  assertEquals(1, acutalMessages.size());
  IncomingMessage actualMessage = acutalMessages.get(0);
  assertEquals(ACK_ID, actualMessage.ackId);
  assertEquals(DATA, new String(actualMessage.elementBytes));
  assertEquals(RECORD_ID, actualMessage.recordId);
  assertEquals(REQ_TIME, actualMessage.requestTimeMsSinceEpoch);
  assertEquals(MESSAGE_TIME, actualMessage.timestampMsSinceEpoch);
}
 
开发者ID:apache,项目名称:beam,代码行数:32,代码来源:PubsubJsonClientTest.java

示例13: publishOneMessageWithNoTimestampOrIdAttribute

import com.google.api.services.pubsub.model.PubsubMessage; //导入依赖的package包/类
@Test
public void publishOneMessageWithNoTimestampOrIdAttribute() throws IOException {
  // For this test, create a new PubsubJsonClient without the timestamp attribute
  // or id attribute set.
  client = new PubsubJsonClient(null, null, mockPubsub);

  String expectedTopic = TOPIC.getPath();
  PubsubMessage expectedPubsubMessage = new PubsubMessage()
      .encodeData(DATA.getBytes())
      .setAttributes(
          ImmutableMap.<String, String> builder()
                  .put("k", "v").build());
  PublishRequest expectedRequest = new PublishRequest()
      .setMessages(ImmutableList.of(expectedPubsubMessage));
  PublishResponse expectedResponse = new PublishResponse()
      .setMessageIds(ImmutableList.of(MESSAGE_ID));
  Mockito.when((Object) (mockPubsub.projects()
                              .topics()
                              .publish(expectedTopic, expectedRequest)
                              .execute()))
         .thenReturn(expectedResponse);
  Map<String, String> attrs = new HashMap<>();
  attrs.put("k", "v");
  OutgoingMessage actualMessage = new OutgoingMessage(
          DATA.getBytes(), attrs, MESSAGE_TIME, RECORD_ID);
  int n = client.publish(TOPIC, ImmutableList.of(actualMessage));
  assertEquals(1, n);
}
 
开发者ID:apache,项目名称:beam,代码行数:29,代码来源:PubsubJsonClientTest.java

示例14: publish

import com.google.api.services.pubsub.model.PubsubMessage; //导入依赖的package包/类
/**
 * Publishes a message to Google Cloud Pub/Sub.
 * TODO(rshanky) - Provide config option for automatic topic creation on publish/subscribe through
 * Google Cloud Pub/Sub.
 *
 * @param msg the message and attributes to be published is contained in this object.
 * @throws IOException is thrown on Google Cloud Pub/Sub publish(or createTopic) API failure.
 */
@Override
public void publish(PublishMessage msg) throws IOException {
  String publishTopic = createFullGcloudPubsubTopic(createPubSubTopic(msg.getMqttTopic()));
  PubsubMessage pubsubMessage = new PubsubMessage();
  byte[] payload = convertMqttPayloadToGcloudPayload(msg.getMqttPaylaod());
  pubsubMessage.setData(new String(payload));
  // create attributes for the message
  Map<String, String> attributes = ImmutableMap.of(MQTT_CLIENT_ID, msg.getMqttClientId(),
      MQTT_TOPIC_NAME, msg.getMqttTopic(),
      MQTT_MESSAGE_ID, msg.getMqttMessageId() == null ? "" : msg.getMqttMessageId().toString(),
      MQTT_RETAIN, msg.isMqttMessageRetained().toString(),
      PROXY_SERVER_ID, serverName);
  pubsubMessage.setAttributes(attributes);
  // publish message
  List<PubsubMessage> messages = ImmutableList.of(pubsubMessage);
  PublishRequest publishRequest = new PublishRequest().setMessages(messages);
  try {
    pubsub.projects().topics().publish(publishTopic, publishRequest).execute();
  } catch (GoogleJsonResponseException e) {
    if (e.getStatusCode() == RESOURCE_NOT_FOUND) {
      logger.info("Cloud PubSub Topic Not Found");
      createTopic(publishTopic);
      pubsub.projects().topics().publish(publishTopic, publishRequest).execute();
    } else {
      // re-throw the exception so that we do not send a PUBACK
      throw e;
    }
  }
  logger.info("Google Cloud Pub/Sub publish SUCCESS for topic " + publishTopic);
}
 
开发者ID:GoogleCloudPlatform,项目名称:cloud-pubsub-mqtt-proxy,代码行数:39,代码来源:GcloudPubsub.java

示例15: pullMessages

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


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