PublishMessage implements HttpFunction { @Override public void service(HttpRequest request, HttpResponse response) throws IOException { Optional<String> maybeTopicName = request.getFirstQueryParameter("topic"); Optional<String> maybeMessage = request.getFirstQueryParameter("message"); BufferedWriter responseWriter = response.getWriter(); if (maybeTopicName.isEmpty() || maybeMessage.isEmpty()) { response.setStatusCode(HttpURLConnection.HTTP_BAD_REQUEST); responseWriter.write("Missing 'topic' and/or 'message' parameter(s)."); return; } String topicName = maybeTopicName.get(); logger.info("Publishing message to topic: " + topicName); ByteString byteStr = ByteString.copyFrom(maybeMessage.get(), StandardCharsets.UTF_8); PubsubMessage pubsubApiMessage = PubsubMessage.newBuilder().setData(byteStr).build(); Publisher publisher = Publisher.newBuilder( ProjectTopicName.of(PROJECT_ID, topicName)).build(); String responseMessage; try { publisher.publish(pubsubApiMessage).get(); responseMessage = "Message published."; } catch (InterruptedException | ExecutionException e) { logger.log(Level.SEVERE, "Error publishing Pub/Sub message: " + e.getMessage(), e); responseMessage = "Error publishing Pub/Sub message; see logs for more info."; } responseWriter.write(responseMessage); }  @Override void service(HttpRequest request, HttpResponse response);  }
@Test public void functionsPubsubPublish_shouldFailWithoutParameters() throws IOException { new PublishMessage().service(request, response); writerOut.flush(); assertThat(responseOut.toString()).isEqualTo( "Missing 'topic' and/or 'message' parameter(s)."); }
@Test public void functionsPubsubPublish_shouldPublishMessage() throws Exception { when(request.getFirstQueryParameter("topic")).thenReturn(Optional.of(FUNCTIONS_TOPIC)); when(request.getFirstQueryParameter("message")).thenReturn(Optional.of("hello")); new PublishMessage().service(request, response); writerOut.flush(); assertThat(logHandler.getStoredLogRecords().get(0).getMessage()).isEqualTo( "Publishing message to topic: " + FUNCTIONS_TOPIC); assertThat(responseOut.toString()).isEqualTo("Message published."); }