tpalfy commented on code in PR #6762:
URL: https://github.com/apache/nifi/pull/6762#discussion_r1050011016


##########
nifi-nar-bundles/nifi-gcp-bundle/nifi-gcp-processors/src/main/java/org/apache/nifi/processors/gcp/vision/AbstractStartGcpVisionOperation.java:
##########
@@ -0,0 +1,53 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+
+package org.apache.nifi.processors.gcp.vision;
+
+import com.google.api.gax.longrunning.OperationFuture;
+import com.google.api.gax.longrunning.OperationSnapshot;
+import com.google.protobuf.InvalidProtocolBufferException;
+import com.google.protobuf.Message;
+import java.io.IOException;
+import org.apache.nifi.flowfile.FlowFile;
+import org.apache.nifi.processor.ProcessContext;
+import org.apache.nifi.processor.ProcessSession;
+import org.apache.nifi.processor.exception.ProcessException;
+
+public abstract class AbstractStartGcpVisionOperation extends 
AbstractGcpVisionProcessor  {
+
+
+    @Override
+    public void onTrigger(ProcessContext context, ProcessSession session) 
throws ProcessException {
+        FlowFile flowFile = session.get();
+        if (flowFile == null) {
+            return;
+        }
+        try  {
+            OperationFuture asyncResponse = startOperation(session, flowFile);
+            String operationName = ((OperationSnapshot) 
asyncResponse.getInitialFuture().get()).getName();
+            session.putAttribute(flowFile, GCP_OPERATION_KEY, operationName);
+            session.transfer(flowFile, REL_SUCCESS);
+        } catch (Exception e) {
+            getLogger().error("Fail to start GCP Vision operation", e);
+            session.transfer(flowFile, REL_FAILURE);
+        }
+    }
+
+    abstract protected Message fromJson(String json) throws IOException;

Review Comment:
    No need for this method to be declared here. In fact their implementation 
might be better off inlined into the `startOperation` implementations.



##########
nifi-nar-bundles/nifi-gcp-bundle/nifi-gcp-processors/src/main/java/org/apache/nifi/processors/gcp/vision/AbstractStartGcpVisionOperation.java:
##########
@@ -0,0 +1,53 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+
+package org.apache.nifi.processors.gcp.vision;
+
+import com.google.api.gax.longrunning.OperationFuture;
+import com.google.api.gax.longrunning.OperationSnapshot;
+import com.google.protobuf.InvalidProtocolBufferException;
+import com.google.protobuf.Message;
+import java.io.IOException;
+import org.apache.nifi.flowfile.FlowFile;
+import org.apache.nifi.processor.ProcessContext;
+import org.apache.nifi.processor.ProcessSession;
+import org.apache.nifi.processor.exception.ProcessException;
+
+public abstract class AbstractStartGcpVisionOperation extends 
AbstractGcpVisionProcessor  {
+
+
+    @Override
+    public void onTrigger(ProcessContext context, ProcessSession session) 
throws ProcessException {
+        FlowFile flowFile = session.get();
+        if (flowFile == null) {
+            return;
+        }
+        try  {
+            OperationFuture asyncResponse = startOperation(session, flowFile);
+            String operationName = ((OperationSnapshot) 
asyncResponse.getInitialFuture().get()).getName();

Review Comment:
   ```suggestion
               OperationFuture<?, ?> asyncResponse = startOperation(session, 
flowFile);
               String operationName = asyncResponse.getName();
   ```



##########
nifi-nar-bundles/nifi-gcp-bundle/nifi-gcp-processors/src/main/java/org/apache/nifi/processors/gcp/vision/AbstractGcpVisionProcessor.java:
##########
@@ -0,0 +1,96 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+
+package org.apache.nifi.processors.gcp.vision;
+
+import static 
org.apache.nifi.processors.gcp.util.GoogleUtils.GCP_CREDENTIALS_PROVIDER_SERVICE;
+
+import com.google.api.gax.core.FixedCredentialsProvider;
+import com.google.auth.oauth2.GoogleCredentials;
+import com.google.cloud.vision.v1.ImageAnnotatorClient;
+import com.google.cloud.vision.v1.ImageAnnotatorSettings;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import org.apache.commons.io.IOUtils;
+import org.apache.nifi.annotation.lifecycle.OnScheduled;
+import org.apache.nifi.components.PropertyDescriptor;
+import org.apache.nifi.flowfile.FlowFile;
+import org.apache.nifi.gcp.credentials.service.GCPCredentialsService;
+import org.apache.nifi.processor.AbstractProcessor;
+import org.apache.nifi.processor.ProcessContext;
+import org.apache.nifi.processor.ProcessSession;
+import org.apache.nifi.processor.Relationship;
+import org.apache.nifi.processor.exception.ProcessException;
+
+public abstract class AbstractGcpVisionProcessor extends AbstractProcessor  {
+    public static final String GCP_OPERATION_KEY = "operationKey";
+
+    public static final Relationship REL_SUCCESS = new 
Relationship.Builder().name("success")
+            .description("FlowFiles are routed to success 
relationship").build();
+    public static final Relationship REL_FAILURE = new 
Relationship.Builder().name("failure")
+            .description("FlowFiles are routed to failure 
relationship").build();
+
+    protected static final Set<Relationship> relationships = 
Collections.unmodifiableSet(new HashSet<>(Arrays.asList(
+            REL_SUCCESS,
+            REL_FAILURE
+    )));
+
+    private ImageAnnotatorClient vision;
+
+    @Override
+    public List<PropertyDescriptor> getSupportedPropertyDescriptors() {
+        return Collections.unmodifiableList(Arrays.asList(
+                GCP_CREDENTIALS_PROVIDER_SERVICE)
+        );
+    }
+
+    @Override
+    public Set<Relationship> getRelationships() {
+        return relationships;
+    }
+
+    @OnScheduled
+    public void onScheduled(ProcessContext context) {
+        final GCPCredentialsService gcpCredentialsService =
+                
context.getProperty(GCP_CREDENTIALS_PROVIDER_SERVICE).asControllerService(GCPCredentialsService.class);
+        try {
+            GoogleCredentials credentials = 
gcpCredentialsService.getGoogleCredentials();
+            FixedCredentialsProvider credentialsProvider = 
FixedCredentialsProvider.create(credentials);
+            ImageAnnotatorSettings.Builder builder = 
ImageAnnotatorSettings.newBuilder().setCredentialsProvider(credentialsProvider);
+            vision = ImageAnnotatorClient.create(builder.build());
+        } catch (Exception e) {
+            getLogger().error("Failed to create vision client.", e);

Review Comment:
   The framework should know that the processor is incapable of doing it's job 
when this happens.
   We should throw a ProcessException.



##########
nifi-nar-bundles/nifi-gcp-bundle/nifi-gcp-processors/src/main/java/org/apache/nifi/processors/gcp/vision/AbstractGcpVisionProcessor.java:
##########
@@ -0,0 +1,96 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+
+package org.apache.nifi.processors.gcp.vision;
+
+import static 
org.apache.nifi.processors.gcp.util.GoogleUtils.GCP_CREDENTIALS_PROVIDER_SERVICE;
+
+import com.google.api.gax.core.FixedCredentialsProvider;
+import com.google.auth.oauth2.GoogleCredentials;
+import com.google.cloud.vision.v1.ImageAnnotatorClient;
+import com.google.cloud.vision.v1.ImageAnnotatorSettings;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import org.apache.commons.io.IOUtils;
+import org.apache.nifi.annotation.lifecycle.OnScheduled;
+import org.apache.nifi.components.PropertyDescriptor;
+import org.apache.nifi.flowfile.FlowFile;
+import org.apache.nifi.gcp.credentials.service.GCPCredentialsService;
+import org.apache.nifi.processor.AbstractProcessor;
+import org.apache.nifi.processor.ProcessContext;
+import org.apache.nifi.processor.ProcessSession;
+import org.apache.nifi.processor.Relationship;
+import org.apache.nifi.processor.exception.ProcessException;
+
+public abstract class AbstractGcpVisionProcessor extends AbstractProcessor  {
+    public static final String GCP_OPERATION_KEY = "operationKey";
+
+    public static final Relationship REL_SUCCESS = new 
Relationship.Builder().name("success")
+            .description("FlowFiles are routed to success 
relationship").build();
+    public static final Relationship REL_FAILURE = new 
Relationship.Builder().name("failure")
+            .description("FlowFiles are routed to failure 
relationship").build();
+
+    protected static final Set<Relationship> relationships = 
Collections.unmodifiableSet(new HashSet<>(Arrays.asList(
+            REL_SUCCESS,
+            REL_FAILURE
+    )));
+
+    private ImageAnnotatorClient vision;

Review Comment:
   `vision` should be closed in an `@OnStopped` method.



##########
nifi-nar-bundles/nifi-gcp-bundle/nifi-gcp-processors/src/main/java/org/apache/nifi/processors/gcp/vision/AbstractGcpVisionProcessor.java:
##########
@@ -0,0 +1,96 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+
+package org.apache.nifi.processors.gcp.vision;
+
+import static 
org.apache.nifi.processors.gcp.util.GoogleUtils.GCP_CREDENTIALS_PROVIDER_SERVICE;
+
+import com.google.api.gax.core.FixedCredentialsProvider;
+import com.google.auth.oauth2.GoogleCredentials;
+import com.google.cloud.vision.v1.ImageAnnotatorClient;
+import com.google.cloud.vision.v1.ImageAnnotatorSettings;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import org.apache.commons.io.IOUtils;
+import org.apache.nifi.annotation.lifecycle.OnScheduled;
+import org.apache.nifi.components.PropertyDescriptor;
+import org.apache.nifi.flowfile.FlowFile;
+import org.apache.nifi.gcp.credentials.service.GCPCredentialsService;
+import org.apache.nifi.processor.AbstractProcessor;
+import org.apache.nifi.processor.ProcessContext;
+import org.apache.nifi.processor.ProcessSession;
+import org.apache.nifi.processor.Relationship;
+import org.apache.nifi.processor.exception.ProcessException;
+
+public abstract class AbstractGcpVisionProcessor extends AbstractProcessor  {
+    public static final String GCP_OPERATION_KEY = "operationKey";
+
+    public static final Relationship REL_SUCCESS = new 
Relationship.Builder().name("success")
+            .description("FlowFiles are routed to success 
relationship").build();
+    public static final Relationship REL_FAILURE = new 
Relationship.Builder().name("failure")
+            .description("FlowFiles are routed to failure 
relationship").build();
+
+    protected static final Set<Relationship> relationships = 
Collections.unmodifiableSet(new HashSet<>(Arrays.asList(
+            REL_SUCCESS,
+            REL_FAILURE
+    )));
+
+    private ImageAnnotatorClient vision;
+
+    @Override
+    public List<PropertyDescriptor> getSupportedPropertyDescriptors() {
+        return Collections.unmodifiableList(Arrays.asList(

Review Comment:
   This collection should be extracted to a `PROPERTIES` constant.



##########
nifi-nar-bundles/nifi-gcp-bundle/nifi-gcp-processors/src/main/java/org/apache/nifi/processors/gcp/vision/AbstractStartGcpVisionOperation.java:
##########
@@ -0,0 +1,53 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+
+package org.apache.nifi.processors.gcp.vision;
+
+import com.google.api.gax.longrunning.OperationFuture;
+import com.google.api.gax.longrunning.OperationSnapshot;
+import com.google.protobuf.InvalidProtocolBufferException;
+import com.google.protobuf.Message;
+import java.io.IOException;
+import org.apache.nifi.flowfile.FlowFile;
+import org.apache.nifi.processor.ProcessContext;
+import org.apache.nifi.processor.ProcessSession;
+import org.apache.nifi.processor.exception.ProcessException;
+
+public abstract class AbstractStartGcpVisionOperation extends 
AbstractGcpVisionProcessor  {
+
+
+    @Override
+    public void onTrigger(ProcessContext context, ProcessSession session) 
throws ProcessException {
+        FlowFile flowFile = session.get();
+        if (flowFile == null) {
+            return;
+        }
+        try  {
+            OperationFuture asyncResponse = startOperation(session, flowFile);
+            String operationName = ((OperationSnapshot) 
asyncResponse.getInitialFuture().get()).getName();
+            session.putAttribute(flowFile, GCP_OPERATION_KEY, operationName);
+            session.transfer(flowFile, REL_SUCCESS);
+        } catch (Exception e) {
+            getLogger().error("Fail to start GCP Vision operation", e);
+            session.transfer(flowFile, REL_FAILURE);
+        }
+    }
+
+    abstract protected Message fromJson(String json) throws IOException;
+
+    abstract protected OperationFuture startOperation(ProcessSession session, 
FlowFile flowFile) throws InvalidProtocolBufferException;

Review Comment:
   There are multiple issues here. Each one is minor on it's own but overall an 
improvement is warranted in my option.
   
   First the issues:
   1.  The `startOperation` implementation have logic duplications. (Not too 
big but still.)
   2. `AbstractGcpVisionProcessor` has a `readFlowFile` method which it doesn't 
use and overall not something that should be the concern of that class. We 
could move that method into `AbstractStartGcpVisionOperation` - only subclasses 
of that uses that method, but we basically using the parent as a utility 
repository.
   
   My recommended improvement is to remove the `readFlowFile` entirely, 
implement `startOperation` in `AbstractStartGcpVisionOperation` itself while 
declaring abstract methods for logic that absolutely requires it. Here's what I 
came up with:
    ```suggestion
    public abstract class AbstractStartGcpVisionOperation<B extends 
com.google.protobuf.GeneratedMessageV3.Builder<B>> extends 
AbstractGcpVisionProcessor  {
   ... 
       protected OperationFuture<?, ?> startOperation(ProcessSession session, 
FlowFile flowFile) throws InvalidProtocolBufferException {
           B builder = newBuilder();
   
           try (InputStream inputStream = session.read(flowFile)) {
               JsonFormat.parser().ignoringUnknownFields().merge(new 
InputStreamReader(inputStream), builder);
           } catch (final IOException e) {
               throw new ProcessException("Read FlowFile Failed", e);
           }
   
           return startOperation(builder);
       }
   
       abstract B newBuilder();
   
       abstract OperationFuture<?, ?> startOperation(B builder);
   ```
   
   The two implementation would be fairly straightforward:
   
   ```java
   public class StartGcpVisionAnnotateFilesOperation extends 
AbstractStartGcpVisionOperation<AsyncBatchAnnotateFilesRequest.Builder> {
   
       @Override
       AsyncBatchAnnotateFilesRequest.Builder newBuilder() {
           return AsyncBatchAnnotateFilesRequest.newBuilder();
       }
   
       @Override
       OperationFuture<?, ?> 
startOperation(AsyncBatchAnnotateFilesRequest.Builder builder) {
           return 
getVisionClient().asyncBatchAnnotateFilesAsync(builder.build());
       }
   }
   
   public class StartGcpVisionAnnotateImagesOperation extends 
AbstractStartGcpVisionOperation<AsyncBatchAnnotateImagesRequest.Builder> {
   
       @Override
       AsyncBatchAnnotateImagesRequest.Builder newBuilder() {
           return AsyncBatchAnnotateImagesRequest.newBuilder();
       }
   
       @Override
       OperationFuture<?, ?> 
startOperation(AsyncBatchAnnotateImagesRequest.Builder builder) {
           return 
getVisionClient().asyncBatchAnnotateImagesAsync(builder.build());
       }
   }
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to