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


##########
nifi-extension-bundles/nifi-box-bundle/nifi-box-processors/src/main/java/org/apache/nifi/processors/box/CreateBoxFileMetadataInstance.java:
##########
@@ -0,0 +1,246 @@
+/*
+ * 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.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+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", "create"})
+@CapabilityDescription("""
+        Creates a metadata instance for a Box file using a specified template 
with values from the flowFile content.\s
+        The Box API requires newly created templates to be created with the 
scope set as enterprise so no scope is required.\s
+        The input record should be a flat key-value object where each field 
name is used as the metadata key.
+        """)
+@SeeAlso({ListBoxFileMetadataTemplates.class, 
UpdateBoxFileMetadataInstance.class, ListBoxFile.class, FetchBoxFile.class})
+@WritesAttributes({
+        @WritesAttribute(attribute = "box.id", description = "The ID of the 
file for which metadata was created"),
+        @WritesAttribute(attribute = "box.template.name", description = "The 
template name used for metadata creation"),
+        @WritesAttribute(attribute = ERROR_CODE, description = 
ERROR_CODE_DESC),
+        @WritesAttribute(attribute = ERROR_MESSAGE, description = 
ERROR_MESSAGE_DESC)
+})
+public class CreateBoxFileMetadataInstance extends AbstractProcessor {
+
+    public static final PropertyDescriptor FILE_ID = new 
PropertyDescriptor.Builder()
+            .name("File ID")
+            .description("The ID of the file for which to create 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 use for 
creation.")
+            .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 created.")
+            .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 creation.")
+            .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 Set<Relationship> RELATIONSHIPS = Set.of(
+            REL_SUCCESS,
+            REL_FAILURE,
+            REL_NOT_FOUND
+    );
+
+    private static final List<PropertyDescriptor> PROPERTY_DESCRIPTORS = 
List.of(
+            BoxClientService.BOX_CLIENT_SERVICE,
+            FILE_ID,
+            TEMPLATE_NAME,
+            RECORD_READER
+    );
+
+    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 RecordReaderFactory recordReaderFactory = 
context.getProperty(RECORD_READER).asControllerService(RecordReaderFactory.class);
+
+        try (final InputStream inputStream = session.read(flowFile);
+             final RecordReader recordReader = 
recordReaderFactory.createRecordReader(flowFile, inputStream, getLogger())) {
+
+            final Metadata metadata = new Metadata();
+            final Set<String> createdKeys = new HashSet<>();
+            final List<String> errors = new ArrayList<>();
+
+            Record record = recordReader.nextRecord();
+            if (record != null) {
+                processRecord(record, metadata, createdKeys, errors);
+            } else {
+                errors.add("No records found in input");
+            }
+
+            if (!errors.isEmpty()) {
+                flowFile = session.putAttribute(flowFile, ERROR_MESSAGE, 
String.join(", ", errors));
+                session.transfer(flowFile, REL_FAILURE);
+                return;
+            }
+
+            if (createdKeys.isEmpty()) {
+                flowFile = session.putAttribute(flowFile, ERROR_MESSAGE, "No 
valid metadata key-value pairs found in the input");
+                session.transfer(flowFile, REL_FAILURE);
+                return;
+            }
+
+            final BoxFile boxFile = getBoxFile(fileId);
+            boxFile.createMetadata(templateName, metadata);
+        } 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);

Review Comment:
   Mapped to a new relationship so we can handle it easily 



##########
nifi-extension-bundles/nifi-box-bundle/nifi-box-processors/src/test/java/org/apache/nifi/processors/box/ListBoxFileMetadataInstancesTest.java:
##########
@@ -0,0 +1,173 @@
+/*
+ * 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.BoxAPIException;
+import com.box.sdk.BoxAPIResponseException;
+import com.box.sdk.BoxFile;
+import com.box.sdk.Metadata;
+import com.eclipsesource.json.JsonValue;
+import org.apache.nifi.util.MockFlowFile;
+import org.apache.nifi.util.TestRunners;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+@ExtendWith(MockitoExtension.class)
+public class ListBoxFileMetadataInstancesTest extends AbstractBoxFileTest {
+
+    private static final String TEMPLATE_1_ID = "12345";
+    private static final String TEMPLATE_1_NAME = "fileMetadata";
+    private static final String TEMPLATE_1_SCOPE = "enterprise_123";
+    private static final String TEMPLATE_2_ID = "67890";
+    private static final String TEMPLATE_2_NAME = "properties";
+    private static final String TEMPLATE_2_SCOPE = "global";
+
+    @Mock
+    private BoxFile mockBoxFile;
+
+    @Mock
+    private Metadata mockMetadata1;
+
+    @Mock
+    private Metadata mockMetadata2;
+
+    @Override
+    @BeforeEach
+    void setUp() throws Exception {
+        final ListBoxFileMetadataTemplates testSubject = new 
ListBoxFileMetadataTemplates() {
+            @Override
+            BoxFile getBoxFile(String fileId) {
+                return mockBoxFile;
+            }
+        };
+
+        testRunner = TestRunners.newTestRunner(testSubject);
+        super.setUp();
+    }
+
+    @Test
+    void testSuccessfulMetadataRetrieval() {
+        final List<Metadata> metadataList = new ArrayList<>();
+        metadataList.add(mockMetadata1);
+        metadataList.add(mockMetadata2);
+        JsonValue mockJsonValue1 = mock(JsonValue.class);
+        JsonValue mockJsonValue2 = mock(JsonValue.class);
+        JsonValue mockJsonValue3 = mock(JsonValue.class);
+        JsonValue mockJsonValue4 = mock(JsonValue.class);
+
+        when(mockJsonValue1.asString()).thenReturn("document.pdf");
+        when(mockJsonValue2.asString()).thenReturn("pdf");
+        when(mockJsonValue3.asString()).thenReturn("Test Document");
+        when(mockJsonValue4.asString()).thenReturn("John Doe");
+
+        // Template 1 setup (fileMetadata)
+        when(mockMetadata1.getID()).thenReturn(TEMPLATE_1_ID);
+        when(mockMetadata1.getTemplateName()).thenReturn(TEMPLATE_1_NAME);
+        when(mockMetadata1.getScope()).thenReturn(TEMPLATE_1_SCOPE);
+        List<String> template1Fields = List.of("fileName", "fileExtension");
+        when(mockMetadata1.getPropertyPaths()).thenReturn(template1Fields);
+        when(mockMetadata1.getValue("fileName")).thenReturn(mockJsonValue1);
+        
when(mockMetadata1.getValue("fileExtension")).thenReturn(mockJsonValue2);
+
+        // Template 2 setup (properties)
+        when(mockMetadata2.getID()).thenReturn(TEMPLATE_2_ID);
+        when(mockMetadata2.getTemplateName()).thenReturn(TEMPLATE_2_NAME);
+        when(mockMetadata2.getScope()).thenReturn(TEMPLATE_2_SCOPE);
+
+        List<String> template2Fields = List.of("Test Number", "Title", 
"Author", "Date");
+        when(mockMetadata2.getPropertyPaths()).thenReturn(template2Fields);
+        when(mockMetadata2.getValue("Test Number")).thenReturn(null); // Test 
null handling
+        when(mockMetadata2.getValue("Title")).thenReturn(mockJsonValue3);
+        when(mockMetadata2.getValue("Author")).thenReturn(mockJsonValue4);
+        doReturn(metadataList).when(mockBoxFile).getAllMetadata();

Review Comment:
   Done



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