You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@nifi.apache.org by kd...@apache.org on 2025/12/17 22:16:59 UTC
(nifi) branch NIFI-15258 updated: NIFI-15315 Add support for assets in connectors (#10647)
This is an automated email from the ASF dual-hosted git repository.
kdoran pushed a commit to branch NIFI-15258
in repository https://gitbox.apache.org/repos/asf/nifi.git
The following commit(s) were added to refs/heads/NIFI-15258 by this push:
new 2d120a1222 NIFI-15315 Add support for assets in connectors (#10647)
2d120a1222 is described below
commit 2d120a12223d73eed84384b99476baf6d48876fd
Author: Bryan Bende <bb...@apache.org>
AuthorDate: Wed Dec 17 17:16:54 2025 -0500
NIFI-15315 Add support for assets in connectors (#10647)
- Support multiple asset references
- Clean up of assets in StandardConnectorDAO after apply and discard
- Add endpoint for listing assets for a given connector
- Add endpoint for discarding the working config of a connector
- Add endpoint for retrieving asset content
- Add system test for connectors that uploads an asset
Signed-off-by: Kevin Doran <kd...@apache.org>
* Fix issues after rebasing, enable ClusteredConnectorAssetsIT
---
.../java/org/apache/nifi/util/NiFiProperties.java | 3 +
.../java/org/apache/nifi/asset/AssetManager.java | 30 +-
.../web/api/dto/ConnectorValueReferenceDTO.java | 28 +-
.../http/endpoints/AssetsEndpointMerger.java | 2 +-
.../java/org/apache/nifi/asset/StandardAsset.java | 13 +-
.../apache/nifi/asset/StandardAssetManager.java | 103 ++++---
.../nifi/asset/StandardConnectorAssetManager.java | 225 ++++++++++++++
.../flow/mapping/VersionedComponentFlowMapper.java | 2 +-
.../services/org.apache.nifi.asset.AssetManager | 3 +-
.../asset/StandardConnectorAssetManagerTest.java | 178 +++++++++++
...nContext.java => ConnectorAssetRepository.java} | 23 +-
.../components/connector/ConnectorRepository.java | 1 +
.../ConnectorRepositoryInitializationContext.java | 3 +
.../org/apache/nifi/asset/AssetsRestApiClient.java | 55 +++-
.../nifi/asset/StandardAssetComponentManager.java | 4 +-
.../nifi/asset/StandardAssetSynchronizer.java | 4 +-
...ava => StandardConnectorAssetSynchronizer.java} | 115 ++++----
.../StandardConnectorAssetRepository.java | 63 ++++
.../StandardConnectorConfigurationContext.java | 19 +-
.../connector/StandardConnectorNode.java | 33 ++-
...StandardConnectorRepoInitializationContext.java | 9 +
.../connector/StandardConnectorRepository.java | 6 +
.../apache/nifi/controller/ExtensionBuilder.java | 2 +-
.../org/apache/nifi/controller/FlowController.java | 57 +++-
.../nifi/controller/StandardFlowService.java | 30 +-
.../nifi/controller/flow/StandardFlowManager.java | 2 +-
.../serialization/VersionedFlowSynchronizer.java | 2 +-
.../configuration/FlowControllerConfiguration.java | 21 +-
...TestStandardConnectorInitializationContext.java | 16 +
.../apache/nifi/headless/HeadlessNiFiServer.java | 3 +-
.../org/apache/nifi/audit/ConnectorAuditor.java | 10 +-
.../org/apache/nifi/web/NiFiServiceFacade.java | 26 +-
.../apache/nifi/web/StandardNiFiServiceFacade.java | 59 +++-
.../org/apache/nifi/web/api/ConnectorResource.java | 327 ++++++++++++++++++++-
.../nifi/web/api/ParameterContextResource.java | 4 +-
.../org/apache/nifi/web/api/dto/DtoFactory.java | 22 +-
.../configuration/WebApplicationConfiguration.java | 1 +
.../java/org/apache/nifi/web/dao/ConnectorDAO.java | 16 +-
.../nifi/web/dao/impl/StandardConnectorDAO.java | 97 +++++-
.../web/dao/impl/StandardParameterContextDAO.java | 2 +-
.../web/dao/impl/StandardConnectorDAOTest.java | 25 ++
.../connectors/tests/system/AssetConnector.java | 93 ++++++
.../org.apache.nifi.components.connector.Connector | 3 +
.../connectors/ClusteredConnectorAssetsIT.java | 142 +++++++++
.../tests/system/connectors/ConnectorAssetsIT.java | 202 +++++++++++++
.../nifi/toolkit/client/ConnectorClient.java | 39 +++
.../toolkit/client/impl/JerseyConnectorClient.java | 86 ++++++
.../nifi/toolkit/client/impl/JerseyNiFiClient.java | 2 +-
48 files changed, 1975 insertions(+), 236 deletions(-)
diff --git a/nifi-commons/nifi-properties/src/main/java/org/apache/nifi/util/NiFiProperties.java b/nifi-commons/nifi-properties/src/main/java/org/apache/nifi/util/NiFiProperties.java
index ecfa644fd3..38d00cc682 100644
--- a/nifi-commons/nifi-properties/src/main/java/org/apache/nifi/util/NiFiProperties.java
+++ b/nifi-commons/nifi-properties/src/main/java/org/apache/nifi/util/NiFiProperties.java
@@ -124,6 +124,9 @@ public class NiFiProperties extends ApplicationProperties {
public static final String ASSET_MANAGER_IMPLEMENTATION = "nifi.asset.manager.implementation";
public static final String ASSET_MANAGER_PREFIX = "nifi.asset.manager.properties.";
+ public static final String CONNECTOR_ASSET_MANAGER_IMPLEMENTATION = "nifi.connector.asset.manager.implementation";
+ public static final String CONNECTOR_ASSET_MANAGER_PREFIX = "nifi.connector.asset.manager.properties.";
+
// status repository properties
public static final String COMPONENT_STATUS_REPOSITORY_IMPLEMENTATION = "nifi.components.status.repository.implementation";
public static final String COMPONENT_STATUS_SNAPSHOT_FREQUENCY = "nifi.components.status.snapshot.frequency";
diff --git a/nifi-framework-api/src/main/java/org/apache/nifi/asset/AssetManager.java b/nifi-framework-api/src/main/java/org/apache/nifi/asset/AssetManager.java
index d1501c2f93..321d0afe7b 100644
--- a/nifi-framework-api/src/main/java/org/apache/nifi/asset/AssetManager.java
+++ b/nifi-framework-api/src/main/java/org/apache/nifi/asset/AssetManager.java
@@ -31,13 +31,25 @@ public interface AssetManager {
/**
* Creates a new Asset with the given name and contents.
- * @param parameterContextId the id of the parameter context
+ * @param ownerId the id of the resource that this asset belongs to
* @param assetName the name of the asset
* @param contents the contents of the asset
* @return the created asset
* @throws IOException if there is an error creating the asset
*/
- Asset createAsset(String parameterContextId, String assetName, InputStream contents) throws IOException;
+ Asset createAsset(String ownerId, String assetName, InputStream contents) throws IOException;
+
+ /**
+ * Saves the given asset. If an asset already exists with the given identifier, the content will be replaced.
+ *
+ * @param ownerId the id of the resource that this asset belongs to
+ * @param assetId the identifier of the asset
+ * @param assetName the name of the asset
+ * @param contents the new contents of the asset
+ * @return the created or updated Asset
+ * @throws IOException if there is an error writing the asset
+ */
+ Asset saveAsset(String ownerId, String assetId, String assetName, InputStream contents) throws IOException;
/**
* Retrieves the Asset with the given id, if it exists.
@@ -47,22 +59,22 @@ public interface AssetManager {
Optional<Asset> getAsset(String id);
/**
- * Retrieves the Assets that belong to the given parameter context.
- * @param parameterContextId the id of the parameter context
- * @return the list of assets for the given context
+ * Retrieves the Assets that belong to the given owner.
+ * @param ownerId the id of the owner resource
+ * @return the list of assets for the given owner
*/
- List<Asset> getAssets(String parameterContextId);
+ List<Asset> getAssets(String ownerId);
/**
- * Creates an Asset with the given name and associates it with the given parameter context. If the asset already exists, it is returned. Otherwise, an asset is created
+ * Creates an Asset with the given name and associates it with the given owner. If the asset already exists, it is returned. Otherwise, an asset is created
* but the underlying file is not created. This allows the asset to be referenced but any component that attempts to use the asset will still see a File that does not exist, which
* will typically lead to an invalid component.
*
- * @param parameterContextId the id of the parameter context
+ * @param ownerId the id of the owner
* @param assetName the name of the asset
* @return the created asset
*/
- Asset createMissingAsset(String parameterContextId, String assetName);
+ Asset createMissingAsset(String ownerId, String assetName);
/**
* Deletes the Asset with the given id, if it exists.
diff --git a/nifi-framework-bundle/nifi-framework/nifi-client-dto/src/main/java/org/apache/nifi/web/api/dto/ConnectorValueReferenceDTO.java b/nifi-framework-bundle/nifi-framework/nifi-client-dto/src/main/java/org/apache/nifi/web/api/dto/ConnectorValueReferenceDTO.java
index 297ddee44c..ed79bdb3ac 100644
--- a/nifi-framework-bundle/nifi-framework/nifi-client-dto/src/main/java/org/apache/nifi/web/api/dto/ConnectorValueReferenceDTO.java
+++ b/nifi-framework-bundle/nifi-framework/nifi-client-dto/src/main/java/org/apache/nifi/web/api/dto/ConnectorValueReferenceDTO.java
@@ -19,6 +19,8 @@ package org.apache.nifi.web.api.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.xml.bind.annotation.XmlType;
+import java.util.List;
+
/**
* A reference to a connector property value, which includes the value and its type.
* The value can be a string literal, a reference to an asset, or a reference to a secret.
@@ -28,11 +30,11 @@ public class ConnectorValueReferenceDTO {
private String valueType;
private String value;
- private String assetIdentifier;
private String secretProviderId;
private String secretProviderName;
private String secretName;
private String fullyQualifiedSecretName;
+ private List<AssetReferenceDTO> assetReferences;
/**
* @return the type of value (STRING_LITERAL, ASSET_REFERENCE, or SECRET_REFERENCE)
@@ -58,18 +60,6 @@ public class ConnectorValueReferenceDTO {
this.value = value;
}
- /**
- * @return the asset identifier when valueType is ASSET_REFERENCE
- */
- @Schema(description = "The asset identifier. Applicable when valueType is ASSET_REFERENCE.")
- public String getAssetIdentifier() {
- return assetIdentifier;
- }
-
- public void setAssetIdentifier(final String assetIdentifier) {
- this.assetIdentifier = assetIdentifier;
- }
-
/**
* @return the secret provider identifier when valueType is SECRET_REFERENCE
*/
@@ -114,5 +104,17 @@ public class ConnectorValueReferenceDTO {
public String getFullyQualifiedSecretName() {
return fullyQualifiedSecretName;
}
+
+ /**
+ * @return the asset identifiers when valueType is ASSET_REFERENCE
+ */
+ @Schema(description = "The asset references. Applicable when valueType is ASSET_REFERENCE.")
+ public List<AssetReferenceDTO> getAssetReferences() {
+ return assetReferences;
+ }
+
+ public void setAssetReferences(final List<AssetReferenceDTO> assetReferences) {
+ this.assetReferences = assetReferences;
+ }
}
diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-cluster/src/main/java/org/apache/nifi/cluster/coordination/http/endpoints/AssetsEndpointMerger.java b/nifi-framework-bundle/nifi-framework/nifi-framework-cluster/src/main/java/org/apache/nifi/cluster/coordination/http/endpoints/AssetsEndpointMerger.java
index 422ade1492..bcf5e0e066 100644
--- a/nifi-framework-bundle/nifi-framework/nifi-framework-cluster/src/main/java/org/apache/nifi/cluster/coordination/http/endpoints/AssetsEndpointMerger.java
+++ b/nifi-framework-bundle/nifi-framework/nifi-framework-cluster/src/main/java/org/apache/nifi/cluster/coordination/http/endpoints/AssetsEndpointMerger.java
@@ -31,7 +31,7 @@ import java.util.regex.Pattern;
public class AssetsEndpointMerger extends AbstractSingleDTOEndpoint<AssetsEntity, Collection<AssetEntity>> {
- private static final Pattern ASSETS_URI = Pattern.compile("/nifi-api/parameter-contexts/[a-f0-9\\-]{36}/assets");
+ private static final Pattern ASSETS_URI = Pattern.compile("/nifi-api/(parameter-contexts|connectors)/[a-f0-9\\-]{36}/assets");
@Override
public boolean canHandle(final URI uri, final String method) {
diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-components/src/main/java/org/apache/nifi/asset/StandardAsset.java b/nifi-framework-bundle/nifi-framework/nifi-framework-components/src/main/java/org/apache/nifi/asset/StandardAsset.java
index 77e2ef5b64..ed0cea997b 100644
--- a/nifi-framework-bundle/nifi-framework/nifi-framework-components/src/main/java/org/apache/nifi/asset/StandardAsset.java
+++ b/nifi-framework-bundle/nifi-framework/nifi-framework-components/src/main/java/org/apache/nifi/asset/StandardAsset.java
@@ -23,14 +23,14 @@ import java.util.Optional;
public class StandardAsset implements Asset {
private final String identifier;
- private final String parameterContextIdentifier;
+ private final String ownerIdentifier;
private final String name;
private final File file;
private final String digest;
- public StandardAsset(final String identifier, final String paramContextIdentifier, final String name, final File file, final String digest) {
+ public StandardAsset(final String identifier, final String ownerIdentifier, final String name, final File file, final String digest) {
this.identifier = Objects.requireNonNull(identifier, "Identifier is required");
- this.parameterContextIdentifier = Objects.requireNonNull(paramContextIdentifier, "Parameter Context Identifier is required");
+ this.ownerIdentifier = Objects.requireNonNull(ownerIdentifier, "Owner Identifier is required");
this.name = Objects.requireNonNull(name, "Name is required");
this.file = Objects.requireNonNull(file, "File is required");
this.digest = digest;
@@ -43,7 +43,12 @@ public class StandardAsset implements Asset {
@Override
public String getParameterContextIdentifier() {
- return parameterContextIdentifier;
+ return ownerIdentifier;
+ }
+
+ @Override
+ public String getOwnerIdentifier() {
+ return ownerIdentifier;
}
@Override
diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-components/src/main/java/org/apache/nifi/asset/StandardAssetManager.java b/nifi-framework-bundle/nifi-framework/nifi-framework-components/src/main/java/org/apache/nifi/asset/StandardAssetManager.java
index f643cccf3a..28b9054622 100644
--- a/nifi-framework-bundle/nifi-framework/nifi-framework-components/src/main/java/org/apache/nifi/asset/StandardAssetManager.java
+++ b/nifi-framework-bundle/nifi-framework/nifi-framework-components/src/main/java/org/apache/nifi/asset/StandardAssetManager.java
@@ -68,36 +68,20 @@ public class StandardAssetManager implements AssetManager {
}
@Override
- public Asset createAsset(final String parameterContextId, final String assetName, final InputStream contents) throws IOException {
- final String assetId = createAssetId(parameterContextId, assetName);
-
- final File file = getFile(parameterContextId, assetName);
- final File dir = file.getParentFile();
- if (!dir.exists()) {
- try {
- Files.createDirectories(dir.toPath());
- } catch (final IOException ioe) {
- throw new IOException("Could not create directory in order to store asset", ioe);
- }
- }
-
- // Write contents to a temporary file, then move it to the final location.
- // This allows us to avoid a situation where we upload a file, then we attempt to overwrite it but fail, leaving a corrupt asset.
- final File tempFile = new File(dir, file.getName() + ".tmp");
- logger.debug("Writing temp asset file [{}]", tempFile.getAbsolutePath());
+ public Asset createAsset(final String ownerId, final String assetName, final InputStream contents) throws IOException {
+ final String assetId = createAssetId(ownerId, assetName);
+ final File assetFile = getFile(ownerId, assetName);
+ return saveAsset(ownerId, assetId, assetName, contents, assetFile);
+ }
- try {
- Files.copy(contents, tempFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
- } catch (final Exception e) {
- throw new IOException("Failed to write asset to file " + tempFile.getAbsolutePath(), e);
+ @Override
+ public Asset saveAsset(final String ownerId, final String assetId, final String assetName, final InputStream contents) throws IOException {
+ final String generatedAssetId = createAssetId(ownerId, assetName);
+ if (!generatedAssetId.equals(assetId)) {
+ throw new IllegalArgumentException("The provided asset id [%s] does not match the id this asset manager generated for the given owner and name".formatted(assetId));
}
-
- Files.move(tempFile.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING);
-
- final String digest = computeDigest(file);
- final Asset asset = new StandardAsset(assetId, parameterContextId, assetName, file, digest);
- assets.put(assetId, asset);
- return asset;
+ final File assetFile = getFile(ownerId, assetName);
+ return saveAsset(ownerId, assetId, assetName, contents, assetFile);
}
@Override
@@ -106,22 +90,22 @@ public class StandardAssetManager implements AssetManager {
}
@Override
- public List<Asset> getAssets(final String parameterContextId) {
+ public List<Asset> getAssets(final String ownerId) {
final List<Asset> allAssets = new ArrayList<>(assets.values());
- final List<Asset> paramContextAssets = new ArrayList<>();
+ final List<Asset> ownerAssets = new ArrayList<>();
for (final Asset asset : allAssets) {
- if (asset.getParameterContextIdentifier().equals(parameterContextId)) {
- paramContextAssets.add(asset);
+ if (asset.getOwnerIdentifier().equals(ownerId)) {
+ ownerAssets.add(asset);
}
}
- return paramContextAssets;
+ return ownerAssets;
}
@Override
- public Asset createMissingAsset(final String parameterContextId, final String assetName) {
- final String assetId = createAssetId(parameterContextId, assetName);
- final File file = getFile(parameterContextId, assetName);
- final Asset asset = new StandardAsset(assetId, parameterContextId, assetName, file, null);
+ public Asset createMissingAsset(final String ownerId, final String assetName) {
+ final String assetId = createAssetId(ownerId, assetName);
+ final File file = getFile(ownerId, assetName);
+ final Asset asset = new StandardAsset(assetId, ownerId, assetName, file, null);
assets.put(assetId, asset);
return asset;
}
@@ -155,14 +139,43 @@ public class StandardAssetManager implements AssetManager {
return Optional.of(removed);
}
- private String createAssetId(final String parameterContextId, final String assetName) {
- final String seed = parameterContextId + "/" + assetName;
+ private Asset saveAsset(final String ownerId, final String assetId, final String assetName, final InputStream contents, final File assetFile) throws IOException {
+ final File dir = assetFile.getParentFile();
+ if (!dir.exists()) {
+ try {
+ Files.createDirectories(dir.toPath());
+ } catch (final IOException ioe) {
+ throw new IOException("Could not create directory in order to store asset", ioe);
+ }
+ }
+
+ // Write contents to a temporary file, then move it to the final location.
+ // This allows us to avoid a situation where we upload a file, then we attempt to overwrite it but fail, leaving a corrupt asset.
+ final File tempFile = new File(dir, assetFile.getName() + ".tmp");
+ logger.debug("Writing temp asset file [{}]", tempFile.getAbsolutePath());
+
+ try {
+ Files.copy(contents, tempFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
+ } catch (final Exception e) {
+ throw new IOException("Failed to write asset to file " + tempFile.getAbsolutePath(), e);
+ }
+
+ Files.move(tempFile.toPath(), assetFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
+
+ final String digest = computeDigest(assetFile);
+ final Asset asset = new StandardAsset(assetId, ownerId, assetName, assetFile, digest);
+ assets.put(assetId, asset);
+ return asset;
+ }
+
+ private String createAssetId(final String ownerId, final String assetName) {
+ final String seed = ownerId + "/" + assetName;
return UUID.nameUUIDFromBytes(seed.getBytes(StandardCharsets.UTF_8)).toString();
}
- private File getFile(final String paramContextId, final String assetName) {
+ private File getFile(final String ownerId, final String assetName) {
final Path parentPath = assetStorageLocation.toPath().normalize();
- final Path assetPath = Paths.get(paramContextId, assetName).normalize();
+ final Path assetPath = Paths.get(ownerId, assetName).normalize();
final Path fullPath = parentPath.resolve(assetPath);
return fullPath.toFile();
}
@@ -183,17 +196,17 @@ public class StandardAssetManager implements AssetManager {
continue;
}
- final String contextId = file.getName();
+ final String ownerId = file.getName();
final File[] assetFiles = file.listFiles();
if (assetFiles == null) {
- logger.warn("Unable to determine which assets exist for Parameter Context {}", contextId);
+ logger.warn("Unable to determine which assets exist for owner {}", ownerId);
continue;
}
for (final File assetFile : assetFiles) {
- final String assetId = createAssetId(contextId, assetFile.getName());
+ final String assetId = createAssetId(ownerId, assetFile.getName());
final String digest = computeDigest(assetFile);
- final Asset asset = new StandardAsset(assetId, contextId, assetFile.getName(), assetFile, digest);
+ final Asset asset = new StandardAsset(assetId, ownerId, assetFile.getName(), assetFile, digest);
assets.put(assetId, asset);
}
}
diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-components/src/main/java/org/apache/nifi/asset/StandardConnectorAssetManager.java b/nifi-framework-bundle/nifi-framework/nifi-framework-components/src/main/java/org/apache/nifi/asset/StandardConnectorAssetManager.java
new file mode 100644
index 0000000000..7cc907de11
--- /dev/null
+++ b/nifi-framework-bundle/nifi-framework/nifi-framework-components/src/main/java/org/apache/nifi/asset/StandardConnectorAssetManager.java
@@ -0,0 +1,225 @@
+/*
+ * 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.asset;
+
+import org.apache.nifi.nar.FileDigestUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.nio.file.StandardCopyOption;
+import java.util.ArrayList;
+import java.util.HexFormat;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+
+/**
+ * AssetManager implementation for Connectors. This differs from the StandardAssetManager used for Parameter Contexts in that
+ * Connectors want every asset added to be treated as a new asset, even if the same filename is being saved to the same Connector.
+ * This is because all changes to the Connector needs to be stored separately in the working configuration until applied and can
+ * not interfere with the active configuration.
+ */
+public class StandardConnectorAssetManager implements AssetManager {
+
+ private static final Logger logger = LoggerFactory.getLogger(StandardConnectorAssetManager.class);
+
+ public static final String ASSET_STORAGE_LOCATION_PROPERTY = "directory";
+ public static final String DEFAULT_ASSET_STORAGE_LOCATION = "./connector-assets";
+
+ private volatile File assetStorageLocation;
+ private final Map<String, Asset> assets = new ConcurrentHashMap<>();
+
+ @Override
+ public void initialize(final AssetManagerInitializationContext context) {
+ final String storageLocation = getStorageLocation(context);
+
+ assetStorageLocation = new File(storageLocation);
+ if (!assetStorageLocation.exists()) {
+ try {
+ Files.createDirectories(assetStorageLocation.toPath());
+ } catch (IOException e) {
+ throw new RuntimeException("The Connector Asset Manager's [%s] property is set to [%s] but the directory does not exist and cannot be created"
+ .formatted(ASSET_STORAGE_LOCATION_PROPERTY, storageLocation), e);
+ }
+ }
+
+ try {
+ recoverLocalAssets();
+ } catch (final IOException e) {
+ throw new RuntimeException("Unable to access connector assets", e);
+ }
+ }
+
+ @Override
+ public Asset createAsset(final String connectorId, final String assetName, final InputStream contents) throws IOException {
+ final String assetId = generateAssetId();
+ final File assetFile = getFile(connectorId, assetId, assetName);
+ return saveAsset(connectorId, assetId, assetName, contents, assetFile);
+ }
+
+ @Override
+ public Asset saveAsset(final String connectorId, final String assetId, final String assetName, final InputStream contents) throws IOException {
+ final File assetFile = getFile(connectorId, assetId, assetName);
+ return saveAsset(connectorId, assetId, assetName, contents, assetFile);
+ }
+
+ @Override
+ public Optional<Asset> getAsset(final String id) {
+ return Optional.ofNullable(assets.get(id));
+ }
+
+ @Override
+ public List<Asset> getAssets(final String connectorId) {
+ final List<Asset> allAssets = new ArrayList<>(assets.values());
+ final List<Asset> ownerAssets = new ArrayList<>();
+ for (final Asset asset : allAssets) {
+ if (asset.getOwnerIdentifier().equals(connectorId)) {
+ ownerAssets.add(asset);
+ }
+ }
+ return ownerAssets;
+ }
+
+ @Override
+ public Asset createMissingAsset(final String connectorId, final String assetName) {
+ final String assetId = generateAssetId();
+ final File file = getFile(connectorId, assetId, assetName);
+ final Asset asset = new StandardAsset(assetId, connectorId, assetName, file, null);
+ assets.put(assetId, asset);
+ return asset;
+ }
+
+ @Override
+ public Optional<Asset> deleteAsset(final String id) {
+ final Asset removed = assets.remove(id);
+ if (removed == null) {
+ return Optional.empty();
+ }
+
+ final File assetFile = removed.getFile();
+ if (assetFile.exists()) {
+ deleteFile(assetFile);
+
+ final File assetIdDir = assetFile.getParentFile();
+ deleteFile(assetIdDir);
+
+ final File connectorDir = assetIdDir.getParentFile();
+ final File[] children = connectorDir.listFiles();
+ if (children != null && children.length == 0) {
+ deleteFile(connectorDir);
+ }
+ }
+
+ return Optional.of(removed);
+ }
+
+ private Asset saveAsset(final String connectorId, final String assetId, final String assetName, final InputStream contents, final File assetFile) throws IOException {
+ final File dir = assetFile.getParentFile();
+ if (!dir.exists()) {
+ try {
+ Files.createDirectories(dir.toPath());
+ } catch (final IOException ioe) {
+ throw new IOException("Could not create directory in order to store connector asset", ioe);
+ }
+ }
+
+ try {
+ Files.copy(contents, assetFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
+ } catch (final Exception e) {
+ throw new IOException("Failed to write connector asset to file " + assetFile.getAbsolutePath(), e);
+ }
+
+ final String digest = computeDigest(assetFile);
+ final Asset asset = new StandardAsset(assetId, connectorId, assetName, assetFile, digest);
+ assets.put(assetId, asset);
+ return asset;
+ }
+
+ private void deleteFile(final File file) {
+ try {
+ Files.delete(file.toPath());
+ } catch (final IOException e) {
+ logger.warn("Failed to delete [{}]", file.getAbsolutePath(), e);
+ }
+ }
+
+ private String generateAssetId() {
+ return UUID.randomUUID().toString();
+ }
+
+ private File getFile(final String connectorId, final String assetId, final String assetName) {
+ final Path parentPath = assetStorageLocation.toPath().normalize();
+ final Path assetPath = Paths.get(connectorId, assetId, assetName).normalize();
+ final Path fullPath = parentPath.resolve(assetPath);
+ return fullPath.toFile();
+ }
+
+ private String getStorageLocation(final AssetManagerInitializationContext initializationContext) {
+ final String storageLocation = initializationContext.getProperties().get(ASSET_STORAGE_LOCATION_PROPERTY);
+ return storageLocation == null ? DEFAULT_ASSET_STORAGE_LOCATION : storageLocation;
+ }
+
+ private void recoverLocalAssets() throws IOException {
+ final File[] connectorDirectories = assetStorageLocation.listFiles();
+ if (connectorDirectories == null) {
+ throw new IOException("Unable to list files for connector asset storage location %s".formatted(assetStorageLocation.getAbsolutePath()));
+ }
+
+ for (final File connectorDirectory : connectorDirectories) {
+ if (!connectorDirectory.isDirectory()) {
+ continue;
+ }
+
+ final String connectorId = connectorDirectory.getName();
+ final File[] assetIdDirectories = connectorDirectory.listFiles();
+ if (assetIdDirectories == null) {
+ logger.warn("Unable to list directory [{}]", connectorDirectory.getAbsolutePath());
+ continue;
+ }
+
+ for (final File assetIdDirectory : assetIdDirectories) {
+ final String assetId = assetIdDirectory.getName();
+
+ final File[] assetFiles = assetIdDirectory.listFiles();
+ if (assetFiles == null) {
+ logger.warn("Unable to list directory [{}]", assetIdDirectory.getAbsolutePath());
+ continue;
+ }
+
+ for (final File assetFile : assetFiles) {
+ final String assetName = assetFile.getName();
+ final String digest = computeDigest(assetFile);
+ final Asset asset = new StandardAsset(assetId, connectorId, assetName, assetFile, digest);
+ assets.put(assetId, asset);
+ }
+ }
+ }
+ }
+
+ private String computeDigest(final File file) throws IOException {
+ return HexFormat.of().formatHex(FileDigestUtils.getDigest(file));
+ }
+
+}
diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-components/src/main/java/org/apache/nifi/registry/flow/mapping/VersionedComponentFlowMapper.java b/nifi-framework-bundle/nifi-framework/nifi-framework-components/src/main/java/org/apache/nifi/registry/flow/mapping/VersionedComponentFlowMapper.java
index c31b3f284a..655dcf99ca 100644
--- a/nifi-framework-bundle/nifi-framework/nifi-framework-components/src/main/java/org/apache/nifi/registry/flow/mapping/VersionedComponentFlowMapper.java
+++ b/nifi-framework-bundle/nifi-framework/nifi-framework-components/src/main/java/org/apache/nifi/registry/flow/mapping/VersionedComponentFlowMapper.java
@@ -1085,7 +1085,7 @@ public class VersionedComponentFlowMapper {
switch (valueReference) {
case StringLiteralValue stringLiteral -> versionedReference.setValue(stringLiteral.getValue());
- case AssetReference assetRef -> versionedReference.setAssetId(assetRef.getAssetIdentifier());
+ case AssetReference assetRef -> versionedReference.setAssetIds(assetRef.getAssetIdentifiers());
case SecretReference secretRef -> {
versionedReference.setProviderId(secretRef.getProviderId());
versionedReference.setProviderName(secretRef.getProviderName());
diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-components/src/main/resources/META-INF/services/org.apache.nifi.asset.AssetManager b/nifi-framework-bundle/nifi-framework/nifi-framework-components/src/main/resources/META-INF/services/org.apache.nifi.asset.AssetManager
index 6fbf05d949..3a438fb65d 100644
--- a/nifi-framework-bundle/nifi-framework/nifi-framework-components/src/main/resources/META-INF/services/org.apache.nifi.asset.AssetManager
+++ b/nifi-framework-bundle/nifi-framework/nifi-framework-components/src/main/resources/META-INF/services/org.apache.nifi.asset.AssetManager
@@ -13,4 +13,5 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-org.apache.nifi.asset.StandardAssetManager
\ No newline at end of file
+org.apache.nifi.asset.StandardAssetManager
+org.apache.nifi.asset.StandardConnectorAssetManager
\ No newline at end of file
diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-components/src/test/java/org/apache/nifi/asset/StandardConnectorAssetManagerTest.java b/nifi-framework-bundle/nifi-framework/nifi-framework-components/src/test/java/org/apache/nifi/asset/StandardConnectorAssetManagerTest.java
new file mode 100644
index 0000000000..fa13d28bba
--- /dev/null
+++ b/nifi-framework-bundle/nifi-framework/nifi-framework-components/src/test/java/org/apache/nifi/asset/StandardConnectorAssetManagerTest.java
@@ -0,0 +1,178 @@
+/*
+ * 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.asset;
+
+import org.apache.nifi.controller.NodeTypeProvider;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+import java.io.ByteArrayInputStream;
+import java.io.File;
+import java.io.InputStream;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.Mockito.mock;
+
+class StandardConnectorAssetManagerTest {
+
+ @Test
+ void testInitializeRecoversExistingAssets(@TempDir final Path tempDir) throws Exception {
+ final Path storageDirectory = tempDir.resolve("assets");
+ final String connectorIdentifier = "connector-1";
+ final String assetIdentifier = "asset-1";
+ final String assetName = "asset.txt";
+
+ final Path assetDirectory = storageDirectory.resolve(connectorIdentifier).resolve(assetIdentifier);
+ Files.createDirectories(assetDirectory);
+ final Path assetPath = assetDirectory.resolve(assetName);
+ Files.writeString(assetPath, "existing-content", StandardCharsets.UTF_8);
+
+ final StandardConnectorAssetManager manager = new StandardConnectorAssetManager();
+ final AssetManagerInitializationContext context = createInitializationContext(storageDirectory.toFile());
+ manager.initialize(context);
+
+ final List<Asset> assets = manager.getAssets(connectorIdentifier);
+ assertEquals(1, assets.size());
+
+ final Asset recoveredAsset = assets.getFirst();
+ assertEquals(assetName, recoveredAsset.getName());
+ assertEquals(connectorIdentifier, recoveredAsset.getOwnerIdentifier());
+ assertTrue(recoveredAsset.getDigest().isPresent());
+ assertEquals(assetPath.toFile().getAbsolutePath(), recoveredAsset.getFile().getAbsolutePath());
+ }
+
+ @Test
+ void testCreateAssetAndGetAsset(@TempDir final Path tempDir) throws Exception {
+ final Path storageDirectory = tempDir.resolve("assets");
+ final StandardConnectorAssetManager manager = new StandardConnectorAssetManager();
+ final AssetManagerInitializationContext context = createInitializationContext(storageDirectory.toFile());
+ manager.initialize(context);
+
+ assertTrue(Files.isDirectory(storageDirectory));
+
+ final String connectorIdentifier = "connector-1";
+ final String assetName = "created-asset.txt";
+ final byte[] contents = "created-content".getBytes(StandardCharsets.UTF_8);
+ final InputStream inputStream = new ByteArrayInputStream(contents);
+
+ final Asset createdAsset = manager.createAsset(connectorIdentifier, assetName, inputStream);
+ assertNotNull(createdAsset);
+ assertEquals(connectorIdentifier, createdAsset.getOwnerIdentifier());
+ assertEquals(assetName, createdAsset.getName());
+ assertTrue(createdAsset.getDigest().isPresent());
+ assertTrue(createdAsset.getFile().exists());
+
+ final Optional<Asset> retrievedByIdentifier = manager.getAsset(createdAsset.getIdentifier());
+ assertTrue(retrievedByIdentifier.isPresent());
+ assertEquals(createdAsset.getIdentifier(), retrievedByIdentifier.get().getIdentifier());
+
+ final List<Asset> connectorAssets = manager.getAssets(connectorIdentifier);
+ assertEquals(1, connectorAssets.size());
+ assertEquals(createdAsset.getIdentifier(), connectorAssets.get(0).getIdentifier());
+ }
+
+ @Test
+ void testCreateMissingAssetDoesNotCreateFile(@TempDir final Path tempDir) {
+ final Path storageDirectory = tempDir.resolve("assets");
+ final StandardConnectorAssetManager manager = new StandardConnectorAssetManager();
+ final AssetManagerInitializationContext context = createInitializationContext(storageDirectory.toFile());
+ manager.initialize(context);
+
+ final String connectorIdentifier = "connector-2";
+ final String assetName = "missing-asset.txt";
+
+ final Asset missingAsset = manager.createMissingAsset(connectorIdentifier, assetName);
+ assertNotNull(missingAsset);
+ assertEquals(connectorIdentifier, missingAsset.getOwnerIdentifier());
+ assertEquals(assetName, missingAsset.getName());
+ assertFalse(missingAsset.getDigest().isPresent());
+ assertFalse(missingAsset.getFile().exists());
+
+ final Optional<Asset> retrieved = manager.getAsset(missingAsset.getIdentifier());
+ assertTrue(retrieved.isPresent());
+ assertEquals(missingAsset.getIdentifier(), retrieved.get().getIdentifier());
+
+ final List<Asset> connectorAssets = manager.getAssets(connectorIdentifier);
+ assertEquals(1, connectorAssets.size());
+ assertEquals(missingAsset.getIdentifier(), connectorAssets.getFirst().getIdentifier());
+ }
+
+ @Test
+ void testDeleteAssetRemovesFilesAndDirectories(@TempDir final Path tempDir) throws Exception {
+ final Path storageDirectory = tempDir.resolve("assets");
+ final StandardConnectorAssetManager manager = new StandardConnectorAssetManager();
+ final AssetManagerInitializationContext context = createInitializationContext(storageDirectory.toFile());
+ manager.initialize(context);
+
+ final String connectorIdentifier = "connector-3";
+ final String assetName = "deletable-asset.txt";
+ final byte[] contents = "deletable-content".getBytes(StandardCharsets.UTF_8);
+ final InputStream inputStream = new ByteArrayInputStream(contents);
+
+ final Asset asset = manager.createAsset(connectorIdentifier, assetName, inputStream);
+ final File assetFile = asset.getFile();
+ final File assetDirectory = assetFile.getParentFile();
+ final File connectorDirectory = assetDirectory.getParentFile();
+
+ assertTrue(assetFile.exists());
+ assertTrue(assetDirectory.exists());
+ assertTrue(connectorDirectory.exists());
+
+ final Optional<Asset> deleted = manager.deleteAsset(asset.getIdentifier());
+ assertTrue(deleted.isPresent());
+ assertFalse(assetFile.exists());
+ assertFalse(assetDirectory.exists());
+ assertFalse(connectorDirectory.exists());
+
+ assertTrue(manager.getAsset(asset.getIdentifier()).isEmpty());
+ assertTrue(manager.getAssets(connectorIdentifier).isEmpty());
+ }
+
+ @Test
+ void testDeleteNonExistentAssetReturnsEmpty(@TempDir final Path tempDir) {
+ final Path storageDirectory = tempDir.resolve("assets");
+ final StandardConnectorAssetManager manager = new StandardConnectorAssetManager();
+ final AssetManagerInitializationContext context = createInitializationContext(storageDirectory.toFile());
+ manager.initialize(context);
+
+ final Optional<Asset> deleted = manager.deleteAsset("non-existent-id");
+ assertTrue(deleted.isEmpty());
+ }
+
+ private AssetManagerInitializationContext createInitializationContext(final File storageDirectory) {
+ final Map<String, String> properties = new HashMap<>();
+ properties.put(StandardConnectorAssetManager.ASSET_STORAGE_LOCATION_PROPERTY, storageDirectory.getAbsolutePath());
+
+ final AssetReferenceLookup assetReferenceLookup = mock(AssetReferenceLookup.class);
+ final NodeTypeProvider nodeTypeProvider = mock(NodeTypeProvider.class);
+
+ return new StandardAssetManagerInitializationContext(assetReferenceLookup, properties, nodeTypeProvider);
+ }
+}
+
+
diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/ConnectorRepositoryInitializationContext.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/ConnectorAssetRepository.java
similarity index 63%
copy from nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/ConnectorRepositoryInitializationContext.java
copy to nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/ConnectorAssetRepository.java
index 0f0c50c394..8305b0b0e4 100644
--- a/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/ConnectorRepositoryInitializationContext.java
+++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/ConnectorAssetRepository.java
@@ -14,24 +14,25 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.apache.nifi.components.connector;
-import org.apache.nifi.components.connector.secrets.SecretsManager;
-import org.apache.nifi.controller.NodeTypeProvider;
-import org.apache.nifi.controller.flow.FlowManager;
-import org.apache.nifi.nar.ExtensionManager;
+import org.apache.nifi.asset.Asset;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.List;
+import java.util.Optional;
-public interface ConnectorRepositoryInitializationContext {
+public interface ConnectorAssetRepository {
- FlowManager getFlowManager();
+ Asset storeAsset(String connectorId, String assetId, String assetName, InputStream content) throws IOException;
- ExtensionManager getExtensionManager();
+ Optional<Asset> getAsset(String assetId);
- SecretsManager getSecretsManager();
+ List<Asset> getAssets(String connectorId);
- NodeTypeProvider getNodeTypeProvider();
+ void deleteAsset(String assetId);
- ConnectorRequestReplicator getRequestReplicator();
+ void deleteAssets(String connectorId);
}
diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/ConnectorRepository.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/ConnectorRepository.java
index be39e14dc6..2a134d8e5e 100644
--- a/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/ConnectorRepository.java
+++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/ConnectorRepository.java
@@ -96,4 +96,5 @@ public interface ConnectorRepository {
FrameworkConnectorInitializationContextBuilder createInitializationContextBuilder();
+ ConnectorAssetRepository getAssetRepository();
}
diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/ConnectorRepositoryInitializationContext.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/ConnectorRepositoryInitializationContext.java
index 0f0c50c394..9723e85e16 100644
--- a/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/ConnectorRepositoryInitializationContext.java
+++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/ConnectorRepositoryInitializationContext.java
@@ -18,6 +18,7 @@
package org.apache.nifi.components.connector;
import org.apache.nifi.components.connector.secrets.SecretsManager;
+import org.apache.nifi.asset.AssetManager;
import org.apache.nifi.controller.NodeTypeProvider;
import org.apache.nifi.controller.flow.FlowManager;
import org.apache.nifi.nar.ExtensionManager;
@@ -30,6 +31,8 @@ public interface ConnectorRepositoryInitializationContext {
SecretsManager getSecretsManager();
+ AssetManager getAssetManager();
+
NodeTypeProvider getNodeTypeProvider();
ConnectorRequestReplicator getRequestReplicator();
diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/asset/AssetsRestApiClient.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/asset/AssetsRestApiClient.java
index b8f2052dd5..29cecc02a0 100644
--- a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/asset/AssetsRestApiClient.java
+++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/asset/AssetsRestApiClient.java
@@ -40,13 +40,14 @@ class AssetsRestApiClient extends NiFiRestApiClient {
private static final String NIFI_API_PATH_PART = "nifi-api";
private static final String PARAMETER_CONTEXTS_PATH_PART = "parameter-contexts";
+ private static final String CONNECTORS_PATH_PART = "connectors";
private static final String ASSETS_PATH_PART = "assets";
public AssetsRestApiClient(final WebClientService webClientService, final String host, final int port, final boolean secure) {
super(webClientService, host, port, secure);
}
- public AssetsEntity getAssets(final String parameterContextId) {
+ public AssetsEntity getParameterContextAssets(final String parameterContextId) {
final URI requestUri = new StandardHttpUriBuilder()
.scheme(baseUri.getScheme())
.host(baseUri.getHost())
@@ -56,7 +57,7 @@ class AssetsRestApiClient extends NiFiRestApiClient {
.addPathSegment(parameterContextId)
.addPathSegment(ASSETS_PATH_PART)
.build();
- logger.debug("Requesting Asset listing from {}", requestUri);
+ logger.debug("Requesting Parameter Context Asset listing from {}", requestUri);
// Send the replicated header so that the cluster coordinator does not replicate the request, otherwise this call can happen when no nodes
// are considered connected and result in a 500 exception that can't easily be differentiated from other unknown errors
@@ -68,7 +69,7 @@ class AssetsRestApiClient extends NiFiRestApiClient {
return executeEntityRequest(requestUri, requestBodySpec, AssetsEntity.class);
}
- public InputStream getAssetContent(final String parameterContextId, final String assetId) {
+ public InputStream getParameterContextAssetContent(final String parameterContextId, final String assetId) {
final URI requestUri = new StandardHttpUriBuilder()
.scheme(baseUri.getScheme())
.host(baseUri.getHost())
@@ -79,7 +80,53 @@ class AssetsRestApiClient extends NiFiRestApiClient {
.addPathSegment(ASSETS_PATH_PART)
.addPathSegment(assetId)
.build();
- logger.debug("Getting asset content from {}", requestUri);
+ logger.debug("Getting Parameter Context asset content from {}", requestUri);
+
+ try {
+ final HttpResponseEntity response = webClientService.get()
+ .uri(requestUri)
+ .header(ACCEPT_HEADER, APPLICATION_OCTET_STREAM)
+ .retrieve();
+ return getResponseBody(requestUri, response);
+ } catch (final WebClientServiceException e) {
+ throw new NiFiRestApiRetryableException(e.getMessage(), e);
+ }
+ }
+
+ public AssetsEntity getConnectorAssets(final String connectorId) {
+ final URI requestUri = new StandardHttpUriBuilder()
+ .scheme(baseUri.getScheme())
+ .host(baseUri.getHost())
+ .port(baseUri.getPort())
+ .addPathSegment(NIFI_API_PATH_PART)
+ .addPathSegment(CONNECTORS_PATH_PART)
+ .addPathSegment(connectorId)
+ .addPathSegment(ASSETS_PATH_PART)
+ .build();
+ logger.debug("Requesting Connector Asset listing from {}", requestUri);
+
+ // Send the replicated header so that the cluster coordinator does not replicate the request, otherwise this call can happen when no nodes
+ // are considered connected and result in a 500 exception that can't easily be differentiated from other unknown errors
+ final HttpRequestBodySpec requestBodySpec = webClientService.get()
+ .uri(requestUri)
+ .header(ACCEPT_HEADER, APPLICATION_JSON)
+ .header(REQUEST_REPLICATED_HEADER, Boolean.TRUE.toString());
+
+ return executeEntityRequest(requestUri, requestBodySpec, AssetsEntity.class);
+ }
+
+ public InputStream getConnectorAssetContent(final String connectorId, final String assetId) {
+ final URI requestUri = new StandardHttpUriBuilder()
+ .scheme(baseUri.getScheme())
+ .host(baseUri.getHost())
+ .port(baseUri.getPort())
+ .addPathSegment(NIFI_API_PATH_PART)
+ .addPathSegment(CONNECTORS_PATH_PART)
+ .addPathSegment(connectorId)
+ .addPathSegment(ASSETS_PATH_PART)
+ .addPathSegment(assetId)
+ .build();
+ logger.debug("Getting Connector asset content from {}", requestUri);
try {
final HttpResponseEntity response = webClientService.get()
diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/asset/StandardAssetComponentManager.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/asset/StandardAssetComponentManager.java
index 78b197cfb0..827b17b63d 100644
--- a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/asset/StandardAssetComponentManager.java
+++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/asset/StandardAssetComponentManager.java
@@ -57,7 +57,7 @@ public class StandardAssetComponentManager implements AssetComponentManager {
@Override
public void restartReferencingComponentsAsync(final Asset asset) {
final String assetName = asset.getName();
- final String paramContextId = asset.getParameterContextIdentifier();
+ final String paramContextId = asset.getOwnerIdentifier();
Thread.ofVirtual().name("Restart Components for Asset [%s] in ParameterContext [%s]".formatted(assetName, paramContextId)).start(() -> {
try {
restartReferencingComponents(asset);
@@ -70,7 +70,7 @@ public class StandardAssetComponentManager implements AssetComponentManager {
@Override
public void restartReferencingComponents(final Asset asset) {
final ParameterContextManager parameterContextManager = flowManager.getParameterContextManager();
- final ParameterContext parameterContext = parameterContextManager.getParameterContext(asset.getParameterContextIdentifier());
+ final ParameterContext parameterContext = parameterContextManager.getParameterContext(asset.getOwnerIdentifier());
// Determine which parameters reference the given asset
final Set<Parameter> parametersReferencingAsset = getParametersReferencingAsset(parameterContext, asset);
diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/asset/StandardAssetSynchronizer.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/asset/StandardAssetSynchronizer.java
index a64fef129d..5f5b7e371a 100644
--- a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/asset/StandardAssetSynchronizer.java
+++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/asset/StandardAssetSynchronizer.java
@@ -185,7 +185,7 @@ public class StandardAssetSynchronizer implements AssetSynchronizer {
private AssetsEntity listAssets(final AssetsRestApiClient assetsRestApiClient, final String parameterContextId) {
try {
- return assetsRestApiClient.getAssets(parameterContextId);
+ return assetsRestApiClient.getParameterContextAssets(parameterContextId);
} catch (final NiFiRestApiRetryableException e) {
final Throwable rootCause = ExceptionUtils.getRootCause(e);
logger.warn("{}, root cause [{}]: retrying", e.getMessage(), rootCause.getMessage());
@@ -212,7 +212,7 @@ public class StandardAssetSynchronizer implements AssetSynchronizer {
if (Boolean.TRUE == coordinatorAsset.getMissingContent()) {
return assetManager.createMissingAsset(parameterContextId, assetName);
} else {
- try (final InputStream assetInputStream = assetsRestApiClient.getAssetContent(parameterContextId, assetId)) {
+ try (final InputStream assetInputStream = assetsRestApiClient.getParameterContextAssetContent(parameterContextId, assetId)) {
return assetManager.createAsset(parameterContextId, assetName, assetInputStream);
} catch (final NiFiRestApiRetryableException e) {
final Throwable rootCause = ExceptionUtils.getRootCause(e);
diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/asset/StandardAssetSynchronizer.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/asset/StandardConnectorAssetSynchronizer.java
similarity index 61%
copy from nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/asset/StandardAssetSynchronizer.java
copy to nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/asset/StandardConnectorAssetSynchronizer.java
index a64fef129d..2eb1aa5a9a 100644
--- a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/asset/StandardAssetSynchronizer.java
+++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/asset/StandardConnectorAssetSynchronizer.java
@@ -21,11 +21,9 @@ import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.nifi.client.NiFiRestApiRetryableException;
import org.apache.nifi.cluster.coordination.ClusterCoordinator;
import org.apache.nifi.cluster.protocol.NodeIdentifier;
+import org.apache.nifi.components.connector.ConnectorNode;
import org.apache.nifi.controller.FlowController;
import org.apache.nifi.controller.flow.FlowManager;
-import org.apache.nifi.parameter.Parameter;
-import org.apache.nifi.parameter.ParameterContext;
-import org.apache.nifi.parameter.ParameterContextManager;
import org.apache.nifi.util.NiFiProperties;
import org.apache.nifi.web.api.dto.AssetDTO;
import org.apache.nifi.web.api.entity.AssetEntity;
@@ -39,17 +37,17 @@ import java.io.InputStream;
import java.time.Duration;
import java.time.Instant;
import java.util.Collection;
+import java.util.List;
import java.util.Map;
-import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
- * Synchronizes assets from the cluster coordinator using the NiFi REST API.
+ * Synchronizes connector assets from the cluster coordinator using the NiFi REST API.
*/
-public class StandardAssetSynchronizer implements AssetSynchronizer {
+public class StandardConnectorAssetSynchronizer implements AssetSynchronizer {
- private static final Logger logger = LoggerFactory.getLogger(StandardAssetSynchronizer.class);
+ private static final Logger logger = LoggerFactory.getLogger(StandardConnectorAssetSynchronizer.class);
private static final Duration CLUSTER_COORDINATOR_RETRY_DURATION = Duration.ofSeconds(60);
private static final Duration LIST_ASSETS_RETRY_DURATION = Duration.ofMinutes(5);
@@ -61,11 +59,11 @@ public class StandardAssetSynchronizer implements AssetSynchronizer {
private final WebClientService webClientService;
private final NiFiProperties properties;
- public StandardAssetSynchronizer(final FlowController flowController,
- final ClusterCoordinator clusterCoordinator,
- final WebClientService webClientService,
- final NiFiProperties properties) {
- this.assetManager = flowController.getAssetManager();
+ public StandardConnectorAssetSynchronizer(final FlowController flowController,
+ final ClusterCoordinator clusterCoordinator,
+ final WebClientService webClientService,
+ final NiFiProperties properties) {
+ this.assetManager = flowController.getConnectorAssetManager();
this.flowManager = flowController.getFlowManager();
this.clusterCoordinator = clusterCoordinator;
this.webClientService = webClientService;
@@ -75,117 +73,104 @@ public class StandardAssetSynchronizer implements AssetSynchronizer {
@Override
public void synchronize() {
if (clusterCoordinator == null) {
- logger.info("Clustering is not configured: Asset synchronization disabled");
+ logger.info("Clustering is not configured: Connector asset synchronization disabled");
return;
}
- // This sync method is called from the method that loads the flow from a connection response, which means there must already be a cluster coordinator to
- // have gotten a response from, but during testing there were cases where calling clusterCoordinator.getElectedActiveCoordinatorNode() was still null, so
- // the helper method here will keep checking for the identifier up to a certain threshold to avoid slight timing issues
final NodeIdentifier coordinatorNodeId = getElectedActiveCoordinatorNode();
if (coordinatorNodeId == null) {
- logger.warn("Unable to obtain the node identifier for the cluster coordinator: Asset synchronization disabled");
+ logger.warn("Unable to obtain the node identifier for the cluster coordinator: Connector asset synchronization disabled");
return;
}
if (clusterCoordinator.isActiveClusterCoordinator()) {
- logger.info("Current node is the cluster coordinator: Asset synchronization disabled");
+ logger.info("Current node is the cluster coordinator: Connector asset synchronization disabled");
return;
}
final String coordinatorAddress = coordinatorNodeId.getApiAddress();
final int coordinatorPort = coordinatorNodeId.getApiPort();
final AssetsRestApiClient assetsRestApiClient = new AssetsRestApiClient(webClientService, coordinatorAddress, coordinatorPort, properties.isHTTPSConfigured());
- logger.info("Synchronizing assets with cluster coordinator at {}:{}", coordinatorAddress, coordinatorPort);
+ logger.info("Synchronizing connector assets with cluster coordinator at {}:{}", coordinatorAddress, coordinatorPort);
- final ParameterContextManager parameterContextManager = flowManager.getParameterContextManager();
- final Set<ParameterContext> parameterContexts = parameterContextManager.getParameterContexts();
- logger.info("Found {} parameter contexts for synchronizing assets", parameterContexts.size());
+ final List<ConnectorNode> connectors = flowManager.getAllConnectors();
+ logger.info("Found {} connectors for synchronizing assets", connectors.size());
- for (final ParameterContext parameterContext : parameterContexts) {
+ for (final ConnectorNode connector : connectors) {
try {
- synchronize(assetsRestApiClient, parameterContext);
+ synchronize(assetsRestApiClient, connector);
} catch (final Exception e) {
- logger.error("Failed to synchronize assets for parameter context [{}]", parameterContext.getIdentifier(), e);
+ logger.error("Failed to synchronize assets for connector [{}]", connector.getIdentifier(), e);
}
}
}
- private void synchronize(final AssetsRestApiClient assetsRestApiClient, final ParameterContext parameterContext) {
- final Map<String, Asset> existingAssets = parameterContext.getParameters().values().stream()
- .map(Parameter::getReferencedAssets)
- .flatMap(Collection::stream)
+ private void synchronize(final AssetsRestApiClient assetsRestApiClient, final ConnectorNode connector) {
+ final String connectorId = connector.getIdentifier();
+ final Map<String, Asset> existingAssets = assetManager.getAssets(connectorId).stream()
.collect(Collectors.toMap(Asset::getIdentifier, Function.identity()));
- if (existingAssets.isEmpty()) {
- logger.info("Parameter context [{}] does not contain any assets to synchronize", parameterContext.getIdentifier());
- return;
- }
-
- logger.info("Parameter context [{}] has {} assets on the current node", parameterContext.getIdentifier(), existingAssets.size());
-
- final AssetsEntity coordinatorAssetsEntity = listAssetsWithRetry(assetsRestApiClient, parameterContext.getIdentifier());
+ final AssetsEntity coordinatorAssetsEntity = listConnectorAssetsWithRetry(assetsRestApiClient, connectorId);
if (coordinatorAssetsEntity == null) {
- logger.error("Timeout listing assets from cluster coordinator for parameter context [{}]", parameterContext.getIdentifier());
+ logger.error("Timeout listing assets from cluster coordinator for connector [{}]", connectorId);
return;
}
final Collection<AssetEntity> coordinatorAssets = coordinatorAssetsEntity.getAssets();
if (coordinatorAssets == null || coordinatorAssets.isEmpty()) {
- logger.info("Parameter context [{}] did not return any assets from the cluster coordinator", parameterContext.getIdentifier());
+ logger.info("Connector [{}] did not return any assets from the cluster coordinator", connectorId);
return;
}
- logger.info("Parameter context [{}] returned {} assets from the cluster coordinator", parameterContext.getIdentifier(), coordinatorAssets.size());
+ logger.info("Connector [{}] returned {} assets from the cluster coordinator", connectorId, coordinatorAssets.size());
for (final AssetEntity coordinatorAssetEntity : coordinatorAssets) {
final AssetDTO coordinatorAsset = coordinatorAssetEntity.getAsset();
final Asset matchingAsset = existingAssets.get(coordinatorAsset.getId());
try {
- synchronize(assetsRestApiClient, parameterContext, coordinatorAsset, matchingAsset);
+ synchronize(assetsRestApiClient, connectorId, coordinatorAsset, matchingAsset);
} catch (final Exception e) {
- logger.error("Failed to synchronize asset [id={},name={}] for parameter context [{}]",
- coordinatorAsset.getId(), coordinatorAsset.getName(), parameterContext.getIdentifier(), e);
+ logger.error("Failed to synchronize asset [id={},name={}] for connector [{}]",
+ coordinatorAsset.getId(), coordinatorAsset.getName(), connectorId, e);
}
}
}
- private void synchronize(final AssetsRestApiClient assetsRestApiClient, final ParameterContext parameterContext, final AssetDTO coordinatorAsset, final Asset matchingAsset) {
- final String paramContextId = parameterContext.getIdentifier();
+ private void synchronize(final AssetsRestApiClient assetsRestApiClient, final String connectorId, final AssetDTO coordinatorAsset, final Asset matchingAsset) {
final String assetId = coordinatorAsset.getId();
final String assetName = coordinatorAsset.getName();
if (matchingAsset == null || !matchingAsset.getFile().exists()) {
- logger.info("Synchronizing missing asset [id={},name={}] for parameter context [{}]", assetId, assetName, paramContextId);
- synchronizeAssetWithRetry(assetsRestApiClient, paramContextId, coordinatorAsset);
+ logger.info("Synchronizing missing asset [id={},name={}] for connector [{}]", assetId, assetName, connectorId);
+ synchronizeConnectorAssetWithRetry(assetsRestApiClient, connectorId, coordinatorAsset);
} else {
final String coordinatorAssetDigest = coordinatorAsset.getDigest();
final String matchingAssetDigest = matchingAsset.getDigest().orElse(null);
if (!coordinatorAssetDigest.equals(matchingAssetDigest)) {
- logger.info("Synchronizing asset [id={},name={}] with updated digest [{}] for parameter context [{}]",
- assetId, assetName, coordinatorAssetDigest, paramContextId);
- synchronizeAssetWithRetry(assetsRestApiClient, paramContextId, coordinatorAsset);
+ logger.info("Synchronizing asset [id={},name={}] with updated digest [{}] for connector [{}]",
+ assetId, assetName, coordinatorAssetDigest, connectorId);
+ synchronizeConnectorAssetWithRetry(assetsRestApiClient, connectorId, coordinatorAsset);
} else {
- logger.info("Coordinator asset [id={},name={}] found for parameter context [{}]: retrieval not required", assetId, assetName, paramContextId);
+ logger.info("Coordinator asset [id={},name={}] found for connector [{}]: retrieval not required", assetId, assetName, connectorId);
}
}
}
- private AssetsEntity listAssetsWithRetry(final AssetsRestApiClient assetsRestApiClient, final String parameterContextId) {
+ private AssetsEntity listConnectorAssetsWithRetry(final AssetsRestApiClient assetsRestApiClient, final String connectorId) {
final Instant expirationTime = Instant.ofEpochMilli(System.currentTimeMillis() + LIST_ASSETS_RETRY_DURATION.toMillis());
while (System.currentTimeMillis() < expirationTime.toEpochMilli()) {
- final AssetsEntity assetsEntity = listAssets(assetsRestApiClient, parameterContextId);
+ final AssetsEntity assetsEntity = listConnectorAssets(assetsRestApiClient, connectorId);
if (assetsEntity != null) {
return assetsEntity;
}
- logger.info("Unable to list assets from cluster coordinator for parameter context [{}]: retrying until [{}]", parameterContextId, expirationTime);
+ logger.info("Unable to list assets from cluster coordinator for connector [{}]: retrying until [{}]", connectorId, expirationTime);
sleep(Duration.ofSeconds(5));
}
return null;
}
- private AssetsEntity listAssets(final AssetsRestApiClient assetsRestApiClient, final String parameterContextId) {
+ private AssetsEntity listConnectorAssets(final AssetsRestApiClient assetsRestApiClient, final String connectorId) {
try {
- return assetsRestApiClient.getAssets(parameterContextId);
+ return assetsRestApiClient.getConnectorAssets(connectorId);
} catch (final NiFiRestApiRetryableException e) {
final Throwable rootCause = ExceptionUtils.getRootCause(e);
logger.warn("{}, root cause [{}]: retrying", e.getMessage(), rootCause.getMessage());
@@ -193,27 +178,27 @@ public class StandardAssetSynchronizer implements AssetSynchronizer {
}
}
- private void synchronizeAssetWithRetry(final AssetsRestApiClient assetsRestApiClient, final String parameterContextId, final AssetDTO coordinatorAsset) {
+ private void synchronizeConnectorAssetWithRetry(final AssetsRestApiClient assetsRestApiClient, final String connectorId, final AssetDTO coordinatorAsset) {
final Instant expirationTime = Instant.ofEpochMilli(System.currentTimeMillis() + SYNC_ASSET_RETRY_DURATION.toMillis());
while (System.currentTimeMillis() < expirationTime.toEpochMilli()) {
- final Asset syncedAsset = synchronizeAsset(assetsRestApiClient, parameterContextId, coordinatorAsset);
+ final Asset syncedAsset = synchronizeConnectorAsset(assetsRestApiClient, connectorId, coordinatorAsset);
if (syncedAsset != null) {
return;
}
- logger.info("Unable to synchronize asset [id={},name={}] for parameter context [{}]: retrying until [{}]",
- coordinatorAsset.getId(), coordinatorAsset.getName(), parameterContextId, expirationTime);
+ logger.info("Unable to synchronize asset [id={},name={}] for connector [{}]: retrying until [{}]",
+ coordinatorAsset.getId(), coordinatorAsset.getName(), connectorId, expirationTime);
sleep(Duration.ofSeconds(5));
}
}
- private Asset synchronizeAsset(final AssetsRestApiClient assetsRestApiClient, final String parameterContextId, final AssetDTO coordinatorAsset) {
+ private Asset synchronizeConnectorAsset(final AssetsRestApiClient assetsRestApiClient, final String connectorId, final AssetDTO coordinatorAsset) {
final String assetId = coordinatorAsset.getId();
final String assetName = coordinatorAsset.getName();
if (Boolean.TRUE == coordinatorAsset.getMissingContent()) {
- return assetManager.createMissingAsset(parameterContextId, assetName);
+ return assetManager.createMissingAsset(connectorId, assetName);
} else {
- try (final InputStream assetInputStream = assetsRestApiClient.getAssetContent(parameterContextId, assetId)) {
- return assetManager.createAsset(parameterContextId, assetName, assetInputStream);
+ try (final InputStream assetInputStream = assetsRestApiClient.getConnectorAssetContent(connectorId, assetId)) {
+ return assetManager.saveAsset(connectorId, assetId, assetName, assetInputStream);
} catch (final NiFiRestApiRetryableException e) {
final Throwable rootCause = ExceptionUtils.getRootCause(e);
logger.warn("{}, root cause [{}]: retrying", e.getMessage(), rootCause.getMessage());
@@ -248,3 +233,5 @@ public class StandardAssetSynchronizer implements AssetSynchronizer {
}
}
}
+
+
diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandardConnectorAssetRepository.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandardConnectorAssetRepository.java
new file mode 100644
index 0000000000..2ada8b424d
--- /dev/null
+++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandardConnectorAssetRepository.java
@@ -0,0 +1,63 @@
+/*
+ * 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.components.connector;
+
+import org.apache.nifi.asset.Asset;
+import org.apache.nifi.asset.AssetManager;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.List;
+import java.util.Optional;
+
+public class StandardConnectorAssetRepository implements ConnectorAssetRepository {
+
+ private final AssetManager assetManager;
+
+ public StandardConnectorAssetRepository(final AssetManager assetManager) {
+ this.assetManager = assetManager;
+ }
+
+ @Override
+ public Asset storeAsset(final String connectorId, final String assetId, final String assetName, final InputStream content) throws IOException {
+ return assetManager.saveAsset(connectorId, assetId, assetName, content);
+ }
+
+ @Override
+ public Optional<Asset> getAsset(String assetId) {
+ return assetManager.getAsset(assetId);
+ }
+
+ @Override
+ public List<Asset> getAssets(final String connectorId) {
+ return assetManager.getAssets(connectorId);
+ }
+
+ @Override
+ public void deleteAsset(final String assetId) {
+ assetManager.deleteAsset(assetId);
+ }
+
+ @Override
+ public void deleteAssets(final String connectorId) {
+ final List<Asset> assets = assetManager.getAssets(connectorId);
+ for (final Asset asset : assets) {
+ assetManager.deleteAsset(asset.getIdentifier());
+ }
+ }
+
+}
diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandardConnectorConfigurationContext.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandardConnectorConfigurationContext.java
index e1722ff9a3..b601d154ed 100644
--- a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandardConnectorConfigurationContext.java
+++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandardConnectorConfigurationContext.java
@@ -17,10 +17,12 @@
package org.apache.nifi.components.connector;
+import org.apache.nifi.asset.Asset;
import org.apache.nifi.asset.AssetManager;
import org.apache.nifi.components.connector.secrets.SecretProvider;
import org.apache.nifi.components.connector.secrets.SecretsManager;
+import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.Collections;
@@ -185,10 +187,7 @@ public class StandardConnectorConfigurationContext implements MutableConnectorCo
try {
return switch (reference) {
case StringLiteralValue stringLiteral -> stringLiteral;
- case AssetReference assetReference -> assetManager.getAsset(assetReference.getAssetIdentifier())
- .map(asset -> asset.getFile().getAbsolutePath())
- .map(StringLiteralValue::new)
- .orElse(null);
+ case AssetReference assetReference -> resolveAssetReferences(assetReference);
case SecretReference secretReference -> new StringLiteralValue(getSecretValue(secretReference));
};
} catch (final IOException ioe) {
@@ -196,6 +195,18 @@ public class StandardConnectorConfigurationContext implements MutableConnectorCo
}
}
+ private StringLiteralValue resolveAssetReferences(final AssetReference assetReference) {
+ final Set<String> resolvedAssetValues = new HashSet<>();
+ for (final String assetId : assetReference.getAssetIdentifiers()) {
+ assetManager.getAsset(assetId)
+ .map(Asset::getFile)
+ .map(File::getAbsolutePath)
+ .ifPresent(resolvedAssetValues::add);
+ }
+
+ return new StringLiteralValue(String.join(",", resolvedAssetValues));
+ }
+
private String getSecretValue(final SecretReference secretReference) throws IOException {
final SecretProvider provider = getSecretProvider(secretReference);
if (provider == null) {
diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandardConnectorNode.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandardConnectorNode.java
index 80b5d126c6..a0dd520c70 100644
--- a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandardConnectorNode.java
+++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandardConnectorNode.java
@@ -17,6 +17,7 @@
package org.apache.nifi.components.connector;
+import org.apache.nifi.asset.Asset;
import org.apache.nifi.authorization.Resource;
import org.apache.nifi.authorization.resource.Authorizable;
import org.apache.nifi.authorization.resource.ResourceFactory;
@@ -44,9 +45,11 @@ import org.apache.nifi.groups.ProcessGroup;
import org.apache.nifi.logging.ComponentLog;
import org.apache.nifi.nar.ExtensionManager;
import org.apache.nifi.nar.NarCloseable;
+import org.apache.nifi.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.time.Duration;
@@ -54,6 +57,7 @@ import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
+import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
@@ -211,7 +215,7 @@ public class StandardConnectorNode implements ConnectorNode {
final ConnectorValueType valueType = ConnectorValueType.valueOf(versionedReference.getValueType());
return switch (valueType) {
case STRING_LITERAL -> new StringLiteralValue(versionedReference.getValue());
- case ASSET_REFERENCE -> new AssetReference(versionedReference.getAssetId());
+ case ASSET_REFERENCE -> new AssetReference(versionedReference.getAssetIds());
case SECRET_REFERENCE -> new SecretReference(versionedReference.getProviderId(), versionedReference.getProviderName(),
versionedReference.getSecretName(), versionedReference.getFullyQualifiedSecretName());
};
@@ -735,16 +739,25 @@ public class StandardConnectorNode implements ConnectorNode {
return switch (valueReference) {
case StringLiteralValue stringLiteralValue -> stringLiteralValue.getValue();
- case AssetReference assetReference -> initializationContext.getAssetManager().getAsset(assetReference.getAssetIdentifier())
- .map(asset -> asset.getFile().getAbsolutePath())
- .orElse(null);
+ case AssetReference assetReference -> resolveAssetReferences(assetReference);
case SecretReference secretReference -> initializationContext.getSecretsManager()
- .getSecret((SecretReference) valueReference)
+ .getSecret(secretReference)
.map(Secret::getValue)
.orElse(null);
};
}
+ private String resolveAssetReferences(final AssetReference assetReference) {
+ final Set<String> resolvedAssetValues = new HashSet<>();
+ for (final String assetId : assetReference.getAssetIdentifiers()) {
+ initializationContext.getAssetManager().getAsset(assetId)
+ .map(Asset::getFile)
+ .map(File::getAbsolutePath)
+ .ifPresent(resolvedAssetValues::add);
+ }
+ return String.join(",", resolvedAssetValues);
+ }
+
private Optional<ConfigurationStep> getConfigurationStep(final String stepName) {
for (final ConfigurationStep step : getConfigurationSteps()) {
if (Objects.equals(step.getName(), stepName)) {
@@ -959,7 +972,7 @@ public class StandardConnectorNode implements ConnectorNode {
results.add(new ValidationResult.Builder()
.subject("Asset Reference")
.valid(false)
- .explanation("The referenced asset [" + invalidAssetRef.getAssetIdentifier() + "] could not be found")
+ .explanation("The referenced assets [" + StringUtils.join(invalidAssetRef.getAssetIdentifiers(), ",") + "] could not be found")
.build());
}
}
@@ -1004,7 +1017,7 @@ public class StandardConnectorNode implements ConnectorNode {
}
}
case AssetReference assetReference -> {
- if (assetReference.getAssetIdentifier() == null) {
+ if (assetReference.getAssetIdentifiers() == null || assetReference.getAssetIdentifiers().isEmpty()) {
return true;
}
}
@@ -1019,7 +1032,11 @@ public class StandardConnectorNode implements ConnectorNode {
return reference.getValueType() == ConnectorValueType.SECRET_REFERENCE;
}
- return reference.getValueType() != ConnectorValueType.SECRET_REFERENCE;
+ if (propertyType == PropertyType.ASSET || propertyType == PropertyType.ASSET_LIST) {
+ return reference.getValueType() == ConnectorValueType.ASSET_REFERENCE;
+ }
+
+ return reference.getValueType() != ConnectorValueType.SECRET_REFERENCE && reference.getValueType() != ConnectorValueType.ASSET_REFERENCE;
}
private ConnectorValidationContext createValidationContext(final FrameworkFlowContext context) {
diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandardConnectorRepoInitializationContext.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandardConnectorRepoInitializationContext.java
index 4a1b8ed8b3..1aa7a4b271 100644
--- a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandardConnectorRepoInitializationContext.java
+++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandardConnectorRepoInitializationContext.java
@@ -18,6 +18,7 @@
package org.apache.nifi.components.connector;
import org.apache.nifi.components.connector.secrets.SecretsManager;
+import org.apache.nifi.asset.AssetManager;
import org.apache.nifi.controller.NodeTypeProvider;
import org.apache.nifi.controller.flow.FlowManager;
import org.apache.nifi.nar.ExtensionManager;
@@ -26,17 +27,20 @@ public class StandardConnectorRepoInitializationContext implements ConnectorRepo
private final FlowManager flowManager;
private final ExtensionManager extensionManager;
private final SecretsManager secretsManager;
+ private final AssetManager assetManager;
private final NodeTypeProvider nodeTypeProvider;
private final ConnectorRequestReplicator requestReplicator;
public StandardConnectorRepoInitializationContext(final FlowManager flowManager,
final ExtensionManager extensionManager,
final SecretsManager secretsManager,
+ final AssetManager assetManager,
final NodeTypeProvider nodeTypeProvider,
final ConnectorRequestReplicator requestReplicator) {
this.flowManager = flowManager;
this.extensionManager = extensionManager;
this.secretsManager = secretsManager;
+ this.assetManager = assetManager;
this.nodeTypeProvider = nodeTypeProvider;
this.requestReplicator = requestReplicator;
}
@@ -56,6 +60,11 @@ public class StandardConnectorRepoInitializationContext implements ConnectorRepo
return secretsManager;
}
+ @Override
+ public AssetManager getAssetManager() {
+ return assetManager;
+ }
+
@Override
public NodeTypeProvider getNodeTypeProvider() {
return nodeTypeProvider;
diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandardConnectorRepository.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandardConnectorRepository.java
index df31268c3c..dfa7a91a94 100644
--- a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandardConnectorRepository.java
+++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandardConnectorRepository.java
@@ -46,12 +46,14 @@ public class StandardConnectorRepository implements ConnectorRepository {
private volatile ExtensionManager extensionManager;
private volatile ConnectorRequestReplicator requestReplicator;
private volatile SecretsManager secretsManager;
+ private volatile ConnectorAssetRepository assetRepository;
@Override
public void initialize(final ConnectorRepositoryInitializationContext context) {
this.extensionManager = context.getExtensionManager();
this.requestReplicator = context.getRequestReplicator();
this.secretsManager = context.getSecretsManager();
+ this.assetRepository = new StandardConnectorAssetRepository(context.getAssetManager());
}
@Override
@@ -223,4 +225,8 @@ public class StandardConnectorRepository implements ConnectorRepository {
return new StandardConnectorInitializationContext.Builder();
}
+ @Override
+ public ConnectorAssetRepository getAssetRepository() {
+ return assetRepository;
+ }
}
\ No newline at end of file
diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/ExtensionBuilder.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/ExtensionBuilder.java
index 796827f7c7..dab271d3f3 100644
--- a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/ExtensionBuilder.java
+++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/ExtensionBuilder.java
@@ -568,7 +568,7 @@ public class ExtensionBuilder {
.name(name)
.componentLog(componentLog)
.secretsManager(flowController.getConnectorRepository().getSecretsManager())
- .assetManager(flowController.getAssetManager())
+ .assetManager(flowController.getConnectorAssetManager())
.build();
}
diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/FlowController.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/FlowController.java
index 03d65c6db3..8f845b853d 100644
--- a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/FlowController.java
+++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/FlowController.java
@@ -27,6 +27,7 @@ import org.apache.nifi.asset.AssetReferenceLookup;
import org.apache.nifi.asset.StandardAssetManager;
import org.apache.nifi.asset.StandardAssetManagerInitializationContext;
import org.apache.nifi.asset.StandardAssetReferenceLookup;
+import org.apache.nifi.asset.StandardConnectorAssetManager;
import org.apache.nifi.authorization.Authorizer;
import org.apache.nifi.authorization.Resource;
import org.apache.nifi.authorization.resource.Authorizable;
@@ -228,6 +229,8 @@ import org.apache.nifi.web.revision.RevisionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import javax.management.NotificationEmitter;
+import javax.net.ssl.SSLContext;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
@@ -260,8 +263,6 @@ import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.function.Supplier;
import java.util.stream.Collectors;
-import javax.management.NotificationEmitter;
-import javax.net.ssl.SSLContext;
import static java.util.Objects.requireNonNull;
@@ -274,6 +275,7 @@ public class FlowController implements ReportingTaskProvider, FlowAnalysisRulePr
public static final String DEFAULT_PROVENANCE_REPO_IMPLEMENTATION = "org.apache.nifi.provenance.VolatileProvenanceRepository";
public static final String DEFAULT_SWAP_MANAGER_IMPLEMENTATION = "org.apache.nifi.controller.FileSystemSwapManager";
public static final String DEFAULT_ASSET_MANAGER_IMPLEMENTATION = StandardAssetManager.class.getName();
+ public static final String DEFAULT_CONNECTOR_ASSET_MANAGER_IMPLEMENTATION = StandardConnectorAssetManager.class.getName();
public static final String DEFAULT_CONNECTOR_REPOSITORY_IMPLEMENTATION = StandardConnectorRepository.class.getName();
public static final String DEFAULT_SECRETS_MANAGER_IMPLEMENTATION = ParameterProviderSecretsManager.class.getName();
@@ -291,6 +293,7 @@ public class FlowController implements ReportingTaskProvider, FlowAnalysisRulePr
private final ProvenanceRepository provenanceRepository;
private final BulletinRepository bulletinRepository;
private final AssetManager assetManager;
+ private final AssetManager connectorAssetManager;
private final LifecycleStateManager lifecycleStateManager;
private final StandardProcessScheduler processScheduler;
private final SnippetManager snippetManager;
@@ -584,7 +587,19 @@ public class FlowController implements ReportingTaskProvider, FlowAnalysisRulePr
final long maxAppendableBytes = getMaxAppendableBytes();
repositoryContextFactory = new RepositoryContextFactory(contentRepository, flowFileRepository, flowFileEventRepository,
counterRepositoryRef.get(), provenanceRepository, stateManagerProvider, maxAppendableBytes);
- assetManager = createAssetManager(nifiProperties);
+
+ assetManager = createAssetManager(
+ nifiProperties,
+ NiFiProperties.ASSET_MANAGER_IMPLEMENTATION,
+ NiFiProperties.ASSET_MANAGER_PREFIX,
+ DEFAULT_ASSET_MANAGER_IMPLEMENTATION
+ );
+ connectorAssetManager = createAssetManager(
+ nifiProperties,
+ NiFiProperties.CONNECTOR_ASSET_MANAGER_IMPLEMENTATION,
+ NiFiProperties.CONNECTOR_ASSET_MANAGER_PREFIX,
+ DEFAULT_CONNECTOR_ASSET_MANAGER_IMPLEMENTATION
+ );
this.flowAnalysisThreadPool = new FlowEngine(1, "Background Flow Analysis", true);
if (ruleViolationsManager != null) {
@@ -612,7 +627,7 @@ public class FlowController implements ReportingTaskProvider, FlowAnalysisRulePr
controllerServiceProvider, new StandardControllerServiceApiLookup(extensionManager));
final SecretsManager secretsManager = createSecretsManager(nifiProperties, extensionManager, flowManager);
- connectorRepository = createConnectorRepository(nifiProperties, extensionManager, flowManager, secretsManager, this, connectorRequestReplicator);
+ connectorRepository = createConnectorRepository(nifiProperties, extensionManager, flowManager, connectorAssetManager, secretsManager, this, connectorRequestReplicator);
final PythonBridge rawPythonBridge = createPythonBridge(nifiProperties, controllerServiceProvider);
final ClassLoader pythonBridgeClassLoader = rawPythonBridge.getClass().getClassLoader();
@@ -886,7 +901,7 @@ public class FlowController implements ReportingTaskProvider, FlowAnalysisRulePr
}
private static ConnectorRepository createConnectorRepository(final NiFiProperties properties, final ExtensionDiscoveringManager extensionManager, final FlowManager flowManager,
- final SecretsManager secretsManager, final NodeTypeProvider nodeTypeProvider, final ConnectorRequestReplicator requestReplicator) {
+ final AssetManager assetManager, final SecretsManager secretsManager, final NodeTypeProvider nodeTypeProvider, final ConnectorRequestReplicator requestReplicator) {
final String implementationClassName = properties.getProperty(NiFiProperties.CONNECTOR_REPOSITORY_IMPLEMENTATION, DEFAULT_CONNECTOR_REPOSITORY_IMPLEMENTATION);
@@ -902,6 +917,7 @@ public class FlowController implements ReportingTaskProvider, FlowAnalysisRulePr
flowManager,
extensionManager,
secretsManager,
+ assetManager,
nodeTypeProvider,
requestReplicator
);
@@ -1458,14 +1474,14 @@ public class FlowController implements ReportingTaskProvider, FlowAnalysisRulePr
}
}
- private AssetManager createAssetManager(final NiFiProperties properties) {
- final String implementationClassName = properties.getProperty(NiFiProperties.ASSET_MANAGER_IMPLEMENTATION, DEFAULT_ASSET_MANAGER_IMPLEMENTATION);
+ private AssetManager createAssetManager(final NiFiProperties properties, final String implementationClassProperty, final String propertyPrefix, final String defaultImplementationClass) {
+ final String implementationClassName = properties.getProperty(implementationClassProperty, defaultImplementationClass);
try {
final AssetManager assetManager = NarThreadContextClassLoader.createInstance(extensionManager, implementationClassName, AssetManager.class, properties);
final AssetReferenceLookup assetReferenceLookup = new StandardAssetReferenceLookup(parameterContextManager);
- final Map<String, String> relevantNiFiProperties = properties.getPropertiesWithPrefix(NiFiProperties.ASSET_MANAGER_PREFIX);
- final int prefixLength = NiFiProperties.ASSET_MANAGER_PREFIX.length();
+ final Map<String, String> relevantNiFiProperties = properties.getPropertiesWithPrefix(propertyPrefix);
+ final int prefixLength = propertyPrefix.length();
final Map<String, String> assetManagerProperties = relevantNiFiProperties.entrySet().stream()
.collect(Collectors.toMap(entry -> entry.getKey().substring(prefixLength), Map.Entry::getValue));
@@ -1483,9 +1499,16 @@ public class FlowController implements ReportingTaskProvider, FlowAnalysisRulePr
}
@Override
- public Asset createAsset(final String parameterContextId, final String assetName, final InputStream contents) throws IOException {
+ public Asset createAsset(final String ownerId, final String assetName, final InputStream contents) throws IOException {
try (final NarCloseable ignored = NarCloseable.withComponentNarLoader(assetManagerClassLoader)) {
- return assetManager.createAsset(parameterContextId, assetName, contents);
+ return assetManager.createAsset(ownerId, assetName, contents);
+ }
+ }
+
+ @Override
+ public Asset saveAsset(final String ownerId, final String assetId, final String assetName, final InputStream contents) throws IOException {
+ try (final NarCloseable ignored = NarCloseable.withComponentNarLoader(assetManagerClassLoader)) {
+ return assetManager.saveAsset(ownerId, assetId, assetName, contents);
}
}
@@ -1497,16 +1520,16 @@ public class FlowController implements ReportingTaskProvider, FlowAnalysisRulePr
}
@Override
- public List<Asset> getAssets(final String parameterContextId) {
+ public List<Asset> getAssets(final String ownerId) {
try (final NarCloseable ignored = NarCloseable.withComponentNarLoader(assetManagerClassLoader)) {
- return assetManager.getAssets(parameterContextId);
+ return assetManager.getAssets(ownerId);
}
}
@Override
- public Asset createMissingAsset(final String parameterContextId, final String assetName) {
+ public Asset createMissingAsset(final String ownerId, final String assetName) {
try (final NarCloseable ignored = NarCloseable.withComponentNarLoader(assetManagerClassLoader)) {
- return assetManager.createMissingAsset(parameterContextId, assetName);
+ return assetManager.createMissingAsset(ownerId, assetName);
}
}
@@ -1530,6 +1553,10 @@ public class FlowController implements ReportingTaskProvider, FlowAnalysisRulePr
return assetManager;
}
+ public AssetManager getConnectorAssetManager() {
+ return connectorAssetManager;
+ }
+
private ProvenanceRepository createProvenanceRepository(final NiFiProperties properties) {
final String implementationClassName = properties.getProperty(NiFiProperties.PROVENANCE_REPO_IMPLEMENTATION_CLASS, DEFAULT_PROVENANCE_REPO_IMPLEMENTATION);
if (StringUtils.isBlank(implementationClassName)) {
diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/StandardFlowService.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/StandardFlowService.java
index 5de3486164..4c021429d1 100644
--- a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/StandardFlowService.java
+++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/StandardFlowService.java
@@ -122,7 +122,8 @@ public class StandardFlowService implements FlowService, ProtocolHandler {
private final ClusterCoordinator clusterCoordinator;
private final RevisionManager revisionManager;
private final NarManager narManager;
- private final AssetSynchronizer assetSynchronizer;
+ private final AssetSynchronizer parameterContextAssetSynchronizer;
+ private final AssetSynchronizer connectorAssetSynchronizer;
private volatile SaveReportingTask saveReportingTask;
/**
@@ -153,10 +154,12 @@ public class StandardFlowService implements FlowService, ProtocolHandler {
final NiFiProperties nifiProperties,
final RevisionManager revisionManager,
final NarManager narManager,
- final AssetSynchronizer assetSynchronizer,
+ final AssetSynchronizer parameterContextAssetSynchronizer,
+ final AssetSynchronizer connectorAssetSynchronizer,
final Authorizer authorizer) throws IOException {
- return new StandardFlowService(controller, nifiProperties, null, false, null, revisionManager, narManager, assetSynchronizer, authorizer);
+ return new StandardFlowService(controller, nifiProperties, null, false, null, revisionManager, narManager,
+ parameterContextAssetSynchronizer, connectorAssetSynchronizer, authorizer);
}
public static StandardFlowService createClusteredInstance(
@@ -166,10 +169,12 @@ public class StandardFlowService implements FlowService, ProtocolHandler {
final ClusterCoordinator coordinator,
final RevisionManager revisionManager,
final NarManager narManager,
- final AssetSynchronizer assetSynchronizer,
+ final AssetSynchronizer parameterContextAssetSynchronizer,
+ final AssetSynchronizer connectorAssetSynchronizer,
final Authorizer authorizer) throws IOException {
- return new StandardFlowService(controller, nifiProperties, senderListener, true, coordinator, revisionManager, narManager, assetSynchronizer, authorizer);
+ return new StandardFlowService(controller, nifiProperties, senderListener, true, coordinator, revisionManager,
+ narManager, parameterContextAssetSynchronizer, connectorAssetSynchronizer, authorizer);
}
private StandardFlowService(
@@ -180,7 +185,8 @@ public class StandardFlowService implements FlowService, ProtocolHandler {
final ClusterCoordinator clusterCoordinator,
final RevisionManager revisionManager,
final NarManager narManager,
- final AssetSynchronizer assetSynchronizer,
+ final AssetSynchronizer parameterContextAssetSynchronizer,
+ final AssetSynchronizer connectorAssetSynchronizer,
final Authorizer authorizer) throws IOException {
this.nifiProperties = nifiProperties;
@@ -196,7 +202,8 @@ public class StandardFlowService implements FlowService, ProtocolHandler {
}
this.revisionManager = revisionManager;
this.narManager = narManager;
- this.assetSynchronizer = assetSynchronizer;
+ this.parameterContextAssetSynchronizer = parameterContextAssetSynchronizer;
+ this.connectorAssetSynchronizer = connectorAssetSynchronizer;
this.authorizer = authorizer;
if (configuredForClustering) {
@@ -913,8 +920,13 @@ public class StandardFlowService implements FlowService, ProtocolHandler {
// load new controller state
loadFromBytes(dataFlow, true, BundleUpdateStrategy.USE_SPECIFIED_OR_COMPATIBLE_OR_GHOST);
- // sync assets after loading the flow so that parameter contexts exist first
- assetSynchronizer.synchronize();
+ // sync assets after loading the flow so that parameter contexts and connectors exist first
+ if (parameterContextAssetSynchronizer != null) {
+ parameterContextAssetSynchronizer.synchronize();
+ }
+ if (connectorAssetSynchronizer != null) {
+ connectorAssetSynchronizer.synchronize();
+ }
// set node ID on controller before we start heartbeating because heartbeat needs node ID
clusterCoordinator.setLocalNodeIdentifier(nodeId);
diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/flow/StandardFlowManager.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/flow/StandardFlowManager.java
index 398cb085bc..c48288bd71 100644
--- a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/flow/StandardFlowManager.java
+++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/flow/StandardFlowManager.java
@@ -765,7 +765,7 @@ public class StandardFlowManager extends AbstractFlowManager implements FlowMana
final ConnectorRepository connectorRepository = flowController.getConnectorRepository();
final ConnectorStateTransition stateTransition = connectorRepository.createStateTransition(type, id);
final StandardConnectorConfigurationContext activeConfigurationContext = new StandardConnectorConfigurationContext(
- flowController.getAssetManager(), flowController.getConnectorRepository().getSecretsManager());
+ flowController.getConnectorAssetManager(), flowController.getConnectorRepository().getSecretsManager());
final ProcessGroupFactory processGroupFactory = groupId -> createProcessGroup(groupId, false);
final FlowContextFactory flowContextFactory = new FlowControllerFlowContextFactory(flowController, managedRootGroup, activeConfigurationContext, processGroupFactory);
diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/serialization/VersionedFlowSynchronizer.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/serialization/VersionedFlowSynchronizer.java
index 68a420b34f..abb58be0d5 100644
--- a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/serialization/VersionedFlowSynchronizer.java
+++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/serialization/VersionedFlowSynchronizer.java
@@ -1136,7 +1136,7 @@ public class VersionedFlowSynchronizer implements FlowSynchronizer {
return switch (existingReference) {
case StringLiteralValue stringLiteral -> Objects.equals(stringLiteral.getValue(), versionedReference.getValue());
- case AssetReference assetRef -> Objects.equals(assetRef.getAssetIdentifier(), versionedReference.getAssetId());
+ case AssetReference assetRef -> Objects.equals(assetRef.getAssetIdentifiers(), versionedReference.getAssetIds());
case SecretReference secretRef -> Objects.equals(secretRef.getProviderId(), versionedReference.getProviderId())
&& Objects.equals(secretRef.getSecretName(), versionedReference.getSecretName());
};
diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/framework/configuration/FlowControllerConfiguration.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/framework/configuration/FlowControllerConfiguration.java
index a290ba7be2..680486a005 100644
--- a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/framework/configuration/FlowControllerConfiguration.java
+++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/framework/configuration/FlowControllerConfiguration.java
@@ -25,6 +25,7 @@ import org.apache.nifi.asset.AssetManager;
import org.apache.nifi.asset.AssetSynchronizer;
import org.apache.nifi.asset.StandardAssetComponentManager;
import org.apache.nifi.asset.StandardAssetSynchronizer;
+import org.apache.nifi.asset.StandardConnectorAssetSynchronizer;
import org.apache.nifi.authorization.Authorizer;
import org.apache.nifi.cluster.coordination.ClusterCoordinator;
import org.apache.nifi.cluster.coordination.heartbeat.HeartbeatMonitor;
@@ -254,7 +255,8 @@ public class FlowControllerConfiguration {
properties,
revisionManager,
narManager,
- assetSynchronizer(),
+ parameterContextAssetSynchronizer(),
+ connectorAssetSynchronizer(),
authorizer
);
} else {
@@ -265,7 +267,8 @@ public class FlowControllerConfiguration {
clusterCoordinator,
revisionManager,
narManager,
- assetSynchronizer(),
+ parameterContextAssetSynchronizer(),
+ connectorAssetSynchronizer(),
authorizer
);
}
@@ -454,15 +457,25 @@ public class FlowControllerConfiguration {
}
/**
- * Asset Synchronizer depends on ClusterCoordinator, WebClientService, and NiFiProperties
+ * Parameter Conext Asset Synchronizer depends on ClusterCoordinator, WebClientService, and NiFiProperties
*
* @return Asset Synchronizer
*/
@Bean
- public AssetSynchronizer assetSynchronizer() throws Exception {
+ public AssetSynchronizer parameterContextAssetSynchronizer() throws Exception {
return new StandardAssetSynchronizer(flowController(), clusterCoordinator, webClientService(), properties);
}
+ /**
+ * Connector Asset Synchronizer depends on ClusterCoordinator, WebClientService, and NiFiProperties
+ *
+ * @return Connector Asset Synchronizer
+ */
+ @Bean
+ public AssetSynchronizer connectorAssetSynchronizer() throws Exception {
+ return new StandardConnectorAssetSynchronizer(flowController(), clusterCoordinator, webClientService(), properties);
+ }
+
/**
* Affected Component Manager depends on FlowController
*
diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/TestStandardConnectorInitializationContext.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/TestStandardConnectorInitializationContext.java
index 8b1cae7311..ae15efa509 100644
--- a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/TestStandardConnectorInitializationContext.java
+++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/TestStandardConnectorInitializationContext.java
@@ -1,3 +1,19 @@
+/*
+ * 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.components.connector;
import org.apache.nifi.components.connector.components.ParameterValue;
diff --git a/nifi-framework-bundle/nifi-framework/nifi-headless-server/src/main/java/org/apache/nifi/headless/HeadlessNiFiServer.java b/nifi-framework-bundle/nifi-framework/nifi-headless-server/src/main/java/org/apache/nifi/headless/HeadlessNiFiServer.java
index 0ca2ea65c0..8ce84b0a8f 100644
--- a/nifi-framework-bundle/nifi-framework/nifi-headless-server/src/main/java/org/apache/nifi/headless/HeadlessNiFiServer.java
+++ b/nifi-framework-bundle/nifi-framework/nifi-headless-server/src/main/java/org/apache/nifi/headless/HeadlessNiFiServer.java
@@ -156,7 +156,8 @@ public class HeadlessNiFiServer implements NiFiServer {
props,
null, // revision manager
null, // NAR Manager
- null, // Asset Synchronizer
+ null, // Parameter Context Asset Synchronizer
+ null, // Connector Asset Synchronizer
authorizer);
diagnosticsFactory = new BootstrapDiagnosticsFactory();
diff --git a/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/audit/ConnectorAuditor.java b/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/audit/ConnectorAuditor.java
index e26e0d2aa3..73922f984a 100644
--- a/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/audit/ConnectorAuditor.java
+++ b/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/audit/ConnectorAuditor.java
@@ -32,6 +32,7 @@ import org.apache.nifi.components.connector.NamedStepConfiguration;
import org.apache.nifi.components.connector.SecretReference;
import org.apache.nifi.components.connector.StepConfiguration;
import org.apache.nifi.components.connector.StringLiteralValue;
+import org.apache.nifi.web.api.dto.AssetReferenceDTO;
import org.apache.nifi.web.api.dto.ConfigurationStepConfigurationDTO;
import org.apache.nifi.web.api.dto.ConnectorValueReferenceDTO;
import org.apache.nifi.web.api.dto.PropertyGroupConfigurationDTO;
@@ -49,6 +50,8 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
/**
* Audits connector creation/removal and configuration changes.
@@ -275,7 +278,7 @@ public class ConnectorAuditor extends NiFiAuditor {
return switch (valueRef) {
case StringLiteralValue stringLiteral -> stringLiteral.getValue();
- case AssetReference assetRef -> "asset:" + assetRef.getAssetIdentifier();
+ case AssetReference assetRef -> "assets:" + assetRef.getAssetIdentifiers();
case SecretReference secretRef -> "secret:" + secretRef.getProviderId() + "/" + secretRef.getProviderName() + "/" + secretRef.getSecretName();
};
}
@@ -295,7 +298,10 @@ public class ConnectorAuditor extends NiFiAuditor {
if (valueType == null || "STRING_LITERAL".equals(valueType)) {
return valueRefDto.getValue();
} else if ("ASSET_REFERENCE".equals(valueType)) {
- return "asset:" + valueRefDto.getAssetIdentifier();
+ return "assets:" + Stream.ofNullable(valueRefDto.getAssetReferences())
+ .flatMap(List::stream)
+ .map(AssetReferenceDTO::getId)
+ .collect(Collectors.joining(","));
} else if ("SECRET_REFERENCE".equals(valueType)) {
return "secret:" + valueRefDto.getSecretProviderId() + "/" + valueRefDto.getSecretProviderName() + "/" + valueRefDto.getSecretName();
}
diff --git a/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/NiFiServiceFacade.java b/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/NiFiServiceFacade.java
index 963ec8e401..b10cf18a45 100644
--- a/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/NiFiServiceFacade.java
+++ b/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/NiFiServiceFacade.java
@@ -17,6 +17,7 @@
package org.apache.nifi.web;
import io.prometheus.client.CollectorRegistry;
+import org.apache.nifi.asset.Asset;
import org.apache.nifi.authorization.AuthorizeAccess;
import org.apache.nifi.authorization.RequestAction;
import org.apache.nifi.authorization.user.NiFiUser;
@@ -57,7 +58,9 @@ import org.apache.nifi.web.api.dto.ClusterDTO;
import org.apache.nifi.web.api.dto.ComponentHistoryDTO;
import org.apache.nifi.web.api.dto.ComponentStateDTO;
import org.apache.nifi.web.api.dto.ConfigVerificationResultDTO;
+import org.apache.nifi.web.api.dto.ConfigurationStepConfigurationDTO;
import org.apache.nifi.web.api.dto.ConnectionDTO;
+import org.apache.nifi.web.api.dto.ConnectorDTO;
import org.apache.nifi.web.api.dto.ControllerConfigurationDTO;
import org.apache.nifi.web.api.dto.ControllerDTO;
import org.apache.nifi.web.api.dto.ControllerServiceDTO;
@@ -82,8 +85,6 @@ import org.apache.nifi.web.api.dto.PropertyDescriptorDTO;
import org.apache.nifi.web.api.dto.RemoteProcessGroupDTO;
import org.apache.nifi.web.api.dto.RemoteProcessGroupPortDTO;
import org.apache.nifi.web.api.dto.ReportingTaskDTO;
-import org.apache.nifi.web.api.dto.ConfigurationStepConfigurationDTO;
-import org.apache.nifi.web.api.dto.ConnectorDTO;
import org.apache.nifi.web.api.dto.ResourceDTO;
import org.apache.nifi.web.api.dto.SnippetDTO;
import org.apache.nifi.web.api.dto.SystemDiagnosticsDTO;
@@ -104,13 +105,17 @@ import org.apache.nifi.web.api.entity.ActivateControllerServicesEntity;
import org.apache.nifi.web.api.entity.AffectedComponentEntity;
import org.apache.nifi.web.api.entity.AssetEntity;
import org.apache.nifi.web.api.entity.BulletinEntity;
-import org.apache.nifi.web.api.entity.ClearBulletinsResultEntity;
import org.apache.nifi.web.api.entity.ClearBulletinsForGroupResultsEntity;
+import org.apache.nifi.web.api.entity.ClearBulletinsResultEntity;
import org.apache.nifi.web.api.entity.ComponentValidationResultEntity;
import org.apache.nifi.web.api.entity.ConfigurationAnalysisEntity;
+import org.apache.nifi.web.api.entity.ConfigurationStepEntity;
+import org.apache.nifi.web.api.entity.ConfigurationStepNamesEntity;
import org.apache.nifi.web.api.entity.ConnectionEntity;
import org.apache.nifi.web.api.entity.ConnectionStatisticsEntity;
import org.apache.nifi.web.api.entity.ConnectionStatusEntity;
+import org.apache.nifi.web.api.entity.ConnectorEntity;
+import org.apache.nifi.web.api.entity.ConnectorPropertyAllowableValuesEntity;
import org.apache.nifi.web.api.entity.ControllerBulletinsEntity;
import org.apache.nifi.web.api.entity.ControllerConfigurationEntity;
import org.apache.nifi.web.api.entity.ControllerServiceEntity;
@@ -150,10 +155,6 @@ import org.apache.nifi.web.api.entity.RemoteProcessGroupEntity;
import org.apache.nifi.web.api.entity.RemoteProcessGroupPortEntity;
import org.apache.nifi.web.api.entity.RemoteProcessGroupStatusEntity;
import org.apache.nifi.web.api.entity.ReportingTaskEntity;
-import org.apache.nifi.web.api.entity.ConnectorEntity;
-import org.apache.nifi.web.api.entity.ConnectorPropertyAllowableValuesEntity;
-import org.apache.nifi.web.api.entity.ConfigurationStepEntity;
-import org.apache.nifi.web.api.entity.ConfigurationStepNamesEntity;
import org.apache.nifi.web.api.entity.ScheduleComponentsEntity;
import org.apache.nifi.web.api.entity.SnippetEntity;
import org.apache.nifi.web.api.entity.StartVersionControlRequestEntity;
@@ -177,6 +178,7 @@ import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
+import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Supplier;
@@ -215,6 +217,8 @@ public interface NiFiServiceFacade {
ConnectorEntity applyConnectorUpdate(Revision revision, String connectorId);
+ ConnectorEntity discardConnectorUpdate(Revision revision, String connectorId);
+
ProcessGroupFlowEntity getConnectorFlow(String id, boolean uiOnly);
ProcessGroupStatusEntity getConnectorProcessGroupStatus(String id, Boolean recursive);
@@ -227,6 +231,14 @@ public interface NiFiServiceFacade {
ConnectorPropertyAllowableValuesEntity getConnectorPropertyAllowableValues(String connectorId, String stepName, String groupName, String propertyName, String filter);
+ void verifyCreateConnectorAsset(String connectorId);
+
+ AssetEntity createConnectorAsset(String connectorId, String assetId, String assetName, InputStream content) throws IOException;
+
+ List<AssetEntity> getConnectorAssets(String connectorId);
+
+ Optional<Asset> getConnectorAsset(String assetId);
+
// ----------------------------------------
// Synchronization methods
// ----------------------------------------
diff --git a/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/StandardNiFiServiceFacade.java b/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/StandardNiFiServiceFacade.java
index 6a6e575039..9155e6f55b 100644
--- a/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/StandardNiFiServiceFacade.java
+++ b/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/StandardNiFiServiceFacade.java
@@ -246,7 +246,9 @@ import org.apache.nifi.web.api.dto.ComponentStateDTO;
import org.apache.nifi.web.api.dto.ComponentValidationResultDTO;
import org.apache.nifi.web.api.dto.ConfigVerificationResultDTO;
import org.apache.nifi.web.api.dto.ConfigurationAnalysisDTO;
+import org.apache.nifi.web.api.dto.ConfigurationStepConfigurationDTO;
import org.apache.nifi.web.api.dto.ConnectionDTO;
+import org.apache.nifi.web.api.dto.ConnectorDTO;
import org.apache.nifi.web.api.dto.ControllerConfigurationDTO;
import org.apache.nifi.web.api.dto.ControllerDTO;
import org.apache.nifi.web.api.dto.ControllerServiceDTO;
@@ -258,8 +260,6 @@ import org.apache.nifi.web.api.dto.DocumentedTypeDTO;
import org.apache.nifi.web.api.dto.DropRequestDTO;
import org.apache.nifi.web.api.dto.DtoFactory;
import org.apache.nifi.web.api.dto.EntityFactory;
-import org.apache.nifi.web.api.dto.ConnectorDTO;
-import org.apache.nifi.web.api.dto.ConfigurationStepConfigurationDTO;
import org.apache.nifi.web.api.dto.FlowAnalysisRuleDTO;
import org.apache.nifi.web.api.dto.FlowAnalysisRuleViolationDTO;
import org.apache.nifi.web.api.dto.FlowConfigurationDTO;
@@ -331,11 +331,10 @@ import org.apache.nifi.web.api.dto.status.StatusHistoryDTO;
import org.apache.nifi.web.api.dto.status.StatusSnapshotDTO;
import org.apache.nifi.web.api.entity.AccessPolicyEntity;
import org.apache.nifi.web.api.entity.AccessPolicySummaryEntity;
-import org.apache.nifi.web.api.entity.AllowableValueEntity;
-import org.apache.nifi.web.api.entity.ConnectorPropertyAllowableValuesEntity;
import org.apache.nifi.web.api.entity.ActionEntity;
import org.apache.nifi.web.api.entity.ActivateControllerServicesEntity;
import org.apache.nifi.web.api.entity.AffectedComponentEntity;
+import org.apache.nifi.web.api.entity.AllowableValueEntity;
import org.apache.nifi.web.api.entity.AssetEntity;
import org.apache.nifi.web.api.entity.BulletinEntity;
import org.apache.nifi.web.api.entity.ClearBulletinsForGroupResultsEntity;
@@ -343,9 +342,13 @@ import org.apache.nifi.web.api.entity.ClearBulletinsResultEntity;
import org.apache.nifi.web.api.entity.ComponentReferenceEntity;
import org.apache.nifi.web.api.entity.ComponentValidationResultEntity;
import org.apache.nifi.web.api.entity.ConfigurationAnalysisEntity;
+import org.apache.nifi.web.api.entity.ConfigurationStepEntity;
+import org.apache.nifi.web.api.entity.ConfigurationStepNamesEntity;
import org.apache.nifi.web.api.entity.ConnectionEntity;
import org.apache.nifi.web.api.entity.ConnectionStatisticsEntity;
import org.apache.nifi.web.api.entity.ConnectionStatusEntity;
+import org.apache.nifi.web.api.entity.ConnectorEntity;
+import org.apache.nifi.web.api.entity.ConnectorPropertyAllowableValuesEntity;
import org.apache.nifi.web.api.entity.ControllerBulletinsEntity;
import org.apache.nifi.web.api.entity.ControllerConfigurationEntity;
import org.apache.nifi.web.api.entity.ControllerServiceEntity;
@@ -390,9 +393,6 @@ import org.apache.nifi.web.api.entity.RemoteProcessGroupEntity;
import org.apache.nifi.web.api.entity.RemoteProcessGroupPortEntity;
import org.apache.nifi.web.api.entity.RemoteProcessGroupStatusEntity;
import org.apache.nifi.web.api.entity.ReportingTaskEntity;
-import org.apache.nifi.web.api.entity.ConnectorEntity;
-import org.apache.nifi.web.api.entity.ConfigurationStepEntity;
-import org.apache.nifi.web.api.entity.ConfigurationStepNamesEntity;
import org.apache.nifi.web.api.entity.ScheduleComponentsEntity;
import org.apache.nifi.web.api.entity.SecretsEntity;
import org.apache.nifi.web.api.entity.SnippetEntity;
@@ -409,10 +409,10 @@ import org.apache.nifi.web.api.entity.VersionedFlowSnapshotMetadataEntity;
import org.apache.nifi.web.api.entity.VersionedReportingTaskImportResponseEntity;
import org.apache.nifi.web.api.request.FlowMetricsRegistry;
import org.apache.nifi.web.api.request.FlowMetricsReportingStrategy;
-import org.apache.nifi.web.dao.ConnectorDAO;
import org.apache.nifi.web.controller.ControllerFacade;
import org.apache.nifi.web.dao.AccessPolicyDAO;
import org.apache.nifi.web.dao.ConnectionDAO;
+import org.apache.nifi.web.dao.ConnectorDAO;
import org.apache.nifi.web.dao.ControllerServiceDAO;
import org.apache.nifi.web.dao.FlowAnalysisRuleDAO;
import org.apache.nifi.web.dao.FlowRegistryDAO;
@@ -3666,6 +3666,26 @@ public class StandardNiFiServiceFacade implements NiFiServiceFacade {
return entityFactory.createConnectorEntity(snapshot.getComponent(), dtoFactory.createRevisionDTO(snapshot.getLastModification()), permissions, operatePermissions);
}
+ @Override
+ public ConnectorEntity discardConnectorUpdate(final Revision revision, final String connectorId) {
+ final NiFiUser user = NiFiUserUtils.getNiFiUser();
+ final RevisionClaim claim = new StandardRevisionClaim(revision);
+
+ final RevisionUpdate<ConnectorDTO> snapshot = revisionManager.updateRevision(claim, user, () -> {
+ connectorDAO.discardWorkingConfiguration(connectorId);
+
+ final ConnectorNode node = connectorDAO.getConnector(connectorId);
+ final ConnectorDTO dto = dtoFactory.createConnectorDto(node);
+ final FlowModification lastMod = new FlowModification(revision.incrementRevision(revision.getClientId()), user.getIdentity());
+ return new StandardRevisionUpdate<>(dto, lastMod);
+ });
+
+ final ConnectorNode node = connectorDAO.getConnector(snapshot.getComponent().getId());
+ final PermissionsDTO permissions = dtoFactory.createPermissionsDto(node);
+ final PermissionsDTO operatePermissions = dtoFactory.createPermissionsDto(new OperationAuthorizable(node));
+ return entityFactory.createConnectorEntity(snapshot.getComponent(), dtoFactory.createRevisionDTO(snapshot.getLastModification()), permissions, operatePermissions);
+ }
+
@Override
public ProcessGroupFlowEntity getConnectorFlow(final String id, final boolean uiOnly) {
final ConnectorNode connectorNode = connectorDAO.getConnector(id);
@@ -3729,6 +3749,29 @@ public class StandardNiFiServiceFacade implements NiFiServiceFacade {
return entityFactory.createConnectorPropertyAllowableValuesEntity(stepName, groupName, propertyName, allowableValueEntities);
}
+ @Override
+ public void verifyCreateConnectorAsset(final String connectorId) {
+ connectorDAO.verifyCreateAsset(connectorId);
+ }
+
+ @Override
+ public AssetEntity createConnectorAsset(final String connectorId, final String assetId, final String assetName, final InputStream content) throws IOException {
+ final Asset createdAsset = connectorDAO.createAsset(connectorId, assetId, assetName, content);
+ return dtoFactory.createAssetEntity(createdAsset);
+ }
+
+ @Override
+ public List<AssetEntity> getConnectorAssets(final String connectorId) {
+ return connectorDAO.getAssets(connectorId).stream()
+ .map(dtoFactory::createAssetEntity)
+ .toList();
+ }
+
+ @Override
+ public Optional<Asset> getConnectorAsset(final String assetId) {
+ return connectorDAO.getAsset(assetId);
+ }
+
@Override
public ReportingTaskEntity updateReportingTask(final Revision revision, final ReportingTaskDTO reportingTaskDTO) {
// get the component, ensure we have access to it, and perform the update request
diff --git a/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/api/ConnectorResource.java b/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/api/ConnectorResource.java
index e5ad85ea1a..0112d7e61c 100644
--- a/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/api/ConnectorResource.java
+++ b/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/api/ConnectorResource.java
@@ -28,6 +28,7 @@ import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.DefaultValue;
import jakarta.ws.rs.GET;
+import jakarta.ws.rs.HeaderParam;
import jakarta.ws.rs.HttpMethod;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.PUT;
@@ -36,27 +37,50 @@ import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.core.Context;
+import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
+import jakarta.ws.rs.core.StreamingOutput;
import org.apache.commons.lang3.StringUtils;
-import org.apache.nifi.cluster.manager.NodeResponse;
+import org.apache.nifi.asset.Asset;
import org.apache.nifi.authorization.Authorizer;
import org.apache.nifi.authorization.RequestAction;
import org.apache.nifi.authorization.resource.Authorizable;
import org.apache.nifi.authorization.resource.OperationAuthorizable;
import org.apache.nifi.authorization.user.NiFiUser;
import org.apache.nifi.authorization.user.NiFiUserUtils;
+import org.apache.nifi.cluster.coordination.ClusterCoordinator;
+import org.apache.nifi.cluster.coordination.http.replication.RequestReplicationHeader;
+import org.apache.nifi.cluster.coordination.http.replication.UploadRequest;
+import org.apache.nifi.cluster.coordination.http.replication.UploadRequestReplicator;
+import org.apache.nifi.cluster.coordination.node.NodeConnectionState;
+import org.apache.nifi.cluster.manager.NodeResponse;
+import org.apache.nifi.cluster.protocol.NodeIdentifier;
import org.apache.nifi.controller.ScheduledState;
+import org.apache.nifi.processor.DataUnit;
+import org.apache.nifi.stream.io.MaxLengthInputStream;
import org.apache.nifi.ui.extension.UiExtension;
import org.apache.nifi.ui.extension.UiExtensionMapping;
+import org.apache.nifi.util.file.FileUtils;
import org.apache.nifi.web.NiFiServiceFacade;
+import org.apache.nifi.web.ResourceNotFoundException;
import org.apache.nifi.web.Revision;
import org.apache.nifi.web.UiExtensionType;
-import org.apache.nifi.web.api.dto.ConfigVerificationResultDTO;
+import org.apache.nifi.web.api.concurrent.AsyncRequestManager;
+import org.apache.nifi.web.api.concurrent.AsynchronousWebRequest;
+import org.apache.nifi.web.api.concurrent.RequestManager;
+import org.apache.nifi.web.api.concurrent.StandardAsynchronousWebRequest;
+import org.apache.nifi.web.api.concurrent.StandardUpdateStep;
+import org.apache.nifi.web.api.concurrent.UpdateStep;
+import org.apache.nifi.web.api.dto.AssetDTO;
import org.apache.nifi.web.api.dto.BundleDTO;
+import org.apache.nifi.web.api.dto.ConfigVerificationResultDTO;
import org.apache.nifi.web.api.dto.ConfigurationStepConfigurationDTO;
import org.apache.nifi.web.api.dto.ConnectorDTO;
+import org.apache.nifi.web.api.dto.VerifyConnectorConfigStepRequestDTO;
import org.apache.nifi.web.api.dto.search.SearchResultsDTO;
+import org.apache.nifi.web.api.entity.AssetEntity;
+import org.apache.nifi.web.api.entity.AssetsEntity;
import org.apache.nifi.web.api.entity.ConfigurationStepEntity;
import org.apache.nifi.web.api.entity.ConfigurationStepNamesEntity;
import org.apache.nifi.web.api.entity.ConnectorEntity;
@@ -66,26 +90,24 @@ import org.apache.nifi.web.api.entity.ProcessGroupFlowEntity;
import org.apache.nifi.web.api.entity.ProcessGroupStatusEntity;
import org.apache.nifi.web.api.entity.SearchResultsEntity;
import org.apache.nifi.web.api.entity.SecretsEntity;
-import org.apache.nifi.web.api.concurrent.AsyncRequestManager;
-import org.apache.nifi.web.api.concurrent.AsynchronousWebRequest;
-import org.apache.nifi.web.api.concurrent.RequestManager;
-import org.apache.nifi.web.api.concurrent.StandardAsynchronousWebRequest;
-import org.apache.nifi.web.api.concurrent.StandardUpdateStep;
-import org.apache.nifi.web.api.concurrent.UpdateStep;
-import org.apache.nifi.web.api.dto.VerifyConnectorConfigStepRequestDTO;
import org.apache.nifi.web.api.entity.VerifyConnectorConfigStepRequestEntity;
import org.apache.nifi.web.api.request.ClientIdParameter;
import org.apache.nifi.web.api.request.LongParameter;
+import org.apache.nifi.web.client.api.HttpResponseStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
import java.net.URI;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
+import java.util.UUID;
import java.util.function.Consumer;
/**
@@ -98,10 +120,16 @@ public class ConnectorResource extends ApplicationResource {
private static final Logger logger = LoggerFactory.getLogger(ConnectorResource.class);
private static final String VERIFICATION_REQUEST_TYPE = "verification-request";
+ private static final String FILENAME_HEADER = "Filename";
+ private static final String CONTENT_TYPE_HEADER = "Content-Type";
+ private static final String UPLOAD_CONTENT_TYPE = "application/octet-stream";
+ private static final long MAX_ASSET_SIZE_BYTES = (long) DataUnit.GB.toB(1);
private NiFiServiceFacade serviceFacade;
private Authorizer authorizer;
private FlowResource flowResource;
+ private UploadRequestReplicator uploadRequestReplicator;
+
private final RequestManager<VerifyConnectorConfigStepRequestEntity, List<ConfigVerificationResultDTO>> configVerificationRequestManager =
new AsyncRequestManager<>(100, 1L, "Connector Configuration Step Verification");
@@ -1242,6 +1270,83 @@ public class ConnectorResource extends ApplicationResource {
);
}
+ /**
+ * Discards the working configuration of a connector, reverting to the last applied configuration.
+ *
+ * @param version The revision is used to verify the client is working with the latest version of the flow.
+ * @param clientId Optional client id. If the client id is not specified, a new one will be generated. This value (whether specified or generated) is included in the response.
+ * @param id The id of the connector whose working configuration should be discarded.
+ * @return A connectorEntity.
+ */
+ @DELETE
+ @Consumes(MediaType.WILDCARD)
+ @Produces(MediaType.APPLICATION_JSON)
+ @Path("/{id}/working-configuration")
+ @Operation(
+ summary = "Discards the working configuration of a connector",
+ responses = {
+ @ApiResponse(responseCode = "200", content = @Content(schema = @Schema(implementation = ConnectorEntity.class))),
+ @ApiResponse(responseCode = "400", description = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."),
+ @ApiResponse(responseCode = "401", description = "Client could not be authenticated."),
+ @ApiResponse(responseCode = "403", description = "Client is not authorized to make this request."),
+ @ApiResponse(responseCode = "404", description = "The specified resource could not be found."),
+ @ApiResponse(responseCode = "409", description = "The request was valid but NiFi was not in the appropriate state to process it.")
+ },
+ description = "This will discard any pending configuration changes for the connector and revert to the last applied configuration.",
+ security = {
+ @SecurityRequirement(name = "Write - /connectors/{uuid}")
+ }
+ )
+ public Response discardConnectorUpdate(
+ @Parameter(
+ description = "The revision is used to verify the client is working with the latest version of the flow."
+ )
+ @QueryParam(VERSION) final LongParameter version,
+ @Parameter(
+ description = "If the client id is not specified, new one will be generated. This value (whether specified or generated) is included in the response."
+ )
+ @QueryParam(CLIENT_ID) final ClientIdParameter clientId,
+ @Parameter(
+ description = "Acknowledges that this node is disconnected to allow for mutable requests to proceed."
+ )
+ @QueryParam(DISCONNECTED_NODE_ACKNOWLEDGED) @DefaultValue("false") final Boolean disconnectedNodeAcknowledged,
+ @Parameter(
+ description = "The connector id.",
+ required = true
+ )
+ @PathParam("id") final String id) {
+
+ if (isReplicateRequest()) {
+ return replicate(HttpMethod.DELETE);
+ } else if (isDisconnectedFromCluster()) {
+ verifyDisconnectedNodeModification(disconnectedNodeAcknowledged);
+ }
+
+ final ConnectorEntity requestConnectorEntity = new ConnectorEntity();
+ requestConnectorEntity.setId(id);
+
+ final Revision requestRevision = new Revision(version == null ? null : version.getLong(), clientId.getClientId(), id);
+ return withWriteLock(
+ serviceFacade,
+ requestConnectorEntity,
+ requestRevision,
+ lookup -> {
+ final Authorizable connector = lookup.getConnector(id);
+ connector.authorize(authorizer, RequestAction.WRITE, NiFiUserUtils.getNiFiUser());
+ },
+ () -> {
+ // Verify the connector exists
+ serviceFacade.getConnector(id);
+ },
+ (revision, connectorEntity) -> {
+ final ConnectorEntity entity = serviceFacade.discardConnectorUpdate(revision, id);
+ populateRemainingConnectorEntityContent(entity);
+
+ return generateOkResponse(entity).build();
+ }
+ );
+ }
+
/**
* Retrieves the flow for the process group managed by the specified connector.
*
@@ -1380,6 +1485,204 @@ public class ConnectorResource extends ApplicationResource {
return generateOkResponse(entity).build();
}
+ @POST
+ @Consumes(MediaType.APPLICATION_OCTET_STREAM)
+ @Produces(MediaType.APPLICATION_JSON)
+ @Path("{id}/assets")
+ @Operation(
+ summary = "Creates a new Asset in the given Connector",
+ responses = {
+ @ApiResponse(responseCode = "200", content = @Content(schema = @Schema(implementation = AssetEntity.class))),
+ @ApiResponse(responseCode = "400", description = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."),
+ @ApiResponse(responseCode = "401", description = "Client could not be authenticated."),
+ @ApiResponse(responseCode = "403", description = "Client is not authorized to make this request."),
+ @ApiResponse(responseCode = "404", description = "The specified resource could not be found."),
+ @ApiResponse(responseCode = "409", description = "The request was valid but NiFi was not in the appropriate state to process it.")
+ },
+ description = "This endpoint will create a new Asset in the Connector. The Asset will be created with the given name and the contents of the file that is uploaded.",
+ security = {
+ @SecurityRequirement(name = "Write - /connectors/{uuid}")
+ }
+ )
+ public Response createAsset(
+ @PathParam("id") final String connectorId,
+ @HeaderParam(FILENAME_HEADER) final String assetName,
+ @Parameter(description = "The contents of the asset", required = true) final InputStream assetContents) throws IOException {
+
+ // Validate input
+ if (StringUtils.isBlank(assetName)) {
+ throw new IllegalArgumentException(FILENAME_HEADER + " header is required");
+ }
+ if (assetContents == null) {
+ throw new IllegalArgumentException("Asset contents must be specified.");
+ }
+
+ final String sanitizedAssetName = FileUtils.getSanitizedFilename(assetName);
+ if (!assetName.equals(sanitizedAssetName)) {
+ throw new IllegalArgumentException(FILENAME_HEADER + " header contains an invalid file name");
+ }
+
+ // If clustered and not all nodes are connected, do not allow creating an asset.
+ // Generally, we allow the flow to be modified when nodes are disconnected, but we do not allow creating an asset because
+ // the cluster has no mechanism for synchronizing those assets after the upload.
+ final ClusterCoordinator clusterCoordinator = getClusterCoordinator();
+ if (clusterCoordinator != null) {
+ final Set<NodeIdentifier> disconnectedNodes = clusterCoordinator.getNodeIdentifiers(NodeConnectionState.CONNECTING, NodeConnectionState.DISCONNECTED, NodeConnectionState.DISCONNECTING);
+ if (!disconnectedNodes.isEmpty()) {
+ throw new IllegalStateException("Cannot create an Asset because the following %s nodes are not currently connected: %s".formatted(disconnectedNodes.size(), disconnectedNodes));
+ }
+ }
+
+ final NiFiUser currentUser = NiFiUserUtils.getNiFiUser();
+
+ // Verify Connector exists
+ serviceFacade.verifyCreateConnectorAsset(connectorId);
+
+ // Authorize the request
+ serviceFacade.authorizeAccess(lookup -> {
+ final Authorizable connector = lookup.getConnector(connectorId);
+ connector.authorize(authorizer, RequestAction.WRITE, currentUser);
+ });
+
+ // If we need to replicate the request, we do so using the Upload Request Replicator, rather than the typical replicate() method.
+ // This is because Upload Request Replication works differently in that it needs to be able to replicate the InputStream multiple times,
+ // so it must create a file on disk to do so and then use the file's content to replicate the request. It also bypasses the two-phase
+ // commit process that is used for other requests because doing so would result in uploading the file twice to each node or providing a
+ // different request for each of the two phases.
+
+ final long startTime = System.currentTimeMillis();
+ final InputStream maxLengthInputStream = new MaxLengthInputStream(assetContents, MAX_ASSET_SIZE_BYTES);
+
+ final AssetEntity assetEntity;
+ if (isReplicateRequest()) {
+ final String uploadRequestId = UUID.randomUUID().toString();
+ final UploadRequest<AssetEntity> uploadRequest = new UploadRequest.Builder<AssetEntity>()
+ .user(NiFiUserUtils.getNiFiUser())
+ .filename(sanitizedAssetName)
+ .identifier(uploadRequestId)
+ .contents(maxLengthInputStream)
+ .header(FILENAME_HEADER, sanitizedAssetName)
+ .header(CONTENT_TYPE_HEADER, UPLOAD_CONTENT_TYPE)
+ .header(RequestReplicationHeader.CLUSTER_ID_GENERATION_SEED.getHeader(), uploadRequestId)
+ .exampleRequestUri(getAbsolutePath())
+ .responseClass(AssetEntity.class)
+ .successfulResponseStatus(HttpResponseStatus.OK.getCode())
+ .build();
+ assetEntity = uploadRequestReplicator.upload(uploadRequest);
+ } else {
+ final String assetId = generateUuid();
+ logger.info("Creating asset [id={},name={}] in Connector [{}]", assetId, sanitizedAssetName, connectorId);
+ assetEntity = serviceFacade.createConnectorAsset(connectorId, assetId, sanitizedAssetName, maxLengthInputStream);
+
+ final AssetDTO assetDTO = assetEntity.getAsset();
+ final long elapsedTime = System.currentTimeMillis() - startTime;
+ logger.info("Creation of asset [id={},name={}] in Connector [{}] completed in {} ms", assetDTO.getId(), assetDTO.getName(), connectorId, elapsedTime);
+ }
+
+ return generateOkResponse(assetEntity).build();
+ }
+
+ @GET
+ @Consumes(MediaType.WILDCARD)
+ @Produces(MediaType.APPLICATION_JSON)
+ @Path("{id}/assets")
+ @Operation(
+ summary = "Lists the assets that belong to the Connector with the given ID",
+ responses = {
+ @ApiResponse(responseCode = "200", content = @Content(schema = @Schema(implementation = AssetsEntity.class))),
+ @ApiResponse(responseCode = "400", description = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."),
+ @ApiResponse(responseCode = "401", description = "Client could not be authenticated."),
+ @ApiResponse(responseCode = "403", description = "Client is not authorized to make this request."),
+ @ApiResponse(responseCode = "404", description = "The specified resource could not be found."),
+ @ApiResponse(responseCode = "409", description = "The request was valid but NiFi was not in the appropriate state to process it.")
+ },
+ description = "Lists the assets that belong to the Connector with the given ID.",
+ security = {
+ @SecurityRequirement(name = "Read - /connectors/{uuid}")
+ }
+ )
+ public Response getAssets(
+ @Parameter(
+ description = "The connector id.",
+ required = true
+ )
+ @PathParam("id") final String connectorId
+ ) {
+ serviceFacade.authorizeAccess(lookup -> {
+ final Authorizable connector = lookup.getConnector(connectorId);
+ connector.authorize(authorizer, RequestAction.READ, NiFiUserUtils.getNiFiUser());
+ });
+
+ if (isReplicateRequest()) {
+ return replicate(HttpMethod.GET);
+ }
+
+ final List<AssetEntity> connectorAssets = serviceFacade.getConnectorAssets(connectorId);
+ logger.debug("Returning [{}] assets for connector [{}]", connectorAssets.size(), connectorId);
+
+ final AssetsEntity assetsEntity = new AssetsEntity();
+ assetsEntity.setAssets(connectorAssets);
+
+ return generateOkResponse(assetsEntity).build();
+ }
+
+ @GET
+ @Consumes(MediaType.WILDCARD)
+ @Produces(MediaType.APPLICATION_OCTET_STREAM)
+ @Path("{id}/assets/{assetId}")
+ @Operation(
+ summary = "Retrieves the content of the asset with the given id for a connector",
+ responses = {
+ @ApiResponse(responseCode = "200", content = @Content(schema = @Schema(implementation = byte[].class))),
+ @ApiResponse(responseCode = "400", description = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."),
+ @ApiResponse(responseCode = "401", description = "Client could not be authenticated."),
+ @ApiResponse(responseCode = "403", description = "Client is not authorized to make this request."),
+ @ApiResponse(responseCode = "404", description = "The specified resource could not be found."),
+ @ApiResponse(responseCode = "409", description = "The request was valid but NiFi was not in the appropriate state to process it.")
+ },
+ security = {
+ @SecurityRequirement(name = "Read - /connectors/{uuid}")
+ }
+ )
+ public Response getAssetContent(
+ @Parameter(
+ description = "The connector id.",
+ required = true
+ )
+ @PathParam("id") final String connectorId,
+ @Parameter(
+ description = "The asset id.",
+ required = true
+ )
+ @PathParam("assetId") final String assetId
+ ) {
+ serviceFacade.authorizeAccess(lookup -> {
+ final Authorizable connector = lookup.getConnector(connectorId);
+ connector.authorize(authorizer, RequestAction.READ, NiFiUserUtils.getNiFiUser());
+ });
+
+ final Asset asset = serviceFacade.getConnectorAsset(assetId)
+ .orElseThrow(() -> new ResourceNotFoundException("Asset does not exist with id %s".formatted(assetId)));
+
+ if (!asset.getOwnerIdentifier().equals(connectorId)) {
+ throw new ResourceNotFoundException("Asset does not exist with id %s".formatted(assetId));
+ }
+
+ if (!asset.getFile().exists()) {
+ throw new IllegalStateException("Content does not exist for asset with id %s".formatted(assetId));
+ }
+
+ final StreamingOutput streamingOutput = outputStream -> {
+ try (final InputStream assetInputStream = new FileInputStream(asset.getFile())) {
+ assetInputStream.transferTo(outputStream);
+ }
+ };
+
+ return generateOkResponse(streamingOutput)
+ .header(HttpHeaders.CONTENT_DISPOSITION, String.format("attachment; filename=\"%s\"", asset.getName()))
+ .build();
+ }
+
// -----------------
// setters
// -----------------
@@ -1398,4 +1701,10 @@ public class ConnectorResource extends ApplicationResource {
public void setFlowResource(final FlowResource flowResource) {
this.flowResource = flowResource;
}
+
+ @Autowired(required = false)
+ public void setUploadRequestReplicator(final UploadRequestReplicator uploadRequestReplicator) {
+ this.uploadRequestReplicator = uploadRequestReplicator;
+ }
+
}
diff --git a/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/api/ParameterContextResource.java b/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/api/ParameterContextResource.java
index 072c9949a1..8544e33ffa 100644
--- a/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/api/ParameterContextResource.java
+++ b/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/api/ParameterContextResource.java
@@ -535,7 +535,7 @@ public class ParameterContextResource extends AbstractParameterResource {
final Asset asset = assetManager.getAsset(assetId)
.orElseThrow(() -> new ResourceNotFoundException("Asset does not exist with the id %s".formatted(assetId)));
- if (!asset.getParameterContextIdentifier().equals(parameterContextId)) {
+ if (!asset.getOwnerIdentifier().equals(parameterContextId)) {
throw new ResourceNotFoundException("Asset does not exist with id %s".formatted(assetId));
}
@@ -810,7 +810,7 @@ public class ParameterContextResource extends AbstractParameterResource {
}
final Asset asset = assetManager.getAsset(referencedAsset.getId())
.orElseThrow(() -> new IllegalArgumentException("Request contains a reference to an Asset (%s) that does not exist".formatted(referencedAsset)));
- if (!asset.getParameterContextIdentifier().equals(parameterContextDto.getId())) {
+ if (!asset.getOwnerIdentifier().equals(parameterContextDto.getId())) {
throw new IllegalArgumentException("Request contains a reference to an Asset (%s) that does not exist in Parameter Context (%s)"
.formatted(referencedAsset, parameterContextDto.getId()));
}
diff --git a/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/api/dto/DtoFactory.java b/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/api/dto/DtoFactory.java
index 9f46284f1b..8af59df8ff 100644
--- a/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/api/dto/DtoFactory.java
+++ b/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/api/dto/DtoFactory.java
@@ -66,6 +66,7 @@ import org.apache.nifi.components.ConfigVerificationResult;
import org.apache.nifi.components.PropertyDependency;
import org.apache.nifi.components.PropertyDescriptor;
import org.apache.nifi.components.ValidationResult;
+import org.apache.nifi.components.connector.ConnectorAssetRepository;
import org.apache.nifi.components.state.Scope;
import org.apache.nifi.components.state.StateMap;
import org.apache.nifi.components.validation.ValidationState;
@@ -316,6 +317,7 @@ public final class DtoFactory {
private EntityFactory entityFactory;
private Authorizer authorizer;
private ExtensionManager extensionManager;
+ private ConnectorAssetRepository connectorAssetRepository;
public ControllerConfigurationDTO createControllerConfigurationDto(final ControllerFacade controllerFacade) {
final ControllerConfigurationDTO dto = new ControllerConfigurationDTO();
@@ -5204,14 +5206,18 @@ public final class DtoFactory {
this.entityFactory = entityFactory;
}
- public void setBulletinRepository(BulletinRepository bulletinRepository) {
+ public void setBulletinRepository(final BulletinRepository bulletinRepository) {
this.bulletinRepository = bulletinRepository;
}
- public void setExtensionManager(ExtensionManager extensionManager) {
+ public void setExtensionManager(final ExtensionManager extensionManager) {
this.extensionManager = extensionManager;
}
+ public void setConnectorAssetRepository(final ConnectorAssetRepository connectorAssetRepository) {
+ this.connectorAssetRepository = connectorAssetRepository;
+ }
+
private ProcessingPerformanceStatusDTO createProcessingPerformanceStatusDTO(final ProcessingPerformanceStatus performanceStatus) {
final ProcessingPerformanceStatusDTO performanceStatusDTO = new ProcessingPerformanceStatusDTO();
@@ -5345,7 +5351,12 @@ public final class DtoFactory {
switch (valueReference) {
case StringLiteralValue stringLiteral -> dto.setValue(stringLiteral.getValue());
- case AssetReference assetRef -> dto.setAssetIdentifier(assetRef.getAssetIdentifier());
+ case AssetReference assetRef -> {
+ final List<AssetReferenceDTO> assetReferences = assetRef.getAssetIdentifiers().stream()
+ .map(this::createConnectorAssetReferenceDto)
+ .toList();
+ dto.setAssetReferences(assetReferences);
+ }
case SecretReference secretRef -> {
dto.setSecretProviderId(secretRef.getProviderId());
dto.setSecretProviderName(secretRef.getProviderName());
@@ -5357,6 +5368,11 @@ public final class DtoFactory {
return dto;
}
+ private AssetReferenceDTO createConnectorAssetReferenceDto(final String assetId) {
+ final String assetName = connectorAssetRepository.getAsset(assetId).map(Asset::getName).orElse(assetId);
+ return new AssetReferenceDTO(assetId, assetName);
+ }
+
private ConnectorPropertyDescriptorDTO createConnectorPropertyDescriptorDto(final ConnectorPropertyDescriptor propertyDescriptor) {
if (propertyDescriptor == null) {
return null;
diff --git a/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/configuration/WebApplicationConfiguration.java b/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/configuration/WebApplicationConfiguration.java
index 24b4a42c6c..f51fb0c0c2 100644
--- a/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/configuration/WebApplicationConfiguration.java
+++ b/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/configuration/WebApplicationConfiguration.java
@@ -178,6 +178,7 @@ public class WebApplicationConfiguration {
dtoFactory.setControllerServiceProvider(flowController.getControllerServiceProvider());
dtoFactory.setEntityFactory(entityFactory());
dtoFactory.setExtensionManager(extensionManager);
+ dtoFactory.setConnectorAssetRepository(flowController.getConnectorRepository().getAssetRepository());
return dtoFactory;
}
diff --git a/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/dao/ConnectorDAO.java b/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/dao/ConnectorDAO.java
index 53c87afc99..a494cf47ba 100644
--- a/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/dao/ConnectorDAO.java
+++ b/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/dao/ConnectorDAO.java
@@ -16,6 +16,7 @@
*/
package org.apache.nifi.web.dao;
+import org.apache.nifi.asset.Asset;
import org.apache.nifi.bundle.BundleCoordinate;
import org.apache.nifi.components.AllowableValue;
import org.apache.nifi.components.ConfigVerificationResult;
@@ -23,7 +24,10 @@ import org.apache.nifi.components.connector.ConnectorNode;
import org.apache.nifi.components.connector.ConnectorUpdateContext;
import org.apache.nifi.web.api.dto.ConfigurationStepConfigurationDTO;
+import java.io.IOException;
+import java.io.InputStream;
import java.util.List;
+import java.util.Optional;
public interface ConnectorDAO {
@@ -49,11 +53,21 @@ public interface ConnectorDAO {
void applyConnectorUpdate(String id, ConnectorUpdateContext updateContext);
+ void discardWorkingConfiguration(String id);
+
void verifyCanVerifyConfigurationStep(String id, String configurationStepName);
List<ConfigVerificationResult> verifyConfigurationStep(String id, String configurationStepName, ConfigurationStepConfigurationDTO configurationStepConfiguration);
List<AllowableValue> fetchAllowableValues(String id, String stepName, String propertyName, String filter);
-}
+ void verifyCreateAsset(String id);
+
+ Asset createAsset(String id, String assetId, String assetName, InputStream content) throws IOException;
+
+ List<Asset> getAssets(String id);
+
+ Optional<Asset> getAsset(String assetId);
+
+}
diff --git a/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/dao/impl/StandardConnectorDAO.java b/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/dao/impl/StandardConnectorDAO.java
index 8dbdfa538a..d4b2183604 100644
--- a/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/dao/impl/StandardConnectorDAO.java
+++ b/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/dao/impl/StandardConnectorDAO.java
@@ -16,15 +16,20 @@
*/
package org.apache.nifi.web.dao.impl;
+import org.apache.nifi.asset.Asset;
import org.apache.nifi.bundle.BundleCoordinate;
import org.apache.nifi.components.AllowableValue;
import org.apache.nifi.components.ConfigVerificationResult;
import org.apache.nifi.components.connector.AssetReference;
+import org.apache.nifi.components.connector.ConnectorAssetRepository;
+import org.apache.nifi.components.connector.ConnectorConfiguration;
import org.apache.nifi.components.connector.ConnectorNode;
import org.apache.nifi.components.connector.ConnectorRepository;
import org.apache.nifi.components.connector.ConnectorUpdateContext;
import org.apache.nifi.components.connector.ConnectorValueReference;
import org.apache.nifi.components.connector.ConnectorValueType;
+import org.apache.nifi.components.connector.FrameworkFlowContext;
+import org.apache.nifi.components.connector.NamedStepConfiguration;
import org.apache.nifi.components.connector.SecretReference;
import org.apache.nifi.components.connector.StepConfiguration;
import org.apache.nifi.components.connector.StringLiteralValue;
@@ -32,20 +37,32 @@ import org.apache.nifi.controller.FlowController;
import org.apache.nifi.controller.flow.FlowManager;
import org.apache.nifi.web.NiFiCoreException;
import org.apache.nifi.web.ResourceNotFoundException;
+import org.apache.nifi.web.api.dto.AssetReferenceDTO;
import org.apache.nifi.web.api.dto.ConfigurationStepConfigurationDTO;
import org.apache.nifi.web.api.dto.ConnectorValueReferenceDTO;
import org.apache.nifi.web.api.dto.PropertyGroupConfigurationDTO;
import org.apache.nifi.web.dao.ConnectorDAO;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Collections;
import java.util.HashMap;
+import java.util.HashSet;
import java.util.List;
import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.stream.Collectors;
@Repository
public class StandardConnectorDAO implements ConnectorDAO {
+ private static final Logger logger = LoggerFactory.getLogger(StandardConnectorDAO.class);
+
private FlowController flowController;
@Autowired
@@ -61,6 +78,10 @@ public class StandardConnectorDAO implements ConnectorDAO {
return flowController.getConnectorRepository();
}
+ private ConnectorAssetRepository getConnectorAssetRepository() {
+ return flowController.getConnectorRepository().getAssetRepository();
+ }
+
@Override
public boolean hasConnector(final String id) {
return getConnectorRepository().getConnector(id) != null;
@@ -91,6 +112,7 @@ public class StandardConnectorDAO implements ConnectorDAO {
@Override
public void deleteConnector(final String id) {
getConnectorRepository().removeConnector(id);
+ getConnectorAssetRepository().deleteAssets(id);
}
@Override
@@ -153,21 +175,36 @@ public class StandardConnectorDAO implements ConnectorDAO {
final ConnectorValueType valueType = dto.getValueType() != null ? ConnectorValueType.valueOf(dto.getValueType()) : ConnectorValueType.STRING_LITERAL;
return switch (valueType) {
case STRING_LITERAL -> new StringLiteralValue(dto.getValue());
- case ASSET_REFERENCE -> new AssetReference(dto.getAssetIdentifier());
+ case ASSET_REFERENCE -> new AssetReference(convertToAssetIdentifiers(dto.getAssetReferences()));
case SECRET_REFERENCE -> new SecretReference(dto.getSecretProviderId(), dto.getSecretProviderName(), dto.getSecretName(), dto.getFullyQualifiedSecretName());
};
}
+ private Set<String> convertToAssetIdentifiers(final List<AssetReferenceDTO> assetReferenceDTOs) {
+ if (assetReferenceDTOs == null || assetReferenceDTOs.isEmpty()) {
+ return Collections.emptySet();
+ }
+ return assetReferenceDTOs.stream().map(AssetReferenceDTO::getId).collect(Collectors.toSet());
+ }
+
@Override
public void applyConnectorUpdate(final String id, final ConnectorUpdateContext updateContext) {
final ConnectorNode connector = getConnector(id);
try {
getConnectorRepository().applyUpdate(connector, updateContext);
+ cleanUpAssets(connector);
} catch (final Exception e) {
throw new NiFiCoreException("Failed to apply connector update: " + e, e);
}
}
+ @Override
+ public void discardWorkingConfiguration(final String id) {
+ final ConnectorNode connector = getConnector(id);
+ connector.discardWorkingConfiguration();
+ cleanUpAssets(connector);
+ }
+
@Override
public void verifyCanVerifyConfigurationStep(final String id, final String configurationStepName) {
// Verify that the connector exists
@@ -190,6 +227,64 @@ public class StandardConnectorDAO implements ConnectorDAO {
return connector.fetchAllowableValues(stepName, propertyName, filter);
}
}
+
+ @Override
+ public void verifyCreateAsset(final String id) {
+ getConnector(id);
+ }
+
+ @Override
+ public Asset createAsset(final String id, final String assetId, final String assetName, final InputStream content) throws IOException {
+ final ConnectorAssetRepository assetRepository = getConnectorAssetRepository();
+ return assetRepository.storeAsset(id, assetId, assetName, content);
+ }
+
+ @Override
+ public List<Asset> getAssets(final String id) {
+ final ConnectorAssetRepository assetRepository = getConnectorAssetRepository();
+ return assetRepository.getAssets(id);
+ }
+
+ @Override
+ public Optional<Asset> getAsset(final String assetId) {
+ final ConnectorAssetRepository assetRepository = getConnectorAssetRepository();
+ return assetRepository.getAsset(assetId);
+ }
+
+ private void cleanUpAssets(final ConnectorNode connector) {
+ final FrameworkFlowContext activeFlowContext = connector.getActiveFlowContext();
+ final ConnectorConfiguration activeConfiguration = activeFlowContext.getConfigurationContext().toConnectorConfiguration();
+
+ final Set<String> referencedAssetIds = new HashSet<>();
+ for (final NamedStepConfiguration namedStepConfiguration : activeConfiguration.getNamedStepConfigurations()) {
+ final StepConfiguration stepConfiguration = namedStepConfiguration.configuration();
+ final Map<String, ConnectorValueReference> stepPropertyValues = stepConfiguration.getPropertyValues();
+ if (stepPropertyValues == null) {
+ continue;
+ }
+ for (final ConnectorValueReference valueReference : stepPropertyValues.values()) {
+ if (valueReference instanceof AssetReference assetReference) {
+ referencedAssetIds.addAll(assetReference.getAssetIdentifiers());
+ }
+ }
+ }
+
+ logger.debug("Found {} assets referenced for Connector [{}]", referencedAssetIds.size(), connector.getIdentifier());
+
+ final ConnectorAssetRepository assetRepository = getConnectorAssetRepository();
+ final List<Asset> allConnectorAssets = assetRepository.getAssets(connector.getIdentifier());
+ for (final Asset asset : allConnectorAssets) {
+ final String assetId = asset.getIdentifier();
+ if (!referencedAssetIds.contains(assetId)) {
+ try {
+ logger.info("Deleting unreferenced asset [id={},name={}] for connector [{}]", assetId, asset.getName(), connector.getIdentifier());
+ assetRepository.deleteAsset(assetId);
+ } catch (final Exception e) {
+ logger.warn("Unable to delete unreferenced asset [id={},name={}] for connector [{}]", assetId, asset.getName(), connector.getIdentifier(), e);
+ }
+ }
+ }
+ }
}
diff --git a/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/dao/impl/StandardParameterContextDAO.java b/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/dao/impl/StandardParameterContextDAO.java
index b151f08575..016e4962d2 100644
--- a/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/dao/impl/StandardParameterContextDAO.java
+++ b/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/dao/impl/StandardParameterContextDAO.java
@@ -350,7 +350,7 @@ public class StandardParameterContextDAO implements ParameterContextDAO {
if (parameter != null) {
final List<Asset> assets = parameter.getReferencedAssets() == null ? Collections.emptyList() : parameter.getReferencedAssets();
for (final Asset asset : assets) {
- if (!asset.getParameterContextIdentifier().equals(parameterContextDto.getId())) {
+ if (!asset.getOwnerIdentifier().equals(parameterContextDto.getId())) {
throw new IllegalArgumentException(String.format("Parameter [%s] is not allowed to reference asset [%s] which does not belong to parameter context [%s]",
parameter.getDescriptor().getName(), asset.getName(), parameterContextDto.getId()));
}
diff --git a/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/test/java/org/apache/nifi/web/dao/impl/StandardConnectorDAOTest.java b/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/test/java/org/apache/nifi/web/dao/impl/StandardConnectorDAOTest.java
index 19dff6703a..420c650620 100644
--- a/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/test/java/org/apache/nifi/web/dao/impl/StandardConnectorDAOTest.java
+++ b/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/test/java/org/apache/nifi/web/dao/impl/StandardConnectorDAOTest.java
@@ -17,6 +17,7 @@
package org.apache.nifi.web.dao.impl;
import org.apache.nifi.components.AllowableValue;
+import org.apache.nifi.components.connector.ConnectorAssetRepository;
import org.apache.nifi.components.connector.ConnectorNode;
import org.apache.nifi.components.connector.ConnectorRepository;
import org.apache.nifi.components.connector.ConnectorUpdateContext;
@@ -57,6 +58,9 @@ class StandardConnectorDAOTest {
@Mock
private ConnectorUpdateContext connectorUpdateContext;
+ @Mock
+ private ConnectorAssetRepository connectorAssetRepository;
+
private static final String CONNECTOR_ID = "test-connector-id";
private static final String STEP_NAME = "test-step";
private static final String PROPERTY_NAME = "test-property";
@@ -67,6 +71,7 @@ class StandardConnectorDAOTest {
connectorDAO.setFlowController(flowController);
when(flowController.getConnectorRepository()).thenReturn(connectorRepository);
+ when(connectorRepository.getAssetRepository()).thenReturn(connectorAssetRepository);
}
@Test
@@ -212,5 +217,25 @@ class StandardConnectorDAOTest {
verify(connectorRepository).getConnector(CONNECTOR_ID);
}
+
+ @Test
+ void testDeleteConnectorRemovesConnectorAndAssets() {
+ connectorDAO.deleteConnector(CONNECTOR_ID);
+
+ verify(connectorRepository).removeConnector(CONNECTOR_ID);
+ verify(connectorAssetRepository).deleteAssets(CONNECTOR_ID);
+ }
+
+ @Test
+ void testDeleteConnectorDoesNotDeleteAssetsWhenRemovalFails() {
+ doThrow(new RuntimeException("Removal failed")).when(connectorRepository).removeConnector(CONNECTOR_ID);
+
+ assertThrows(RuntimeException.class, () ->
+ connectorDAO.deleteConnector(CONNECTOR_ID)
+ );
+
+ verify(connectorRepository).removeConnector(CONNECTOR_ID);
+ verify(connectorAssetRepository, never()).deleteAssets(any());
+ }
}
diff --git a/nifi-system-tests/nifi-system-test-extensions-bundle/nifi-system-test-extensions/src/main/java/org/apache/nifi/connectors/tests/system/AssetConnector.java b/nifi-system-tests/nifi-system-test-extensions-bundle/nifi-system-test-extensions/src/main/java/org/apache/nifi/connectors/tests/system/AssetConnector.java
new file mode 100644
index 0000000000..cbab02f64c
--- /dev/null
+++ b/nifi-system-tests/nifi-system-test-extensions-bundle/nifi-system-test-extensions/src/main/java/org/apache/nifi/connectors/tests/system/AssetConnector.java
@@ -0,0 +1,93 @@
+/*
+ * 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.connectors.tests.system;
+
+import org.apache.nifi.components.ConfigVerificationResult;
+import org.apache.nifi.components.connector.AbstractConnector;
+import org.apache.nifi.components.connector.ConfigurationStep;
+import org.apache.nifi.components.connector.ConnectorPropertyDescriptor;
+import org.apache.nifi.components.connector.ConnectorPropertyGroup;
+import org.apache.nifi.components.connector.FlowUpdateException;
+import org.apache.nifi.components.connector.PropertyType;
+import org.apache.nifi.components.connector.components.FlowContext;
+import org.apache.nifi.flow.VersionedExternalFlow;
+
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Example Connector used by system tests for exercising Connector Asset APIs.
+ * <p>
+ * The connector defines a single configuration step with one property whose type is ASSET.
+ * The connector itself does not manipulate the flow; it is intended only to drive API-level tests.
+ */
+public class AssetConnector extends AbstractConnector {
+
+ static final ConnectorPropertyDescriptor ASSET_PROPERTY = new ConnectorPropertyDescriptor.Builder()
+ .name("Test Asset")
+ .description("Asset used for validating Connector Asset APIs in system tests")
+ .type(PropertyType.ASSET)
+ .required(true)
+ .build();
+
+ private static final ConnectorPropertyGroup ASSET_GROUP = new ConnectorPropertyGroup.Builder()
+ .name("Asset Configuration")
+ .description("Configuration properties related to Assets")
+ .addProperty(ASSET_PROPERTY)
+ .build();
+
+ private static final ConfigurationStep ASSET_CONFIGURATION_STEP = new ConfigurationStep.Builder()
+ .name("Asset Configuration")
+ .description("Configuration Step that exposes an ASSET-type property")
+ .propertyGroups(List.of(ASSET_GROUP))
+ .build();
+
+ @Override
+ public VersionedExternalFlow getInitialFlow() {
+ // This Connector is intended only for exercising the REST API and does not manage a flow.
+ return null;
+ }
+
+ @Override
+ public void prepareForUpdate(final FlowContext workingContext, final FlowContext activeContext) throws FlowUpdateException {
+ // No-op: this connector does not manipulate the flow.
+ }
+
+ @Override
+ public List<ConfigurationStep> getConfigurationSteps(final FlowContext flowContext) {
+ return List.of(ASSET_CONFIGURATION_STEP);
+ }
+
+ @Override
+ public void applyUpdate(final FlowContext workingContext, final FlowContext activeContext) throws FlowUpdateException {
+ // No-op: this connector does not manipulate the flow.
+ }
+
+ @Override
+ protected void onStepConfigured(final String stepName, final FlowContext workingContext) throws FlowUpdateException {
+ // No-op: there is no additional behavior when the step is configured.
+ }
+
+ @Override
+ public List<ConfigVerificationResult> verifyConfigurationStep(final String stepName, final Map<String, String> overrides, final FlowContext flowContext) {
+ // No additional verification is required for this simple test connector.
+ return List.of();
+ }
+}
+
+
diff --git a/nifi-system-tests/nifi-system-test-extensions-bundle/nifi-system-test-extensions/src/main/resources/META-INF/services/org.apache.nifi.components.connector.Connector b/nifi-system-tests/nifi-system-test-extensions-bundle/nifi-system-test-extensions/src/main/resources/META-INF/services/org.apache.nifi.components.connector.Connector
index 8231782690..85b4fb889a 100644
--- a/nifi-system-tests/nifi-system-test-extensions-bundle/nifi-system-test-extensions/src/main/resources/META-INF/services/org.apache.nifi.components.connector.Connector
+++ b/nifi-system-tests/nifi-system-test-extensions-bundle/nifi-system-test-extensions/src/main/resources/META-INF/services/org.apache.nifi.components.connector.Connector
@@ -14,3 +14,6 @@
# limitations under the License.
org.apache.nifi.connectors.tests.system.NopConnector
+org.apache.nifi.connectors.tests.system.AssetConnector
+
+
diff --git a/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/ClusteredConnectorAssetsIT.java b/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/ClusteredConnectorAssetsIT.java
new file mode 100644
index 0000000000..9016c504ce
--- /dev/null
+++ b/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/ClusteredConnectorAssetsIT.java
@@ -0,0 +1,142 @@
+/*
+ * 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.tests.system.connectors;
+
+import org.apache.nifi.tests.system.NiFiInstanceFactory;
+import org.apache.nifi.toolkit.client.ConnectorClient;
+import org.apache.nifi.toolkit.client.NiFiClientException;
+import org.apache.nifi.util.file.FileUtils;
+import org.apache.nifi.web.api.entity.AssetEntity;
+import org.apache.nifi.web.api.entity.AssetsEntity;
+import org.apache.nifi.web.api.entity.ConnectorEntity;
+import org.junit.jupiter.api.Test;
+
+import java.io.File;
+import java.io.IOException;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Clustered variants of the connector system tests that verify connector assets
+ * are synchronized across all cluster nodes.
+ *
+ * The structure of these tests is based on the clustered parameter context
+ * asset synchronization tests in {@code ClusteredParameterContextIT}.
+ */
+public class ClusteredConnectorAssetsIT extends ConnectorAssetsIT {
+
+ @Override
+ public NiFiInstanceFactory getInstanceFactory() {
+ return createTwoNodeInstanceFactory();
+ }
+
+ @Test
+ public void testSynchronizeConnectorAssets() throws NiFiClientException, IOException, InterruptedException {
+ waitForAllNodesConnected();
+
+ // Create a Connector instance using the AssetConnector test extension
+ final ConnectorEntity connector = getClientUtil().createConnector("AssetConnector");
+ assertNotNull(connector);
+ assertNotNull(connector.getId());
+
+ final String connectorId = connector.getId();
+
+ // Upload an Asset to the Connector
+ final File assetFile = new File("src/test/resources/sample-assets/helloworld.txt");
+ final ConnectorClient connectorClient = getNifiClient().getConnectorClient();
+ final AssetEntity assetEntity = connectorClient.createAsset(connectorId, assetFile.getName(), assetFile);
+
+ assertNotNull(assetEntity);
+ assertNotNull(assetEntity.getAsset());
+ assertNotNull(assetEntity.getAsset().getId());
+ assertEquals(assetFile.getName(), assetEntity.getAsset().getName());
+
+ final String uploadedAssetId = assetEntity.getAsset().getId();
+
+ // List the Connector's Assets and verify that the uploaded Asset is present
+ final AssetsEntity assetsEntity = connectorClient.getAssets(connectorId);
+ assertNotNull(assetsEntity);
+ assertNotNull(assetsEntity.getAssets());
+ assertFalse(assetsEntity.getAssets().isEmpty());
+
+ final boolean assetFound = assetsEntity.getAssets().stream()
+ .filter(a -> a.getAsset() != null)
+ .anyMatch(a -> uploadedAssetId.equals(a.getAsset().getId()));
+
+ assertTrue(assetFound);
+
+ // Check that the asset exists in the connector-assets directory for each node
+ final File node1Dir = getNiFiInstance().getNodeInstance(1).getInstanceDirectory();
+ final File node1AssetsDir = new File(node1Dir, "connector-assets");
+ final File node1ConnectorDir = new File(node1AssetsDir, connectorId);
+ assertTrue(node1ConnectorDir.exists());
+
+ final File node2Dir = getNiFiInstance().getNodeInstance(2).getInstanceDirectory();
+ final File node2AssetsDir = new File(node2Dir, "connector-assets");
+ final File node2ConnectorDir = new File(node2AssetsDir, connectorId);
+ assertTrue(node2ConnectorDir.exists());
+
+ final File[] node1AssetIdDirs = node1ConnectorDir.listFiles();
+ assertNotNull(node1AssetIdDirs);
+ assertEquals(1, node1AssetIdDirs.length);
+
+ final File[] node2AssetIdDirs = node2ConnectorDir.listFiles();
+ assertNotNull(node2AssetIdDirs);
+ assertEquals(1, node2AssetIdDirs.length);
+
+ // Stop node 2 and delete its connector-assets directory
+ disconnectNode(2);
+ getNiFiInstance().getNodeInstance(2).stop();
+
+ FileUtils.deleteFilesInDir(node2AssetsDir, (dir, name) -> true, null, true, true);
+ assertTrue(node2AssetsDir.delete());
+ assertFalse(node2AssetsDir.exists());
+
+ // Start node 2 again and wait for it to rejoin the cluster
+ getNiFiInstance().getNodeInstance(2).start(true);
+ reconnectNode(2);
+ waitForAllNodesConnected();
+
+ // Verify node 2 connector assets directory is recreated and contains the expected asset
+ assertTrue(node2AssetsDir.exists());
+ assertTrue(node2ConnectorDir.exists());
+
+ final File[] node2AssetIdDirsAfterRestart = node2ConnectorDir.listFiles();
+ assertNotNull(node2AssetIdDirsAfterRestart);
+ assertEquals(1, node2AssetIdDirsAfterRestart.length);
+ assertEquals(uploadedAssetId, node2AssetIdDirsAfterRestart[0].getName());
+
+ // Verify that the Asset is still returned from the Connector's Assets list
+ final AssetsEntity assetsAfterRestart = connectorClient.getAssets(connectorId);
+ assertNotNull(assetsAfterRestart);
+ assertNotNull(assetsAfterRestart.getAssets());
+
+ final boolean assetStillPresent = assetsAfterRestart.getAssets().stream()
+ .filter(a -> a.getAsset() != null)
+ .anyMatch(a -> uploadedAssetId.equals(a.getAsset().getId()));
+
+ assertTrue(assetStillPresent);
+
+ connectorClient.deleteConnector(connector);
+ }
+}
+
+
diff --git a/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/ConnectorAssetsIT.java b/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/ConnectorAssetsIT.java
new file mode 100644
index 0000000000..59b46ddd82
--- /dev/null
+++ b/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/ConnectorAssetsIT.java
@@ -0,0 +1,202 @@
+/*
+ * 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.tests.system.connectors;
+
+import org.apache.nifi.tests.system.NiFiSystemIT;
+import org.apache.nifi.toolkit.client.ConnectorClient;
+import org.apache.nifi.toolkit.client.NiFiClientException;
+import org.apache.nifi.web.api.dto.AssetReferenceDTO;
+import org.apache.nifi.web.api.dto.ConfigurationStepConfigurationDTO;
+import org.apache.nifi.web.api.dto.ConnectorConfigurationDTO;
+import org.apache.nifi.web.api.dto.ConnectorValueReferenceDTO;
+import org.apache.nifi.web.api.dto.PropertyGroupConfigurationDTO;
+import org.apache.nifi.web.api.entity.AssetEntity;
+import org.apache.nifi.web.api.entity.AssetsEntity;
+import org.apache.nifi.web.api.entity.ConfigurationStepEntity;
+import org.apache.nifi.web.api.entity.ConnectorEntity;
+import org.junit.jupiter.api.Test;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+public class ConnectorAssetsIT extends NiFiSystemIT {
+
+ @Test
+ public void testCreateConnectorAndUploadAsset() throws NiFiClientException, IOException, InterruptedException {
+ // Create a Connector instance using the AssetConnector test extension
+ final ConnectorEntity connector = getClientUtil().createConnector("AssetConnector");
+ assertNotNull(connector);
+ assertNotNull(connector.getId());
+
+ final String connectorId = connector.getId();
+
+ // Upload an Asset to the Connector
+ final File assetFile = new File("src/test/resources/sample-assets/helloworld.txt");
+ final ConnectorClient connectorClient = getNifiClient().getConnectorClient();
+ final AssetEntity assetEntity = connectorClient.createAsset(connectorId, assetFile.getName(), assetFile);
+
+ assertNotNull(assetEntity);
+ assertNotNull(assetEntity.getAsset());
+ assertNotNull(assetEntity.getAsset().getId());
+ assertEquals(assetFile.getName(), assetEntity.getAsset().getName());
+
+ // List the Connector's Assets and verify that the uploaded Asset is present
+ final AssetsEntity assetsEntity = connectorClient.getAssets(connectorId);
+ assertNotNull(assetsEntity);
+ assertNotNull(assetsEntity.getAssets());
+ assertFalse(assetsEntity.getAssets().isEmpty());
+
+ final String uploadedAssetId = assetEntity.getAsset().getId();
+ final boolean assetFound = assetsEntity.getAssets().stream()
+ .filter(a -> a.getAsset() != null)
+ .anyMatch(a -> uploadedAssetId.equals(a.getAsset().getId()));
+
+ assertTrue(assetFound);
+
+ // Update the configuration step to reference the uploaded Asset in the Test Asset property
+ final String configurationStepName = "Asset Configuration";
+ final String propertyGroupName = "Asset Configuration";
+ final String propertyName = "Test Asset";
+
+ final ConfigurationStepEntity configurationStepEntity = connectorClient.getConfigurationStep(connectorId, configurationStepName);
+ assertNotNull(configurationStepEntity);
+ assertNotNull(configurationStepEntity.getConfigurationStep());
+
+ final ConfigurationStepConfigurationDTO configurationStepConfiguration = configurationStepEntity.getConfigurationStep();
+ assertNotNull(configurationStepConfiguration.getPropertyGroupConfigurations());
+ assertFalse(configurationStepConfiguration.getPropertyGroupConfigurations().isEmpty());
+
+ PropertyGroupConfigurationDTO assetConfigurationGroup = null;
+ for (final PropertyGroupConfigurationDTO group : configurationStepConfiguration.getPropertyGroupConfigurations()) {
+ if (propertyGroupName.equals(group.getPropertyGroupName())) {
+ assetConfigurationGroup = group;
+ break;
+ }
+ }
+ assertNotNull(assetConfigurationGroup);
+
+ Map<String, ConnectorValueReferenceDTO> propertyValues = assetConfigurationGroup.getPropertyValues();
+ if (propertyValues == null) {
+ propertyValues = new HashMap<>();
+ assetConfigurationGroup.setPropertyValues(propertyValues);
+ }
+
+ final ConnectorValueReferenceDTO assetValueReference = new ConnectorValueReferenceDTO();
+ assetValueReference.setValueType("ASSET_REFERENCE");
+
+ final AssetReferenceDTO assetReferenceDTO = new AssetReferenceDTO(uploadedAssetId);
+ assetValueReference.setAssetReferences(List.of(assetReferenceDTO));
+
+ propertyValues.put(propertyName, assetValueReference);
+
+ final ConfigurationStepEntity updatedConfigurationStepEntity = connectorClient.updateConfigurationStep(configurationStepEntity);
+ assertNotNull(updatedConfigurationStepEntity);
+
+ // Retrieve the Connector configuration and verify that the Test Asset property has the Asset reference set
+ final ConnectorEntity connectorWithConfiguration = connectorClient.getConnector(connectorId);
+ assertNotNull(connectorWithConfiguration);
+ assertNotNull(connectorWithConfiguration.getComponent());
+
+ final ConnectorConfigurationDTO workingConfiguration = connectorWithConfiguration.getComponent().getWorkingConfiguration();
+ assertNotNull(workingConfiguration);
+ assertNotNull(workingConfiguration.getConfigurationStepConfigurations());
+ assertFalse(workingConfiguration.getConfigurationStepConfigurations().isEmpty());
+
+ ConfigurationStepConfigurationDTO configuredStep = null;
+ for (final ConfigurationStepConfigurationDTO stepConfiguration : workingConfiguration.getConfigurationStepConfigurations()) {
+ if (configurationStepName.equals(stepConfiguration.getConfigurationStepName())) {
+ configuredStep = stepConfiguration;
+ break;
+ }
+ }
+ assertNotNull(configuredStep);
+ assertNotNull(configuredStep.getPropertyGroupConfigurations());
+ assertFalse(configuredStep.getPropertyGroupConfigurations().isEmpty());
+
+ PropertyGroupConfigurationDTO configuredAssetGroup = null;
+ for (final PropertyGroupConfigurationDTO group : configuredStep.getPropertyGroupConfigurations()) {
+ if (propertyGroupName.equals(group.getPropertyGroupName())) {
+ configuredAssetGroup = group;
+ break;
+ }
+ }
+ assertNotNull(configuredAssetGroup);
+ assertNotNull(configuredAssetGroup.getPropertyValues());
+
+ final ConnectorValueReferenceDTO configuredAssetValue = configuredAssetGroup.getPropertyValues().get(propertyName);
+ assertNotNull(configuredAssetValue);
+ assertEquals("ASSET_REFERENCE", configuredAssetValue.getValueType());
+ assertNotNull(configuredAssetValue.getAssetReferences());
+ assertFalse(configuredAssetValue.getAssetReferences().isEmpty());
+ assertEquals(uploadedAssetId, configuredAssetValue.getAssetReferences().getFirst().getId());
+
+ // Update the configuration step again to remove the Asset reference
+ final ConfigurationStepEntity configurationStepEntityWithoutAsset = connectorClient.getConfigurationStep(connectorId, configurationStepName);
+ assertNotNull(configurationStepEntityWithoutAsset);
+ assertNotNull(configurationStepEntityWithoutAsset.getConfigurationStep());
+
+ final ConfigurationStepConfigurationDTO configurationStepConfigurationWithoutAsset = configurationStepEntityWithoutAsset.getConfigurationStep();
+ assertNotNull(configurationStepConfigurationWithoutAsset.getPropertyGroupConfigurations());
+
+ PropertyGroupConfigurationDTO groupWithoutAsset = null;
+ for (final PropertyGroupConfigurationDTO group : configurationStepConfigurationWithoutAsset.getPropertyGroupConfigurations()) {
+ if (propertyGroupName.equals(group.getPropertyGroupName())) {
+ groupWithoutAsset = group;
+ break;
+ }
+ }
+ assertNotNull(groupWithoutAsset);
+
+ configuredAssetValue.setAssetReferences(null);
+ final Map<String, ConnectorValueReferenceDTO> propertyValuesWithoutAsset = groupWithoutAsset.getPropertyValues();
+ propertyValuesWithoutAsset.put(propertyName, configuredAssetValue);
+
+ final ConfigurationStepEntity configurationStepEntityAfterRemoval = connectorClient.updateConfigurationStep(configurationStepEntityWithoutAsset);
+ assertNotNull(configurationStepEntityAfterRemoval);
+
+ // Apply the connector update so that unreferenced assets are cleaned up based on the active configuration
+ final ConnectorEntity connectorBeforeApply = connectorClient.getConnector(connectorId);
+ assertNotNull(connectorBeforeApply);
+ connectorBeforeApply.setDisconnectedNodeAcknowledged(true);
+
+ final ConnectorEntity connectorAfterApply = connectorClient.applyUpdate(connectorBeforeApply);
+ assertNotNull(connectorAfterApply);
+
+ // Verify that the Asset has been removed from the Connector's Assets list
+ final AssetsEntity assetsAfterRemoval = connectorClient.getAssets(connectorId);
+ assertNotNull(assetsAfterRemoval);
+
+ final boolean assetStillPresent = assetsAfterRemoval.getAssets() != null && assetsAfterRemoval.getAssets().stream()
+ .filter(a -> a.getAsset() != null)
+ .anyMatch(a -> uploadedAssetId.equals(a.getAsset().getId()));
+
+ assertFalse(assetStillPresent);
+
+ connectorClient.deleteConnector(connectorAfterApply);
+ }
+}
+
+
diff --git a/nifi-toolkit/nifi-toolkit-client/src/main/java/org/apache/nifi/toolkit/client/ConnectorClient.java b/nifi-toolkit/nifi-toolkit-client/src/main/java/org/apache/nifi/toolkit/client/ConnectorClient.java
index 504558232e..923604ba5f 100644
--- a/nifi-toolkit/nifi-toolkit-client/src/main/java/org/apache/nifi/toolkit/client/ConnectorClient.java
+++ b/nifi-toolkit/nifi-toolkit-client/src/main/java/org/apache/nifi/toolkit/client/ConnectorClient.java
@@ -16,6 +16,8 @@
*/
package org.apache.nifi.toolkit.client;
+import org.apache.nifi.web.api.entity.AssetEntity;
+import org.apache.nifi.web.api.entity.AssetsEntity;
import org.apache.nifi.web.api.entity.ConfigurationStepEntity;
import org.apache.nifi.web.api.entity.ConfigurationStepNamesEntity;
import org.apache.nifi.web.api.entity.ConnectorEntity;
@@ -24,7 +26,9 @@ import org.apache.nifi.web.api.entity.ProcessGroupFlowEntity;
import org.apache.nifi.web.api.entity.ProcessGroupStatusEntity;
import org.apache.nifi.web.api.entity.VerifyConnectorConfigStepRequestEntity;
+import java.io.File;
import java.io.IOException;
+import java.nio.file.Path;
/**
* Client for interacting with the Connector REST endpoints.
@@ -251,6 +255,40 @@ public interface ConnectorClient {
*/
ProcessGroupStatusEntity getStatus(String connectorId, boolean recursive) throws NiFiClientException, IOException;
+ /**
+ * Creates an asset in the given connector.
+ *
+ * @param connectorId the connector ID
+ * @param assetName the asset name
+ * @param file the file
+ * @return the created asset entity
+ * @throws NiFiClientException if an error occurs during the request
+ * @throws IOException if an I/O error occurs
+ */
+ AssetEntity createAsset(String connectorId, String assetName, File file) throws NiFiClientException, IOException;
+
+ /**
+ * Lists the assets for the given connector.
+ *
+ * @param connectorId the connector ID
+ * @return the list of asset entities
+ * @throws NiFiClientException if an error occurs during the request
+ * @throws IOException if an I/O error occurs
+ */
+ AssetsEntity getAssets(String connectorId) throws NiFiClientException, IOException;
+
+ /**
+ * Retrieves the content of the given asset.
+ *
+ * @param connectorId the connector ID
+ * @param assetId the asset ID
+ * @param outputDirectory the directory to write the asset content
+ * @return the path to the asset content
+ * @throws NiFiClientException if an error occurs during the request
+ * @throws IOException if an I/O error occurs
+ */
+ Path getAssetContent(String connectorId, String assetId, File outputDirectory) throws NiFiClientException, IOException;
+
/**
* Indicates that mutable requests should indicate that the client has
* acknowledged that the node is disconnected.
@@ -258,3 +296,4 @@ public interface ConnectorClient {
void acknowledgeDisconnectedNode();
}
+
diff --git a/nifi-toolkit/nifi-toolkit-client/src/main/java/org/apache/nifi/toolkit/client/impl/JerseyConnectorClient.java b/nifi-toolkit/nifi-toolkit-client/src/main/java/org/apache/nifi/toolkit/client/impl/JerseyConnectorClient.java
index 0c184aa125..8df19b09d5 100644
--- a/nifi-toolkit/nifi-toolkit-client/src/main/java/org/apache/nifi/toolkit/client/impl/JerseyConnectorClient.java
+++ b/nifi-toolkit/nifi-toolkit-client/src/main/java/org/apache/nifi/toolkit/client/impl/JerseyConnectorClient.java
@@ -19,11 +19,14 @@ package org.apache.nifi.toolkit.client.impl;
import jakarta.ws.rs.client.Entity;
import jakarta.ws.rs.client.WebTarget;
import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
import org.apache.commons.lang3.StringUtils;
import org.apache.nifi.toolkit.client.ConnectorClient;
import org.apache.nifi.toolkit.client.NiFiClientException;
import org.apache.nifi.toolkit.client.RequestConfig;
import org.apache.nifi.web.api.dto.RevisionDTO;
+import org.apache.nifi.web.api.entity.AssetEntity;
+import org.apache.nifi.web.api.entity.AssetsEntity;
import org.apache.nifi.web.api.entity.ConfigurationStepEntity;
import org.apache.nifi.web.api.entity.ConfigurationStepNamesEntity;
import org.apache.nifi.web.api.entity.ConnectorEntity;
@@ -33,8 +36,15 @@ import org.apache.nifi.web.api.entity.ProcessGroupFlowEntity;
import org.apache.nifi.web.api.entity.ProcessGroupStatusEntity;
import org.apache.nifi.web.api.entity.VerifyConnectorConfigStepRequestEntity;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Objects;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardCopyOption;
/**
* Jersey implementation of ConnectorClient.
@@ -326,6 +336,9 @@ public class JerseyConnectorClient extends AbstractJerseyClient implements Conne
if (connectorEntity == null) {
throw new IllegalArgumentException("Connector entity cannot be null");
}
+ if (StringUtils.isBlank(connectorEntity.getId())) {
+ throw new IllegalArgumentException("Connector id cannot be null or blank");
+ }
if (connectorEntity.getRevision() == null) {
throw new IllegalArgumentException("Revision cannot be null");
}
@@ -384,4 +397,77 @@ public class JerseyConnectorClient extends AbstractJerseyClient implements Conne
return getRequestBuilder(target).get(ProcessGroupStatusEntity.class);
});
}
+
+ @Override
+ public AssetEntity createAsset(final String connectorId, final String assetName, final File file) throws NiFiClientException, IOException {
+ if (StringUtils.isBlank(connectorId)) {
+ throw new IllegalArgumentException("Connector id cannot be null or blank");
+ }
+ if (StringUtils.isBlank(assetName)) {
+ throw new IllegalArgumentException("Asset name cannot be null or blank");
+ }
+ if (file == null) {
+ throw new IllegalArgumentException("File cannot be null");
+ }
+ if (!file.exists()) {
+ throw new FileNotFoundException(file.getAbsolutePath());
+ }
+
+ try (final InputStream assetInputStream = new FileInputStream(file)) {
+ return executeAction("Error creating Connector Asset " + assetName + " for Connector " + connectorId, () -> {
+ final WebTarget target = connectorsTarget
+ .path("{id}/assets")
+ .resolveTemplate("id", connectorId);
+
+ return getRequestBuilder(target)
+ .header("Filename", assetName)
+ .post(
+ Entity.entity(assetInputStream, MediaType.APPLICATION_OCTET_STREAM_TYPE),
+ AssetEntity.class);
+ });
+ }
+ }
+
+ @Override
+ public AssetsEntity getAssets(final String connectorId) throws NiFiClientException, IOException {
+ if (StringUtils.isBlank(connectorId)) {
+ throw new IllegalArgumentException("Connector id cannot be null or blank");
+ }
+
+ return executeAction("Error retrieving Connector assets", () -> {
+ final WebTarget target = connectorsTarget
+ .path("{id}/assets")
+ .resolveTemplate("id", connectorId);
+ return getRequestBuilder(target).get(AssetsEntity.class);
+ });
+ }
+
+ @Override
+ public Path getAssetContent(final String connectorId, final String assetId, final File outputDirectory) throws NiFiClientException, IOException {
+ if (StringUtils.isBlank(connectorId)) {
+ throw new IllegalArgumentException("Connector id cannot be null or blank");
+ }
+ if (StringUtils.isBlank(assetId)) {
+ throw new IllegalArgumentException("Asset id cannot be null or blank");
+ }
+
+ return executeAction("Error getting Connector asset content", () -> {
+ final WebTarget target = connectorsTarget
+ .path("{id}/assets/{assetId}")
+ .resolveTemplate("id", connectorId)
+ .resolveTemplate("assetId", assetId);
+
+ final Response response = getRequestBuilder(target)
+ .accept(MediaType.APPLICATION_OCTET_STREAM_TYPE)
+ .get();
+
+ final String filename = getContentDispositionFilename(response);
+ final File assetFile = new File(outputDirectory, filename);
+
+ try (final InputStream responseInputStream = response.readEntity(InputStream.class)) {
+ Files.copy(responseInputStream, assetFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
+ return assetFile.toPath();
+ }
+ });
+ }
}
diff --git a/nifi-toolkit/nifi-toolkit-client/src/main/java/org/apache/nifi/toolkit/client/impl/JerseyNiFiClient.java b/nifi-toolkit/nifi-toolkit-client/src/main/java/org/apache/nifi/toolkit/client/impl/JerseyNiFiClient.java
index 1fcc29a738..8477a14495 100644
--- a/nifi-toolkit/nifi-toolkit-client/src/main/java/org/apache/nifi/toolkit/client/impl/JerseyNiFiClient.java
+++ b/nifi-toolkit/nifi-toolkit-client/src/main/java/org/apache/nifi/toolkit/client/impl/JerseyNiFiClient.java
@@ -363,7 +363,7 @@ public class JerseyNiFiClient implements NiFiClient {
JacksonJaxbJsonProvider jacksonJaxbJsonProvider = new JacksonJaxbJsonProvider();
ObjectMapper mapper = new ObjectMapper();
- mapper.setDefaultPropertyInclusion(JsonInclude.Value.construct(JsonInclude.Include.NON_NULL, JsonInclude.Include.NON_NULL));
+ mapper.setDefaultPropertyInclusion(JsonInclude.Value.construct(JsonInclude.Include.NON_NULL, JsonInclude.Include.ALWAYS));
mapper.setAnnotationIntrospector(new JakartaXmlBindAnnotationIntrospector(mapper.getTypeFactory()));
// Ignore unknown properties so that deployed client remain compatible with
// future versions of NiFi that add new fields