in publish-events/channel/client-libraries/java/src/main/java/com/google/cloud/eventarc/publishing/example/PublishEventsExample.java [86:121]
public void PublishEvent(String channelName, boolean useTextEvent) throws Exception {
CustomMessage eventData = new CustomMessage("Hello world from Java");
LOGGER.log(Level.INFO, "Building CloudEvent");
ObjectMapper objectMapper = new ObjectMapper();
CloudEvent event = new CloudEventBuilder()
.withId(UUID.randomUUID().toString())
.withSource(URI.create("//custom/from/java"))
// Note: Type has to match with the trigger!
.withType("mycompany.myorg.myproject.v1.myevent")
.withTime(OffsetDateTime.now())
// Note: someattribute and somevalue have to match with the trigger!
.withExtension("someattribute", "somevalue")
.withExtension("extsourcelang", "java")
.withData("application/json",
JsonCloudEventData.wrap(objectMapper.valueToTree(eventData)))
.build();
PublishEventsRequest request = useTextEvent ?
GetPublishEventsRequestWithTextFormat(channelName, event) :
GetPublishEventsRequestWithProtoFormat(channelName, event);
LOGGER.log(Level.INFO, "Publishing message to Eventarc");
try {
PublisherClient client = PublisherClient.create();
PublishEventsResponse response = client.publishEvents(request);
LOGGER.log(Level.INFO, String.format("Message published successfully.\nReceived response: %s",
response.toString()));
} catch (Exception ex) {
LOGGER.log(Level.SEVERE, "An exception occurred while publishing", ex);
}
}