ncover21 commented on code in PR #9825:
URL: https://github.com/apache/nifi/pull/9825#discussion_r2023478141


##########
nifi-extension-bundles/nifi-box-bundle/nifi-box-processors/src/main/java/org/apache/nifi/processors/box/UpdateBoxFileMetadataInstance.java:
##########
@@ -0,0 +1,338 @@
+/*
+ * 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.box;
+
+import com.box.sdk.BoxAPIConnection;
+import com.box.sdk.BoxAPIResponseException;
+import com.box.sdk.BoxFile;
+import com.box.sdk.Metadata;
+import org.apache.nifi.annotation.behavior.InputRequirement;
+import org.apache.nifi.annotation.behavior.WritesAttribute;
+import org.apache.nifi.annotation.behavior.WritesAttributes;
+import org.apache.nifi.annotation.documentation.CapabilityDescription;
+import org.apache.nifi.annotation.documentation.SeeAlso;
+import org.apache.nifi.annotation.documentation.Tags;
+import org.apache.nifi.annotation.lifecycle.OnScheduled;
+import org.apache.nifi.box.controllerservices.BoxClientService;
+import org.apache.nifi.components.PropertyDescriptor;
+import org.apache.nifi.expression.ExpressionLanguageScope;
+import org.apache.nifi.flowfile.FlowFile;
+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;
+import org.apache.nifi.processor.util.StandardValidators;
+import org.apache.nifi.serialization.RecordReader;
+import org.apache.nifi.serialization.RecordReaderFactory;
+import org.apache.nifi.serialization.record.Record;
+
+import java.io.InputStream;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import static java.lang.String.valueOf;
+import static org.apache.nifi.processors.box.BoxFileAttributes.ERROR_CODE;
+import static org.apache.nifi.processors.box.BoxFileAttributes.ERROR_CODE_DESC;
+import static org.apache.nifi.processors.box.BoxFileAttributes.ERROR_MESSAGE;
+import static 
org.apache.nifi.processors.box.BoxFileAttributes.ERROR_MESSAGE_DESC;
+
+@InputRequirement(InputRequirement.Requirement.INPUT_REQUIRED)
+@Tags({"box", "storage", "metadata", "templates", "update"})
+@CapabilityDescription("""
+         Updates metadata template values for a Box file using the record in 
the given flowFile.\s
+         This record represents the desired end state of the template after 
the update.\s
+         The processor will calculate the necessary changes 
(add/replace/remove) to transform
+         the current metadata to the desired state. The input record should be 
a flat key-value object.
+        """)
+@SeeAlso({ListBoxFileMetadataTemplates.class, ListBoxFile.class, 
FetchBoxFile.class})
+@WritesAttributes({
+        @WritesAttribute(attribute = "box.id", description = "The ID of the 
file whose metadata was updated"),
+        @WritesAttribute(attribute = "box.template.name", description = "The 
template name used for metadata update"),
+        @WritesAttribute(attribute = "box.template.scope", description = "The 
template scope used for metadata update"),
+        @WritesAttribute(attribute = ERROR_CODE, description = 
ERROR_CODE_DESC),
+        @WritesAttribute(attribute = ERROR_MESSAGE, description = 
ERROR_MESSAGE_DESC)
+})
+public class UpdateBoxFileMetadataInstance extends AbstractProcessor {
+
+    public static final PropertyDescriptor FILE_ID = new 
PropertyDescriptor.Builder()
+            .name("File ID")
+            .description("The ID of the file for which to update metadata.")
+            .required(true)
+            .defaultValue("${box.id}")
+            
.expressionLanguageSupported(ExpressionLanguageScope.FLOWFILE_ATTRIBUTES)
+            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
+            .build();
+
+    public static final PropertyDescriptor TEMPLATE_NAME = new 
PropertyDescriptor.Builder()
+            .name("Template Name")
+            .description("The name of the metadata template to update.")
+            .required(true)
+            
.expressionLanguageSupported(ExpressionLanguageScope.FLOWFILE_ATTRIBUTES)
+            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
+            .build();
+
+    public static final PropertyDescriptor TEMPLATE_SCOPE = new 
PropertyDescriptor.Builder()
+            .name("Template Scope")
+            .description("The scope of the metadata template to update (e.g., 
'enterprise', 'global').")
+            .required(true)
+            
.expressionLanguageSupported(ExpressionLanguageScope.FLOWFILE_ATTRIBUTES)
+            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
+            .build();
+
+    public static final PropertyDescriptor RECORD_READER = new 
PropertyDescriptor.Builder()
+            .name("Record Reader")
+            .description("The Record Reader to use for parsing the incoming 
data")
+            .required(true)
+            .identifiesControllerService(RecordReaderFactory.class)
+            .build();
+
+    public static final Relationship REL_SUCCESS = new Relationship.Builder()
+            .name("success")
+            .description("A FlowFile is routed to this relationship after 
metadata has been successfully updated.")
+            .build();
+
+    public static final Relationship REL_FAILURE = new Relationship.Builder()
+            .name("failure")
+            .description("A FlowFile is routed to this relationship if an 
error occurs during metadata update.")
+            .build();
+
+    public static final Relationship REL_NOT_FOUND = new Relationship.Builder()
+            .name("not found")
+            .description("FlowFiles for which the specified Box file was not 
found will be routed to this relationship.")
+            .build();
+
+    private static final List<PropertyDescriptor> PROPERTY_DESCRIPTORS = 
List.of(
+            BoxClientService.BOX_CLIENT_SERVICE,
+            FILE_ID,
+            TEMPLATE_NAME,
+            TEMPLATE_SCOPE,
+            RECORD_READER
+    );
+
+    private static final Set<Relationship> RELATIONSHIPS = Set.of(
+            REL_SUCCESS,
+            REL_FAILURE,
+            REL_NOT_FOUND
+    );
+
+    private volatile BoxAPIConnection boxAPIConnection;
+
+    @Override
+    protected List<PropertyDescriptor> getSupportedPropertyDescriptors() {
+        return PROPERTY_DESCRIPTORS;
+    }
+
+    @Override
+    public Set<Relationship> getRelationships() {
+        return RELATIONSHIPS;
+    }
+
+    @OnScheduled
+    public void onScheduled(final ProcessContext context) {
+        final BoxClientService boxClientService = 
context.getProperty(BoxClientService.BOX_CLIENT_SERVICE)
+                .asControllerService(BoxClientService.class);
+        boxAPIConnection = boxClientService.getBoxApiConnection();
+    }
+
+    @Override
+    public void onTrigger(final ProcessContext context, final ProcessSession 
session) throws ProcessException {
+        FlowFile flowFile = session.get();
+        if (flowFile == null) {
+            return;
+        }
+
+        final String fileId = 
context.getProperty(FILE_ID).evaluateAttributeExpressions(flowFile).getValue();
+        final String templateName = 
context.getProperty(TEMPLATE_NAME).evaluateAttributeExpressions(flowFile).getValue();
+        final String templateScope = 
context.getProperty(TEMPLATE_SCOPE).evaluateAttributeExpressions(flowFile).getValue();
+        final RecordReaderFactory recordReaderFactory = 
context.getProperty(RECORD_READER).asControllerService(RecordReaderFactory.class);
+
+        try {
+            final BoxFile boxFile = getBoxFile(fileId);
+
+            // Parse the input record to get the desired state
+            final Map<String, Object> desiredState = readDesiredState(session, 
flowFile, recordReaderFactory);
+
+            if (desiredState.isEmpty()) {
+                flowFile = session.putAttribute(flowFile, ERROR_MESSAGE, "No 
valid metadata key-value pairs found in the input");
+                session.transfer(flowFile, REL_FAILURE);
+                return;
+            }
+
+            final Metadata metadata = getOrCreateMetadata(boxFile, 
templateScope, templateName, fileId);
+            final Set<String> processedKeys = updateMetadata(metadata, 
desiredState);
+
+            if (!processedKeys.isEmpty()) {
+                getLogger().info("Updating {} metadata fields for file {}", 
processedKeys.size(), fileId);
+                boxFile.updateMetadata(metadata);
+            } else {
+                getLogger().info("No changes needed for metadata on file {}", 
fileId);
+            }
+
+
+            final Map<String, String> attributes = new HashMap<>();
+            attributes.put("box.id", fileId);
+            attributes.put("box.template.name", templateName);
+            attributes.put("box.template.scope", templateScope);
+            flowFile = session.putAllAttributes(flowFile, attributes);
+
+            session.getProvenanceReporter().modifyAttributes(flowFile, 
BoxFileUtils.BOX_URL + fileId + "/metadata/" + templateScope + "/" + 
templateName);
+            session.transfer(flowFile, REL_SUCCESS);
+
+        } catch (final BoxAPIResponseException e) {
+            flowFile = session.putAttribute(flowFile, ERROR_CODE, 
valueOf(e.getResponseCode()));
+            flowFile = session.putAttribute(flowFile, ERROR_MESSAGE, 
e.getMessage());
+
+            if (e.getResponseCode() == 404) {
+                getLogger().warn("Box file with ID {} was not found.", fileId);
+                session.transfer(flowFile, REL_NOT_FOUND);
+            } else {
+                getLogger().error("Couldn't update metadata for file with id 
[{}]", fileId, e);
+                session.transfer(flowFile, REL_FAILURE);
+            }
+        } catch (Exception e) {
+            getLogger().error("Error processing metadata update for Box file 
[{}]", fileId, e);
+            flowFile = session.putAttribute(flowFile, ERROR_MESSAGE, 
e.getMessage());
+            session.transfer(flowFile, REL_FAILURE);
+        }
+    }
+
+    private Map<String, Object> readDesiredState(final ProcessSession session,
+                                                 final FlowFile flowFile,
+                                                 final RecordReaderFactory 
recordReaderFactory) throws Exception {
+        final Map<String, Object> desiredState = new HashMap<>();
+
+        try (final InputStream inputStream = session.read(flowFile);
+             final RecordReader recordReader = 
recordReaderFactory.createRecordReader(flowFile, inputStream, getLogger())) {
+
+            final Record record = recordReader.nextRecord();
+            if (record != null) {
+                for (String fieldName : record.getSchema().getFieldNames()) {
+                    desiredState.put(fieldName, record.getValue(fieldName));
+                }
+            }
+        }
+
+        return desiredState;
+    }
+
+    private Metadata getOrCreateMetadata(final BoxFile boxFile,
+                                         final String templateScope,
+                                         final String templateName,
+                                         final String fileId) {
+        try {
+            final Metadata metadata = boxFile.getMetadata(templateScope, 
templateName);

Review Comment:
   Removed



-- 
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