awelless commented on code in PR #9825: URL: https://github.com/apache/nifi/pull/9825#discussion_r2020738187
########## nifi-extension-bundles/nifi-box-bundle/nifi-box-processors/src/main/java/org/apache/nifi/processors/box/CreateBoxFileMetadataInstance.java: ########## @@ -0,0 +1,283 @@ +/* + * 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.record.path.FieldValue; +import org.apache.nifi.record.path.RecordPath; +import org.apache.nifi.record.path.RecordPathResult; +import org.apache.nifi.record.path.validation.RecordPathValidator; +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. " + + "The Box API requires newly created templates to be created with the scope set as enterprise so no scope is required.") +@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 PropertyDescriptor KEY_RECORD_PATH = new PropertyDescriptor.Builder() + .name("Metadata Key Record Path") + .description("Specifies the RecordPath to use for getting the metadata key to create.") + .required(true) + .addValidator(new RecordPathValidator()) + .defaultValue("/key") + .expressionLanguageSupported(ExpressionLanguageScope.FLOWFILE_ATTRIBUTES) + .build(); + + public static final PropertyDescriptor VALUE_RECORD_PATH = new PropertyDescriptor.Builder() + .name("Metadata Value Record Path") + .description("Specifies the record path to use for getting the metadata value to create.") + .required(true) + .addValidator(new RecordPathValidator()) + .defaultValue("/value") + .expressionLanguageSupported(ExpressionLanguageScope.FLOWFILE_ATTRIBUTES) + .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, + KEY_RECORD_PATH, + VALUE_RECORD_PATH + ); + + 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); + final String keyRecordPathStr = context.getProperty(KEY_RECORD_PATH).evaluateAttributeExpressions(flowFile).getValue(); + final String valueRecordPathStr = context.getProperty(VALUE_RECORD_PATH).evaluateAttributeExpressions(flowFile).getValue(); + + try (final InputStream inputStream = session.read(flowFile); + final RecordReader recordReader = recordReaderFactory.createRecordReader(flowFile, inputStream, getLogger())) { + + final RecordPath keyRecordPath = RecordPath.compile(keyRecordPathStr); + final RecordPath valueRecordPath = RecordPath.compile(valueRecordPathStr); + final Metadata metadata = new Metadata(); + final Set<String> createdKeys = new HashSet<>(); + final List<String> errors = new ArrayList<>(); + + Record record; + try { + while ((record = recordReader.nextRecord()) != null) { + processRecord(record, keyRecordPath, valueRecordPath, metadata, createdKeys, errors); + } Review Comment: So here we expect the incoming metadata to look like: ```json [ {"key": "a", "value": "b"}, ... ] ``` Shall we just use the object format for the metadata, similar to what [the Box API accepts](https://developer.box.com/reference/post-files-id-metadata-id-id/)? This will also make the key and value extraction simpler, as the incoming file or record is going to represent the metadata instance as is. Is there any reason why having a list of metadata fields is more desired? ########## nifi-extension-bundles/nifi-box-bundle/nifi-box-processors/src/main/java/org/apache/nifi/processors/box/UpdateBoxFileMetadataInstance.java: ########## @@ -0,0 +1,296 @@ +/* + * 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.record.path.FieldValue; +import org.apache.nifi.record.path.RecordPath; +import org.apache.nifi.record.path.RecordPathResult; +import org.apache.nifi.record.path.validation.RecordPathValidator; +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", "update"}) +@CapabilityDescription("Updates metadata template values for a Box file using records from the flowFile content.") Review Comment: Does it mean the input is the desired state of the metadata? So the processor is the one to calculate the difference and apply it accordingly? ########## nifi-extension-bundles/nifi-box-bundle/nifi-box-processors/src/main/java/org/apache/nifi/processors/box/CreateBoxMetadataTemplate.java: ########## @@ -0,0 +1,361 @@ +/* + * 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.MetadataTemplate; +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.record.path.FieldValue; +import org.apache.nifi.record.path.RecordPath; +import org.apache.nifi.record.path.RecordPathResult; +import org.apache.nifi.record.path.validation.RecordPathValidator; +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.Arrays; +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 Box metadata template using field specifications from the flowFile content.") +@SeeAlso({ListBoxFileMetadataTemplates.class, UpdateBoxFileMetadataInstance.class}) +@WritesAttributes({ + @WritesAttribute(attribute = "box.template.name", description = "The template name that was created"), + @WritesAttribute(attribute = "box.template.key", description = "The template key that was created"), + @WritesAttribute(attribute = "box.template.scope", description = "The template scope."), + @WritesAttribute(attribute = "box.template.fields.count", description = "Number of fields created for the template"), + @WritesAttribute(attribute = ERROR_CODE, description = ERROR_CODE_DESC), + @WritesAttribute(attribute = ERROR_MESSAGE, description = ERROR_MESSAGE_DESC) +}) +public class CreateBoxMetadataTemplate extends AbstractProcessor { + + public static final String SCOPE_ENTERPRISE = "enterprise"; + + private static final Set<String> VALID_FIELD_TYPES = new HashSet<>(Arrays.asList("string", "float", "date")); + + public static final PropertyDescriptor TEMPLATE_NAME = new PropertyDescriptor.Builder() + .name("Template Name") + .description("The display name of the metadata template to create.") + .required(true) + .expressionLanguageSupported(ExpressionLanguageScope.FLOWFILE_ATTRIBUTES) + .addValidator(StandardValidators.NON_EMPTY_VALIDATOR) + .build(); + + public static final PropertyDescriptor TEMPLATE_KEY = new PropertyDescriptor.Builder() + .name("Template Key") + .description("The key of the metadata template to create (used for API calls).") + .required(true) + .expressionLanguageSupported(ExpressionLanguageScope.FLOWFILE_ATTRIBUTES) + .addValidator(StandardValidators.NON_EMPTY_VALIDATOR) + .build(); + + public static final PropertyDescriptor HIDDEN = new PropertyDescriptor.Builder() + .name("Hidden") + .description("Whether the template should be hidden in the Box UI.") + .required(true) + .allowableValues("true", "false") + .defaultValue("false") + .expressionLanguageSupported(ExpressionLanguageScope.FLOWFILE_ATTRIBUTES) + .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 PropertyDescriptor KEY_RECORD_PATH = new PropertyDescriptor.Builder() + .name("Template Key Field Record Path") + .description("Specifies the RecordPath to use for getting the field key names.") + .required(true) + .addValidator(new RecordPathValidator()) + .defaultValue("/key") + .expressionLanguageSupported(ExpressionLanguageScope.FLOWFILE_ATTRIBUTES) + .build(); + + public static final PropertyDescriptor TYPE_RECORD_PATH = new PropertyDescriptor.Builder() + .name("Template Type Field Record Path") + .description("Specifies the RecordPath to use for getting the field type (string, float, date).") + .required(true) + .addValidator(new RecordPathValidator()) + .defaultValue("/type") + .expressionLanguageSupported(ExpressionLanguageScope.FLOWFILE_ATTRIBUTES) + .build(); + + public static final PropertyDescriptor DISPLAY_NAME_RECORD_PATH = new PropertyDescriptor.Builder() + .name("Template Display Name Field Record Path") + .description("Specifies the RecordPath to use for getting the field display name. If not specified or if the path doesn't resolve to a value, the key will be used.") + .required(false) + .addValidator(new RecordPathValidator()) + .defaultValue("/displayName") + .expressionLanguageSupported(ExpressionLanguageScope.FLOWFILE_ATTRIBUTES) + .build(); + + public static final Relationship REL_SUCCESS = new Relationship.Builder() + .name("success") + .description("A FlowFile is routed to this relationship after a template 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 template creation.") + .build(); + + private static final Set<Relationship> RELATIONSHIPS = Set.of( + REL_SUCCESS, + REL_FAILURE + ); + + private static final List<PropertyDescriptor> PROPERTY_DESCRIPTORS = List.of( + BoxClientService.BOX_CLIENT_SERVICE, + TEMPLATE_NAME, + TEMPLATE_KEY, + HIDDEN, + RECORD_READER, + KEY_RECORD_PATH, + TYPE_RECORD_PATH, + DISPLAY_NAME_RECORD_PATH + ); + + 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) { + boxAPIConnection = getBoxAPIConnection(context); + } + + protected BoxAPIConnection getBoxAPIConnection(final ProcessContext context) { + final BoxClientService boxClientService = context.getProperty(BoxClientService.BOX_CLIENT_SERVICE) + .asControllerService(BoxClientService.class); + return boxClientService.getBoxApiConnection(); + } + + @Override + public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException { + FlowFile flowFile = session.get(); + if (flowFile == null) { + return; + } + + final String templateName = context.getProperty(TEMPLATE_NAME).evaluateAttributeExpressions(flowFile).getValue(); + final String templateKey = context.getProperty(TEMPLATE_KEY).evaluateAttributeExpressions(flowFile).getValue(); + final boolean hidden = Boolean.parseBoolean(context.getProperty(HIDDEN).evaluateAttributeExpressions(flowFile).getValue()); + final RecordReaderFactory recordReaderFactory = context.getProperty(RECORD_READER).asControllerService(RecordReaderFactory.class); + final String keyRecordPathStr = context.getProperty(KEY_RECORD_PATH).evaluateAttributeExpressions(flowFile).getValue(); + final String typeRecordPathStr = context.getProperty(TYPE_RECORD_PATH).evaluateAttributeExpressions(flowFile).getValue(); + + final String displayNameRecordPathStr; + if (context.getProperty(DISPLAY_NAME_RECORD_PATH).isSet()) { + displayNameRecordPathStr = context.getProperty(DISPLAY_NAME_RECORD_PATH).evaluateAttributeExpressions(flowFile).getValue(); + } else { + displayNameRecordPathStr = null; + } Review Comment: Shall we just have a specific record schema, which expects the same schema as [Box Metadata Template fields](https://developer.box.com/reference/post-metadata-templates-schema/#param-fields)? The record parsing must be much more straightforward. Also, adhering to the API makes the usage of the processor more intuitive. ########## nifi-extension-bundles/nifi-box-bundle/nifi-box-processors/src/main/java/org/apache/nifi/processors/box/CreateBoxMetadataTemplate.java: ########## @@ -0,0 +1,361 @@ +/* + * 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.MetadataTemplate; +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.record.path.FieldValue; +import org.apache.nifi.record.path.RecordPath; +import org.apache.nifi.record.path.RecordPathResult; +import org.apache.nifi.record.path.validation.RecordPathValidator; +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.Arrays; +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 Box metadata template using field specifications from the flowFile content.") +@SeeAlso({ListBoxFileMetadataTemplates.class, UpdateBoxFileMetadataInstance.class}) +@WritesAttributes({ + @WritesAttribute(attribute = "box.template.name", description = "The template name that was created"), + @WritesAttribute(attribute = "box.template.key", description = "The template key that was created"), + @WritesAttribute(attribute = "box.template.scope", description = "The template scope."), + @WritesAttribute(attribute = "box.template.fields.count", description = "Number of fields created for the template"), + @WritesAttribute(attribute = ERROR_CODE, description = ERROR_CODE_DESC), + @WritesAttribute(attribute = ERROR_MESSAGE, description = ERROR_MESSAGE_DESC) +}) +public class CreateBoxMetadataTemplate extends AbstractProcessor { + + public static final String SCOPE_ENTERPRISE = "enterprise"; + + private static final Set<String> VALID_FIELD_TYPES = new HashSet<>(Arrays.asList("string", "float", "date")); Review Comment: Since it's going to be a generic processor, I would support `enum,multiSelect` as well. Having a RecordSchema for template fields should make supporting them much easier ########## nifi-extension-bundles/nifi-box-bundle/nifi-box-processors/src/main/java/org/apache/nifi/processors/box/CreateBoxFileMetadataInstance.java: ########## @@ -0,0 +1,283 @@ +/* + * 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.record.path.FieldValue; +import org.apache.nifi.record.path.RecordPath; +import org.apache.nifi.record.path.RecordPathResult; +import org.apache.nifi.record.path.validation.RecordPathValidator; +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. " + + "The Box API requires newly created templates to be created with the scope set as enterprise so no scope is required.") +@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 PropertyDescriptor KEY_RECORD_PATH = new PropertyDescriptor.Builder() + .name("Metadata Key Record Path") + .description("Specifies the RecordPath to use for getting the metadata key to create.") + .required(true) + .addValidator(new RecordPathValidator()) + .defaultValue("/key") + .expressionLanguageSupported(ExpressionLanguageScope.FLOWFILE_ATTRIBUTES) + .build(); + + public static final PropertyDescriptor VALUE_RECORD_PATH = new PropertyDescriptor.Builder() + .name("Metadata Value Record Path") + .description("Specifies the record path to use for getting the metadata value to create.") + .required(true) + .addValidator(new RecordPathValidator()) + .defaultValue("/value") + .expressionLanguageSupported(ExpressionLanguageScope.FLOWFILE_ATTRIBUTES) + .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, + KEY_RECORD_PATH, + VALUE_RECORD_PATH + ); + + 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); + final String keyRecordPathStr = context.getProperty(KEY_RECORD_PATH).evaluateAttributeExpressions(flowFile).getValue(); + final String valueRecordPathStr = context.getProperty(VALUE_RECORD_PATH).evaluateAttributeExpressions(flowFile).getValue(); + + try (final InputStream inputStream = session.read(flowFile); + final RecordReader recordReader = recordReaderFactory.createRecordReader(flowFile, inputStream, getLogger())) { + + final RecordPath keyRecordPath = RecordPath.compile(keyRecordPathStr); + final RecordPath valueRecordPath = RecordPath.compile(valueRecordPathStr); + final Metadata metadata = new Metadata(); + final Set<String> createdKeys = new HashSet<>(); + final List<String> errors = new ArrayList<>(); + + Record record; + try { + while ((record = recordReader.nextRecord()) != null) { + processRecord(record, keyRecordPath, valueRecordPath, metadata, createdKeys, errors); + } + } catch (final Exception e) { + getLogger().error("Error processing record: {}", e.getMessage(), e); + errors.add("Error processing record: " + e.getMessage()); + } + + 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); + + // Update FlowFile attributes + final Map<String, String> attributes = new HashMap<>(); + attributes.put("box.id", fileId); + attributes.put("box.template.name", templateName); + flowFile = session.putAllAttributes(flowFile, attributes); + + session.getProvenanceReporter().create(flowFile, BoxFileUtils.BOX_URL + fileId); Review Comment: It should be a url of the metadata instance, not the file. ########## nifi-extension-bundles/nifi-box-bundle/nifi-box-processors/src/main/java/org/apache/nifi/processors/box/UpdateBoxFileMetadataInstance.java: ########## @@ -0,0 +1,296 @@ +/* + * 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.record.path.FieldValue; +import org.apache.nifi.record.path.RecordPath; +import org.apache.nifi.record.path.RecordPathResult; +import org.apache.nifi.record.path.validation.RecordPathValidator; +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", "update"}) +@CapabilityDescription("Updates metadata template values for a Box file using records from the flowFile content.") +@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 PropertyDescriptor KEY_RECORD_PATH = new PropertyDescriptor.Builder() + .name("Metadata Key Record Path") + .description("Specifies the RecordPath to use for getting the metadata key to update.") + .required(true) + .addValidator(new RecordPathValidator()) + .defaultValue("/key") + .expressionLanguageSupported(ExpressionLanguageScope.FLOWFILE_ATTRIBUTES) + .build(); + + public static final PropertyDescriptor VALUE_RECORD_PATH = new PropertyDescriptor.Builder() + .name("Metadata Value Record Path") + .description("Specifies the record path to use for getting the metadata value to update.") + .required(true) + .addValidator(new RecordPathValidator()) + .defaultValue("/value") + .expressionLanguageSupported(ExpressionLanguageScope.FLOWFILE_ATTRIBUTES) + .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 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, + TEMPLATE_SCOPE, + RECORD_READER, + KEY_RECORD_PATH, + VALUE_RECORD_PATH + ); + + 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); + final String keyRecordPathStr = context.getProperty(KEY_RECORD_PATH).evaluateAttributeExpressions(flowFile).getValue(); + final String valueRecordPathStr = context.getProperty(VALUE_RECORD_PATH).evaluateAttributeExpressions(flowFile).getValue(); + + try (final InputStream inputStream = session.read(flowFile); + final RecordReader recordReader = recordReaderFactory.createRecordReader(flowFile, inputStream, getLogger())) { + + final RecordPath keyRecordPath = RecordPath.compile(keyRecordPathStr); + final RecordPath valueRecordPath = RecordPath.compile(valueRecordPathStr); + + // Create metadata object + final Metadata metadata = new Metadata(templateScope, templateName); + final Set<String> updatedKeys = new HashSet<>(); + final List<String> errors = new ArrayList<>(); + + Record record; + try { + while ((record = recordReader.nextRecord()) != null) { + processRecord(record, keyRecordPath, valueRecordPath, metadata, updatedKeys, errors); + } Review Comment: Same as in `CreateBoxFileMetadataInstance`. Shall we just accept the record as the desired metadata state? ########## nifi-extension-bundles/nifi-box-bundle/nifi-box-processors/src/main/java/org/apache/nifi/processors/box/ExtractBoxFileMetadataWithBoxAI.java: ########## @@ -0,0 +1,217 @@ +/* + * 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.BoxAI; +import com.box.sdk.BoxAIExtractMetadataTemplate; +import com.box.sdk.BoxAIExtractStructuredResponse; +import com.box.sdk.BoxAIItem; +import com.box.sdk.BoxAPIConnection; +import com.box.sdk.BoxAPIResponseException; +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.flowfile.attributes.CoreAttributes; +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.jetbrains.annotations.NotNull; + +import java.io.IOException; +import java.io.OutputStream; +import java.util.Collections; +import java.util.HashMap; +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", "ai", "extract"}) +@CapabilityDescription("Extracts metadata from a Box file using Box AI and a template. The extracted metadata is written to the FlowFile content as JSON.") +@SeeAlso({ListBoxFileMetadataTemplates.class, ListBoxFile.class, FetchBoxFile.class, UpdateBoxFileMetadataInstance.class}) +@WritesAttributes({ + @WritesAttribute(attribute = "box.id", description = "The ID of the file from which metadata was extracted"), + @WritesAttribute(attribute = "box.ai.template.key", description = "The template key used for extraction"), + @WritesAttribute(attribute = "box.ai.completion.reason", description = "The completion reason from the AI extraction"), + @WritesAttribute(attribute = "mime.type", description = "Set to 'application/json' for the JSON content"), + @WritesAttribute(attribute = ERROR_CODE, description = ERROR_CODE_DESC), + @WritesAttribute(attribute = ERROR_MESSAGE, description = ERROR_MESSAGE_DESC) +}) +public class ExtractBoxFileMetadataWithBoxAI extends AbstractProcessor { + + public static final PropertyDescriptor FILE_ID = new PropertyDescriptor.Builder() + .name("File ID") + .description("The ID of the file from which to extract metadata.") + .required(true) + .defaultValue("${box.id}") + .expressionLanguageSupported(ExpressionLanguageScope.FLOWFILE_ATTRIBUTES) + .addValidator(StandardValidators.NON_EMPTY_VALIDATOR) + .build(); + + public static final PropertyDescriptor TEMPLATE_KEY = new PropertyDescriptor.Builder() Review Comment: I think there should be 2 options to get the fields from. Either a template key, which represents a key of a Box Metadata Template. Or a list of fields, perhaps coming in the FlowFile content. ########## nifi-extension-bundles/nifi-box-bundle/nifi-box-processors/src/main/java/org/apache/nifi/processors/box/CreateBoxMetadataTemplate.java: ########## @@ -0,0 +1,361 @@ +/* + * 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.MetadataTemplate; +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.record.path.FieldValue; +import org.apache.nifi.record.path.RecordPath; +import org.apache.nifi.record.path.RecordPathResult; +import org.apache.nifi.record.path.validation.RecordPathValidator; +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.Arrays; +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 Box metadata template using field specifications from the flowFile content.") +@SeeAlso({ListBoxFileMetadataTemplates.class, UpdateBoxFileMetadataInstance.class}) +@WritesAttributes({ + @WritesAttribute(attribute = "box.template.name", description = "The template name that was created"), + @WritesAttribute(attribute = "box.template.key", description = "The template key that was created"), + @WritesAttribute(attribute = "box.template.scope", description = "The template scope."), + @WritesAttribute(attribute = "box.template.fields.count", description = "Number of fields created for the template"), + @WritesAttribute(attribute = ERROR_CODE, description = ERROR_CODE_DESC), + @WritesAttribute(attribute = ERROR_MESSAGE, description = ERROR_MESSAGE_DESC) +}) +public class CreateBoxMetadataTemplate extends AbstractProcessor { + + public static final String SCOPE_ENTERPRISE = "enterprise"; + + private static final Set<String> VALID_FIELD_TYPES = new HashSet<>(Arrays.asList("string", "float", "date")); + + public static final PropertyDescriptor TEMPLATE_NAME = new PropertyDescriptor.Builder() + .name("Template Name") + .description("The display name of the metadata template to create.") + .required(true) + .expressionLanguageSupported(ExpressionLanguageScope.FLOWFILE_ATTRIBUTES) + .addValidator(StandardValidators.NON_EMPTY_VALIDATOR) + .build(); + + public static final PropertyDescriptor TEMPLATE_KEY = new PropertyDescriptor.Builder() + .name("Template Key") + .description("The key of the metadata template to create (used for API calls).") + .required(true) + .expressionLanguageSupported(ExpressionLanguageScope.FLOWFILE_ATTRIBUTES) + .addValidator(StandardValidators.NON_EMPTY_VALIDATOR) + .build(); + + public static final PropertyDescriptor HIDDEN = new PropertyDescriptor.Builder() + .name("Hidden") + .description("Whether the template should be hidden in the Box UI.") + .required(true) + .allowableValues("true", "false") + .defaultValue("false") + .expressionLanguageSupported(ExpressionLanguageScope.FLOWFILE_ATTRIBUTES) + .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 PropertyDescriptor KEY_RECORD_PATH = new PropertyDescriptor.Builder() + .name("Template Key Field Record Path") + .description("Specifies the RecordPath to use for getting the field key names.") + .required(true) + .addValidator(new RecordPathValidator()) + .defaultValue("/key") + .expressionLanguageSupported(ExpressionLanguageScope.FLOWFILE_ATTRIBUTES) + .build(); + + public static final PropertyDescriptor TYPE_RECORD_PATH = new PropertyDescriptor.Builder() + .name("Template Type Field Record Path") + .description("Specifies the RecordPath to use for getting the field type (string, float, date).") + .required(true) + .addValidator(new RecordPathValidator()) + .defaultValue("/type") + .expressionLanguageSupported(ExpressionLanguageScope.FLOWFILE_ATTRIBUTES) + .build(); + + public static final PropertyDescriptor DISPLAY_NAME_RECORD_PATH = new PropertyDescriptor.Builder() + .name("Template Display Name Field Record Path") + .description("Specifies the RecordPath to use for getting the field display name. If not specified or if the path doesn't resolve to a value, the key will be used.") + .required(false) + .addValidator(new RecordPathValidator()) + .defaultValue("/displayName") + .expressionLanguageSupported(ExpressionLanguageScope.FLOWFILE_ATTRIBUTES) + .build(); + + public static final Relationship REL_SUCCESS = new Relationship.Builder() + .name("success") + .description("A FlowFile is routed to this relationship after a template 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 template creation.") + .build(); + + private static final Set<Relationship> RELATIONSHIPS = Set.of( + REL_SUCCESS, + REL_FAILURE + ); + + private static final List<PropertyDescriptor> PROPERTY_DESCRIPTORS = List.of( + BoxClientService.BOX_CLIENT_SERVICE, + TEMPLATE_NAME, + TEMPLATE_KEY, + HIDDEN, + RECORD_READER, + KEY_RECORD_PATH, + TYPE_RECORD_PATH, + DISPLAY_NAME_RECORD_PATH + ); + + 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) { + boxAPIConnection = getBoxAPIConnection(context); + } + + protected BoxAPIConnection getBoxAPIConnection(final ProcessContext context) { + final BoxClientService boxClientService = context.getProperty(BoxClientService.BOX_CLIENT_SERVICE) + .asControllerService(BoxClientService.class); + return boxClientService.getBoxApiConnection(); + } + + @Override + public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException { + FlowFile flowFile = session.get(); + if (flowFile == null) { + return; + } + + final String templateName = context.getProperty(TEMPLATE_NAME).evaluateAttributeExpressions(flowFile).getValue(); + final String templateKey = context.getProperty(TEMPLATE_KEY).evaluateAttributeExpressions(flowFile).getValue(); + final boolean hidden = Boolean.parseBoolean(context.getProperty(HIDDEN).evaluateAttributeExpressions(flowFile).getValue()); + final RecordReaderFactory recordReaderFactory = context.getProperty(RECORD_READER).asControllerService(RecordReaderFactory.class); + final String keyRecordPathStr = context.getProperty(KEY_RECORD_PATH).evaluateAttributeExpressions(flowFile).getValue(); + final String typeRecordPathStr = context.getProperty(TYPE_RECORD_PATH).evaluateAttributeExpressions(flowFile).getValue(); Review Comment: [Template fields can be hidden](https://developer.box.com/reference/post-metadata-templates-schema/#param-fields-hidden) as well. ########## nifi-extension-bundles/nifi-box-bundle/nifi-box-processors/src/main/java/org/apache/nifi/processors/box/CreateBoxMetadataTemplate.java: ########## @@ -0,0 +1,361 @@ +/* + * 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.MetadataTemplate; +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.record.path.FieldValue; +import org.apache.nifi.record.path.RecordPath; +import org.apache.nifi.record.path.RecordPathResult; +import org.apache.nifi.record.path.validation.RecordPathValidator; +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.Arrays; +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 Box metadata template using field specifications from the flowFile content.") +@SeeAlso({ListBoxFileMetadataTemplates.class, UpdateBoxFileMetadataInstance.class}) +@WritesAttributes({ + @WritesAttribute(attribute = "box.template.name", description = "The template name that was created"), + @WritesAttribute(attribute = "box.template.key", description = "The template key that was created"), + @WritesAttribute(attribute = "box.template.scope", description = "The template scope."), + @WritesAttribute(attribute = "box.template.fields.count", description = "Number of fields created for the template"), + @WritesAttribute(attribute = ERROR_CODE, description = ERROR_CODE_DESC), + @WritesAttribute(attribute = ERROR_MESSAGE, description = ERROR_MESSAGE_DESC) +}) +public class CreateBoxMetadataTemplate extends AbstractProcessor { + + public static final String SCOPE_ENTERPRISE = "enterprise"; + + private static final Set<String> VALID_FIELD_TYPES = new HashSet<>(Arrays.asList("string", "float", "date")); + + public static final PropertyDescriptor TEMPLATE_NAME = new PropertyDescriptor.Builder() + .name("Template Name") + .description("The display name of the metadata template to create.") + .required(true) + .expressionLanguageSupported(ExpressionLanguageScope.FLOWFILE_ATTRIBUTES) + .addValidator(StandardValidators.NON_EMPTY_VALIDATOR) + .build(); + + public static final PropertyDescriptor TEMPLATE_KEY = new PropertyDescriptor.Builder() + .name("Template Key") + .description("The key of the metadata template to create (used for API calls).") + .required(true) + .expressionLanguageSupported(ExpressionLanguageScope.FLOWFILE_ATTRIBUTES) + .addValidator(StandardValidators.NON_EMPTY_VALIDATOR) + .build(); + + public static final PropertyDescriptor HIDDEN = new PropertyDescriptor.Builder() + .name("Hidden") + .description("Whether the template should be hidden in the Box UI.") + .required(true) + .allowableValues("true", "false") + .defaultValue("false") + .expressionLanguageSupported(ExpressionLanguageScope.FLOWFILE_ATTRIBUTES) + .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 PropertyDescriptor KEY_RECORD_PATH = new PropertyDescriptor.Builder() + .name("Template Key Field Record Path") + .description("Specifies the RecordPath to use for getting the field key names.") + .required(true) + .addValidator(new RecordPathValidator()) + .defaultValue("/key") + .expressionLanguageSupported(ExpressionLanguageScope.FLOWFILE_ATTRIBUTES) + .build(); + + public static final PropertyDescriptor TYPE_RECORD_PATH = new PropertyDescriptor.Builder() + .name("Template Type Field Record Path") + .description("Specifies the RecordPath to use for getting the field type (string, float, date).") + .required(true) + .addValidator(new RecordPathValidator()) + .defaultValue("/type") + .expressionLanguageSupported(ExpressionLanguageScope.FLOWFILE_ATTRIBUTES) + .build(); + + public static final PropertyDescriptor DISPLAY_NAME_RECORD_PATH = new PropertyDescriptor.Builder() + .name("Template Display Name Field Record Path") + .description("Specifies the RecordPath to use for getting the field display name. If not specified or if the path doesn't resolve to a value, the key will be used.") + .required(false) + .addValidator(new RecordPathValidator()) + .defaultValue("/displayName") + .expressionLanguageSupported(ExpressionLanguageScope.FLOWFILE_ATTRIBUTES) + .build(); + + public static final Relationship REL_SUCCESS = new Relationship.Builder() + .name("success") + .description("A FlowFile is routed to this relationship after a template 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 template creation.") + .build(); + + private static final Set<Relationship> RELATIONSHIPS = Set.of( + REL_SUCCESS, + REL_FAILURE + ); + + private static final List<PropertyDescriptor> PROPERTY_DESCRIPTORS = List.of( + BoxClientService.BOX_CLIENT_SERVICE, + TEMPLATE_NAME, + TEMPLATE_KEY, + HIDDEN, + RECORD_READER, + KEY_RECORD_PATH, + TYPE_RECORD_PATH, + DISPLAY_NAME_RECORD_PATH + ); + + 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) { + boxAPIConnection = getBoxAPIConnection(context); + } + + protected BoxAPIConnection getBoxAPIConnection(final ProcessContext context) { + final BoxClientService boxClientService = context.getProperty(BoxClientService.BOX_CLIENT_SERVICE) + .asControllerService(BoxClientService.class); + return boxClientService.getBoxApiConnection(); + } + + @Override + public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException { + FlowFile flowFile = session.get(); + if (flowFile == null) { + return; + } + + final String templateName = context.getProperty(TEMPLATE_NAME).evaluateAttributeExpressions(flowFile).getValue(); + final String templateKey = context.getProperty(TEMPLATE_KEY).evaluateAttributeExpressions(flowFile).getValue(); + final boolean hidden = Boolean.parseBoolean(context.getProperty(HIDDEN).evaluateAttributeExpressions(flowFile).getValue()); + final RecordReaderFactory recordReaderFactory = context.getProperty(RECORD_READER).asControllerService(RecordReaderFactory.class); + final String keyRecordPathStr = context.getProperty(KEY_RECORD_PATH).evaluateAttributeExpressions(flowFile).getValue(); + final String typeRecordPathStr = context.getProperty(TYPE_RECORD_PATH).evaluateAttributeExpressions(flowFile).getValue(); + + final String displayNameRecordPathStr; + if (context.getProperty(DISPLAY_NAME_RECORD_PATH).isSet()) { + displayNameRecordPathStr = context.getProperty(DISPLAY_NAME_RECORD_PATH).evaluateAttributeExpressions(flowFile).getValue(); + } else { + displayNameRecordPathStr = null; + } + + try (final InputStream inputStream = session.read(flowFile); + final RecordReader recordReader = recordReaderFactory.createRecordReader(flowFile, inputStream, getLogger())) { + + final RecordPath keyRecordPath = RecordPath.compile(keyRecordPathStr); + final RecordPath typeRecordPath = RecordPath.compile(typeRecordPathStr); + final RecordPath displayNameRecordPath = displayNameRecordPathStr != null ? RecordPath.compile(displayNameRecordPathStr) : null; + + // Create list to hold fields for the template + final List<MetadataTemplate.Field> fields = new ArrayList<>(); + final List<String> errors = new ArrayList<>(); + final Set<String> processedKeys = new HashSet<>(); + + Record record; + try { + while ((record = recordReader.nextRecord()) != null) { + processRecord(record, keyRecordPath, typeRecordPath, displayNameRecordPath, fields, processedKeys, errors); + } + } catch (final Exception e) { + getLogger().error("Error processing record: {}", e.getMessage(), e); + errors.add("Error processing record: " + e.getMessage()); + } + + if (!errors.isEmpty()) { + flowFile = session.putAttribute(flowFile, ERROR_MESSAGE, String.join(", ", errors)); + session.transfer(flowFile, REL_FAILURE); + return; + } + + if (fields.isEmpty()) { + flowFile = session.putAttribute(flowFile, ERROR_MESSAGE, "No valid metadata field specifications found in the input"); + session.transfer(flowFile, REL_FAILURE); + return; + } + + // Create the template + createBoxMetadataTemplate( + boxAPIConnection, + templateKey, + templateName, + hidden, + fields); + final Map<String, String> attributes = new HashMap<>(); + attributes.put("box.template.name", templateName); + attributes.put("box.template.key", templateKey); + attributes.put("box.template.scope", SCOPE_ENTERPRISE); + attributes.put("box.template.fields.count", String.valueOf(fields.size())); + flowFile = session.putAllAttributes(flowFile, attributes); + + session.getProvenanceReporter().create(flowFile, "Created Box metadata template: " + 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()); + getLogger().error("Couldn't create metadata template with name [{}]", templateName, e); + session.transfer(flowFile, REL_FAILURE); + } catch (final Exception e) { + getLogger().error("Error processing metadata template creation", e); + flowFile = session.putAttribute(flowFile, ERROR_MESSAGE, e.getMessage()); + session.transfer(flowFile, REL_FAILURE); + } + } + + private void processRecord(final Record record, + final RecordPath keyRecordPath, + final RecordPath typeRecordPath, + final RecordPath displayNameRecordPath, + final List<MetadataTemplate.Field> fields, + final Set<String> processedKeys, + final List<String> errors) { + final RecordPathResult keyPathResult = keyRecordPath.evaluate(record); + final List<FieldValue> keyValues = keyPathResult.getSelectedFields().toList(); + + if (keyValues.isEmpty()) { + errors.add("Record is missing a key field"); + return; + } + + final Object keyObj = keyValues.getFirst().getValue(); + if (keyObj == null) { + errors.add("Record has a null key value"); + return; + } + + final String key = keyObj.toString(); + + // Skip if we've already processed this key + if (processedKeys.contains(key)) { + getLogger().warn("Duplicate key '{}' found in record, skipping", key); + return; + } Review Comment: Shall we fail the template creation in that case? ########## nifi-extension-bundles/nifi-box-bundle/nifi-box-processors/src/main/java/org/apache/nifi/processors/box/UpdateBoxFileMetadataInstance.java: ########## @@ -0,0 +1,296 @@ +/* + * 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.record.path.FieldValue; +import org.apache.nifi.record.path.RecordPath; +import org.apache.nifi.record.path.RecordPathResult; +import org.apache.nifi.record.path.validation.RecordPathValidator; +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", "update"}) +@CapabilityDescription("Updates metadata template values for a Box file using records from the flowFile content.") +@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 PropertyDescriptor KEY_RECORD_PATH = new PropertyDescriptor.Builder() + .name("Metadata Key Record Path") + .description("Specifies the RecordPath to use for getting the metadata key to update.") + .required(true) + .addValidator(new RecordPathValidator()) + .defaultValue("/key") + .expressionLanguageSupported(ExpressionLanguageScope.FLOWFILE_ATTRIBUTES) + .build(); + + public static final PropertyDescriptor VALUE_RECORD_PATH = new PropertyDescriptor.Builder() + .name("Metadata Value Record Path") + .description("Specifies the record path to use for getting the metadata value to update.") + .required(true) + .addValidator(new RecordPathValidator()) + .defaultValue("/value") + .expressionLanguageSupported(ExpressionLanguageScope.FLOWFILE_ATTRIBUTES) + .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 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, + TEMPLATE_SCOPE, + RECORD_READER, + KEY_RECORD_PATH, + VALUE_RECORD_PATH + ); + + 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); + final String keyRecordPathStr = context.getProperty(KEY_RECORD_PATH).evaluateAttributeExpressions(flowFile).getValue(); + final String valueRecordPathStr = context.getProperty(VALUE_RECORD_PATH).evaluateAttributeExpressions(flowFile).getValue(); + + try (final InputStream inputStream = session.read(flowFile); + final RecordReader recordReader = recordReaderFactory.createRecordReader(flowFile, inputStream, getLogger())) { + + final RecordPath keyRecordPath = RecordPath.compile(keyRecordPathStr); + final RecordPath valueRecordPath = RecordPath.compile(valueRecordPathStr); + + // Create metadata object + final Metadata metadata = new Metadata(templateScope, templateName); Review Comment: We should operate on the existing metadata object. ```java boxFile.getMetadata(templateName, templateScope); ``` ########## nifi-extension-bundles/nifi-box-bundle/nifi-box-processors/src/main/java/org/apache/nifi/processors/box/UpdateBoxFileMetadataInstance.java: ########## @@ -0,0 +1,296 @@ +/* + * 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.record.path.FieldValue; +import org.apache.nifi.record.path.RecordPath; +import org.apache.nifi.record.path.RecordPathResult; +import org.apache.nifi.record.path.validation.RecordPathValidator; +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", "update"}) +@CapabilityDescription("Updates metadata template values for a Box file using records from the flowFile content.") +@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 PropertyDescriptor KEY_RECORD_PATH = new PropertyDescriptor.Builder() + .name("Metadata Key Record Path") + .description("Specifies the RecordPath to use for getting the metadata key to update.") + .required(true) + .addValidator(new RecordPathValidator()) + .defaultValue("/key") + .expressionLanguageSupported(ExpressionLanguageScope.FLOWFILE_ATTRIBUTES) + .build(); + + public static final PropertyDescriptor VALUE_RECORD_PATH = new PropertyDescriptor.Builder() + .name("Metadata Value Record Path") + .description("Specifies the record path to use for getting the metadata value to update.") + .required(true) + .addValidator(new RecordPathValidator()) + .defaultValue("/value") + .expressionLanguageSupported(ExpressionLanguageScope.FLOWFILE_ATTRIBUTES) + .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 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, + TEMPLATE_SCOPE, + RECORD_READER, + KEY_RECORD_PATH, + VALUE_RECORD_PATH + ); + + 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); + final String keyRecordPathStr = context.getProperty(KEY_RECORD_PATH).evaluateAttributeExpressions(flowFile).getValue(); + final String valueRecordPathStr = context.getProperty(VALUE_RECORD_PATH).evaluateAttributeExpressions(flowFile).getValue(); + + try (final InputStream inputStream = session.read(flowFile); + final RecordReader recordReader = recordReaderFactory.createRecordReader(flowFile, inputStream, getLogger())) { + + final RecordPath keyRecordPath = RecordPath.compile(keyRecordPathStr); + final RecordPath valueRecordPath = RecordPath.compile(valueRecordPathStr); + + // Create metadata object + final Metadata metadata = new Metadata(templateScope, templateName); + final Set<String> updatedKeys = new HashSet<>(); + final List<String> errors = new ArrayList<>(); + + Record record; + try { + while ((record = recordReader.nextRecord()) != null) { + processRecord(record, keyRecordPath, valueRecordPath, metadata, updatedKeys, errors); + } + } catch (final Exception e) { + getLogger().error("Error processing record: {}", e.getMessage(), e); + errors.add("Error processing record: " + e.getMessage()); + } + + if (!errors.isEmpty()) { + flowFile = session.putAttribute(flowFile, ERROR_MESSAGE, String.join(", ", errors)); + session.transfer(flowFile, REL_FAILURE); + return; + } + + if (updatedKeys.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.updateMetadata(metadata); + + // Update FlowFile attributes + 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); + 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 void processRecord(Record record, RecordPath keyRecordPath, RecordPath valueRecordPath, + Metadata metadata, Set<String> updatedKeys, List<String> errors) { + // Get the key from the record + final RecordPathResult keyPathResult = keyRecordPath.evaluate(record); + final List<FieldValue> keyValues = keyPathResult.getSelectedFields().toList(); + + if (keyValues.isEmpty()) { + errors.add("Record is missing a key field"); + return; + } + + final Object keyObj = keyValues.getFirst().getValue(); + if (keyObj == null) { + errors.add("Record has a null key value"); + return; + } + + final String key = keyObj.toString(); + + // Get the value from the record + final RecordPathResult valuePathResult = valueRecordPath.evaluate(record); + final List<FieldValue> valueValues = valuePathResult.getSelectedFields().toList(); + + if (valueValues.isEmpty()) { + errors.add("Record with key '" + key + "' is missing a value field"); + return; + } + + final Object valueObj = valueValues.getFirst().getValue(); + final String value = valueObj != null ? valueObj.toString() : null; + + // Add the key-value pair to the metadata update + metadata.add("/" + key, value); Review Comment: I reckon the metadata deletes must be processed as well. When it comes to updates, shall we ensure no concurrent change happened in meantime, by using json-patch `test` operation? ########## nifi-extension-bundles/nifi-box-bundle/nifi-box-processors/src/main/java/org/apache/nifi/processors/box/UpdateBoxFileMetadataInstance.java: ########## @@ -0,0 +1,296 @@ +/* + * 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.record.path.FieldValue; +import org.apache.nifi.record.path.RecordPath; +import org.apache.nifi.record.path.RecordPathResult; +import org.apache.nifi.record.path.validation.RecordPathValidator; +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", "update"}) +@CapabilityDescription("Updates metadata template values for a Box file using records from the flowFile content.") +@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 PropertyDescriptor KEY_RECORD_PATH = new PropertyDescriptor.Builder() + .name("Metadata Key Record Path") + .description("Specifies the RecordPath to use for getting the metadata key to update.") + .required(true) + .addValidator(new RecordPathValidator()) + .defaultValue("/key") + .expressionLanguageSupported(ExpressionLanguageScope.FLOWFILE_ATTRIBUTES) + .build(); + + public static final PropertyDescriptor VALUE_RECORD_PATH = new PropertyDescriptor.Builder() + .name("Metadata Value Record Path") + .description("Specifies the record path to use for getting the metadata value to update.") + .required(true) + .addValidator(new RecordPathValidator()) + .defaultValue("/value") + .expressionLanguageSupported(ExpressionLanguageScope.FLOWFILE_ATTRIBUTES) + .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 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, + TEMPLATE_SCOPE, + RECORD_READER, + KEY_RECORD_PATH, + VALUE_RECORD_PATH + ); + + 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); + final String keyRecordPathStr = context.getProperty(KEY_RECORD_PATH).evaluateAttributeExpressions(flowFile).getValue(); + final String valueRecordPathStr = context.getProperty(VALUE_RECORD_PATH).evaluateAttributeExpressions(flowFile).getValue(); + + try (final InputStream inputStream = session.read(flowFile); + final RecordReader recordReader = recordReaderFactory.createRecordReader(flowFile, inputStream, getLogger())) { + + final RecordPath keyRecordPath = RecordPath.compile(keyRecordPathStr); + final RecordPath valueRecordPath = RecordPath.compile(valueRecordPathStr); + + // Create metadata object + final Metadata metadata = new Metadata(templateScope, templateName); + final Set<String> updatedKeys = new HashSet<>(); + final List<String> errors = new ArrayList<>(); + + Record record; + try { + while ((record = recordReader.nextRecord()) != null) { + processRecord(record, keyRecordPath, valueRecordPath, metadata, updatedKeys, errors); + } + } catch (final Exception e) { + getLogger().error("Error processing record: {}", e.getMessage(), e); + errors.add("Error processing record: " + e.getMessage()); + } + + if (!errors.isEmpty()) { + flowFile = session.putAttribute(flowFile, ERROR_MESSAGE, String.join(", ", errors)); + session.transfer(flowFile, REL_FAILURE); + return; + } + + if (updatedKeys.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.updateMetadata(metadata); + + // Update FlowFile attributes + 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); Review Comment: This should be a file metadata instance address. ########## nifi-extension-bundles/nifi-box-bundle/nifi-box-processors/src/main/java/org/apache/nifi/processors/box/UpdateBoxFileMetadataInstance.java: ########## @@ -0,0 +1,296 @@ +/* + * 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.record.path.FieldValue; +import org.apache.nifi.record.path.RecordPath; +import org.apache.nifi.record.path.RecordPathResult; +import org.apache.nifi.record.path.validation.RecordPathValidator; +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", "update"}) +@CapabilityDescription("Updates metadata template values for a Box file using records from the flowFile content.") +@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 PropertyDescriptor KEY_RECORD_PATH = new PropertyDescriptor.Builder() + .name("Metadata Key Record Path") + .description("Specifies the RecordPath to use for getting the metadata key to update.") + .required(true) + .addValidator(new RecordPathValidator()) + .defaultValue("/key") + .expressionLanguageSupported(ExpressionLanguageScope.FLOWFILE_ATTRIBUTES) + .build(); + + public static final PropertyDescriptor VALUE_RECORD_PATH = new PropertyDescriptor.Builder() + .name("Metadata Value Record Path") + .description("Specifies the record path to use for getting the metadata value to update.") + .required(true) + .addValidator(new RecordPathValidator()) + .defaultValue("/value") + .expressionLanguageSupported(ExpressionLanguageScope.FLOWFILE_ATTRIBUTES) + .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 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, + TEMPLATE_SCOPE, + RECORD_READER, + KEY_RECORD_PATH, + VALUE_RECORD_PATH + ); + + 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); + final String keyRecordPathStr = context.getProperty(KEY_RECORD_PATH).evaluateAttributeExpressions(flowFile).getValue(); + final String valueRecordPathStr = context.getProperty(VALUE_RECORD_PATH).evaluateAttributeExpressions(flowFile).getValue(); + + try (final InputStream inputStream = session.read(flowFile); + final RecordReader recordReader = recordReaderFactory.createRecordReader(flowFile, inputStream, getLogger())) { + + final RecordPath keyRecordPath = RecordPath.compile(keyRecordPathStr); + final RecordPath valueRecordPath = RecordPath.compile(valueRecordPathStr); + + // Create metadata object + final Metadata metadata = new Metadata(templateScope, templateName); + final Set<String> updatedKeys = new HashSet<>(); + final List<String> errors = new ArrayList<>(); + + Record record; + try { + while ((record = recordReader.nextRecord()) != null) { + processRecord(record, keyRecordPath, valueRecordPath, metadata, updatedKeys, errors); + } + } catch (final Exception e) { + getLogger().error("Error processing record: {}", e.getMessage(), e); + errors.add("Error processing record: " + e.getMessage()); + } + + if (!errors.isEmpty()) { + flowFile = session.putAttribute(flowFile, ERROR_MESSAGE, String.join(", ", errors)); + session.transfer(flowFile, REL_FAILURE); + return; + } + + if (updatedKeys.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.updateMetadata(metadata); + + // Update FlowFile attributes + 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); + 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 void processRecord(Record record, RecordPath keyRecordPath, RecordPath valueRecordPath, + Metadata metadata, Set<String> updatedKeys, List<String> errors) { + // Get the key from the record + final RecordPathResult keyPathResult = keyRecordPath.evaluate(record); + final List<FieldValue> keyValues = keyPathResult.getSelectedFields().toList(); + + if (keyValues.isEmpty()) { + errors.add("Record is missing a key field"); + return; + } + + final Object keyObj = keyValues.getFirst().getValue(); + if (keyObj == null) { + errors.add("Record has a null key value"); + return; + } + + final String key = keyObj.toString(); + + // Get the value from the record + final RecordPathResult valuePathResult = valueRecordPath.evaluate(record); + final List<FieldValue> valueValues = valuePathResult.getSelectedFields().toList(); + + if (valueValues.isEmpty()) { + errors.add("Record with key '" + key + "' is missing a value field"); + return; + } + + final Object valueObj = valueValues.getFirst().getValue(); + final String value = valueObj != null ? valueObj.toString() : null; + + // Add the key-value pair to the metadata update + metadata.add("/" + key, value); Review Comment: Will `add` overwrite the existing values? The [Metadata update API](https://developer.box.com/reference/put-files-id-metadata-id-id/) accepts json-patch, which has a dedicated `replace` operation. -- 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]
