OcrTranslateText implements BackgroundFunction<PubSubMessage> { @Override public void accept(PubSubMessage pubSubMessage, Context context) { OcrTranslateApiMessage ocrMessage = OcrTranslateApiMessage.fromPubsubData( pubSubMessage.getData().getBytes(StandardCharsets.UTF_8)); String targetLang = ocrMessage.getLang(); logger.info("Translating text into " + targetLang); String text = ocrMessage.getText(); TranslateTextRequest request = TranslateTextRequest.newBuilder() .setParent(LOCATION_NAME) .setMimeType("text/plain") .setTargetLanguageCode(targetLang) .addContents(text) .build(); TranslateTextResponse response; try (TranslationServiceClient client = TranslationServiceClient.create()) { response = client.translateText(request); } catch (IOException e) { logger.log(Level.SEVERE, "Error translating text: " + e.getMessage(), e); return; } if (response.getTranslationsCount() == 0) { return; } String translatedText = response.getTranslations(0).getTranslatedText(); logger.info("Translated text: " + translatedText); String filename = ocrMessage.getFilename(); OcrTranslateApiMessage translateMessage = new OcrTranslateApiMessage( translatedText, filename, targetLang); try { ByteString byteStr = ByteString.copyFrom(translateMessage.toPubsubData()); PubsubMessage pubsubApiMessage = PubsubMessage.newBuilder().setData(byteStr).build(); publisher.publish(pubsubApiMessage).get(); logger.info("Text translated to " + targetLang); } catch (InterruptedException | ExecutionException e) { logger.log(Level.SEVERE, "Error publishing translation save request: " + e.getMessage(), e); } } OcrTranslateText(); @Override void accept(PubSubMessage pubSubMessage, Context context);  }
@Test(expected = IllegalArgumentException.class) public void functionsOcrTranslate_shouldValidateParams() throws IOException { PubSubMessage message = new PubSubMessage(); message.setData(new String(Base64.getEncoder().encode("{}".getBytes()))); sampleUnderTest.accept(message, null); }
@Test public void functionsOcrTranslate_shouldTranslateText() throws IOException { String text = "Wake up human!"; String filename = "wakeupcat.jpg"; String lang = "es"; JsonObject dataJson = new JsonObject(); dataJson.addProperty("text", text); dataJson.addProperty("filename", filename); dataJson.addProperty("lang", lang); PubSubMessage message = new PubSubMessage(); message.setData(new String(Base64.getEncoder().encode(gson.toJson(dataJson).getBytes()))); sampleUnderTest.accept(message, null); List<LogRecord> logs = LOG_HANDLER.getStoredLogRecords(); Truth.assertThat(logs.get(1).getMessage()).contains("¡Despierta humano!"); Truth.assertThat(logs.get(2).getMessage()).isEqualTo("Text translated to es"); }