From 41b49ca44f72c9dbc83965eef7424482718d7526 Mon Sep 17 00:00:00 2001 From: Gus Class Date: Thu, 6 Jul 2017 11:13:58 -0700 Subject: [PATCH 1/2] Closes image annotator client. --- .../main/java/com/example/vision/Detect.java | 198 +++++++++++------- .../com/example/vision/QuickstartSample.java | 3 + .../java/com/example/vision/DetectIT.java | 4 +- 3 files changed, 129 insertions(+), 76 deletions(-) diff --git a/vision/cloud-client/src/main/java/com/example/vision/Detect.java b/vision/cloud-client/src/main/java/com/example/vision/Detect.java index f50f03e7c9f..3ee293a8674 100644 --- a/vision/cloud-client/src/main/java/com/example/vision/Detect.java +++ b/vision/cloud-client/src/main/java/com/example/vision/Detect.java @@ -27,7 +27,6 @@ import com.google.cloud.vision.v1.Feature.Type; import com.google.cloud.vision.v1.Image; import com.google.cloud.vision.v1.ImageAnnotatorClient; -import com.google.cloud.vision.v1.ImageAnnotatorSettings; import com.google.cloud.vision.v1.ImageSource; import com.google.cloud.vision.v1.LocationInfo; import com.google.cloud.vision.v1.Page; @@ -41,7 +40,6 @@ import com.google.cloud.vision.v1.WebDetection.WebPage; import com.google.cloud.vision.v1.Word; import com.google.protobuf.ByteString; -import org.threeten.bp.Duration; import java.io.FileInputStream; import java.io.IOException; @@ -54,18 +52,20 @@ public class Detect { /** * Detects entities,sentiment and syntax in a document using the Natural Language API. * + * @throws Exception on errors while closing the client. * @throws IOException on Input/Output errors. */ - public static void main(String[] args) throws IOException { + public static void main(String[] args) throws Exception, IOException { argsHelper(args, System.out); } /** * Helper that handles the input passed to the program. * + * @throws Exception on errors while closing the client. * @throws IOException on Input/Output errors. */ - public static void argsHelper(String[] args, PrintStream out) throws IOException { + public static void argsHelper(String[] args, PrintStream out) throws Exception, IOException { if (args.length < 1) { out.println("Usage:"); out.printf( @@ -160,9 +160,10 @@ public Detect() { * * @param filePath The path to the file to perform face detection on. * @param out A {@link PrintStream} to write detected features to. + * @throws Exception on errors while closing the client. * @throws IOException on Input/Output errors. */ - public static void detectFaces(String filePath, PrintStream out) throws IOException { + public static void detectFaces(String filePath, PrintStream out) throws Exception, IOException { List requests = new ArrayList<>(); ByteString imgBytes = ByteString.readFrom(new FileInputStream(filePath)); @@ -173,9 +174,10 @@ public static void detectFaces(String filePath, PrintStream out) throws IOExcept AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); - BatchAnnotateImagesResponse response = - ImageAnnotatorClient.create().batchAnnotateImages(requests); + ImageAnnotatorClient client = ImageAnnotatorClient.create(); + BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); List responses = response.getResponsesList(); + client.close(); for (AnnotateImageResponse res : responses) { if (res.hasError()) { @@ -200,19 +202,13 @@ public static void detectFaces(String filePath, PrintStream out) throws IOExcept * * @param gcsPath The path to the remote file to perform face detection on. * @param out A {@link PrintStream} to write detected features to. + * @throws Exception on errors while closing the client. * @throws IOException on Input/Output errors. */ - public static void detectFacesGcs(String gcsPath, PrintStream out) throws IOException { + public static void detectFacesGcs(String gcsPath, PrintStream out) throws Exception, + IOException { List requests = new ArrayList<>(); - ImageAnnotatorSettings.Builder imageAnnotatorSettingsBuilder = - ImageAnnotatorSettings.defaultBuilder(); - imageAnnotatorSettingsBuilder - .batchAnnotateImagesSettings() - .getRetrySettingsBuilder() - .setTotalTimeout(Duration.ofSeconds(30)); - ImageAnnotatorSettings settings = imageAnnotatorSettingsBuilder.build(); - ImageSource imgSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build(); Image img = Image.newBuilder().setSource(imgSource).build(); Feature feat = Feature.newBuilder().setType(Type.FACE_DETECTION).build(); @@ -221,9 +217,10 @@ public static void detectFacesGcs(String gcsPath, PrintStream out) throws IOExce AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); - ImageAnnotatorClient client = ImageAnnotatorClient.create(settings); + ImageAnnotatorClient client = ImageAnnotatorClient.create(); BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); List responses = response.getResponsesList(); + client.close(); for (AnnotateImageResponse res : responses) { if (res.hasError()) { @@ -248,9 +245,10 @@ public static void detectFacesGcs(String gcsPath, PrintStream out) throws IOExce * * @param filePath The path to the file to perform label detection on. * @param out A {@link PrintStream} to write detected labels to. + * @throws Exception on errors while closing the client. * @throws IOException on Input/Output errors. */ - public static void detectLabels(String filePath, PrintStream out) throws IOException { + public static void detectLabels(String filePath, PrintStream out) throws Exception, IOException { List requests = new ArrayList<>(); ByteString imgBytes = ByteString.readFrom(new FileInputStream(filePath)); @@ -261,9 +259,10 @@ public static void detectLabels(String filePath, PrintStream out) throws IOExcep AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); - BatchAnnotateImagesResponse response = - ImageAnnotatorClient.create().batchAnnotateImages(requests); + ImageAnnotatorClient client = ImageAnnotatorClient.create(); + BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); List responses = response.getResponsesList(); + client.close(); for (AnnotateImageResponse res : responses) { if (res.hasError()) { @@ -283,9 +282,11 @@ public static void detectLabels(String filePath, PrintStream out) throws IOExcep * * @param gcsPath The path to the remote file to perform label detection on. * @param out A {@link PrintStream} to write detected features to. + * @throws Exception on errors while closing the client. * @throws IOException on Input/Output errors. */ - public static void detectLabelsGcs(String gcsPath, PrintStream out) throws IOException { + public static void detectLabelsGcs(String gcsPath, PrintStream out) throws Exception, + IOException { List requests = new ArrayList<>(); ImageSource imgSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build(); @@ -295,9 +296,10 @@ public static void detectLabelsGcs(String gcsPath, PrintStream out) throws IOExc AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); - BatchAnnotateImagesResponse response = - ImageAnnotatorClient.create().batchAnnotateImages(requests); + ImageAnnotatorClient client = ImageAnnotatorClient.create(); + BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); List responses = response.getResponsesList(); + client.close(); for (AnnotateImageResponse res : responses) { if (res.hasError()) { @@ -318,9 +320,11 @@ public static void detectLabelsGcs(String gcsPath, PrintStream out) throws IOExc * * @param filePath The path to the file to perform landmark detection on. * @param out A {@link PrintStream} to write detected landmarks to. + * @throws Exception on errors while closing the client. * @throws IOException on Input/Output errors. */ - public static void detectLandmarks(String filePath, PrintStream out) throws IOException { + public static void detectLandmarks(String filePath, PrintStream out) throws Exception, + IOException { List requests = new ArrayList<>(); ByteString imgBytes = ByteString.readFrom(new FileInputStream(filePath)); @@ -330,9 +334,10 @@ public static void detectLandmarks(String filePath, PrintStream out) throws IOEx AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); - BatchAnnotateImagesResponse response = - ImageAnnotatorClient.create().batchAnnotateImages(requests); + ImageAnnotatorClient client = ImageAnnotatorClient.create(); + BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); List responses = response.getResponsesList(); + client.close(); for (AnnotateImageResponse res : responses) { if (res.hasError()) { @@ -353,9 +358,11 @@ public static void detectLandmarks(String filePath, PrintStream out) throws IOEx * * @param url The path to the file to perform landmark detection on. * @param out A {@link PrintStream} to write detected landmarks to. + * @throws Exception on errors while closing the client. * @throws IOException on Input/Output errors. */ - public static void detectLandmarksUrl(String url, PrintStream out) throws IOException { + public static void detectLandmarksUrl(String url, PrintStream out) throws Exception, + IOException { List requests = new ArrayList<>(); ImageSource imgSource = ImageSource.newBuilder().setImageUri(url).build(); @@ -365,9 +372,10 @@ public static void detectLandmarksUrl(String url, PrintStream out) throws IOExce AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); - BatchAnnotateImagesResponse response = - ImageAnnotatorClient.create().batchAnnotateImages(requests); + ImageAnnotatorClient client = ImageAnnotatorClient.create(); + BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); List responses = response.getResponsesList(); + client.close(); for (AnnotateImageResponse res : responses) { if (res.hasError()) { @@ -388,9 +396,11 @@ public static void detectLandmarksUrl(String url, PrintStream out) throws IOExce * * @param gcsPath The path to the remote file to perform landmark detection on. * @param out A {@link PrintStream} to write detected landmarks to. + * @throws Exception on errors while closing the client. * @throws IOException on Input/Output errors. */ - public static void detectLandmarksGcs(String gcsPath, PrintStream out) throws IOException { + public static void detectLandmarksGcs(String gcsPath, PrintStream out) throws Exception, + IOException { List requests = new ArrayList<>(); ImageSource imgSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build(); @@ -400,9 +410,10 @@ public static void detectLandmarksGcs(String gcsPath, PrintStream out) throws IO AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); - BatchAnnotateImagesResponse response = - ImageAnnotatorClient.create().batchAnnotateImages(requests); + ImageAnnotatorClient client = ImageAnnotatorClient.create(); + BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); List responses = response.getResponsesList(); + client.close(); for (AnnotateImageResponse res : responses) { if (res.hasError()) { @@ -423,9 +434,10 @@ public static void detectLandmarksGcs(String gcsPath, PrintStream out) throws IO * * @param filePath The path to the local file to perform logo detection on. * @param out A {@link PrintStream} to write detected logos to. + * @throws Exception on errors while closing the client. * @throws IOException on Input/Output errors. */ - public static void detectLogos(String filePath, PrintStream out) throws IOException { + public static void detectLogos(String filePath, PrintStream out) throws Exception, IOException { List requests = new ArrayList<>(); ByteString imgBytes = ByteString.readFrom(new FileInputStream(filePath)); @@ -436,9 +448,10 @@ public static void detectLogos(String filePath, PrintStream out) throws IOExcept AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); - BatchAnnotateImagesResponse response = - ImageAnnotatorClient.create().batchAnnotateImages(requests); + ImageAnnotatorClient client = ImageAnnotatorClient.create(); + BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); List responses = response.getResponsesList(); + client.close(); for (AnnotateImageResponse res : responses) { if (res.hasError()) { @@ -458,9 +471,11 @@ public static void detectLogos(String filePath, PrintStream out) throws IOExcept * * @param gcsPath The path to the remote file to perform logo detection on. * @param out A {@link PrintStream} to write detected logos to. + * @throws Exception on errors while closing the client. * @throws IOException on Input/Output errors. */ - public static void detectLogosGcs(String gcsPath, PrintStream out) throws IOException { + public static void detectLogosGcs(String gcsPath, PrintStream out) throws Exception, + IOException { List requests = new ArrayList<>(); ImageSource imgSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build(); @@ -470,9 +485,10 @@ public static void detectLogosGcs(String gcsPath, PrintStream out) throws IOExce AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); - BatchAnnotateImagesResponse response = - ImageAnnotatorClient.create().batchAnnotateImages(requests); + ImageAnnotatorClient client = ImageAnnotatorClient.create(); + BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); List responses = response.getResponsesList(); + client.close(); for (AnnotateImageResponse res : responses) { if (res.hasError()) { @@ -492,9 +508,10 @@ public static void detectLogosGcs(String gcsPath, PrintStream out) throws IOExce * * @param filePath The path to the file to detect text in. * @param out A {@link PrintStream} to write the detected text to. + * @throws Exception on errors while closing the client. * @throws IOException on Input/Output errors. */ - public static void detectText(String filePath, PrintStream out) throws IOException { + public static void detectText(String filePath, PrintStream out) throws Exception, IOException { List requests = new ArrayList<>(); ByteString imgBytes = ByteString.readFrom(new FileInputStream(filePath)); @@ -505,9 +522,10 @@ public static void detectText(String filePath, PrintStream out) throws IOExcepti AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); - BatchAnnotateImagesResponse response = - ImageAnnotatorClient.create().batchAnnotateImages(requests); + ImageAnnotatorClient client = ImageAnnotatorClient.create(); + BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); List responses = response.getResponsesList(); + client.close(); for (AnnotateImageResponse res : responses) { if (res.hasError()) { @@ -528,9 +546,10 @@ public static void detectText(String filePath, PrintStream out) throws IOExcepti * * @param gcsPath The path to the remote file to detect text in. * @param out A {@link PrintStream} to write the detected text to. + * @throws Exception on errors while closing the client. * @throws IOException on Input/Output errors. */ - public static void detectTextGcs(String gcsPath, PrintStream out) throws IOException { + public static void detectTextGcs(String gcsPath, PrintStream out) throws Exception, IOException { List requests = new ArrayList<>(); ImageSource imgSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build(); @@ -540,9 +559,10 @@ public static void detectTextGcs(String gcsPath, PrintStream out) throws IOExcep AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); - BatchAnnotateImagesResponse response = - ImageAnnotatorClient.create().batchAnnotateImages(requests); + ImageAnnotatorClient client = ImageAnnotatorClient.create(); + BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); List responses = response.getResponsesList(); + client.close(); for (AnnotateImageResponse res : responses) { if (res.hasError()) { @@ -563,9 +583,11 @@ public static void detectTextGcs(String gcsPath, PrintStream out) throws IOExcep * * @param filePath The path to the file to detect properties. * @param out A {@link PrintStream} to write + * @throws Exception on errors while closing the client. * @throws IOException on Input/Output errors. */ - public static void detectProperties(String filePath, PrintStream out) throws IOException { + public static void detectProperties(String filePath, PrintStream out) throws Exception, + IOException { List requests = new ArrayList<>(); ByteString imgBytes = ByteString.readFrom(new FileInputStream(filePath)); @@ -576,9 +598,10 @@ public static void detectProperties(String filePath, PrintStream out) throws IOE AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); - BatchAnnotateImagesResponse response = - ImageAnnotatorClient.create().batchAnnotateImages(requests); + ImageAnnotatorClient client = ImageAnnotatorClient.create(); + BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); List responses = response.getResponsesList(); + client.close(); for (AnnotateImageResponse res : responses) { if (res.hasError()) { @@ -604,9 +627,11 @@ public static void detectProperties(String filePath, PrintStream out) throws IOE * * @param gcsPath The path to the remote file to detect properties on. * @param out A {@link PrintStream} to write + * @throws Exception on errors while closing the client. * @throws IOException on Input/Output errors. */ - public static void detectPropertiesGcs(String gcsPath, PrintStream out) throws IOException { + public static void detectPropertiesGcs(String gcsPath, PrintStream out) throws Exception, + IOException { List requests = new ArrayList<>(); ImageSource imgSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build(); @@ -616,9 +641,10 @@ public static void detectPropertiesGcs(String gcsPath, PrintStream out) throws I AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); - BatchAnnotateImagesResponse response = - ImageAnnotatorClient.create().batchAnnotateImages(requests); + ImageAnnotatorClient client = ImageAnnotatorClient.create(); + BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); List responses = response.getResponsesList(); + client.close(); for (AnnotateImageResponse res : responses) { if (res.hasError()) { @@ -644,9 +670,11 @@ public static void detectPropertiesGcs(String gcsPath, PrintStream out) throws I * * @param filePath The path to the local file used for safe search detection. * @param out A {@link PrintStream} to write the results to. + * @throws Exception on errors while closing the client. * @throws IOException on Input/Output errors. */ - public static void detectSafeSearch(String filePath, PrintStream out) throws IOException { + public static void detectSafeSearch(String filePath, PrintStream out) throws Exception, + IOException { List requests = new ArrayList<>(); ByteString imgBytes = ByteString.readFrom(new FileInputStream(filePath)); @@ -657,9 +685,10 @@ public static void detectSafeSearch(String filePath, PrintStream out) throws IOE AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); - BatchAnnotateImagesResponse response = - ImageAnnotatorClient.create().batchAnnotateImages(requests); + ImageAnnotatorClient client = ImageAnnotatorClient.create(); + BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); List responses = response.getResponsesList(); + client.close(); for (AnnotateImageResponse res : responses) { if (res.hasError()) { @@ -683,9 +712,11 @@ public static void detectSafeSearch(String filePath, PrintStream out) throws IOE * * @param gcsPath The path to the remote file to detect safe-search on. * @param out A {@link PrintStream} to write the results to. + * @throws Exception on errors while closing the client. * @throws IOException on Input/Output errors. */ - public static void detectSafeSearchGcs(String gcsPath, PrintStream out) throws IOException { + public static void detectSafeSearchGcs(String gcsPath, PrintStream out) throws Exception, + IOException { List requests = new ArrayList<>(); ImageSource imgSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build(); @@ -695,9 +726,10 @@ public static void detectSafeSearchGcs(String gcsPath, PrintStream out) throws I AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); - BatchAnnotateImagesResponse response = - ImageAnnotatorClient.create().batchAnnotateImages(requests); + ImageAnnotatorClient client = ImageAnnotatorClient.create(); + BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); List responses = response.getResponsesList(); + client.close(); for (AnnotateImageResponse res : responses) { if (res.hasError()) { @@ -721,9 +753,11 @@ public static void detectSafeSearchGcs(String gcsPath, PrintStream out) throws I * * @param filePath The path to the local file used for web annotation detection. * @param out A {@link PrintStream} to write the results to. + * @throws Exception on errors while closing the client. * @throws IOException on Input/Output errors. */ - public static void detectWebDetections(String filePath, PrintStream out) throws IOException { + public static void detectWebDetections(String filePath, PrintStream out) throws Exception, + IOException { List requests = new ArrayList<>(); ByteString imgBytes = ByteString.readFrom(new FileInputStream(filePath)); @@ -734,9 +768,10 @@ public static void detectWebDetections(String filePath, PrintStream out) throws AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); - BatchAnnotateImagesResponse response = - ImageAnnotatorClient.create().batchAnnotateImages(requests); + ImageAnnotatorClient client = ImageAnnotatorClient.create(); + BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); List responses = response.getResponsesList(); + client.close(); for (AnnotateImageResponse res : responses) { if (res.hasError()) { @@ -774,9 +809,11 @@ public static void detectWebDetections(String filePath, PrintStream out) throws * * @param gcsPath The path to the remote file to detect safe-search on. * @param out A {@link PrintStream} to write the results to. + * @throws Exception on errors while closing the client. * @throws IOException on Input/Output errors. */ - public static void detectWebDetectionsGcs(String gcsPath, PrintStream out) throws IOException { + public static void detectWebDetectionsGcs(String gcsPath, PrintStream out) throws Exception, + IOException { List requests = new ArrayList<>(); ImageSource imgSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build(); @@ -786,9 +823,10 @@ public static void detectWebDetectionsGcs(String gcsPath, PrintStream out) throw AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); - BatchAnnotateImagesResponse response = - ImageAnnotatorClient.create().batchAnnotateImages(requests); + ImageAnnotatorClient client = ImageAnnotatorClient.create(); + BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); List responses = response.getResponsesList(); + client.close(); for (AnnotateImageResponse res : responses) { if (res.hasError()) { @@ -826,9 +864,11 @@ public static void detectWebDetectionsGcs(String gcsPath, PrintStream out) throw * * @param filePath The path to the local file used for web annotation detection. * @param out A {@link PrintStream} to write the results to. + * @throws Exception on errors while closing the client. * @throws IOException on Input/Output errors. */ - public static void detectCropHints(String filePath, PrintStream out) throws IOException { + public static void detectCropHints(String filePath, PrintStream out) throws Exception, + IOException { List requests = new ArrayList<>(); ByteString imgBytes = ByteString.readFrom(new FileInputStream(filePath)); @@ -839,9 +879,10 @@ public static void detectCropHints(String filePath, PrintStream out) throws IOEx AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); - BatchAnnotateImagesResponse response = - ImageAnnotatorClient.create().batchAnnotateImages(requests); + ImageAnnotatorClient client = ImageAnnotatorClient.create(); + BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); List responses = response.getResponsesList(); + client.close(); for (AnnotateImageResponse res : responses) { if (res.hasError()) { @@ -862,9 +903,11 @@ public static void detectCropHints(String filePath, PrintStream out) throws IOEx * * @param gcsPath The path to the remote file to detect safe-search on. * @param out A {@link PrintStream} to write the results to. + * @throws Exception on errors while closing the client. * @throws IOException on Input/Output errors. */ - public static void detectCropHintsGcs(String gcsPath, PrintStream out) throws IOException { + public static void detectCropHintsGcs(String gcsPath, PrintStream out) throws Exception, + IOException { List requests = new ArrayList<>(); ImageSource imgSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build(); @@ -874,9 +917,10 @@ public static void detectCropHintsGcs(String gcsPath, PrintStream out) throws IO AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); - BatchAnnotateImagesResponse response = - ImageAnnotatorClient.create().batchAnnotateImages(requests); + ImageAnnotatorClient client = ImageAnnotatorClient.create(); + BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); List responses = response.getResponsesList(); + client.close(); for (AnnotateImageResponse res : responses) { if (res.hasError()) { @@ -897,9 +941,11 @@ public static void detectCropHintsGcs(String gcsPath, PrintStream out) throws IO * * @param filePath The path to the local file to detect document text on. * @param out A {@link PrintStream} to write the results to. + * @throws Exception on errors while closing the client. * @throws IOException on Input/Output errors. */ - public static void detectDocumentText(String filePath, PrintStream out) throws IOException { + public static void detectDocumentText(String filePath, PrintStream out) throws Exception, + IOException { List requests = new ArrayList<>(); ByteString imgBytes = ByteString.readFrom(new FileInputStream(filePath)); @@ -910,9 +956,10 @@ public static void detectDocumentText(String filePath, PrintStream out) throws I AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); - BatchAnnotateImagesResponse response = - ImageAnnotatorClient.create().batchAnnotateImages(requests); + ImageAnnotatorClient client = ImageAnnotatorClient.create(); + BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); List responses = response.getResponsesList(); + client.close(); for (AnnotateImageResponse res : responses) { if (res.hasError()) { @@ -952,9 +999,11 @@ public static void detectDocumentText(String filePath, PrintStream out) throws I * * @param gcsPath The path to the remote file to detect document text on. * @param out A {@link PrintStream} to write the results to. + * @throws Exception on errors while closing the client. * @throws IOException on Input/Output errors. */ - public static void detectDocumentTextGcs(String gcsPath, PrintStream out) throws IOException { + public static void detectDocumentTextGcs(String gcsPath, PrintStream out) throws Exception, + IOException { List requests = new ArrayList<>(); ImageSource imgSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build(); @@ -964,9 +1013,10 @@ public static void detectDocumentTextGcs(String gcsPath, PrintStream out) throws AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); - BatchAnnotateImagesResponse response = - ImageAnnotatorClient.create().batchAnnotateImages(requests); + ImageAnnotatorClient client = ImageAnnotatorClient.create(); + BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); List responses = response.getResponsesList(); + client.close(); for (AnnotateImageResponse res : responses) { if (res.hasError()) { diff --git a/vision/cloud-client/src/main/java/com/example/vision/QuickstartSample.java b/vision/cloud-client/src/main/java/com/example/vision/QuickstartSample.java index 195b67f16a4..ee64a5f96ef 100644 --- a/vision/cloud-client/src/main/java/com/example/vision/QuickstartSample.java +++ b/vision/cloud-client/src/main/java/com/example/vision/QuickstartSample.java @@ -71,6 +71,9 @@ public static void main(String... args) throws Exception { annotation.getAllFields().forEach((k, v)->System.out.printf("%s : %s\n", k, v.toString())); } } + + // Close the client to free any resources + vision.close(); } } // [END vision_quickstart] diff --git a/vision/cloud-client/src/test/java/com/example/vision/DetectIT.java b/vision/cloud-client/src/test/java/com/example/vision/DetectIT.java index 6315f92363b..656c62a8d8f 100644 --- a/vision/cloud-client/src/test/java/com/example/vision/DetectIT.java +++ b/vision/cloud-client/src/test/java/com/example/vision/DetectIT.java @@ -61,7 +61,7 @@ public void testFaces() throws Exception { String got = bout.toString(); assertThat(got).contains("anger: POSSIBLE"); assertThat(got).contains("joy: POSSIBLE"); - assertThat(got).contains("surprise: UNLIKELY"); + assertThat(got).contains("surprise: LIKELY"); } @Test @@ -74,7 +74,7 @@ public void testFacesGcs() throws Exception { String got = bout.toString(); assertThat(got).contains("anger: POSSIBLE"); assertThat(got).contains("joy: POSSIBLE"); - assertThat(got).contains("surprise: UNLIKELY"); + assertThat(got).contains("surprise: LIKELY"); } @Test From cc66da6371c5160ef87bee670165528a912b0f90 Mon Sep 17 00:00:00 2001 From: Gus Class Date: Mon, 10 Jul 2017 09:55:33 -0700 Subject: [PATCH 2/2] Uses try with resource to ensure client gets closed. --- .../main/java/com/example/vision/Detect.java | 724 +++++++++--------- .../com/example/vision/QuickstartSample.java | 57 +- 2 files changed, 391 insertions(+), 390 deletions(-) diff --git a/vision/cloud-client/src/main/java/com/example/vision/Detect.java b/vision/cloud-client/src/main/java/com/example/vision/Detect.java index 3ee293a8674..9289d09d4f1 100644 --- a/vision/cloud-client/src/main/java/com/example/vision/Detect.java +++ b/vision/cloud-client/src/main/java/com/example/vision/Detect.java @@ -174,25 +174,25 @@ public static void detectFaces(String filePath, PrintStream out) throws Exceptio AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); - ImageAnnotatorClient client = ImageAnnotatorClient.create(); - BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); - List responses = response.getResponsesList(); - client.close(); - - for (AnnotateImageResponse res : responses) { - if (res.hasError()) { - out.printf("Error: %s\n", res.getError().getMessage()); - return; - } + try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { + BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); + List responses = response.getResponsesList(); + + for (AnnotateImageResponse res : responses) { + if (res.hasError()) { + out.printf("Error: %s\n", res.getError().getMessage()); + return; + } - // For full list of available annotations, see http://g.co/cloud/vision/docs - for (FaceAnnotation annotation : res.getFaceAnnotationsList()) { - out.printf( - "anger: %s\njoy: %s\nsurprise: %s\nposition: %s", - annotation.getAngerLikelihood(), - annotation.getJoyLikelihood(), - annotation.getSurpriseLikelihood(), - annotation.getBoundingPoly()); + // For full list of available annotations, see http://g.co/cloud/vision/docs + for (FaceAnnotation annotation : res.getFaceAnnotationsList()) { + out.printf( + "anger: %s\njoy: %s\nsurprise: %s\nposition: %s", + annotation.getAngerLikelihood(), + annotation.getJoyLikelihood(), + annotation.getSurpriseLikelihood(), + annotation.getBoundingPoly()); + } } } } @@ -217,25 +217,25 @@ public static void detectFacesGcs(String gcsPath, PrintStream out) throws Except AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); - ImageAnnotatorClient client = ImageAnnotatorClient.create(); - BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); - List responses = response.getResponsesList(); - client.close(); + try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { + BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); + List responses = response.getResponsesList(); - for (AnnotateImageResponse res : responses) { - if (res.hasError()) { - out.printf("Error: %s\n", res.getError().getMessage()); - return; - } + for (AnnotateImageResponse res : responses) { + if (res.hasError()) { + out.printf("Error: %s\n", res.getError().getMessage()); + return; + } - // For full list of available annotations, see http://g.co/cloud/vision/docs - for (FaceAnnotation annotation : res.getFaceAnnotationsList()) { - out.printf( - "anger: %s\njoy: %s\nsurprise: %s\nposition: %s", - annotation.getAngerLikelihood(), - annotation.getJoyLikelihood(), - annotation.getSurpriseLikelihood(), - annotation.getBoundingPoly()); + // For full list of available annotations, see http://g.co/cloud/vision/docs + for (FaceAnnotation annotation : res.getFaceAnnotationsList()) { + out.printf( + "anger: %s\njoy: %s\nsurprise: %s\nposition: %s", + annotation.getAngerLikelihood(), + annotation.getJoyLikelihood(), + annotation.getSurpriseLikelihood(), + annotation.getBoundingPoly()); + } } } } @@ -259,20 +259,20 @@ public static void detectLabels(String filePath, PrintStream out) throws Excepti AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); - ImageAnnotatorClient client = ImageAnnotatorClient.create(); - BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); - List responses = response.getResponsesList(); - client.close(); + try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { + BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); + List responses = response.getResponsesList(); - for (AnnotateImageResponse res : responses) { - if (res.hasError()) { - out.printf("Error: %s\n", res.getError().getMessage()); - return; - } + for (AnnotateImageResponse res : responses) { + if (res.hasError()) { + out.printf("Error: %s\n", res.getError().getMessage()); + return; + } - // For full list of available annotations, see http://g.co/cloud/vision/docs - for (EntityAnnotation annotation : res.getLabelAnnotationsList()) { - annotation.getAllFields().forEach((k, v) -> out.printf("%s : %s\n", k, v.toString())); + // For full list of available annotations, see http://g.co/cloud/vision/docs + for (EntityAnnotation annotation : res.getLabelAnnotationsList()) { + annotation.getAllFields().forEach((k, v) -> out.printf("%s : %s\n", k, v.toString())); + } } } } @@ -296,21 +296,21 @@ public static void detectLabelsGcs(String gcsPath, PrintStream out) throws Excep AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); - ImageAnnotatorClient client = ImageAnnotatorClient.create(); - BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); - List responses = response.getResponsesList(); - client.close(); + try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { + BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); + List responses = response.getResponsesList(); - for (AnnotateImageResponse res : responses) { - if (res.hasError()) { - out.printf("Error: %s\n", res.getError().getMessage()); - return; - } + for (AnnotateImageResponse res : responses) { + if (res.hasError()) { + out.printf("Error: %s\n", res.getError().getMessage()); + return; + } - // For full list of available annotations, see http://g.co/cloud/vision/docs - for (EntityAnnotation annotation : res.getLabelAnnotationsList()) { - annotation.getAllFields().forEach((k, v) -> - out.printf("%s : %s\n", k, v.toString())); + // For full list of available annotations, see http://g.co/cloud/vision/docs + for (EntityAnnotation annotation : res.getLabelAnnotationsList()) { + annotation.getAllFields().forEach((k, v) -> + out.printf("%s : %s\n", k, v.toString())); + } } } } @@ -334,21 +334,21 @@ public static void detectLandmarks(String filePath, PrintStream out) throws Exce AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); - ImageAnnotatorClient client = ImageAnnotatorClient.create(); - BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); - List responses = response.getResponsesList(); - client.close(); + try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { + BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); + List responses = response.getResponsesList(); - for (AnnotateImageResponse res : responses) { - if (res.hasError()) { - out.printf("Error: %s\n", res.getError().getMessage()); - return; - } + for (AnnotateImageResponse res : responses) { + if (res.hasError()) { + out.printf("Error: %s\n", res.getError().getMessage()); + return; + } - // For full list of available annotations, see http://g.co/cloud/vision/docs - for (EntityAnnotation annotation : res.getLandmarkAnnotationsList()) { - LocationInfo info = annotation.getLocationsList().listIterator().next(); - out.printf("Landmark: %s\n %s\n", annotation.getDescription(), info.getLatLng()); + // For full list of available annotations, see http://g.co/cloud/vision/docs + for (EntityAnnotation annotation : res.getLandmarkAnnotationsList()) { + LocationInfo info = annotation.getLocationsList().listIterator().next(); + out.printf("Landmark: %s\n %s\n", annotation.getDescription(), info.getLatLng()); + } } } } @@ -372,21 +372,21 @@ public static void detectLandmarksUrl(String url, PrintStream out) throws Except AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); - ImageAnnotatorClient client = ImageAnnotatorClient.create(); - BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); - List responses = response.getResponsesList(); - client.close(); + try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { + BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); + List responses = response.getResponsesList(); - for (AnnotateImageResponse res : responses) { - if (res.hasError()) { - out.printf("Error: %s\n", res.getError().getMessage()); - return; - } + for (AnnotateImageResponse res : responses) { + if (res.hasError()) { + out.printf("Error: %s\n", res.getError().getMessage()); + return; + } - // For full list of available annotations, see http://g.co/cloud/vision/docs - for (EntityAnnotation annotation : res.getLandmarkAnnotationsList()) { - LocationInfo info = annotation.getLocationsList().listIterator().next(); - out.printf("Landmark: %s\n %s\n", annotation.getDescription(), info.getLatLng()); + // For full list of available annotations, see http://g.co/cloud/vision/docs + for (EntityAnnotation annotation : res.getLandmarkAnnotationsList()) { + LocationInfo info = annotation.getLocationsList().listIterator().next(); + out.printf("Landmark: %s\n %s\n", annotation.getDescription(), info.getLatLng()); + } } } } @@ -410,21 +410,21 @@ public static void detectLandmarksGcs(String gcsPath, PrintStream out) throws Ex AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); - ImageAnnotatorClient client = ImageAnnotatorClient.create(); - BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); - List responses = response.getResponsesList(); - client.close(); + try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { + BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); + List responses = response.getResponsesList(); - for (AnnotateImageResponse res : responses) { - if (res.hasError()) { - out.printf("Error: %s\n", res.getError().getMessage()); - return; - } + for (AnnotateImageResponse res : responses) { + if (res.hasError()) { + out.printf("Error: %s\n", res.getError().getMessage()); + return; + } - // For full list of available annotations, see http://g.co/cloud/vision/docs - for (EntityAnnotation annotation : res.getLandmarkAnnotationsList()) { - LocationInfo info = annotation.getLocationsList().listIterator().next(); - out.printf("Landmark: %s\n %s\n", annotation.getDescription(), info.getLatLng()); + // For full list of available annotations, see http://g.co/cloud/vision/docs + for (EntityAnnotation annotation : res.getLandmarkAnnotationsList()) { + LocationInfo info = annotation.getLocationsList().listIterator().next(); + out.printf("Landmark: %s\n %s\n", annotation.getDescription(), info.getLatLng()); + } } } } @@ -448,20 +448,20 @@ public static void detectLogos(String filePath, PrintStream out) throws Exceptio AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); - ImageAnnotatorClient client = ImageAnnotatorClient.create(); - BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); - List responses = response.getResponsesList(); - client.close(); + try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { + BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); + List responses = response.getResponsesList(); - for (AnnotateImageResponse res : responses) { - if (res.hasError()) { - out.printf("Error: %s\n", res.getError().getMessage()); - return; - } + for (AnnotateImageResponse res : responses) { + if (res.hasError()) { + out.printf("Error: %s\n", res.getError().getMessage()); + return; + } - // For full list of available annotations, see http://g.co/cloud/vision/docs - for (EntityAnnotation annotation : res.getLogoAnnotationsList()) { - out.println(annotation.getDescription()); + // For full list of available annotations, see http://g.co/cloud/vision/docs + for (EntityAnnotation annotation : res.getLogoAnnotationsList()) { + out.println(annotation.getDescription()); + } } } } @@ -485,20 +485,20 @@ public static void detectLogosGcs(String gcsPath, PrintStream out) throws Except AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); - ImageAnnotatorClient client = ImageAnnotatorClient.create(); - BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); - List responses = response.getResponsesList(); - client.close(); + try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { + BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); + List responses = response.getResponsesList(); - for (AnnotateImageResponse res : responses) { - if (res.hasError()) { - out.printf("Error: %s\n", res.getError().getMessage()); - return; - } + for (AnnotateImageResponse res : responses) { + if (res.hasError()) { + out.printf("Error: %s\n", res.getError().getMessage()); + return; + } - // For full list of available annotations, see http://g.co/cloud/vision/docs - for (EntityAnnotation annotation : res.getLogoAnnotationsList()) { - out.println(annotation.getDescription()); + // For full list of available annotations, see http://g.co/cloud/vision/docs + for (EntityAnnotation annotation : res.getLogoAnnotationsList()) { + out.println(annotation.getDescription()); + } } } } @@ -522,21 +522,21 @@ public static void detectText(String filePath, PrintStream out) throws Exception AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); - ImageAnnotatorClient client = ImageAnnotatorClient.create(); - BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); - List responses = response.getResponsesList(); - client.close(); + try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { + BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); + List responses = response.getResponsesList(); - for (AnnotateImageResponse res : responses) { - if (res.hasError()) { - out.printf("Error: %s\n", res.getError().getMessage()); - return; - } + for (AnnotateImageResponse res : responses) { + if (res.hasError()) { + out.printf("Error: %s\n", res.getError().getMessage()); + return; + } - // For full list of available annotations, see http://g.co/cloud/vision/docs - for (EntityAnnotation annotation : res.getTextAnnotationsList()) { - out.printf("Text: %s\n", annotation.getDescription()); - out.printf("Position : %s\n", annotation.getBoundingPoly()); + // For full list of available annotations, see http://g.co/cloud/vision/docs + for (EntityAnnotation annotation : res.getTextAnnotationsList()) { + out.printf("Text: %s\n", annotation.getDescription()); + out.printf("Position : %s\n", annotation.getBoundingPoly()); + } } } } @@ -559,21 +559,21 @@ public static void detectTextGcs(String gcsPath, PrintStream out) throws Excepti AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); - ImageAnnotatorClient client = ImageAnnotatorClient.create(); - BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); - List responses = response.getResponsesList(); - client.close(); + try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { + BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); + List responses = response.getResponsesList(); - for (AnnotateImageResponse res : responses) { - if (res.hasError()) { - out.printf("Error: %s\n", res.getError().getMessage()); - return; - } + for (AnnotateImageResponse res : responses) { + if (res.hasError()) { + out.printf("Error: %s\n", res.getError().getMessage()); + return; + } - // For full list of available annotations, see http://g.co/cloud/vision/docs - for (EntityAnnotation annotation : res.getTextAnnotationsList()) { - out.printf("Text: %s\n", annotation.getDescription()); - out.printf("Position : %s\n", annotation.getBoundingPoly()); + // For full list of available annotations, see http://g.co/cloud/vision/docs + for (EntityAnnotation annotation : res.getTextAnnotationsList()) { + out.printf("Text: %s\n", annotation.getDescription()); + out.printf("Position : %s\n", annotation.getBoundingPoly()); + } } } } @@ -598,26 +598,26 @@ public static void detectProperties(String filePath, PrintStream out) throws Exc AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); - ImageAnnotatorClient client = ImageAnnotatorClient.create(); - BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); - List responses = response.getResponsesList(); - client.close(); + try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { + BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); + List responses = response.getResponsesList(); - for (AnnotateImageResponse res : responses) { - if (res.hasError()) { - out.printf("Error: %s\n", res.getError().getMessage()); - return; - } + for (AnnotateImageResponse res : responses) { + if (res.hasError()) { + out.printf("Error: %s\n", res.getError().getMessage()); + return; + } - // For full list of available annotations, see http://g.co/cloud/vision/docs - DominantColorsAnnotation colors = res.getImagePropertiesAnnotation().getDominantColors(); - for (ColorInfo color : colors.getColorsList()) { - out.printf( - "fraction: %f\nr: %f, g: %f, b: %f\n", - color.getPixelFraction(), - color.getColor().getRed(), - color.getColor().getGreen(), - color.getColor().getBlue()); + // For full list of available annotations, see http://g.co/cloud/vision/docs + DominantColorsAnnotation colors = res.getImagePropertiesAnnotation().getDominantColors(); + for (ColorInfo color : colors.getColorsList()) { + out.printf( + "fraction: %f\nr: %f, g: %f, b: %f\n", + color.getPixelFraction(), + color.getColor().getRed(), + color.getColor().getGreen(), + color.getColor().getBlue()); + } } } } @@ -641,26 +641,26 @@ public static void detectPropertiesGcs(String gcsPath, PrintStream out) throws E AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); - ImageAnnotatorClient client = ImageAnnotatorClient.create(); - BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); - List responses = response.getResponsesList(); - client.close(); + try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { + BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); + List responses = response.getResponsesList(); - for (AnnotateImageResponse res : responses) { - if (res.hasError()) { - out.printf("Error: %s\n", res.getError().getMessage()); - return; - } + for (AnnotateImageResponse res : responses) { + if (res.hasError()) { + out.printf("Error: %s\n", res.getError().getMessage()); + return; + } - // For full list of available annotations, see http://g.co/cloud/vision/docs - DominantColorsAnnotation colors = res.getImagePropertiesAnnotation().getDominantColors(); - for (ColorInfo color : colors.getColorsList()) { - out.printf( - "fraction: %f\nr: %f, g: %f, b: %f\n", - color.getPixelFraction(), - color.getColor().getRed(), - color.getColor().getGreen(), - color.getColor().getBlue()); + // For full list of available annotations, see http://g.co/cloud/vision/docs + DominantColorsAnnotation colors = res.getImagePropertiesAnnotation().getDominantColors(); + for (ColorInfo color : colors.getColorsList()) { + out.printf( + "fraction: %f\nr: %f, g: %f, b: %f\n", + color.getPixelFraction(), + color.getColor().getRed(), + color.getColor().getGreen(), + color.getColor().getBlue()); + } } } } @@ -685,25 +685,25 @@ public static void detectSafeSearch(String filePath, PrintStream out) throws Exc AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); - ImageAnnotatorClient client = ImageAnnotatorClient.create(); - BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); - List responses = response.getResponsesList(); - client.close(); + try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { + BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); + List responses = response.getResponsesList(); - for (AnnotateImageResponse res : responses) { - if (res.hasError()) { - out.printf("Error: %s\n", res.getError().getMessage()); - return; - } + for (AnnotateImageResponse res : responses) { + if (res.hasError()) { + out.printf("Error: %s\n", res.getError().getMessage()); + return; + } - // For full list of available annotations, see http://g.co/cloud/vision/docs - SafeSearchAnnotation annotation = res.getSafeSearchAnnotation(); - out.printf( - "adult: %s\nmedical: %s\nspoofed: %s\nviolence: %s\n", - annotation.getAdult(), - annotation.getMedical(), - annotation.getSpoof(), - annotation.getViolence()); + // For full list of available annotations, see http://g.co/cloud/vision/docs + SafeSearchAnnotation annotation = res.getSafeSearchAnnotation(); + out.printf( + "adult: %s\nmedical: %s\nspoofed: %s\nviolence: %s\n", + annotation.getAdult(), + annotation.getMedical(), + annotation.getSpoof(), + annotation.getViolence()); + } } } @@ -726,25 +726,25 @@ public static void detectSafeSearchGcs(String gcsPath, PrintStream out) throws E AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); - ImageAnnotatorClient client = ImageAnnotatorClient.create(); - BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); - List responses = response.getResponsesList(); - client.close(); + try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { + BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); + List responses = response.getResponsesList(); - for (AnnotateImageResponse res : responses) { - if (res.hasError()) { - out.printf("Error: %s\n", res.getError().getMessage()); - return; - } + for (AnnotateImageResponse res : responses) { + if (res.hasError()) { + out.printf("Error: %s\n", res.getError().getMessage()); + return; + } - // For full list of available annotations, see http://g.co/cloud/vision/docs - SafeSearchAnnotation annotation = res.getSafeSearchAnnotation(); - out.printf( - "adult: %s\nmedical: %s\nspoofed: %s\nviolence: %s\n", - annotation.getAdult(), - annotation.getMedical(), - annotation.getSpoof(), - annotation.getViolence()); + // For full list of available annotations, see http://g.co/cloud/vision/docs + SafeSearchAnnotation annotation = res.getSafeSearchAnnotation(); + out.printf( + "adult: %s\nmedical: %s\nspoofed: %s\nviolence: %s\n", + annotation.getAdult(), + annotation.getMedical(), + annotation.getSpoof(), + annotation.getViolence()); + } } } @@ -768,38 +768,38 @@ public static void detectWebDetections(String filePath, PrintStream out) throws AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); - ImageAnnotatorClient client = ImageAnnotatorClient.create(); - BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); - List responses = response.getResponsesList(); - client.close(); + try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { + BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); + List responses = response.getResponsesList(); - for (AnnotateImageResponse res : responses) { - if (res.hasError()) { - out.printf("Error: %s\n", res.getError().getMessage()); - return; - } + for (AnnotateImageResponse res : responses) { + if (res.hasError()) { + out.printf("Error: %s\n", res.getError().getMessage()); + return; + } - // Search the web for usages of the image. You could use these signals later - // for user input moderation or linking external references. - // For a full list of available annotations, see http://g.co/cloud/vision/docs - WebDetection annotation = res.getWebDetection(); - out.println("Entity:Id:Score"); - out.println("==============="); - for (WebEntity entity : annotation.getWebEntitiesList()) { - out.println(entity.getDescription() + " : " + entity.getEntityId() + " : " - + entity.getScore()); - } - out.println("\nPages with matching images: Score\n=="); - for (WebPage page : annotation.getPagesWithMatchingImagesList()) { - out.println(page.getUrl() + " : " + page.getScore()); - } - out.println("\nPages with partially matching images: Score\n=="); - for (WebImage image : annotation.getPartialMatchingImagesList()) { - out.println(image.getUrl() + " : " + image.getScore()); - } - out.println("\nPages with fully matching images: Score\n=="); - for (WebImage image : annotation.getFullMatchingImagesList()) { - out.println(image.getUrl() + " : " + image.getScore()); + // Search the web for usages of the image. You could use these signals later + // for user input moderation or linking external references. + // For a full list of available annotations, see http://g.co/cloud/vision/docs + WebDetection annotation = res.getWebDetection(); + out.println("Entity:Id:Score"); + out.println("==============="); + for (WebEntity entity : annotation.getWebEntitiesList()) { + out.println(entity.getDescription() + " : " + entity.getEntityId() + " : " + + entity.getScore()); + } + out.println("\nPages with matching images: Score\n=="); + for (WebPage page : annotation.getPagesWithMatchingImagesList()) { + out.println(page.getUrl() + " : " + page.getScore()); + } + out.println("\nPages with partially matching images: Score\n=="); + for (WebImage image : annotation.getPartialMatchingImagesList()) { + out.println(image.getUrl() + " : " + image.getScore()); + } + out.println("\nPages with fully matching images: Score\n=="); + for (WebImage image : annotation.getFullMatchingImagesList()) { + out.println(image.getUrl() + " : " + image.getScore()); + } } } } @@ -823,38 +823,38 @@ public static void detectWebDetectionsGcs(String gcsPath, PrintStream out) throw AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); - ImageAnnotatorClient client = ImageAnnotatorClient.create(); - BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); - List responses = response.getResponsesList(); - client.close(); + try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { + BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); + List responses = response.getResponsesList(); - for (AnnotateImageResponse res : responses) { - if (res.hasError()) { - out.printf("Error: %s\n", res.getError().getMessage()); - return; - } + for (AnnotateImageResponse res : responses) { + if (res.hasError()) { + out.printf("Error: %s\n", res.getError().getMessage()); + return; + } - // Search the web for usages of the image. You could use these signals later - // for user input moderation or linking external references. - // For a full list of available annotations, see http://g.co/cloud/vision/docs - WebDetection annotation = res.getWebDetection(); - out.println("Entity:Id:Score"); - out.println("==============="); - for (WebEntity entity : annotation.getWebEntitiesList()) { - out.println(entity.getDescription() + " : " + entity.getEntityId() + " : " - + entity.getScore()); - } - out.println("\nPages with matching images: Score\n=="); - for (WebPage page : annotation.getPagesWithMatchingImagesList()) { - out.println(page.getUrl() + " : " + page.getScore()); - } - out.println("\nPages with partially matching images: Score\n=="); - for (WebImage image : annotation.getPartialMatchingImagesList()) { - out.println(image.getUrl() + " : " + image.getScore()); - } - out.println("\nPages with fully matching images: Score\n=="); - for (WebImage image : annotation.getFullMatchingImagesList()) { - out.println(image.getUrl() + " : " + image.getScore()); + // Search the web for usages of the image. You could use these signals later + // for user input moderation or linking external references. + // For a full list of available annotations, see http://g.co/cloud/vision/docs + WebDetection annotation = res.getWebDetection(); + out.println("Entity:Id:Score"); + out.println("==============="); + for (WebEntity entity : annotation.getWebEntitiesList()) { + out.println(entity.getDescription() + " : " + entity.getEntityId() + " : " + + entity.getScore()); + } + out.println("\nPages with matching images: Score\n=="); + for (WebPage page : annotation.getPagesWithMatchingImagesList()) { + out.println(page.getUrl() + " : " + page.getScore()); + } + out.println("\nPages with partially matching images: Score\n=="); + for (WebImage image : annotation.getPartialMatchingImagesList()) { + out.println(image.getUrl() + " : " + image.getScore()); + } + out.println("\nPages with fully matching images: Score\n=="); + for (WebImage image : annotation.getFullMatchingImagesList()) { + out.println(image.getUrl() + " : " + image.getScore()); + } } } } @@ -879,21 +879,21 @@ public static void detectCropHints(String filePath, PrintStream out) throws Exce AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); - ImageAnnotatorClient client = ImageAnnotatorClient.create(); - BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); - List responses = response.getResponsesList(); - client.close(); + try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { + BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); + List responses = response.getResponsesList(); - for (AnnotateImageResponse res : responses) { - if (res.hasError()) { - out.printf("Error: %s\n", res.getError().getMessage()); - return; - } + for (AnnotateImageResponse res : responses) { + if (res.hasError()) { + out.printf("Error: %s\n", res.getError().getMessage()); + return; + } - // For full list of available annotations, see http://g.co/cloud/vision/docs - CropHintsAnnotation annotation = res.getCropHintsAnnotation(); - for (CropHint hint : annotation.getCropHintsList()) { - out.println(hint.getBoundingPoly()); + // For full list of available annotations, see http://g.co/cloud/vision/docs + CropHintsAnnotation annotation = res.getCropHintsAnnotation(); + for (CropHint hint : annotation.getCropHintsList()) { + out.println(hint.getBoundingPoly()); + } } } } @@ -917,21 +917,21 @@ public static void detectCropHintsGcs(String gcsPath, PrintStream out) throws Ex AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); - ImageAnnotatorClient client = ImageAnnotatorClient.create(); - BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); - List responses = response.getResponsesList(); - client.close(); + try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { + BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); + List responses = response.getResponsesList(); - for (AnnotateImageResponse res : responses) { - if (res.hasError()) { - out.printf("Error: %s\n", res.getError().getMessage()); - return; - } + for (AnnotateImageResponse res : responses) { + if (res.hasError()) { + out.printf("Error: %s\n", res.getError().getMessage()); + return; + } - // For full list of available annotations, see http://g.co/cloud/vision/docs - CropHintsAnnotation annotation = res.getCropHintsAnnotation(); - for (CropHint hint : annotation.getCropHintsList()) { - out.println(hint.getBoundingPoly()); + // For full list of available annotations, see http://g.co/cloud/vision/docs + CropHintsAnnotation annotation = res.getCropHintsAnnotation(); + for (CropHint hint : annotation.getCropHintsList()) { + out.println(hint.getBoundingPoly()); + } } } } @@ -956,41 +956,42 @@ public static void detectDocumentText(String filePath, PrintStream out) throws E AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); - ImageAnnotatorClient client = ImageAnnotatorClient.create(); - BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); - List responses = response.getResponsesList(); - client.close(); + try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { + BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); + List responses = response.getResponsesList(); + client.close(); - for (AnnotateImageResponse res : responses) { - if (res.hasError()) { - out.printf("Error: %s\n", res.getError().getMessage()); - return; - } + for (AnnotateImageResponse res : responses) { + if (res.hasError()) { + out.printf("Error: %s\n", res.getError().getMessage()); + return; + } - // For full list of available annotations, see http://g.co/cloud/vision/docs - TextAnnotation annotation = res.getFullTextAnnotation(); - for (Page page: annotation.getPagesList()) { - String pageText = ""; - for (Block block : page.getBlocksList()) { - String blockText = ""; - for (Paragraph para : block.getParagraphsList()) { - String paraText = ""; - for (Word word: para.getWordsList()) { - String wordText = ""; - for (Symbol symbol: word.getSymbolsList()) { - wordText = wordText + symbol.getText(); + // For full list of available annotations, see http://g.co/cloud/vision/docs + TextAnnotation annotation = res.getFullTextAnnotation(); + for (Page page: annotation.getPagesList()) { + String pageText = ""; + for (Block block : page.getBlocksList()) { + String blockText = ""; + for (Paragraph para : block.getParagraphsList()) { + String paraText = ""; + for (Word word: para.getWordsList()) { + String wordText = ""; + for (Symbol symbol: word.getSymbolsList()) { + wordText = wordText + symbol.getText(); + } + paraText = paraText + wordText; } - paraText = paraText + wordText; + // Output Example using Paragraph: + out.println("Paragraph: \n" + paraText); + out.println("Bounds: \n" + para.getBoundingBox() + "\n"); + blockText = blockText + paraText; } - // Output Example using Paragraph: - out.println("Paragraph: \n" + paraText); - out.println("Bounds: \n" + para.getBoundingBox() + "\n"); - blockText = blockText + paraText; + pageText = pageText + blockText; } - pageText = pageText + blockText; } + out.println(annotation.getText()); } - out.println(annotation.getText()); } } @@ -1013,40 +1014,41 @@ public static void detectDocumentTextGcs(String gcsPath, PrintStream out) throws AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); - ImageAnnotatorClient client = ImageAnnotatorClient.create(); - BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); - List responses = response.getResponsesList(); - client.close(); + try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { + BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); + List responses = response.getResponsesList(); + client.close(); - for (AnnotateImageResponse res : responses) { - if (res.hasError()) { - out.printf("Error: %s\n", res.getError().getMessage()); - return; - } - // For full list of available annotations, see http://g.co/cloud/vision/docs - TextAnnotation annotation = res.getFullTextAnnotation(); - for (Page page: annotation.getPagesList()) { - String pageText = ""; - for (Block block : page.getBlocksList()) { - String blockText = ""; - for (Paragraph para : block.getParagraphsList()) { - String paraText = ""; - for (Word word: para.getWordsList()) { - String wordText = ""; - for (Symbol symbol: word.getSymbolsList()) { - wordText = wordText + symbol.getText(); + for (AnnotateImageResponse res : responses) { + if (res.hasError()) { + out.printf("Error: %s\n", res.getError().getMessage()); + return; + } + // For full list of available annotations, see http://g.co/cloud/vision/docs + TextAnnotation annotation = res.getFullTextAnnotation(); + for (Page page: annotation.getPagesList()) { + String pageText = ""; + for (Block block : page.getBlocksList()) { + String blockText = ""; + for (Paragraph para : block.getParagraphsList()) { + String paraText = ""; + for (Word word: para.getWordsList()) { + String wordText = ""; + for (Symbol symbol: word.getSymbolsList()) { + wordText = wordText + symbol.getText(); + } + paraText = paraText + wordText; } - paraText = paraText + wordText; + // Output Example using Paragraph: + out.println("Paragraph: \n" + paraText); + out.println("Bounds: \n" + para.getBoundingBox() + "\n"); + blockText = blockText + paraText; } - // Output Example using Paragraph: - out.println("Paragraph: \n" + paraText); - out.println("Bounds: \n" + para.getBoundingBox() + "\n"); - blockText = blockText + paraText; + pageText = pageText + blockText; } - pageText = pageText + blockText; } + out.println(annotation.getText()); } - out.println(annotation.getText()); } } } diff --git a/vision/cloud-client/src/main/java/com/example/vision/QuickstartSample.java b/vision/cloud-client/src/main/java/com/example/vision/QuickstartSample.java index ee64a5f96ef..53e840c43e0 100644 --- a/vision/cloud-client/src/main/java/com/example/vision/QuickstartSample.java +++ b/vision/cloud-client/src/main/java/com/example/vision/QuickstartSample.java @@ -37,43 +37,42 @@ public class QuickstartSample { public static void main(String... args) throws Exception { // Instantiates a client - ImageAnnotatorClient vision = ImageAnnotatorClient.create(); + try (ImageAnnotatorClient vision = ImageAnnotatorClient.create()) { - // The path to the image file to annotate - String fileName = "./resources/wakeupcat.jpg"; + // The path to the image file to annotate + String fileName = "./resources/wakeupcat.jpg"; - // Reads the image file into memory - Path path = Paths.get(fileName); - byte[] data = Files.readAllBytes(path); - ByteString imgBytes = ByteString.copyFrom(data); + // Reads the image file into memory + Path path = Paths.get(fileName); + byte[] data = Files.readAllBytes(path); + ByteString imgBytes = ByteString.copyFrom(data); - // Builds the image annotation request - List requests = new ArrayList<>(); - Image img = Image.newBuilder().setContent(imgBytes).build(); - Feature feat = Feature.newBuilder().setType(Type.LABEL_DETECTION).build(); - AnnotateImageRequest request = AnnotateImageRequest.newBuilder() - .addFeatures(feat) - .setImage(img) - .build(); - requests.add(request); + // Builds the image annotation request + List requests = new ArrayList<>(); + Image img = Image.newBuilder().setContent(imgBytes).build(); + Feature feat = Feature.newBuilder().setType(Type.LABEL_DETECTION).build(); + AnnotateImageRequest request = AnnotateImageRequest.newBuilder() + .addFeatures(feat) + .setImage(img) + .build(); + requests.add(request); - // Performs label detection on the image file - BatchAnnotateImagesResponse response = vision.batchAnnotateImages(requests); - List responses = response.getResponsesList(); + // Performs label detection on the image file + BatchAnnotateImagesResponse response = vision.batchAnnotateImages(requests); + List responses = response.getResponsesList(); - for (AnnotateImageResponse res : responses) { - if (res.hasError()) { - System.out.printf("Error: %s\n", res.getError().getMessage()); - return; - } + for (AnnotateImageResponse res : responses) { + if (res.hasError()) { + System.out.printf("Error: %s\n", res.getError().getMessage()); + return; + } - for (EntityAnnotation annotation : res.getLabelAnnotationsList()) { - annotation.getAllFields().forEach((k, v)->System.out.printf("%s : %s\n", k, v.toString())); + for (EntityAnnotation annotation : res.getLabelAnnotationsList()) { + annotation.getAllFields().forEach((k, v)-> + System.out.printf("%s : %s\n", k, v.toString())); + } } } - - // Close the client to free any resources - vision.close(); } } // [END vision_quickstart]