aboutsummaryrefslogtreecommitdiffstats
path: root/catalog-be/src/main/java
diff options
context:
space:
mode:
authorMichael Lando <ml636r@att.com>2017-06-09 03:19:04 +0300
committerMichael Lando <ml636r@att.com>2017-06-09 03:19:04 +0300
commited64b5edff15e702493df21aa3230b81593e6133 (patch)
treea4cb01fdaccc34930a8db403a3097c0d1e40914b /catalog-be/src/main/java
parent280f8015d06af1f41a3ef12e8300801c7a5e0d54 (diff)
[SDC-29] catalog 1707 rebase commit.
Change-Id: I43c3dc5cf44abf5da817649bc738938a3e8388c1 Signed-off-by: Michael Lando <ml636r@att.com>
Diffstat (limited to 'catalog-be/src/main/java')
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditingLogFormatConstants.java50
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditingLogFormatUtil.java25
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/CambriaHandler.java192
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngine.java22
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineClusterHealth.java9
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionNotificationSender.java10
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/JsonContainerResourceInstance.java37
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/PublishNotificationRunnable.java4
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ServiceDistributionArtifactsBuilder.java137
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/TestQueue.java4
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/VfModuleArtifactPayload.java65
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AdditionalInformationBusinessLogic.java14
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactsBusinessLogic.java2267
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AttributeBusinessLogic.java53
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/BaseBusinessLogic.java504
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CategoriesImportManager.java24
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CommonImportManager.java6
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogic.java724
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogic.java1416
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CompositionBusinessLogic.java3
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ConsumerBusinessLogic.java6
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CsarValidationUtils.java100
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ElementBusinessLogic.java486
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogic.java1523
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/HealthCheckBusinessLogic.java3
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/IDeploymentArtifactTypeConfigGetter.java4
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ImportUtils.java24
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InformationDeployedArtifactsBusinessLogic.java4
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogic.java1190
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceLifecycleTypeImportManager.java2
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductBusinessLogic.java53
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductComponentInstanceBusinessLogic.java13
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PropertyBusinessLogic.java279
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogic.java2837
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceImportManager.java67
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogic.java509
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceComponentInstanceBusinessLogic.java10
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/VFComponentInstanceBusinessLogic.java11
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CertificationChangeTransition.java75
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CertificationRequestTransition.java180
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CheckinTransition.java67
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CheckoutTransition.java96
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifeCycleTransition.java75
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifecycleBusinessLogic.java404
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/StartCertificationTransition.java64
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/UndoCheckoutTransition.java59
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/api/CategoryTypeEnum.java2
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/UiComponentDataConverter.java218
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/EcompIntImpl.java39
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/EcompRoleConverter.java3
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/EcompUserConverter.java12
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/ArtifactExternalServlet.java307
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/AssetMetadataConverter.java105
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/AssetsDataServlet.java507
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ArtifactMetadata.java20
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ResourceAssetDetailedMetadata.java10
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ResourceInstanceMetadata.java10
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/filters/BasicAuthenticationFilter.java2
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/filters/BeServletFilter.java20
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/impl/ComponentsUtils.java33
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/impl/DownloadArtifactLogic.java9
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactTemplateInfo.java12
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/info/GroupDefinitionInfo.java57
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/info/GroupTemplateInfo.java4
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/info/MergedArtifactInfo.java22
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/listen/BEAppContextListener.java9
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AbstractValidationsServlet.java236
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AdditionalInformationServlet.java12
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ArtifactServlet.java188
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AttributeServlet.java10
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/BeGenericServlet.java58
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/BeMonitoringServlet.java14
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentInstanceServlet.java248
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentServlet.java200
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ConfigServlet.java4
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ConsumerServlet.java2
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/CsarBuildServlet.java142
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ElementServlet.java32
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/GroupServlet.java115
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/InputsServlet.java161
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/LifecycleServlet.java69
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/PropertyServlet.java140
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/RepresentationUtils.java11
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourceArtifactDownloadServlet.java37
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourceUploadServlet.java9
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourcesServlet.java47
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ServiceServlet.java100
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TypesFetchServlet.java5
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TypesUploadServlet.java43
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/UserAdminServlet.java18
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/switchover/detector/SwitchoverDetector.java16
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ArtifactTypes.java1
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CapabiltyRequirementConvertor.java89
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CsarUtils.java1255
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/tosca/PropertyConvertor.java5
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaExportHandler.java593
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaUtils.java4
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/IToscaMetadata.java3
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/SubstitutionMapping.java14
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaMetadata.java36
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTopolgyTemplate.java8
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/VfModuleToscaMetadata.java9
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/user/IUserBusinessLogic.java5
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/user/UserAdminValidator.java3
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/user/UserBusinessLogic.java33
105 files changed, 13501 insertions, 5582 deletions
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditingLogFormatConstants.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditingLogFormatConstants.java
index eb14b5afe7..8ff3fca4f8 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditingLogFormatConstants.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditingLogFormatConstants.java
@@ -20,6 +20,9 @@
package org.openecomp.sdc.be.auditing.impl;
+import org.apache.commons.lang3.StringUtils;
+import org.openecomp.sdc.be.components.impl.ImportUtils;
+import org.openecomp.sdc.be.model.LifecycleStateEnum;
import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
public interface AuditingLogFormatConstants {
@@ -148,7 +151,8 @@ public interface AuditingLogFormatConstants {
AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION,
AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID,
AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE,
- AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE
+ AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE
+
};
static AuditingFieldsKeysEnum[] USER_ACCESS_TEMPLATE_ARRAY = {
@@ -234,9 +238,6 @@ public interface AuditingLogFormatConstants {
AuditingFieldsKeysEnum.AUDIT_DESC
};
static AuditingFieldsKeysEnum[] EXTERNAL_DOWNLOAD_ARTIFACT_ARRAY = {
- AuditingFieldsKeysEnum.AUDIT_ACTION,
- AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME,
- AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE,
AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID,
AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL,
AuditingFieldsKeysEnum.AUDIT_STATUS,
@@ -255,4 +256,45 @@ public interface AuditingLogFormatConstants {
AuditingFieldsKeysEnum.AUDIT_STATUS,
AuditingFieldsKeysEnum.AUDIT_DESC
};
+
+ static AuditingFieldsKeysEnum[] EXTERNAL_CRUD_API_ARRAY = {
+ AuditingFieldsKeysEnum.AUDIT_ACTION,
+ AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME,
+ AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE,
+ AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID,
+ AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL,
+ AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID,
+
+ AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION,
+ AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION,
+ AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE,
+ AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE,
+
+ AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID,
+ AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID,
+ AuditingFieldsKeysEnum.AUDIT_STATUS,
+ AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID,
+ AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID,
+ AuditingFieldsKeysEnum.AUDIT_DESC
+ };
+
+ static AuditingFieldsKeysEnum[] EXTERNAL_LYFECYCLE_API_ARRAY = {
+ AuditingFieldsKeysEnum.AUDIT_ACTION,
+ AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME,
+ AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE,
+ AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID,
+ AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL,
+ AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME,
+ AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID,
+
+ AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION,
+ AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION,
+ AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE,
+ AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE,
+
+ AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID,
+ AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID,
+ AuditingFieldsKeysEnum.AUDIT_STATUS,
+ AuditingFieldsKeysEnum.AUDIT_DESC
+ };
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditingLogFormatUtil.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditingLogFormatUtil.java
index 5fec39bbdb..b965516df8 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditingLogFormatUtil.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditingLogFormatUtil.java
@@ -24,7 +24,9 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.EnumMap;
import java.util.Formatter;
+import java.util.HashSet;
import java.util.Locale;
+import java.util.Set;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
import org.openecomp.sdc.common.api.Constants;
@@ -43,7 +45,7 @@ public class AuditingLogFormatUtil {
// This is the key by which audit marker is recognized in logback.xml
private static String AUDIT_MARKER_STR = "AUDIT_MARKER";
- public static Marker auditMarker = MarkerFactory.getMarker(AUDIT_MARKER_STR);
+ public static final Marker auditMarker = MarkerFactory.getMarker(AUDIT_MARKER_STR);
protected static void logAuditEvent(EnumMap<AuditingFieldsKeysEnum, Object> auditingFields) {
@@ -77,7 +79,7 @@ public class AuditingLogFormatUtil {
log.info(auditMarker, formattedString);
}
} catch (Exception e) {
- log.debug("unexpected error occurred: {} {}", e.getMessage(), e);
+ log.debug("unexpected error occurred: {}", e.getMessage(), e);
} finally {
formatter.close();
@@ -144,14 +146,13 @@ public class AuditingLogFormatUtil {
case ARTIFACT_METADATA_UPDATE:
case ARTIFACT_PAYLOAD_UPDATE:
case ARTIFACT_DOWNLOAD:
- ArrayList<AuditingFieldsKeysEnum> artifactFieldsList = new ArrayList(Arrays.asList(AuditingLogFormatConstants.CREATE_RESOURCE_TEMPLATE_PREFIX_ARRAY));
- artifactFieldsList.add(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID);
- artifactFieldsList.add(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID);
- artifactFieldsList.add(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA);
- artifactFieldsList.addAll(Arrays.asList(AuditingLogFormatConstants.CREATE_RESOURCE_TEMPLATE_SUFFIX_ARRAY));
- artifactFieldsList.addAll(Arrays.asList(AuditingLogFormatConstants.EXTERNAL_DOWNLOAD_ARTIFACT_ARRAY));
+ ArrayList<AuditingFieldsKeysEnum> artifactFieldsSet = new ArrayList<>(Arrays.asList(AuditingLogFormatConstants.CREATE_RESOURCE_TEMPLATE_PREFIX_ARRAY)) ;
+ artifactFieldsSet.add(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID);
+ artifactFieldsSet.add(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID);
+ artifactFieldsSet.add(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA);
+ artifactFieldsSet.addAll(Arrays.asList(AuditingLogFormatConstants.EXTERNAL_DOWNLOAD_ARTIFACT_ARRAY));
AuditingFieldsKeysEnum[] artifactFieldsArray = new AuditingFieldsKeysEnum[100];
- artifactFieldsArray = artifactFieldsList.toArray(artifactFieldsArray);
+ artifactFieldsArray = artifactFieldsSet.toArray(artifactFieldsArray);
formattedString = buildStringAccrodingToArray(artifactFieldsArray, auditingFields);
break;
case DOWNLOAD_ARTIFACT:
@@ -225,6 +226,12 @@ public class AuditingLogFormatUtil {
artifactFieldsArray = uploadArtifactFieldsList.toArray(uploadArtifactFieldsArray);
formattedString = buildStringAccrodingToArray(artifactFieldsArray, auditingFields);
break;
+ case CREATE_RESOURCE_BY_API:
+ formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.EXTERNAL_CRUD_API_ARRAY, auditingFields);
+ break;
+ case CHANGE_LIFECYCLE_BY_API:
+ formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.EXTERNAL_LYFECYCLE_API_ARRAY, auditingFields);
+ break;
default:
break;
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/CambriaHandler.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/CambriaHandler.java
index 3528ed9be3..6738b87853 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/CambriaHandler.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/CambriaHandler.java
@@ -21,7 +21,6 @@
package org.openecomp.sdc.be.components.distribution.engine;
import java.io.IOException;
-import java.net.MalformedURLException;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Collection;
@@ -54,6 +53,7 @@ import com.att.nsa.cambria.client.CambriaTopicManager;
import com.google.gson.Gson;
import fj.data.Either;
+import jline.internal.Log;
public class CambriaHandler {
@@ -63,6 +63,169 @@ public class CambriaHandler {
private Gson gson = new Gson();
+ public static void main(String[] args) {
+
+ // String userBodyJson ="{\"artifactName\":\"myartifact\",
+ // \"artifactType\":\"MURANO-PKG\",
+ // \"artifactDescription\":\"description\",
+ // \"payloadData\":\"UEsDBAoAAAAIAAeLb0bDQz\", \"Content-MD5\":
+ // \"YTg2Mjg4MWJhNmI5NzBiNzdDFkMWI=\" }";
+ // System.out.println(userBodyJson);
+ // String encodeBase64Str = GeneralUtililty.calculateMD5 (userBodyJson);
+ // System.out.println(encodeBase64Str);
+
+ CambriaTopicManager createTopicManager = null;
+ try {
+ List<String> servers = new ArrayList<String>();
+ // servers.add("uebsb91kcdc.it.sdc.com:3904");
+ // servers.add("uebsb92kcdc.it.sdc.com:3904");
+ // servers.add("uebsb93kcdc.it.sdc.com:3904");
+ servers.add("uebsb91sfdc.it.att.com:3904");
+ servers.add("uebsb92sfdc.it.att.com:3904");
+
+ String key = "sSJc5qiBnKy2qrlc";
+ String secret = "4ZRPzNJfEUK0sSNBvccd2m7X";
+
+ createTopicManager = new TopicManagerBuilder().usingHttps().usingHosts(servers).authenticatedBy(key, secret).build();
+
+ String topicName = "ASDC-DISTR-NOTIF-TOPIC-PRODesofer";
+
+ String clientKey1 = "CGGoorrGPXPx2B1C";
+ String clientSecret1 = "OTHk2mcCSbskEtHhDw8h5oUa";
+
+ CambriaTopicManager createStatusTopicManager = new TopicManagerBuilder().usingHttps().usingHosts(servers).authenticatedBy(key, secret).build();
+ String reportTopic = "ASDC-DISTR-STATUS-TOPIC-PRODESOFER";
+ createStatusTopicManager.allowProducer(reportTopic, clientKey1);
+
+ CambriaBatchingPublisher createSimplePublisher = new PublisherBuilder().onTopic(reportTopic).usingHttps().usingHosts(servers).build();
+ createSimplePublisher.setApiCredentials(clientKey1, clientSecret1);
+
+ DistributionStatusNotification distributionStatusNotification = new DistributionStatusNotification();
+ distributionStatusNotification.setStatus(DistributionStatusNotificationEnum.DEPLOY_OK);
+ distributionStatusNotification.setArtifactURL("Ssssssss url");
+ distributionStatusNotification.setDistributionID("idddddddddddddd");
+ distributionStatusNotification.setTimestamp(System.currentTimeMillis());
+ distributionStatusNotification.setConsumerID("my consumer id");
+
+ Gson gson = new Gson();
+ int result = createSimplePublisher.send(PARTITION_KEY, gson.toJson(distributionStatusNotification));
+
+ List<message> messagesInQ = createSimplePublisher.close(20, TimeUnit.SECONDS);
+ System.out.println(messagesInQ == null ? 0 : messagesInQ.size());
+
+ // createTopicManager.createTopic(topicName, "my test topic", 1, 1);
+
+ /*
+ *
+ * { "secret": "OTHk2mcCSbskEtHhDw8h5oUa", "aux": { "email": "esofer@intl.sdc.com", "description": "test-keys" }, "key": "CGGoorrGPXPx2B1C" }
+ *
+ *
+ * { "secret": "FSlNJbmGWWBvBLJetQMYxPP6", "aux": { "email": "esofer@intl.sdc.com", "description": "test-keys" }, "key": "TAIEPO0aDU4VzM0G" }
+ *
+ */
+
+ String clientKey2 = "TAIEPO0aDU4VzM0G";
+
+ CambriaConsumer createConsumer1 = new ConsumerBuilder().authenticatedBy("asdc1", "consumerId1").onTopic(topicName).usingHttps().usingHosts(servers).build();
+ createConsumer1.setApiCredentials(clientKey1, "OTHk2mcCSbskEtHhDw8h5oUa");
+
+ createTopicManager.allowConsumer(topicName, clientKey1);
+
+ CambriaConsumer createConsumer2 = null;
+ if (true) {
+ createConsumer2 = new ConsumerBuilder().authenticatedBy("asdc2", "consumerId3").onTopic(topicName).usingHttps().usingHosts(servers).build();
+ createConsumer2.setApiCredentials(clientKey2, "FSlNJbmGWWBvBLJetQMYxPP6");
+
+ createTopicManager.allowConsumer(topicName, clientKey2);
+ }
+
+ createSimplePublisher = new PublisherBuilder().onTopic(topicName).usingHttps().usingHosts(servers).build();
+ createSimplePublisher.setApiCredentials(key, secret);
+ createTopicManager.allowProducer(topicName, key);
+
+ createSimplePublisher.send("aaaa", "{ my testttttttttttttttt }");
+
+ while (true) {
+
+ Iterable<String> fetch1 = createConsumer1.fetch();
+
+ Iterator<String> iterator1 = fetch1.iterator();
+ while (iterator1.hasNext()) {
+ System.out.println("***********************************************");
+ System.out.println("client 1" + iterator1.next());
+ System.out.println("***********************************************");
+ }
+
+ if (createConsumer2 != null) {
+ Iterable<String> fetch2 = createConsumer2.fetch();
+
+ Iterator<String> iterator2 = fetch2.iterator();
+ while (iterator2.hasNext()) {
+ System.out.println("***********************************************");
+ System.out.println("client 2" + iterator2.next());
+ System.out.println("***********************************************");
+ }
+ }
+ Thread.sleep(1000 * 20);
+ }
+
+ // createTopicManager = CambriaClientFactory.createTopicManager(
+ // servers, "8F3MDAtMSBwwpSMy", "gzFmsTxSCtO5RQfAccM6PqqX");
+
+ // createTopicManager.deleteTopic("ASDC-DISTR-NOTIF-TOPIC-PROD");
+ // createTopicManager.deleteTopic("ASDC-DISTR-NOTIF-TOPIC-PROD1");
+
+ // CambriaIdentityManager createIdentityManager =
+ // CambriaClientFactory.createIdentityManager(null, null, null);
+ // createIdentityManager.setApiCredentials(arg0, arg1);
+ // createIdentityManager.cl
+
+ // String topicName = " ";
+ // createTopicManager.createTopic(topicName,
+ // "ASDC distribution notification topic", 1, 1);
+ //
+ // Thread.sleep(10 * 1000);
+ //
+ // for (int i = 0; i < 5; i++) {
+ // try {
+ // boolean openForProducing = createTopicManager
+ // .isOpenForProducing(topicName);
+ //
+ // System.out.println("openForProducing=" + openForProducing);
+ // createTopicManager.allowProducer(topicName,
+ // "8F3MDAtMSBwwpSMy");
+ // Set<String> allowedProducers = createTopicManager
+ // .getAllowedProducers(topicName);
+ // System.out.println(allowedProducers);
+ //
+ // } catch (Exception e) {
+ // e.printStackTrace();
+ // }
+ // }
+
+ // createTopicManager.createTopic("", "", 0, 0);
+ // createTopicManager.allowProducer(arg0, arg1);
+ // createTopicManager.getTopics();
+ // createTopicManager.close();
+ // CambriaClientFactory.
+ // CambriaBatchingPublisher createSimplePublisher =
+ // CambriaClientFactory.createSimplePublisher("hostlist", "topic");
+
+ // CambriaIdentityManager createIdentityManager =
+ // CambriaClientFactory.createIdentityManager(null, "apiKey",
+ // "apiSecret");
+ // createIdentityManager.
+
+ } catch (Exception e) {
+ Log.debug("Exception in main test of Cambria Handler: {}", e.getMessage(), e);
+ e.printStackTrace();
+ } finally {
+ if (createTopicManager != null) {
+ createTopicManager.close();
+ }
+ }
+ }
+
/**
* process the response error from Cambria client
*
@@ -121,7 +284,8 @@ public class CambriaHandler {
CambriaTopicManager createTopicManager = null;
try {
- createTopicManager = new TopicManagerBuilder().usingHosts(hostSet).build();
+ createTopicManager = new TopicManagerBuilder().usingHttps().usingHosts(hostSet).build();
+
Set<String> topics = createTopicManager.getTopics();
if (topics == null || true == topics.isEmpty()) {
@@ -263,10 +427,13 @@ public class CambriaHandler {
CambriaTopicManager createTopicManager = null;
try {
- createTopicManager = new TopicManagerBuilder().usingHosts(hostSet).authenticatedBy(apiKey, secretKey).build();
+
+ createTopicManager = new TopicManagerBuilder().usingHttps().usingHosts(hostSet).authenticatedBy(apiKey, secretKey).build();
+
createTopicManager.createTopic(topicName, "ASDC distribution notification topic", partitionCount, replicationCount);
- } catch (GeneralSecurityException | HttpException | IOException e) {
+ } catch (HttpException | IOException | GeneralSecurityException e) {
+
logger.debug("Failed to create topic {}", topicName, e);
String methodName = new Object() {
}.getClass().getEnclosingMethod().getName();
@@ -285,12 +452,13 @@ public class CambriaHandler {
}
}
return new CambriaErrorResponse(CambriaOperationStatus.OK);
+
}
public CambriaErrorResponse unRegisterFromTopic(Collection<String> hostSet, String topicName, String managerApiKey, String managerSecretKey, String subscriberApiKey, SubscriberTypeEnum subscriberTypeEnum) {
CambriaTopicManager createTopicManager = null;
try {
- createTopicManager = new TopicManagerBuilder().usingHosts(hostSet).authenticatedBy(managerApiKey, managerSecretKey).build();
+ createTopicManager = new TopicManagerBuilder().usingHttps().usingHosts(hostSet).authenticatedBy(managerApiKey, managerSecretKey).build();
if (subscriberTypeEnum == SubscriberTypeEnum.PRODUCER) {
createTopicManager.revokeProducer(topicName, subscriberApiKey);
@@ -345,7 +513,7 @@ public class CambriaHandler {
CambriaTopicManager createTopicManager = null;
try {
- createTopicManager = new TopicManagerBuilder().usingHosts(hostSet).authenticatedBy(managerApiKey, managerSecretKey).build();
+ createTopicManager = new TopicManagerBuilder().usingHttps().usingHosts(hostSet).authenticatedBy(managerApiKey, managerSecretKey).build();
if (subscriberTypeEnum == SubscriberTypeEnum.PRODUCER) {
createTopicManager.allowProducer(topicName, subscriberApiKey);
@@ -395,11 +563,11 @@ public class CambriaHandler {
* @param consumerGroup
* @param timeoutMS
* @return
- * @throws Exception
+ * @throws Exception
*/
public CambriaConsumer createConsumer(Collection<String> hostSet, String topicName, String apiKey, String secretKey, String consumerId, String consumerGroup, int timeoutMS) throws Exception {
- CambriaConsumer consumer = new ConsumerBuilder().authenticatedBy(apiKey, secretKey).knownAs(consumerGroup, consumerId).onTopic(topicName).usingHosts(hostSet).withSocketTimeout(timeoutMS).build();
+ CambriaConsumer consumer = new ConsumerBuilder().authenticatedBy(apiKey, secretKey).knownAs(consumerGroup, consumerId).onTopic(topicName).usingHttps().usingHosts(hostSet).withSocketTimeout(timeoutMS).build();
consumer.setApiCredentials(apiKey, secretKey);
return consumer;
}
@@ -470,7 +638,7 @@ public class CambriaHandler {
String json = gson.toJson(data);
logger.trace("Before sending notification data {} to topic {}", json, topicName);
- createSimplePublisher = new PublisherBuilder().onTopic(topicName).usingHosts(uebServers).build();
+ createSimplePublisher = new PublisherBuilder().onTopic(topicName).usingHttps().usingHosts(uebServers).build();
createSimplePublisher.setApiCredentials(uebPublicKey, uebSecretKey);
int result = createSimplePublisher.send(PARTITION_KEY, json);
@@ -532,7 +700,7 @@ public class CambriaHandler {
String json = gson.toJson(data);
logger.debug("Before sending notification data {} to topic {}", json, topicName);
- createSimplePublisher = new PublisherBuilder().onTopic(topicName).usingHosts(uebServers).build();
+ createSimplePublisher = new PublisherBuilder().onTopic(topicName).usingHttps().usingHosts(uebServers).build();
createSimplePublisher.setApiCredentials(uebPublicKey, uebSecretKey);
int result = createSimplePublisher.send(PARTITION_KEY, json);
@@ -559,7 +727,7 @@ public class CambriaHandler {
}
- logger.debug("Before closing publisher. Maximum timeout is {} seconds.", waitBeforeCloseTimeout);
+ logger.debug("Before closing publisher. Maximum timeout is {} seconds", waitBeforeCloseTimeout);
try {
List<message> messagesInQ = createSimplePublisher.close(waitBeforeCloseTimeout, TimeUnit.SECONDS);
if (messagesInQ != null && false == messagesInQ.isEmpty()) {
@@ -593,7 +761,7 @@ public class CambriaHandler {
hostSet.add(server);
CambriaIdentityManager createIdentityManager = null;
try {
- createIdentityManager = new IdentityManagerBuilder().usingHosts(hostSet).build();
+ createIdentityManager = new IdentityManagerBuilder().usingHttps().usingHosts(hostSet).build();
createIdentityManager.getApiKey(apiKey);
response = new CambriaErrorResponse(CambriaOperationStatus.OK, 200);
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngine.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngine.java
index 6cb31c8cf2..d3d04ea735 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngine.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngine.java
@@ -51,6 +51,22 @@ public class DistributionEngine implements IDistributionEngine {
public static final Pattern FQDN_PATTERN = Pattern.compile("^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])(\\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9]))*(:[0-9]{2,4})*$", Pattern.CASE_INSENSITIVE);
+ public static void main(String[] args) {
+
+ List<String> servers = new ArrayList<>();
+
+ servers.add("uebsb91kcdc.it.att.com:3904");
+ servers.add("uebsb91kcdc.it.att.com:3904");
+ servers.add("uebsb91kcdc.it.att.com:3904");
+
+ YamlToObjectConverter converter = new YamlToObjectConverter();
+ DistributionEngineConfiguration distributionEngineConfiguration = converter.convert("src/test/resources/config/catalog-be/distribEngine1/distribution-engine-configuration.yaml", DistributionEngineConfiguration.class);
+
+ DistributionEngineInitTask distributionEngineInitTask = new DistributionEngineInitTask(2l, distributionEngineConfiguration, "PROD", new AtomicBoolean(false), null, null);
+ distributionEngineInitTask.startTask();
+
+ }
+
@javax.annotation.Resource
private ComponentsUtils componentUtils;
@@ -319,10 +335,8 @@ public class DistributionEngine implements IDistributionEngine {
@Override
public StorageOperationStatus notifyService(String distributionId, Service service, INotificationData notificationData, String envName, String userId, String modifierName) {
-
- if (logger.isDebugEnabled()) {
- logger.debug("Received notify service request. distributionId = {}, serviceUuid = {}, serviceUid = {}, envName = {}, userId = {}, modifierName {}", distributionId, service.getUUID(), service.getUniqueId(), envName, userId, modifierName);
- }
+
+ logger.debug("Received notify service request. distributionId = {}, serviceUuid = {} serviceUid = {}, envName = {}, userId = {}, modifierName {}", distributionId, service.getUUID(), service.getUniqueId(), envName, userId, modifierName);
DistributionEngineConfiguration deConfiguration = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration();
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineClusterHealth.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineClusterHealth.java
index a3d0362c61..1b868951c5 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineClusterHealth.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineClusterHealth.java
@@ -72,10 +72,10 @@ public class DistributionEngineClusterHealth {
public enum HealthCheckInfoResult {
- OK(new HealthCheckInfo(HealthCheckComponent.DE, HealthCheckStatus.UP, null, ClusterStatusDescription.OK.getDescription())), UNAVAILABLE(
- new HealthCheckInfo(HealthCheckComponent.DE, HealthCheckStatus.DOWN, null, ClusterStatusDescription.UNAVAILABLE.getDescription())), NOT_CONFIGURED(
- new HealthCheckInfo(HealthCheckComponent.DE, HealthCheckStatus.DOWN, null, ClusterStatusDescription.NOT_CONFIGURED.getDescription())), DISABLED(
- new HealthCheckInfo(HealthCheckComponent.DE, HealthCheckStatus.DOWN, null, ClusterStatusDescription.DISABLED.getDescription()));
+ OK(new HealthCheckInfo(HealthCheckComponent.DE, HealthCheckStatus.UP, null, ClusterStatusDescription.OK.getDescription())),
+ UNAVAILABLE(new HealthCheckInfo(HealthCheckComponent.DE, HealthCheckStatus.DOWN, null, ClusterStatusDescription.UNAVAILABLE.getDescription())),
+ NOT_CONFIGURED(new HealthCheckInfo(HealthCheckComponent.DE, HealthCheckStatus.DOWN, null, ClusterStatusDescription.NOT_CONFIGURED.getDescription())),
+ DISABLED(new HealthCheckInfo(HealthCheckComponent.DE, HealthCheckStatus.DOWN, null, ClusterStatusDescription.DISABLED.getDescription()));
private HealthCheckInfo healthCheckInfo;
@@ -237,6 +237,7 @@ public class DistributionEngineClusterHealth {
message = e.getClass().getName();
}
healthLogger.debug("Error occured during running Health Check retry query towards UEB server {}. Result is {}", healthCheckCall.getServer(), message);
+ healthLogger.trace("Error occured during running Health Check retry query towards UEB server {}. Result is {}", healthCheckCall.getServer(), message, e);
}
retryNumber++;
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionNotificationSender.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionNotificationSender.java
index 667276db2c..16a0a1dc31 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionNotificationSender.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionNotificationSender.java
@@ -30,10 +30,8 @@ import org.openecomp.sdc.be.config.DistributionEngineConfiguration;
import org.openecomp.sdc.be.config.DistributionEngineConfiguration.DistributionNotificationTopicConfig;
import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.model.Service;
-import org.openecomp.sdc.be.model.operations.api.IServiceOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation;
-import org.openecomp.sdc.be.model.operations.impl.ResourceOperation;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
import org.openecomp.sdc.common.util.ThreadLocalsHolder;
import org.slf4j.Logger;
@@ -47,7 +45,7 @@ public class DistributionNotificationSender {
private static Logger logger = LoggerFactory.getLogger(DistributionNotificationSender.class.getName());
- // final String BASE_ARTIFACT_URL = "/asdc/v1/catalog/services/%s/%s/";
+ // final String BASE_ARTIFACT_URL = "/sdc/v1/catalog/services/%s/%s/";
// final String RESOURCE_ARTIFACT_URL = BASE_ARTIFACT_URL
// + "resources/%s/%s/artifacts/%s";
// final String SERVICE_ARTIFACT_URL = BASE_ARTIFACT_URL + "artifacts/%s";
@@ -56,12 +54,6 @@ public class DistributionNotificationSender {
InterfaceLifecycleOperation interfaceLifecycleOperation;
@javax.annotation.Resource
- protected IServiceOperation serviceOperation;
-
- @javax.annotation.Resource
- protected ResourceOperation resourceOperation;
-
- @javax.annotation.Resource
protected ComponentsUtils componentUtils;
ExecutorService executorService = null;
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/JsonContainerResourceInstance.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/JsonContainerResourceInstance.java
index 25a6f46c90..d1b445b065 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/JsonContainerResourceInstance.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/JsonContainerResourceInstance.java
@@ -25,7 +25,7 @@ import java.util.List;
import org.openecomp.sdc.be.model.ComponentInstance;
public class JsonContainerResourceInstance {
- private String resourceInstanceName, resourceName, resourceVersion, resoucreType, resourceUUID, resourceInvariantUUID;
+ private String resourceInstanceName, resourceName, resourceVersion, resoucreType, resourceUUID, resourceInvariantUUID, resourceCustomizationUUID, category, subcategory;
private List<ArtifactInfoImpl> artifacts;
public JsonContainerResourceInstance(ComponentInstance resourceInstance, String resourceType, List<ArtifactInfoImpl> artifacts) {
@@ -36,17 +36,7 @@ public class JsonContainerResourceInstance {
this.resoucreType = resourceType;
this.resourceUUID = resourceInstance.getComponentUid();
this.artifacts = artifacts;
- }
-
- public JsonContainerResourceInstance(ComponentInstance resourceInstance, String resourceInvariantUUID, String resourceType, List<ArtifactInfoImpl> artifacts) {
- super();
- this.resourceInstanceName = resourceInstance.getName();
- this.resourceName = resourceInstance.getComponentName();
- this.resourceVersion = resourceInstance.getComponentVersion();
- this.resoucreType = resourceType;
- this.resourceUUID = resourceInstance.getComponentUid();
- this.resourceInvariantUUID = resourceInvariantUUID;
- this.artifacts = artifacts;
+ this.resourceCustomizationUUID = resourceInstance.getCustomizationUUID();
}
public String getResourceInstanceName() {
@@ -105,4 +95,27 @@ public class JsonContainerResourceInstance {
this.resourceInvariantUUID = resourceInvariantUUID;
}
+ public String getResourceCustomizationUUID() {
+ return resourceCustomizationUUID;
+ }
+
+ public void setResourceCustomizationUUID(String customizationUUID) {
+ this.resourceCustomizationUUID = customizationUUID;
+ }
+
+ public String getCategory() {
+ return category;
+ }
+
+ public void setCategory(String category) {
+ this.category = category;
+ }
+
+ public String getSubcategory() {
+ return subcategory;
+ }
+
+ public void setSubcategory(String subcategory) {
+ this.subcategory = subcategory;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/PublishNotificationRunnable.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/PublishNotificationRunnable.java
index 362f3948ed..c283ecc92b 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/PublishNotificationRunnable.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/PublishNotificationRunnable.java
@@ -108,13 +108,13 @@ public class PublishNotificationRunnable implements Runnable {
ThreadLocalsHolder.setUuid(this.requestId);
CambriaErrorResponse status = cambriaHandler.sendNotificationAndClose(topicName, deConfiguration.getUebPublicKey(), deConfiguration.getUebSecretKey(), deConfiguration.getUebServers(), data,
- deConfiguration.getDistributionNotificationTopic().getMaxWaitingAfterSendingSeconds().longValue());
+ deConfiguration.getDistributionNotificationTopic().getMaxWaitingAfterSendingSeconds());
logger.info("After publishing service {} of version {}. Status is {}", service.getName(), service.getVersion(), status.getHttpCode());
auditDistributionNotification(topicName, status, service, distributionId, envName, userId, modifierName);
long endTime = System.currentTimeMillis();
- logger.debug("After building and publishing artifacts object. Total took {} milliseconds.", (endTime - startTime));
+ logger.debug("After building and publishing artifacts object. Total took {} milliseconds", (endTime - startTime));
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ServiceDistributionArtifactsBuilder.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ServiceDistributionArtifactsBuilder.java
index 6e67e38c15..90120288bc 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ServiceDistributionArtifactsBuilder.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ServiceDistributionArtifactsBuilder.java
@@ -24,22 +24,27 @@ import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
+import java.util.Optional;
+import java.util.stream.Collectors;
import javax.annotation.PostConstruct;
import org.openecomp.sdc.be.config.ConfigurationManager;
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.model.ArtifactDefinition;
import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.ComponentParametersView;
import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.be.model.category.CategoryDefinition;
+import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
import org.openecomp.sdc.be.model.operations.api.IArtifactOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation;
-import org.openecomp.sdc.be.model.operations.impl.ResourceOperation;
-import org.openecomp.sdc.be.model.operations.impl.ServiceOperation;
+import org.openecomp.sdc.common.api.ArtifactTypeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import fj.data.Either;
@@ -51,47 +56,31 @@ public class ServiceDistributionArtifactsBuilder {
private static Logger logger = LoggerFactory.getLogger(ServiceDistributionArtifactsBuilder.class.getName());
- final static String BASE_ARTIFACT_URL = "/asdc/v1/catalog/services/%s/%s/";
+ final static String BASE_ARTIFACT_URL = "/sdc/v1/catalog/services/%s/%s/";
final static String RESOURCE_ARTIFACT_URL = BASE_ARTIFACT_URL + "resources/%s/%s/artifacts/%s";
final static String SERVICE_ARTIFACT_URL = BASE_ARTIFACT_URL + "artifacts/%s";
final static String RESOURCE_INSTANCE_ARTIFACT_URL = BASE_ARTIFACT_URL + "resourceInstances/%s/artifacts/%s";
@javax.annotation.Resource
- ServiceOperation serviceOperation;
-
- @javax.annotation.Resource
- ResourceOperation resourceOperation;
-
- @javax.annotation.Resource
InterfaceLifecycleOperation interfaceLifecycleOperation;
@javax.annotation.Resource
IArtifactOperation artifactOperation;
+
+ @Autowired
+ ToscaOperationFacade toscaOperationFacade;
/*
- * @javax.annotation.Resource private InformationDeployedArtifactsBusinessLogic informationDeployedArtifactsBusinessLogic;
+ * @javax.annotation.Resource private
+ * InformationDeployedArtifactsBusinessLogic
+ * informationDeployedArtifactsBusinessLogic;
*/
@PostConstruct
private void init() {
- defaultArtifactInstallTimeout = ConfigurationManager.getConfigurationManager().getConfiguration().getDefaultHeatArtifactTimeoutMinutes();
- }
-
- public ServiceOperation getServiceOperation() {
- return serviceOperation;
- }
-
- public void setServiceOperation(ServiceOperation serviceOperation) {
- this.serviceOperation = serviceOperation;
- }
-
- public ResourceOperation getResourceOperation() {
- return resourceOperation;
- }
-
- public void setResourceOperation(ResourceOperation resourceOperation) {
- this.resourceOperation = resourceOperation;
+ defaultArtifactInstallTimeout = ConfigurationManager.getConfigurationManager().getConfiguration()
+ .getDefaultHeatArtifactTimeoutMinutes();
}
public InterfaceLifecycleOperation getInterfaceLifecycleOperation() {
@@ -130,37 +119,91 @@ public class ServiceDistributionArtifactsBuilder {
}
private List<ArtifactInfoImpl> convertServiceArtifactsToArtifactInfo(Service service) {
-
+
Map<String, ArtifactDefinition> serviceArtifactsMap = service.getDeploymentArtifacts();
- List<ArtifactDefinition> ret = new ArrayList<ArtifactDefinition>();
-
- for (ArtifactDefinition artifactDef : serviceArtifactsMap.values()) {
- if (artifactDef.checkEsIdExist()) {
- ret.add(artifactDef);
- }
+ List<ArtifactDefinition> extractedServiceArtifacts = serviceArtifactsMap.values().stream()
+ //filters all artifacts with existing EsId
+ .filter(artifactDef -> artifactDef.checkEsIdExist())
+ //collects all filtered artifacts with existing EsId to List
+ .collect(Collectors.toList());
+
+ Optional<ArtifactDefinition> toscaTemplateArtifactOptl = exrtactToscaTemplateArtifact(service);
+ if(toscaTemplateArtifactOptl.isPresent()){
+ extractedServiceArtifacts.add(toscaTemplateArtifactOptl.get());
}
- List<ArtifactInfoImpl> artifacts = ArtifactInfoImpl.convertServiceArtifactToArtifactInfoImpl(service, ret);
+
+ Optional<ArtifactDefinition> toscaCsarArtifactOptl = exrtactToscaCsarArtifact(service);
+ if(toscaCsarArtifactOptl.isPresent()){
+ extractedServiceArtifacts.add(toscaCsarArtifactOptl.get());
+ }
+
+ List<ArtifactInfoImpl> artifacts = ArtifactInfoImpl.convertServiceArtifactToArtifactInfoImpl(service, extractedServiceArtifacts);
return artifacts;
}
+ private Optional<ArtifactDefinition> exrtactToscaTemplateArtifact(Service service) {
+ return service.getToscaArtifacts().values().stream()
+ //filters TOSCA_TEMPLATE artifact
+ .filter(e -> e.getArtifactType().equals(ArtifactTypeEnum.TOSCA_TEMPLATE.getType())).findAny();
+ }
+
+ private Optional<ArtifactDefinition> exrtactToscaCsarArtifact(Service service) {
+ return service.getToscaArtifacts().values().stream()
+ //filters TOSCA_CSAR artifact
+ .filter(e -> e.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType())).findAny();
+ }
+
private List<JsonContainerResourceInstance> convertRIToJsonContanier(Service service) {
List<JsonContainerResourceInstance> ret = new ArrayList<JsonContainerResourceInstance>();
if (service.getComponentInstances() != null) {
for (ComponentInstance resourceInstance : service.getComponentInstances()) {
- String resourceType = "VF";
+ String resoucreType = resourceInstance.getOriginType().getValue();
List<ArtifactDefinition> artifactsDefList = getArtifactsWithPayload(resourceInstance);
- List<ArtifactInfoImpl> artifacts = ArtifactInfoImpl.convertToArtifactInfoImpl(service, resourceInstance, artifactsDefList);
- Either<String, StorageOperationStatus> responseResult = resourceOperation.getInvariantUUID(NodeTypeEnum.Resource, resourceInstance.getComponentUid(), false);
+ List<ArtifactInfoImpl> artifacts = ArtifactInfoImpl.convertToArtifactInfoImpl(service, resourceInstance,
+ artifactsDefList);
+
String resourceInvariantUUID = null;
- if (responseResult.isRight()) {
- logger.debug("Resource {} Invariant UUID retrieving failed", resourceInstance.getComponentUid());
+ String resourceCategory = null;
+ String resourceSubcategory = null;
+
+ ComponentParametersView componentParametersView = new ComponentParametersView();
+ componentParametersView.disableAll();
+ componentParametersView.setIgnoreCategories(false);
+ Either<Resource, StorageOperationStatus> componentResponse = toscaOperationFacade
+ .getToscaElement(resourceInstance.getComponentUid(), componentParametersView);
+
+ if (componentResponse.isRight()) {
+ logger.debug("Resource {} Invariant UUID & Categories retrieving failed", resourceInstance.getComponentUid());
} else {
- resourceInvariantUUID = responseResult.left().value();
+ Resource resource = componentResponse.left().value();
+ resourceInvariantUUID = resource.getInvariantUUID();
+
+ List<CategoryDefinition> categories = resource.getCategories();
+
+ if (categories != null) {
+ CategoryDefinition categoryDefinition = categories.get(0);
+
+ if (categoryDefinition != null) {
+ resourceCategory = categoryDefinition.getName();
+ List<SubCategoryDefinition> subcategories = categoryDefinition.getSubcategories();
+ if (null != subcategories) {
+ SubCategoryDefinition subCategoryDefinition = subcategories.get(0);
+
+ if (subCategoryDefinition != null) {
+ resourceSubcategory = subCategoryDefinition.getName();
+ }
+ }
+ }
+ }
}
- JsonContainerResourceInstance jsonContainer = new JsonContainerResourceInstance(resourceInstance, resourceInvariantUUID, resourceType, artifacts);
+
+ JsonContainerResourceInstance jsonContainer = new JsonContainerResourceInstance(resourceInstance, resoucreType,
+ artifacts);
+ jsonContainer.setResourceInvariantUUID(resourceInvariantUUID);
+ jsonContainer.setCategory(resourceCategory);
+ jsonContainer.setSubcategory(resourceSubcategory);
ret.add(jsonContainer);
}
-
}
return ret;
}
@@ -193,9 +236,11 @@ public class ServiceDistributionArtifactsBuilder {
* @param artifactName
* @return
*/
- public static String buildResourceInstanceArtifactUrl(Service service, ComponentInstance resourceInstance, String artifactName) {
+ public static String buildResourceInstanceArtifactUrl(Service service, ComponentInstance resourceInstance,
+ String artifactName) {
- String url = String.format(RESOURCE_INSTANCE_ARTIFACT_URL, service.getSystemName(), service.getVersion(), resourceInstance.getNormalizedName(), artifactName);
+ String url = String.format(RESOURCE_INSTANCE_ARTIFACT_URL, service.getSystemName(), service.getVersion(),
+ resourceInstance.getNormalizedName(), artifactName);
logger.debug("After building artifact url {}", url);
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/TestQueue.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/TestQueue.java
index c9e3c4e34d..d9cd6ef51f 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/TestQueue.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/TestQueue.java
@@ -64,13 +64,11 @@ public class TestQueue {
@Override
public void run() {
- // TODO Auto-generated method stub
try {
System.out.println("iN SLEEP" + Thread.currentThread());
Thread.sleep(10 * 1000);
System.out.println("OUT SLEEP");
} catch (InterruptedException e) {
- // TODO Auto-generated catch block
e.printStackTrace();
}
}
@@ -98,7 +96,6 @@ public class TestQueue {
try {
queue.put("message " + i);
} catch (InterruptedException e) {
- // TODO Auto-generated catch block
e.printStackTrace();
}
}
@@ -175,7 +172,6 @@ public class TestQueue {
try {
Thread.sleep(1 * 1000);
} catch (InterruptedException e) {
- // TODO Auto-generated catch block
for (int i = 0; i < 10; i++) {
System.out.println("*************************************************");
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/VfModuleArtifactPayload.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/VfModuleArtifactPayload.java
index 89cb6d91ee..71593fa99a 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/VfModuleArtifactPayload.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/VfModuleArtifactPayload.java
@@ -20,14 +20,26 @@
package org.openecomp.sdc.be.components.distribution.engine;
+import java.util.ArrayList;
import java.util.List;
+import java.util.Map;
import java.util.Optional;
+import java.util.stream.Collectors;
+import org.apache.commons.collections.CollectionUtils;
import org.openecomp.sdc.be.model.GroupDefinition;
+import org.openecomp.sdc.be.model.GroupInstance;
+import org.openecomp.sdc.be.model.GroupInstanceProperty;
import org.openecomp.sdc.be.model.GroupProperty;
import org.openecomp.sdc.common.api.Constants;
public class VfModuleArtifactPayload {
+
+ private String vfModuleModelName, vfModuleModelInvariantUUID, vfModuleModelVersion, vfModuleModelUUID, vfModuleModelCustomizationUUID, vfModuleModelDescription;
+ private Boolean isBase;
+ private List<String> artifacts;
+ private Map< String, Object> properties;
+
public VfModuleArtifactPayload(GroupDefinition group) {
vfModuleModelName = group.getName();
vfModuleModelInvariantUUID = group.getInvariantUUID();
@@ -40,10 +52,38 @@ public class VfModuleArtifactPayload {
setBaseValue(group);
}
+
+ public VfModuleArtifactPayload(GroupInstance group) {
+ vfModuleModelName = group.getGroupName();
+ vfModuleModelInvariantUUID = group.getInvariantUUID();
+ vfModuleModelVersion = group.getVersion();
+ vfModuleModelUUID = group.getGroupUUID();
+ vfModuleModelCustomizationUUID = group.getCustomizationUUID();
+ vfModuleModelDescription = group.getDescription();
+ artifacts = group.getArtifactsUuid();
+ // Base Value is set from properties
+ setBaseValue(group);
+
+ if(group.convertToGroupInstancesProperties() != null)
+ setProperties(group.convertToGroupInstancesProperties());
+ //converts List of GroupInstanceProperties to Map propertyName : GroupInstanceProperty ()
+ //setProperties(group.getGroupInstancesProperties().stream().collect(Collectors.toMap(p->p.getName(), p->p)));
+
+ }
+
+ private void setBaseValue(GroupInstance group) {
+ if (group.convertToGroupInstancesProperties() != null) {
+ Optional<GroupInstanceProperty> findBaseProperty = group.convertToGroupInstancesProperties().stream().filter(p -> p.getName().equals(Constants.IS_BASE)).findAny();
+ if (findBaseProperty.isPresent()) {
+ isBase = Boolean.valueOf(findBaseProperty.get().getValue());
+ }
+
+ }
+ }
private void setBaseValue(GroupDefinition group) {
if (group.getProperties() != null) {
- Optional<GroupProperty> findBaseProperty = group.getProperties().stream().filter(p -> p.getName().equals(Constants.IS_BASE)).findAny();
+ Optional<GroupProperty> findBaseProperty = group.convertToGroupProperties().stream().filter(p -> p.getName().equals(Constants.IS_BASE)).findAny();
if (findBaseProperty.isPresent()) {
isBase = Boolean.valueOf(findBaseProperty.get().getValue());
}
@@ -51,9 +91,7 @@ public class VfModuleArtifactPayload {
}
}
- private String vfModuleModelName, vfModuleModelInvariantUUID, vfModuleModelVersion, vfModuleModelUUID, vfModuleModelDescription;
- private Boolean isBase;
- private List<String> artifacts;
+
public List<String> getArtifacts() {
return artifacts;
@@ -62,10 +100,25 @@ public class VfModuleArtifactPayload {
public void setArtifacts(List<String> artifacts) {
this.artifacts = artifacts;
}
+
+
+
+ public Map<String, Object> getProperties() {
+ return properties;
+ }
+
+ /*public void setProperties(Map<String, Object> properties) {
+ this.properties = properties;
+ }*/
+
+ public void setProperties(List<GroupInstanceProperty> properties) {
+ this.properties = properties.stream().filter(p -> !p.getName().equals(Constants.IS_BASE)).collect(
+ Collectors.toMap(x -> x.getName(), x -> x.getValue() == null? "":x.getValue() ));
+ }
public static int compareByGroupName(VfModuleArtifactPayload art1, VfModuleArtifactPayload art2) {
- Integer thisCounter = Integer.parseInt(art1.vfModuleModelName.split(Constants.MODULE_NAME_DELIMITER)[1]);
- Integer otherCounter = Integer.parseInt(art2.vfModuleModelName.split(Constants.MODULE_NAME_DELIMITER)[1]);
+ Float thisCounter = Float.parseFloat(art1.vfModuleModelName.split(Constants.MODULE_NAME_DELIMITER)[1].replace(' ', '.'));
+ Float otherCounter = Float.parseFloat(art2.vfModuleModelName.split(Constants.MODULE_NAME_DELIMITER)[1].replace(' ', '.'));
return thisCounter.compareTo(otherCounter);
}
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AdditionalInformationBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AdditionalInformationBusinessLogic.java
index e01d4c238c..51b5679ffa 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AdditionalInformationBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AdditionalInformationBusinessLogic.java
@@ -29,17 +29,15 @@ import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.dao.graph.datatype.AdditionalInformationEnum;
import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
+import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterInfo;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.impl.WebAppContextWrapper;
-import org.openecomp.sdc.be.model.AdditionalInfoParameterInfo;
import org.openecomp.sdc.be.model.AdditionalInformationDefinition;
import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.model.operations.api.IAdditionalInformationOperation;
import org.openecomp.sdc.be.model.operations.api.IElementOperation;
import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation;
-import org.openecomp.sdc.be.model.operations.api.IResourceOperation;
-import org.openecomp.sdc.be.model.operations.api.IServiceOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
@@ -73,12 +71,6 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic {
private IAdditionalInformationOperation additionalInformationOperation = null;
@javax.annotation.Resource
- private IResourceOperation resourceOperation;
-
- @javax.annotation.Resource
- private IServiceOperation serviceOperation;
-
- @javax.annotation.Resource
private IGraphLockOperation graphLockOperation;
@javax.annotation.Resource
@@ -551,7 +543,7 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic {
// verify that resource is checked-out and the user is the last
// updater
- if (!ComponentValidationUtils.canWorkOnResource(resourceId, resourceOperation, userId)) {
+ if (!ComponentValidationUtils.canWorkOnComponent(resourceId, toscaOperationFacade, userId)) {
return componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
}
break;
@@ -559,7 +551,7 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic {
// verify that resource is checked-out and the user is the last
// updater
- if (!ComponentValidationUtils.canWorkOnService(resourceId, serviceOperation, userId)) {
+ if (!ComponentValidationUtils.canWorkOnComponent(resourceId, toscaOperationFacade, userId)) {
return componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
}
break;
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactsBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactsBusinessLogic.java
index 16ed4a1868..6739d28bd4 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactsBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactsBusinessLogic.java
@@ -24,13 +24,13 @@ import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
-import java.util.Collection;
import java.util.Comparator;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
+import java.util.Optional;
import java.util.Set;
import java.util.function.Predicate;
import java.util.function.Supplier;
@@ -39,6 +39,9 @@ import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.codec.binary.Base64;
+import org.apache.commons.collections.CollectionUtils;
+import org.apache.commons.collections.MapUtils;
+import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum;
import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaTagNamesEnum;
@@ -46,14 +49,15 @@ import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction.LifecycleChanceActionEnum;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
-import org.openecomp.sdc.be.config.Configuration.DeploymentArtifactTypeConfig;
+import org.openecomp.sdc.be.config.Configuration.ArtifactTypeConfig;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.config.validation.DeploymentArtifactHeatConfiguration;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao;
import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus;
-import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
+import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
@@ -61,6 +65,9 @@ import org.openecomp.sdc.be.model.ArtifactDefinition;
import org.openecomp.sdc.be.model.ArtifactType;
import org.openecomp.sdc.be.model.Component;
import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.ComponentParametersView;
+import org.openecomp.sdc.be.model.GroupDefinition;
+import org.openecomp.sdc.be.model.GroupInstance;
import org.openecomp.sdc.be.model.HeatParameterDefinition;
import org.openecomp.sdc.be.model.InterfaceDefinition;
import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
@@ -70,19 +77,14 @@ import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.Service;
import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.model.heat.HeatParameterType;
-import org.openecomp.sdc.be.model.operations.api.IArtifactOperation;
-import org.openecomp.sdc.be.model.operations.api.IComponentInstanceOperation;
+import org.openecomp.sdc.be.model.jsontitan.operations.NodeTemplateOperation;
import org.openecomp.sdc.be.model.operations.api.IElementOperation;
import org.openecomp.sdc.be.model.operations.api.IHeatParametersOperation;
import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation;
-import org.openecomp.sdc.be.model.operations.api.IResourceOperation;
import org.openecomp.sdc.be.model.operations.api.IUserAdminOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.be.model.operations.impl.ComponentOperation;
import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
-import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
-import org.openecomp.sdc.be.resources.data.ArtifactData;
import org.openecomp.sdc.be.resources.data.ComponentMetadataData;
import org.openecomp.sdc.be.resources.data.ESArtifactData;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
@@ -98,7 +100,6 @@ import org.openecomp.sdc.be.user.UserBusinessLogic;
import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
import org.openecomp.sdc.common.api.ArtifactTypeEnum;
import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.config.EcompErrorName;
import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
import org.openecomp.sdc.common.datastructure.Wrapper;
import org.openecomp.sdc.common.util.GeneralUtility;
@@ -132,25 +133,21 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
private static final String ARTIFACT_PLACEHOLDER_DISPLAY_NAME = "displayName";
private static final Object ARTIFACT_PLACEHOLDER_DESCRIPTION = "description";
- private static Integer defaultHeatTimeout;
- private static final Integer NON_HEAT_TIMEOUT = 0;
+ public static final String HEAT_ENV_NAME = "heatEnv";
+ public static final String HEAT_VF_ENV_NAME = "VfHeatEnv";
+ public static final String HEAT_ENV_SUFFIX = "env";
+ private static final String ARTIFACT_PLACEHOLDER_FILE_EXTENSION = "fileExtension";
+
+ // private static Integer defaultHeatTimeout;
+ // private static final Integer NON_HEAT_TIMEOUT = 0;
private static Logger log = LoggerFactory.getLogger(ArtifactsBusinessLogic.class.getName());
private Gson gson = new GsonBuilder().setPrettyPrinting().create();
@javax.annotation.Resource
- private IArtifactOperation artifactOperation;
-
- // @javax.annotation.Resource
- // private IResourceUploader daoUploader;
-
- @javax.annotation.Resource
private IInterfaceLifecycleOperation interfaceLifecycleOperation;
@javax.annotation.Resource
private IUserAdminOperation userOperaton;
- // @javax.annotation.Resource
- // private ESCatalogDAO esCatalogDao;
-
@javax.annotation.Resource
private IElementOperation elementOperation;
@@ -166,9 +163,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
@javax.annotation.Resource
private IHeatParametersOperation heatParametersOperation;
- @javax.annotation.Resource
- private IComponentInstanceOperation resourceInstanceOperation;
-
@Autowired
private ArtifactCassandraDao artifactCassandraDao;
@@ -183,62 +177,71 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
@Autowired
private IUserBusinessLogic userBusinessLogic;
+ @Autowired
+ NodeTemplateOperation nodeTemplateOperation;
public ArtifactsBusinessLogic() {
- defaultHeatTimeout = ConfigurationManager.getConfigurationManager().getConfiguration().getDefaultHeatArtifactTimeoutMinutes();
- if ((defaultHeatTimeout == null) || (defaultHeatTimeout < 1)) {
- defaultHeatTimeout = 60;
- }
+ // defaultHeatTimeout = ConfigurationManager.getConfigurationManager().getConfiguration().getDefaultHeatArtifactTimeoutMinutes();
+ // if ((defaultHeatTimeout == null) || (defaultHeatTimeout < 1)) {
+ // defaultHeatTimeout = 60;
+ // }
}
- public static enum ArtifactOperation {
+ public static enum ArtifactOperationEnum {
+ Create(), Update(), Delete(), Download();
+ }
- Create(false), Update(false), Delete(false), Download(false);
+ public class ArtifactOperationInfo {
+ private ArtifactOperationEnum artifactOperationEnum;
private boolean isExternalApi;
+ private boolean ignoreLifecycleState;
- ArtifactOperation(boolean isExternalApi) {
+ public ArtifactOperationInfo(boolean isExternalApi, boolean ignoreLifecycleState, ArtifactOperationEnum artifactOperationEnum) {
+ this.artifactOperationEnum = artifactOperationEnum;
this.isExternalApi = isExternalApi;
+ this.ignoreLifecycleState = ignoreLifecycleState;
}
public boolean isExternalApi() {
return isExternalApi;
}
- public void setExternalApi(boolean isExternalApi) {
- this.isExternalApi = isExternalApi;
+ public boolean ignoreLifecycleState() {
+ return ignoreLifecycleState;
}
+
+ public ArtifactOperationEnum getArtifactOperationEnum() {
+ return artifactOperationEnum;
+ }
+
}
// new flow US556184
- public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperation operation, String artifactId, ArtifactDefinition artifactInfo,
+ public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo,
String origMd5, String originData, String interfaceName, String operationName, String parentId, String containerComponentType) {
return handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, originData, interfaceName, operationName, parentId, containerComponentType, true, false);
}
- public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperation operation, String artifactId, ArtifactDefinition artifactInfo,
+ public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo,
String origMd5, String originData, String interfaceName, String operationName, String parentId, String containerComponentType, boolean shouldLock, boolean inTransaction) {
- // step 1
- // detect auditing type
+
+ // step 1 - detect auditing type
AuditingActionEnum auditingAction = detectAuditingType(operation, origMd5);
- Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
- // step 2
- // check header
+ // step 2 - check header
if (userId == null) {
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
log.debug("handleArtifactRequest - no HTTP_CSP_HEADER , component id {}", componentId);
handleAuditing(auditingAction, null, componentId, null, null, null, artifactId, responseFormat, componentType, null);
return Either.right(responseFormat);
}
- // step 3
- // check user existence
- // step 4
- // check user's role
+ // step 3 - check user existence
Either<User, ResponseFormat> userResult = validateUserExists(userId, auditingAction, componentId, artifactId, componentType, inTransaction);
if (userResult.isRight()) {
return Either.right(userResult.right().value());
}
+ // step 4 - check user's role
User user = userResult.left().value();
Either<Boolean, ResponseFormat> validateUserRole = validateUserRole(user, auditingAction, componentId, artifactId, componentType, operation);
if (validateUserRole.isRight()) {
@@ -271,17 +274,17 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
/**
* This Method validates only the Artifact and does not validate user / role / component ect...<br>
* For regular usage use <br>
- * {@link #handleArtifactRequest(String, String, ComponentTypeEnum, ArtifactOperation, String, ArtifactDefinition, String, String, String, String, String, String)}
+ * {@link #handleArtifactRequest(String, String, ComponentTypeEnum, ArtifactOperationInfo, String, ArtifactDefinition, String, String, String, String, String, String)}
*
* @return
*/
- public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> validateAndHandleArtifact(String componentUniqueId, ComponentTypeEnum componentType, ArtifactOperation operation, String artifactUniqueId, ArtifactDefinition artifactDefinition,
- String origMd5, String originData, String interfaceName, String operationName, String parentId, User user, Component component, boolean shouldLock, boolean inTransaction) {
+ public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> validateAndHandleArtifact(String componentUniqueId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactUniqueId,
+ ArtifactDefinition artifactDefinition, String origMd5, String originData, String interfaceName, String operationName, String parentId, User user, Component component, boolean shouldLock, boolean inTransaction) {
Component parent = component;
Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
AuditingActionEnum auditingAction = detectAuditingType(operation, origMd5);
- artifactDefinition = validateArtifact(componentUniqueId, componentType, operation, artifactUniqueId, artifactDefinition, parentId, auditingAction, user, component, parent, shouldLock, errorWrapper);
+ artifactDefinition = validateArtifact(componentUniqueId, componentType, operation, artifactUniqueId, artifactDefinition, parentId, auditingAction, user, component, parent, shouldLock, errorWrapper, inTransaction);
Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result;
if (errorWrapper.isEmpty()) {
@@ -293,43 +296,53 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return result;
}
- private ArtifactDefinition validateArtifact(String componentId, ComponentTypeEnum componentType, ArtifactOperation operation, String artifactId, ArtifactDefinition artifactInfo, String parentId, AuditingActionEnum auditingAction, User user,
- org.openecomp.sdc.be.model.Component component, org.openecomp.sdc.be.model.Component parent, boolean shouldLock, Wrapper<ResponseFormat> errorWrapper) {
- if (operation == ArtifactOperation.Update || operation == ArtifactOperation.Delete || operation == ArtifactOperation.Download) {
- Either<ArtifactDefinition, ResponseFormat> validateArtifact = validateArtifact(componentId, componentType, artifactId, component, auditingAction, parentId);
+ private ArtifactDefinition validateArtifact(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String parentId, AuditingActionEnum auditingAction, User user,
+ org.openecomp.sdc.be.model.Component component, org.openecomp.sdc.be.model.Component parent, boolean shouldLock, Wrapper<ResponseFormat> errorWrapper, boolean inTransaction) {
+ if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Update || operation.getArtifactOperationEnum() == ArtifactOperationEnum.Delete || operation.getArtifactOperationEnum() == ArtifactOperationEnum.Download) {
+ Either<ArtifactDefinition, ResponseFormat> validateArtifact = validateArtifact(componentId, componentType, artifactId, component, auditingAction, parentId, inTransaction);
if (validateArtifact.isRight()) {
ResponseFormat responseFormat = validateArtifact.right().value();
handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
errorWrapper.setInnerElement(validateArtifact.right().value());
- } else if (operation == ArtifactOperation.Download) {
- artifactInfo = validateArtifact.left().value();
- handleHeatEnvDownload(componentId, user, component, validateArtifact, shouldLock, errorWrapper);
+ } else {
+ if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Download) {
+ artifactInfo = validateArtifact.left().value();
+ handleHeatEnvDownload(componentId, componentType, user, component, validateArtifact, shouldLock, errorWrapper);
+ }
}
}
return artifactInfo;
}
- private void handleHeatEnvDownload(String componentId, User user, org.openecomp.sdc.be.model.Component component, Either<ArtifactDefinition, ResponseFormat> validateArtifact, boolean shouldLock, Wrapper<ResponseFormat> errorWrapper) {
+ private void handleHeatEnvDownload(String componentId, ComponentTypeEnum componentType, User user, org.openecomp.sdc.be.model.Component component, Either<ArtifactDefinition, ResponseFormat> validateArtifact, boolean shouldLock,
+ Wrapper<ResponseFormat> errorWrapper) {
ArtifactDefinition validatedArtifact = validateArtifact.left().value();
if (validatedArtifact.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType())) {
- ComponentInstance componentInstance = component.getComponentInstances().stream().filter(p -> p.getUniqueId().equals(componentId)).findAny().get();
- ArtifactDefinition heatEnvWithHeatParams = componentInstance.getDeploymentArtifacts().values().stream().filter(p -> p.getUniqueId().equals(validatedArtifact.getUniqueId())).findAny().get();
- Either<ArtifactDefinition, ResponseFormat> eitherGenerated = generateHeatEnvArtifact(heatEnvWithHeatParams, component, componentInstance.getName(), user, shouldLock);
- if (eitherGenerated.isRight()) {
- errorWrapper.setInnerElement(eitherGenerated.right().value());
+ if (ComponentTypeEnum.SERVICE == component.getComponentType()) {
+ ComponentInstance componentInstance = component.getComponentInstances().stream().filter(p -> p.getUniqueId().equals(componentId)).findAny().get();
+ Map<String, ArtifactDefinition> deploymentArtifacts = componentInstance.getDeploymentArtifacts();
+
+ ArtifactDefinition heatEnvWithHeatParams = deploymentArtifacts.values().stream().filter(p -> p.getUniqueId().equals(validatedArtifact.getUniqueId())).findAny().get();
+ Either<ArtifactDefinition, ResponseFormat> eitherGenerated = generateHeatEnvArtifact(heatEnvWithHeatParams, componentType, component, componentInstance.getName(), user, shouldLock, componentId);
+ if (eitherGenerated.isRight()) {
+ errorWrapper.setInnerElement(eitherGenerated.right().value());
+ }
}
}
}
private boolean artifactGenerationRequired(org.openecomp.sdc.be.model.Component component, ArtifactDefinition artifactInfo) {
- return artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && (component.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN || component.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ boolean needGenerate;
+ needGenerate = artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && (component.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN || component.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ needGenerate = needGenerate || (ComponentTypeEnum.RESOURCE == component.getComponentType() && artifactInfo.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType()));
+ return needGenerate;
}
public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateAndSaveToscaArtifact(ArtifactDefinition artifactDefinition, org.openecomp.sdc.be.model.Component component, User user, boolean isInCertificationRequest,
boolean shouldLock, boolean inTransaction, boolean fetchTemplatesFromDB) {
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generated = generateToscaArtifact(component, artifactDefinition, isInCertificationRequest, fetchTemplatesFromDB, shouldLock, inTransaction);
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generated = generateToscaArtifact(component, artifactDefinition, isInCertificationRequest, fetchTemplatesFromDB);
if (generated.isRight()) {
return generated;
}
@@ -341,11 +354,10 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
- private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateToscaArtifact(Component parent, ArtifactDefinition artifactInfo, boolean isInCertificationRequest, boolean fetchTemplatesFromDB, boolean shouldLock,
- boolean inTransaction) {
+ private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateToscaArtifact(Component parent, ArtifactDefinition artifactInfo, boolean isInCertificationRequest, boolean fetchTemplatesFromDB) {
log.debug("tosca artifact generation");
if (artifactInfo.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType())) {
- Either<byte[], ResponseFormat> generated = csarUtils.createCsar(parent, fetchTemplatesFromDB, isInCertificationRequest, shouldLock, inTransaction);
+ Either<byte[], ResponseFormat> generated = csarUtils.createCsar(parent, fetchTemplatesFromDB, isInCertificationRequest);
if (generated.isRight()) {
log.debug("Failed to export tosca csar for component {} error {}", parent.getUniqueId(), generated.right().value());
@@ -370,16 +382,16 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return Either.left(Either.left(artifactInfo));
}
- private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> doAction(String componentId, ComponentTypeEnum componentType, ArtifactOperation operation, String artifactId, ArtifactDefinition artifactInfo, String origMd5,
+ private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> doAction(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String origMd5,
String originData, String interfaceName, String operationName, AuditingActionEnum auditingAction, User user, org.openecomp.sdc.be.model.Component parent, boolean shouldLock, boolean inTransaction) {
if (interfaceName != null && operationName != null) {
interfaceName = interfaceName.toLowerCase();
operationName = operationName.toLowerCase();
}
- switch (operation) {
+ switch (operation.getArtifactOperationEnum()) {
case Download:
if (artifactGenerationRequired(parent, artifactInfo)) {
- return generateToscaArtifact(parent, artifactInfo, false, false, shouldLock, inTransaction);
+ return generateNotSavedArtifact(parent, artifactInfo, shouldLock, inTransaction);
}
return handleDownload(componentId, artifactId, user, auditingAction, componentType, parent, shouldLock, inTransaction);
case Delete:
@@ -389,6 +401,10 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)
&& (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_VOL || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_ENV)) {
return handleUpdateHeatEnv(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation, shouldLock, inTransaction);
+ } else {
+ if (componentType.equals(ComponentTypeEnum.RESOURCE) && artifactType == ArtifactTypeEnum.HEAT_ENV) {
+ return handleUpdateHeatWithHeatEnvParams(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation, shouldLock, inTransaction);
+ }
}
return handleUpdate(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction);
case Create:
@@ -397,6 +413,87 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return null;
}
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateNotSavedArtifact(org.openecomp.sdc.be.model.Component parent, ArtifactDefinition artifactInfo, boolean shouldLock, boolean inTransaction) {
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result;
+ if (artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA) {
+ result = generateToscaArtifact(parent, artifactInfo, false, false);
+ } else {
+ String heatArtifactId = artifactInfo.getGeneratedFromId();
+ Either<ArtifactDefinition, StorageOperationStatus> heatRes = artifactToscaOperation.getArtifactById(parent.getUniqueId(), heatArtifactId);
+ if (heatRes.isRight()) {
+ log.debug("Failed to fetch heat artifact by generated id {} for heat env {}", heatArtifactId, artifactInfo.getUniqueId());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(heatRes.right().value()), "");
+ return Either.right(responseFormat);
+ }
+ String generatedPayload = generateHeatEnvPayload(heatRes.left().value());
+ artifactInfo.setPayloadData(generatedPayload);
+ result = Either.left(Either.left(artifactInfo));
+ }
+ return result;
+ }
+
+ private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdateHeatWithHeatEnvParams(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user,
+ ComponentTypeEnum componentType, Component parent, String originData, String origMd5, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) {
+ convertParentType(componentType);
+ String parentId = parent.getUniqueId();
+ Either<ArtifactDefinition, StorageOperationStatus> artifactHeatRes = artifactToscaOperation.getArtifactById(componentId, artifactInfo.getGeneratedFromId());
+ ArtifactDefinition currHeatArtifact = artifactHeatRes.left().value();
+
+ if (origMd5 != null) {
+ Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
+ if (validateMd5.isRight()) {
+ ResponseFormat responseFormat = validateMd5.right().value();
+ handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
+ return Either.right(responseFormat);
+ }
+
+ if (artifactInfo.getPayloadData() != null && artifactInfo.getPayloadData().length != 0) {
+
+ Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
+ if (payloadEither.isRight()) {
+ ResponseFormat responseFormat = payloadEither.right().value();
+ handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
+ return Either.right(responseFormat);
+ }
+ } else { // duplicate
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
+ handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
+ return Either.right(responseFormat);
+ }
+ }
+
+ // lock resource
+ if (shouldLock) {
+ Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Update Artifact - lock ");
+ if (lockComponent.isRight()) {
+ handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right().value(), componentType, null);
+ return Either.right(lockComponent.right().value());
+ }
+ }
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
+ try {
+ resultOp = updateHeatParams(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, currHeatArtifact, origMd5);
+ return resultOp;
+
+ } finally {
+ // unlock resource
+ if (resultOp == null || resultOp.isRight()) {
+ log.debug("all changes rollback");
+ if (false == inTransaction)
+ titanDao.rollback();
+ } else {
+ log.debug("all changes committed");
+ if (false == inTransaction)
+ titanDao.commit();
+ }
+ if (shouldLock)
+ componentType = parent.getComponentType();
+ NodeTypeEnum nodeType = componentType.getNodeType();
+ graphLockOperation.unlockComponent(parent.getUniqueId(), nodeType);
+ // graphLockOperation.unlockComponent(parentId, parentType);
+ }
+ }
+
/**
*
* @param componentId
@@ -404,13 +501,12 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
* @param userId
* @param componentType
* @param parentId
- * TODO
* @return
*/
- public Either<ImmutablePair<String, byte[]>, ResponseFormat> handleDownloadToscaModelRequest(Component component, ArtifactDefinition csarArtifact, boolean shouldLock, boolean inTransaction) {
+ public Either<ImmutablePair<String, byte[]>, ResponseFormat> handleDownloadToscaModelRequest(Component component, ArtifactDefinition csarArtifact) {
if (artifactGenerationRequired(component, csarArtifact)) {
- Either<byte[], ResponseFormat> generated = csarUtils.createCsar(component, false, false, shouldLock, inTransaction);
+ Either<byte[], ResponseFormat> generated = csarUtils.createCsar(component, false, false);
if (generated.isRight()) {
log.debug("Failed to export tosca csar for component {} error {}", component.getUniqueId(), generated.right().value());
@@ -424,7 +520,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
public Either<ImmutablePair<String, byte[]>, ResponseFormat> handleDownloadRequestById(String componentId, String artifactId, String userId, ComponentTypeEnum componentType, String parentId, String containerComponentType) {
// perform all validation in common flow
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result = handleArtifactRequest(componentId, userId, componentType, ArtifactOperation.Download, artifactId, null, null, null, null, null, parentId, containerComponentType);
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result = handleArtifactRequest(componentId, userId, componentType, new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Download), artifactId, null, null, null, null,
+ null, parentId, containerComponentType);
if (result.isRight()) {
return Either.right(result.right().value());
}
@@ -433,19 +530,134 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
if (insideValue.isLeft()) {
artifactDefinition = insideValue.left().value();
} else {
- artifactDefinition = insideValue.right().value().getImplementation();
+ artifactDefinition = insideValue.right().value().getImplementationArtifact();
}
- // for tosca artifacts generated on download without saving
- if (artifactDefinition.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && artifactDefinition.getPayloadData() != null) {
+ // for tosca artifacts and heat env on VF level generated on download without saving
+ if (artifactDefinition.getPayloadData() != null) {
return Either.left(new ImmutablePair<String, byte[]>(artifactDefinition.getArtifactName(), artifactDefinition.getPayloadData()));
}
return downloadArtifact(artifactDefinition);
}
- private Either<ArtifactDefinition, ResponseFormat> validateArtifact(String componentId, ComponentTypeEnum componentType, String artifactId, org.openecomp.sdc.be.model.Component component, AuditingActionEnum auditingAction, String parentId) {
+ public Either<Map<String, ArtifactDefinition>, ResponseFormat> handleGetArtifactsByType(String containerComponentType, String parentId, ComponentTypeEnum componentType, String componentId, String artifactGroupType, String userId) {
+ // step 1
+ // detect auditing type
+ Map<String, ArtifactDefinition> resMap = null;
+ Either<Map<String, ArtifactDefinition>, ResponseFormat> resultOp = null;
+
+ new Wrapper<>();
+ // step 2
+ // check header
+ if (userId == null) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
+ log.debug("handleGetArtifactsByType - no HTTP_CSP_HEADER , component id {}", componentId);
+
+ resultOp = Either.right(responseFormat);
+ return resultOp;
+ }
+ // step 3
+ // check user existence
+ // step 4
+ // check user's role
+
+ Either<User, ResponseFormat> userResult = validateUserExists(userId, "get artifacts", false);
+ if (userResult.isRight()) {
+
+ resultOp = Either.right(userResult.right().value());
+ return resultOp;
+ }
+
+ userResult.left().value();
+
+ // steps 5 - 6 - 7
+ // 5. check service/resource existence
+ // 6. check service/resource check out
+ // 7. user is owner of checkout state
+ org.openecomp.sdc.be.model.Component component = null;
+ // ComponentInstance resourceInstance = null;
+ String realComponentId = componentType == ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId;
+ ComponentParametersView componentFilter = new ComponentParametersView();
+ componentFilter.disableAll();
+ componentFilter.setIgnoreArtifacts(false);
+ if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE)
+ componentFilter.setIgnoreComponentInstances(false);
+
+ Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExistsByFilter(realComponentId, ComponentTypeEnum.findByParamName(containerComponentType), componentFilter, false);
+
+ if (validateComponent.isRight()) {
+ resultOp = Either.right(validateComponent.right().value());
+ return resultOp;
+ }
+ component = validateComponent.left().value();
+ Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, "Update Artifact - lock ");
+ if (lockComponent.isRight()) {
+
+ resultOp = Either.right(lockComponent.right().value());
+ return resultOp;
+ }
+
+ try {
+ ArtifactGroupTypeEnum groupType = ArtifactGroupTypeEnum.findType(artifactGroupType);
+
+ if (groupType == null) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
+ log.debug("handleGetArtifactsByType - not falid groupType {} , component id {}", artifactGroupType, componentId);
+
+ resultOp = Either.right(responseFormat);
+ return resultOp;
+
+ }
+ if (groupType == ArtifactGroupTypeEnum.DEPLOYMENT) {
+ List<ArtifactDefinition> list = getDeploymentArtifacts(component, componentType.getNodeType(), componentId);
+ if (list != null && !list.isEmpty()){
+ resMap = list.stream().collect(Collectors.toMap(a -> a.getArtifactLabel(), a -> a));
+ }else{
+ resMap = new HashMap<>();
+ }
+ resultOp = Either.left(resMap);
+ return resultOp;
+ } else {
+
+ Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifactsMapStatus = getArtifacts(realComponentId, componentType.getNodeType(), false, groupType, componentId );
+ if (artifactsMapStatus.isRight()) {
+ if (artifactsMapStatus.right().value() != StorageOperationStatus.NOT_FOUND) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
+ log.debug("handleGetArtifactsByType - not falid groupType {} , component id {}", artifactGroupType, componentId);
+ resultOp = Either.right(responseFormat);
+ }else{
+ resMap = new HashMap<>();
+ resultOp = Either.left(resMap);
+ }
+ } else {
+ resMap = artifactsMapStatus.left().value();
+ resultOp = Either.left(resMap);
+ }
+ return resultOp;
+ }
+ } finally {
+ // unlock resource
+ if (resultOp == null || resultOp.isRight()) {
+ log.debug("all changes rollback");
+ titanDao.rollback();
+ } else {
+ log.debug("all changes committed");
+
+ titanDao.commit();
+ }
+
+ componentType = component.getComponentType();
+ NodeTypeEnum nodeType = componentType.getNodeType();
+ graphLockOperation.unlockComponent(component.getUniqueId(), nodeType);
+ // graphLockOperation.unlockComponent(parentId, parentType);
+ }
+
+ }
+
+ private Either<ArtifactDefinition, ResponseFormat> validateArtifact(String componentId, ComponentTypeEnum componentType, String artifactId, org.openecomp.sdc.be.model.Component component, AuditingActionEnum auditingAction, String parentId,
+ boolean inTransaction) {
// step 9
// check artifact existence
- Either<ArtifactDefinition, StorageOperationStatus> artifactResult = artifactOperation.getArtifactById(artifactId, false);
+ Either<ArtifactDefinition, StorageOperationStatus> artifactResult = artifactToscaOperation.getArtifactById(componentId, artifactId, componentType, component.getUniqueId());
if (artifactResult.isRight()) {
if (artifactResult.right().value().equals(StorageOperationStatus.ARTIFACT_NOT_FOUND)) {
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, "");
@@ -484,7 +696,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return Either.left(artifactResult.left().value());
}
- private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleCreate(String parentId, ArtifactDefinition artifactInfo, ArtifactOperation operation, AuditingActionEnum auditingAction, User user, ComponentTypeEnum componentType,
+ private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleCreate(String parentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, User user, ComponentTypeEnum componentType,
org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
String artifactId = null;
@@ -495,8 +707,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return Either.right(payloadEither.right().value());
}
byte[] decodedPayload = payloadEither.left().value();
- NodeTypeEnum parentType = convertParentType(componentType);
- // lock resource
+ convertParentType(componentType);
if (shouldLock) {
Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Upload Artifact - lock ");
@@ -522,11 +733,12 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> lockComponentAndUpdateArtifact(String parentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user,
ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, byte[] decodedPayload, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
- NodeTypeEnum parentType = convertParentType(componentType);
+ convertParentType(componentType);
// lock resource
if (shouldLock) {
Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Update Artifact - lock ");
+
if (lockComponent.isRight()) {
handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right().value(), componentType, null);
return Either.right(lockComponent.right().value());
@@ -545,7 +757,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
}
- private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdate(String parentId, ArtifactDefinition artifactInfo, ArtifactOperation operation, AuditingActionEnum auditingAction, String artifactId, User user,
+ private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdate(String parentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user,
ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
Either<byte[], ResponseFormat> payloadEither = validateInput(parentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceType, operationName, inTransaction);
@@ -558,7 +770,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return lockComponentAndUpdateArtifact(parentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, decodedPayload, interfaceType, operationName, shouldLock, inTransaction);
}
- private Either<byte[], ResponseFormat> validateInput(String parentId, ArtifactDefinition artifactInfo, ArtifactOperation operation, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType,
+ private Either<byte[], ResponseFormat> validateInput(String parentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType,
org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean inTransaction) {
// Md5 validations
Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
@@ -688,7 +900,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return sb.toString();
}
- private Either<Boolean, ResponseFormat> validateMd5(String origMd5, String originData, byte[] payload, ArtifactOperation operation) {
+ private Either<Boolean, ResponseFormat> validateMd5(String origMd5, String originData, byte[] payload, ArtifactOperationInfo operation) {
if (origMd5 != null) {
String encodeBase64Str = GeneralUtility.calculateMD5ByString(originData);
@@ -698,7 +910,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5));
}
} else {
- if (operation == ArtifactOperation.Create) {
+ if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create) {
log.debug("Missing md5 header during artifact create");
return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5));
}
@@ -711,14 +923,18 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return Either.left(true);
}
- private Either<ArtifactDefinition, ResponseFormat> validateInput(String parentId, ArtifactDefinition artifactInfo, ArtifactOperation operation, String artifactId, User user, String interfaceName, String operationName,
+ private Either<ArtifactDefinition, ResponseFormat> validateInput(String parentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, String artifactId, User user, String interfaceName, String operationName,
ComponentTypeEnum componentType, Component parentComponent, boolean inTransaction) {
+ Either<Boolean, ResponseFormat> validateInformationalArtifactRes = validateInformationalArtifact(artifactInfo, parentComponent);
+ if (validateInformationalArtifactRes.isRight()) {
+ return Either.right(validateInformationalArtifactRes.right().value());
+ }
Either<Boolean, ResponseFormat> validateAndSetArtifactname = validateAndSetArtifactname(artifactInfo);
if (validateAndSetArtifactname.isRight()) {
return Either.right(validateAndSetArtifactname.right().value());
}
- Either<ArtifactDefinition, ResponseFormat> artifactById = fetchCurrentArtifact(operation, artifactId);
+ Either<ArtifactDefinition, ResponseFormat> artifactById = findArtifactOnParentComponent(parentComponent, parentId, operation, artifactId);
if (artifactById.isRight()) {
return Either.right(artifactById.right().value());
}
@@ -734,7 +950,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
// This is a patch to block possibility of updating service api fields
// through other artifacts flow
- if (!operation.equals(ArtifactOperation.Create)) {
+ if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.Create) {
checkAndSetUnUpdatableFields(user, artifactInfo, currentArtifactInfo, (operationName != null ? ArtifactGroupTypeEnum.LIFE_CYCLE : ArtifactGroupTypeEnum.INFORMATIONAL));
} else {
checkCreateFields(user, artifactInfo, (operationName != null ? ArtifactGroupTypeEnum.LIFE_CYCLE : ArtifactGroupTypeEnum.INFORMATIONAL));
@@ -746,7 +962,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
// artifactGroupType is not allowed to be updated
- if (!operation.equals(ArtifactOperation.Create)) {
+ if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.Create) {
Either<ArtifactDefinition, ResponseFormat> validateGroupType = validateOrSetArtifactGroupType(artifactInfo, currentArtifactInfo);
if (validateGroupType.isRight()) {
return Either.right(validateGroupType.right().value());
@@ -756,7 +972,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
NodeTypeEnum parentType = convertParentType(componentType);
// TODO TEMP !!!
- boolean isCreate = operation.equals(ArtifactOperation.Create);
+ boolean isCreate = operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create;
if (isDeploymentArtifact(artifactInfo)) {
Either<Boolean, ResponseFormat> deploymentValidationResult = validateDeploymentArtifact(parentComponent, parentId, user.getUserId(), isCreate, artifactInfo, currentArtifactInfo, parentType);
@@ -764,7 +980,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return Either.right(deploymentValidationResult.right().value());
}
} else {
- artifactInfo.setTimeout(NON_HEAT_TIMEOUT);
+ artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
/*
* if (informationDeployedArtifactsBusinessLogic. isInformationDeployedArtifact(artifactInfo)) { Either<Boolean, ResponseFormat> validationResult = informationDeployedArtifactsBusinessLogic.validateArtifact( isCreate, artifactInfo,
@@ -817,6 +1033,66 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return Either.left(artifactInfo);
}
+ private Either<ArtifactDefinition, ResponseFormat> findArtifactOnParentComponent(Component parentComponent, String parentId, ArtifactOperationInfo operation, String artifactId) {
+
+ Either<ArtifactDefinition, ResponseFormat> result = null;
+ ArtifactDefinition foundArtifact = null;
+ if (StringUtils.isNotEmpty(artifactId)) {
+ if (parentComponent.getUniqueId().equals(parentId)) {
+ if (parentComponent.getDeploymentArtifacts() != null) {
+ foundArtifact = parentComponent.getDeploymentArtifacts().values().stream().filter(e -> e.getUniqueId().equals(artifactId)).findFirst().orElse(null);
+ }
+ if (foundArtifact == null && parentComponent.getArtifacts() != null) {
+ foundArtifact = parentComponent.getArtifacts().values().stream().filter(e -> e.getUniqueId().equals(artifactId)).findFirst().orElse(null);
+ }
+ } else {
+ ComponentInstance instance = findComponentInstance(parentId, parentComponent);
+ if (instance.getDeploymentArtifacts() != null) {
+ foundArtifact = instance.getDeploymentArtifacts().values().stream().filter(e -> e.getUniqueId().equals(artifactId)).findFirst().orElse(null);
+ }
+ if (foundArtifact == null && instance.getArtifacts() != null) {
+ foundArtifact = instance.getArtifacts().values().stream().filter(e -> e.getUniqueId().equals(artifactId)).findFirst().orElse(null);
+ }
+ }
+ }
+ if (foundArtifact != null && operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create) {
+ log.debug("Artifact {} already exist", artifactId);
+ result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, foundArtifact.getArtifactLabel()));
+ }
+ if (foundArtifact == null && operation.getArtifactOperationEnum() != ArtifactOperationEnum.Create) {
+ log.debug("The artifact {} was not found on parent {}. ", artifactId, parentId);
+ result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ""));
+ }
+ if (result == null) {
+ result = Either.left(foundArtifact);
+ }
+ return result;
+ }
+
+ private Either<Boolean, ResponseFormat> validateInformationalArtifact(ArtifactDefinition artifactInfo, Component parentComponent) {
+ ComponentTypeEnum parentComponentType = parentComponent.getComponentType();
+ ArtifactGroupTypeEnum groupType = artifactInfo.getArtifactGroupType();
+ Either<Boolean, ResponseFormat> validationResult = Either.left(true);
+ ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
+ if (artifactType == null) {
+ validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType()));
+ } else if (parentComponentType == ComponentTypeEnum.RESOURCE && groupType == ArtifactGroupTypeEnum.INFORMATIONAL) {
+ String artifactTypeName = artifactType.getType();
+ ResourceTypeEnum parentResourceType = ((Resource) parentComponent).getResourceType();
+ Map<String, ArtifactTypeConfig> resourceInformationalArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceInformationalArtifacts();
+ Set<String> validArtifactTypes = resourceInformationalArtifacts.keySet();
+ if (!validArtifactTypes.contains(artifactTypeName)) {
+ validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactTypeName));
+ } else {
+ List<String> validResourceType = resourceInformationalArtifacts.get(artifactTypeName).getValidForResourceTypes();
+ if (!validResourceType.contains(parentResourceType.name())) {
+ validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactTypeName));
+ }
+ }
+ }
+ return validationResult;
+ }
+
private NodeTypeEnum convertParentType(ComponentTypeEnum componentType) {
if (componentType.equals(ComponentTypeEnum.RESOURCE)) {
return NodeTypeEnum.Resource;
@@ -829,128 +1105,303 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete(String parentId, String artifactId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent,
String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
+
NodeTypeEnum parentType = convertParentType(componentType);
- // lock resource
- if (shouldLock) {
- Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Delete Artifact - lock resource: ");
- if (lockComponent.isRight()) {
- handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right().value(), componentType, null);
- return Either.right(lockComponent.right().value());
- }
- }
Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
- Either<ArtifactDefinition, Operation> insideEither = null;
- StorageOperationStatus error = null;
- boolean isLeft = false;
- ArtifactDefinition artifactDefinition = null;
- Integer artifactParentsCount = 1;
+ Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> getArtifactRes = null;
+ ArtifactDefinition foundArtifact = null;
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
+ Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getContainerRes = null;
+ org.openecomp.sdc.be.model.Component fetchedContainerComponent = null;
+ boolean isDuplicated = false;
+ String esId = null;
+ Either<Boolean, StorageOperationStatus> needCloneRes = null;
try {
- if (interfaceType != null && operationName != null) {
- log.debug("Try to delete inteface lifecycle artifact {}", artifactId);
-
- Either<Operation, StorageOperationStatus> result = interfaceLifecycleOperation.deleteInterfaceOperation(parentId, interfaceType, UniqueIdBuilder.buildOperationByInterfaceUniqueId(parentId, interfaceType, operationName),
- inTransaction);
- isLeft = result.isLeft();
- if (isLeft) {
- artifactDefinition = result.left().value().getImplementation();
- insideEither = Either.right(result.left().value());
+ if (shouldLock) {
+ Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Delete Artifact - lock resource: ");
+ if (lockComponent.isRight()) {
+ handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right().value(), componentType, null);
+ resultOp = Either.right(lockComponent.right().value());
}
- } else {
- log.debug("Try to delete artifact, get parents {}", artifactId);
-
- Either<Integer, StorageOperationStatus> parentsOfArtifact = artifactOperation.getParentsOfArtifact(artifactId, parentType);
- if (parentsOfArtifact.isRight()) {
- log.debug("Failed to delete entry on graph for artifact {}", artifactId);
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(parentsOfArtifact.right().value()), "");
+ }
+ if (resultOp == null) {
+ log.debug("Going to fetch the container component {}. ", parent.getUniqueId());
+ getContainerRes = toscaOperationFacade.getToscaElement(parent.getUniqueId());
+ if (getContainerRes.isRight()) {
+ log.debug("Failed to fetch the container component {}. ", parentId);
+ responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(getContainerRes.right().value()), artifactId);
+ handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
+ resultOp = Either.right(responseFormat);
+ }
+ }
+ if (resultOp == null) {
+ fetchedContainerComponent = getContainerRes.left().value();
+ log.debug("Going to find the artifact {} on the component {}", artifactId, fetchedContainerComponent.getUniqueId());
+ getArtifactRes = findArtifact(artifactId, fetchedContainerComponent, parentId, componentType);
+ if (getArtifactRes.isRight()) {
+ log.debug("Failed to find the artifact {} belonging to {} on the component {}", artifactId, parentId, fetchedContainerComponent.getUniqueId());
+ responseFormat = componentsUtils.getResponseFormatByArtifactId(getArtifactRes.right().value(), artifactId);
+ handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
resultOp = Either.right(responseFormat);
} else {
-
- artifactParentsCount = parentsOfArtifact.left().value();
- log.debug("Number of parents nodes on graph for artifact {} is {}", artifactId, artifactParentsCount);
-
- Either<ArtifactDefinition, StorageOperationStatus> result = artifactOperation.removeArifactFromResource(parentId, artifactId, parentType, false, true);
- isLeft = result.isLeft();
- if (isLeft) {
- log.debug("Artifact removed from graph {}", artifactId);
-
- artifactDefinition = result.left().value();
- insideEither = Either.left(result.left().value());
- } else {
- error = result.right().value();
- }
+ foundArtifact = getArtifactRes.left().value().getLeft();
+ esId = foundArtifact.getEsId();
}
}
-
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
- if (isLeft) {
- StorageOperationStatus deleteIfNotOnGraph = StorageOperationStatus.OK;
- if (artifactParentsCount < 2) {
- log.debug("Number of parent nodes is 1. Need to delete from ES {}", artifactId);
- deleteIfNotOnGraph = deleteIfNotOnGraph(artifactId, artifactDefinition.getEsId(), true);
+ if (resultOp == null && StringUtils.isNotEmpty(esId)) {
+ needCloneRes = artifactToscaOperation.isCloneNeeded(parent.getUniqueId(), foundArtifact, convertParentType(parent.getComponentType()));
+ if (needCloneRes.isRight()) {
+ log.debug("Failed to delete or update the artifact {}. Parent uniqueId is {}", artifactId, parentId);
+ responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(needCloneRes.right().value()), foundArtifact.getArtifactDisplayName());
+ handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
+ resultOp = Either.right(responseFormat);
}
- if (deleteIfNotOnGraph.equals(StorageOperationStatus.OK)) {
- if (artifactDefinition.getMandatory() || artifactDefinition.getServiceApi()) {
- log.debug("Artifact is mandatory or service API. Clean all fields for {}", artifactId);
- artifactDefinition.setEsId("");
- artifactDefinition.setArtifactName("");
- artifactDefinition.setDescription("");
- artifactDefinition.setApiUrl("");
- artifactDefinition.setArtifactChecksum("");
- setDefaultArtifactTimeout(artifactDefinition.getArtifactGroupType(), artifactDefinition);
- artifactDefinition.setArtifactUUID("");
- long time = System.currentTimeMillis();
- artifactDefinition.setPayloadUpdateDate(time);
- artifactDefinition.setHeatParameters(null);
- artifactDefinition.setHeatParamsUpdateDate(null);
- Either<ArtifactDefinition, StorageOperationStatus> resStatus = null;
- if (artifactParentsCount < 2) {
- log.debug("Only one parent , clean existing placeholder for {}", artifactId);
- resStatus = artifactOperation.updateArifactOnResource(artifactDefinition, parentId, artifactId, parentType, true);
- } else {
- log.debug("more than one parent , create new placeholder for {}", artifactId);
- artifactDefinition.setUniqueId(null);
- resStatus = artifactOperation.addArifactToComponent(artifactDefinition, parentId, parentType, true, true);
- }
- if (resStatus.isRight()) {
- log.debug("Failed to clean placeholder for {}", artifactId);
- responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(resStatus.right().value()), artifactDefinition.getArtifactDisplayName());
- resultOp = Either.right(responseFormat);
- } else {
- log.debug("Placeholder was cleaned for {}", artifactId);
+ }
+ if (resultOp == null) {
+ Either<ArtifactDataDefinition, StorageOperationStatus> updatedArtifactRes = deleteOrUpdateArtifactOnGraph(parent, parentId, artifactId, parentType, foundArtifact, needCloneRes.left().value());
+ if (updatedArtifactRes.isRight()) {
+ log.debug("Failed to delete or update the artifact {}. Parent uniqueId is {}", artifactId, parentId);
+ responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updatedArtifactRes.right().value()), foundArtifact.getArtifactDisplayName());
+ handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
+ resultOp = Either.right(responseFormat);
+ } else {
+ isDuplicated = updatedArtifactRes.left().value().getDuplicated();
+ }
+ }
- ArtifactDefinition artifactUfterChange = resStatus.left().value();
+ if (resultOp == null && (!needCloneRes.left().value() && !isDuplicated)) {
+ log.debug("Going to delete the artifact {} from the database. ", artifactId);
+ CassandraOperationStatus cassandraStatus = artifactCassandraDao.deleteArtifact(esId);
+ if (cassandraStatus != CassandraOperationStatus.OK) {
+ log.debug("Failed to delete the artifact {} from the database. ", artifactId);
+ responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(convertToStorageOperationStatus(cassandraStatus)), foundArtifact.getArtifactDisplayName());
+ handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
+ resultOp = Either.right(responseFormat);
+ }
+ }
+ if (resultOp == null && componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
- insideEither = Either.left(artifactUfterChange);
- resultOp = Either.left(insideEither);
- }
- } else {
- log.debug("Artifact isn't mandatory/service API. Removed. {}", artifactId);
- resultOp = Either.left(insideEither);
+ List<GroupInstance> updatedGroupInstances = getUpdatedGroupInstances(artifactId, foundArtifact, getArtifactRes.left().value().getRight().getGroupInstances());
+ if (CollectionUtils.isNotEmpty(updatedGroupInstances)) {
+ Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(fetchedContainerComponent, componentType, parentId, updatedGroupInstances);
+ if (status.isRight()) {
+ log.debug("Failed to update groups of the component {}. ", fetchedContainerComponent.getUniqueId());
+ responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status.right().value()), foundArtifact.getArtifactDisplayName());
+ handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
+ resultOp = Either.right(responseFormat);
}
-
- } else {
- log.debug("failed to delete artifact from ES {} status {}", artifactId, deleteIfNotOnGraph);
- responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(deleteIfNotOnGraph), artifactDefinition.getArtifactDisplayName());
+ }
+ }
+ if (resultOp == null && componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
+ StorageOperationStatus status = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType);
+ if (status != StorageOperationStatus.OK) {
+ log.debug("Failed to generate new customization UUID for the component instance {}. ", parentId);
+ responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status), foundArtifact.getArtifactDisplayName());
+ handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
resultOp = Either.right(responseFormat);
}
- } else {
- log.debug("Failed to delete entry on graph for artifact {}", artifactId);
- responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(error), "");
- resultOp = Either.right(responseFormat);
}
- handleAuditing(auditingAction, parent, parentId, user, artifactDefinition, null, artifactId, responseFormat, componentType, null);
+ if (resultOp == null && componentType != ComponentTypeEnum.RESOURCE_INSTANCE) {
+ List<GroupDataDefinition> updatedGroups = getUpdatedGroups(artifactId, foundArtifact, fetchedContainerComponent.getGroups());
+ if (CollectionUtils.isNotEmpty(updatedGroups)) {
+ Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(fetchedContainerComponent, componentType, updatedGroups);
+ if (status.isRight()) {
+ log.debug("Failed to update groups of the component {}. ", fetchedContainerComponent.getUniqueId());
+ responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status.right().value()), foundArtifact.getArtifactDisplayName());
+ handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
+ resultOp = Either.right(responseFormat);
+ }
+ }
+ }
+ if (resultOp == null) {
+ resultOp = Either.left(Either.left(foundArtifact));
+ handleAuditing(auditingAction, parent, parentId, user, foundArtifact, null, artifactId, responseFormat, componentType, null);
+ }
return resultOp;
} finally {
if (shouldLock) {
unlockComponent(resultOp, parent, inTransaction);
}
}
+ }
+ private List<GroupDataDefinition> getUpdatedGroups(String artifactId, ArtifactDefinition foundArtifact, List<GroupDefinition> groups) {
+ List<GroupDataDefinition> updatedGroups = new ArrayList<>();
+ boolean isUpdated = false;
+ if (groups != null) {
+ for (GroupDefinition group : groups) {
+ isUpdated = false;
+ if (CollectionUtils.isNotEmpty(group.getArtifacts()) && group.getArtifacts().contains(artifactId)) {
+ group.getArtifacts().remove(artifactId);
+ isUpdated = true;
+ }
+ if (CollectionUtils.isNotEmpty(group.getArtifactsUuid()) && group.getArtifactsUuid().contains(foundArtifact.getArtifactUUID())) {
+ group.getArtifacts().remove(foundArtifact.getArtifactUUID());
+ isUpdated = true;
+ }
+ if (isUpdated) {
+ updatedGroups.add(group);
+ }
+ }
+ }
+ return updatedGroups;
+ }
+
+ private List<GroupInstance> getUpdatedGroupInstances(String artifactId, ArtifactDefinition foundArtifact, List<GroupInstance> groupInstances) {
+ List<GroupInstance> updatedGroupInstances = new ArrayList<>();
+ if (CollectionUtils.isNotEmpty(groupInstances)) {
+ boolean isUpdated = false;
+ for (GroupInstance groupInstance : groupInstances) {
+ isUpdated = false;
+ if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifacts()) && groupInstance.getGroupInstanceArtifacts().contains(artifactId)) {
+ groupInstance.getArtifacts().remove(artifactId);
+ isUpdated = true;
+ }
+ if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifactsUuid()) && groupInstance.getGroupInstanceArtifactsUuid().contains(foundArtifact.getArtifactUUID())) {
+ groupInstance.getArtifacts().remove(foundArtifact.getArtifactUUID());
+ isUpdated = true;
+ }
+ if (isUpdated) {
+ updatedGroupInstances.add(groupInstance);
+ }
+ }
+ }
+ return updatedGroupInstances;
+ }
+
+ private Either<ArtifactDataDefinition, StorageOperationStatus> deleteOrUpdateArtifactOnGraph(Component component, String parentId, String artifactId, NodeTypeEnum parentType, ArtifactDefinition foundArtifact, Boolean cloneIsNeeded) {
+
+ Either<ArtifactDataDefinition, StorageOperationStatus> result;
+ boolean isMandatory = foundArtifact.getMandatory() || foundArtifact.getServiceApi();
+ String componentId = component.getUniqueId();
+ String instanceId = componentId.equals(parentId) ? null : parentId;
+ if (isMandatory) {
+ log.debug("Going to update mandatory artifact {} from the component {}", artifactId, parentId);
+ resetMandatoryArtifactFields(foundArtifact);
+ result = artifactToscaOperation.updateArtifactOnGraph(componentId, foundArtifact, parentType, artifactId, instanceId);
+ } else if (cloneIsNeeded) {
+ log.debug("Going to clone artifacts and to delete the artifact {} from the component {}", artifactId, parentId);
+ result = artifactToscaOperation.deleteArtifactWithClonnigOnGraph(componentId, foundArtifact, parentType, instanceId, false);
+ } else {
+ log.debug("Going to delete the artifact {} from the component {}", artifactId, parentId);
+ result = artifactToscaOperation.removeArtifactOnGraph(foundArtifact, componentId, instanceId, parentType, false);
+ }
+ return result;
+ }
+
+ private Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> findArtifact(String artifactId, Component fetchedContainerComponent, String parentId, ComponentTypeEnum componentType) {
+
+ Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> result = null;
+ Map<String, ArtifactDefinition> artifacts = new HashMap<>();
+ ComponentInstance foundInstance = null;
+ if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE && StringUtils.isNotEmpty(parentId)) {
+ Optional<ComponentInstance> componentInstanceOpt = fetchedContainerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(parentId)).findFirst();
+ if (!componentInstanceOpt.isPresent()) {
+ result = Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER);
+ } else {
+ foundInstance = componentInstanceOpt.get();
+ fetchArtifactsFromInstance(artifactId, artifacts, foundInstance);
+ }
+ } else {
+ fetchArtifactsFromComponent(artifactId, fetchedContainerComponent, artifacts);
+ }
+ if (result == null) {
+ if (artifacts.containsKey(artifactId)) {
+ result = Either.left(new ImmutablePair<>(artifacts.get(artifactId), foundInstance));
+ } else {
+ result = Either.right(ActionStatus.ARTIFACT_NOT_FOUND);
+ }
+ }
+ return result;
+ }
+
+ private void fetchArtifactsFromComponent(String artifactId, Component component, Map<String, ArtifactDefinition> artifacts) {
+ Map<String, ArtifactDefinition> currArtifacts;
+ if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getDeploymentArtifacts())) {
+ currArtifacts = component.getDeploymentArtifacts().values().stream().collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
+ if (MapUtils.isNotEmpty(currArtifacts)) {
+ artifacts.putAll(currArtifacts);
+ }
+ }
+ if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getArtifacts())) {
+ currArtifacts = component.getArtifacts().values().stream().collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
+ if (MapUtils.isNotEmpty(currArtifacts)) {
+ artifacts.putAll(currArtifacts);
+ }
+ }
+ if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getArtifacts())) {
+ currArtifacts = component.getToscaArtifacts().values().stream().collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
+ if (MapUtils.isNotEmpty(currArtifacts)) {
+ artifacts.putAll(currArtifacts);
+ }
+ }
+ }
+
+ private void fetchArtifactsFromInstance(String artifactId, Map<String, ArtifactDefinition> artifacts, ComponentInstance instance) {
+ Map<String, ArtifactDefinition> currArtifacts;
+ if (MapUtils.isNotEmpty(instance.getDeploymentArtifacts())) {
+ currArtifacts = instance.getDeploymentArtifacts().values().stream().collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
+ if (MapUtils.isNotEmpty(currArtifacts)) {
+ artifacts.putAll(currArtifacts);
+ }
+ }
+ if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(instance.getArtifacts())) {
+ currArtifacts = instance.getArtifacts().values().stream().collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
+ if (MapUtils.isNotEmpty(currArtifacts)) {
+ artifacts.putAll(currArtifacts);
+ }
+ }
+ }
+
+ private StorageOperationStatus convertToStorageOperationStatus(CassandraOperationStatus cassandraStatus) {
+ StorageOperationStatus result;
+ switch (cassandraStatus) {
+ case OK:
+ result = StorageOperationStatus.OK;
+ break;
+ case NOT_FOUND:
+ result = StorageOperationStatus.NOT_FOUND;
+ break;
+ case CLUSTER_NOT_CONNECTED:
+ case KEYSPACE_NOT_CONNECTED:
+ result = StorageOperationStatus.CONNECTION_FAILURE;
+ break;
+ default:
+ result = StorageOperationStatus.GENERAL_ERROR;
+ break;
+ }
+ return result;
+ }
+
+ private void resetMandatoryArtifactFields(ArtifactDefinition fetchedArtifact) {
+ if (fetchedArtifact != null) {
+ log.debug("Going to reset mandatory artifact {} fields. ", fetchedArtifact.getUniqueId());
+ fetchedArtifact.setEsId("");
+ fetchedArtifact.setArtifactName("");
+ fetchedArtifact.setDescription("");
+ fetchedArtifact.setApiUrl("");
+ fetchedArtifact.setArtifactChecksum("");
+ nodeTemplateOperation.setDefaultArtifactTimeout(fetchedArtifact.getArtifactGroupType(), fetchedArtifact);
+ fetchedArtifact.setArtifactUUID("");
+ long time = System.currentTimeMillis();
+ fetchedArtifact.setPayloadUpdateDate(time);
+ fetchedArtifact.setHeatParameters(null);
+ fetchedArtifact.setHeatParamsUpdateDate(null);
+ }
+ }
+
+ private StorageOperationStatus generateCustomizationUUIDOnInstance(String componentId, String instanceId, ComponentTypeEnum componentType) {
+ StorageOperationStatus error = StorageOperationStatus.OK;
+ if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
+ log.debug("Need to re-generate customization UUID for instance {}", instanceId);
+ error = toscaOperationFacade.generateCustomizationUUIDOnInstance(componentId, instanceId);
+ }
+ return error;
}
private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDownload(String componentId, String artifactId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType,
org.openecomp.sdc.be.model.Component parent, boolean shouldLock, boolean inTransaction) {
- Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactOperation.getArtifactById(artifactId, false);
+ Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(componentId, artifactId, componentType, parent.getUniqueId());
if (artifactById.isRight()) {
ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(artifactById.right().value());
log.debug("Error when getting artifact info by id{}, error: {}", artifactId, actionStatus.name());
@@ -971,16 +1422,15 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return Either.left(insideEither);
}
- private Either<ArtifactDefinition, ResponseFormat> fetchCurrentArtifact(ArtifactOperation operation, String artifactId) {
- Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactOperation.getArtifactById(artifactId, true);
- if (!operation.equals(ArtifactOperation.Create) && artifactById.isRight()) {
+ private Either<ArtifactDefinition, ResponseFormat> fetchCurrentArtifact(String parentId, ArtifactOperationInfo operation, String artifactId) {
+ Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(parentId, artifactId);
+ if (!(operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create) && artifactById.isRight()) {
// in case of update artifact must be
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeArtifactMissingError, "Artifact Update / Upload", artifactId);
BeEcompErrorManager.getInstance().logBeArtifactMissingError("Artifact Update / Upload", artifactId);
log.debug("Failed to fetch artifact {}. error: {}", artifactId, artifactById.right().value());
return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(artifactById.right().value()), artifactId));
}
- if (operation.equals(ArtifactOperation.Create) && artifactById.isLeft()) {
+ if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create && artifactById.isLeft()) {
log.debug("Artifact {} already exist", artifactId);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactById.left().value().getArtifactLabel()));
}
@@ -992,17 +1442,16 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return Either.left(currentArtifactInfo);
}
- private Either<ActionStatus, ResponseFormat> handleArtifactLabel(String componentId, ArtifactOperation operation, String artifactId, ArtifactDefinition artifactInfo, String interfaceName, String operationName,
+ private Either<ActionStatus, ResponseFormat> handleArtifactLabel(String componentId, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String interfaceName, String operationName,
ArtifactDefinition currentArtifactInfo, ComponentTypeEnum componentType, boolean inTransaction) {
String artifactLabel = artifactInfo.getArtifactLabel();
if (operationName == null && (artifactInfo.getArtifactLabel() == null || artifactInfo.getArtifactLabel().isEmpty())) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeMissingArtifactInformationError, "Artifact Update / Upload", "artifactLabel");
BeEcompErrorManager.getInstance().logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel");
log.debug("missing artifact logical name for component {}", componentId);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL));
}
- if (operation.equals(ArtifactOperation.Create) && !artifactInfo.getMandatory()) {
+ if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create && !artifactInfo.getMandatory()) {
if (operationName != null) {
if (artifactInfo.getArtifactLabel() != null && !operationName.equals(artifactInfo.getArtifactLabel())) {
@@ -1016,6 +1465,10 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
if (displayName == null || displayName.isEmpty())
displayName = artifactLabel;
displayName = ValidationUtils.cleanArtifactDisplayName(displayName);
+ // if (!ValidationUtils.validateArtifactDisplayName(displayName)) {
+ // log.debug("Invalid format form Artifact displayName : {}", displayName);
+ // return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
+ // }
artifactInfo.setArtifactDisplayName(displayName);
if (!ValidationUtils.validateArtifactLabel(artifactLabel)) {
@@ -1033,7 +1486,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
log.debug("Invalid lenght form Artifact label : {}", artifactLabel);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_LABEL, String.valueOf(ValidationUtils.ARTIFACT_LABEL_LENGTH)));
}
- if (!validateLabelUniqueness(componentId, artifactLabel, componentType, inTransaction)) {
+ if (!validateLabelUniqueness(componentId, artifactLabel, componentType)) {
log.debug("Non unique Artifact label : {}", artifactLabel);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactLabel));
}
@@ -1041,21 +1494,19 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
artifactInfo.setArtifactLabel(artifactLabel);
if (currentArtifactInfo != null && !currentArtifactInfo.getArtifactLabel().equals(artifactInfo.getArtifactLabel())) {
- log.info("Logical artifact's name cannot be changed {}", artifactId);
+ log.info("Logical artifact's name cannot be changed {}", artifactId);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_LOGICAL_NAME_CANNOT_BE_CHANGED));
}
return Either.left(ActionStatus.OK);
}
- private boolean validateLabelUniqueness(String parentId, String artifactLabel, ComponentTypeEnum componentType, boolean inTransaction) {
+ private boolean validateLabelUniqueness(String parentId, String artifactLabel, ComponentTypeEnum componentType) {
boolean isUnique = true;
- NodeTypeEnum parentType;
if (componentType.equals(ComponentTypeEnum.RESOURCE)) {
- parentType = NodeTypeEnum.Resource;
} else {
- parentType = NodeTypeEnum.Service;
}
- Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts = artifactOperation.getArtifacts(parentId, parentType, inTransaction);
+ // Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts = artifactOperation.getArtifacts(parentId, parentType, inTransaction);
+ Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts = artifactToscaOperation.getArtifacts(parentId);
if (artifacts.isLeft()) {
for (String label : artifacts.left().value().keySet()) {
if (label.equals(artifactLabel)) {
@@ -1065,10 +1516,10 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
}
if (componentType.equals(ComponentTypeEnum.RESOURCE)) {
- Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation.getAllInterfacesOfResource(parentId, true, inTransaction);
+ Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation.getAllInterfacesOfResource(parentId, true, true);
if (allInterfacesOfResource.isLeft()) {
for (InterfaceDefinition interace : allInterfacesOfResource.left().value().values()) {
- for (Operation operation : interace.getOperations().values()) {
+ for (Operation operation : interace.getOperationsMap().values()) {
if (operation.getImplementation() != null && operation.getImplementation().getArtifactLabel().equals(artifactLabel)) {
isUnique = false;
break;
@@ -1088,9 +1539,14 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
ESArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload);
Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
Either<ArtifactDefinition, Operation> insideEither = null;
-
+ ComponentInstance foundInstance = findComponentInstance(parentId, parent);
+ String instanceId = null;
+ String instanceName = null;
+ if (foundInstance != null) {
+ instanceId = foundInstance.getUniqueId();
+ instanceName = foundInstance.getName();
+ }
if (artifactData == null) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError, "Upload Artifact");
BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact");
log.debug("Failed to create artifact object for ES.");
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
@@ -1104,7 +1560,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
boolean isLeft = false;
String artifactUniqueId = null;
- ArtifactDefinition artifactDefinition = null;
StorageOperationStatus error = null;
if (interfaceType != null && operationName != null) {
// lifecycle artifact
@@ -1115,7 +1570,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
isLeft = result.isLeft();
if (isLeft) {
artifactUniqueId = result.left().value().getImplementation().getUniqueId();
- artifactDefinition = result.left().value().getImplementation();
+ result.left().value().getImplementation();
insideEither = Either.right(result.left().value());
resultOp = Either.left(insideEither);
@@ -1124,17 +1579,23 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
} else {
// information/deployment/api aritfacts
- log.debug("Try to create entry on graph");
+ log.trace("Try to create entry on graph");
NodeTypeEnum nodeType = convertParentType(componentTypeEnum);
- Either<ArtifactDefinition, StorageOperationStatus> result = artifactOperation.addArifactToComponent(artifactInfo, parentId, nodeType, true, true);
+ Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.addArifactToComponent(artifactInfo, parent.getUniqueId(), nodeType, true, instanceId);
isLeft = result.isLeft();
if (isLeft) {
artifactUniqueId = result.left().value().getUniqueId();
- artifactDefinition = result.left().value();
+ result.left().value();
insideEither = Either.left(result.left().value());
resultOp = Either.left(insideEither);
+
+ error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentTypeEnum);
+ if (error != StorageOperationStatus.OK) {
+ isLeft = false;
+ }
+
} else {
error = result.right().value();
}
@@ -1147,14 +1608,13 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
log.debug("Artifact saved into ES - {}", artifactUniqueId);
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
- handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, artifactUniqueId, artifactUniqueId, responseFormat, componentTypeEnum, null);
+ handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, artifactUniqueId, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
return resultOp;
} else {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError, "Upload Artifact");
BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact");
log.debug("Failed to save the artifact.");
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
- handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, artifactUniqueId, responseFormat, componentTypeEnum, null);
+ handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
resultOp = Either.right(responseFormat);
return resultOp;
@@ -1162,13 +1622,21 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
} else {
log.debug("Failed to create entry on graph for artifact {}", artifactInfo.getArtifactName());
ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(error), artifactInfo.getArtifactDisplayName());
- handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, null);
+ handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, instanceName);
resultOp = Either.right(responseFormat);
return resultOp;
}
}
+ private ComponentInstance findComponentInstance(String componentInstanceId, Component containerComponent) {
+ ComponentInstance foundInstance = null;
+ if (CollectionUtils.isNotEmpty(containerComponent.getComponentInstances())) {
+ foundInstance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(componentInstanceId)).findFirst().orElse(null);
+ }
+ return foundInstance;
+ }
+
private Either<Boolean, ResponseFormat> validateDeploymentArtifact(Component parentComponent, String parentId, String userId, boolean isCreate, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, NodeTypeEnum parentType) {
Either<Boolean, ResponseFormat> result = Either.left(true);
@@ -1178,7 +1646,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
- Map<String, DeploymentArtifactTypeConfig> resourceDeploymentArtifacts = fillDeploymentArtifactTypeConf(parentType);
+ Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts = fillDeploymentArtifactTypeConf(parentType);
if (responseWrapper.isEmpty()) {
validateDeploymentArtifactConf(artifactInfo, responseWrapper, artifactType, resourceDeploymentArtifacts);
@@ -1199,7 +1667,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
// if (parentComponent instanceof Resource) {
Resource resource = (Resource) parentComponent;
ResourceTypeEnum resourceType = resource.getResourceType();
- DeploymentArtifactTypeConfig config = resourceDeploymentArtifacts.get(artifactType.getType());
+ ArtifactTypeConfig config = resourceDeploymentArtifacts.get(artifactType.getType());
if (config == null) {
responseWrapper.setInnerElement(ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType()));
} else {
@@ -1232,7 +1700,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
case HEAT_ENV: {
result = validateHeatEnvDeploymentArtifact(parentComponent, parentId, userId, isCreate, artifactInfo, parentType);
- artifactInfo.setTimeout(NON_HEAT_TIMEOUT);
+ artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
break;
}
case DCAE_INVENTORY_TOSCA:
@@ -1244,7 +1712,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
case DCAE_INVENTORY_EVENT:
// No specific validation
default: {
- artifactInfo.setTimeout(NON_HEAT_TIMEOUT);
+ artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
}
}
@@ -1256,7 +1724,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return result;
}
- private void validateDeploymentArtifactConf(ArtifactDefinition artifactInfo, Wrapper<ResponseFormat> responseWrapper, ArtifactTypeEnum artifactType, Map<String, DeploymentArtifactTypeConfig> resourceDeploymentArtifacts) {
+ private void validateDeploymentArtifactConf(ArtifactDefinition artifactInfo, Wrapper<ResponseFormat> responseWrapper, ArtifactTypeEnum artifactType, Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts) {
if ((resourceDeploymentArtifacts == null) || !resourceDeploymentArtifacts.containsKey(artifactType.name())) {
ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType());
responseWrapper.setInnerElement(responseFormat);
@@ -1264,8 +1732,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
}
- private Map<String, DeploymentArtifactTypeConfig> fillDeploymentArtifactTypeConf(NodeTypeEnum parentType) {
- Map<String, DeploymentArtifactTypeConfig> resourceDeploymentArtifacts = null;
+ private Map<String, ArtifactTypeConfig> fillDeploymentArtifactTypeConf(NodeTypeEnum parentType) {
+ Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts = null;
if (parentType.equals(NodeTypeEnum.Resource)) {
resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceDeploymentArtifacts();
} else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
@@ -1279,14 +1747,14 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
public void validateArtifactTypeExists(Wrapper<ResponseFormat> responseWrapper, ArtifactDefinition artifactInfo) {
ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
if (artifactType == null) {
- ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.GENERAL_ERROR);
+ ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType());
responseWrapper.setInnerElement(responseFormat);
log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType());
}
}
- private DeploymentArtifactTypeConfig getDeploymentArtifactTypeConfig(NodeTypeEnum parentType, ArtifactTypeEnum artifactType) {
- DeploymentArtifactTypeConfig retConfig = null;
+ private ArtifactTypeConfig getDeploymentArtifactTypeConfig(NodeTypeEnum parentType, ArtifactTypeEnum artifactType) {
+ ArtifactTypeConfig retConfig = null;
String fileType = artifactType.getType();
if (parentType.equals(NodeTypeEnum.Resource)) {
retConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceDeploymentArtifacts().get(fileType);
@@ -1301,14 +1769,14 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
private Either<Boolean, ResponseFormat> extractHeatParameters(ArtifactDefinition artifactInfo) {
// extract heat parameters
if (artifactInfo.getPayloadData() != null) {
- String heatDecodedPayload = GeneralUtility.isBase64Encoded(artifactInfo.getPayloadData()) ? new String(Base64.decodeBase64(artifactInfo.getPayloadData())) : new String(artifactInfo.getPayloadData());
+ String heatDecodedPayload = new String(Base64.decodeBase64(artifactInfo.getPayloadData()));
Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParamsWithoutImplicitTypes(heatDecodedPayload, artifactInfo.getArtifactType());
if (heatParameters.isRight() && (!heatParameters.right().value().equals(ResultStatusEnum.ELEMENT_NOT_FOUND))) {
log.info("failed to parse heat parameters ");
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo.getArtifactType());
return Either.right(responseFormat);
} else if (heatParameters.isLeft() && heatParameters.left().value() != null) {
- artifactInfo.setHeatParameters(heatParameters.left().value());
+ artifactInfo.setListHeatParameters(heatParameters.left().value());
}
}
return Either.left(true);
@@ -1319,7 +1787,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
public void validateFileExtension(Wrapper<ResponseFormat> responseWrapper, IDeploymentArtifactTypeConfigGetter deploymentConfigGetter, ArtifactDefinition artifactInfo, NodeTypeEnum parentType, ArtifactTypeEnum artifactType) {
String fileType = artifactType.getType();
List<String> acceptedTypes = null;
- DeploymentArtifactTypeConfig deploymentAcceptedTypes = deploymentConfigGetter.getDeploymentArtifactConfig();
+ ArtifactTypeConfig deploymentAcceptedTypes = deploymentConfigGetter.getDeploymentArtifactConfig();
if (!parentType.equals(NodeTypeEnum.Resource) && !parentType.equals(NodeTypeEnum.Service) && !parentType.equals(NodeTypeEnum.ResourceInstance)) {
log.debug("parent type of artifact can be either resource or service");
responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -1365,13 +1833,13 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
if (errorWrapper.isEmpty()) {
// Validate Heat Exist
- validateHeatExist(artifactInfo.getUniqueId(), errorWrapper, heatMDWrapper, getDeploymentArtifacts(parentComponent, parentType, parentId));
+ validateHeatExist(parentComponent.getUniqueId(), parentId, errorWrapper, heatMDWrapper, artifactInfo, parentType, parentComponent.getComponentType());
}
- if (errorWrapper.isEmpty() && isCreate) {
- // Validate Only Single HeatEnv Artifact
- validateSingleArtifactType(errorWrapper, ArtifactTypeEnum.HEAT_ENV, parentComponent, parentType, parentId);
- }
+ // if (errorWrapper.isEmpty() && isCreate) {
+ // // Validate Only Single HeatEnv Artifact
+ // validateSingleArtifactType(errorWrapper, ArtifactTypeEnum.HEAT_ENV, parentComponent, parentType, parentId);
+ // }
if (errorWrapper.isEmpty() && !heatMDWrapper.isEmpty()) {
fillArtifactPayloadValidation(errorWrapper, payloadWrapper, heatMDWrapper.getInnerElement());
@@ -1406,13 +1874,9 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
public Either<Boolean, ResponseFormat> fillArtifactPayload(Wrapper<byte[]> payloadWrapper, ArtifactDefinition artifactMD) {
Either<Boolean, ResponseFormat> result = Either.left(true);
Either<ESArtifactData, CassandraOperationStatus> eitherArtifactData = artifactCassandraDao.getArtifact(artifactMD.getEsId());
- // Either<ESArtifactData, ResourceUploadStatus> eitherArtifactData =
- // esCatalogDao.getArtifact(artifactMD.getEsId());
if (eitherArtifactData.isLeft()) {
byte[] data = eitherArtifactData.left().value().getDataAsArray();
- if (!GeneralUtility.isBase64Encoded(data)) {
- data = Base64.encodeBase64(data);
- }
+ data = Base64.encodeBase64(data);
payloadWrapper.setInnerElement(data);
} else {
StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(eitherArtifactData.right().value());
@@ -1425,11 +1889,9 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
@SuppressWarnings("unchecked")
private void validateEnvVsHeat(Wrapper<ResponseFormat> errorWrapper, ArtifactDefinition envArtifact, ArtifactDefinition heatArtifact, byte[] heatPayloadData) {
-
- String envPayload = (GeneralUtility.isBase64Encoded(envArtifact.getPayloadData())) ? new String(Base64.decodeBase64(envArtifact.getPayloadData())) : new String(envArtifact.getPayloadData());
+ String envPayload = new String(Base64.decodeBase64(envArtifact.getPayloadData()));
Map<String, Object> heatEnvToscaJson = (Map<String, Object>) new Yaml().load(envPayload);
-
- String heatDecodedPayload = (GeneralUtility.isBase64Encoded(heatPayloadData)) ? new String(Base64.decodeBase64(heatPayloadData)) : new String(heatPayloadData);
+ String heatDecodedPayload = new String(Base64.decodeBase64(heatPayloadData));
Map<String, Object> heatToscaJson = (Map<String, Object>) new Yaml().load(heatDecodedPayload);
Either<Map<String, Object>, ResultStatusEnum> eitherHeatEnvProperties = ImportUtils.findFirstToscaMapElement(heatEnvToscaJson, ToscaTagNamesEnum.PARAMETERS);
@@ -1455,7 +1917,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
private void validateValidYaml(Wrapper<ResponseFormat> errorWrapper, ArtifactDefinition artifactInfo) {
YamlToObjectConverter yamlConvertor = new YamlToObjectConverter();
- boolean isYamlValid = yamlConvertor.isValidYaml(artifactInfo.getPayloadData());
+ boolean isYamlValid = yamlConvertor.isValidYamlEncoded64(artifactInfo.getPayloadData());
if (!isYamlValid) {
ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.INVALID_YAML, artifactInfo.getArtifactType());
errorWrapper.setInnerElement(responseFormat);
@@ -1463,12 +1925,14 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
}
+ @SuppressWarnings("restriction")
public boolean isValidXml(byte[] xmlToParse) {
XMLReader parser = new SAXParser();
boolean isXmlValid = true;
try {
parser.parse(new InputSource(new ByteArrayInputStream(xmlToParse)));
} catch (IOException | SAXException e) {
+ log.debug("Xml is invalid : {}", e.getMessage(), e);
isXmlValid = false;
}
return isXmlValid;
@@ -1479,6 +1943,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
try {
gson.fromJson(parsed, Object.class);
} catch (Exception e) {
+ log.debug("Json is invalid : {}", e.getMessage(), e);
return false;
}
return true;
@@ -1531,31 +1996,40 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
}
- private void validateHeatExist(String heatEnvId, Wrapper<ResponseFormat> errorWrapper, Wrapper<ArtifactDefinition> heatArtifactMDWrapper, Collection<ArtifactDefinition> parentDeploymentArtifacts) {
- boolean heatFound = false;
- Either<ArtifactDefinition, StorageOperationStatus> res = artifactOperation.getHeatArtifactByHeatEnvId(heatEnvId, true);
+ private void validateHeatExist(String componentId, String parentRiId, Wrapper<ResponseFormat> errorWrapper, Wrapper<ArtifactDefinition> heatArtifactMDWrapper, ArtifactDefinition heatEnvArtifact, NodeTypeEnum parentType,
+ ComponentTypeEnum componentType) {
+ Either<ArtifactDefinition, StorageOperationStatus> res = artifactToscaOperation.getHeatArtifactByHeatEnvId(parentRiId, heatEnvArtifact, parentType, componentId, componentType);
if (res.isRight()) {
+ ResponseFormat responseFormat;
+ if (res.right().value() == StorageOperationStatus.NOT_FOUND) {
+ responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT);
+ } else {
+ responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT);
+ }
+ errorWrapper.setInnerElement(responseFormat);
+
return;
}
ArtifactDefinition heatArtifact = res.left().value();
- Iterator<ArtifactDefinition> parentArtifactsItr = parentDeploymentArtifacts.iterator();
- while (!heatFound && parentArtifactsItr.hasNext()) {
- ArtifactDefinition currArtifact = parentArtifactsItr.next();
- if (heatArtifact.getUniqueId().equals(currArtifact.getUniqueId())) {
- heatFound = true;
- heatArtifactMDWrapper.setInnerElement(currArtifact);
- log.trace("In validateHeatExist found artifact {}", currArtifact);
- /*
- * ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(currArtifact.getArtifactType()); if(artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_VOL || artifactType == ArtifactTypeEnum.HEAT_NET){
- * heatFound = true; } if (heatFound) { heatArtifactMDWrapper.setInnerElement(currArtifact); }
- */
- }
- }
- if (!heatFound) {
- ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT);
- errorWrapper.setInnerElement(responseFormat);
- log.debug("Can't create heat env artifact because No heat Artifact exist.");
- }
+ heatArtifactMDWrapper.setInnerElement(heatArtifact);
+ // Iterator<ArtifactDefinition> parentArtifactsItr = parentDeploymentArtifacts.iterator();
+ // while (!heatFound && parentArtifactsItr.hasNext()) {
+ // ArtifactDefinition currArtifact = parentArtifactsItr.next();
+ // if (heatArtifact.getUniqueId().equals(currArtifact.getUniqueId())) {
+ // heatFound = true;
+ // heatArtifactMDWrapper.setInnerElement(currArtifact);
+ // log.trace("In validateHeatExist found artifact {}", currArtifact);
+ // /*
+ // * ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(currArtifact.getArtifactType()); if(artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_VOL || artifactType == ArtifactTypeEnum.HEAT_NET){
+ // * heatFound = true; } if (heatFound) { heatArtifactMDWrapper.setInnerElement(currArtifact); }
+ // */
+ // }
+ // }
+ // if (!heatFound) {
+ // ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT);
+ // errorWrapper.setInnerElement(responseFormat);
+ // log.debug("Can't create heat env artifact because No heat Artifact exist.");
+ // }
}
@@ -1563,7 +2037,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
log.trace("Started HEAT pre-payload validation for artifact {}", artifactInfo.getArtifactLabel());
// timeout > 0 for HEAT artifacts
Integer timeout = artifactInfo.getTimeout();
- Integer defaultTimeout = (isCreate) ? defaultHeatTimeout : currentArtifact.getTimeout();
+ Integer defaultTimeout = (isCreate) ? NodeTemplateOperation.getDefaultHeatTimeout() : currentArtifact.getTimeout();
if (timeout == null) {
artifactInfo.setTimeout(defaultTimeout);
// HEAT artifact but timeout is invalid
@@ -1594,7 +2068,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
private Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers(ArtifactDefinition artifactInfo, String artifactType) {
if (artifactInfo.getHeatParameters() != null) {
- for (HeatParameterDefinition heatParam : artifactInfo.getHeatParameters()) {
+ for (HeatParameterDefinition heatParam : artifactInfo.getListHeatParameters()) {
String parameterType = heatParam.getType();
HeatParameterType heatParameterType = HeatParameterType.isValidType(parameterType);
String artifactTypeStr = artifactType != null ? artifactType : ArtifactTypeEnum.HEAT.getType();
@@ -1605,7 +2079,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
StorageOperationStatus validateAndUpdateProperty = heatParametersOperation.validateAndUpdateProperty(heatParam);
if (validateAndUpdateProperty != StorageOperationStatus.OK) {
- log.debug("Heat parameter {} is invalid. Status is: {}", heatParam.getName(), validateAndUpdateProperty);
+ log.debug("Heat parameter {} is invalid. Status is {}", heatParam.getName(), validateAndUpdateProperty);
ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, artifactTypeStr, heatParam.getType(), heatParam.getName());
return Either.right(responseFormat);
@@ -1617,16 +2091,18 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
public List<ArtifactDefinition> getDeploymentArtifacts(Component parentComponent, NodeTypeEnum parentType, String ciId) {
List<ArtifactDefinition> deploymentArtifacts = new ArrayList<>();
- if (parentComponent.getDeploymentArtifacts() != null && ciId != null) {
- if (NodeTypeEnum.ResourceInstance == parentType) {
+ if (parentComponent.getDeploymentArtifacts() != null) {
+ if (NodeTypeEnum.ResourceInstance == parentType && ciId != null) {
Either<ComponentInstance, ResponseFormat> getRI = getRIFromComponent(parentComponent, ciId, null, null, null);
if (getRI.isRight()) {
return deploymentArtifacts;
}
ComponentInstance ri = getRI.left().value();
- deploymentArtifacts.addAll(ri.getDeploymentArtifacts().values());
- } else {
- deploymentArtifacts.addAll(parentComponent.getDeploymentArtifacts().values());
+ if(ri.getDeploymentArtifacts() != null){
+ deploymentArtifacts.addAll(ri.getDeploymentArtifacts().values());
+ }
+ } else if(parentComponent.getDeploymentArtifacts() !=null){
+ deploymentArtifacts.addAll(parentComponent.getDeploymentArtifacts().values());
}
}
return deploymentArtifacts;
@@ -1691,105 +2167,14 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
- private Either<ArtifactDefinition, ResponseFormat> fetchCurrentArtifact(boolean isCreate, String artifactId) {
- Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactOperation.getArtifactById(artifactId, true);
- if (isCreate == false && artifactById.isRight()) {
- // in case of update artifact must be
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeArtifactMissingError, "Artifact Update / Upload", artifactId);
- BeEcompErrorManager.getInstance().logBeArtifactMissingError("Artifact Update / Upload", artifactId);
- log.debug("Failed to fetch artifact {}. error: {}", artifactId, artifactById.right().value());
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(artifactById.right().value()), artifactId));
- }
- if (isCreate && artifactById.isLeft()) {
- log.debug("Artifact {} already exist", artifactId);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactById.left().value().getArtifactLabel()));
- }
- ArtifactDefinition currentArtifactInfo = null;
- if (artifactById.isLeft()) {
- // get previous value
- currentArtifactInfo = artifactById.left().value();
- }
- return Either.left(currentArtifactInfo);
- }
-
- private Either<ActionStatus, ResponseFormat> handleArtifactLabel(String resourceId, boolean isCreate, String artifactId, ArtifactDefinition artifactInfo, String interfaceName, String operationName, ArtifactDefinition currentArtifactInfo,
- NodeTypeEnum parentType) {
- String artifactLabel = artifactInfo.getArtifactLabel();
-
- if (operationName == null && (artifactInfo.getArtifactLabel() == null || artifactInfo.getArtifactLabel().isEmpty())) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeMissingArtifactInformationError, "Artifact Update / Upload", "artifactLabel");
- BeEcompErrorManager.getInstance().logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel");
- log.debug("missing artifact logical name for component {}", resourceId);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL));
- }
- if (isCreate && !artifactInfo.getMandatory()) {
-
- if (operationName != null) {
- if (artifactInfo.getArtifactLabel() != null && !operationName.equals(artifactInfo.getArtifactLabel())) {
- log.debug("artifact label cannot be set {}", artifactLabel);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_LOGICAL_NAME_CANNOT_BE_CHANGED));
- } else {
- artifactLabel = operationName;
- }
- }
- String displayName = ValidationUtils.cleanArtifactDisplayName(artifactLabel);
- artifactInfo.setArtifactDisplayName(displayName);
-
- if (!ValidationUtils.validateArtifactLabel(artifactLabel)) {
- log.debug("Invalid format form Artifact label : {}", artifactLabel);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
- }
- artifactLabel = ValidationUtils.normalizeArtifactLabel(artifactLabel);
-
- if (artifactLabel.isEmpty()) {
- log.debug("missing normalized artifact logical name for component {}", resourceId);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL));
- }
-
- if (!ValidationUtils.validateArtifactLabelLength(artifactLabel)) {
- log.debug("Invalid lenght form Artifact label : {}", artifactLabel);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_LABEL, String.valueOf(ValidationUtils.ARTIFACT_LABEL_LENGTH)));
- }
- if (!validateLabelUniqueness(resourceId, artifactLabel, parentType)) {
- log.debug("Non unique Artifact label : {}", artifactLabel);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactLabel));
- }
- }
- artifactInfo.setArtifactLabel(artifactLabel);
-
- if (currentArtifactInfo != null && !currentArtifactInfo.getArtifactLabel().equals(artifactInfo.getArtifactLabel())) {
- log.info("Logical artifact's name cannot be changed {}", artifactId);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_LOGICAL_NAME_CANNOT_BE_CHANGED));
- }
- return Either.left(ActionStatus.OK);
- }
-
- private boolean validateLabelUniqueness(String parentId, String artifactLabel, NodeTypeEnum parentType) {
- boolean isUnique = true;
- Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts = artifactOperation.getArtifacts(parentId, parentType, true);
- if (artifacts.isLeft()) {
- for (String label : artifacts.left().value().keySet()) {
- if (label.equals(artifactLabel)) {
- isUnique = false;
- break;
- }
- }
- }
- if (parentType.equals(NodeTypeEnum.Resource)) {
- Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation.getAllInterfacesOfResource(parentId, true);
- if (allInterfacesOfResource.isLeft()) {
- for (InterfaceDefinition interace : allInterfacesOfResource.left().value().values()) {
- for (Operation operation : interace.getOperations().values()) {
- if (operation.getImplementation() != null && operation.getImplementation().getArtifactLabel().equals(artifactLabel)) {
- isUnique = false;
- break;
- }
- }
- }
- }
- }
- return isUnique;
- }
+ /*
+ * private Either<ArtifactDefinition, ResponseFormat> fetchCurrentArtifact(boolean isCreate, String artifactId) { Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(artifactId); if (isCreate
+ * == false && artifactById.isRight()) { // in case of update artifact must be BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeArtifactMissingError, "Artifact Update / Upload", artifactId);
+ * BeEcompErrorManager.getInstance().logBeArtifactMissingError("Artifact Update / Upload", artifactId); log.debug("Failed to fetch artifact {}. error: {}", artifactId, artifactById.right().value()); return
+ * Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(artifactById.right().value()), artifactId)); } if (isCreate && artifactById.isLeft()) { log.debug("Artifact {} already exist", artifactId); return
+ * Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactById.left().value().getArtifactLabel())); } ArtifactDefinition currentArtifactInfo = null; if (artifactById.isLeft()) { // get previous value
+ * currentArtifactInfo = artifactById.left().value(); } return Either.left(currentArtifactInfo); }
+ */
private String composeArtifactId(String resourceId, String artifactId, ArtifactDefinition artifactInfo, String interfaceName, String operationName) {
String id = artifactId;
@@ -1812,7 +2197,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
private Either<ActionStatus, ResponseFormat> validateArtifactType(String userId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) {
if (artifactInfo.getArtifactType() == null || artifactInfo.getArtifactType().isEmpty()) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeMissingArtifactInformationError, "Artifact Upload / Update");
BeEcompErrorManager.getInstance().logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel");
log.debug("Missing artifact type for artifact {}", artifactInfo.getArtifactName());
return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_TYPE));
@@ -1829,7 +2213,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
allArtifactTypes = elementOperation.getAllArtifactTypes();
}
if (allArtifactTypes.isRight()) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeInvalidConfigurationError, "Artifact Upload / Update", "artifactTypes", allArtifactTypes.right().value().name());
BeEcompErrorManager.getInstance().logBeInvalidConfigurationError("Artifact Upload / Update", "artifactTypes", allArtifactTypes.right().value().name());
log.debug("Failed to retrieve list of suported artifact types. error: {}", allArtifactTypes.right().value());
return Either.right(componentsUtils.getResponseFormatByUserId(allArtifactTypes.right().value(), userId));
@@ -1844,7 +2227,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
if (!artifactTypeExist) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeInvalidTypeError, "Artifact Upload / Delete / Update - Not supported artifact type", artifactInfo.getArtifactType(), "Artifact " + artifactInfo.getArtifactName());
BeEcompErrorManager.getInstance().logBeInvalidTypeError("Artifact Upload / Delete / Update - Not supported artifact type", artifactInfo.getArtifactType(), "Artifact " + artifactInfo.getArtifactName());
log.debug("Not supported artifact type = {}", artifactInfo.getArtifactType());
return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType()));
@@ -1855,7 +2237,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
private Either<List<ArtifactType>, ActionStatus> getDeploymentArtifactTypes(String userId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) {
- Map<String, DeploymentArtifactTypeConfig> deploymentArtifacts = null;
+ Map<String, ArtifactTypeConfig> deploymentArtifacts = null;
List<ArtifactType> artifactTypes = new ArrayList<ArtifactType>();
if (parentType.equals(NodeTypeEnum.Service)) {
@@ -2016,7 +2398,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
artifactInfo.setArtifactUUID(currentArtifact.getArtifactUUID());
if ((artifactInfo.getHeatParameters() != null) && (currentArtifact.getHeatParameters() != null) && !artifactInfo.getHeatParameters().isEmpty() && !currentArtifact.getHeatParameters().isEmpty()) {
- checkAndSetUnupdatableHeatParams(artifactInfo.getHeatParameters(), currentArtifact.getHeatParameters());
+ checkAndSetUnupdatableHeatParams(artifactInfo.getListHeatParameters(), currentArtifact.getListHeatParameters());
}
}
@@ -2110,7 +2492,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
Either<ArtifactDefinition, Operation> insideEither = null;
if (artifactData == null) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError, "Update Artifact");
BeEcompErrorManager.getInstance().logBeDaoSystemError("Update Artifact");
log.debug("Failed to create artifact object for ES.");
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
@@ -2118,111 +2499,96 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
resultOp = Either.right(responseFormat);
return resultOp;
}
- log.debug("Try to update entry on graph");
+ log.trace("Try to update entry on graph");
String artifactUniqueId = null;
- ArtifactDefinition artifactDefinition = null;
+ ArtifactDefinition artifactDefinition = artifactInfo;
StorageOperationStatus error = null;
boolean isLeft = false;
if (interfaceType != null && operationName != null) {
// lifecycle artifact
- Operation operation = convertToOperation(artifactInfo, operationName);
-
- Either<Operation, StorageOperationStatus> result = interfaceLifecycleOperation.updateInterfaceOperation(parentId, interfaceType, operationName, operation);
+ /*
+ * Operation operation = convertToOperation(artifactInfo, operationName);
+ *
+ * Either<Operation, StorageOperationStatus> result = interfaceLifecycleOperation.updateInterfaceOperation(parentId, interfaceType, operationName, operation);
+ *
+ * isLeft = result.isLeft(); if (isLeft) { artifactUniqueId = result.left().value().getUniqueId(); artifactDefinition = result.left().value().getImplementation();
+ *
+ * insideEither = Either.right(result.left().value()); resultOp = Either.left(insideEither); } else { error = result.right().value(); }
+ */
+ } else {
+ log.debug("Enty on graph is updated. Update artifact in ES");
+ boolean res = true;
+ // Changing previous and current artifactId for auditing
+ prevArtifactId = currArtifactId;
+ currArtifactId = artifactDefinition.getUniqueId();
- isLeft = result.isLeft();
- if (isLeft) {
- artifactUniqueId = result.left().value().getUniqueId();
- artifactDefinition = result.left().value().getImplementation();
+ NodeTypeEnum convertParentType = convertParentType(componentType);
- insideEither = Either.right(result.left().value());
- resultOp = Either.left(insideEither);
+ if (decodedPayload == null) {
+ if (!artifactDefinition.getMandatory() || artifactDefinition.getEsId() != null) {
+ Either<ESArtifactData, CassandraOperationStatus> artifactFromCassandra = artifactCassandraDao.getArtifact(artifactDefinition.getEsId());
+ // Either<ESArtifactData, ResourceUploadStatus>
+ // artifactfromES = daoUploader.getArtifact(artifactId);
+ if (artifactFromCassandra.isRight()) {
+ log.debug("Failed to get artifact data from ES for artifact id {}", artifactId);
+ error = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactFromCassandra.right().value());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
+ handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
+ resultOp = Either.right(responseFormat);
+ return resultOp;
+ }
+ // clone data to new artifact
+ artifactData.setData(artifactFromCassandra.left().value().getData());
+ artifactData.setId(artifactFromCassandra.left().value().getId());
+ }
} else {
- error = result.right().value();
+ if (artifactDefinition.getEsId() == null) {
+ artifactDefinition.setEsId(artifactDefinition.getUniqueId());
+ artifactData.setId(artifactDefinition.getUniqueId());
+ }
}
- } else {
- NodeTypeEnum convertParentType = convertParentType(componentType);
- Either<ArtifactDefinition, StorageOperationStatus> result = artifactOperation.updateArifactOnResource(artifactInfo, parentId, artifactId, convertParentType, true);
+ Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.updateArifactOnResource(artifactInfo, parent.getUniqueId(), artifactId, convertParentType, parentId);
isLeft = result.isLeft();
if (isLeft) {
artifactUniqueId = result.left().value().getUniqueId();
artifactDefinition = result.left().value();
+ String artifactType = artifactInfo.getArtifactType();
+ if (NodeTypeEnum.Resource == convertParentType
+ && (ArtifactTypeEnum.HEAT.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_VOL.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_NET.getType().equalsIgnoreCase(artifactType))) {
+ /*
+ * if (!artifactUniqueId.equals(artifactId)) { artifactToscaOperation.updateHeatEnvArtifact(parentId, null, artifactId, artifactUniqueId, convertParentType);
+ *
+ * } else { if (!artifactInfo.getArtifactChecksum().equals(artifactDefinition.getArtifactChecksum())) { Either<ArtifactDefinition, StorageOperationStatus> heatEnvEither =
+ * artifactToscaOperation.getHeatEnvByGeneratedFromId(artifactUniqueId); if (heatEnvEither.isLeft()) { artifactToscaOperation.updateHeatEnvPlaceholder(heatEnvEither.left().value(), parentId);
+ *
+ * } } }
+ */
+ }
+ error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType);
insideEither = Either.left(result.left().value());
resultOp = Either.left(insideEither);
+ if (error != StorageOperationStatus.OK) {
+ isLeft = false;
+ }
+
} else {
error = result.right().value();
}
- }
- if (isLeft) {
- log.debug("Enty on graph is updated. Update artifact in ES");
- boolean res;
- // Changing previous and current artifactId for auditing
- prevArtifactId = currArtifactId;
- currArtifactId = artifactDefinition.getUniqueId();
+ if (isLeft) {
- if (!artifactDefinition.getUniqueId().equals(artifactId)) {
- // different ids ==> artifact node was cloned .
- // if no data in request get from ES
- if (decodedPayload == null) {
- if (!artifactDefinition.getMandatory() || artifactDefinition.getEsId() != null) {
- Either<ESArtifactData, CassandraOperationStatus> artifactFromCassandra = artifactCassandraDao.getArtifact(artifactId);
- // Either<ESArtifactData, ResourceUploadStatus>
- // artifactfromES = daoUploader.getArtifact(artifactId);
- if (artifactFromCassandra.isRight()) {
- log.debug("Failed to get artifact data from ES for artifact id {}", artifactId);
- StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactFromCassandra.right().value());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus));
- handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
- resultOp = Either.right(responseFormat);
- return resultOp;
- }
- // clone data to new artifact
- artifactData.setData(artifactFromCassandra.left().value().getData());
- }
- }
- artifactData.setId(artifactDefinition.getUniqueId());
// create new entry in ES
res = true;
if (artifactData.getData() != null) {
+ if (!artifactDefinition.getDuplicated() || artifactData.getId() == null)
+ artifactData.setId(artifactDefinition.getEsId());
res = saveArtifacts(artifactData, parentId, false);
- // set on graph object id of artifact in ES!
- if (res) {
- artifactInfo.setEsId(artifactData.getId());
- Either<ArtifactDefinition, StorageOperationStatus> updateArifactRes = artifactOperation.updateArifactDefinition(artifactInfo, true);
- if (updateArifactRes.isRight()) {
- log.debug("Failed to update artifact on graph - {}", artifactId);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArifactRes.right().value()));
- handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
- resultOp = Either.right(responseFormat);
- return resultOp;
-
- } else {
- insideEither = Either.left(updateArifactRes.left().value());
- resultOp = Either.left(insideEither);
- }
- }
- }
- } else {
- res = true;
- if (artifactData.getData() != null) {
- // override artifact in ES
- res = saveArtifacts(artifactData, parentId, true);
- if (res && artifactDefinition.getMandatory()) {
- artifactInfo.setEsId(artifactData.getId());
- Either<ArtifactDefinition, StorageOperationStatus> updateArifactRes = artifactOperation.updateArifactDefinition(artifactInfo, true);
- if (updateArifactRes.isRight()) {
- log.debug("Failed to update artifact on graph - {}", artifactId);
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactRes.right().value()), artifactId);
- handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
- resultOp = Either.right(responseFormat);
- return resultOp;
- }
- }
}
}
+
if (res) {
log.debug("Artifact saved into ES - {}", artifactUniqueId);
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
@@ -2230,7 +2596,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
// resultOp = Either.left(result.left().value());
// return resultOp;
} else {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError, "Update Artifact");
BeEcompErrorManager.getInstance().logBeDaoSystemError("Update Artifact");
log.debug("Failed to save the artifact.");
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
@@ -2238,12 +2603,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
resultOp = Either.right(responseFormat);
// return resultOp;
}
- } else {
- log.debug("Failed to create entry on graph for artifact {}", artifactInfo.getArtifactDisplayName());
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(error), artifactInfo.getArtifactDisplayName());
- handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
- resultOp = Either.right(responseFormat);
- // return resultOp;
}
return resultOp;
@@ -2255,8 +2614,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
byte[] decodedPayload = null;
if (payload != null && payload.length != 0) {
-
- decodedPayload = Base64.decodeBase64(payload);
+ // the generated artifacts were already decoded by the handler
+ decodedPayload = artifactInfo.getGenerated() ? payload : Base64.decodeBase64(payload);
if (decodedPayload.length == 0) {
log.debug("Failed to decode the payload.");
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
@@ -2285,7 +2644,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
// else
// if(ArtifactTypeEnum.APPC_CONFIG.getType().equalsIgnoreCase(artifactType)
// || ){
- } else if (ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType().equalsIgnoreCase(artifactType)) {
+ } else if (ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType().equalsIgnoreCase(artifactType)
+ || ArtifactTypeEnum.VES_EVENTS.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.LIFECYCLE_OPERATIONS.getType().equalsIgnoreCase(artifactType)) {
String artifactFileName = artifactInfo.getArtifactName();
String fileExtension = GeneralUtility.getFilenameExtension(artifactFileName).toLowerCase();
switch (fileExtension) {
@@ -2321,17 +2681,17 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return Either.left(decodedPayload);
}
- private Either<Boolean, ResponseFormat> validateDeploymentHeatPayload(byte[] payload, String artifactType) {
+ private Either<Boolean, ResponseFormat> validateDeploymentHeatPayload(byte[] decodedPayload, String artifactType) {
// Basic YAML validation
YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter();
- if (!yamlToObjectConverter.isValidYaml(payload)) {
+ if (!yamlToObjectConverter.isValidYaml(decodedPayload)) {
log.debug("Invalid YAML format");
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, artifactType);
return Either.right(responseFormat);
}
if (!ArtifactTypeEnum.HEAT_ENV.getType().equalsIgnoreCase(artifactType)) {
// HEAT specific YAML validation
- DeploymentArtifactHeatConfiguration heatConfiguration = yamlToObjectConverter.convert(payload, DeploymentArtifactHeatConfiguration.class);
+ DeploymentArtifactHeatConfiguration heatConfiguration = yamlToObjectConverter.convert(decodedPayload, DeploymentArtifactHeatConfiguration.class);
if (heatConfiguration == null || heatConfiguration.getHeat_template_version() == null || heatConfiguration.getResources() == null) {
log.debug("HEAT doesn't contain required \"heat_template_version\" and \"resources\" sections ");
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactType);
@@ -2376,17 +2736,17 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
public void handleTransaction(Either<Operation, ResponseFormat> opState) {
if (opState == null || opState.isRight()) {
- titanGenericDao.rollback();
+ titanDao.rollback();
} else {
- titanGenericDao.commit();
+ titanDao.commit();
}
}
- public Either<Operation, ResponseFormat> deleteArtifactByInterface(String resourceId, String interfaceType, String operationName, String userId, String artifactId, ImmutablePair<User, Resource> userResourceAuditPair, boolean shouldLock,
+ public Either<Operation, ResponseFormat> deleteArtifactByInterface(String resourceId, String interfaceType, String operationName, String userUserId, String artifactId, ImmutablePair<User, Resource> userResourceAuditPair, boolean shouldLock,
boolean inTransaction) {
User user = new User();
- user.setUserId(userId);
- Either<Resource, StorageOperationStatus> parent = resourceOperation.getResource(resourceId);
+ user.setUserId(userUserId);
+ Either<Resource, StorageOperationStatus> parent = toscaOperationFacade.getToscaElement(resourceId, JsonParseFlagEnum.ParseMetadata);
if (parent.isRight()) {
ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(parent.right().value()));
return Either.right(responseFormat);
@@ -2438,26 +2798,26 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
public StorageOperationStatus deleteIfNotOnGraph(String artifactId, String artifactEsId, boolean deleteOnlyPayload) {
log.debug("deleteIfNotOnGraph: delete only payload = {}", deleteOnlyPayload);
- Either<ArtifactData, TitanOperationStatus> checkArtifactNode = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ArtifactRef), artifactId, ArtifactData.class);
- if ((artifactEsId != null && !artifactEsId.isEmpty())) {
- boolean isNotExistOnGraph = checkArtifactNode.isRight() && checkArtifactNode.right().value().equals(TitanOperationStatus.NOT_FOUND);
-
- if ((isNotExistOnGraph) || (checkArtifactNode.left().value().getArtifactDataDefinition().getMandatory() && deleteOnlyPayload)
- || (ArtifactGroupTypeEnum.SERVICE_API.equals(checkArtifactNode.left().value().getArtifactDataDefinition().getArtifactGroupType()) && deleteOnlyPayload)) {
- // last one. need to delete in ES
- log.debug("Entry on graph is deleted. Delete artifact in ES for id = {}", artifactEsId);
- artifactCassandraDao.deleteArtifact(artifactEsId);
- return StorageOperationStatus.OK;
- // return
- // componentsUtils.getResponseFormatByResourceId(ActionStatus.OK,
- // resourceId);
-
- } else {
- log.debug("Entry on graph is deleted. Exist more connections on this artifact. Don't delete artifact in ES for id = {}", artifactEsId);
- return StorageOperationStatus.OK;
- }
-
- }
+ // Either<ArtifactData, TitanOperationStatus> checkArtifactNode = titanDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ArtifactRef), artifactId, ArtifactData.class);
+ // if ((artifactEsId != null && !artifactEsId.isEmpty())) {
+ // boolean isNotExistOnGraph = checkArtifactNode.isRight() && checkArtifactNode.right().value().equals(TitanOperationStatus.NOT_FOUND);
+ //
+ // if ((isNotExistOnGraph) || (checkArtifactNode.left().value().getArtifactDataDefinition().getMandatory() && deleteOnlyPayload)
+ // || (ArtifactGroupTypeEnum.SERVICE_API.equals(checkArtifactNode.left().value().getArtifactDataDefinition().getArtifactGroupType()) && deleteOnlyPayload)) {
+ // // last one. need to delete in ES
+ // log.debug("Entry on graph is deleted. Delete artifact in ES for id = {}", artifactEsId);
+ // artifactCassandraDao.deleteArtifact(artifactEsId);
+ // return StorageOperationStatus.OK;
+ // // return
+ // // componentsUtils.getResponseFormatByResourceId(ActionStatus.OK,
+ // // resourceId);
+ //
+ // } else {
+ // log.debug("Entry on graph is deleted. Exist more connections on this artifact. Don't delete artifact in ES for id = {}", artifactEsId);
+ // return StorageOperationStatus.OK;
+ // }
+ //
+ // }
return StorageOperationStatus.OK;
}
@@ -2594,7 +2954,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
private Either<Service, ResponseFormat> validateServiceNameAndVersion(String serviceName, String serviceVersion) {
- Either<List<Service>, StorageOperationStatus> serviceListBySystemName = serviceOperation.getServiceListBySystemName(serviceName, false);
+ Either<List<Service>, StorageOperationStatus> serviceListBySystemName = toscaOperationFacade.getBySystemName(ComponentTypeEnum.SERVICE, serviceName);
if (serviceListBySystemName.isRight()) {
log.debug("Couldn't fetch any service with name {}", serviceName);
return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceListBySystemName.right().value(), ComponentTypeEnum.SERVICE), serviceName));
@@ -2622,31 +2982,13 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
private Either<Resource, ResponseFormat> validateResourceNameAndVersion(String resourceName, String resourceVersion) {
- Either<List<Resource>, StorageOperationStatus> resourceListBySystemName = resourceOperation.getResourceListBySystemName(resourceName, false);
+
+ Either<Resource, StorageOperationStatus> resourceListBySystemName = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion, JsonParseFlagEnum.ParseMetadata);
if (resourceListBySystemName.isRight()) {
- log.debug("Couldn't fetch any resource with name {}", resourceName);
+ log.debug("Couldn't fetch any resource with name {} and version {}. ", resourceName, resourceVersion);
return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceListBySystemName.right().value()), resourceName));
}
- List<Resource> resourceList = resourceListBySystemName.left().value();
- if (resourceList == null || resourceList.isEmpty()) {
- log.debug("Couldn't fetch any resource with name {}", resourceName);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceName));
- }
-
- Resource foundResource = null;
- for (Resource resource : resourceList) {
- if (resource.getVersion().equals(resourceVersion)) {
- log.trace("Found resource with version {}", resourceVersion);
- foundResource = resource;
- break;
- }
- }
-
- if (foundResource == null) {
- log.debug("Couldn't find version {} for resource {}", resourceVersion, resourceName);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_VERSION_NOT_FOUND, ComponentTypeEnum.RESOURCE.getValue(), resourceVersion));
- }
- return Either.left(foundResource);
+ return Either.left(resourceListBySystemName.left().value());
}
public Either<byte[], ResponseFormat> downloadServiceArtifactByNames(String serviceName, String serviceVersion, String artifactName) {
@@ -2658,7 +3000,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
// Normalizing artifact name
- artifactName = ValidationUtils.normalizeFileName(artifactName);
+ final String normalizedArtifactName = ValidationUtils.normalizeFileName(artifactName);
// Service validation
Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
@@ -2668,41 +3010,44 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
String serviceId = validateServiceNameAndVersion.left().value().getUniqueId();
- // Looking for deployment artifacts
+ // Looking for deployment or tosca artifacts
Service service = validateServiceNameAndVersion.left().value();
- Map<String, ArtifactDefinition> artifacts = service.getDeploymentArtifacts();
- if (artifacts == null || artifacts.isEmpty()) {
- log.debug("Deployment artifacts of service {} are not found", serviceId);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
+
+ if (MapUtils.isEmpty(service.getDeploymentArtifacts()) && MapUtils.isEmpty(service.getToscaArtifacts())) {
+ log.debug("Neither Deployment nor Tosca artifacts of service {} are found", serviceId);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName));
}
- ArtifactDefinition deploymentArtifact = null;
+ Optional<ArtifactDefinition> foundArtifactOptl = null;
- for (ArtifactDefinition artifactDefinition : artifacts.values()) {
- if (artifactDefinition.getArtifactName().equals(artifactName)) {
- log.debug("Found deployment artifact {}", artifactName);
- deploymentArtifact = artifactDefinition;
- }
+ if (!MapUtils.isEmpty(service.getDeploymentArtifacts())) {
+ foundArtifactOptl = service.getDeploymentArtifacts().values().stream()
+ // filters artifact by name
+ .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny();
}
-
- if (deploymentArtifact == null) {
- log.debug("No deployment artifact {} was found for service {}", artifactName, serviceId);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
+ if ((foundArtifactOptl == null || !foundArtifactOptl.isPresent()) && !MapUtils.isEmpty(service.getToscaArtifacts())) {
+ foundArtifactOptl = service.getToscaArtifacts().values().stream()
+ // filters TOSCA artifact by name
+ .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny();
}
-
+ if (!foundArtifactOptl.isPresent()) {
+ log.debug("The artifact {} was not found for service {}", normalizedArtifactName, serviceId);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName));
+ }
+ log.debug("Found deployment artifact {}", normalizedArtifactName);
// Downloading the artifact
- Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(deploymentArtifact);
+ Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(foundArtifactOptl.get());
if (downloadArtifactEither.isRight()) {
- log.debug("Download artifact {} failed", artifactName);
+ log.debug("Download artifact {} failed", normalizedArtifactName);
return Either.right(downloadArtifactEither.right().value());
}
- log.trace("Download of service artifact succeeded, uniqueId {}", deploymentArtifact.getUniqueId());
+ log.trace("Download of service artifact succeeded, uniqueId {}", foundArtifactOptl.get().getUniqueId());
return Either.left(downloadArtifactEither.left().value().getRight());
}
- public Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifact(String artifactUniqueId) {
+ public Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifact(String parentId, String artifactUniqueId) {
log.trace("Starting download of artifact, uniqueId {}", artifactUniqueId);
- Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactOperation.getArtifactById(artifactUniqueId, false);
+ Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(parentId, artifactUniqueId);
if (artifactById.isRight()) {
ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(artifactById.right().value());
log.debug("Error when getting artifact info by id{}, error: {}", artifactUniqueId, actionStatus.name());
@@ -2751,7 +3096,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
Map<String, InterfaceDefinition> interfaces = ((Resource) component).getInterfaces();
if (!found && interfaces != null) {
for (Map.Entry<String, InterfaceDefinition> entry : interfaces.entrySet()) {
- Map<String, Operation> operations = entry.getValue().getOperations();
+ Map<String, Operation> operations = entry.getValue().getOperationsMap();
for (Map.Entry<String, Operation> entryOp : operations.entrySet()) {
if (entryOp.getValue().getImplementation() != null && entryOp.getValue().getImplementation().getUniqueId().equals(artifactId)) {
found = true;
@@ -2800,6 +3145,17 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
}
}
+ if ( !found ){
+ artifacts = resourceInstance.getArtifacts();
+ if (artifacts != null) {
+ for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
+ if (entry.getValue().getUniqueId().equals(artifactId)) {
+ found = true;
+ break;
+ }
+ }
+ }
+ }
}
return found;
}
@@ -2807,24 +3163,13 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
private Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists(String componentId, String userId, AuditingActionEnum auditingAction, User user, String artifactId, ComponentTypeEnum componentType,
String containerComponentType, boolean inTransaction) {
- NodeTypeEnum nodeType = componentType.getNodeType();
- if (containerComponentType != null && NodeTypeEnum.ResourceInstance == nodeType) {
- nodeType = (ComponentTypeEnum.findByParamName(containerComponentType)).getNodeType();
- }
- ComponentOperation componentOperation = getComponentOperation(nodeType);
+ ComponentTypeEnum componentForAudit = null == containerComponentType ? componentType : ComponentTypeEnum.findByParamName(containerComponentType);
+ componentForAudit.getNodeType();
- if (componentOperation == null) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
- log.debug("addArtifact - not supported component type {}", componentType);
- handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentType, null);
- return Either.right(responseFormat);
- }
- Either<? extends org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentResult = componentOperation.getComponent(componentId, inTransaction);
+ Either<? extends org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentResult = toscaOperationFacade.getToscaFullElement(componentId);
if (componentResult.isRight()) {
- ActionStatus status = (componentType.equals(ComponentTypeEnum.RESOURCE)) ? ActionStatus.RESOURCE_NOT_FOUND : ActionStatus.SERVICE_NOT_FOUND;
- ComponentTypeEnum componentForAudit = (componentType.equals(ComponentTypeEnum.RESOURCE)) ? ComponentTypeEnum.RESOURCE : ComponentTypeEnum.SERVICE;
-
+ ActionStatus status = componentForAudit == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND : componentType == ComponentTypeEnum.SERVICE ? ActionStatus.SERVICE_NOT_FOUND : ActionStatus.PRODUCT_NOT_FOUND;
ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, componentId);
log.debug("Service not found, serviceId {}", componentId);
handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentForAudit, null);
@@ -2833,9 +3178,9 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return Either.left(componentResult.left().value());
}
- private Either<Boolean, ResponseFormat> validateWorkOnComponent(org.openecomp.sdc.be.model.Component component, String userId, AuditingActionEnum auditingAction, User user, String artifactId, ArtifactOperation operation,
+ private Either<Boolean, ResponseFormat> validateWorkOnComponent(org.openecomp.sdc.be.model.Component component, String userId, AuditingActionEnum auditingAction, User user, String artifactId, ArtifactOperationInfo operation,
ComponentTypeEnum componentType) {
- if (operation != ArtifactOperation.Download) {
+ if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.Download && !operation.ignoreLifecycleState()) {
Either<Boolean, ResponseFormat> canWork = validateCanWorkOnComponent(component, userId);
if (canWork.isRight()) {
String uniqueId = component.getUniqueId();
@@ -2847,22 +3192,9 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return Either.left(true);
}
- private Either<Boolean, ResponseFormat> validateWorkOnResource(Resource resource, String userId, AuditingActionEnum auditingAction, User user, String artifactId, ArtifactOperation operation) {
- if (operation != ArtifactOperation.Download) {
- if (!ComponentValidationUtils.canWorkOnResource(resource, userId)) {
- String uniqueId = resource.getUniqueId();
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
- log.debug("Resource status isn't CHECKOUT or user isn't owner, resourceId {}", uniqueId);
- handleAuditing(auditingAction, resource, uniqueId, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE, null);
- return Either.right(responseFormat);
- }
- }
- return Either.left(true);
- }
+ private Either<Boolean, ResponseFormat> validateUserRole(User user, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, ArtifactOperationInfo operation) {
- private Either<Boolean, ResponseFormat> validateUserRole(User user, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, ArtifactOperation operation) {
-
- if (operation != ArtifactOperation.Download) {
+ if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.Download) {
String role = user.getRole();
if (!role.equals(Role.ADMIN.name()) && !role.equals(Role.DESIGNER.name())) {
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
@@ -2874,12 +3206,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return Either.left(true);
}
- private Either<User, ResponseFormat> validateUserExists(String userId, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType) {
-
- return validateUserExists(userId, auditingAction, componentId, artifactId, componentType, false);
-
- }
-
private Either<User, ResponseFormat> validateUserExists(String userId, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, boolean inTransaction) {
Either<User, ResponseFormat> validateUserExists = validateUserExists(userId, auditingAction.getName(), inTransaction);
@@ -2892,9 +3218,9 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return Either.left(validateUserExists.left().value());
}
- private AuditingActionEnum detectAuditingType(ArtifactOperation operation, String origMd5) {
+ protected AuditingActionEnum detectAuditingType(ArtifactOperationInfo operation, String origMd5) {
AuditingActionEnum auditingAction = null;
- switch (operation) {
+ switch (operation.getArtifactOperationEnum()) {
case Create:
auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API : AuditingActionEnum.ARTIFACT_UPLOAD;
break;
@@ -2945,7 +3271,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
CassandraOperationStatus resourceUploadStatus = artifactCassandraDao.saveArtifact(artifactData);
if (resourceUploadStatus.equals(CassandraOperationStatus.OK)) {
- log.debug("Artifact {} was saved in component {}.", artifactData.getId(), resourceId);
+ log.debug("Artifact {} was saved in component .", artifactData.getId(), resourceId);
} else {
log.info("Failed to save artifact {}.", artifactData.getId());
return false;
@@ -2961,19 +3287,15 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return (ArtifactGroupTypeEnum.DEPLOYMENT.equals(artifactInfo.getArtifactGroupType()));
}
- public IResourceOperation getResourceOperation() {
- return this.resourceOperation;
- }
-
- public Either<ArtifactDefinition, ResponseFormat> createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap, String userId, ArtifactGroupTypeEnum groupType, boolean inTransaction) {
- Either<User, ActionStatus> user = userAdminManager.getUser(userId, inTransaction);
+ public Either<ArtifactDefinition, ResponseFormat> createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap, String userUserId, ArtifactGroupTypeEnum groupType, boolean inTransaction) {
+ Either<User, ActionStatus> user = userAdminManager.getUser(userUserId, inTransaction);
if (user.isRight()) {
ResponseFormat responseFormat;
if (user.right().value().equals(ActionStatus.USER_NOT_FOUND)) {
- log.debug("create artifact placeholder - not authorized user, userId {}", userId);
+ log.debug("create artifact placeholder - not authorized user, userId {}", userUserId);
responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
} else {
- log.debug("create artifact placeholder - failed to authorize user, userId {}", userId);
+ log.debug("create artifact placeholder - failed to authorize user, userId {}", userUserId);
responseFormat = componentsUtils.getResponseFormat(user.right().value());
}
return Either.right(responseFormat);
@@ -2995,21 +3317,13 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
artifactInfo.setArtifactType(artifactType);
artifactInfo.setDescription(artifactDescription);
artifactInfo.setArtifactGroupType(groupType);
- setDefaultArtifactTimeout(groupType, artifactInfo);
+ nodeTemplateOperation.setDefaultArtifactTimeout(groupType, artifactInfo);
setArtifactPlaceholderCommonFields(resourceId, user, artifactInfo);
return artifactInfo;
}
- private void setDefaultArtifactTimeout(ArtifactGroupTypeEnum groupType, ArtifactDefinition artifactInfo) {
- if (groupType.equals(ArtifactGroupTypeEnum.DEPLOYMENT)) {
- artifactInfo.setTimeout(defaultHeatTimeout);
- } else {
- artifactInfo.setTimeout(NON_HEAT_TIMEOUT);
- }
- }
-
private void setArtifactPlaceholderCommonFields(String resourceId, User user, ArtifactDefinition artifactInfo) {
String uniqueId = null;
@@ -3032,29 +3346,17 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
artifactInfo.setMandatory(true);
}
- public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType, boolean inTransaction, ArtifactGroupTypeEnum groupType) {
- return artifactOperation.getArtifacts(parentId, parentType, inTransaction, groupType.getType());
+ public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType, boolean inTransaction, ArtifactGroupTypeEnum groupType, String instanceId) {
+ return artifactToscaOperation.getArtifacts(parentId, parentType, groupType, instanceId);
}
- public Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact(ArtifactDefinition artifactHeatEnv, ArtifactDefinition artifact, String parentId, NodeTypeEnum parentType, boolean inTransaction) {
- return artifactOperation.addHeatEnvArtifact(artifactHeatEnv, artifact, parentId, parentType, inTransaction);
-
+ public Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact(ArtifactDefinition artifactHeatEnv, ArtifactDefinition artifact, String componentId, NodeTypeEnum parentType, String instanceId) {
+ return artifactToscaOperation.addHeatEnvArtifact(artifactHeatEnv, artifact, componentId, parentType, true, instanceId);
}
- private Either<ESArtifactData, ResponseFormat> createEsHeatEnvArtifactDataFromString(ArtifactDefinition artifactDefinition, String parameters) {
- StringBuilder sb = new StringBuilder();
-
- sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactHeader());
- sb.append(parameters);
- sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactFooter());
- byte[] payload = sb.toString().getBytes();
+ private Either<ESArtifactData, ResponseFormat> createEsHeatEnvArtifactDataFromString(ArtifactDefinition artifactDefinition, String payloadStr) {
- YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter();
-
- /*
- * if (!yamlToObjectConverter.isValidYaml(payload)) { log.debug("Invalid YAML format"); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, ArtifactTypeEnum.HEAT_ENV.getType()); return
- * Either.right(responseFormat); }
- */
+ byte[] payload = payloadStr.getBytes();
ESArtifactData artifactData = createEsArtifactData(artifactDefinition, payload);
return Either.left(artifactData);
@@ -3065,60 +3367,81 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
* @param artifactDefinition
* @return
*/
- public Either<ArtifactDefinition, ResponseFormat> generateHeatEnvArtifact(ArtifactDefinition artifactDefinition, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier, boolean shouldLock) {
- List<HeatParameterDefinition> heatParameters = artifactDefinition.getHeatParameters();
+ public Either<ArtifactDefinition, ResponseFormat> generateHeatEnvArtifact(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
+ boolean shouldLock, String instanceId) {
+ String payload = generateHeatEnvPayload(artifactDefinition);
+ return generateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, shouldLock, instanceId);
+ }
+
+ private String generateHeatEnvPayload(ArtifactDefinition artifactDefinition) {
+ List<HeatParameterDefinition> heatParameters = artifactDefinition.getListHeatParameters();
heatParameters.sort(Comparator.comparing(e -> e.getName()));
- StringBuilder sb = new StringBuilder("parameters:\n");
+ StringBuilder sb = new StringBuilder();
+ sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactHeader());
+ sb.append("parameters:\n");
if (heatParameters != null) {
+ List<HeatParameterDefinition> empltyHeatValues = new ArrayList<>();
for (HeatParameterDefinition heatParameterDefinition : heatParameters) {
- if (heatParameterDefinition.getCurrentValue() != null) {
- HeatParameterType type = HeatParameterType.isValidType(heatParameterDefinition.getType());
- if (type != null) {
- switch (type) {
- case BOOLEAN:
- sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(Boolean.parseBoolean(heatParameterDefinition.getCurrentValue())).append("\n");
- break;
- case NUMBER:
- // if
- // (ValidationUtils.isFloatNumber(heatParameterDefinition.getCurrentValue()))
- // {
- // sb.append("
- // ").append(heatParameterDefinition.getName()).append(":").append("
- // ").append(Float.parseFloat(heatParameterDefinition.getCurrentValue())).append("\n");
- // } else {
- // sb.append("
- // ").append(heatParameterDefinition.getName()).append(":").append("
- // ").append(Integer.parseInt(heatParameterDefinition.getCurrentValue())).append("\n");
- // }
- sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(new BigDecimal(heatParameterDefinition.getCurrentValue()).toPlainString()).append("\n");
- break;
- case COMMA_DELIMITED_LIST:
- case JSON:
- sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(heatParameterDefinition.getCurrentValue()).append("\n");
- break;
- default:
- String value = heatParameterDefinition.getCurrentValue();
- boolean starts = value.startsWith("\"");
- boolean ends = value.endsWith("\"");
+
+ String heatValue = heatParameterDefinition.getCurrentValue();
+ if (!ValidationUtils.validateStringNotEmpty(heatValue)) {
+ heatValue = heatParameterDefinition.getDefaultValue();
+ if (!ValidationUtils.validateStringNotEmpty(heatValue)) {
+ empltyHeatValues.add(heatParameterDefinition);
+ continue;
+ }
+ }
+ HeatParameterType type = HeatParameterType.isValidType(heatParameterDefinition.getType());
+ if (type != null) {
+ switch (type) {
+ case BOOLEAN:
+ sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(Boolean.parseBoolean(heatValue)).append("\n");
+ break;
+ case NUMBER:
+ sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(new BigDecimal(heatValue).toPlainString()).append("\n");
+ break;
+ case COMMA_DELIMITED_LIST:
+ case JSON:
+ sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(heatValue).append("\n");
+ break;
+ default:
+ String value = heatValue;
+ boolean starts = value.startsWith("\"");
+ boolean ends = value.endsWith("\"");
+ if (!(starts && ends)) {
+ starts = value.startsWith("'");
+ ends = value.endsWith("'");
if (!(starts && ends)) {
- starts = value.startsWith("'");
- ends = value.endsWith("'");
- if (!(starts && ends)) {
- value = "\"" + value + "\"";
- }
+ value = "\"" + value + "\"";
}
- sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(value);
- sb.append("\n");
- break;
-
}
+ sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(value);
+ sb.append("\n");
+ break;
+
}
}
}
+ if (!empltyHeatValues.isEmpty()) {
+ empltyHeatValues.sort(Comparator.comparing(e -> e.getName()));
+ empltyHeatValues.forEach(hv -> {
+ sb.append(" ").append(hv.getName()).append(":");
+ HeatParameterType type = HeatParameterType.isValidType(hv.getType());
+ if (type != null && type == HeatParameterType.STRING && (hv.getCurrentValue() != null && "".equals(hv.getCurrentValue()) || hv.getDefaultValue() != null && "".equals(hv.getDefaultValue()))) {
+ sb.append(" \"\"").append("\n");
+ } else {
+ sb.append(" ").append("\n");
+ }
+ });
+ }
}
- return generateAndSaveHeatEnvArtifact(artifactDefinition, sb.toString(), component, resourceInstanceName, modifier, shouldLock);
+ sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactFooter());
+
+ // DE265919 fix Tal G
+ String result = sb.toString().replaceAll("\\\\n", "\n");
+ return result;
}
/**
@@ -3127,14 +3450,15 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
* @param payload
* @return
*/
- public Either<ArtifactDefinition, ResponseFormat> generateAndSaveHeatEnvArtifact(ArtifactDefinition artifactDefinition, String payload, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
- boolean shouldLock) {
- return generateArtifactPayload(artifactDefinition, component, resourceInstanceName, modifier, shouldLock, () -> artifactDefinition.getHeatParamsUpdateDate(), () -> createEsHeatEnvArtifactDataFromString(artifactDefinition, payload));
+ public Either<ArtifactDefinition, ResponseFormat> generateAndSaveHeatEnvArtifact(ArtifactDefinition artifactDefinition, String payload, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName,
+ User modifier, boolean shouldLock, String instanceId) {
+ return generateArtifactPayload(artifactDefinition, componentType, component, resourceInstanceName, modifier, shouldLock, () -> artifactDefinition.getHeatParamsUpdateDate(),
+ () -> createEsHeatEnvArtifactDataFromString(artifactDefinition, payload), instanceId);
}
- protected Either<ArtifactDefinition, ResponseFormat> generateArtifactPayload(ArtifactDefinition artifactDefinition, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier, boolean shouldLock,
- Supplier<Long> payloadUpdateDateGen, Supplier<Either<ESArtifactData, ResponseFormat>> esDataCreator) {
+ protected Either<ArtifactDefinition, ResponseFormat> generateArtifactPayload(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
+ boolean shouldLock, Supplier<Long> payloadUpdateDateGen, Supplier<Either<ESArtifactData, ResponseFormat>> esDataCreator, String instanceId) {
if (artifactDefinition.getPayloadUpdateDate() == null || artifactDefinition.getPayloadUpdateDate() == 0 || artifactDefinition.getPayloadUpdateDate() < payloadUpdateDateGen.get()) {
@@ -3156,7 +3480,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
String esArtifactId = artifactDefinition.getEsId();
Either<ESArtifactData, CassandraOperationStatus> artifactfromES;
ESArtifactData esArtifactData;
- if (esArtifactId != null && !esArtifactId.isEmpty()) {
+ if (esArtifactId != null && !esArtifactId.isEmpty() && artifactDefinition.getPayloadData() == null) {
artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
if (artifactfromES.isRight()) {
CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value();
@@ -3169,8 +3493,9 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
oldCheckSum = GeneralUtility.calculateMD5ByByteArray(esArtifactData.getDataAsArray());
} else {
oldCheckSum = artifactDefinition.getArtifactChecksum();
+
}
- Either<ArtifactDefinition, StorageOperationStatus> updateArifactDefinitionStatus;
+ Either<ArtifactDefinition, StorageOperationStatus> updateArifactDefinitionStatus = null;
if (shouldLock) {
Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, "Update Artifact - lock resource: ");
@@ -3183,11 +3508,11 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
if (oldCheckSum != null && oldCheckSum.equals(newCheckSum)) {
artifactDefinition.setPayloadUpdateDate(payloadUpdateDateGen.get());
- updateArifactDefinitionStatus = artifactOperation.updateArifactDefinition(artifactDefinition, false);
+ updateArifactDefinitionStatus = artifactToscaOperation.updateArifactOnResource(artifactDefinition, component.getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId);
log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId());
if (updateArifactDefinitionStatus.isRight()) {
ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus.right().value()), artifactDefinition.getArtifactDisplayName());
- log.trace("Failed to update payloadUpdateDate ", artifactDefinition.getEsId());
+ log.trace("Failed to update payloadUpdateDate {}", artifactDefinition.getEsId());
handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
@@ -3197,42 +3522,41 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
oldCheckSum = artifactDefinition.getArtifactChecksum();
artifactDefinition.setArtifactChecksum(newCheckSum);
- artifactOperation.updateUUID(artifactDefinition, oldCheckSum, artifactDefinition.getArtifactVersion());
+ artifactToscaOperation.updateUUID(artifactDefinition, oldCheckSum, artifactDefinition.getArtifactVersion());
artifactDefinition.setEsId(artifactDefinition.getUniqueId());
- updateArifactDefinitionStatus = artifactOperation.updateArifactDefinition(artifactDefinition, true);
+ updateArifactDefinitionStatus = artifactToscaOperation.updateArifactOnResource(artifactDefinition, component.getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId);
log.trace("Update Payload ", artifactDefinition.getEsId());
+ }
+ if (updateArifactDefinitionStatus != null && updateArifactDefinitionStatus.isLeft()) {
- if (updateArifactDefinitionStatus.isLeft()) {
-
- artifactData.setId(artifactDefinition.getUniqueId());
- CassandraOperationStatus saveArtifactStatus = artifactCassandraDao.saveArtifact(artifactData);
-
- if (saveArtifactStatus.equals(CassandraOperationStatus.OK)) {
- titanGenericDao.commit();
- log.debug("Artifact Saved In ES {}", artifactData.getId());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
- handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
- ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
+ artifactData.setId(artifactDefinition.getUniqueId());
+ CassandraOperationStatus saveArtifactStatus = artifactCassandraDao.saveArtifact(artifactData);
- } else {
- titanGenericDao.rollback();
- log.info("Failed to save artifact {}.", artifactData.getId());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
- handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
- ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
+ if (saveArtifactStatus.equals(CassandraOperationStatus.OK)) {
+ titanDao.commit();
+ log.debug("Artifact Saved In ES {}", artifactData.getId());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
+ handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
+ ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
- return Either.right(responseFormat);
- }
} else {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus.right().value()), artifactDefinition.getArtifactDisplayName());
- log.debug("Failed To update artifact {}", artifactData.getId());
+ titanDao.rollback();
+ log.info("Failed to save artifact {}.", artifactData.getId());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
return Either.right(responseFormat);
-
}
+ } else {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus.right().value()), artifactDefinition.getArtifactDisplayName());
+ log.debug("Failed To update artifact {}", artifactData.getId());
+ handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
+ ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
+
+ return Either.right(responseFormat);
+
}
} finally {
if (shouldLock) {
@@ -3245,11 +3569,11 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdateHeatEnv(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType,
- org.openecomp.sdc.be.model.Component parent, String originData, String origMd5, ArtifactOperation operation, boolean shouldLock, boolean inTransaction) {
- NodeTypeEnum parentType = convertParentType(componentType);
+ org.openecomp.sdc.be.model.Component parent, String originData, String origMd5, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) {
+ convertParentType(componentType);
String parentId = parent.getUniqueId();
- Either<ArtifactDefinition, StorageOperationStatus> artifactRes = artifactOperation.getArtifactById(artifactId, false);
- ArtifactDefinition currArtifact = artifactRes.left().value();
+ // Either<ArtifactDefinition, StorageOperationStatus> artifactRes = this.artifactToscaOperation.getArtifactById(componentId, artifactId);
+ ArtifactDefinition currArtifact = artifactInfo;
if (origMd5 != null) {
Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
@@ -3298,11 +3622,11 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
if (resultOp == null || resultOp.isRight()) {
log.debug("all changes rollback");
if (false == inTransaction)
- titanGenericDao.rollback();
+ titanDao.rollback();
} else {
log.debug("all changes committed");
if (false == inTransaction)
- titanGenericDao.commit();
+ titanDao.commit();
}
if (shouldLock)
componentType = parent.getComponentType();
@@ -3336,9 +3660,9 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
return Either.right(responseFormat);
}
- List<HeatParameterDefinition> currentHeatEnvParams = currArtifact.getHeatParameters();
- List<HeatParameterDefinition> updatedHeatEnvParams = artifactInfo.getHeatParameters();
- List<HeatParameterDefinition> reducedHeatEnvParams = new ArrayList<HeatParameterDefinition>();
+ List<HeatParameterDefinition> currentHeatEnvParams = currArtifact.getListHeatParameters();
+ List<HeatParameterDefinition> updatedHeatEnvParams = artifactInfo.getListHeatParameters();
+ new ArrayList<HeatParameterDefinition>();
// upload
if (origMd5 != null) {
@@ -3349,7 +3673,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
return Either.right(responseFormat);
}
- artifactInfo.setHeatParameters(updatedHeatEnvParams);
+ artifactInfo.setListHeatParameters(updatedHeatEnvParams);
}
Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParamers(artifactInfo, ArtifactTypeEnum.HEAT_ENV.getType());
@@ -3368,61 +3692,133 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
String updatedParamValue = heatEnvParam.getCurrentValue();
if (updatedParamValue != null && updatedParamValue.equals("")) { // reset
- heatEnvParam.setCurrentValue(heatEnvParam.getDefaultValue());
- reducedHeatEnvParams.add(heatEnvParam);
+ currHeatParam.setCurrentValue(heatEnvParam.getDefaultValue());
} else if (updatedParamValue != null) {
- reducedHeatEnvParams.add(heatEnvParam);
+ currHeatParam.setCurrentValue(updatedParamValue);
}
}
}
}
- if (reducedHeatEnvParams.size() > 0) {
- ArtifactDefinition reducedArtifactInfo = new ArtifactDefinition(artifactInfo);
- reducedArtifactInfo.setHeatParameters(reducedHeatEnvParams);
- Either<ArtifactDefinition, StorageOperationStatus> updateArtifactResult = artifactOperation.updateArifactOnResource(reducedArtifactInfo, componentId, artifactInfo.getUniqueId(), componentType.getNodeType(), inTransaction);
+ currArtifact.setHeatParamsUpdateDate(System.currentTimeMillis());
+ currArtifact.setListHeatParameters(currentHeatEnvParams);
- if (updateArtifactResult.isRight()) {
- log.debug("Failed to update artifact on graph - {}", artifactId);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArtifactResult.right().value()));
- handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
- return Either.right(responseFormat);
- }
- ArtifactDefinition updatedArtifact = updateArtifactResult.left().value();
- String updatedArtifactId = updatedArtifact.getUniqueId();
- if (!currArtifact.getUniqueId().equals(updatedArtifactId)) {
- currArtifact.setUniqueId(updatedArtifactId);
- currArtifact.setPayloadUpdateDate(updatedArtifact.getPayloadUpdateDate());
- currArtifact.setCreationDate(updatedArtifact.getCreationDate());
- currArtifact.setLastUpdateDate(updatedArtifact.getLastUpdateDate());
- currArtifact.setEsId(updatedArtifact.getEsId());
- }
- currArtifact.setHeatParamsUpdateDate(System.currentTimeMillis());
+ Either<ArtifactDefinition, StorageOperationStatus> updateArifactRes = artifactToscaOperation.updateArifactOnResource(currArtifact, parent.getUniqueId(), currArtifact.getUniqueId(), componentType.getNodeType(), componentId);
+ if (updateArifactRes.isRight()) {
+ log.debug("Failed to update artifact on graph - {}", artifactId);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArifactRes.right().value()));
+ handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
+ return Either.right(responseFormat);
+ }
+ StorageOperationStatus error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), ri.getUniqueId(), componentType);
+ if (error != StorageOperationStatus.OK) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
+ handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
+ return Either.right(responseFormat);
+ }
- Either<List<HeatParameterDefinition>, StorageOperationStatus> heatParamsForEnv = ((org.openecomp.sdc.be.model.operations.impl.ArtifactOperation) artifactOperation).getHeatParamsForEnv(currArtifact);
- if (heatParamsForEnv.isRight()) {
- log.debug("failed to get heat parameters values for heat artifact {}", updatedArtifact.getUniqueId());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(heatParamsForEnv.right().value()));
- handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
- return Either.right(responseFormat);
+ error = generateCustomizationUUIDOnGroupInstance(ri, updateArifactRes.left().value().getUniqueId(), parent.getUniqueId());
+ if (error != StorageOperationStatus.OK) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
+ handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
+ return Either.right(responseFormat);
+ }
+
+ }
+ // }
+
+ insideEither = Either.left(currArtifact);
+ resultOp = Either.left(insideEither);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
+ handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currArtifact, null, artifactId, responseFormat, componentType, ri.getName());
+ return resultOp;
+ }
+
+ private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateHeatParams(String componentId, String artifactId, ArtifactDefinition artifactEnvInfo, User user, AuditingActionEnum auditingAction, Component parent,
+ ComponentTypeEnum componentType, ArtifactDefinition currHeatArtifact, String origMd5) {
+
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
+ Either<ArtifactDefinition, Operation> insideEither = null;
+ /*
+ * currently getArtifactById does not retrieve heatParameters Either<ArtifactDefinition, StorageOperationStatus> artifactRes = artifactOperation.getArtifactById(artifactId, false); ArtifactDefinition currArtifact = artifactRes.left().value();
+ */
+ String currentHeatId = currHeatArtifact.getUniqueId();
+ ArtifactDefinition updatedHeatArt = currHeatArtifact;
+
+ List<HeatParameterDefinition> updatedHeatEnvParams = artifactEnvInfo.getListHeatParameters();
+ List<HeatParameterDefinition> currentHeatEnvParams = currHeatArtifact.getListHeatParameters();
+ List<HeatParameterDefinition> newHeatEnvParams = new ArrayList<HeatParameterDefinition>();
+
+ if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty() && currentHeatEnvParams != null && !currentHeatEnvParams.isEmpty()) {
+
+ String paramName;
+ for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
+
+ paramName = heatEnvParam.getName();
+ for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
+ if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
+
+ String updatedParamValue = heatEnvParam.getCurrentValue();
+ if (updatedParamValue == null)
+ updatedParamValue = heatEnvParam.getDefaultValue();
+ HeatParameterType paramType = HeatParameterType.isValidType(currHeatParam.getType());
+ if (!paramType.getValidator().isValid(updatedParamValue, null)) {
+ ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, ArtifactTypeEnum.HEAT_ENV.getType(), paramType.getType(), paramName);
+ handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactEnvInfo, null, artifactId, responseFormat, componentType, "");
+ return Either.right(responseFormat);
+
+ }
+ currHeatParam.setCurrentValue(paramType.getConverter().convert(updatedParamValue, null, null));
+ newHeatEnvParams.add(currHeatParam);
+ break;
+ }
}
- List<HeatParameterDefinition> updatedHeatParaetersList = heatParamsForEnv.left().value();
- currArtifact.setHeatParameters(updatedHeatParaetersList);
-
- Either<ArtifactDefinition, StorageOperationStatus> updateArifactRes = artifactOperation.updateArifactDefinition(currArtifact, true);
- if (updateArifactRes.isRight()) {
- log.debug("Failed to update artifact on graph - {}", artifactId);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArifactRes.right().value()));
- handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
+ }
+ if (!newHeatEnvParams.isEmpty()) {
+ currHeatArtifact.setListHeatParameters(currentHeatEnvParams);
+ Either<ArtifactDefinition, StorageOperationStatus> operationStatus = artifactToscaOperation.updateArifactOnResource(currHeatArtifact, parent.getUniqueId(), currHeatArtifact.getUniqueId(), componentType.getNodeType(), componentId);
+
+ if (operationStatus.isRight()) {
+ log.debug("Failed to update artifact on graph - {}", currHeatArtifact.getUniqueId());
+
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(operationStatus.right().value()));
return Either.right(responseFormat);
+
}
+ updatedHeatArt = operationStatus.left().value();
+ insideEither = Either.left(updatedHeatArt);
}
}
- insideEither = Either.left(currArtifact);
+ if (!currentHeatId.equals(updatedHeatArt.getUniqueId())) {
+ artifactEnvInfo.setArtifactChecksum(null);
+ artifactToscaOperation.updateHeatEnvArtifact(parent.getUniqueId(), artifactEnvInfo, currentHeatId, updatedHeatArt.getUniqueId(), componentType.getNodeType(), componentId);
+ } else {
+ artifactToscaOperation.updateHeatEnvPlaceholder(artifactEnvInfo, componentId, componentType.getNodeType());
+
+ }
resultOp = Either.left(insideEither);
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
- handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currArtifact, null, artifactId, responseFormat, componentType, ri.getName());
+ handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, null, artifactId, responseFormat, componentType, "");
return resultOp;
+
+ }
+
+ private StorageOperationStatus generateCustomizationUUIDOnGroupInstance(ComponentInstance ri, String artifactId, String componentId) {
+ StorageOperationStatus error = StorageOperationStatus.OK;
+ log.debug("Need to re-generate customization UUID for group instance on component instance {}", ri.getUniqueId());
+ List<GroupInstance> groupsInstances = ri.getGroupInstances();
+ // List<GroupInstance> associatedGroups = null;
+ List<String> groupInstancesId = null;
+ if (groupsInstances != null && !groupsInstances.isEmpty()) {
+ groupInstancesId = groupsInstances.stream().filter(p -> p.getGroupInstanceArtifacts() != null && p.getGroupInstanceArtifacts().contains(artifactId)).map(p -> p.getUniqueId()).collect(Collectors.toList());
+ }
+ if (groupInstancesId != null && !groupInstancesId.isEmpty()) {
+ // associatedGroups.stream().forEach(c -> this.groupInstanceOperation.updateCustomizationUUID(c.getUniqueId()));
+ toscaOperationFacade.generateCustomizationUUIDOnInstanceGroup(componentId, ri.getUniqueId(), groupInstancesId);
+ }
+ return error;
+
}
public Either<List<HeatParameterDefinition>, ResponseFormat> validateUploadParamsFromEnvFile(AuditingActionEnum auditingAction, Component parent, User user, ArtifactDefinition artifactInfo, String artifactId, ComponentTypeEnum componentType,
@@ -3484,25 +3880,12 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return Either.right(responseFormat);
}
- public ComponentOperation getComponentOperation(NodeTypeEnum componentType) {
-
- switch (componentType) {
- case Service:
- case ResourceInstance:
- return serviceOperation;
- case Resource:
- return resourceOperation;
- default:
- return null;
- }
- }
-
public ArtifactDefinition extractArtifactDefinition(Either<ArtifactDefinition, Operation> eitherArtifact) {
ArtifactDefinition ret;
if (eitherArtifact.isLeft()) {
ret = eitherArtifact.left().value();
} else {
- ret = eitherArtifact.right().value().getImplementation();
+ ret = eitherArtifact.right().value().getImplementationArtifact();
}
return ret;
}
@@ -3549,7 +3932,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
byte[] downloadedArtifact = null;
ComponentInstance resourceInstance = getRelatedComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
if (errorWrapper.isEmpty()) {
- auditAdditionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInstance.getName());
downloadedArtifact = downloadArtifact(resourceInstance.getDeploymentArtifacts(), artifactUUID, errorWrapper, resourceInstance.getName());
}
if (errorWrapper.isEmpty()) {
@@ -3568,39 +3950,41 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
* @param componentType
* @param componentUuid
* @param additionalParams
+ * @param operation
* @return
*/
- public Either<ArtifactDefinition, ResponseFormat> uploadArtifactToComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, Map<AuditingFieldsKeysEnum, Object> additionalParams) {
+ public Either<ArtifactDefinition, ResponseFormat> uploadArtifactToComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, Map<AuditingFieldsKeysEnum, Object> additionalParams,
+ ArtifactOperationInfo operation) {
Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
Either<ArtifactDefinition, ResponseFormat> uploadArtifactResult;
- ArtifactDefinition uploadArtifact;
+ ArtifactDefinition uploadArtifact = null;
Component component = null;
String componentId = null;
- ArtifactOperation operation = ArtifactOperation.Create;
- operation.setExternalApi(true);
ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
String origMd5 = request.getHeader(Constants.MD5_HEADER);
String userId = request.getHeader(Constants.USER_ID_HEADER);
- Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = getComponentOperation(componentType).getLatestComponentMetadataByUuid(componentType.getNodeType(), componentUuid);
+ Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata);
if (getComponentRes.isRight()) {
StorageOperationStatus status = getComponentRes.right().value();
log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
- errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
- }
- if (errorWrapper.isEmpty() && !getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
- component = checkoutParentComponent(componentType, getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(), userId, errorWrapper);
+ errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid));
}
if (errorWrapper.isEmpty()) {
- if (component != null) {
- componentId = component.getUniqueId();
- } else {
- componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
+ componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
+ String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
+
+ if (!getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
+ component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
+ if (component != null) {
+ componentId = component.getUniqueId();
+ componentName = component.getName();
+ }
}
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName);
}
if (errorWrapper.isEmpty()) {
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, getComponentRes.left().value().getMetadataDataDefinition().getName());
actionResult = handleArtifactRequest(componentId, userId, componentType, operation, null, artifactInfo, origMd5, data, null, null, null, null);
if (actionResult.isRight()) {
log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult.right().value());
@@ -3609,11 +3993,11 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
if (errorWrapper.isEmpty()) {
uploadArtifact = actionResult.left().value().left().value();
- updateAuditParametersWithArtifactDefinition(additionalParams, uploadArtifact);
uploadArtifactResult = Either.left(uploadArtifact);
} else {
uploadArtifactResult = Either.right(errorWrapper.getInnerElement());
}
+ updateAuditParametersWithArtifactDefinition(additionalParams, uploadArtifact);
return uploadArtifactResult;
}
@@ -3626,14 +4010,15 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
* @param componentUuid
* @param resourceInstanceName
* @param additionalParams
+ * @param operation
* @return
*/
public Either<ArtifactDefinition, ResponseFormat> uploadArtifactToRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName,
- Map<AuditingFieldsKeysEnum, Object> additionalParams) {
+ Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
Either<ArtifactDefinition, ResponseFormat> uploadArtifactResult;
Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
- ArtifactDefinition uploadArtifact;
+ ArtifactDefinition uploadArtifact = null;
Component component = null;
String componentInstanceId;
String componentId;
@@ -3641,11 +4026,11 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
String userId = request.getHeader(Constants.USER_ID_HEADER);
ImmutablePair<Component, ComponentInstance> componentRiPair = null;
- Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = getComponentOperation(componentType).getLatestComponentMetadataByUuid(componentType.getNodeType(), componentUuid);
+ Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata);
if (getComponentRes.isRight()) {
StorageOperationStatus status = getComponentRes.right().value();
log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
- errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
+ errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), resourceInstanceName));
}
if (errorWrapper.isEmpty() && !getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
component = checkoutParentComponent(componentType, getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(), userId, errorWrapper);
@@ -3660,9 +4045,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
if (errorWrapper.isEmpty()) {
componentInstanceId = componentRiPair.getRight().getUniqueId();
componentId = componentRiPair.getLeft().getUniqueId();
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInstanceName);
- ArtifactOperation operation = ArtifactOperation.Create;
- operation.setExternalApi(true);
ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, null, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum.findParamByType(componentType));
@@ -3673,11 +4055,11 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
if (errorWrapper.isEmpty()) {
uploadArtifact = actionResult.left().value().left().value();
- updateAuditParametersWithArtifactDefinition(additionalParams, uploadArtifact);
uploadArtifactResult = Either.left(uploadArtifact);
} else {
uploadArtifactResult = Either.right(errorWrapper.getInnerElement());
}
+ updateAuditParametersWithArtifactDefinition(additionalParams, uploadArtifact);
return uploadArtifactResult;
}
@@ -3690,45 +4072,46 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
* @param componentUuid
* @param artifactUUID
* @param additionalParams
+ * @param operation
+ * TODO
* @return
*/
public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID,
- Map<AuditingFieldsKeysEnum, Object> additionalParams) {
+ Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
- ArtifactDefinition updateArtifact;
+ ArtifactDefinition updateArtifact = null;
Component component = null;
String componentId = null;
String artifactId = null;
- ArtifactOperation operation = ArtifactOperation.Update;
- operation.setExternalApi(true);
ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
String origMd5 = request.getHeader(Constants.MD5_HEADER);
String userId = request.getHeader(Constants.USER_ID_HEADER);
- Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = getComponentOperation(componentType).getLatestComponentMetadataByUuid(componentType.getNodeType(), componentUuid);
+ Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata);
if (getComponentRes.isRight()) {
StorageOperationStatus status = getComponentRes.right().value();
log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
}
- if (errorWrapper.isEmpty() && !getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
- component = checkoutParentComponent(componentType, getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(), userId, errorWrapper);
- }
if (errorWrapper.isEmpty()) {
- if (component != null) {
- componentId = component.getUniqueId();
- } else {
- componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
+ componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
+ String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
+
+ if (!getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
+ component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
+ if (component != null) {
+ componentId = component.getUniqueId();
+ componentName = component.getName();
+ }
}
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName);
}
if (errorWrapper.isEmpty()) {
artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType);
}
if (errorWrapper.isEmpty()) {
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, getComponentRes.left().value().getMetadataDataDefinition().getName());
-
actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, data, null, null, null, null);
if (actionResult.isRight()) {
log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult.right().value());
@@ -3737,12 +4120,12 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
if (errorWrapper.isEmpty()) {
updateArtifact = actionResult.left().value().left().value();
- updateAuditParametersWithArtifactDefinition(additionalParams, updateArtifact);
updateArtifactResult = Either.left(updateArtifact);
} else {
updateArtifactResult = Either.right(errorWrapper.getInnerElement());
}
+ updateAuditParametersWithArtifactDefinition(additionalParams, updateArtifact);
return updateArtifactResult;
}
@@ -3756,15 +4139,17 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
* @param resourceInstanceName
* @param artifactUUID
* @param additionalParams
+ * @param operation
+ * TODO
* @return
*/
public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID,
- Map<AuditingFieldsKeysEnum, Object> additionalParams) {
+ Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
- ArtifactDefinition updateArtifact;
+ ArtifactDefinition updateArtifact = null;
Component component = null;
String componentInstanceId = null;
String componentId = null;
@@ -3773,7 +4158,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
String userId = request.getHeader(Constants.USER_ID_HEADER);
ImmutablePair<Component, ComponentInstance> componentRiPair = null;
- Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = getComponentOperation(componentType).getLatestComponentMetadataByUuid(componentType.getNodeType(), componentUuid);
+ Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata);
if (getComponentRes.isRight()) {
StorageOperationStatus status = getComponentRes.right().value();
log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
@@ -3792,12 +4177,9 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
if (errorWrapper.isEmpty()) {
componentInstanceId = componentRiPair.getRight().getUniqueId();
componentId = componentRiPair.getLeft().getUniqueId();
- artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentInstanceId, ComponentTypeEnum.RESOURCE_INSTANCE);
+ artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper);
}
if (errorWrapper.isEmpty()) {
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInstanceName);
- ArtifactOperation operation = ArtifactOperation.Update;
- operation.setExternalApi(true);
ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum.findParamByType(componentType));
@@ -3808,13 +4190,12 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
if (errorWrapper.isEmpty()) {
updateArtifact = actionResult.left().value().left().value();
- updateAuditParametersWithArtifactDefinition(additionalParams, updateArtifact);
updateArtifactResult = Either.left(updateArtifact);
} else {
updateArtifactResult = Either.right(errorWrapper.getInnerElement());
}
+ updateAuditParametersWithArtifactDefinition(additionalParams, updateArtifact);
return updateArtifactResult;
-
}
/**
@@ -3825,44 +4206,45 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
* @param componentUuid
* @param artifactUUID
* @param additionalParams
+ * @param operation
+ * TODO
* @return
*/
- public Either<ArtifactDefinition, ResponseFormat> deleteArtifactOnComponentByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID, Map<AuditingFieldsKeysEnum, Object> additionalParams) {
+ public Either<ArtifactDefinition, ResponseFormat> deleteArtifactOnComponentByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID, Map<AuditingFieldsKeysEnum, Object> additionalParams,
+ ArtifactOperationInfo operation) {
Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
Either<ArtifactDefinition, ResponseFormat> deleteArtifactResult;
Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
- ArtifactDefinition deleteArtifact;
+ ArtifactDefinition deleteArtifact = null;
Component component = null;
String componentId = null;
String artifactId = null;
- ArtifactOperation operation = ArtifactOperation.Delete;
- operation.setExternalApi(true);
String origMd5 = request.getHeader(Constants.MD5_HEADER);
String userId = request.getHeader(Constants.USER_ID_HEADER);
- Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = getComponentOperation(componentType).getLatestComponentMetadataByUuid(componentType.getNodeType(), componentUuid);
+ Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata);
if (getComponentRes.isRight()) {
StorageOperationStatus status = getComponentRes.right().value();
log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
- errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
- }
- if (errorWrapper.isEmpty() && !getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
- component = checkoutParentComponent(componentType, getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(), userId, errorWrapper);
+ errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid));
}
if (errorWrapper.isEmpty()) {
- if (component != null) {
- componentId = component.getUniqueId();
- } else {
- componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
+ componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
+ String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
+ if (!getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
+ component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
+ if (component != null) {
+ componentId = component.getUniqueId();
+ componentName = component.getName();
+ }
}
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName);
}
if (errorWrapper.isEmpty()) {
artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType);
}
if (errorWrapper.isEmpty()) {
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, getComponentRes.left().value().getMetadataDataDefinition().getName());
-
actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, null, origMd5, null, null, null, null, null);
if (actionResult.isRight()) {
log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult.right().value());
@@ -3871,16 +4253,16 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
if (errorWrapper.isEmpty()) {
deleteArtifact = actionResult.left().value().left().value();
- updateAuditParametersWithArtifactDefinition(additionalParams, deleteArtifact);
deleteArtifactResult = Either.left(deleteArtifact);
} else {
deleteArtifactResult = Either.right(errorWrapper.getInnerElement());
}
+ updateAuditParametersWithArtifactDefinition(additionalParams, deleteArtifact);
return deleteArtifactResult;
}
/**
- * deletes an artifact an a resource instance by UUID
+ * deletes an artifact from a resource instance by UUID
*
* @param request
* @param componentType
@@ -3888,15 +4270,17 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
* @param resourceInstanceName
* @param artifactUUID
* @param additionalParams
+ * @param operation
+ * TODO
* @return
*/
public Either<ArtifactDefinition, ResponseFormat> deleteArtifactOnRiByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID,
- Map<AuditingFieldsKeysEnum, Object> additionalParams) {
+ Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
Either<ArtifactDefinition, ResponseFormat> deleteArtifactResult;
Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
- ArtifactDefinition deleteArtifact;
+ ArtifactDefinition deleteArtifact = null;
Component component = null;
String componentInstanceId = null;
String componentId = null;
@@ -3904,7 +4288,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
String origMd5 = request.getHeader(Constants.MD5_HEADER);
String userId = request.getHeader(Constants.USER_ID_HEADER);
ImmutablePair<Component, ComponentInstance> componentRiPair = null;
- Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = getComponentOperation(componentType).getLatestComponentMetadataByUuid(componentType.getNodeType(), componentUuid);
+ Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata);
if (getComponentRes.isRight()) {
StorageOperationStatus status = getComponentRes.right().value();
log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
@@ -3923,14 +4307,10 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
if (errorWrapper.isEmpty()) {
componentInstanceId = componentRiPair.getRight().getUniqueId();
componentId = componentRiPair.getLeft().getUniqueId();
- artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentInstanceId, ComponentTypeEnum.RESOURCE_INSTANCE);
+ artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper);
}
if (errorWrapper.isEmpty()) {
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInstanceName);
- ArtifactOperation operation = ArtifactOperation.Delete;
- operation.setExternalApi(true);
-
actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, null, origMd5, null, null, null, componentId, ComponentTypeEnum.findParamByType(componentType));
if (actionResult.isRight()) {
@@ -3940,50 +4320,204 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
if (errorWrapper.isEmpty()) {
deleteArtifact = actionResult.left().value().left().value();
- updateAuditParametersWithArtifactDefinition(additionalParams, deleteArtifact);
deleteArtifactResult = Either.left(deleteArtifact);
} else {
deleteArtifactResult = Either.right(errorWrapper.getInnerElement());
}
+ updateAuditParametersWithArtifactDefinition(additionalParams, deleteArtifact);
return deleteArtifactResult;
}
+ private String findArtifactId(ComponentInstance instance, String artifactUUID, Wrapper<ResponseFormat> errorWrapper) {
+ String artifactId = null;
+ ArtifactDefinition foundArtifact = null;
+ if (instance.getDeploymentArtifacts() != null) {
+ foundArtifact = instance.getDeploymentArtifacts().values().stream().filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID().equals(artifactUUID)).findFirst().orElse(null);
+ }
+ if (foundArtifact == null && instance.getArtifacts() != null) {
+ foundArtifact = instance.getArtifacts().values().stream().filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID().equals(artifactUUID)).findFirst().orElse(null);
+ }
+ if (foundArtifact == null) {
+ log.debug("The artifact {} was not found on instance {}. ", artifactUUID, instance.getUniqueId());
+ errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID));
+ } else {
+ artifactId = foundArtifact.getUniqueId();
+ }
+ return artifactId;
+ }
+
+ public Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder(ArtifactDefinition artifact, String envType, String parentId, NodeTypeEnum parentType, String parentName, User user, Component component,
+ Map<String, String> existingEnvVersions) {
+ return createHeatEnvPlaceHolder(artifact, envType, parentId, parentType, parentName, user, component, existingEnvVersions, true);
+
+ }
+
+ @SuppressWarnings("unchecked")
+ public Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder(ArtifactDefinition artifact, String envType, String parentId, NodeTypeEnum parentType, String parentName, User user, Component component,
+ Map<String, String> existingEnvVersions, boolean overrideId) {
+ Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getDeploymentResourceInstanceArtifacts();
+ if (deploymentResourceArtifacts == null) {
+ log.debug("no deployment artifacts are configured for generated artifacts");
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ Map<String, Object> placeHolderData = (Map<String, Object>) deploymentResourceArtifacts.get(envType);
+ if (placeHolderData == null) {
+ log.debug("no env type {} are configured for generated artifacts", envType);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+
+ String envLabel = (artifact.getArtifactLabel() + HEAT_ENV_SUFFIX).toLowerCase();
+ String parentIdParam = parentId;
+ if (!overrideId) {
+ parentIdParam = null;
+ }
+ Either<ArtifactDefinition, ResponseFormat> createArtifactPlaceHolder = createArtifactPlaceHolderInfo(parentIdParam, envLabel, placeHolderData, user.getUserId(), ArtifactGroupTypeEnum.DEPLOYMENT, true);
+ if (createArtifactPlaceHolder.isRight()) {
+ return Either.right(createArtifactPlaceHolder.right().value());
+ }
+ ArtifactDefinition artifactHeatEnv = createArtifactPlaceHolder.left().value();
+ if (!overrideId) {
+ // fix for migration only!!!! create heat env placeholder according to heat id.
+ artifactHeatEnv.setUniqueId(artifact.getUniqueId() + HEAT_ENV_SUFFIX);
+ }
+
+ artifactHeatEnv.setGeneratedFromId(artifact.getUniqueId());
+ artifactHeatEnv.setHeatParamsUpdateDate(System.currentTimeMillis());
+ artifactHeatEnv.setTimeout(0);
+ buildHeatEnvFileName(artifact, artifactHeatEnv, placeHolderData);
+ // rbetzer - keep env artifactVersion - changeComponentInstanceVersion flow
+ handleEnvArtifactVersion(artifactHeatEnv, existingEnvVersions);
+ // clone heat parameters in case of heat env only not VF heat env
+ if (envType.equals(HEAT_ENV_NAME)) {
+ artifactHeatEnv.setHeatParameters(artifact.getHeatParameters());
+ }
+ ArtifactDefinition artifactDefinition;
+ // Evg : for resource instance artifact will be added later as block with other env artifacts from BL
+ if (parentType != NodeTypeEnum.ResourceInstance) {
+ Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact = addHeatEnvArtifact(artifactHeatEnv, artifact, component.getUniqueId(), parentType, parentId);
+ if (addHeatEnvArtifact.isRight()) {
+ log.debug("failed to create heat env artifact on resource instance");
+ return Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(addHeatEnvArtifact.right().value(), false), "", null));
+ }
+ artifactDefinition = createArtifactPlaceHolder.left().value();
+ } else {
+ artifactDefinition = artifactHeatEnv;
+ artifactToscaOperation.generateUUID(artifactDefinition, artifactDefinition.getArtifactVersion());
+ }
+
+ if (artifact.getHeatParameters() != null) {
+ List<HeatParameterDefinition> heatEnvParameters = new ArrayList<HeatParameterDefinition>();
+ for (HeatParameterDefinition parameter : artifact.getListHeatParameters()) {
+ HeatParameterDefinition heatEnvParameter = new HeatParameterDefinition(parameter);
+ heatEnvParameter.setDefaultValue(parameter.getCurrentValue());
+ heatEnvParameters.add(heatEnvParameter);
+ }
+ artifactDefinition.setListHeatParameters(heatEnvParameters);
+ }
+
+ // audit
+ EnumMap<AuditingFieldsKeysEnum, Object> artifactAuditingFields = createArtifactAuditingFields(artifactDefinition, "", artifactDefinition.getUniqueId());
+ artifactAuditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, parentName);
+ ComponentTypeEnum componentType = component.getComponentType();
+ if (parentType == NodeTypeEnum.ResourceInstance) {
+ componentType = ComponentTypeEnum.RESOURCE_INSTANCE;
+ }
+ componentsUtils.auditComponent(componentsUtils.getResponseFormat(ActionStatus.OK), user, component, "", "", AuditingActionEnum.ARTIFACT_UPLOAD, componentType, artifactAuditingFields);
+ return Either.left(artifactDefinition);
+ }
+
+ private void buildHeatEnvFileName(ArtifactDefinition heatArtifact, ArtifactDefinition heatEnvArtifact, Map<String, Object> placeHolderData) {
+ String heatExtension = GeneralUtility.getFilenameExtension(heatArtifact.getArtifactName());
+ String envExtension = (String) placeHolderData.get(ARTIFACT_PLACEHOLDER_FILE_EXTENSION);
+ String name = heatArtifact.getArtifactName();
+ String fileName;
+ if (name == null) {
+ name = heatArtifact.getArtifactLabel();
+ fileName = name + "." + envExtension;
+ } else {
+ fileName = name.replaceAll("." + heatExtension, "." + envExtension);
+ }
+ heatEnvArtifact.setArtifactName(fileName);
+ }
+
+ private void handleEnvArtifactVersion(ArtifactDefinition heatEnvArtifact, Map<String, String> existingEnvVersions) {
+ if (null != existingEnvVersions) {
+ String prevVersion = existingEnvVersions.get(heatEnvArtifact.getArtifactName());
+ if (null != prevVersion) {
+ heatEnvArtifact.setArtifactVersion(prevVersion);
+ }
+ }
+ }
+
+ /**
+ * Handles Artifacts Request For Inner Component
+ *
+ * @param artifactsToHandle
+ * @param component
+ * @param user
+ * @param vfcsNewCreatedArtifacts
+ * @param operation
+ * @param shouldLock
+ * @param inTransaction
+ * @return
+ */
+ public Either<List<ArtifactDefinition>, ResponseFormat> handleArtifactsRequestForInnerVfcComponent(List<ArtifactDefinition> artifactsToHandle, Resource component, User user, List<ArtifactDefinition> vfcsNewCreatedArtifacts,
+ ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) {
+
+ Either<List<ArtifactDefinition>, ResponseFormat> handleArtifactsResult = null;
+ ComponentTypeEnum componentType = component.getComponentType();
+ List<ArtifactDefinition> uploadedArtifacts = new ArrayList<>();
+ Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult;
+ String originData;
+ String origMd5;
+ try {
+ for (ArtifactDefinition artifact : artifactsToHandle) {
+ originData = buildJsonStringForCsarVfcArtifact(artifact);
+ origMd5 = GeneralUtility.calculateMD5ByString(originData);
+ actionResult = handleArtifactRequest(component.getUniqueId(), user.getUserId(), componentType, operation, artifact.getUniqueId(), artifact, origMd5, originData, null, null, null, null, shouldLock, inTransaction);
+ if (actionResult.isRight()) {
+ log.debug("Failed to upload artifact to component with type {} and name {}. Status is {}. ", componentType, component.getName(), actionResult.right().value());
+ errorWrapper.setInnerElement(actionResult.right().value());
+ if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create) {
+ vfcsNewCreatedArtifacts.addAll(uploadedArtifacts);
+ }
+ break;
+ }
+ uploadedArtifacts.add(actionResult.left().value().left().value());
+ }
+ if (errorWrapper.isEmpty()) {
+ handleArtifactsResult = Either.left(uploadedArtifacts);
+ } else {
+ handleArtifactsResult = Either.right(errorWrapper.getInnerElement());
+ }
+ } catch (Exception e) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
+ handleArtifactsResult = Either.right(responseFormat);
+ log.debug("Exception occured when handleArtifactsRequestForInnerVfcComponent, error is:{}", e.getMessage(), e);
+ }
+ return handleArtifactsResult;
+ }
+
private ComponentInstance getRelatedComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
ComponentInstance componentInstance = null;
- StorageOperationStatus status;
- Either<ComponentInstance, StorageOperationStatus> getResourceInstanceRes = null;
+ String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName);
Component component = getLatestComponentByUuid(componentType, componentUuid, errorWrapper);
if (errorWrapper.isEmpty()) {
- componentInstance = component.getComponentInstances().stream().filter(ci -> ci.getNormalizedName().equals(resourceInstanceName)).findAny().get();
+ componentInstance = component.getComponentInstances().stream().filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName()).equals(normalizedName)).findFirst().orElse(null);
if (componentInstance == null) {
errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component.getComponentType().getValue(), component.getName()));
log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName());
}
}
- if (errorWrapper.isEmpty()) {
- getResourceInstanceRes = resourceInstanceOperation.getResourceInstanceById(componentInstance.getUniqueId());
- if (getResourceInstanceRes.isRight()) {
- status = getResourceInstanceRes.right().value();
- errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
- }
- }
- if (errorWrapper.isEmpty()) {
- componentInstance = getResourceInstanceRes.left().value();
- getResourceInstanceRes = resourceInstanceOperation.getFullComponentInstance(componentInstance, componentType.getNodeType());
- if (getResourceInstanceRes.isRight()) {
- status = getResourceInstanceRes.right().value();
- errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
- } else {
- componentInstance = getResourceInstanceRes.left().value();
- }
- }
return componentInstance;
}
private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(Component component, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
ImmutablePair<Component, ComponentInstance> relatedComponentComponentInstancePair = null;
- ComponentInstance componentInstance = component.getComponentInstances().stream().filter(ci -> ci.getNormalizedName().equals(resourceInstanceName)).findAny().get();
+ String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName);
+ ComponentInstance componentInstance = component.getComponentInstances().stream().filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName()).equals(normalizedName)).findFirst().orElse(null);
if (componentInstance == null) {
errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component.getComponentType().getValue(), component.getName()));
log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName());
@@ -3998,7 +4532,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
ImmutablePair<Component, ComponentInstance> relatedComponentComponentInstancePair = null;
Component component = getLatestComponentByUuid(componentType, componentUuid, errorWrapper);
if (errorWrapper.isEmpty()) {
- componentInstance = component.getComponentInstances().stream().filter(ci -> ci.getNormalizedName().equals(resourceInstanceName)).findAny().get();
+ componentInstance = component.getComponentInstances().stream().filter(ci -> ci.getNormalizedName().equals(resourceInstanceName)).findFirst().orElse(null);
if (componentInstance == null) {
errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component.getComponentType().getValue(), component.getName()));
log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName());
@@ -4039,7 +4573,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
private Component getLatestComponentByUuid(ComponentTypeEnum componentType, String componentUuid, Wrapper<ResponseFormat> errorWrapper) {
Component component = null;
- Either<Component, StorageOperationStatus> getComponentRes = getComponentOperation(componentType).getLatestComponentByUuid(componentType.getNodeType(), componentUuid);
+ Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentByUuid(componentUuid);
if (getComponentRes.isRight()) {
StorageOperationStatus status = getComponentRes.right().value();
log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
@@ -4056,13 +4590,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
StorageOperationStatus storageStatus;
ArtifactDefinition latestArtifact = null;
List<ArtifactDefinition> artifacts = null;
- NodeTypeEnum parentType;
- if (componentType.equals(ComponentTypeEnum.RESOURCE)) {
- parentType = NodeTypeEnum.Resource;
- } else {
- parentType = NodeTypeEnum.Service;
- }
- Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifactsRes = artifactOperation.getArtifacts(parentId, parentType, false);
+ Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifactsRes = artifactToscaOperation.getArtifacts(parentId);
if (getArtifactsRes.isRight()) {
storageStatus = getArtifactsRes.right().value();
log.debug("Couldn't fetch artifacts data for parent component {} with uid {}, error: {}", componentType.name(), parentId, storageStatus);
@@ -4120,8 +4648,29 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
private void updateAuditParametersWithArtifactDefinition(Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactDefinition artifact) {
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifact.getArtifactUUID());
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, buildAuditingArtifactData(artifact));
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, artifact.getUpdaterFullName());
+ if (artifact == null) {
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, "");
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, "");
+ if (!additionalParams.containsKey(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID)) {
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, "");
+ }
+ } else {
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifact.getArtifactUUID());
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, buildAuditingArtifactData(artifact));
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, artifact.getUpdaterFullName());
+ }
+ }
+
+ private String buildJsonStringForCsarVfcArtifact(ArtifactDefinition artifact) {
+ Map<String, Object> json = new HashMap<>();
+ String artifactName = artifact.getArtifactName();
+ json.put(Constants.ARTIFACT_NAME, artifactName);
+ json.put(Constants.ARTIFACT_LABEL, artifact.getArtifactLabel());
+ json.put(Constants.ARTIFACT_TYPE, artifact.getArtifactType());
+ json.put(Constants.ARTIFACT_GROUP_TYPE, ArtifactGroupTypeEnum.DEPLOYMENT.getType());
+ json.put(Constants.ARTIFACT_DESCRIPTION, artifact.getDescription());
+ json.put(Constants.ARTIFACT_PAYLOAD_DATA, artifact.getPayloadData());
+ json.put(Constants.ARTIFACT_DISPLAY_NAME, artifact.getArtifactDisplayName());
+ return gson.toJson(json);
}
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AttributeBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AttributeBusinessLogic.java
index 15fe86da33..84cf20dcfa 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AttributeBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AttributeBusinessLogic.java
@@ -34,7 +34,7 @@ import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
-import org.openecomp.sdc.be.resources.data.AttributeData;
+
import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -78,10 +78,10 @@ public class AttributeBusinessLogic extends BaseBusinessLogic {
log.info("Failed to lock component {}. Error - {}", resourceId, lockResult);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
}
- try {
+ try {
// Get the resource from DB
- Either<Resource, StorageOperationStatus> status = getResource(resourceId);
+ Either<Resource, StorageOperationStatus> status = toscaOperationFacade.getToscaElement(resourceId);
if (status.isRight()) {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, ""));
}
@@ -111,17 +111,16 @@ public class AttributeBusinessLogic extends BaseBusinessLogic {
// add the new attribute to resource on graph
// need to get StorageOpaerationStatus and convert to ActionStatus from
// componentsUtils
- Either<AttributeData, StorageOperationStatus> either = attributeOperation.addAttribute(newAttributeDef, resourceId);
+ Either<AttributeDefinition, StorageOperationStatus> either = toscaOperationFacade.addAttributeOfResource(resource, newAttributeDef);
if (either.isRight()) {
result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(either.right().value()), resource.getName()));
return result;
}
-
- result = Either.left(attributeOperation.convertAttributeDataToAttributeDefinition(either.left().value(), newAttributeDef.getName(), resourceId));
+ result = Either.left(either.left().value());
+
return result;
} finally {
commitOrRollback(result);
- // unlock component
graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource);
}
@@ -150,7 +149,7 @@ public class AttributeBusinessLogic extends BaseBusinessLogic {
}
// Get the resource from DB
- Either<Resource, StorageOperationStatus> status = getResource(resourceId);
+ Either<Resource, StorageOperationStatus> status = toscaOperationFacade.getToscaElement(resourceId);
if (status.isRight()) {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, ""));
}
@@ -185,16 +184,16 @@ public class AttributeBusinessLogic extends BaseBusinessLogic {
*/
public Either<AttributeDefinition, ResponseFormat> updateAttribute(String resourceId, String attributeId, AttributeDefinition newAttDef, String userId) {
Either<AttributeDefinition, ResponseFormat> result = null;
-
+
StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource);
if (lockResult != StorageOperationStatus.OK) {
BeEcompErrorManager.getInstance().logBeFailedLockObjectError(UPDATE_ATTRIBUTE, NodeTypeEnum.Resource.name().toLowerCase(), resourceId);
+ log.info("Failed to lock component {}. Error - {}", resourceId, lockResult);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
}
-
try {
// Get the resource from DB
- Either<Resource, StorageOperationStatus> eitherResource = getResource(resourceId);
+ Either<Resource, StorageOperationStatus> eitherResource = toscaOperationFacade.getToscaElement(resourceId);
if (eitherResource.isRight()) {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, ""));
}
@@ -204,7 +203,7 @@ public class AttributeBusinessLogic extends BaseBusinessLogic {
if (!ComponentValidationUtils.canWorkOnResource(resource, userId)) {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
}
-
+
// verify attribute exist in resource
Either<AttributeDefinition, ResponseFormat> eitherAttribute = getAttribute(resourceId, attributeId, userId);
if (eitherAttribute.isRight()) {
@@ -221,7 +220,15 @@ public class AttributeBusinessLogic extends BaseBusinessLogic {
return Either.right(defaultValuesValidation.right().value());
}
// add the new property to resource on graph
- Either<AttributeData, StorageOperationStatus> eitherAttUpdate = attributeOperation.updateAttribute(attributeId, newAttDef, eitherAllDataTypes.left().value());
+
+ StorageOperationStatus validateAndUpdateAttribute = propertyOperation.validateAndUpdateProperty(newAttDef, eitherAllDataTypes.left().value());
+ if (validateAndUpdateAttribute != StorageOperationStatus.OK) {
+ log.debug("Problem while updating attribute with id {}. Reason - {}", attributeId, validateAndUpdateAttribute);
+ result = Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(validateAndUpdateAttribute), resource.getName()));
+ }
+
+
+ Either<AttributeDefinition, StorageOperationStatus> eitherAttUpdate = toscaOperationFacade.updateAttributeOfResource(resource, newAttDef);
if (eitherAttUpdate.isRight()) {
log.debug("Problem while updating attribute with id {}. Reason - {}", attributeId, eitherAttUpdate.right().value());
@@ -229,12 +236,13 @@ public class AttributeBusinessLogic extends BaseBusinessLogic {
return result;
}
- result = Either.left(attributeOperation.convertAttributeDataToAttributeDefinition(eitherAttUpdate.left().value(), newAttDef.getName(), resourceId));
+ result = Either.left(eitherAttUpdate.left().value());
return result;
} finally {
commitOrRollback(result);
graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource);
}
+
}
/**
@@ -246,7 +254,9 @@ public class AttributeBusinessLogic extends BaseBusinessLogic {
* @return
*/
public Either<AttributeDefinition, ResponseFormat> deleteAttribute(String resourceId, String attributeId, String userId) {
+
Either<AttributeDefinition, ResponseFormat> result = null;
+
Either<User, ResponseFormat> resp = validateUserExists(userId, "delete Attribute", false);
if (resp.isRight()) {
return Either.right(resp.right().value());
@@ -255,13 +265,13 @@ public class AttributeBusinessLogic extends BaseBusinessLogic {
StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource);
if (lockResult != StorageOperationStatus.OK) {
BeEcompErrorManager.getInstance().logBeFailedLockObjectError(DELETE_ATTRIBUTE, NodeTypeEnum.Resource.name().toLowerCase(), resourceId);
- result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
- return result;
+ log.info("Failed to lock component {}. Error - {}", resourceId, lockResult);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
}
try {
// Get the resource from DB
- Either<Resource, StorageOperationStatus> eitherResource = getResource(resourceId);
+ Either<Resource, StorageOperationStatus> eitherResource = toscaOperationFacade.getToscaElement(resourceId);
if (eitherResource.isRight()) {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, ""));
}
@@ -280,12 +290,13 @@ public class AttributeBusinessLogic extends BaseBusinessLogic {
String attributeName = eitherAttributeExist.left().value().getName();
// delete attribute of resource from graph
- Either<AttributeData, StorageOperationStatus> eitherAttributeDelete = attributeOperation.deleteAttribute(attributeId);
- if (eitherAttributeDelete.isRight()) {
- result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(eitherAttributeDelete.right().value()), resource.getName()));
+ StorageOperationStatus eitherAttributeDelete = toscaOperationFacade.deleteAttributeOfResource(resource, attributeName);
+ if (eitherAttributeDelete != StorageOperationStatus.OK) {
+ result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(eitherAttributeDelete), resource.getName()));
return result;
}
- result = Either.left(attributeOperation.convertAttributeDataToAttributeDefinition(eitherAttributeDelete.left().value(), attributeName, resourceId));
+
+ result = Either.left(eitherAttributeExist.left().value());
return result;
} finally {
commitOrRollback(result);
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/BaseBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/BaseBusinessLogic.java
index 93ddff38d5..df8460ca96 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/BaseBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/BaseBusinessLogic.java
@@ -20,57 +20,67 @@
package org.openecomp.sdc.be.components.impl;
+import java.util.ArrayList;
+import java.util.Arrays;
import java.util.List;
import java.util.Map;
+import java.util.function.Function;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.PropertyRule;
import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.ComponentInstanceInput;
+import org.openecomp.sdc.be.model.ComponentInstanceProperty;
import org.openecomp.sdc.be.model.ComponentParametersView;
import org.openecomp.sdc.be.model.DataTypeDefinition;
+import org.openecomp.sdc.be.model.GroupProperty;
import org.openecomp.sdc.be.model.IComplexDefaultValue;
import org.openecomp.sdc.be.model.LifecycleStateEnum;
-import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
-import org.openecomp.sdc.be.model.operations.api.IArtifactOperation;
+import org.openecomp.sdc.be.model.jsontitan.operations.ArtifactsOperations;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
import org.openecomp.sdc.be.model.operations.api.IAttributeOperation;
-import org.openecomp.sdc.be.model.operations.api.IComponentOperation;
import org.openecomp.sdc.be.model.operations.api.IElementOperation;
import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation;
+import org.openecomp.sdc.be.model.operations.api.IGroupInstanceOperation;
import org.openecomp.sdc.be.model.operations.api.IGroupOperation;
import org.openecomp.sdc.be.model.operations.api.IGroupTypeOperation;
import org.openecomp.sdc.be.model.operations.api.IPropertyOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.be.model.operations.impl.ComponentOperation;
-import org.openecomp.sdc.be.model.operations.impl.ProductOperation;
-import org.openecomp.sdc.be.model.operations.impl.ResourceOperation;
-import org.openecomp.sdc.be.model.operations.impl.ServiceOperation;
+import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
+import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
import org.openecomp.sdc.be.model.tosca.converters.PropertyValueConverter;
-import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.model.tosca.validators.DataTypeValidatorConverter;
+import org.openecomp.sdc.be.model.tosca.validators.PropertyTypeValidator;
+import org.openecomp.sdc.be.resources.data.PropertyValueData;
import org.openecomp.sdc.be.user.IUserBusinessLogic;
import org.openecomp.sdc.be.user.Role;
import org.openecomp.sdc.be.user.UserBusinessLogic;
import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.config.EcompErrorName;
import org.openecomp.sdc.common.datastructure.Wrapper;
+import org.openecomp.sdc.common.util.ValidationUtils;
import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
+import com.google.gson.JsonElement;
+
import fj.data.Either;
public abstract class BaseBusinessLogic {
@@ -82,17 +92,11 @@ public abstract class BaseBusinessLogic {
protected IUserBusinessLogic userAdmin;
@Autowired
- protected ResourceOperation resourceOperation;
-
- @Autowired
protected IGraphLockOperation graphLockOperation;
@Autowired
- protected ServiceOperation serviceOperation;
-
- @Autowired
- protected ProductOperation productOperation;
-
+ protected TitanDao titanDao;
+
@Autowired
protected TitanGenericDao titanGenericDao;
@@ -101,22 +105,32 @@ public abstract class BaseBusinessLogic {
@Autowired
protected IGroupOperation groupOperation;
+
+ @Autowired
+ protected IGroupInstanceOperation groupInstanceOperation;
@Autowired
protected IGroupTypeOperation groupTypeOperation;
- @Autowired
- protected IArtifactOperation artifactOperation;
+ /*@Autowired
+ protected IArtifactOperation artifactOperation;*/
+ @javax.annotation.Resource
+ protected ArtifactsOperations artifactToscaOperation;
- @Autowired
- protected IAttributeOperation attributeOperation;
+// @Autowired
+// protected IAttributeOperation attributeOperation;
@Autowired
- protected IPropertyOperation propertyOperation;
+ protected PropertyOperation propertyOperation;
@Autowired
protected ApplicationDataTypeCache applicationDataTypeCache;
+ @Autowired
+ protected ToscaOperationFacade toscaOperationFacade;
+
+ protected DataTypeValidatorConverter dataTypeValidatorConverter = DataTypeValidatorConverter.getInstance();
+
public void setUserAdmin(UserBusinessLogic userAdmin) {
this.userAdmin = userAdmin;
}
@@ -129,15 +143,20 @@ public abstract class BaseBusinessLogic {
this.graphLockOperation = graphLockOperation;
}
+ public void setToscaOperationFacade(ToscaOperationFacade toscaOperationFacade) {
+ this.toscaOperationFacade = toscaOperationFacade;
+ }
+
+
private static Logger log = LoggerFactory.getLogger(BaseBusinessLogic.class.getName());
+
+ public static final String EMPTY_VALUE = null;
protected Either<User, ResponseFormat> validateUserNotEmpty(User user, String ecompErrorContext) {
String userId = user.getUserId();
if (StringUtils.isEmpty(userId)) {
- // user.setUserId("UNKNOWN");
log.debug("User header is missing ");
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeUserMissingError, ecompErrorContext, user.getUserId());
BeEcompErrorManager.getInstance().logBeUserMissingError(ecompErrorContext, user.getUserId());
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
return Either.right(responseFormat);
@@ -166,7 +185,7 @@ public abstract class BaseBusinessLogic {
log.debug("validateUserExists - failed to authorize user, userId {}", userId);
}
log.debug("User is not listed. userId {}", userId);
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeUserMissingError, ecompErrorContext, userId);
+ BeEcompErrorManager.getInstance().logBeUserMissingError(ecompErrorContext, userId);
return Either.right(eitherCreator.right().value());
}
return Either.left(eitherCreator.left().value());
@@ -187,7 +206,6 @@ public abstract class BaseBusinessLogic {
}
if (log.isDebugEnabled())
log.debug("User is not listed. userId {}", userId);
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeUserMissingError, ecompErrorContext, userId);
BeEcompErrorManager.getInstance().logBeUserMissingError(ecompErrorContext, userId);
return Either.right(responseFormat);
}
@@ -223,7 +241,7 @@ public abstract class BaseBusinessLogic {
BeEcompErrorManager.getInstance().logBeFailedLockObjectError(ecompErrorContext, nodeType.getName(), componentId);
ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(lockResourceStatus, componentType);
ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus, component.getName());
- log.debug("Failed to lock component {} error - {}", componentId, actionStatus);
+ log.debug("Failed to lock component {} error - {}" ,componentId, actionStatus);
return Either.right(responseFormat);
}
}
@@ -233,9 +251,9 @@ public abstract class BaseBusinessLogic {
NodeTypeEnum nodeType = componentType.getNodeType();
if (false == inTransaction) {
if (either == null || either.isRight()) {
- titanGenericDao.rollback();
+ titanDao.rollback();
} else {
- titanGenericDao.commit();
+ titanDao.commit();
}
}
// unlock resource
@@ -265,17 +283,12 @@ public abstract class BaseBusinessLogic {
}
}
- protected Either<Component, ResponseFormat> validateComponentExists(String componentId, ComponentTypeEnum componentType, boolean inTransaction, boolean createNewTransaction) {
- ComponentOperation componentOperation = getComponentOperation(componentType);
- Either<Component, StorageOperationStatus> componentFound = null;
- // if(createNewTransaction){
- // componentFound = componentOperation.getComponent_tx(componentId,
- // inTransaction);
- // }
- // else{
- componentFound = componentOperation.getComponent(componentId, inTransaction);
- // }
-
+ protected Either<Component, ResponseFormat> validateComponentExists(String componentId, ComponentTypeEnum componentType, ComponentParametersView filter) {
+
+ if(filter == null){
+ filter = new ComponentParametersView();
+ }
+ Either<Component, StorageOperationStatus> componentFound = toscaOperationFacade.getToscaElement(componentId, filter);
if (componentFound.isRight()) {
StorageOperationStatus storageOperationStatus = componentFound.right().value();
ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageOperationStatus, componentType);
@@ -286,35 +299,33 @@ public abstract class BaseBusinessLogic {
return Either.left(componentFound.left().value());
}
- protected Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists(String componentId, ComponentTypeEnum componentType, ComponentParametersView componentParametersView, String userId,
- AuditingActionEnum auditingAction, User user) {
-
- ComponentOperation componentOperation = getComponentOperation(componentType);
-
- if (componentOperation == null) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
- log.debug("addGroup - not supported component type {}", componentType);
- // handleAuditing(auditingAction, null, componentId, user, null,
- // null, artifactId, responseFormat, componentType, null);
- return Either.right(responseFormat);
- }
- Either<? extends org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentResult = componentOperation.getComponent(componentId, componentParametersView, true);
-
- if (componentResult.isRight()) {
- ActionStatus status = (componentType.equals(ComponentTypeEnum.RESOURCE)) ? ActionStatus.RESOURCE_NOT_FOUND : ActionStatus.SERVICE_NOT_FOUND;
-
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, componentId);
-
- log.debug("Service not found, serviceId {}", componentId);
- // ComponentTypeEnum componentForAudit =
- // (componentType.equals(ComponentTypeEnum.RESOURCE)) ?
- // ComponentTypeEnum.RESOURCE : ComponentTypeEnum.SERVICE;
- // handleAuditing(auditingAction, null, componentId, user, null,
- // null, artifactId, responseFormat, componentForAudit, null);
- return Either.right(responseFormat);
- }
- return Either.left(componentResult.left().value());
- }
+// protected Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists(String componentId, ComponentTypeEnum componentType, ComponentParametersView componentParametersView, String userId,
+// AuditingActionEnum auditingAction, User user) {
+//
+// ComponentOperation componentOperation = getComponentOperation(componentType);
+//
+// if (componentOperation == null) {
+// ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
+// log.debug("addGroup - not supported component type {}", componentType);
+// return Either.right(responseFormat);
+// }
+// Either<? extends org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentResult = componentOperation.getComponent(componentId, componentParametersView, true);
+//
+// if (componentResult.isRight()) {
+// ActionStatus status = (componentType.equals(ComponentTypeEnum.RESOURCE)) ? ActionStatus.RESOURCE_NOT_FOUND : ActionStatus.SERVICE_NOT_FOUND;
+//
+// ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, componentId);
+//
+// log.debug("Service not found, serviceId {}", componentId);
+// // ComponentTypeEnum componentForAudit =
+// // (componentType.equals(ComponentTypeEnum.RESOURCE)) ?
+// // ComponentTypeEnum.RESOURCE : ComponentTypeEnum.SERVICE;
+// // handleAuditing(auditingAction, null, componentId, user, null,
+// // null, artifactId, responseFormat, componentForAudit, null);
+// return Either.right(responseFormat);
+// }
+// return Either.left(componentResult.left().value());
+// }
public Either<Boolean, ResponseFormat> validateCanWorkOnComponent(Component component, String userId) {
Either<Boolean, ResponseFormat> canWork = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
@@ -323,7 +334,7 @@ public abstract class BaseBusinessLogic {
return canWork;
}
- // verify user id is not null
+ // verify userId is not null
if (userId == null) {
log.debug("Current user userId is null");
return canWork;
@@ -345,47 +356,6 @@ public abstract class BaseBusinessLogic {
return Either.left(true);
}
- public ComponentOperation getComponentOperation(ComponentTypeEnum componentTypeEnum) {
- if (ComponentTypeEnum.SERVICE == componentTypeEnum) {
- return serviceOperation;
- } else if (ComponentTypeEnum.RESOURCE == componentTypeEnum) {
- return resourceOperation;
- } else if (ComponentTypeEnum.PRODUCT == componentTypeEnum) {
- return productOperation;
- }
- return null;
- }
-
- public IComponentOperation getIComponentOperation(ComponentTypeEnum componentTypeEnum) {
-
- switch (componentTypeEnum) {
- case SERVICE:
- return serviceOperation;
- case RESOURCE:
- return resourceOperation;
- case PRODUCT:
- return productOperation;
- default:
- break;
- }
-
- return null;
- }
-
- public ComponentOperation getComponentOperationByParentComponentType(ComponentTypeEnum parentComponentType) {
- switch (parentComponentType) {
- case SERVICE:
- return resourceOperation;
- case RESOURCE:
- return resourceOperation;
- case PRODUCT:
- return serviceOperation;
- default:
- break;
- }
- return null;
- }
-
public ComponentTypeEnum getComponentTypeByParentComponentType(ComponentTypeEnum parentComponentType) {
switch (parentComponentType) {
case SERVICE:
@@ -401,8 +371,8 @@ public abstract class BaseBusinessLogic {
}
// For UT
- public void setTitanGenericDao(TitanGenericDao titanGenericDao) {
- this.titanGenericDao = titanGenericDao;
+ public void setTitanGenericDao(TitanDao titanDao) {
+ this.titanDao = titanDao;
}
protected Either<Map<String, DataTypeDefinition>, ResponseFormat> getAllDataTypes(ApplicationDataTypeCache applicationDataTypeCache) {
@@ -453,23 +423,23 @@ public abstract class BaseBusinessLogic {
return Either.left(true);
}
- protected Either<Resource, StorageOperationStatus> getResource(final String resourceId) {
-
- log.debug("Get resource with id {}", resourceId);
- Either<Resource, StorageOperationStatus> status = resourceOperation.getResource(resourceId);
- if (status.isRight()) {
- log.debug("Resource with id {} was not found", resourceId);
- return Either.right(status.right().value());
- }
-
- Resource resource = status.left().value();
- if (resource == null) {
- BeEcompErrorManager.getInstance().logBeComponentMissingError("Property Business Logic", ComponentTypeEnum.RESOURCE.getValue(), resourceId);
- log.debug("General Error while get resource with id {}", resourceId);
- return Either.right(StorageOperationStatus.GENERAL_ERROR);
- }
- return Either.left(resource);
- }
+// protected Either<Resource, StorageOperationStatus> getResource(final String resourceId) {
+//
+// log.debug("Get resource with id {}", resourceId);
+// Either<Resource, StorageOperationStatus> status = resourceOperation.getResource(resourceId);
+// if (status.isRight()) {
+// log.debug("Resource with id {} was not found", resourceId);
+// return Either.right(status.right().value());
+// }
+//
+// Resource resource = status.left().value();
+// if (resource == null) {
+// BeEcompErrorManager.getInstance().logBeComponentMissingError("Property Business Logic", ComponentTypeEnum.RESOURCE.getValue(), resourceId);
+// log.debug("General Error while get resource with id {}", resourceId);
+// return Either.right(StorageOperationStatus.GENERAL_ERROR);
+// }
+// return Either.left(resource);
+// }
protected void handleDefaultValue(IComplexDefaultValue newAttributeDef, Map<String, DataTypeDefinition> dataTypes) {
// convert property
@@ -503,8 +473,7 @@ public abstract class BaseBusinessLogic {
}
protected void validateCanWorkOnComponent(String componentId, ComponentTypeEnum componentTypeEnum, String userId, Wrapper<ResponseFormat> errorWrapper) {
- IComponentOperation componentOperation = getIComponentOperation(componentTypeEnum);
- if (!ComponentValidationUtils.canWorkOnComponent(componentId, componentOperation, userId)) {
+ if (!ComponentValidationUtils.canWorkOnComponent(componentId, toscaOperationFacade, userId)) {
log.info("Restricted operation for user {} on {} {}", userId, componentTypeEnum.getValue(), componentId);
errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
}
@@ -531,10 +500,10 @@ public abstract class BaseBusinessLogic {
protected void commitOrRollback(Either<? extends Object, ResponseFormat> result) {
if (result == null || result.isRight()) {
log.warn("operation failed. do rollback");
- titanGenericDao.rollback();
+ titanDao.rollback();
} else {
log.debug("operation success. do commit");
- titanGenericDao.commit();
+ titanDao.commit();
}
}
@@ -555,9 +524,9 @@ public abstract class BaseBusinessLogic {
}
protected Either<Component, ResponseFormat> validateComponentExistsByFilter(String componentId, ComponentTypeEnum componentType, ComponentParametersView componentParametersView, boolean inTransaction) {
- ComponentOperation componentOperation = getComponentOperation(componentType);
+
Either<Component, StorageOperationStatus> componentFound = null;
- componentFound = componentOperation.getComponent(componentId, componentParametersView, inTransaction);
+ componentFound = toscaOperationFacade.getToscaElement(componentId, componentParametersView);
if (componentFound.isRight()) {
StorageOperationStatus storageOperationStatus = componentFound.right().value();
@@ -568,4 +537,267 @@ public abstract class BaseBusinessLogic {
}
return Either.left(componentFound.left().value());
}
+
+ protected Either<GroupProperty, ResponseFormat> validateFreeText(GroupProperty groupPropertyToUpdate) {
+
+ Either<GroupProperty, ResponseFormat> ret;
+ final String groupTypeValue = groupPropertyToUpdate.getValue();
+ if (!StringUtils.isEmpty(groupTypeValue)) {
+ if (!ValidationUtils.validateDescriptionLength(groupTypeValue)) {
+ ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT,
+ NodeTypeEnum.Property.getName(),
+ String.valueOf(ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH)));
+ }
+
+ else if (!ValidationUtils.validateIsEnglish(groupTypeValue)) {
+ ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_DESCRIPTION,
+ NodeTypeEnum.Property.getName()));
+ } else {
+ ret = Either.left(groupPropertyToUpdate);
+ }
+
+ } else {
+ ret = Either.left(groupPropertyToUpdate);
+ }
+ return ret;
+ }
+
+ @SuppressWarnings("unchecked")
+ protected <T extends Enum<T>> boolean enumHasValueFilter(String name, Function<String, T> enumGetter, T... enumValues) {
+ T enumFound = enumGetter.apply(name);
+ return Arrays.asList(enumValues).contains(enumFound);
+ }
+
+ protected Either<String, StorageOperationStatus> validatePropValueBeforeCreate(ComponentInstanceProperty property, String value, boolean isValidate, String innerType, Map<String, DataTypeDefinition> allDataTypes) {
+ String propertyType = property.getType();
+ ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
+
+ if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
+ SchemaDefinition def = property.getSchema();
+ if (def == null) {
+ log.debug("Schema doesn't exists for property of type {}", type);
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT));
+ }
+ PropertyDataDefinition propDef = def.getProperty();
+ if (propDef == null) {
+ log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
+
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT));
+ }
+ innerType = propDef.getType();
+ }
+
+ Either<Object, Boolean> isValid = validateAndUpdatePropertyValue(propertyType, value, isValidate, innerType, allDataTypes);
+
+ String newValue = value;
+ if (isValid.isRight()) {
+ Boolean res = isValid.right().value();
+ if (res == false) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT));
+ }
+ } else {
+ Object object = isValid.left().value();
+ if (object != null) {
+ newValue = object.toString();
+ }
+ }
+
+ ImmutablePair<String, Boolean> pair = validateAndUpdateRules(propertyType, property.getRules(), innerType, allDataTypes, isValidate);
+ log.debug("After validateAndUpdateRules. pair = {}", pair);
+ if (pair.getRight() != null && pair.getRight() == false) {
+ BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType);
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT));
+ }
+
+ return Either.left(newValue);
+ }
+
+ protected Either<String, StorageOperationStatus> validateInputValueBeforeCreate(ComponentInstanceInput property, String value, boolean isValidate, String innerType, Map<String, DataTypeDefinition> allDataTypes) {
+ String propertyType = property.getType();
+ ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
+
+ if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
+ SchemaDefinition def = property.getSchema();
+ if (def == null) {
+ log.debug("Schema doesn't exists for property of type {}", type);
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT));
+ }
+ PropertyDataDefinition propDef = def.getProperty();
+ if (propDef == null) {
+ log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
+
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT));
+ }
+ innerType = propDef.getType();
+ }
+
+ Either<Object, Boolean> isValid = validateAndUpdatePropertyValue(propertyType, value, isValidate, innerType, allDataTypes);
+
+ String newValue = value;
+ if (isValid.isRight()) {
+ Boolean res = isValid.right().value();
+ if (res == false) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT));
+ }
+ } else {
+ Object object = isValid.left().value();
+ if (object != null) {
+ newValue = object.toString();
+ }
+ }
+
+ ImmutablePair<String, Boolean> pair = validateAndUpdateRules(propertyType, property.getRules(), innerType, allDataTypes, isValidate);
+ log.debug("After validateAndUpdateRules. pair = {}", pair);
+ if (pair.getRight() != null && pair.getRight() == false) {
+ BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType);
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT));
+ }
+
+ return Either.left(newValue);
+ }
+
+ public Either<Object, Boolean> validateAndUpdatePropertyValue(String propertyType, String value, boolean isValidate, String innerType, Map<String, DataTypeDefinition> dataTypes) {
+ log.trace("Going to validate property value and its type. type = {}, value = {}", propertyType, value);
+ ToscaPropertyType type = getType(propertyType);
+
+ if (isValidate) {
+
+ if (type == null) {
+ DataTypeDefinition dataTypeDefinition = dataTypes.get(propertyType);
+ ImmutablePair<JsonElement, Boolean> validateResult = dataTypeValidatorConverter.validateAndUpdate(value, dataTypeDefinition, dataTypes);
+ if (validateResult.right.booleanValue() == false) {
+ log.debug("The value {} of property from type {} is invalid", value, propertyType);
+ return Either.right(false);
+ }
+ JsonElement jsonElement = validateResult.left;
+ String valueFromJsonElement = getValueFromJsonElement(jsonElement);
+ return Either.left(valueFromJsonElement);
+ }
+ log.trace("before validating property type {}", propertyType);
+ boolean isValidProperty = isValidValue(type, value, innerType, dataTypes);
+ if (false == isValidProperty) {
+ log.debug("The value {} of property from type {} is invalid", value, type);
+ return Either.right(false);
+ }
+ }
+ Object convertedValue = value;
+ if (false == isEmptyValue(value) && isValidate) {
+ PropertyValueConverter converter = type.getConverter();
+ convertedValue = converter.convert(value, innerType, dataTypes);
+ }
+ return Either.left(convertedValue);
+ }
+
+ public ImmutablePair<String, Boolean> validateAndUpdateRules(String propertyType, List<PropertyRule> rules, String innerType, Map<String, DataTypeDefinition> dataTypes, boolean isValidate) {
+
+ if (rules == null || rules.isEmpty() == true) {
+ return new ImmutablePair<String, Boolean>(null, true);
+ }
+
+ for (PropertyRule rule : rules) {
+ String value = rule.getValue();
+ Either<Object, Boolean> updateResult = validateAndUpdatePropertyValue(propertyType, value, isValidate, innerType, dataTypes);
+ if (updateResult.isRight()) {
+ Boolean status = updateResult.right().value();
+ if (status == false) {
+ return new ImmutablePair<String, Boolean>(value, status);
+ }
+ } else {
+ String newValue = null;
+ Object object = updateResult.left().value();
+ if (object != null) {
+ newValue = object.toString();
+ }
+ rule.setValue(newValue);
+ }
+ }
+
+ return new ImmutablePair<String, Boolean>(null, true);
+ }
+
+ protected boolean isValidValue(ToscaPropertyType type, String value, String innerType, Map<String, DataTypeDefinition> dataTypes) {
+ if (isEmptyValue(value)) {
+ return true;
+ }
+
+ PropertyTypeValidator validator = type.getValidator();
+
+ boolean isValid = validator.isValid(value, innerType, dataTypes);
+ if (true == isValid) {
+ return true;
+ } else {
+ return false;
+ }
+
+ }
+
+ public boolean isEmptyValue(String value) {
+ if (value == null) {
+ return true;
+ }
+ return false;
+ }
+
+ public boolean isNullParam(String value) {
+ if (value == null) {
+ return true;
+ }
+ return false;
+ }
+
+ public void addRulesToNewPropertyValue(PropertyValueData propertyValueData, ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId) {
+
+ List<PropertyRule> rules = resourceInstanceProperty.getRules();
+ if (rules == null) {
+ PropertyRule propertyRule = buildRuleFromPath(propertyValueData, resourceInstanceProperty, resourceInstanceId);
+ rules = new ArrayList<>();
+ rules.add(propertyRule);
+ } else {
+ rules = sortRules(rules);
+ }
+
+ propertyValueData.setRules(rules);
+ }
+
+ private PropertyRule buildRuleFromPath(PropertyValueData propertyValueData, ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId) {
+ List<String> path = resourceInstanceProperty.getPath();
+ // FOR BC. Since old Property values on VFC/VF does not have rules on
+ // graph.
+ // Update could be done on one level only, thus we can use this
+ // operation to avoid migration.
+ if (path == null || path.isEmpty() == true) {
+ path = new ArrayList<>();
+ path.add(resourceInstanceId);
+ }
+ PropertyRule propertyRule = new PropertyRule();
+ propertyRule.setRule(path);
+ propertyRule.setValue(propertyValueData.getValue());
+ return propertyRule;
+ }
+
+ private List<PropertyRule> sortRules(List<PropertyRule> rules) {
+
+ // TODO: sort the rules by size and binary representation.
+ // (x, y, .+) --> 110 6 priority 1
+ // (x, .+, z) --> 101 5 priority 2
+
+ return rules;
+ }
+
+ protected String getValueFromJsonElement(JsonElement jsonElement) {
+ String value = null;
+
+ if (jsonElement == null || jsonElement.isJsonNull()) {
+ value = EMPTY_VALUE;
+ } else {
+ if (jsonElement.toString().isEmpty()) {
+ value = "";
+ } else {
+ value = jsonElement.toString();
+ }
+ }
+
+ return value;
+ }
+
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CategoriesImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CategoriesImportManager.java
index 26ea80ac4b..57ab46346a 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CategoriesImportManager.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CategoriesImportManager.java
@@ -72,9 +72,7 @@ public class CategoriesImportManager {
NodeTypeEnum nodeTypeCategory = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentType, CategoryTypeEnum.CATEGORY);
NodeTypeEnum nodeTypeSubCategory = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentType, CategoryTypeEnum.SUBCATEGORY);
NodeTypeEnum nodeTypeGroup = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentType, CategoryTypeEnum.GROUPING);
- if (log.isDebugEnabled()) {
- log.debug("createCategoriesByDao: creating componentType:{} nodeTypeCategory:{} nodeTypeSubCategory:{} nodeTypeGroup:{}", componentType, nodeTypeCategory, nodeTypeSubCategory, nodeTypeGroup);
- }
+ log.debug("createCategoriesByDao: creating componentType:{} nodeTypeCategory:{} nodeTypeSubCategory:{} nodeTypeGroup:{}", componentType, nodeTypeCategory, nodeTypeSubCategory, nodeTypeGroup);
List<CategoryDefinition> newCategoriesvalue = new ArrayList<>();
for (CategoryDefinition category : entry.getValue()) {
@@ -124,16 +122,18 @@ public class CategoriesImportManager {
Either<GroupingDefinition, ActionStatus> createdGrouping = elementOperation.createGrouping(subcategory.getUniqueId(), grouping, nodeTypeGroup);
if (createdGrouping.isRight()) {
if (ActionStatus.COMPONENT_GROUPING_EXISTS_FOR_SUB_CATEGORY.equals(createdGrouping.right().value())) {
- log.debug(" create grouping for {}. group {} already exists", entry.getKey(), grouping.getName());
+ log.debug(" create grouping for {} group {} already exists ", entry.getKey(), grouping.getName());
String groupingId = UniqueIdBuilder.buildGroupingUid(grouping.getUniqueId(), grouping.getNormalizedName());
createdGrouping = elementOperation.getGroupingUniqueForType(nodeTypeGroup, groupingId);
if (createdGrouping.isRight()) {
- log.debug("failed to get grouping that exists groupingId: {}, type: {}", groupingId, nodeTypeGroup);
+ log.debug("failed to get grouping that exists groupingId: {} type: {}", groupingId, nodeTypeGroup);
return Either.right(componentsUtils.getResponseFormat(createdGrouping.right().value()));
}
}
- log.debug("Failed to create groupingcategory for {}, category {}, subcategory {}, grouping {}, error {}", entry.getKey(), category.getName(), subcategory.getName(), (grouping != null ? grouping.getName() : null),
- (createdGrouping != null && createdGrouping.right() != null ? createdGrouping.right().value() : null));
+ log.debug("Failed to create groupingcategory for {} category {} subcategory {} grouping {} error {}", entry.getKey(),
+ category.getName(), subcategory.getName(), grouping != null ? grouping.getName() : null,
+ createdGrouping != null && createdGrouping.right() != null ? createdGrouping.right().value() : null);
+
return Either.right(componentsUtils.getResponseFormat(createdGrouping.right().value()));
} else {
log.debug("createGroupingDeo: create Grouping was successful {}", createdGrouping.left().value());
@@ -147,15 +147,15 @@ public class CategoriesImportManager {
Either<SubCategoryDefinition, ActionStatus> createdSubCategory = elementOperation.createSubCategory(newcategory.getUniqueId(), subcategory, nodeTypeSubCategory);
if (createdSubCategory.isRight()) {
if (ActionStatus.COMPONENT_SUB_CATEGORY_EXISTS_FOR_CATEGORY.equals(createdSubCategory.right().value())) {
- log.debug(" create subcategory for {} category {}, alreay exists retrieving", entry.getKey(), newcategory.getName(), subcategory.getName());
+ log.debug(" create subcategory for {} category {} subcategory {} already exists retrieving", entry.getKey(), newcategory.getName(), subcategory.getName());
String subCategoryId = UniqueIdBuilder.buildSubCategoryUid(newcategory.getUniqueId(), subcategory.getNormalizedName());
createdSubCategory = elementOperation.getSubCategory(nodeTypeSubCategory, subCategoryId);
if (createdSubCategory.isRight()) {
- log.debug("failed to get sub category that exists subCategoryId: {}, type: {}", subCategoryId, nodeTypeSubCategory);
+ log.debug("failed to get sub category that exists subCategoryId: {} type: {}", subCategoryId, nodeTypeSubCategory);
return Either.right(componentsUtils.getResponseFormat(createdSubCategory.right().value()));
}
} else {
- log.debug("Failed to create subcategory for {} category {}, error {}", entry.getKey(), newcategory.getName(), subcategory.getName(), createdSubCategory.right().value());
+ log.debug("Failed to create subcategory for {} category: {} subcategory: {} error {}", entry.getKey(), newcategory.getName(), subcategory.getName(), createdSubCategory.right().value());
return Either.right(componentsUtils.getResponseFormat(createdSubCategory.right().value()));
}
} else {
@@ -168,7 +168,7 @@ public class CategoriesImportManager {
log.debug("createCategorieDeo: creating category {}", category);
Either<CategoryDefinition, ActionStatus> createdCategory = elementOperation.createCategory(category, nodeTypeCategory);
if (createdCategory.isRight()) {
- log.debug("Failed to create category for {}, error {}", entry.getKey(), category.getName(), createdCategory.right().value());
+ log.debug("Failed to create category for {} {} error {}", entry.getKey(), category.getName(), createdCategory.right().value());
if (!ActionStatus.COMPONENT_CATEGORY_ALREADY_EXISTS.equals(createdCategory.right().value())) {
return Either.right(componentsUtils.getResponseFormat(createdCategory.right().value()));
} else {
@@ -176,7 +176,7 @@ public class CategoriesImportManager {
String categoryId = UniqueIdBuilder.buildCategoryUid(category.getNormalizedName(), nodeTypeCategory);
createdCategory = elementOperation.getCategory(nodeTypeCategory, categoryId);
if (createdCategory.isRight()) {
- log.debug("failed to get category that exists categoryId: {}, type: {}", categoryId, nodeTypeCategory);
+ log.debug("failed to get category that exists categoryId: {} type: {}", categoryId, nodeTypeCategory);
return Either.right(componentsUtils.getResponseFormat(createdCategory.right().value()));
}
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CommonImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CommonImportManager.java
index 9b99b665f7..f97b4cf3f1 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CommonImportManager.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CommonImportManager.java
@@ -119,7 +119,7 @@ public class CommonImportManager {
}
} catch (Exception e) {
- log.debug("Failed to yaml file {} {}", elementTypesYml, e);
+ log.debug("Failed to yaml file {}", elementTypesYml, e);
return Either.right(ActionStatus.INVALID_YAML_FILE);
}
return Either.left(elementTypes);
@@ -133,7 +133,7 @@ public class CommonImportManager {
}
- enum ElementTypeEnum {
+ public enum ElementTypeEnum {
PolicyType, GroupType, DataType, CapabilityType, InterfaceLifecycleType
};
@@ -204,7 +204,7 @@ public class CommonImportManager {
Either<ActionStatus, ResponseFormat> validateElementType = validator.apply(elementType);
if (validateElementType.isRight()) {
ResponseFormat responseFormat = validateElementType.right().value();
- log.debug("Failed in validation of element type {}. Response is {}", elementType, responseFormat.getFormattedMessage());
+ log.debug("Failed in validation of element type: {}. Response is {}", elementType, responseFormat.getFormattedMessage());
eitherResult = Either.right(responseFormat);
break;
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogic.java
index 6c7b8b9bc7..f880883438 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogic.java
@@ -24,37 +24,59 @@ import java.util.ArrayList;
import java.util.Collection;
import java.util.EnumMap;
import java.util.HashMap;
-import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
-import java.util.Set;
+import java.util.function.Function;
+import java.util.function.Predicate;
import java.util.stream.Collectors;
+import org.apache.commons.collections.CollectionUtils;
+import org.apache.commons.collections.MapUtils;
+import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
-import org.apache.commons.lang3.tuple.ImmutableTriple;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
import org.openecomp.sdc.be.datamodel.api.HighestFilterEnum;
+import org.openecomp.sdc.be.datamodel.utils.UiComponentDataConverter;
+import org.openecomp.sdc.be.datatypes.components.ComponentMetadataDataDefinition;
import org.openecomp.sdc.be.datatypes.components.ServiceMetadataDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.ComponentFieldsEnum;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.FilterKeyEnum;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
import org.openecomp.sdc.be.model.ArtifactDefinition;
import org.openecomp.sdc.be.model.CapReqDef;
import org.openecomp.sdc.be.model.CapabilityDefinition;
import org.openecomp.sdc.be.model.Component;
import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.ComponentInstanceInput;
+import org.openecomp.sdc.be.model.ComponentInstanceProperty;
+import org.openecomp.sdc.be.model.ComponentParametersView;
+import org.openecomp.sdc.be.model.DataTypeDefinition;
+import org.openecomp.sdc.be.model.IComponentInstanceConnectedElement;
+import org.openecomp.sdc.be.model.InputDefinition;
+import org.openecomp.sdc.be.model.LifecycleStateEnum;
import org.openecomp.sdc.be.model.Operation;
+import org.openecomp.sdc.be.model.PropertyDefinition;
import org.openecomp.sdc.be.model.RequirementDefinition;
+import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.model.cache.ComponentCache;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.ComponentOperation;
+import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
+import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
import org.openecomp.sdc.be.resources.data.ComponentMetadataData;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer;
import org.openecomp.sdc.be.user.Role;
+import org.openecomp.sdc.be.utils.CommonBeUtils;
import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
import org.openecomp.sdc.common.api.ArtifactTypeEnum;
import org.openecomp.sdc.common.config.EcompErrorName;
@@ -65,6 +87,9 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
+import com.datastax.driver.core.UserType.Field;
+import com.wordnik.swagger.models.auth.In;
+
import fj.data.Either;
public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
@@ -75,6 +100,7 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
@Autowired
protected ComponentCache componentCache;
+
private static Logger log = LoggerFactory.getLogger(ComponentBusinessLogic.class.getName());
private static final String TAG_FIELD_LABEL = "tag";
@@ -85,6 +111,14 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
public abstract Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(String componentId, ComponentTypeEnum componentTypeEnum, String userId, String searchText);
+ /**
+ *
+ * @param componentId
+ * @param dataParamsToReturn
+ * @return
+ */
+ public abstract Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String componentId, List<String> dataParamsToReturn);
+
protected Either<User, ResponseFormat> validateUser(User user, String ecompErrorContext, Component component, AuditingActionEnum auditAction, boolean inTransaction) {
Either<User, ResponseFormat> userValidationResult = validateUserNotEmpty(user, ecompErrorContext);
ResponseFormat responseFormat;
@@ -193,12 +227,14 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
protected Either<Boolean, ResponseFormat> validateComponentNameUnique(User user, Component component, AuditingActionEnum actionEnum) {
ComponentTypeEnum type = component.getComponentType();
- ComponentOperation componentOperation = getComponentOperation(type);
- Either<Boolean, StorageOperationStatus> dataModelResponse;
- dataModelResponse = componentOperation.validateComponentNameExists(component.getName());
+ ResourceTypeEnum resourceType = null;
+ if(component instanceof Resource){
+ resourceType = ((Resource)component).getResourceType();
+ }
+ Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade.validateComponentNameExists(component.getName(), resourceType, type);
if (dataModelResponse.isLeft()) {
- if (dataModelResponse.left().value()) {
+ if ( !dataModelResponse.left().value()) {
return Either.left(true);
} else {
log.info("Component with name {} already exists", component.getName());
@@ -207,7 +243,6 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
return Either.right(errorResponse);
}
}
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "validateComponentNameUnique");
BeEcompErrorManager.getInstance().logBeSystemError("validateComponentNameUnique");
log.debug("Error while validateComponentNameUnique for component: {}", component.getName());
ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
@@ -216,12 +251,12 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
}
protected Either<Boolean, ResponseFormat> validateContactId(User user, Component component, AuditingActionEnum actionEnum) {
- log.debug("validate component contact info");
+ log.debug("validate component contactId");
ComponentTypeEnum type = component.getComponentType();
String contactId = component.getContactId();
if (!ValidationUtils.validateStringNotEmpty(contactId)) {
- log.info("contact info is missing.");
+ log.info("contact is missing.");
ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CONTACT, type.getValue());
componentsUtils.auditComponentAdmin(errorResponse, user, component, "", "", actionEnum, type);
return Either.right(errorResponse);
@@ -238,7 +273,7 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
private Either<Boolean, ResponseFormat> validateContactId(String contactId, ComponentTypeEnum type) {
if (contactId != null) {
if (!ValidationUtils.validateContactId(contactId)) {
- log.info("contact info is invalid.");
+ log.info("contact is invalid.");
ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CONTACT, type.getValue());
return Either.right(errorResponse);
}
@@ -247,6 +282,48 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
return Either.left(false);
}
+
+ public Either<Boolean, ResponseFormat> validateConformanceLevel(String componentId, ComponentTypeEnum componentTypeEnum, String userId) {
+ log.trace("validate conformance level");
+
+ if (componentTypeEnum != ComponentTypeEnum.SERVICE) {
+ log.error("conformance level validation for non service component, id {}", componentId);
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
+ return Either.right(errorResponse);
+ }
+
+ Either<User, ResponseFormat> resp = validateUserExists(userId, "validateConformanceLevel", false);
+ if (resp.isRight()) {
+ log.error("can't validate conformance level, user is not validated, id {}, userId {}", componentId, userId);
+ return Either.right(resp.right().value());
+ }
+
+ ComponentParametersView filter = new ComponentParametersView(true);
+ Either<Component, ResponseFormat> eitherComponent = validateComponentExists(componentId, componentTypeEnum, filter);
+ if (eitherComponent.isRight()) {
+ log.error("can't validate conformance level, component not found, id {}", componentId);
+ BeEcompErrorManager.getInstance().logBeComponentMissingError("validateConformanceLevel", componentTypeEnum.getValue(), componentId);
+ return Either.right(eitherComponent.right().value());
+ }
+
+ Component component = eitherComponent.left().value();
+ if (component.getConformanceLevel() == null || "".equals(component.getConformanceLevel())) {
+ log.error("component conformance level property is null or empty, id {}", componentId);
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
+ return Either.right(errorResponse);
+ }
+
+ String configConformanceLevel = ConfigurationManager.getConfigurationManager().getConfiguration().getMinToscaConformanceLevel();
+ Boolean result = true;
+ if (CommonBeUtils.conformanceLevelCompare(component.getConformanceLevel(), configConformanceLevel) < 0) {
+ log.error("invalid asset conformance level, id {}, asset conformanceLevel {}, config conformanceLevel {}", componentId, component.getConformanceLevel(), configConformanceLevel);
+ result = false;
+ }
+ log.trace("conformance level validation finished");
+
+ return Either.left(result);
+ }
+
protected Either<Boolean, ResponseFormat> validateIcon(User user, Component component, AuditingActionEnum actionEnum) {
log.debug("validate Icon");
ComponentTypeEnum type = component.getComponentType();
@@ -341,7 +418,7 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
if (ComponentTypeEnum.RESOURCE.equals(component.getComponentType())) {
return Either.left(true);
}
- log.debug("validate PROJECT_CODE name ");
+ log.debug("validate ProjectCode name ");
String projectCode = component.getProjectCode();
if (!ValidationUtils.validateStringNotEmpty(projectCode)) {
@@ -452,9 +529,7 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
* @return
*/
public <R extends Component> Either<R, StorageOperationStatus> getComponent(String componentId, ComponentTypeEnum componentTypeEnum) {
- ComponentOperation componentOperation = getComponentOperation(componentTypeEnum);
- Either<R, StorageOperationStatus> eitherComponent = componentOperation.getComponent(componentId, false);
- return eitherComponent;
+ return toscaOperationFacade.getToscaElement(componentId);
}
public Either<CapReqDef, ResponseFormat> getRequirementsAndCapabilities(String componentId, ComponentTypeEnum componentTypeEnum, String userId) {
@@ -463,103 +538,52 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
if (resp.isRight()) {
return Either.right(resp.right().value());
}
-
- Map<String, List<CapabilityDefinition>> capabilities = new HashMap<>();
- Map<String, List<RequirementDefinition>> requirements = new HashMap<>();
- Either<CapReqDef, ResponseFormat> eitherRet;
- ComponentOperation componentOperation = getComponentOperation(componentTypeEnum);
- Either<Component, ResponseFormat> eitherComponent = validateComponentExists(componentId, componentTypeEnum, false, true);
+ Either<CapReqDef, ResponseFormat> eitherRet = null;
+ ComponentParametersView filter = new ComponentParametersView(true);
+ filter.setIgnoreCapabilities(false);
+ filter.setIgnoreRequirements(false);
+ filter.setIgnoreComponentInstances(false);
+ Either<Component, ResponseFormat> eitherComponent = validateComponentExists(componentId, componentTypeEnum, filter);
if (eitherComponent.isLeft()) {
- Either<Map<String, List<CapabilityDefinition>>, TitanOperationStatus> eitherCapabilities = componentOperation.getCapabilities(eitherComponent.left().value(), componentTypeEnum.getNodeType(), false);
- if (eitherCapabilities.isRight()) {
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
- eitherRet = Either.right(errorResponse);
- } else {
- Either<Map<String, List<RequirementDefinition>>, TitanOperationStatus> eitherRequirements = componentOperation.getRequirements(eitherComponent.left().value(), componentTypeEnum.getNodeType(), false);
- if (eitherRequirements.isRight()) {
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
- eitherRet = Either.right(errorResponse);
- } else {
- requirements = eitherRequirements.left().value();
- capabilities = eitherCapabilities.left().value();
- eitherRet = Either.left(new CapReqDef(requirements, capabilities));
- }
- }
+ eitherRet = Either.left(new CapReqDef(eitherComponent.left().value().getRequirements(), eitherComponent.left().value().getCapabilities()));
} else {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeResourceMissingError, "getRequirementsAndCapabilities", componentId);
BeEcompErrorManager.getInstance().logBeComponentMissingError("getRequirementsAndCapabilities", componentTypeEnum.getValue(), componentId);
eitherRet = Either.right(eitherComponent.right().value());
}
-
return eitherRet;
}
public Either<List<Component>, ResponseFormat> getLatestVersionNotAbstractComponents(boolean isAbstractAbstract, HighestFilterEnum highestFilter, ComponentTypeEnum componentTypeEnum, String internalComponentType, List<String> componentUids,
String userId) {
-
- long startUser = System.currentTimeMillis();
- Either<User, ResponseFormat> resp = validateUserExists(userId, "get Latest Version Not Abstract Components", false);
- long endUser = System.currentTimeMillis();
- log.debug("Activation time of get user {} ms", (endUser - startUser));
- ResponseFormat responseFormat;
- if (resp.isLeft()) {
-
- List<Component> result = new ArrayList<Component>();
- Set<String> nonProcessesComponents = new HashSet<>();
- nonProcessesComponents.addAll(componentUids);
-
- long startGetComp = System.currentTimeMillis();
- // Read components from cache
- Set<String> filteredComponents = new HashSet<>();
- filteredComponents.addAll(componentUids);
-
- Either<ImmutableTriple<List<Component>, List<Component>, Set<String>>, ActionStatus> allPartialComponents = componentCache.getComponentsForLeftPanel(componentTypeEnum, internalComponentType, filteredComponents);
-
- if (allPartialComponents.isRight()) {
- log.debug("Components was not fetched from cache. Status is {}", allPartialComponents.right().value());
- } else {
- ImmutableTriple<List<Component>, List<Component>, Set<String>> immutableTriple = allPartialComponents.left().value();
- List<Component> processedComponents = immutableTriple.left;
- if (processedComponents != null) {
- result.addAll(processedComponents);
- }
- List<Component> dirtyComponents = immutableTriple.middle;
- if (dirtyComponents != null) {
- result.addAll(dirtyComponents);
- }
-
- Set<String> nonProcessesComponentsFromCache = immutableTriple.right;
- nonProcessesComponents = nonProcessesComponentsFromCache;
- }
- long endGetComp = System.currentTimeMillis();
- log.debug("Activation time of get Comp from cache {} ms", (endGetComp - startGetComp));
-
- // Fecth non cached components
- List<String> componentsUidToFetch = new ArrayList<String>();
- componentsUidToFetch.addAll(nonProcessesComponents);
-
- long startGetCompFromGraph = System.currentTimeMillis();
- if (componentsUidToFetch.size() > 0) {
- log.debug("Number of Components to fetch from graph is {}", componentsUidToFetch.size());
- ComponentOperation componentOperation = getComponentOperation(componentTypeEnum);
- Boolean isHighest = isHighest(highestFilter);
- Either<List<Component>, StorageOperationStatus> nonCheckoutCompResponse = componentOperation.getLatestVersionNotAbstractComponents(isAbstractAbstract, isHighest, componentTypeEnum, internalComponentType, componentsUidToFetch);
-
- if (nonCheckoutCompResponse.isLeft()) {
- log.debug("Retrived Resource successfully.");
- result.addAll(nonCheckoutCompResponse.left().value());
- } else {
- responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(nonCheckoutCompResponse.right().value()));
+ ResponseFormat responseFormat = null;
+ try{
+ Either<User, ResponseFormat> resp = validateUserExists(userId, "get Latest Version Not Abstract Components", false);
+
+ if (resp.isLeft()) {
+ List<Component> result = new ArrayList<>();
+ List<String> componentsUidToFetch = new ArrayList<>();
+ componentsUidToFetch.addAll(componentUids);
+
+ if (componentsUidToFetch.size() > 0) {
+ log.debug("Number of Components to fetch from graph is {}", componentsUidToFetch.size());
+ Boolean isHighest = isHighest(highestFilter);
+ Either<List<Component>, StorageOperationStatus> nonCheckoutCompResponse = toscaOperationFacade.getLatestVersionNotAbstractComponents(isAbstractAbstract, isHighest, componentTypeEnum, internalComponentType, componentsUidToFetch);
+
+ if (nonCheckoutCompResponse.isLeft()) {
+ log.debug("Retrived Resource successfully.");
+ result.addAll(nonCheckoutCompResponse.left().value());
+ } else {
+ responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(nonCheckoutCompResponse.right().value()));
+ }
}
+ return Either.left(result);
+ } else {
+ responseFormat = resp.right().value();
}
- long endGetCompFromGraph = System.currentTimeMillis();
- log.debug("Activation time of get Comp from graph {} ms", (endGetCompFromGraph - startGetCompFromGraph));
-
- return Either.left(result);
- } else {
- responseFormat = resp.right().value();
}
-
+ finally{
+ titanDao.commit();
+ }
return Either.right(responseFormat);
}
@@ -580,42 +604,27 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
return isHighest;
}
- public Either<List<Map<String, String>>, ResponseFormat> getLatestVersionNotAbstractComponentsUidOnly(boolean isAbstractAbstract, HighestFilterEnum highestFilter, ComponentTypeEnum componentTypeEnum, String internalComponentType, String userId) {
- Either<User, ResponseFormat> resp = validateUserExists(userId, "get Latest Version Not Abstract Components", false);
- ResponseFormat responseFormat;
- if (resp.isLeft()) {
-
- ComponentOperation componentOperation = getComponentOperation(componentTypeEnum);
- Boolean isHighest = isHighest(highestFilter);
- Either<Collection<ComponentMetadataData>, StorageOperationStatus> nonCheckoutCompResponse = componentOperation.getLatestVersionNotAbstractComponentsMetadataOnly(isAbstractAbstract, isHighest, componentTypeEnum, internalComponentType);
-
- if (nonCheckoutCompResponse.isLeft()) {
- log.debug("Retrived Resource successfully.");
- List<Map<String, String>> res = new ArrayList<>();
-
- // Map<String,String>resMap =
- // nonCheckoutCompResponse.left().value().stream().collect()
- // .collect(Collectors.toMap(
- // p -> p.getMetadataDataDefinition().getUniqueId(),
- // p-> p.getMetadataDataDefinition().getVersion()));
-
- res = nonCheckoutCompResponse.left().value().stream().map(p -> {
- HashMap<String, String> map = new HashMap<>();
- map.put("uid", p.getMetadataDataDefinition().getUniqueId());
- map.put("version", p.getMetadataDataDefinition().getVersion());
- Long lastUpdateDate = p.getMetadataDataDefinition().getLastUpdateDate();
- String lastUpdateDateStr = lastUpdateDate != null ? String.valueOf(lastUpdateDate.longValue()) : "0";
- map.put("timestamp", lastUpdateDateStr);
- return map;
- }).collect(Collectors.toList());
-
- return Either.left(res);
- }
- responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(nonCheckoutCompResponse.right().value()));
- } else {
- responseFormat = resp.right().value();
- }
+ public Either<List<Component>, ResponseFormat> getLatestVersionNotAbstractComponentsMetadata(boolean isAbstractAbstract, HighestFilterEnum highestFilter, ComponentTypeEnum componentTypeEnum, String internalComponentType, String userId) {
+ ResponseFormat responseFormat = null;
+ try{
+ Either<User, ResponseFormat> resp = validateUserExists(userId, "get Latest Version Not Abstract Components", false);
+ if (resp.isLeft()) {
+
+ Boolean isHighest = isHighest(highestFilter);
+ Either<List<Component>, StorageOperationStatus> nonCheckoutCompResponse = toscaOperationFacade.getLatestVersionNotAbstractMetadataOnly(isAbstractAbstract, isHighest, componentTypeEnum, internalComponentType);
+
+ if (nonCheckoutCompResponse.isLeft()) {
+ log.debug("Retrived Resource successfully.");
+ return Either.left(nonCheckoutCompResponse.left().value());
+ }
+ responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(nonCheckoutCompResponse.right().value()));
+ } else {
+ responseFormat = resp.right().value();
+ }
+ } finally {
+ titanDao.commit();
+ }
return Either.right(responseFormat);
}
@@ -623,6 +632,7 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
}
+ @SuppressWarnings("unchecked")
public void setToscaArtifactsPlaceHolders(Component component, User user) {
Map<String, ArtifactDefinition> artifactMap = component.getToscaArtifacts();
if (artifactMap == null) {
@@ -645,17 +655,37 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
}
public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> populateToscaArtifacts(Component component, User user, boolean isInCertificationRequest, boolean inTransaction, boolean shouldLock) {
+ return populateToscaArtifacts(component, user, isInCertificationRequest, inTransaction, shouldLock, true);
+ }
+
+ public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> populateToscaArtifacts(Component component, User user, boolean isInCertificationRequest, boolean inTransaction, boolean shouldLock, boolean fetchTemplatesFromDB) {
+ Either<Component, StorageOperationStatus> toscaElement = toscaOperationFacade.getToscaFullElement(component.getUniqueId());
+ if ( toscaElement.isRight() ){
+ ResponseFormat response = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(toscaElement.right().value(), component.getComponentType()));
+ return Either.right(response);
+ }
+ component = toscaElement.left().value();
Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateToscaRes = null;
if (component.getToscaArtifacts() != null && !component.getToscaArtifacts().isEmpty()) {
- ArtifactDefinition toscaArtifact = component.getToscaArtifacts().values().stream().filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.TOSCA_TEMPLATE.getType())).findAny().get();
- generateToscaRes = saveToscaArtifactPayload(toscaArtifact, component, user, isInCertificationRequest, shouldLock, inTransaction, true);
+ ArtifactDefinition toscaArtifact = component.getToscaArtifacts().values().stream()
+ .filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.TOSCA_TEMPLATE.getType()))
+ .findAny().get();
+ generateToscaRes = saveToscaArtifactPayload(toscaArtifact, component, user, isInCertificationRequest, shouldLock, inTransaction, fetchTemplatesFromDB);
if (generateToscaRes.isRight()) {
return generateToscaRes;
}
- toscaArtifact = component.getToscaArtifacts().values().stream().filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType())).findAny().get();
+ toscaArtifact = generateToscaRes.left().value().left().value();
+ component.getToscaArtifacts().put(toscaArtifact.getArtifactLabel(), toscaArtifact);
+ toscaArtifact = component.getToscaArtifacts().values().stream()
+ .filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType()))
+ .findAny().get();
generateToscaRes = saveToscaArtifactPayload(toscaArtifact, component, user, isInCertificationRequest, shouldLock, inTransaction, true);
}
- // TODO if csar artifact fails delete template artifact
+ if (generateToscaRes.isRight()) {
+ return generateToscaRes;
+ }
+ ArtifactDefinition toscaArtifact = generateToscaRes.left().value().left().value();
+ component.getToscaArtifacts().put(toscaArtifact.getArtifactLabel(), toscaArtifact);
return generateToscaRes;
}
@@ -665,23 +695,35 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
}
public Either<ImmutablePair<String, byte[]>, ResponseFormat> getToscaModelByComponentUuid(ComponentTypeEnum componentType, String uuid, EnumMap<AuditingFieldsKeysEnum, Object> additionalParam) {
- // get info
- ComponentOperation componentOperation = getComponentOperation(componentType);
- Either<Component, StorageOperationStatus> latestVersion = componentOperation.getLatestComponentByUuid(componentType.getNodeType(), uuid);
- if (latestVersion.isRight()) {
- ResponseFormat response = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(latestVersion.right().value(), componentType));
+
+ Either<List<Component>, StorageOperationStatus> latestVersionEither = toscaOperationFacade.getComponentListByUuid(uuid, null);
+
+ if (latestVersionEither.isRight()) {
+ ResponseFormat response = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(latestVersionEither.right().value(), componentType));
+ return Either.right(response);
+ }
+
+ List<Component> components = latestVersionEither.left().value();
+
+ Component component = components.stream().filter(c -> c.isHighestVersion()).findFirst().orElse(null);
+ if(component == null){
+ component = components.stream().filter(c -> c.getLifecycleState() == LifecycleStateEnum.CERTIFIED).findFirst().orElse(null);
+ }
+
+ if(component == null){
+ ResponseFormat response = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND, componentType));
return Either.right(response);
-
}
- Component component = latestVersion.left().value();
additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getName());
// TODO remove after migration - handle artifact not found(no
// placeholder)
if (null == component.getToscaArtifacts() || component.getToscaArtifacts().isEmpty()) {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ArtifactTypeEnum.TOSCA_CSAR.name()));
}
- ArtifactDefinition csarArtifact = component.getToscaArtifacts().values().stream().filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType())).findAny().get();
- return artifactsBusinessLogic.handleDownloadToscaModelRequest(component, csarArtifact, true, false);
+ ArtifactDefinition csarArtifact = component.getToscaArtifacts().values().stream()
+ .filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType()))
+ .findAny().get();
+ return artifactsBusinessLogic.handleDownloadToscaModelRequest(component, csarArtifact);
}
protected StorageOperationStatus markComponentToDelete(Component component) {
@@ -693,13 +735,10 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
return StorageOperationStatus.NOT_FOUND;
}
- ComponentOperation componentOperation = getComponentOperation(componentType);
-
- Either<Component, StorageOperationStatus> markResourceToDelete = componentOperation.markComponentToDelete(component, true);
- if (markResourceToDelete.isRight()) {
- StorageOperationStatus result = markResourceToDelete.right().value();
- log.debug("failed to mark component {} of type {} for delete. error = {}", uniqueId, componentType, result);
- return result;
+ StorageOperationStatus markResourceToDelete = toscaOperationFacade.markComponentToDelete(component);
+ if (StorageOperationStatus.OK != markResourceToDelete) {
+ log.debug("failed to mark component {} of type {} for delete. error = {}", uniqueId, componentType, markResourceToDelete);
+ return markResourceToDelete;
} else {
log.debug("Component {} of type {} was marked as deleted", uniqueId, componentType);
return StorageOperationStatus.OK;
@@ -756,43 +795,52 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
protected Either<List<String>, ResponseFormat> deleteMarkedComponents(ComponentTypeEnum componentType) {
- List<String> deletedComponents = new ArrayList<String>();
+// List<String> deletedComponents = new ArrayList<String>();
log.trace("start deleteMarkedComponents");
- ComponentOperation componentOperation = getComponentOperation(componentType);
- Either<List<String>, StorageOperationStatus> resourcesToDelete = componentOperation.getAllComponentsMarkedForDeletion();
- if (resourcesToDelete.isRight()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourcesToDelete.right().value(), componentType));
+ Either<List<String>, StorageOperationStatus> deleteMarkedElements = toscaOperationFacade.deleteMarkedElements(componentType);
+
+ titanDao.commit();
+ if ( deleteMarkedElements.isRight()){
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteMarkedElements.right().value(), componentType));
return Either.right(responseFormat);
}
-
- for (String resourceToDelete : resourcesToDelete.left().value()) {
-
- Either<String, ResponseFormat> deleteMarkedResource = deleteMarkedComponent(resourceToDelete, componentType);
- if (deleteMarkedResource.isLeft()) {
- deletedComponents.add(deleteMarkedResource.left().value());
- }
- }
-
+// ComponentOperation componentOperation = getComponentOperation(componentType);
+// Either<List<String>, StorageOperationStatus> resourcesToDelete = componentOperation.getAllComponentsMarkedForDeletion();
+// if (resourcesToDelete.isRight()) {
+// ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourcesToDelete.right().value(), componentType));
+// return Either.right(responseFormat);
+// }
+//
+// for (String resourceToDelete : resourcesToDelete.left().value()) {
+//
+// Either<String, ResponseFormat> deleteMarkedResource = deleteMarkedComponent(resourceToDelete, componentType);
+// if (deleteMarkedResource.isLeft()) {
+// deletedComponents.add(deleteMarkedResource.left().value());
+// }
+// }
+// if(deletedComponents.size() == 0) {
+// log.debug("Component list to delete is empty. do commit");
+// titanGenericDao.commit();
+// }
log.trace("end deleteMarkedComponents");
- return Either.left(deletedComponents);
+ return Either.left(deleteMarkedElements.left().value());
}
private Either<String, ResponseFormat> deleteMarkedComponent(String componentToDelete, ComponentTypeEnum componentType) {
Either<String, ResponseFormat> result = null;
- ComponentOperation componentOperation = getComponentOperation(componentType);
NodeTypeEnum compNodeType = componentType.getNodeType();
StorageOperationStatus lockResult = graphLockOperation.lockComponent(componentToDelete, compNodeType);
if (!lockResult.equals(StorageOperationStatus.OK)) {
BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedLockObjectError, "Delete marked component");
- log.debug("Failed to lock component {}. error - {}", componentToDelete, lockResult);
+ log.debug("Failed to lock component {} error - {}", componentToDelete, lockResult);
result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
return result;
}
try {
// check if resource has relations
- Either<Boolean, StorageOperationStatus> isResourceInUse = componentOperation.isComponentInUse(componentToDelete);
+ Either<Boolean, StorageOperationStatus> isResourceInUse = toscaOperationFacade.isComponentInUse(componentToDelete);
if (isResourceInUse.isRight()) {
log.info("deleteMarkedResource - failed to find relations to resource. id = {}, type = {}, error = {}", componentToDelete, componentType, isResourceInUse.right().value().name());
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
@@ -803,7 +851,7 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
if (isResourceInUse.isLeft() && isResourceInUse.left().value() == false) {
// delete resource and its artifacts in one transaction
- Either<List<ArtifactDefinition>, StorageOperationStatus> artifactsRes = componentOperation.getComponentArtifactsForDelete(componentToDelete, compNodeType, true);
+ Either<List<ArtifactDefinition>, StorageOperationStatus> artifactsRes = getComponentArtifactsForDelete(componentToDelete, compNodeType, true);
if (artifactsRes.isRight() && !artifactsRes.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
log.info("failed to check artifacts for component node. id = {}, type = {}, error = {}", componentToDelete, componentType, artifactsRes.right().value().name());
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
@@ -814,8 +862,8 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
if (artifactsRes.isLeft()) {
artifactsToDelete = artifactsRes.left().value();
}
-
- Either<Component, StorageOperationStatus> deleteComponentRes = componentOperation.deleteComponent(componentToDelete, true);
+
+ Either<Component, StorageOperationStatus> deleteComponentRes = toscaOperationFacade.deleteToscaComponent(componentToDelete);
if (deleteComponentRes.isRight()) {
log.info("failed to delete component. id = {}, type = {}, error = {}", componentToDelete, componentType, deleteComponentRes.right().value().name());
ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(deleteComponentRes.right().value());
@@ -846,15 +894,337 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
if (result == null || result.isRight()) {
BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "delete marked component");
log.debug("operation failed. do rollback");
- titanGenericDao.rollback();
+ titanDao.rollback();
} else {
log.debug("operation success. do commit");
- titanGenericDao.commit();
+ titanDao.commit();
}
graphLockOperation.unlockComponent(componentToDelete, compNodeType);
}
return result;
}
+
+ public Either<List<ArtifactDefinition>, StorageOperationStatus> getComponentArtifactsForDelete(String parentId, NodeTypeEnum parentType, boolean inTransacton) {
+ List<ArtifactDefinition> artifacts = new ArrayList<ArtifactDefinition>();
+ Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifactsResponse = artifactToscaOperation.getArtifacts(parentId);
+ if (artifactsResponse.isRight()) {
+ if (!artifactsResponse.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
+ log.debug("failed to retrieve artifacts for {} {}", parentType, parentId);
+ return Either.right(artifactsResponse.right().value());
+ }
+ } else {
+ artifacts.addAll(artifactsResponse.left().value().values());
+ }
+
+// if (NodeTypeEnum.Resource.equals(parentType)) {
+// Either<List<ArtifactDefinition>, StorageOperationStatus> interfacesArtifactsForResource = getAdditionalArtifacts(parentId, false, true);
+// if (artifactsResponse.isRight() && !interfacesArtifactsForResource.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
+// log.debug("failed to retrieve interface artifacts for {} {}", parentType, parentId);
+// return Either.right(interfacesArtifactsForResource.right().value());
+// } else if (artifactsResponse.isLeft()) {
+// artifacts.addAll(interfacesArtifactsForResource.left().value());
+// }
+// }
+ return Either.left(artifacts);
+ }
+
+ /**
+ *
+ * @param componentId
+ * @param user
+ * @param dataParamsToReturn - ui list of params to return
+ * @return
+ */
+
+ public Either<UiComponentDataTransfer, ResponseFormat> getComponentDataFilteredByParams(String componentId, User user, List<String> dataParamsToReturn) {
+
+ if (user != null) {
+ Either<User, ResponseFormat> eitherCreator = validateUserExists(user, "Get Component by filtered by ui params", false);
+ if (eitherCreator.isRight()) {
+ return Either.right(eitherCreator.right().value());
+ }
+ }
+
+ UiComponentDataTransfer result = new UiComponentDataTransfer();
+
+ if(dataParamsToReturn == null || dataParamsToReturn.isEmpty()) {
+ Either.left(result);
+
+ } else {
+ Either<UiComponentDataTransfer, ResponseFormat> uiDataTransferEither = getUiComponentDataTransferByComponentId(componentId, dataParamsToReturn);
+ if(uiDataTransferEither.isRight()){
+ return Either.right(uiDataTransferEither.right().value());
+ }
+ result = uiDataTransferEither.left().value();
+ }
+
+ return Either.left(result);
+ }
+
+ protected <T extends Component> void generateInputsFromGenericTypeProperties(T component, Resource genericType) {
+
+ List<PropertyDefinition> genericTypeProps = genericType.getProperties();
+ if(null != genericTypeProps) {
+ String genericUniqueId = genericType.getUniqueId();
+ List<InputDefinition> inputs = convertGenericTypePropertiesToInputsDefintion(genericTypeProps, genericUniqueId);
+ if(null != component.getInputs())
+ inputs.addAll(component.getInputs());
+ component.setInputs(inputs);
+ }
+ }
+
+ private List<InputDefinition> convertGenericTypePropertiesToInputsDefintion(List<PropertyDefinition> genericTypeProps, String genericUniqueId) {
+ return genericTypeProps.stream()
+ .map(p -> setInputDefinitionFromProp(p, genericUniqueId))
+ .collect(Collectors.toList());
+ }
+
+ private InputDefinition setInputDefinitionFromProp(PropertyDefinition prop, String genericUniqueId){
+ InputDefinition input = new InputDefinition(prop);
+ input.setOwnerId(genericUniqueId);
+ return input;
+ }
+
+ protected <T extends Component> Either<Resource, ResponseFormat> fetchAndSetDerivedFromGenericType(T component){
+
+ String genericTypeToscaName = component.fetchGenericTypeToscaNameFromConfig();
+ if(null == genericTypeToscaName)
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ Either<Resource, StorageOperationStatus> findLatestGeneric = toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(genericTypeToscaName);
+ if(findLatestGeneric.isRight())
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERIC_TYPE_NOT_FOUND, component.assetType(), genericTypeToscaName));
+ Resource genericTypeResource = findLatestGeneric.left().value();
+ component.setDerivedFromGenericInfo(genericTypeResource);
+ return Either.left(genericTypeResource);
+ }
+
+ public Either<Map<String, List<IComponentInstanceConnectedElement>>, ResponseFormat> getFilteredComponentInstanceProperties(String componentId, Map<FilterKeyEnum, List<String>> filters, String userId) {
+ Either<Map<String, List<IComponentInstanceConnectedElement>>, ResponseFormat> response = null;
+ Either<Component, StorageOperationStatus> getResourceRes = null;
+ try{
+ if(!filters.containsKey(FilterKeyEnum.NAME_FRAGMENT) && StringUtils.isEmpty(filters.get(FilterKeyEnum.NAME_FRAGMENT).get(0))){
+ response = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
+ }
+ if (userId != null && response == null) {
+ Either<User, ResponseFormat> validateUserRes = validateUserExists(userId, "Get filtered component instance properties", false);
+ if (validateUserRes.isRight()) {
+ response = Either.right(validateUserRes.right().value());
+ }
+ }
+ if(response == null){
+ getResourceRes = toscaOperationFacade.getToscaElement(componentId);
+ if(getResourceRes.isRight()){
+ response = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getResourceRes.right().value())));
+ }
+ }
+ if(response == null){
+ response = getFilteredComponentInstancesProperties(getResourceRes.left().value(), filters);
+ }
+ } catch(Exception e){
+ log.debug("The exception {} occured during filtered instance properties fetching. the containing component is {}. ", e, componentId);
+ response = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ } finally{
+ if (response.isLeft()){
+ toscaOperationFacade.commit();
+ } else {
+ toscaOperationFacade.rollback();
+ }
+ }
+ return response;
+ }
+
+ private Either<Map<String, List<IComponentInstanceConnectedElement>>, ResponseFormat> getFilteredComponentInstancesProperties(Component component, Map<FilterKeyEnum, List<String>> filters) {
+
+ Map<String, List<IComponentInstanceConnectedElement>> filteredProperties = new HashMap<>();
+ Either<Map<String, List<IComponentInstanceConnectedElement>>, ResponseFormat> result = Either.left(filteredProperties);
+ List<ComponentInstance> filteredInstances = getFilteredInstances(component, filters.get(FilterKeyEnum.RESOURCE_TYPE));
+ String propertyNameFragment= filters.get(FilterKeyEnum.NAME_FRAGMENT).get(0);
+ boolean searchByFragment = propertyNameFragment.length() > 3 ;
+ if(CollectionUtils.isNotEmpty(filteredInstances)){
+ for(ComponentInstance instance : filteredInstances){
+ if(component.getComponentInstancesProperties()!=null &&component.getComponentInstancesProperties().containsKey(instance.getUniqueId())){
+ List<IComponentInstanceConnectedElement> currProperties = getFilteredComponentInstanceProperties(component.getComponentInstancesProperties().get(instance.getUniqueId()), propertyNameFragment, searchByFragment);
+ if(CollectionUtils.isNotEmpty(currProperties)){
+ filteredProperties.put(instance.getUniqueId(), currProperties);
+ }
+ }
+ if(component.getComponentInstancesInputs()!=null && component.getComponentInstancesInputs().containsKey(instance.getUniqueId())){
+ List<IComponentInstanceConnectedElement> currInputs = getFilteredComponentInstanceInputs(component.getComponentInstancesInputs().get(instance.getUniqueId()), propertyNameFragment, searchByFragment);
+ if(CollectionUtils.isNotEmpty(currInputs)){
+ if(filteredProperties.get(instance.getUniqueId())!=null){
+ filteredProperties.get(instance.getUniqueId()).addAll(currInputs);
+ } else {
+ filteredProperties.put(instance.getUniqueId(), currInputs);
+ }
+ }
+ }
+ }
+ }
+ return result;
+ }
+
+ private List<IComponentInstanceConnectedElement> getFilteredComponentInstanceInputs(List<ComponentInstanceInput> inputs, String propertyNameFragment, boolean searchByFragment) {
+ return inputs.stream().filter(i -> isMatchingInput(i, propertyNameFragment, searchByFragment)).collect(Collectors.toList());
+ }
+
+ private List<IComponentInstanceConnectedElement> getFilteredComponentInstanceProperties(List<ComponentInstanceProperty> instanceProperties, String propertyNameFragment, boolean searchByFragment) {
+ return instanceProperties.stream().filter(p -> isMatchingProperty(p, propertyNameFragment, searchByFragment)).collect(Collectors.toList());
+ }
+
+ private boolean isMatchingInput(ComponentInstanceInput input, String propertyNameFragment, boolean searchByFragment) {
+ boolean isMatching = false;
+ if(searchByFragment && input.getName().toLowerCase().contains(propertyNameFragment)){
+ isMatching = true;
+ }
+ if(!searchByFragment && input.getName().equalsIgnoreCase(propertyNameFragment)){
+ isMatching = true;
+ }
+ return isMatching;
+ }
+
+ private boolean isMatchingProperty(ComponentInstanceProperty property, String propertyNameFragment, boolean searchByFragment) {
+ boolean isMatching = false;
+ if(searchByFragment && property.getName().toLowerCase().contains(propertyNameFragment)){
+ isMatching = true;
+ }
+ if(!searchByFragment && property.getName().equalsIgnoreCase(propertyNameFragment)){
+ isMatching = true;
+ }
+ if (!isMatching && !ToscaPropertyType.isPrimitiveType(property.getType())){
+ isMatching = isMatchingComplexPropertyByRecursively(property, propertyNameFragment, searchByFragment);
+ }
+ return isMatching;
+ }
+
+ private boolean isMatchingComplexPropertyByRecursively(PropertyDataDefinition property, String propertyNameFragment, boolean searchByFragment) {
+ String propertyType;
+ List<PropertyDefinition> dataTypeProperties;
+ DataTypeDefinition currentProperty;
+ if(searchByFragment && property.getName().toLowerCase().contains(propertyNameFragment.toLowerCase())){
+ return true;
+ }
+ if(!searchByFragment && property.getName().equalsIgnoreCase(propertyNameFragment)){
+ return true;
+ }
+
+ propertyType = isEmptyInnerType(property) ? property.getType() : property.getSchema().getProperty().getType();
+
+ if(ToscaPropertyType.isScalarType(propertyType)){
+ return false;
+ }
+ Either<DataTypeDefinition, StorageOperationStatus> getDataTypeByNameRes = propertyOperation.getDataTypeByName(propertyType);
+ if(getDataTypeByNameRes.isRight()){
+ return false;
+ }
+ currentProperty = getDataTypeByNameRes.left().value();
+ dataTypeProperties = currentProperty.getProperties();
+
+ if(CollectionUtils.isNotEmpty(dataTypeProperties)){
+ for(PropertyDefinition prop : dataTypeProperties){
+ if(isMatchingComplexPropertyByRecursively(prop, propertyNameFragment, searchByFragment)){
+ return true;
+ }
+ }
+ }
+ dataTypeProperties = currentProperty.getDerivedFrom().getProperties();
+ if(CollectionUtils.isNotEmpty(dataTypeProperties)){
+ for(PropertyDefinition prop : dataTypeProperties){
+ if(isMatchingComplexPropertyByRecursively(prop, propertyNameFragment, searchByFragment)){
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ private boolean isEmptyInnerType(PropertyDataDefinition property) {
+ return property == null|| property.getSchema() == null || property.getSchema().getProperty() == null || property.getSchema().getProperty().getType() == null;
+ }
+
+ public Either<Boolean, ResponseFormat> shouldUpgradeToLatestGeneric(Component clonedComponent) {
+
+ if(!clonedComponent.deriveFromGeneric())
+ return Either.left(false);
+ Boolean shouldUpgrade = false;
+ String currentGenericType = clonedComponent.getDerivedFromGenericType();
+ String currentGenericVersion = clonedComponent.getDerivedFromGenericVersion();
+ Either<Resource, ResponseFormat> fetchAndSetLatestGeneric = fetchAndSetDerivedFromGenericType(clonedComponent);
+ if(fetchAndSetLatestGeneric.isRight())
+ return Either.right(fetchAndSetLatestGeneric.right().value());
+ Resource genericTypeResource = fetchAndSetLatestGeneric.left().value();
+ if(null == currentGenericType || !currentGenericType.equals(genericTypeResource.getToscaResourceName()) || !currentGenericVersion.equals(genericTypeResource.getVersion())){
+ List<PropertyDefinition> genericTypeProps = genericTypeResource.getProperties();
+ List<InputDefinition> genericTypeInputs = null == genericTypeProps? null : convertGenericTypePropertiesToInputsDefintion(genericTypeProps, genericTypeResource.getUniqueId());
+ shouldUpgrade = upgradeToLatestGeneric(clonedComponent, genericTypeInputs);
+ if(!shouldUpgrade) {
+ reverntUpdateOfGenericVersion(clonedComponent, currentGenericType, currentGenericVersion);
+ }
+ }
+ return Either.left(shouldUpgrade);
+ }
+
+ private void reverntUpdateOfGenericVersion(Component clonedComponent, String currentGenericType, String currentGenericVersion) {
+ clonedComponent.setDerivedFromGenericType(currentGenericType);
+ clonedComponent.setDerivedFromGenericVersion(currentGenericVersion);
+ }
+
+
+ private boolean upgradeToLatestGeneric(Component componentToCheckOut, List<InputDefinition> upgradedList) {
+
+ if (!componentToCheckOut.shouldGenerateInputs())
+ return true;
+
+ List<InputDefinition> currentList = new ArrayList<>();
+ // nullify existing ownerId from existing list and merge into updated list
+ if (null != componentToCheckOut.getInputs()) {
+ for(InputDefinition input : componentToCheckOut.getInputs()) {
+ InputDefinition copy = new InputDefinition(input);
+ copy.setOwnerId(null);
+ currentList.add(copy);
+ }
+ }
+ if (null == upgradedList) {
+ componentToCheckOut.setInputs(currentList);
+ return true;
+ }
+ Map<String, InputDefinition> currentMap = PropertyDataDefinition.listToMapByName(currentList);
+ Map<String, InputDefinition> upgradedMap = PropertyDataDefinition.listToMapByName(upgradedList);
+ Either<Map<String, InputDefinition>, String> eitherMerged = PropertyDataDefinition.mergeProperties(upgradedMap, currentMap, true);
+ if (eitherMerged.isRight()) {
+ log.debug("property {} cannot be overriden, check out performed without upgrading to latest generic", eitherMerged.right().value());
+ return false;
+ }
+ componentToCheckOut.setInputs(new ArrayList<InputDefinition>(eitherMerged.left().value().values()));
+ return true;
+ }
+
+ private List<ComponentInstance> getFilteredInstances(Component component, List<String> resourceTypes) {
+ List<ComponentInstance> filteredInstances = null;
+ if(CollectionUtils.isEmpty(resourceTypes)){
+ filteredInstances = component.getComponentInstances();
+ }
+ else if(CollectionUtils.isNotEmpty(component.getComponentInstances())){
+ filteredInstances = component.getComponentInstances()
+ .stream().filter(i -> isMatchingType(i.getOriginType(), resourceTypes)).collect(Collectors.toList());
+ }
+ if(filteredInstances == null){
+ filteredInstances = new ArrayList<>();
+ }
+ return filteredInstances;
+ }
+
+ private boolean isMatchingType(OriginTypeEnum originType, List<String> resourceTypes) {
+ boolean isMatchingType = false;
+ for(String resourceType : resourceTypes){
+ if(originType == OriginTypeEnum.findByValue(resourceType.toUpperCase())){
+ isMatchingType = true;
+ break;
+ }
+ }
+ return isMatchingType;
+ }
}
+
+
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogic.java
index 89ef6f7e19..1623375926 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogic.java
@@ -21,21 +21,32 @@
package org.openecomp.sdc.be.components.impl;
import java.util.ArrayList;
-import java.util.EnumMap;
import java.util.HashMap;
+import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
+import java.util.Optional;
+import java.util.UUID;
import java.util.stream.Collectors;
+import org.apache.commons.collections.CollectionUtils;
+import org.apache.commons.collections.MapUtils;
+import org.apache.commons.lang.StringUtils;
+import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
-import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
+import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
+import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
import org.openecomp.sdc.be.info.CreateAndAssotiateInfo;
import org.openecomp.sdc.be.model.ArtifactDefinition;
import org.openecomp.sdc.be.model.Component;
@@ -44,25 +55,29 @@ import org.openecomp.sdc.be.model.ComponentInstanceAttribute;
import org.openecomp.sdc.be.model.ComponentInstanceInput;
import org.openecomp.sdc.be.model.ComponentInstanceProperty;
import org.openecomp.sdc.be.model.ComponentParametersView;
-import org.openecomp.sdc.be.model.HeatParameterDefinition;
+import org.openecomp.sdc.be.model.DataTypeDefinition;
+import org.openecomp.sdc.be.model.GroupDefinition;
+import org.openecomp.sdc.be.model.GroupInstance;
import org.openecomp.sdc.be.model.LifecycleStateEnum;
+import org.openecomp.sdc.be.model.PropertyDefinition.PropertyNames;
+import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
-import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
import org.openecomp.sdc.be.model.operations.api.IComponentInstanceOperation;
-import org.openecomp.sdc.be.model.operations.api.IComponentOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.be.model.operations.impl.ComponentOperation;
-import org.openecomp.sdc.be.model.operations.impl.GroupOperation;
+import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
-import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
+import org.openecomp.sdc.be.resources.data.ComponentInstanceData;
+import org.openecomp.sdc.be.resources.data.PropertyValueData;
import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
import org.openecomp.sdc.common.api.ArtifactTypeEnum;
import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
import org.openecomp.sdc.common.datastructure.Wrapper;
-import org.openecomp.sdc.common.util.GeneralUtility;
+import org.openecomp.sdc.common.jsongraph.util.CommonUtility;
+import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum;
import org.openecomp.sdc.common.util.ValidationUtils;
import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
@@ -73,95 +88,86 @@ import fj.data.Either;
public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
- private static final String ARTIFACT_PLACEHOLDER_FILE_EXTENSION = "fileExtension";
-
- static final String HEAT_ENV_NAME = "heatEnv";
- private static final String HEAT_ENV_SUFFIX = "env";
-
private static Logger log = LoggerFactory.getLogger(ComponentInstanceBusinessLogic.class.getName());
@Autowired
private IComponentInstanceOperation componentInstanceOperation;
@Autowired
- private PropertyOperation propertyOperation;
-
- @Autowired
private ArtifactsBusinessLogic artifactBusinessLogic;
-
@Autowired
- private GroupOperation groupOperation;
+ private ApplicationDataTypeCache dataTypeCache;
+
+ public static final String VF_MODULE = "org.openecomp.groups.VfModule";
public ComponentInstanceBusinessLogic() {
}
public Either<ComponentInstance, ResponseFormat> createComponentInstance(String containerComponentParam, String containerComponentId, String userId, ComponentInstance resourceInstance) {
- return createComponentInstance(containerComponentParam, containerComponentId, userId, resourceInstance, true, true, true);
+ return createComponentInstance(containerComponentParam, containerComponentId, userId, resourceInstance, false, true);
}
- public Either<ComponentInstance, ResponseFormat> createComponentInstance(String containerComponentParam, String containerComponentId, String userId, ComponentInstance resourceInstance, boolean inTransaction, boolean needLock,
- boolean createNewTransaction) {
-
- Either<User, ResponseFormat> resp = validateUserExists(userId, "create Component Instance", inTransaction);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
-
- Either<Boolean, ResponseFormat> validateValidJson = validateJsonBody(resourceInstance, ComponentInstance.class);
- if (validateValidJson.isRight()) {
- return Either.right(validateValidJson.right().value());
- }
+ public Either<ComponentInstance, ResponseFormat> createComponentInstance(String containerComponentParam, String containerComponentId, String userId, ComponentInstance resourceInstance, boolean inTransaction, boolean needLock) {
- Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
- if (validateComponentType.isRight()) {
- return Either.right(validateComponentType.right().value());
- }
-
- final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
- final ComponentOperation containerOperation = getComponentOperation(containerComponentType);
-
- Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, inTransaction, createNewTransaction);
- if (validateComponentExists.isRight()) {
- return Either.right(validateComponentExists.right().value());
- }
- org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
-
- Either<Boolean, ResponseFormat> validateAllowedToContainCompInstances = validateAllowedToContainCompInstances(containerComponent);
- if (validateAllowedToContainCompInstances.isRight()) {
- return Either.right(validateAllowedToContainCompInstances.right().value());
- }
-
- Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
- if (validateCanWorkOnComponent.isRight()) {
- return Either.right(validateCanWorkOnComponent.right().value());
- }
- if (resourceInstance != null && containerComponentType != null) {
- Either<Boolean, ResponseFormat> validateComponentInstanceParentState = validateComponentInstanceParentState(containerComponentType, resourceInstance);
- if (validateComponentInstanceParentState.isRight()) {
- return Either.right(validateComponentInstanceParentState.right().value());
+ Component origComponent = null;
+ Either<ComponentInstance, ResponseFormat> resultOp = null;
+ User user = null;
+ org.openecomp.sdc.be.model.Component containerComponent = null;
+ ComponentTypeEnum containerComponentType;
+
+ try{
+ Either<User, ResponseFormat> resp = validateUserExists(userId, "create Component Instance", inTransaction);
+ if (resp.isRight()) {
+ return Either.right(resp.right().value());
+ } else {
+ user = resp.left().value();
}
- }
- if (needLock) {
-
- Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "createComponentInstance");
- if (lockComponent.isRight()) {
- return Either.right(lockComponent.right().value());
+ Either<Boolean, ResponseFormat> validateValidJson = validateJsonBody(resourceInstance, ComponentInstance.class);
+ if (validateValidJson.isRight()) {
+ return Either.right(validateValidJson.right().value());
}
- }
-
- Either<ComponentInstance, ResponseFormat> resultOp = null;
- try {
- log.debug("Try to create entry on graph");
- Either<Component, ResponseFormat> eitherResourceName = getOriginComponentNameFromComponentInstance(resourceInstance, inTransaction);
-
- if (eitherResourceName.isRight()) {
- resultOp = Either.right(eitherResourceName.right().value());
- return resultOp;
+
+ Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
+ if (validateComponentType.isRight()) {
+ return Either.right(validateComponentType.right().value());
+ } else {
+ containerComponentType = validateComponentType.left().value();
}
- Component origComponent = eitherResourceName.left().value();
-
- resultOp = createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, userId, containerOperation, inTransaction);
+
+ Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
+ if (validateComponentExists.isRight()) {
+ return Either.right(validateComponentExists.right().value());
+ } else {
+ containerComponent = validateComponentExists.left().value();
+ }
+
+ Either<Boolean, ResponseFormat> validateAllowedToContainCompInstances = validateAllowedToContainCompInstances(containerComponent);
+ if (validateAllowedToContainCompInstances.isRight()) {
+ return Either.right(validateAllowedToContainCompInstances.right().value());
+ }
+
+ Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
+ if (validateCanWorkOnComponent.isRight()) {
+ return Either.right(validateCanWorkOnComponent.right().value());
+ }
+
+ if (resourceInstance != null && containerComponentType != null) {
+ Either<Component, ResponseFormat> getOriginComponentRes = getAndValidateOriginComponentOfComponentInstance(containerComponentType, resourceInstance);
+ if (getOriginComponentRes.isRight()) {
+ return Either.right(getOriginComponentRes.right().value());
+ } else {
+ origComponent = getOriginComponentRes.left().value();
+ }
+ }
+ if (needLock) {
+ Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "createComponentInstance");
+ if (lockComponent.isRight()) {
+ return Either.right(lockComponent.right().value());
+ }
+ }
+ log.debug("Try to create entry on graph");
+ resultOp = createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user);
return resultOp;
} finally {
@@ -181,15 +187,15 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
return Either.right(resp.right().value());
}
+ User user = resp.left().value();
Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
if (validateComponentType.isRight()) {
return Either.right(validateComponentType.right().value());
}
final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
- final ComponentOperation containerOperation = getComponentOperation(containerComponentType);
- Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, false, true);
+ Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
if (validateComponentExists.isRight()) {
return Either.right(validateComponentExists.right().value());
}
@@ -212,7 +218,6 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
try {
log.debug("Try to create entry on graph");
- NodeTypeEnum containerNodeType = containerComponentType.getNodeType();
Either<Component, ResponseFormat> eitherResourceName = getOriginComponentNameFromComponentInstance(resourceInstance, true);
if (eitherResourceName.isRight()) {
@@ -221,7 +226,7 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
Component origComponent = eitherResourceName.left().value();
- Either<ComponentInstance, ResponseFormat> result = createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, userId, containerOperation, true);
+ Either<ComponentInstance, ResponseFormat> result = createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user);
if (result.isRight()) {
log.debug("Failed to create resource instance {}", containerComponentId);
resultOp = Either.right(result.right().value());
@@ -238,8 +243,7 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
RequirementCapabilityRelDef requirementCapabilityRelDef = associationInfo;// createRequirementCapabilityrelDef(associationInfo);
-
- Either<RequirementCapabilityRelDef, StorageOperationStatus> resultReqCapDef = componentInstanceOperation.associateResourceInstances(containerComponentId, containerNodeType, requirementCapabilityRelDef, true);
+ Either<RequirementCapabilityRelDef, StorageOperationStatus> resultReqCapDef = toscaOperationFacade.associateResourceInstances(containerComponentId, requirementCapabilityRelDef);
if (resultReqCapDef.isLeft()) {
log.debug("Enty on graph is created.");
RequirementCapabilityRelDef resReqCapabilityRelDef = resultReqCapDef.left().value();
@@ -260,7 +264,7 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
private Either<Component, ResponseFormat> getOriginComponentNameFromComponentInstance(ComponentInstance componentInstance, boolean inTransaction) {
Either<Component, ResponseFormat> eitherResponse;
- Either<Component, StorageOperationStatus> eitherComponent = getCompInstOriginComponentOperation().getComponent(componentInstance.getComponentUid(), inTransaction);
+ Either<Component, StorageOperationStatus> eitherComponent = toscaOperationFacade.getToscaFullElement(componentInstance.getComponentUid());
if (eitherComponent.isRight()) {
log.debug("Failed to get origin component with id {} for component instance {} ", componentInstance.getComponentUid(), componentInstance.getName());
eitherResponse = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponse(eitherComponent.right().value(), ComponentTypeEnum.RESOURCE), "", null));
@@ -270,167 +274,10 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
return eitherResponse;
}
- private Either<String, ResponseFormat> handleNameLogic(Component origComponent, ComponentInstance componentInstance, ComponentTypeEnum containerComponentType, String containerComponentId, boolean isCreate, boolean inTransaction) {
- Either<String, ResponseFormat> eitherResult;
- final ComponentOperation containerOperation = getComponentOperation(containerComponentType);
-
- Either<Integer, StorageOperationStatus> componentInNumberStatus = containerOperation.increaseAndGetComponentInstanceCounter(containerComponentId, true);
-
- if (componentInNumberStatus.isRight()) {
- log.debug("Failed to get component instance number for container component {} ", containerComponentId);
- eitherResult = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(componentInNumberStatus.right().value(), true), "", null));
- } else {
- String resourceInNumber = componentInNumberStatus.left().value().toString();
- eitherResult = Either.left(resourceInNumber);
- }
-
- if (eitherResult.isLeft()) {
- Either<Boolean, ResponseFormat> eitherSpecificLogic;
- if (isCreate) {
- eitherSpecificLogic = handleNameLogicForNewComponentInstance(origComponent, componentInstance, eitherResult.left().value(), containerComponentType, inTransaction);
- } else {
- eitherSpecificLogic = handleNameLogicForUpdatingComponentInstance(origComponent, componentInstance, componentInNumberStatus, containerComponentType, inTransaction);
- }
- if (eitherSpecificLogic.isRight()) {
- eitherResult = Either.right(eitherSpecificLogic.right().value());
- }
- }
- return eitherResult;
- }
-
- private Either<Boolean, ResponseFormat> handleNameLogicForUpdatingComponentInstance(Component origComponent, ComponentInstance componentInstance, Either<Integer, StorageOperationStatus> componentInNumberStatus,
- ComponentTypeEnum containerComponentType, boolean inTransaction) {
- Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
- if (componentInstance.getName() == null || componentInstance.getName().isEmpty()) {
- if (origComponent == null) {
- Either<Component, ResponseFormat> eitherResourceName = getOriginComponentNameFromComponentInstance(componentInstance, inTransaction);
-
- if (eitherResourceName.isRight()) {
- eitherResult = Either.right(eitherResourceName.right().value());
- return eitherResult;
- }
- origComponent = eitherResourceName.left().value();
-
- String resourceName = origComponent.getName();
- String logicalName = componentInstanceOperation.createComponentInstLogicalName(componentInNumberStatus.left().value().toString(), resourceName);
- componentInstance.setName(logicalName);
- if (containerComponentType == ComponentTypeEnum.RESOURCE) {
- Resource resource = (Resource) origComponent;
- componentInstance.setToscaComponentName(resource.getToscaResourceName());
- }
-
- }
- }
-
- Either<Boolean, ResponseFormat> eitherValidation = validateComponentInstanceName(componentInstance.getName(), componentInstance, false);
- if (eitherValidation.isRight()) {
- eitherResult = Either.right(eitherValidation.right().value());
- }
- return eitherResult;
- }
-
- private Either<Boolean, ResponseFormat> handleNameLogicForNewComponentInstance(Component origComponent, ComponentInstance componentInstance, String resourceInNumber, ComponentTypeEnum containerComponentType, boolean inTransaction) {
- Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
-
- if (origComponent == null) {
- Either<Component, ResponseFormat> eitherResourceName = getOriginComponentNameFromComponentInstance(componentInstance, inTransaction);
-
- if (eitherResourceName.isRight()) {
- eitherResult = Either.right(eitherResourceName.right().value());
- return eitherResult;
- }
-
- origComponent = eitherResourceName.left().value();
- }
-
- String resourceName = origComponent.getName();
- componentInstance.setComponentName(resourceName);
- if (componentInstance.getName() == null || componentInstance.getName().isEmpty())
- componentInstance.setName(resourceName);
- String logicalName = componentInstanceOperation.createComponentInstLogicalName(resourceInNumber, componentInstance.getName());
-
- Either<Boolean, ResponseFormat> eitherValidation = validateComponentInstanceName(logicalName, componentInstance, true);
- if (eitherValidation.isRight()) {
- eitherResult = Either.right(eitherValidation.right().value());
- }
- if (containerComponentType == ComponentTypeEnum.RESOURCE) {
- Resource resource = (Resource) origComponent;
- componentInstance.setToscaComponentName(resource.getToscaResourceName());
- }
-
- return eitherResult;
- }
-
- public Either<ComponentInstance, ResponseFormat> createComponentInstanceOnGraph(String containerComponentParam, org.openecomp.sdc.be.model.Component containerComponent, Component origComponent, ComponentInstance componentInstance, String userId,
- boolean needLock, boolean inTransaction) {
-
- Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
- if (validateComponentType.isRight()) {
- return Either.right(validateComponentType.right().value());
- }
-
- final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
- final ComponentOperation containerOperation = getComponentOperation(containerComponentType);
- Either<ComponentInstance, ResponseFormat> resultOp = null;
- if (needLock) {
-
- Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "createComponentInstance");
-
- if (lockComponent.isRight()) {
- return Either.right(lockComponent.right().value());
- }
- }
- try {
- resultOp = createComponentInstanceOnGraph(containerComponent, origComponent, componentInstance, userId, containerOperation, inTransaction);
- return resultOp;
-
- } finally {
- if (needLock)
- unlockComponent(resultOp, containerComponent);
- }
-
- }
-
- private Map<String, String> getExistingEnvVersions(ComponentInstance componentInstance) {
- if (null == componentInstance.getDeploymentArtifacts())
- return null;
- return componentInstance.getDeploymentArtifacts().values()
- //filter env artifacts
- .stream().filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.HEAT_ENV.getType()))
- //map name to version
- .collect(Collectors.toMap(a -> a.getArtifactName(), a -> a.getArtifactVersion()));
- }
-
- private Either<ComponentInstance, ResponseFormat> createComponentInstanceOnGraph(org.openecomp.sdc.be.model.Component containerComponent, Component origComponent, ComponentInstance componentInstance, String userId,
- ComponentOperation containerOperation, boolean inTransaction) {
+ private Either<ComponentInstance, ResponseFormat> createComponentInstanceOnGraph(org.openecomp.sdc.be.model.Component containerComponent, Component originComponent, ComponentInstance componentInstance, User user) {
Either<ComponentInstance, ResponseFormat> resultOp;
- boolean nameAlreadyExist = true;
- String resourceInNumber = "";
- String containerComponentId = containerComponent.getUniqueId();
- ComponentTypeEnum containerComponentType = containerComponent.getComponentType();
- NodeTypeEnum containerNodeType = containerComponentType.getNodeType();
- NodeTypeEnum compInstNodeType = getNodeTypeOfComponentInstanceOrigin();
- while (nameAlreadyExist) {
-
- Either<String, ResponseFormat> eitherNameLogic = handleNameLogic(origComponent, componentInstance, containerComponent.getComponentType(), containerComponent.getUniqueId(), true, inTransaction);
- if (eitherNameLogic.isRight()) {
- return Either.right(eitherNameLogic.right().value());
- } else {
- resourceInNumber = eitherNameLogic.left().value();
- }
-
- Either<Boolean, StorageOperationStatus> isNameExistStatus = componentInstanceOperation.isComponentInstanceNameExist(containerComponentId, containerNodeType, null, componentInstance.getNormalizedName());
- if (isNameExistStatus.isRight()) {
- log.debug("Failed to check if component instance name exists for container component {}", containerComponentId);
- resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_RELATION_NOT_FOUND, componentInstance.getName(), containerComponentId));
- return resultOp;
- }
- nameAlreadyExist = isNameExistStatus.left().value();
-
- }
-
- Either<ComponentInstance, StorageOperationStatus> result = componentInstanceOperation.createComponentInstance(containerComponentId, containerNodeType, resourceInNumber, componentInstance, compInstNodeType, inTransaction);
+ Either<ImmutablePair<Component, String>, StorageOperationStatus> result = toscaOperationFacade.addComponentInstanceToTopologyTemplate(containerComponent, originComponent, componentInstance, false, user);
if (result.isRight()) {
log.debug("Failed to create entry on graph for component instance {}", componentInstance.getName());
@@ -439,17 +286,23 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
log.debug("Entity on graph is created.");
- ComponentInstance compInst = result.left().value();
-
- Map<String, String> existingEnvVersions = getExistingEnvVersions(componentInstance);
- Either<ActionStatus, ResponseFormat> addComponentInstanceArtifacts = addComponentInstanceArtifacts(containerComponent, compInst, userId, inTransaction, existingEnvVersions);
+ Component updatedComponent = result.left().value().getLeft();
+ Map<String, String> existingEnvVersions = new HashMap<>();
+ //TODO existingEnvVersions ??
+ Either<ActionStatus, ResponseFormat> addComponentInstanceArtifacts = addComponentInstanceArtifacts(updatedComponent, componentInstance, originComponent, user, existingEnvVersions);
if (addComponentInstanceArtifacts.isRight()) {
log.debug("Failed to create component instance {}", componentInstance.getName());
resultOp = Either.right(addComponentInstanceArtifacts.right().value());
return resultOp;
}
- resultOp = Either.left(compInst);
+ Optional<ComponentInstance> updatedInstanceOptional = updatedComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(result.left().value().getRight())).findFirst();
+ if (!updatedInstanceOptional.isPresent()) {
+ log.debug("Failed to fetch new added component instance {} from component {}", componentInstance.getName(), containerComponent.getName());
+ resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName()));
+ return resultOp;
+ }
+ resultOp = Either.left(updatedInstanceOptional.get());
return resultOp;
}
@@ -459,14 +312,15 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
* @param componentInstance
* @param userId
* @param existingEnvVersions
+ * TODO
* @param containerComponentId
*
* @return
*/
- protected Either<ActionStatus, ResponseFormat> addComponentInstanceArtifacts(org.openecomp.sdc.be.model.Component containerComponent, ComponentInstance componentInstance, String userId, boolean inTransaction,
+ protected Either<ActionStatus, ResponseFormat> addComponentInstanceArtifacts(org.openecomp.sdc.be.model.Component containerComponent, ComponentInstance componentInstance, org.openecomp.sdc.be.model.Component originComponent, User user,
Map<String, String> existingEnvVersions) {
log.debug("add artifacts to resource instance");
-
+ List<GroupDefinition> filteredGroups = null;
ActionStatus status = setResourceArtifactsOnResourceInstance(componentInstance);
if (!ActionStatus.OK.equals(status)) {
ResponseFormat resultOp = componentsUtils.getResponseFormatForResourceInstance(status, "", null);
@@ -478,10 +332,11 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
if (componentDeploymentArtifacts == null) {
return Either.left(ActionStatus.OK);
}
- Map<String, ArtifactDefinition> finalDeploymentArtifacts = new HashMap<String, ArtifactDefinition>(componentDeploymentArtifacts);
+ Map<String, ArtifactDefinition> finalDeploymentArtifacts = new HashMap<String, ArtifactDefinition>();
+
+ Map<String, List<ArtifactDefinition>> groupInstancesArtifacts = new HashMap<>();
+
for (ArtifactDefinition artifact : componentDeploymentArtifacts.values()) {
- // if (artifact.getArtifactType().equalsIgnoreCase(
- // ArtifactTypeEnum.HEAT.getType())) {
String type = artifact.getArtifactType();
if (!(type.equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType()))) {
@@ -489,92 +344,65 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
if (artifact.checkEsIdExist()) {
- Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getDeploymentResourceInstanceArtifacts();
- if (deploymentResourceArtifacts == null) {
- log.debug("no deployment artifacts are configured for resource instance");
- break;
- }
- Map<String, Object> placeHolderData = (Map<String, Object>) deploymentResourceArtifacts.get(HEAT_ENV_NAME);
-
- String envLabel = (artifact.getArtifactLabel() + HEAT_ENV_SUFFIX).toLowerCase();
- Either<ArtifactDefinition, ResponseFormat> createArtifactPlaceHolder = artifactBusinessLogic.createArtifactPlaceHolderInfo(componentInstance.getUniqueId(), envLabel, placeHolderData, userId, ArtifactGroupTypeEnum.DEPLOYMENT,
- inTransaction);
- if (createArtifactPlaceHolder.isRight()) {
- return Either.right(createArtifactPlaceHolder.right().value());
+ Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder = artifactBusinessLogic.createHeatEnvPlaceHolder(artifact, ArtifactsBusinessLogic.HEAT_ENV_NAME, componentInstance.getUniqueId(), NodeTypeEnum.ResourceInstance,
+ componentInstance.getName(), user, containerComponent, existingEnvVersions);
+ if (createHeatEnvPlaceHolder.isRight()) {
+ return Either.right(createHeatEnvPlaceHolder.right().value());
}
- ArtifactDefinition artifactHeatEnv = createArtifactPlaceHolder.left().value();
-
- artifactHeatEnv.setHeatParamsUpdateDate(System.currentTimeMillis());
- artifactHeatEnv.setTimeout(0);
- buildHeatEnvFileName(artifact, artifactHeatEnv, placeHolderData);
-
- // rbetzer - keep env artifactVersion - changeComponentInstanceVersion flow
- handleEnvArtifactVersion(artifactHeatEnv, existingEnvVersions);
- Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact = artifactBusinessLogic.addHeatEnvArtifact(artifactHeatEnv, artifact, componentInstance.getUniqueId(), NodeTypeEnum.ResourceInstance, true);
- if (addHeatEnvArtifact.isRight()) {
- log.debug("failed to create heat env artifact on resource instance");
- return Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(addHeatEnvArtifact.right().value(), false), "", null));
+ ArtifactDefinition artifactDefinition = createHeatEnvPlaceHolder.left().value();
+
+ //put heat
+ finalDeploymentArtifacts.put(artifact.getArtifactLabel(), artifact);
+
+ //put env
+ finalDeploymentArtifacts.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
+
+ if(CollectionUtils.isNotEmpty(originComponent.getGroups())){
+ filteredGroups = originComponent.getGroups().stream().filter(g -> g.getType().equals(VF_MODULE)).collect(Collectors.toList());
}
-
- ArtifactDefinition artifactDefinition = addHeatEnvArtifact.left().value();
- if (artifact.getHeatParameters() != null) {
- List<HeatParameterDefinition> heatEnvParameters = new ArrayList<HeatParameterDefinition>();
- for (HeatParameterDefinition parameter : artifact.getHeatParameters()) {
- HeatParameterDefinition heatEnvParameter = new HeatParameterDefinition(parameter);
- heatEnvParameter.setDefaultValue(parameter.getCurrentValue());
- heatEnvParameters.add(heatEnvParameter);
+ if (CollectionUtils.isNotEmpty(filteredGroups)) {
+ for (GroupDefinition groupInstance : filteredGroups) {
+ Optional<String> op = groupInstance.getArtifacts().stream().filter(p -> p.equals(artifactDefinition.getGeneratedFromId())).findAny();
+ if (op.isPresent()) {
+ List<ArtifactDefinition> artifactsUid;
+ if (groupInstancesArtifacts.containsKey(groupInstance.getUniqueId())) {
+ artifactsUid = groupInstancesArtifacts.get(groupInstance.getUniqueId());
+ } else {
+ artifactsUid = new ArrayList<>();
+ }
+ artifactsUid.add(artifactDefinition);
+ groupInstancesArtifacts.put(groupInstance.getUniqueId(), artifactsUid);
+ break;
+ }
}
- artifactDefinition.setHeatParameters(heatEnvParameters);
- }
- finalDeploymentArtifacts.put(envLabel, artifactDefinition);
- // audit
- EnumMap<AuditingFieldsKeysEnum, Object> artifactAuditingFields = artifactBusinessLogic.createArtifactAuditingFields(artifactDefinition, "", artifactDefinition.getUniqueId());
- artifactAuditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentInstance.getName());
- handleAuditing(AuditingActionEnum.ARTIFACT_UPLOAD, containerComponent, userId, artifactAuditingFields, inTransaction);
+ }
}
- // }
}
- componentInstance.setDeploymentArtifacts(finalDeploymentArtifacts);
- return Either.left(ActionStatus.OK);
- }
-
- private void handleAuditing(AuditingActionEnum artifactUpload, org.openecomp.sdc.be.model.Component containerComponent, String userId, EnumMap<AuditingFieldsKeysEnum, Object> artifactAuditingFields, boolean inTransaction) {
-
- Either<User, ActionStatus> user = userAdmin.getUser(userId, inTransaction);
- if (user.isRight()) {
- log.debug("failed to get user properties from graph for audit");
- return;
+ StorageOperationStatus artStatus = toscaOperationFacade.addDeploymentArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, finalDeploymentArtifacts);
+ if ( artStatus != StorageOperationStatus.OK){
+ log.debug("Failed to add instance deployment artifacts for instance {} in conatiner {} error {}", componentInstance.getUniqueId(), containerComponent.getUniqueId(), artStatus);
+ return Either.left(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false));
+
}
-
- componentsUtils.auditComponent(componentsUtils.getResponseFormat(ActionStatus.OK), user.left().value(), containerComponent, "", "", AuditingActionEnum.ARTIFACT_UPLOAD, ComponentTypeEnum.RESOURCE_INSTANCE, artifactAuditingFields);
-
- }
-
- private void handleEnvArtifactVersion(ArtifactDefinition heatEnvArtifact, Map<String, String> existingEnvVersions) {
- if (null != existingEnvVersions) {
- String prevVersion = existingEnvVersions.get(heatEnvArtifact.getArtifactName());
- if (null != prevVersion) {
- heatEnvArtifact.setArtifactVersion(prevVersion);
- }
+ StorageOperationStatus result = toscaOperationFacade
+ .addGroupInstancesToComponentInstance(containerComponent, componentInstance, filteredGroups, groupInstancesArtifacts);
+ if (result != StorageOperationStatus.OK) {
+ log.debug("failed to update group instance for component instance {}", componentInstance.getUniqueId());
+ return Either.left(componentsUtils.convertFromStorageResponse(result));
}
- }
-
- private void buildHeatEnvFileName(ArtifactDefinition heatArtifact, ArtifactDefinition heatEnvArtifact, Map<String, Object> placeHolderData) {
- String heatExtension = GeneralUtility.getFilenameExtension(heatArtifact.getArtifactName());
- String envExtension = (String) placeHolderData.get(ARTIFACT_PLACEHOLDER_FILE_EXTENSION);
- String fileName = heatArtifact.getArtifactName().replaceAll("." + heatExtension, "." + envExtension);
- heatEnvArtifact.setArtifactName(fileName);
+ componentInstance.setDeploymentArtifacts(finalDeploymentArtifacts);
+ return Either.left(ActionStatus.OK);
}
private ActionStatus setResourceArtifactsOnResourceInstance(ComponentInstance resourceInstance) {
- Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getResourceDeploymentArtifacts = artifactBusinessLogic.getArtifacts(resourceInstance.getComponentUid(), NodeTypeEnum.Resource, true, ArtifactGroupTypeEnum.DEPLOYMENT);
+ Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getResourceDeploymentArtifacts = artifactBusinessLogic.getArtifacts(resourceInstance.getComponentUid(), NodeTypeEnum.Resource, true, ArtifactGroupTypeEnum.DEPLOYMENT, null);
Map<String, ArtifactDefinition> deploymentArtifacts = new HashMap<String, ArtifactDefinition>();
if (getResourceDeploymentArtifacts.isRight()) {
StorageOperationStatus status = getResourceDeploymentArtifacts.right().value();
if (!status.equals(StorageOperationStatus.NOT_FOUND)) {
- log.debug("Failed to fetch resource artifacts. status is {}", status);
+ log.debug("Failed to fetch resource: {} artifacts. status is {}", resourceInstance.getComponentUid(), status);
return componentsUtils.convertFromStorageResponseForResourceInstance(status, true);
}
} else {
@@ -595,11 +423,11 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
return ActionStatus.OK;
}
- public Either<ComponentInstance, ResponseFormat> updateComponentInstance(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance componentInstance) {
- return updateComponentInstance(containerComponentParam, containerComponentId, componentInstanceId, userId, componentInstance, false, true, true);
+ public Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance componentInstance) {
+ return updateComponentInstanceMetadata(containerComponentParam, containerComponentId, componentInstanceId, userId, componentInstance, false, true, true);
}
- public Either<ComponentInstance, ResponseFormat> updateComponentInstance(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance componentInstance, boolean inTransaction,
+ public Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance componentInstance, boolean inTransaction,
boolean needLock, boolean createNewTransaction) {
Either<User, ResponseFormat> resp = validateUserExists(userId, "update Component Instance", inTransaction);
@@ -616,7 +444,7 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
- Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, inTransaction, createNewTransaction);
+ Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
if (validateComponentExists.isRight()) {
return Either.right(validateComponentExists.right().value());
}
@@ -627,28 +455,24 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
return Either.right(validateCanWorkOnComponent.right().value());
}
ComponentTypeEnum instanceType = getComponentType(containerComponentType);
- Either<Boolean, StorageOperationStatus> validateParentStatus = componentInstanceOperation.validateParent(containerComponentId, componentInstanceId, inTransaction);
+ Either<Boolean, StorageOperationStatus> validateParentStatus = toscaOperationFacade.validateComponentExists(componentInstance.getComponentUid());
if (validateParentStatus.isRight()) {
log.debug("Failed to get component instance {} on service {}", componentInstanceId, containerComponentId);
resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND, componentInstance.getName(), instanceType.getValue().toLowerCase()));
return resultOp;
}
- Boolean isPrentValid = validateParentStatus.left().value();
- if (!isPrentValid) {
+ if (!validateParentStatus.left().value()) {
resultOp = Either.right(
componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(), instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(), containerComponentId));
return resultOp;
-
}
if (needLock) {
-
Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "updateComponentInstance");
if (lockComponent.isRight()) {
return Either.right(lockComponent.right().value());
}
}
-
try {
Either<Component, ResponseFormat> eitherResourceName = getOriginComponentNameFromComponentInstance(componentInstance, inTransaction);
@@ -659,7 +483,7 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
Component origComponent = eitherResourceName.left().value();
- resultOp = updateComponentInstance(containerComponentId, containerComponentType, origComponent, componentInstanceId, componentInstance, inTransaction);
+ resultOp = updateComponentInstanceMetadata(containerComponent, containerComponentType, origComponent, componentInstanceId, componentInstance, inTransaction);
return resultOp;
} finally {
@@ -690,6 +514,7 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
ComponentParametersView componentFilter = new ComponentParametersView();
componentFilter.disableAll();
componentFilter.setIgnoreUsers(false);
+ componentFilter.setIgnoreComponentInstances(false);
Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExistsByFilter(containerComponentId, containerComponentType, componentFilter, true);
if (validateComponentExists.isRight()) {
return Either.right(validateComponentExists.right().value());
@@ -705,14 +530,8 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
ComponentTypeEnum instanceType = getComponentType(containerComponentType);
for (ComponentInstance componentInstance : componentInstanceList) {
- Either<Boolean, StorageOperationStatus> validateParentStatus = componentInstanceOperation.validateParent(containerComponentId, componentInstance.getUniqueId(), true);
- if (validateParentStatus.isRight()) {
- log.debug("Failed to get component instance {} on service {}", componentInstance.getUniqueId(), containerComponentId);
- resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND, componentInstance.getName(), instanceType.getValue().toLowerCase()));
- return resultOp;
- }
- Boolean isPrentValid = validateParentStatus.left().value();
- if (!isPrentValid) {
+ boolean validateParent = validateParent(containerComponent, componentInstance.getUniqueId());
+ if (!validateParent) {
resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(), instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(),
containerComponentId));
return resultOp;
@@ -728,23 +547,46 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
List<ComponentInstance> updatedList = new ArrayList<>();
- for (ComponentInstance componentInstance : componentInstanceList) {
-
- Either<Component, ResponseFormat> eitherResourceName = getOriginComponentNameFromComponentInstance(componentInstance, true);
-
- if (eitherResourceName.isRight()) {
- resultOp = Either.right(eitherResourceName.right().value());
- return resultOp;
+ List<ComponentInstance> instancesFromContainerComponent = containerComponent.getComponentInstances();
+ List<ComponentInstance> listForUpdate = new ArrayList<>();
+ if(instancesFromContainerComponent == null || instancesFromContainerComponent.isEmpty())
+ containerComponent.setComponentInstances(componentInstanceList);
+ else{
+ Iterator<ComponentInstance> iterator = instancesFromContainerComponent.iterator();
+ while(iterator.hasNext()){
+ ComponentInstance origInst = iterator.next();
+ Optional<ComponentInstance> op = componentInstanceList.stream().filter(ci -> ci.getUniqueId().equals(origInst.getUniqueId())).findAny();
+ if(op.isPresent()){
+ ComponentInstance updatedCi = op.get();
+ Boolean isUniqueName = validateInstanceNameUniquenessUponUpdate(containerComponent, origInst, updatedCi.getName());
+ if(!isUniqueName){
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the name of the component instance {} to {}. A component instance with the same name already exists. ",
+ origInst.getName(), updatedCi.getName());
+ resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), origInst.getName()));
+ return resultOp;
+ }
+
+ listForUpdate.add(updatedCi);
+ }
+ else
+ listForUpdate.add(origInst);
}
- Component origComponent = eitherResourceName.left().value();
-
- Either<ComponentInstance, ResponseFormat> resultSingleUpdate = updateComponentInstance(containerComponentId, containerComponentType, origComponent, componentInstance.getUniqueId(), componentInstance, true);
-
- if (resultSingleUpdate.isRight()) {
- resultOp = Either.right(resultSingleUpdate.right().value());
- return resultOp;
+ containerComponent.setComponentInstances(listForUpdate);
+
+ if(resultOp == null){
+ Either<Component, StorageOperationStatus> updateStatus = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
+ if(updateStatus.isRight()){
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update metadata belonging to container component {}. Status is {}. ", containerComponent.getName(), updateStatus.right().value());
+ resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(updateStatus.right().value(), true), "", null));
+ return resultOp;
+ }
+ for(ComponentInstance updatedInstance : updateStatus.left().value().getComponentInstances()){
+ Optional<ComponentInstance> op = componentInstanceList.stream().filter(ci -> ci.getName().equals(updatedInstance.getName())).findAny();
+ if(op.isPresent()){
+ updatedList.add(updatedInstance);
+ }
+ }
}
- updatedList.add(resultSingleUpdate.left().value());
}
resultOp = Either.left(updatedList);
@@ -757,6 +599,10 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
}
+ private boolean validateParent(org.openecomp.sdc.be.model.Component containerComponent, String nodeTemplateId) {
+ return containerComponent.getComponentInstances().stream().anyMatch(p -> p.getUniqueId().equals(nodeTemplateId));
+ }
+
private ComponentTypeEnum getComponentType(ComponentTypeEnum containerComponentType) {
if (ComponentTypeEnum.PRODUCT.equals(containerComponentType)) {
return ComponentTypeEnum.SERVICE_INSTANCE;
@@ -765,78 +611,56 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
}
- public Either<ComponentInstance, ResponseFormat> updateComponentInstance(String containerComponentParam, org.openecomp.sdc.be.model.Component containerComponent, org.openecomp.sdc.be.model.Component origComponent, String componentInstanceId,
- ComponentInstance componentInstance, boolean needLock, boolean inTransaction) {
- Either<ComponentInstance, ResponseFormat> resultOp = null;
- Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
- if (validateComponentType.isRight()) {
- return Either.right(validateComponentType.right().value());
- }
-
- final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
- if (needLock) {
+ private Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(Component containerComponent, ComponentTypeEnum containerComponentType, org.openecomp.sdc.be.model.Component origComponent, String componentInstanceId,
+ ComponentInstance componentInstance, boolean inTransaction) {
- Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "updateComponentInstance");
- if (lockComponent.isRight()) {
- return Either.right(lockComponent.right().value());
+ Either<ComponentInstance, ResponseFormat> resultOp = null;
+ Optional<ComponentInstance> componentInstanceOptional = null;
+ Either<ImmutablePair<Component, String>, StorageOperationStatus> updateRes = null;
+
+ if (resultOp == null) {
+ componentInstanceOptional = containerComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(componentInstance.getUniqueId())).findFirst();
+ if (!componentInstanceOptional.isPresent()) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find the component instance {} in container component {}. ", componentInstance.getName(), containerComponent.getName());
+ resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName()));
}
}
-
- try {
-
- resultOp = updateComponentInstance(containerComponent.getUniqueId(), containerComponentType, origComponent, componentInstanceId, componentInstance, inTransaction);
- return resultOp;
-
- } finally {
- if (needLock)
- unlockComponent(resultOp, containerComponent);
- }
-
- }
-
- private Either<ComponentInstance, ResponseFormat> updateComponentInstance(String containerComponentId, ComponentTypeEnum containerComponentType, org.openecomp.sdc.be.model.Component origComponent, String componentInstanceId,
- ComponentInstance componentInstance, boolean inTransaction) {
- Either<ComponentInstance, ResponseFormat> resultOp;
-
- Either<String, ResponseFormat> eitherNameLogic = handleNameLogic(origComponent, componentInstance, containerComponentType, containerComponentId, false, inTransaction);
- if (eitherNameLogic.isRight()) {
- return Either.right(eitherNameLogic.right().value());
+ if (resultOp == null) {
+ ComponentInstance oldComponentInstance = componentInstanceOptional.get();
+ String newInstanceName = componentInstance.getName();
+ Boolean isUniqueName = validateInstanceNameUniquenessUponUpdate(containerComponent, oldComponentInstance, newInstanceName);
+ if (!isUniqueName) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the name of the component instance {} to {}. A component instance with the same name already exists. ", oldComponentInstance.getName(), newInstanceName);
+ resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), componentInstance.getName()));
+ }
}
- NodeTypeEnum containerNodeType = containerComponentType.getNodeType();
-
- Either<Boolean, StorageOperationStatus> isNameExistStatus = componentInstanceOperation.isComponentInstanceNameExist(containerComponentId, containerNodeType, componentInstanceId, componentInstance.getNormalizedName());
- if (isNameExistStatus.isRight()) {
- log.debug("Failed to get resource instance names for service {}", containerComponentId);
-
- resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_RELATION_NOT_FOUND, componentInstance.getName(), containerComponentId));
- return resultOp;
+ if (resultOp == null) {
+ updateRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, origComponent, componentInstance);
+ if (updateRes.isRight()) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update metadata of component instance {} belonging to container component {}. Status is {}. ", componentInstance.getName(), containerComponent.getName(),
+ updateRes.right().value());
+ resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(updateRes.right().value(), true), "", null));
+ }
}
- Boolean isNameExist = isNameExistStatus.left().value();
- if (isNameExist) {
- containerComponentType = getComponentTypeOfComponentInstance();
- resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), componentInstance.getName()));
- return resultOp;
+ if (resultOp == null) {
+ String newInstanceId = updateRes.left().value().getRight();
+ Optional<ComponentInstance> updatedInstanceOptional = updateRes.left().value().getLeft().getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(newInstanceId)).findFirst();
+ if (!updatedInstanceOptional.isPresent()) {
+ log.debug("Failed to update metadata of component instance {} of container component {}", componentInstance.getName(), containerComponent.getName());
+ resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName()));
+ }else{
+ resultOp = Either.left(updatedInstanceOptional.get());
+ }
+
}
-
- log.debug("Try to update entry on graph");
- Either<ComponentInstance, StorageOperationStatus> result = componentInstanceOperation.updateResourceInstance(containerComponentId, containerNodeType, componentInstanceId, componentInstance, inTransaction);
-
- if (result.isLeft()) {
- log.debug("Enty on graph is updated.");
- ComponentInstance resResourceInfo = result.left().value();
- resultOp = Either.left(resResourceInfo);
- return resultOp;
-
- } else {
- log.debug("Failed to update entry on graph for resource instance {}", componentInstance.getName());
- resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), false), "", componentInstance.getName()));
- return resultOp;
+ if (resultOp == null) {
+ resultOp = Either.left(componentInstanceOptional.get());
}
-
+ return resultOp;
}
- public Either<ComponentInstance, ResponseFormat> deleteComponentInstance(String containerComponentParam, String containerComponentId, String resourceInstanceId, String userId) {
+ public Either<ComponentInstance, ResponseFormat> deleteComponentInstance(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId) {
Either<User, ResponseFormat> resp = validateUserExists(userId, "delete Component Instance", false);
if (resp.isRight()) {
@@ -849,7 +673,7 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
- Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, false, true);
+ Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
if (validateComponentExists.isRight()) {
return Either.right(validateComponentExists.right().value());
}
@@ -865,13 +689,13 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
// validate resource
/*
- * if (!ComponentValidationUtils.canWorkOnComponent(containerComponentId, serviceOperation, userId)) { log.info( "Restricted operation for user {} on service {}", userId, containerComponentId); return Either.right(componentsUtils
+ * if (!ComponentValidationUtils.canWorkOnComponent(containerComponentId, serviceOperation, userId)) { log.info( "Restricted operation for user " + userId + " on service " + containerComponentId); return Either.right(componentsUtils
* .getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); } // lock resource StorageOperationStatus lockStatus = graphLockOperation.lockComponent( containerComponentId, NodeTypeEnum.Service); if (lockStatus != StorageOperationStatus.OK) {
- * log.debug("Failed to lock service {}", containerComponentId); resultOp = Either.right(componentsUtils .getResponseFormat(componentsUtils .convertFromStorageResponse(lockStatus))); return resultOp; }
+ * log.debug("Failed to lock service {}", containerComponentId); resultOp = Either.right(componentsUtils .getResponseFormat(componentsUtils .convertFromStorageResponse(lockStatus))); return resultOp; }
*/
Either<ComponentInstance, ResponseFormat> resultOp = null;
try {
- resultOp = deleteComponentInstance(containerComponentId, resourceInstanceId, containerComponentType);
+ resultOp = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType);
return resultOp;
} finally {
@@ -882,37 +706,51 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
}
- private Either<ComponentInstance, ResponseFormat> deleteComponentInstance(String containerComponentId, String resourceInstanceId, ComponentTypeEnum containerComponentType) {
- Either<ComponentInstance, ResponseFormat> resultOp;
- NodeTypeEnum containerNodeType = containerComponentType.getNodeType();
- Either<ComponentInstance, StorageOperationStatus> result = componentInstanceOperation.deleteComponentInstance(containerNodeType, containerComponentId, resourceInstanceId, true);
+ private Either<ComponentInstance, ResponseFormat> deleteComponentInstance(Component containerComponent, String componentInstanceId, ComponentTypeEnum containerComponentType) {
- if (result.isRight()) {
- log.debug("Failed to delete entry on graph for resourceInstance {}", resourceInstanceId);
- ActionStatus status = componentsUtils.convertFromStorageResponse(result.right().value(), containerComponentType);
- // TODO check
- /*
- * if (ActionStatus.SERVICE_NOT_FOUND.equals(status)) { resultOp = Either .right(componentsUtils .getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND)); } else {
- */
- resultOp = Either.right(componentsUtils.getResponseFormat(status, resourceInstanceId));
- // }
- return resultOp;
+ Either<ComponentInstance, ResponseFormat> resultOp = null;
+ ComponentInstance deletedInstance = null;
+ Either<ImmutablePair<Component, String>, StorageOperationStatus> deleteRes = toscaOperationFacade.deleteComponentInstanceFromTopologyTemplate(containerComponent, componentInstanceId);
+
+ if (deleteRes.isRight()) {
+ log.debug("Failed to delete entry on graph for resourceInstance {}", componentInstanceId);
+ ActionStatus status = componentsUtils.convertFromStorageResponse(deleteRes.right().value(), containerComponentType);
+ resultOp = Either.right(componentsUtils.getResponseFormat(status, componentInstanceId));
+ }
+ if (resultOp == null) {
+ log.debug("The component instance {} has been removed from container component {}. ", componentInstanceId, containerComponent);
+ deletedInstance = findAndRemoveComponentInstanceFromContainerComponent(componentInstanceId, containerComponent);
+ resultOp = Either.left(deletedInstance);
+ }
+ if (resultOp.isLeft() && CollectionUtils.isNotEmpty(containerComponent.getGroups())) {
+ List<GroupDataDefinition> groupsToUpdate = new ArrayList<>();
+ for(GroupDataDefinition currGroup : containerComponent.getGroups()){
+ if(currGroup.getMembers().containsKey(deletedInstance.getName())){
+ currGroup.getMembers().remove(deletedInstance.getName());
+ groupsToUpdate.add(currGroup);
+ }
+ }
+ Either<List<GroupDefinition>, StorageOperationStatus> updateGroupsRes =
+ toscaOperationFacade.updateGroupsOnComponent(containerComponent, containerComponent.getComponentType(), groupsToUpdate);
+ if (updateGroupsRes.isRight()) {
+ log.debug("Failed to delete component instance {} from group members. ", componentInstanceId);
+ ActionStatus status = componentsUtils.convertFromStorageResponse(updateGroupsRes.right().value(), containerComponentType);
+ resultOp = Either.right(componentsUtils.getResponseFormat(status, componentInstanceId));
+ }
}
- ComponentInstance resResourceInfo = result.left().value();
- resultOp = Either.left(resResourceInfo);
-
- log.debug("Entry on graph is deleted. Exist more connections on this artifact.");
+ return resultOp;
+ }
- Map<String, ArtifactDefinition> deploymentArtifacts = resResourceInfo.getDeploymentArtifacts();
- if (deploymentArtifacts != null && !deploymentArtifacts.isEmpty()) {
- StorageOperationStatus deleteArtifactsIfNotOnGraph = artifactBusinessLogic.deleteAllComponentArtifactsIfNotOnGraph(new ArrayList<ArtifactDefinition>(deploymentArtifacts.values()));
- if (!deleteArtifactsIfNotOnGraph.equals(StorageOperationStatus.OK)) {
- log.debug("failed to delete artifact payload. status={}", deleteArtifactsIfNotOnGraph.name());
- resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(result.right().value()), resourceInstanceId));
+ private ComponentInstance findAndRemoveComponentInstanceFromContainerComponent(String componentInstanceId, Component containerComponent) {
+ ComponentInstance foundInstance = null;
+ for(ComponentInstance instance : containerComponent.getComponentInstances()){
+ if(instance.getUniqueId().equals(componentInstanceId)){
+ foundInstance = instance;
+ containerComponent.getComponentInstances().remove(instance);
+ break;
}
-
}
- return resultOp;
+ return foundInstance;
}
public Either<RequirementCapabilityRelDef, ResponseFormat> associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum) {
@@ -929,7 +767,7 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
- Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(componentId, componentTypeEnum, inTransaction, createNewTransaction);
+ Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(componentId, componentTypeEnum, null);
if (validateComponentExists.isRight()) {
return Either.right(validateComponentExists.right().value());
}
@@ -949,7 +787,7 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
try {
- resultOp = associateRIToRIOnGraph(componentId, requirementDef, componentTypeEnum, inTransaction);
+ resultOp = associateRIToRIOnGraph(validateComponentExists.left().value(), requirementDef, componentTypeEnum, inTransaction);
return resultOp;
@@ -959,12 +797,12 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
}
- public Either<RequirementCapabilityRelDef, ResponseFormat> associateRIToRIOnGraph(String componentId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum, boolean inTransaction) {
+ public Either<RequirementCapabilityRelDef, ResponseFormat> associateRIToRIOnGraph(Component containerComponent, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum, boolean inTransaction) {
log.debug("Try to create entry on graph");
Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
- Either<RequirementCapabilityRelDef, StorageOperationStatus> result = componentInstanceOperation.associateResourceInstances(componentId, componentTypeEnum.getNodeType(), requirementDef, inTransaction);
+ Either<RequirementCapabilityRelDef, StorageOperationStatus> result = toscaOperationFacade.associateResourceInstances(containerComponent.getUniqueId(), requirementDef);
if (result.isLeft()) {
log.debug("Enty on graph is created.");
@@ -973,11 +811,11 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
return resultOp;
} else {
- log.debug("Failed to associate node {} with node {}", requirementDef.getFromNode(), requirementDef.getToNode());
+ log.debug("Failed to associate node: {} with node {}", requirementDef.getFromNode(), requirementDef.getToNode());
String fromNameOrId = "";
String toNameOrId = "";
- Either<ComponentInstance, StorageOperationStatus> fromResult = componentInstanceOperation.getResourceInstanceById(requirementDef.getFromNode());
- Either<ComponentInstance, StorageOperationStatus> toResult = componentInstanceOperation.getResourceInstanceById(requirementDef.getToNode());
+ Either<ComponentInstance, StorageOperationStatus> fromResult = getResourceInstanceById(containerComponent, requirementDef.getFromNode());
+ Either<ComponentInstance, StorageOperationStatus> toResult = getResourceInstanceById(containerComponent, requirementDef.getToNode());
toNameOrId = requirementDef.getFromNode();
fromNameOrId = requirementDef.getFromNode();
@@ -1002,7 +840,7 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
- Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(componentId, componentTypeEnum, false, true);
+ Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(componentId, componentTypeEnum, null);
if (validateComponentExists.isRight()) {
return Either.right(validateComponentExists.right().value());
}
@@ -1019,7 +857,7 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
try {
log.debug("Try to create entry on graph");
- Either<RequirementCapabilityRelDef, StorageOperationStatus> result = componentInstanceOperation.dissociateResourceInstances(componentId, componentTypeEnum.getNodeType(), requirementDef, true);
+ Either<RequirementCapabilityRelDef, StorageOperationStatus> result = toscaOperationFacade.dissociateResourceInstances(componentId, requirementDef);
if (result.isLeft()) {
log.debug("Enty on graph is created.");
RequirementCapabilityRelDef requirementCapabilityRelDef = result.left().value();
@@ -1028,11 +866,11 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
} else {
- log.debug("Failed to dissocaite node {} from node {}", requirementDef.getFromNode(), requirementDef.getToNode());
+ log.debug("Failed to dissocaite node {} from node {}", requirementDef.getFromNode(), requirementDef.getToNode());
String fromNameOrId = "";
String toNameOrId = "";
- Either<ComponentInstance, StorageOperationStatus> fromResult = componentInstanceOperation.getResourceInstanceById(requirementDef.getFromNode());
- Either<ComponentInstance, StorageOperationStatus> toResult = componentInstanceOperation.getResourceInstanceById(requirementDef.getToNode());
+ Either<ComponentInstance, StorageOperationStatus> fromResult = getResourceInstanceById(containerComponent, requirementDef.getFromNode());
+ Either<ComponentInstance, StorageOperationStatus> toResult = getResourceInstanceById(containerComponent, requirementDef.getToNode());
toNameOrId = requirementDef.getFromNode();
fromNameOrId = requirementDef.getFromNode();
@@ -1072,26 +910,6 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
return result;
}
- private Either<ComponentInstanceInput, ResponseFormat> updateInputValue(ComponentInstanceInput input, String resourceInstanceId) {
- Either<ComponentInstanceInput, StorageOperationStatus> eitherInput = componentInstanceOperation.updateInputValueInResourceInstance(input, resourceInstanceId, true);
- Either<ComponentInstanceInput, ResponseFormat> result;
- if (eitherInput.isLeft()) {
- log.debug("Input value {} was updated on graph.", input.getValueUniqueUid());
- ComponentInstanceInput instanceInput = eitherInput.left().value();
-
- result = Either.left(instanceInput);
-
- } else {
- log.debug("Failed to update input value {} in resource instance {}", input, resourceInstanceId);
-
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(eitherInput.right().value());
-
- result = Either.right(componentsUtils.getResponseFormat(actionStatus, ""));
-
- }
- return result;
- }
-
private Either<ComponentInstanceAttribute, ResponseFormat> createAttributeValue(ComponentInstanceAttribute attribute, String resourceInstanceId) {
Either<ComponentInstanceAttribute, ResponseFormat> result;
@@ -1161,15 +979,39 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
finally {
if (result == null || result.isRight()) {
- titanGenericDao.rollback();
+ titanDao.rollback();
} else {
- titanGenericDao.commit();
+ titanDao.commit();
}
// unlock resource
graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
}
}
+ // US833308 VLI in service - specific network_role property value logic
+ private StorageOperationStatus concatServiceNameToVLINetworkRolePropertyValue(ToscaOperationFacade toscaOperationFacade, ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceProperty property) {
+ if (StringUtils.isNotEmpty(property.getValue()) && PropertyNames.NETWORK_ROLE.getPropertyName().equalsIgnoreCase(property.getName()) && ComponentTypeEnum.SERVICE == componentTypeEnum) {
+ ComponentParametersView componentParametersView = new ComponentParametersView();
+ componentParametersView.disableAll();
+ componentParametersView.setIgnoreComponentInstances(false);
+ Either<Component, StorageOperationStatus> getServiceResult = toscaOperationFacade.getToscaElement(componentId, componentParametersView);
+ if (getServiceResult.isRight()) {
+ return getServiceResult.right().value();
+ }
+ Component service = getServiceResult.left().value();
+ Optional<ComponentInstance> getInstance = service.getComponentInstances().stream().filter(p -> p.getUniqueId().equals(resourceInstanceId)).findAny();
+ if (!getInstance.isPresent()) {
+ return StorageOperationStatus.NOT_FOUND;
+ }
+ String prefix = service.getSystemName() + ".";
+ String value = property.getValue();
+ if (OriginTypeEnum.VL == getInstance.get().getOriginType() && (!value.startsWith(prefix) || value.equalsIgnoreCase(prefix))) {
+ property.setValue(prefix + value);
+ }
+ }
+ return StorageOperationStatus.OK;
+ }
+
public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdatePropertyValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceProperty property, String userId) {
Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
@@ -1184,11 +1026,264 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
return resultOp;
}
+ Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
+
+ if (getResourceResult.isRight()) {
+ log.debug("Failed to retrieve component, component id {}", componentId);
+ resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
+ return resultOp;
+ }
+ Component containerComponent = getResourceResult.left().value();
+
+ if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
+ log.info("Restricted operation for user: {} on service {}", userId, componentId);
+ resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
+ return resultOp;
+ }
+ Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
+ if (resourceInstanceStatus.isRight()) {
+ resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, resourceInstanceId, componentId));
+ return resultOp;
+ }
+ ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
+ // specific property value logic US833308
+ StorageOperationStatus fetchByIdsStatus = concatServiceNameToVLINetworkRolePropertyValue(toscaOperationFacade, componentTypeEnum, componentId, resourceInstanceId, property);
+ if (StorageOperationStatus.OK != fetchByIdsStatus) {
+ resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(fetchByIdsStatus)));
+ return resultOp;
+ }
+ // lock resource
+ StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
+ if (lockStatus != StorageOperationStatus.OK) {
+ log.debug("Failed to lock service {}", componentId);
+ resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
+ return resultOp;
+ }
+ String innerType = null;
+ String propertyType = property.getType();
+ ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
+ log.debug("The type of the property {} is {}", property.getUniqueId(), propertyType);
+
+ if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
+ SchemaDefinition def = property.getSchema();
+ if (def == null) {
+ log.debug("Schema doesn't exists for property of type {}", type);
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
+ }
+ PropertyDataDefinition propDef = def.getProperty();
+ if (propDef == null) {
+ log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
+ }
+ innerType = propDef.getType();
+ }
+ // Specific Update Logic
+ Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll();
+ if (allDataTypes.isRight()) {
+ TitanOperationStatus status = allDataTypes.right().value();
+ BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status))));
+ }
+ Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, property.getValue(), true, innerType, allDataTypes.left().value());
+
+ String newValue = property.getValue();
+ if (isValid.isRight()) {
+ Boolean res = isValid.right().value();
+ if (res == false) {
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT))));
+ }
+ } else {
+ Object object = isValid.left().value();
+ if (object != null) {
+ newValue = object.toString();
+ }
+ }
+
+ ImmutablePair<String, Boolean> pair = propertyOperation.validateAndUpdateRules(propertyType, property.getRules(), innerType, allDataTypes.left().value(), true);
+ if (pair.getRight() != null && pair.getRight() == false) {
+ BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType);
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT))));
+ }
+
+
+
+ try {
+ List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(resourceInstanceId);
+ Optional<ComponentInstanceProperty> instanceProperty = instanceProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
+ StorageOperationStatus status;
+ instanceProperty.get().setValue(newValue);
+ if(instanceProperty.isPresent()){
+ status = toscaOperationFacade.updateComponentInstanceProperty(containerComponent, foundResourceInstance.getUniqueId(), property);
+ } else {
+ status = toscaOperationFacade.addComponentInstanceProperty(containerComponent, foundResourceInstance.getUniqueId(), property);
+ }
+ if(status != StorageOperationStatus.OK){
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
+ resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
+ return resultOp;
+ }
+ foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
+ Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
+
+ if (updateContainerRes.isRight()) {
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
+ resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
+ return resultOp;
+ }
+ resultOp = Either.left(property);
+ return resultOp;
+
+ } finally {
+ if (resultOp == null || resultOp.isRight()) {
+ titanDao.rollback();
+ } else {
+ titanDao.commit();
+ }
+ // unlock resource
+ graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
+ }
+
+ }
+
+ public Either<ComponentInstanceInput, ResponseFormat> createOrUpdateInstanceInputValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceInput property, String userId) {
+
+ Either<ComponentInstanceInput, ResponseFormat> resultOp = null;
+
+ Either<User, ResponseFormat> resp = validateUserExists(userId, "create Or Update Property Value", false);
+ if (resp.isRight()) {
+ return Either.right(resp.right().value());
+ }
+
+ if (componentTypeEnum == null) {
+ BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertyValue", "invalid component type", ErrorSeverity.INFO);
+ resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
+ return resultOp;
+ }
+ Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
+
+ if (getResourceResult.isRight()) {
+ log.debug("Failed to retrieve component, component id {}", componentId);
+ resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
+ return resultOp;
+ }
+ Component containerComponent = getResourceResult.left().value();
+
+ if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
+ log.info("Restricted operation for user: {} on service {}", userId, componentId);
+ resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
+ return resultOp;
+ }
+ Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
+ if (resourceInstanceStatus.isRight()) {
+ resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, resourceInstanceId, componentId));
+ return resultOp;
+ }
+
+ ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
+
+ // lock resource
+ StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
+ if (lockStatus != StorageOperationStatus.OK) {
+ log.debug("Failed to lock service {}", componentId);
+ resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
+ return resultOp;
+ }
+ String innerType = null;
+ String propertyType = property.getType();
+ ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
+ log.debug("The type of the property {} is {}", property.getUniqueId(), propertyType);
+
+ if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
+ SchemaDefinition def = property.getSchema();
+ if (def == null) {
+ log.debug("Schema doesn't exists for property of type {}", type);
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
+ }
+ PropertyDataDefinition propDef = def.getProperty();
+ if (propDef == null) {
+ log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
+ }
+ innerType = propDef.getType();
+ }
+ // Specific Update Logic
+ Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll();
+ if (allDataTypes.isRight()) {
+ TitanOperationStatus status = allDataTypes.right().value();
+ BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status))));
+ }
+ Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, property.getValue(), true, innerType, allDataTypes.left().value());
+
+ String newValue = property.getValue();
+ if (isValid.isRight()) {
+ Boolean res = isValid.right().value();
+ if (res == false) {
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT))));
+ }
+ } else {
+ Object object = isValid.left().value();
+ if (object != null) {
+ newValue = object.toString();
+ }
+ }
+
+ try {
+ List<ComponentInstanceInput> instanceProperties = containerComponent.getComponentInstancesInputs().get(resourceInstanceId);
+ Optional<ComponentInstanceInput> instanceProperty = instanceProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
+ StorageOperationStatus status;
+ if(instanceProperty.isPresent()){
+ instanceProperty.get().setValue(property.getValue());
+ status = toscaOperationFacade.updateComponentInstanceInput(containerComponent, foundResourceInstance.getUniqueId(), property);
+ } else {
+ status = toscaOperationFacade.addComponentInstanceInput(containerComponent, foundResourceInstance.getUniqueId(), property);
+ }
+ if(status != StorageOperationStatus.OK){
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
+ resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
+ return resultOp;
+ }
+ foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
+ Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
+
+ if (updateContainerRes.isRight()) {
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
+ resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
+ return resultOp;
+ }
+ resultOp = Either.left(property);
+ return resultOp;
+
+ } finally {
+ if (resultOp == null || resultOp.isRight()) {
+ titanDao.rollback();
+ } else {
+ titanDao.commit();
+ }
+ // unlock resource
+ graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
+ }
+
+ }
+
+ public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateGroupInstancePropertyValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, String groupInstanceId, ComponentInstanceProperty property,
+ String userId) {
+
+ Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
- IComponentOperation componentOperation = getIComponentOperation(componentTypeEnum);
+ Either<User, ResponseFormat> resp = validateUserExists(userId, "create Or Update Property Value", false);
+ if (resp.isRight()) {
+ return Either.right(resp.right().value());
+ }
- if (!ComponentValidationUtils.canWorkOnComponent(componentId, componentOperation, userId)) {
- log.info("Restricted operation for user {} on service {}", userId, componentId);
+ if (componentTypeEnum == null) {
+ BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertyValue", "invalid component type", ErrorSeverity.INFO);
+ resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
+ return resultOp;
+ }
+
+ if (!ComponentValidationUtils.canWorkOnComponent(componentId, toscaOperationFacade, userId)) {
+ log.info("Restricted operation for user: {} on service: {}", userId, componentId);
resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
return resultOp;
}
@@ -1201,63 +1296,67 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
try {
String propertyValueUid = property.getValueUniqueUid();
+
if (propertyValueUid == null) {
- Either<Integer, StorageOperationStatus> counterRes = componentInstanceOperation.increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, GraphPropertiesDictionary.PROPERTY_COUNTER, true);
+ Either<Integer, StorageOperationStatus> counterRes = groupInstanceOperation.increaseAndGetGroupInstancePropertyCounter(groupInstanceId);
if (counterRes.isRight()) {
- log.debug("increaseAndGetResourcePropertyCounter failed resource instance {} property {}", resourceInstanceId, property);
+ log.debug("increaseAndGetResourcePropertyCounter failed resource instance: {} property: {}", resourceInstanceId, property);
StorageOperationStatus status = counterRes.right().value();
ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
resultOp = Either.right(componentsUtils.getResponseFormat(actionStatus));
}
Integer index = counterRes.left().value();
- Either<ComponentInstanceProperty, StorageOperationStatus> result = componentInstanceOperation.addPropertyValueToResourceInstance(property, resourceInstanceId, index, true);
+ Either<ComponentInstanceProperty, StorageOperationStatus> result = groupInstanceOperation.addPropertyValueToGroupInstance(property, resourceInstanceId, index, true);
if (result.isLeft()) {
- log.debug("Property value was added to resource instance {}", resourceInstanceId);
+ log.trace("Property value was added to resource instance {}", resourceInstanceId);
ComponentInstanceProperty instanceProperty = result.left().value();
resultOp = Either.left(instanceProperty);
- return resultOp;
} else {
- log.debug("Failed to add property value {} to resource instance {}", property, resourceInstanceId);
- // TODO: esofer add error
+ log.debug("Failed to add property value: {} to resource instance {}", property, resourceInstanceId);
ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
-
- return resultOp;
}
} else {
- Either<ComponentInstanceProperty, StorageOperationStatus> result = componentInstanceOperation.updatePropertyValueInResourceInstance(property, resourceInstanceId, true);
+ Either<ComponentInstanceProperty, StorageOperationStatus> result = groupInstanceOperation.updatePropertyValueInGroupInstance(property, resourceInstanceId, true);
if (result.isLeft()) {
log.debug("Property value {} was updated on graph.", property.getValueUniqueUid());
ComponentInstanceProperty instanceProperty = result.left().value();
resultOp = Either.left(instanceProperty);
- return resultOp;
} else {
- log.debug("Failed to update property value {} in resource instance {}", property, resourceInstanceId);
+ log.debug("Failed to update property value: {}, in resource instance {}", property, resourceInstanceId);
ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
+ }
+ }
+ if (resultOp.isLeft()) {
+ StorageOperationStatus updateCustomizationUUID = componentInstanceOperation.updateCustomizationUUID(resourceInstanceId);
+ if (updateCustomizationUUID != StorageOperationStatus.OK) {
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateCustomizationUUID);
+
+ resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
- return resultOp;
}
}
+ return resultOp;
} finally {
if (resultOp == null || resultOp.isRight()) {
- titanGenericDao.rollback();
+ titanDao.rollback();
} else {
- titanGenericDao.commit();
+ titanDao.commit();
}
// unlock resource
graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
@@ -1280,10 +1379,8 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
return resultOp;
}
- IComponentOperation componentOperation = getIComponentOperation(componentTypeEnum);
-
- if (!ComponentValidationUtils.canWorkOnComponent(componentId, componentOperation, userId)) {
- log.info("Restricted operation for user {} on service {}", userId, componentId);
+ if (!ComponentValidationUtils.canWorkOnComponent(componentId, toscaOperationFacade, userId)) {
+ log.info("Restricted operation for user: {} on service: {}", userId, componentId);
resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
return resultOp;
}
@@ -1318,7 +1415,6 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
} else {
log.debug("Failed to add input value {} to resource instance {}", inputProperty, resourceInstanceId);
- // TODO: esofer add error
ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
@@ -1338,7 +1434,7 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
return resultOp;
} else {
- log.debug("Failed to update property value {} in reosurce instance {}", inputProperty, resourceInstanceId);
+ log.debug("Failed to update property value {} in resource instance {}", inputProperty, resourceInstanceId);
ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
@@ -1350,9 +1446,9 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
} finally {
if (resultOp == null || resultOp.isRight()) {
- titanGenericDao.rollback();
+ titanDao.rollback();
} else {
- titanGenericDao.commit();
+ titanDao.commit();
}
// unlock resource
graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
@@ -1375,9 +1471,7 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
return resultOp;
}
- IComponentOperation componentOperation = getIComponentOperation(componentTypeEnum);
-
- if (!ComponentValidationUtils.canWorkOnComponent(serviceId, componentOperation, userId)) {
+ if (!ComponentValidationUtils.canWorkOnComponent(serviceId, toscaOperationFacade, userId)) {
log.info("Restricted operation for user {} on service {}", userId, serviceId);
resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
return resultOp;
@@ -1411,9 +1505,9 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
} finally {
if (resultOp == null || resultOp.isRight()) {
- titanGenericDao.rollback();
+ titanDao.rollback();
} else {
- titanGenericDao.commit();
+ titanDao.commit();
}
// unlock resource
graphLockOperation.unlockComponent(serviceId, componentTypeEnum.getNodeType());
@@ -1421,60 +1515,32 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
- private Either<Boolean, ResponseFormat> validateComponentInstanceName(String resourceInstanceName, ComponentInstance resourceInstance, boolean isCreate) {
- ComponentTypeEnum containerComponentType = getComponentTypeOfComponentInstance();
- if (!isCreate) {
- if (resourceInstanceName == null)
- return Either.left(true);
- }
-
- if (!ValidationUtils.validateStringNotEmpty(resourceInstanceName)) {
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_COMPONENT_NAME, containerComponentType.getValue());
-
- return Either.right(errorResponse);
- }
- resourceInstance.setNormalizedName(ValidationUtils.normaliseComponentInstanceName(resourceInstanceName));
- if (!isCreate) {
- if (!ValidationUtils.validateResourceInstanceNameLength(resourceInstanceName)) {
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT, containerComponentType.getValue(), "" + ValidationUtils.COMPONENT_NAME_MAX_LENGTH);
-
- return Either.right(errorResponse);
- }
- if (!ValidationUtils.validateResourceInstanceName(resourceInstanceName)) {
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_COMPONENT_NAME, containerComponentType.getValue());
-
- return Either.right(errorResponse);
- }
- }
-
- return Either.left(true);
-
- }
-
- private Either<Boolean, ResponseFormat> validateComponentInstanceParentState(ComponentTypeEnum containerComponentType, ComponentInstance resourceInstance) {
- String componentId = resourceInstance.getComponentUid();
- Either<? extends Component, StorageOperationStatus> eitherResourceResponse = Either.right(StorageOperationStatus.GENERAL_ERROR);
-
+ private Either<Component, ResponseFormat> getAndValidateOriginComponentOfComponentInstance(ComponentTypeEnum containerComponentType, ComponentInstance componentInstance) {
+
+ Either<Component, ResponseFormat> eitherResponse = null;
ComponentTypeEnum componentType = getComponentTypeByParentComponentType(containerComponentType);
- ComponentOperation componentOperation = getComponentOperation(componentType);
- if (componentOperation != null)
- eitherResourceResponse = componentOperation.getComponent(componentId, true);
-
- Component component = null;
- ResponseFormat errorResponse = null;
- if (eitherResourceResponse.isRight()) {
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(eitherResourceResponse.right().value(), componentType);
+ Component component;
+ ResponseFormat errorResponse;
+ Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getToscaFullElement(componentInstance.getComponentUid());
+ if (getComponentRes.isRight()) {
+ log.debug("Failed to get the component with id {} for component instance {} creation. ", componentInstance.getComponentUid(), componentInstance.getName());
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentRes.right().value(), componentType);
errorResponse = componentsUtils.getResponseFormat(actionStatus, Constants.EMPTY_STRING);
- return Either.right(errorResponse);
+ eitherResponse = Either.right(errorResponse);
+ }
+ if(eitherResponse == null) {
+ component = getComponentRes.left().value();
+ LifecycleStateEnum resourceCurrState = component.getLifecycleState();
+ if (resourceCurrState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) {
+ ActionStatus actionStatus = ActionStatus.ILLEGAL_COMPONENT_STATE;
+ errorResponse = componentsUtils.getResponseFormat(actionStatus, component.getComponentType().toString(), component.getName(), resourceCurrState.toString());
+ eitherResponse = Either.right(errorResponse);
+ }
}
- component = eitherResourceResponse.left().value();
- LifecycleStateEnum resourceCurrState = component.getLifecycleState();
- if (resourceCurrState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) {
- ActionStatus actionStatus = ActionStatus.ILLEGAL_COMPONENT_STATE;
- errorResponse = componentsUtils.getResponseFormat(actionStatus, component.getComponentType().toString(), component.getName(), resourceCurrState.toString());
- return Either.right(errorResponse);
+ if(eitherResponse == null) {
+ eitherResponse = Either.left(getComponentRes.left().value());
}
- return Either.left(true);
+ return eitherResponse;
}
public Either<ComponentInstance, ResponseFormat> changeComponentInstanceVersion(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance newComponentInstance) {
@@ -1484,6 +1550,7 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
return Either.right(resp.right().value());
}
+ User user = resp.left().value();
Either<ComponentInstance, ResponseFormat> resultOp = null;
Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
@@ -1492,9 +1559,8 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
- final ComponentOperation containerOperation = getComponentOperation(containerComponentType);
- Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, false, true);
+ Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
if (validateComponentExists.isRight()) {
return Either.right(validateComponentExists.right().value());
}
@@ -1505,25 +1571,12 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
return Either.right(validateCanWorkOnComponent.right().value());
}
- Either<Boolean, StorageOperationStatus> validateParentStatus = componentInstanceOperation.validateParent(containerComponentId, componentInstanceId, false);
- if (validateParentStatus.isRight()) {
- log.debug("Failed to get resource instance {} on service {}", componentInstanceId, containerComponentId);
- resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND, componentInstanceId));
- return resultOp;
- }
- Boolean isPrentValid = validateParentStatus.left().value();
- if (!isPrentValid) {
+ Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent,componentInstanceId);
+ if (resourceInstanceStatus.isRight()) {
resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceId, containerComponentId));
return resultOp;
-
}
- Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = componentInstanceOperation.getResourceInstanceById(componentInstanceId);
- if (resourceInstanceStatus.isRight()) {
- log.debug("Failed to get resource instance {} on service {}", componentInstanceId, containerComponentId);
- resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND, componentInstanceId));
- return resultOp;
- }
ComponentInstance currentResourceInstance = resourceInstanceStatus.left().value();
Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "changeComponentInstanceVersion");
@@ -1538,43 +1591,24 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
String resourceId = newComponentInstance.getComponentUid();
- if (!getCompInstOriginComponentOperation().isComponentExist(resourceId)) {
- log.debug("resource {} not found.", resourceId);
- resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, ""));
+ Either<Boolean, StorageOperationStatus> componentExistsRes = toscaOperationFacade.validateComponentExists(resourceId);
+ if(componentExistsRes.isRight()){
+ log.debug("Failed to validate existing of the component {}. Status is {} ", resourceId);
+ resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(componentExistsRes.right().value()), resourceId));
return resultOp;
}
-
- // esofer - before deleting component instance, we should keep the
- // groups which holds this instance
- List<String> groupsToRevert = new ArrayList<>();
- Either<List<String>, StorageOperationStatus> associatedGroups = groupOperation.getAssociatedGroupsToComponentInstance(componentInstanceId, true);
- if (associatedGroups.isRight()) {
- StorageOperationStatus status = associatedGroups.right().value();
- if (status != StorageOperationStatus.OK) {
- BeEcompErrorManager.getInstance().logInternalFlowError("ChangeComponentInstanceVersion", "Failed to getch groups of current component instance", ErrorSeverity.ERROR);
- resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
- return resultOp;
- }
- } else {
- List<String> groups = associatedGroups.left().value();
- groupsToRevert.addAll(groups);
- }
- // rbetzer - before deleting component instance, retrieve env artifacts to keep track of artifactVersion
-
- Either<Map<String, ArtifactDefinition>, StorageOperationStatus> retrieveEnvArtifacts = componentInstanceOperation.fetchCIEnvArtifacts(componentInstanceId);
- if (retrieveEnvArtifacts.isLeft())
- newComponentInstance.setDeploymentArtifacts(retrieveEnvArtifacts.left().value());
- else if (retrieveEnvArtifacts.right().value() != StorageOperationStatus.OK) {
- log.debug("falied to fetch instance deployment artifacts {}", componentInstanceId );
+ else if (!componentExistsRes.left().value()) {
+ log.debug("The resource {} not found ", resourceId);
+ resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
+ return resultOp;
}
- resultOp = deleteComponentInstance(containerComponentId, componentInstanceId, containerComponentType);
+ List<GroupInstance> groupInstances = currentResourceInstance.getGroupInstances();
+ Map<String, ArtifactDefinition> deploymentArtifacts = currentResourceInstance.getDeploymentArtifacts();
+ resultOp = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType);
if (resultOp.isRight()) {
-
log.debug("failed to delete resource instance {}", resourceId);
-
return resultOp;
-
}
Either<Component, ResponseFormat> eitherResourceName = getOriginComponentNameFromComponentInstance(newComponentInstance, true);
@@ -1592,41 +1626,53 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
newComponentInstance.setPosY(resResourceInfo.getPosY());
newComponentInstance.setDescription(resResourceInfo.getDescription());
- resultOp = createComponentInstanceOnGraph(containerComponent, origComponent, newComponentInstance, userId, containerOperation, true);
+ resultOp = createComponentInstanceOnGraph(containerComponent, origComponent, newComponentInstance, user);
if (resultOp.isRight()) {
-
log.debug("failed to create resource instance {}", resourceId);
-
return resultOp;
-
}
- newComponentInstance = resultOp.left().value();
- newComponentInstance.setName(resResourceInfo.getName());
- resultOp = updateComponentInstance(containerComponentId, containerComponentType, origComponent, newComponentInstance.getUniqueId(), newComponentInstance, true);
-
ComponentInstance updatedComponentInstance = resultOp.left().value();
if (resultOp.isRight()) {
log.debug("failed to create resource instance {}", resourceId);
return resultOp;
}
- if (false == groupsToRevert.isEmpty()) {
- StorageOperationStatus associatedGroupsToComponentInstance = groupOperation.associateGroupsToComponentInstance(groupsToRevert, updatedComponentInstance.getUniqueId(), updatedComponentInstance.getName(), true);
- if (associatedGroupsToComponentInstance != StorageOperationStatus.OK) {
+ if (CollectionUtils.isNotEmpty(groupInstances)) {
+ StorageOperationStatus addGroupsToComponentInstance = toscaOperationFacade.addGroupInstancesToComponentInstance(containerComponent, updatedComponentInstance, groupInstances);
+ if (addGroupsToComponentInstance != StorageOperationStatus.OK) {
+ BeEcompErrorManager.getInstance().logInternalFlowError("ChangeComponentInstanceVersion", "Failed to associate groups to new component instance", ErrorSeverity.ERROR);
+ resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ return resultOp;
+ }
+ }
+ if (MapUtils.isNotEmpty(deploymentArtifacts)) {
+ StorageOperationStatus addDeploymentArtifactsToComponentInstance = toscaOperationFacade.addDeploymentArtifactsToComponentInstance(containerComponent, updatedComponentInstance, deploymentArtifacts);
+ if (addDeploymentArtifactsToComponentInstance != StorageOperationStatus.OK) {
BeEcompErrorManager.getInstance().logInternalFlowError("ChangeComponentInstanceVersion", "Failed to associate groups to new component instance", ErrorSeverity.ERROR);
resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
return resultOp;
}
}
- Either<ComponentInstance, StorageOperationStatus> fullResourceInstance = componentInstanceOperation.getFullComponentInstance(resultOp.left().value(), getNodeTypeOfComponentInstanceOrigin());
- if (fullResourceInstance.isRight()) {
- resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(fullResourceInstance.right().value()), resourceId));
+
+ ComponentParametersView filter = new ComponentParametersView(true);
+ filter.setIgnoreComponentInstances(false);
+ Either<Component, StorageOperationStatus> updatedComponentRes = toscaOperationFacade.getToscaElement(containerComponentId, filter);
+ if (updatedComponentRes.isRight()) {
+ StorageOperationStatus storageOperationStatus = updatedComponentRes.right().value();
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageOperationStatus, containerComponent.getComponentType());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus, Constants.EMPTY_STRING);
+ log.debug("Component with id {} was not found", containerComponentId);
+ return Either.right(responseFormat);
+ }
+ resourceInstanceStatus = getResourceInstanceById(updatedComponentRes.left().value(),updatedComponentInstance.getUniqueId());
+ if (resourceInstanceStatus.isRight()) {
+ resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceInstanceStatus.right().value()), updatedComponentInstance.getUniqueId()));
return resultOp;
}
- resultOp = Either.left(fullResourceInstance.left().value());
+ resultOp = Either.left(resourceInstanceStatus.left().value());
return resultOp;
} finally {
@@ -1640,9 +1686,48 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
protected abstract ComponentTypeEnum getComponentTypeOfComponentInstance();
- protected abstract ComponentOperation getContainerComponentOperation();
+ // US831698
+ public Either<List<ComponentInstanceProperty>, ResponseFormat> getComponentInstancePropertiesById(String containerComponentTypeParam, String containerComponentId, String componentInstanceUniqueId, String userId) {
+ final String ECOMP_ERROR_CONTEXT = "Get Component Instance Properties By Id";
+ Component containerComponent = null;
+
+ Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
+ try {
+ Either<User, ResponseFormat> validateUserExists = validateUserExists(userId, ECOMP_ERROR_CONTEXT, false);
+ if (validateUserExists.isRight()) {
+ resultOp = Either.right(validateUserExists.right().value());
+ return resultOp;
+ }
- protected abstract ComponentOperation getCompInstOriginComponentOperation();
+ Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentTypeParam);
+ if (validateComponentType.isRight()) {
+ resultOp = Either.right(validateComponentType.right().value());
+ return resultOp;
+ }
+
+ Either<Component, StorageOperationStatus> validateContainerComponentExists = toscaOperationFacade.getToscaElement(containerComponentId);
+ if (validateContainerComponentExists.isRight()) {
+ resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validateContainerComponentExists.right().value())));
+ return resultOp;
+ }
+ containerComponent = validateContainerComponentExists.left().value();
+
+ Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId);
+ if (resourceInstanceStatus.isRight()) {
+ resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
+ return resultOp;
+ }
+
+ List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(componentInstanceUniqueId);
+ if(CollectionUtils.isEmpty(instanceProperties)){
+ instanceProperties = new ArrayList<>();
+ }
+ resultOp = Either.left(instanceProperties);
+ return resultOp;
+ } finally {
+ unlockComponent(resultOp, containerComponent);
+ }
+ }
protected void validateIncrementCounter(String resourceInstanceId, GraphPropertiesDictionary counterType, Wrapper<Integer> instaceCounterWrapper, Wrapper<ResponseFormat> errorWrapper) {
Either<Integer, StorageOperationStatus> counterRes = componentInstanceOperation.increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, counterType, true);
@@ -1658,4 +1743,75 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
+ /**
+ * updates componentInstance modificationTime
+ *
+ * @param componentInstance
+ * @param componentInstanceType
+ * @param modificationTime
+ * @param inTransaction
+ * @return
+ */
+ public Either<ComponentInstanceData, ResponseFormat> updateComponentInstanceModificationTimeAndCustomizationUuid(ComponentInstance componentInstance, NodeTypeEnum componentInstanceType, Long modificationTime, boolean inTransaction) {
+ Either<ComponentInstanceData, ResponseFormat> result;
+ Either<ComponentInstanceData, StorageOperationStatus> updateComponentInstanceRes = componentInstanceOperation.updateComponentInstanceModificationTimeAndCustomizationUuidOnGraph(componentInstance, componentInstanceType, modificationTime,
+ inTransaction);
+ if (updateComponentInstanceRes.isRight()) {
+ log.debug("Failed to update component instance {} with new last update date and mofifier. Status is {}. ", componentInstance.getName(), updateComponentInstanceRes.right().value());
+ result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateComponentInstanceRes.right().value())));
+ } else {
+ result = Either.left(updateComponentInstanceRes.left().value());
+ }
+ return result;
+ }
+
+ private Boolean validateInstanceNameUniqueness(Component containerComponent, ComponentInstance oldComponentInstance, String newInstanceName) {
+ Boolean isUnique = true;
+ String newInstanceNormalizedName = ValidationUtils.normalizeComponentInstanceName(newInstanceName);
+ if (!oldComponentInstance.getNormalizedName().equals(newInstanceNormalizedName)) {
+ Optional<ComponentInstance> foundComponentInstance = containerComponent.getComponentInstances().stream().filter(ci -> ci.getNormalizedName().equals(newInstanceNormalizedName)).findFirst();
+ if (foundComponentInstance.isPresent()) {
+ isUnique = false;
+ }
+ if (isUnique) {
+ foundComponentInstance = containerComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().endsWith(newInstanceNormalizedName)).findFirst();
+ if (foundComponentInstance.isPresent()) {
+ isUnique = false;
+ }
+ }
+ }
+ return isUnique;
+ }
+
+ private Boolean validateInstanceNameUniquenessUponUpdate(Component containerComponent, ComponentInstance oldComponentInstance, String newInstanceName) {
+ Boolean isUnique = true;
+ String newInstanceNormalizedName = ValidationUtils.normalizeComponentInstanceName(newInstanceName);
+ if (!oldComponentInstance.getNormalizedName().equals(newInstanceNormalizedName)) {
+ Optional<ComponentInstance> foundComponentInstance = containerComponent.getComponentInstances().stream().filter(ci -> ci.getNormalizedName().equals(newInstanceNormalizedName)).findFirst();
+ if (foundComponentInstance.isPresent()) {
+ isUnique = false;
+ }
+ }
+ return isUnique;
+ }
+
+ private Either<ComponentInstance, StorageOperationStatus> getResourceInstanceById(Component containerComponent, String instanceId) {
+
+ Either<ComponentInstance, StorageOperationStatus> result = null;
+ List<ComponentInstance> instances = containerComponent.getComponentInstances();
+ Optional<ComponentInstance> foundInstance = null;
+ if(CollectionUtils.isEmpty(instances)){
+ result = Either.right(StorageOperationStatus.NOT_FOUND);
+ }
+ if(result == null){
+ foundInstance = instances.stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst();
+ if(!foundInstance.isPresent()){
+ result = Either.right(StorageOperationStatus.NOT_FOUND);
+ }
+ }
+ if(result == null){
+ result = Either.left(foundInstance.get());
+ }
+ return result;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CompositionBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CompositionBusinessLogic.java
index 6cebc7dd53..e8c04c22c1 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CompositionBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CompositionBusinessLogic.java
@@ -110,6 +110,9 @@ public class CompositionBusinessLogic {
case VFC:
offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.VFC_CANVAS_ELEMENT_SIZE / 2;
break;
+ case VFCMT:
+ offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.VFC_CANVAS_ELEMENT_SIZE / 2;
+ break;
default:
offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.VFC_CANVAS_ELEMENT_SIZE / 2;
break;
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ConsumerBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ConsumerBusinessLogic.java
index 226225a07c..9c5cefb24c 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ConsumerBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ConsumerBusinessLogic.java
@@ -87,7 +87,7 @@ public class ConsumerBusinessLogic extends BaseBusinessLogic {
if (!lockResult.equals(StorageOperationStatus.OK)) {
BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedLockObjectError, "createConsumer");
BeEcompErrorManager.getInstance().logBeFailedLockObjectError("createConsumer", NodeTypeEnum.ConsumerCredentials.getName(), consumerName);
- log.debug("Failed to lock consumer {} error - {}", consumerName, lockResult);
+ log.debug("Failed to lock consumer: {} error - {}", consumerName, lockResult);
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
componentsUtils.auditConsumerCredentialsEvent(AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS, consumer, responseFormat, user);
@@ -123,7 +123,7 @@ public class ConsumerBusinessLogic extends BaseBusinessLogic {
private Either<User, ResponseFormat> validateUser(User user, ConsumerDefinition consumer, AuditingActionEnum auditAction) {
if (user.getUserId() == null || user.getUserId().trim().isEmpty()) {
- log.debug("createEcompUser method - user is missing. userId={}", user.getUserId());
+ log.debug("createEcompUser method - user is missing. userId= {}", user.getUserId());
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
log.debug("audit before sending response");
componentsUtils.auditConsumerCredentialsEvent(auditAction, consumer, responseFormat, user);
@@ -132,7 +132,7 @@ public class ConsumerBusinessLogic extends BaseBusinessLogic {
log.debug("get user from DB");
Either<User, ActionStatus> eitherCreator = userAdmin.getUser(user.getUserId(), false);
if (eitherCreator.isRight() || eitherCreator.left().value() == null) {
- log.debug("createEcompUser method - user is not listed. userId={}", user.getUserId());
+ log.debug("createEcompUser method - user is not listed. userId= {}", user.getUserId());
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_ACCESS);
log.debug("audit before sending response");
componentsUtils.auditConsumerCredentialsEvent(auditAction, consumer, responseFormat, user);
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CsarValidationUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CsarValidationUtils.java
index badb257a80..ae6237897a 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CsarValidationUtils.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CsarValidationUtils.java
@@ -22,16 +22,20 @@ package org.openecomp.sdc.be.components.impl;
import java.io.ByteArrayInputStream;
import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
+import java.util.stream.Collectors;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.be.tosca.CsarUtils;
import org.openecomp.sdc.common.util.GeneralUtility;
import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
@@ -55,22 +59,74 @@ public class CsarValidationUtils {
public static final String TOSCA_META_ENTRY_DEFINITIONS = "Entry-Definitions";
- public final static String[] TOSCA_METADATA_FIELDS = { TOSCA_META_FILE_VERSION, CSAR_VERSION, CREATED_BY, TOSCA_META_ENTRY_DEFINITIONS };
+ private static final String[] TOSCA_METADATA_FIELDS = { TOSCA_META_FILE_VERSION, CSAR_VERSION, CREATED_BY, TOSCA_META_ENTRY_DEFINITIONS };
public final static String ARTIFACTS_METADATA_FILE = "HEAT.meta";
- public final static String ARTIFACTS = "Artifacts/";
-
public static final String TOSCA_CSAR_EXTENSION = ".csar";
-
+/**
+ * Validates Csar
+ * @param csar
+ * @param csarUUID
+ * @param componentsUtils
+ * @return
+ */
public static Either<Boolean, ResponseFormat> validateCsar(Map<String, byte[]> csar, String csarUUID, ComponentsUtils componentsUtils) {
Either<Boolean, ResponseFormat> validateStatus = validateIsTOSCAMetadataExist(csar, csarUUID, componentsUtils);
if (validateStatus.isRight()) {
return Either.right(validateStatus.right().value());
}
+
+ removeNonUniqueArtifactsFromCsar(csar);
+
log.trace("TOSCA-Metadata/TOSCA.meta file found, CSAR id {}", csarUUID);
- return validateTOSCAMetadataFile(csar, csarUUID, componentsUtils);
+ validateStatus = validateTOSCAMetadataFile(csar, csarUUID, componentsUtils);
+ if (validateStatus.isRight()) {
+ return Either.right(validateStatus.right().value());
+ }
+ return Either.left(true);
+ }
+
+ private static void removeNonUniqueArtifactsFromCsar(Map<String, byte[]> csar) {
+
+ List<String> nonUniqueArtifactsToRemove = new ArrayList<>();
+ String[] paths = csar.keySet().toArray(new String[csar.keySet().size()]);
+ int numberOfArtifacts = paths.length;
+ for(int i = 0; i < numberOfArtifacts; ++i ){
+ collectNonUniqueArtifact(paths, i, numberOfArtifacts, nonUniqueArtifactsToRemove);
+ }
+ nonUniqueArtifactsToRemove.stream().forEach(path->csar.remove(path));
+ }
+
+ private static void collectNonUniqueArtifact( String[] paths, int currInd, int numberOfArtifacts, List<String> nonUniqueArtifactsToRemove) {
+
+ String[] parsedPath = paths[currInd].split("/");
+ String[] otherParsedPath;
+ int artifactNameInd = parsedPath.length - 1;
+ for(int j = currInd + 1; j < numberOfArtifacts; ++j ){
+ otherParsedPath = paths[j].split("/");
+ if(parsedPath.length == otherParsedPath.length && parsedPath.length > 3 && isEqualArtifactNames(parsedPath, otherParsedPath)){
+ log.error("Can't upload two artifact with the same name {}. The artifact with path {} will be handled, and the artifact with path {} will be ignored. ",
+ parsedPath[artifactNameInd], paths[currInd], paths[j]);
+ nonUniqueArtifactsToRemove.add(paths[j]);
+ }
+ }
+ }
+ private static boolean isEqualArtifactNames(String[] parsedPath, String[] otherParsedPath) {
+ boolean isEqualArtifactNames = false;
+ int artifactNameInd = parsedPath.length - 1;
+ int artifactGroupTypeInd = parsedPath.length - 3;
+ String groupType = parsedPath[artifactGroupTypeInd];
+ String artifactName = parsedPath[artifactNameInd];
+ String otherGroupType = otherParsedPath[artifactGroupTypeInd];
+ String otherArtifactName = otherParsedPath[artifactNameInd];
+ String vfcToscaName = parsedPath.length == 5 ? parsedPath[1] : null;
+
+ if(artifactName.equalsIgnoreCase(otherArtifactName) && groupType.equalsIgnoreCase(otherGroupType)){
+ isEqualArtifactNames = vfcToscaName == null ? true : vfcToscaName.equalsIgnoreCase(otherParsedPath[1]);
+ }
+ return isEqualArtifactNames;
}
public static Either<ImmutablePair<String, String>, ResponseFormat> getToscaYaml(Map<String, byte[]> csar, String csarUUID, ComponentsUtils componentsUtils) {
@@ -83,7 +139,7 @@ public class CsarValidationUtils {
try {
props.load(new ByteArrayInputStream(toscaMetaBytes));
} catch (IOException e) {
- log.debug("TOSCA-Metadata/TOSCA.meta file is not in expected key-value form in csar, csar ID {}", csarUUID);
+ log.debug("TOSCA-Metadata/TOSCA.meta file is not in expected key-value form in csar, csar ID {}", csarUUID, e);
BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID));
}
@@ -110,39 +166,39 @@ public class CsarValidationUtils {
}
public static Either<ImmutablePair<String, String>, ResponseFormat> getArtifactsMeta(Map<String, byte[]> csar, String csarUUID, ComponentsUtils componentsUtils) {
-
- if (!csar.containsKey(ARTIFACTS + ARTIFACTS_METADATA_FILE)) {
+
+ if( !csar.containsKey(CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE) ) {
log.debug("Entry-Definitions entry not found in TOSCA-Metadata/TOSCA.meta file, csar ID {}", csarUUID);
BeEcompErrorManager.getInstance().logInternalDataError("Entry-Definitions entry not found in TOSCA-Metadata/TOSCA.meta file in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.YAML_NOT_FOUND_IN_CSAR, csarUUID, ARTIFACTS_METADATA_FILE));
}
log.trace("Found Entry-Definitions property in TOSCA-Metadata/TOSCA.meta, Entry-Definitions: {}, CSAR id: {}", ARTIFACTS_METADATA_FILE, csarUUID);
- byte[] artifactsMetaBytes = csar.get(ARTIFACTS + ARTIFACTS_METADATA_FILE);
+ byte[] artifactsMetaBytes = csar.get(CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE);
if (artifactsMetaBytes == null) {
- log.debug("Entry-Definitions {} file not found in csar, csar ID {}", ARTIFACTS + ARTIFACTS_METADATA_FILE, csarUUID);
- BeEcompErrorManager.getInstance().logInternalDataError("Entry-Definitions " + ARTIFACTS + ARTIFACTS_METADATA_FILE + " file not found in CSAR with id " + csarUUID, "CSAR structure is invalid", ErrorSeverity.ERROR);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.YAML_NOT_FOUND_IN_CSAR, csarUUID, ARTIFACTS + ARTIFACTS_METADATA_FILE));
+ log.debug("Entry-Definitions {}{} file not found in csar, csar ID {}", CsarUtils.ARTIFACTS_PATH, ARTIFACTS_METADATA_FILE, csarUUID);
+ BeEcompErrorManager.getInstance().logInternalDataError("Entry-Definitions " + CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE + " file not found in CSAR with id " + csarUUID, "CSAR structure is invalid", ErrorSeverity.ERROR);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.YAML_NOT_FOUND_IN_CSAR, csarUUID, CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE));
}
String artifactsFileContents = new String(artifactsMetaBytes);
- return Either.left(new ImmutablePair<String, String>(ARTIFACTS + ARTIFACTS_METADATA_FILE, artifactsFileContents));
+ return Either.left(new ImmutablePair<String, String>(CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE, artifactsFileContents));
}
- public static Either<ImmutablePair<String, byte[]>, ResponseFormat> getArtifactsContent(String csarUUID, Map<String, byte[]> csar, String artifactName, ComponentsUtils componentsUtils) {
- if (!csar.containsKey(ARTIFACTS + artifactName)) {
+ public static Either<ImmutablePair<String, byte[]>, ResponseFormat> getArtifactsContent(String csarUUID, Map<String, byte[]> csar, String artifactPath, String artifactName, ComponentsUtils componentsUtils) {
+ if (!csar.containsKey(artifactPath)) {
log.debug("Entry-Definitions entry not found in Artifacts/HEAT.meta file, csar ID {}", csarUUID);
BeEcompErrorManager.getInstance().logInternalDataError("Entry-Definitions entry not found in TOSCA-Metadata/TOSCA.meta file in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND_IN_CSAR, ARTIFACTS + artifactName, csarUUID));
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND_IN_CSAR, CsarUtils.ARTIFACTS_PATH + artifactName, csarUUID));
}
- log.trace("Found Entry-Definitions property in Artifacts/HEAT.meta, Entry-Definitions: {}, CSAR id: {}", ARTIFACTS + artifactName, csarUUID);
- byte[] artifactFileBytes = csar.get(ARTIFACTS + artifactName);
+ log.trace("Found Entry-Definitions property in Artifacts/HEAT.meta, Entry-Definitions: {}, CSAR id: {}", artifactPath, csarUUID);
+ byte[] artifactFileBytes = csar.get(artifactPath);
if (artifactFileBytes == null) {
- log.debug("Entry-Definitions {} file not found in csar, csar ID {}", ARTIFACTS + artifactName, csarUUID);
- BeEcompErrorManager.getInstance().logInternalDataError("Entry-Definitions " + ARTIFACTS + artifactName + " file not found in CSAR with id " + csarUUID, "CSAR structure is invalid", ErrorSeverity.ERROR);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND_IN_CSAR, ARTIFACTS + artifactName, csarUUID));
+ log.debug("Entry-Definitions {}{} file not found in csar, csar ID {}", CsarUtils.ARTIFACTS_PATH, artifactName, csarUUID);
+ BeEcompErrorManager.getInstance().logInternalDataError("Entry-Definitions " + artifactPath + " file not found in CSAR with id " + csarUUID, "CSAR structure is invalid", ErrorSeverity.ERROR);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND_IN_CSAR, artifactPath, csarUUID));
}
return Either.left(new ImmutablePair<String, byte[]>(artifactName, artifactFileBytes));
@@ -182,7 +238,7 @@ public class CsarValidationUtils {
try {
props.load(new ByteArrayInputStream(splited[index].getBytes()));
} catch (IOException e) {
- log.debug("TOSCA-Metadata/TOSCA.meta file is not in expected key-value form in csar, csar ID {}", csarUUID);
+ log.debug("TOSCA-Metadata/TOSCA.meta file is not in expected key-value form in csar, csar ID {}", csarUUID, e);
BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID));
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ElementBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ElementBusinessLogic.java
index 5ebb86f1ba..958adc0eef 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ElementBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ElementBusinessLogic.java
@@ -29,17 +29,27 @@ import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Predicate;
+import java.util.stream.Collectors;
+import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge;
+import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
+import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
+import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels;
import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
+import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
import org.openecomp.sdc.be.datamodel.api.CategoryTypeEnum;
import org.openecomp.sdc.be.datamodel.utils.NodeTypeConvertUtils;
+import org.openecomp.sdc.be.datatypes.components.ComponentMetadataDataDefinition;
+import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.AssetTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.FilterKeyEnum;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.model.ArtifactType;
import org.openecomp.sdc.be.model.Component;
@@ -48,6 +58,7 @@ import org.openecomp.sdc.be.model.LifecycleStateEnum;
import org.openecomp.sdc.be.model.Product;
import org.openecomp.sdc.be.model.PropertyScope;
import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.ResourceMetadataDefinition;
import org.openecomp.sdc.be.model.Service;
import org.openecomp.sdc.be.model.Tag;
import org.openecomp.sdc.be.model.User;
@@ -56,15 +67,25 @@ import org.openecomp.sdc.be.model.category.GroupingDefinition;
import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
import org.openecomp.sdc.be.model.operations.api.IElementOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.be.model.operations.impl.ComponentOperation;
+import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
+import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
+import org.openecomp.sdc.be.resources.data.ComponentMetadataData;
+import org.openecomp.sdc.be.resources.data.ResourceMetadataData;
+import org.openecomp.sdc.be.resources.data.ServiceMetadataData;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.resources.data.category.CategoryData;
+import org.openecomp.sdc.be.resources.data.category.SubCategoryData;
+import org.openecomp.sdc.be.ui.model.UiCategories;
import org.openecomp.sdc.be.user.Role;
import org.openecomp.sdc.be.user.UserBusinessLogic;
+import org.openecomp.sdc.common.datastructure.Wrapper;
import org.openecomp.sdc.common.util.ValidationUtils;
import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import com.thinkaurelius.titan.core.TitanGraph;
+
import fj.data.Either;
@org.springframework.stereotype.Component("elementsBusinessLogic")
@@ -198,10 +219,8 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
}
private Either<Map<String, List<? extends Component>>, ResponseFormat> handleFollowedCertifiedServices(Set<DistributionStatusEnum> distStatus) {
- Map<String, Object> propertiesToMatch = new HashMap<>();
- propertiesToMatch.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFIED.name());
- Either<Set<Service>, StorageOperationStatus> services = serviceOperation.getCertifiedServicesWithDistStatus(propertiesToMatch, distStatus, false);
+ Either<List<Service>, StorageOperationStatus> services = toscaOperationFacade.getCertifiedServicesWithDistStatus(distStatus);
if (services.isLeft()) {
Map<String, List<? extends Component>> result = new HashMap<String, List<? extends Component>>();
List<Service> list = new ArrayList<>();
@@ -216,43 +235,37 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
private Either<Map<String, List<? extends Component>>, ResponseFormat> handleTester(String userId) {
Set<LifecycleStateEnum> lifecycleStates = new HashSet<LifecycleStateEnum>();
lifecycleStates.add(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
- Either<List<Resource>, StorageOperationStatus> resources = resourceOperation.getTesterFollowed(userId, lifecycleStates, false);
-
- if (resources.isLeft()) {
- Either<List<Service>, StorageOperationStatus> services = serviceOperation.getTesterFollowed(userId, lifecycleStates, false);
- if (services.isLeft()) {
- Map<String, List<? extends Component>> result = new HashMap<String, List<? extends Component>>();
- result.put("services", services.left().value());
- result.put("resources", resources.left().value());
- return Either.left(result);
- } else {
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(services.right().value())));
- }
- } else {
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resources.right().value())));
- }
+ lifecycleStates.add(LifecycleStateEnum.READY_FOR_CERTIFICATION);
+ Either<Map<String, List<? extends Component>>, ResponseFormat> result = getFollowedResourcesAndServices(null, lifecycleStates, null);
+
+ return result;
}
private Either<Map<String, List<? extends Component>>, ResponseFormat> getFollowedResourcesAndServices(String userId, Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates) {
- Either<List<Resource>, StorageOperationStatus> resources = resourceOperation.getFollowed(userId, lifecycleStates, lastStateStates, false);
-
- if (resources.isLeft()) {
- Either<List<Service>, StorageOperationStatus> services = serviceOperation.getFollowed(userId, lifecycleStates, lastStateStates, false);
- if (services.isLeft()) {
- Map<String, List<? extends Component>> result = new HashMap<String, List<? extends Component>>();
- result.put("services", services.left().value());
- result.put("resources", resources.left().value());
- return Either.left(result);
+
+ try {
+ Either<List<Resource>, StorageOperationStatus> resources = toscaOperationFacade.getFollowed(userId, lifecycleStates, lastStateStates, ComponentTypeEnum.RESOURCE);
+
+ if (resources.isLeft()) {
+ Either<List<Service>, StorageOperationStatus> services = toscaOperationFacade.getFollowed(userId, lifecycleStates, lastStateStates, ComponentTypeEnum.SERVICE);
+ if (services.isLeft()) {
+ Map<String, List<? extends Component>> result = new HashMap<String, List<? extends Component>>();
+ result.put("services", services.left().value());
+ result.put("resources", resources.left().value());
+ return Either.left(result);
+ } else {
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(services.right().value())));
+ }
} else {
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(services.right().value())));
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resources.right().value())));
}
- } else {
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resources.right().value())));
+ } finally {
+ titanDao.commit();
}
}
private Either<Map<String, List<? extends Component>>, ResponseFormat> getFollowedProducts(String userId, Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates) {
- Either<List<Product>, StorageOperationStatus> products = productOperation.getFollowed(userId, lifecycleStates, lastStateStates, false);
+ Either<List<Product>, StorageOperationStatus> products = toscaOperationFacade.getFollowed(userId, lifecycleStates, lastStateStates, ComponentTypeEnum.PRODUCT);
if (products.isLeft()) {
Map<String, List<? extends Component>> result = new HashMap<String, List<? extends Component>>();
result.put("products", products.left().value());
@@ -393,10 +406,6 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
String origSubCategoryName = subCategoryName;
User user = new User();
- /*
- * if (userId == null) { user.setUserId("UNKNOWN"); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION); handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName,
- * auditingAction, componentType); return Either.right(responseFormat); }
- */
Either<User, ResponseFormat> validateUser = validateUserExists(userId, "createSubCategory", false);
if (validateUser.isRight()) {
log.debug("Validation of user failed, userId {}", userId);
@@ -720,6 +729,49 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
componentsUtils.auditGetCategoryHierarchy(auditingAction, user, componentType, responseFormat);
return Either.left(categories);
}
+
+ public Either<UiCategories, ResponseFormat> getAllCategories(String userId) {
+ AuditingActionEnum auditingAction = AuditingActionEnum.GET_CATEGORY_HIERARCHY;
+ ResponseFormat responseFormat;
+ UiCategories categories = new UiCategories();
+
+ Either<User, ResponseFormat> userResponse = validateUserExists(userId, "get all categories", false);
+
+ if (userResponse.isRight()) {
+ return Either.right(userResponse.right().value());
+ }
+ User user = userResponse.left().value();
+
+ //GET resource categories
+ Either<List<CategoryDefinition>, ActionStatus> getResourceCategoriesByType = elementOperation.getAllCategories(NodeTypeEnum.ResourceNewCategory, false);
+ if (getResourceCategoriesByType.isRight()) {
+ responseFormat = componentsUtils.getResponseFormat(getResourceCategoriesByType.right().value());
+ componentsUtils.auditGetCategoryHierarchy(auditingAction, user, ComponentTypeEnum.RESOURCE.getValue(), responseFormat);
+ return Either.right(responseFormat);
+ }
+ categories.setResourceCategories(getResourceCategoriesByType.left().value());
+
+ //GET service categories
+ Either<List<CategoryDefinition>, ActionStatus> getServiceCategoriesByType = elementOperation.getAllCategories(NodeTypeEnum.ServiceNewCategory, false);
+ if (getServiceCategoriesByType.isRight()) {
+ responseFormat = componentsUtils.getResponseFormat(getServiceCategoriesByType.right().value());
+ componentsUtils.auditGetCategoryHierarchy(auditingAction, user, ComponentTypeEnum.SERVICE.getValue(), responseFormat);
+ return Either.right(responseFormat);
+ }
+ categories.setServiceCategories(getServiceCategoriesByType.left().value());
+
+ //GET product categories
+ Either<List<CategoryDefinition>, ActionStatus> getProductCategoriesByType = elementOperation.getAllCategories(NodeTypeEnum.ProductCategory, false);
+ if (getProductCategoriesByType.isRight()) {
+ responseFormat = componentsUtils.getResponseFormat(getProductCategoriesByType.right().value());
+ componentsUtils.auditGetCategoryHierarchy(auditingAction, user, ComponentTypeEnum.PRODUCT.getValue(), responseFormat);
+ return Either.right(responseFormat);
+ }
+
+ categories.setProductCategories(getProductCategoriesByType.left().value());
+ return Either.left(categories);
+
+ }
public Either<CategoryDefinition, ResponseFormat> deleteCategory(String categoryId, String componentTypeParamName, String userId) {
@@ -800,7 +852,7 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
// validate user exists
if (userId == null) {
- log.debug("User id is null");
+ log.debug("UserId is null");
return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION));
}
@@ -938,19 +990,17 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
}
Map<String, List<? extends Component>> resMap = new HashMap<>();
- Either<List<Resource>, StorageOperationStatus> resResources = resourceOperation.getResourceCatalogData(false);
+ Either<List<Resource>, StorageOperationStatus> resResources = toscaOperationFacade.getCatalogComponents(ComponentTypeEnum.RESOURCE);
if (resResources.isLeft()) {
- Either<List<Service>, StorageOperationStatus> resServices = serviceOperation.getServiceCatalogData(false);
+ Either<List<Service>, StorageOperationStatus> resServices = toscaOperationFacade.getCatalogComponents(ComponentTypeEnum.SERVICE);
if (resServices.isLeft()) {
- Either<List<Product>, StorageOperationStatus> resProducts = productOperation.getProductCatalogData(false);
- if (resProducts.isLeft()) {
- resMap.put("resources", resResources.left().value());
- resMap.put("services", resServices.left().value());
- resMap.put("products", resProducts.left().value());
- return Either.left(resMap);
- } else {
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resProducts.right().value())));
- }
+ // Either<List<Product>, StorageOperationStatus> resProducts = productOperation.getProductCatalogData(false);
+ // if (resProducts.isLeft()) {
+ resMap.put("resources", resResources.left().value());
+ resMap.put("services", resServices.left().value());
+ resMap.put("products", new ArrayList<>());
+
+ return Either.left(resMap);
} else {
return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resServices.right().value())));
}
@@ -971,11 +1021,14 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
}
if (filters == null || filters.isEmpty()) {
- return getCatalogComponentsByAssetType(assetTypeEnum);
+ Either<List<Component>, StorageOperationStatus> componentsList = toscaOperationFacade.getCatalogComponents(assetTypeEnum);
+ if(componentsList.isRight()) {
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(componentsList.right().value())));
+ }
+ return Either.left(componentsList.left().value());
}
- ComponentOperation componentOperation = getComponentOperation(assetTypeEnum);
- Either<List<Component>, StorageOperationStatus> result = componentOperation.getFilteredComponents(filters, false);
+ Either<List<Component>, StorageOperationStatus> result = getFilteredComponents(filters, assetTypeEnum, false);
if (result.isRight()) {// category hierarchy mismatch or
// category/subCategory/distributionStatus not
@@ -990,46 +1043,51 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
return Either.left(result.left().value());
}
- public Either<List<? extends Component>, ResponseFormat> getCatalogComponentsByAssetType(ComponentTypeEnum assetTypeEnum) {
+ private Either<List<Component>, StorageOperationStatus> getFilteredComponents(Map<FilterKeyEnum, String> filters, ComponentTypeEnum assetType, boolean inTransaction) {
+ Either<List<Component>, StorageOperationStatus> assetResult = null;
+ if(assetType == ComponentTypeEnum.RESOURCE){
+
+ assetResult = getFilteredResouces(filters, inTransaction);
+
+ } else if (assetType == ComponentTypeEnum.SERVICE){
+
+ assetResult = getFilteredServices(filters, inTransaction);
+ }
+ return assetResult;
+ }
- if (assetTypeEnum == null) {
- log.debug("getCatalogComponentsByAssetType: Corresponding ComponentTypeEnum not found");
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
- }
+ private <T> Either<List<T>, StorageOperationStatus> getFilteredServices(Map<FilterKeyEnum, String> filters, boolean inTransaction) {
+
+ Either<List<T>, StorageOperationStatus> components = null;
- switch (assetTypeEnum) {
- case RESOURCE:
+ String categoryName = filters.get(FilterKeyEnum.CATEGORY);
+ String distributionStatus = filters.get(FilterKeyEnum.DISTRIBUTION_STATUS);
+ DistributionStatusEnum distEnum = DistributionStatusEnum.findState(distributionStatus);
+ if (distributionStatus != null && distEnum == null) {
+ filters.remove(FilterKeyEnum.CATEGORY);
+ return Either.right(StorageOperationStatus.CATEGORY_NOT_FOUND);
+ }
- Either<List<Resource>, StorageOperationStatus> resourceCatalogData = resourceOperation.getResourceCatalogDataVFLatestCertifiedAndNonCertified(false);
- if (resourceCatalogData.isLeft()) {
- log.debug("getCatalogComponentsByAssetType: Resource fetching successful");
- return Either.left(resourceCatalogData.left().value());
- } else {
- log.debug("getCatalogComponentsByAssetType: Resource fetching failed");
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceCatalogData.right().value())));
+ if (categoryName != null) { // primary filter
+ components = fetchByCategoryOrSubCategoryName(categoryName, NodeTypeEnum.ServiceNewCategory, GraphEdgeLabels.CATEGORY.getProperty(), NodeTypeEnum.Service, inTransaction, ServiceMetadataData.class, null);
+ if (components.isLeft() && distEnum != null) {// secondary filter
+ Predicate<T> statusFilter = p -> ((Service) p).getDistributionStatus().equals(distEnum);
+ return Either.left(components.left().value().stream().filter(statusFilter).collect(Collectors.toList()));
}
+ filters.remove(FilterKeyEnum.DISTRIBUTION_STATUS);
+ return components;
+ }
- case SERVICE:
- Either<List<Service>, StorageOperationStatus> serviceCatalogData = serviceOperation.getServiceCatalogDataLatestCertifiedAndNotCertified(false);
- if (serviceCatalogData.isLeft()) {
- log.debug("getCatalogComponentsByAssetType: Service fetching successful");
- return Either.left(serviceCatalogData.left().value());
- } else {
- log.debug("getCatalogComponentsByAssetType: Service fetching failed");
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceCatalogData.right().value())));
- }
- /*
- * case PRODUCT: Either<List<Product>, StorageOperationStatus> resCatalogData = productOperation.getProductCatalogData(false); if(resCatalogData.isLeft()){ log. debug("getCatalogComponentsByAssetType: Product fetching successful" );
- * return Either.left(resCatalogData.left().value()); }else { log. debug("getCatalogComponentsByAssetType: Product fetching failed" ); return Either.right(componentsUtils .getResponseFormat(componentsUtils.convertFromStorageResponse(
- * resCatalogData.right().value()))); }
- */
- default:
- log.debug("Invalid Asset Type");
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
+ Set<DistributionStatusEnum> distStatusSet = new HashSet<>();
+ distStatusSet.add(distEnum);
+ Either<List<Service>, StorageOperationStatus> servicesWithDistStatus = toscaOperationFacade.getServicesWithDistStatus(distStatusSet, null);
+ if (servicesWithDistStatus.isRight()) { // not found == empty list
+ return Either.left(new ArrayList<>());
}
+
+ return Either.left((List<T>)servicesWithDistStatus.left().value());
}
- // TODO new story Tal
public Either<List<? extends Component>, ResponseFormat> getCatalogComponentsByUuidAndAssetType(String assetType, String uuid) {
if (assetType == null || assetType == null) {
@@ -1044,40 +1102,15 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
}
- switch (assetTypeEnum) {
-
- case RESOURCE:
- Either<List<Resource>, StorageOperationStatus> resourceListByUuid = resourceOperation.getLatestResourceByUuid(uuid, false);
-
- if (resourceListByUuid.isLeft()) {
- log.debug("getCatalogComponentsByUuidAndAssetType: Resource fetching successful");
- return Either.left(resourceListByUuid.left().value());
- }
-
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(resourceListByUuid.right().value());
- log.debug("getCatalogComponentsByUuidAndAssetType: Resource fetching failed");
- return Either.right(componentsUtils.getResponseFormat(actionStatus));
-
- case SERVICE:
- Either<List<Service>, StorageOperationStatus> serviceCatalogData = serviceOperation.getLatestServiceByUuid(uuid, false);
-
- if (serviceCatalogData.isLeft()) {
- log.debug("getCatalogComponentsByUuidAndAssetType: Service fetching successful");
- return Either.left(serviceCatalogData.left().value());
- }
-
+ Either<List<Component>, StorageOperationStatus> componentsListByUuid = toscaOperationFacade.getComponentListByUuid(uuid, null);
+ if(componentsListByUuid.isRight()) {
log.debug("getCatalogComponentsByUuidAndAssetType: Service fetching failed");
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceCatalogData.right().value())));
- // case Product is for future US
- /*
- * case PRODUCT: Either<List<Product>, StorageOperationStatus> resCatalogData = productOperation.getProductCatalogData(false); if(resCatalogData.isLeft()){ log. debug("getCatalogComponentsByAssetType: Product fetching successful" ); return
- * Either.left(resCatalogData.left().value()); }else { log. debug("getCatalogComponentsByAssetType: Product fetching failed" ); return Either.right(componentsUtils .getResponseFormat(componentsUtils.convertFromStorageResponse(
- * resCatalogData.right().value()))); }
- */
- default:
- log.debug("Invalid Asset Type");
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(componentsListByUuid.right().value(), ComponentTypeEnum.SERVICE);
+ return Either.right(componentsUtils.getResponseFormat(actionStatus, uuid));
}
+
+ log.debug("getCatalogComponentsByUuidAndAssetType: " + assetTypeEnum.getValue() + "Service fetching successful");
+ return Either.left(componentsListByUuid.left().value());
}
public List<String> getAllComponentTypesParamNames() {
@@ -1121,5 +1154,228 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
}
return params;
}
+
+ public Either<List<Component>, StorageOperationStatus> getFilteredResouces(Map<FilterKeyEnum, String> filters, boolean inTransaction) {
+
+ String subCategoryName = filters.get(FilterKeyEnum.SUB_CATEGORY);
+ String categoryName = filters.get(FilterKeyEnum.CATEGORY);
+ ResourceTypeEnum resourceType = ResourceTypeEnum.getType( filters.get(FilterKeyEnum.RESOURCE_TYPE));
+ Either<List<ImmutablePair<SubCategoryData, GraphEdge>>, StorageOperationStatus> subcategories = null;
+ Optional<ImmutablePair<SubCategoryData, GraphEdge>> subCategoryData;
+
+ if (categoryName != null) {
+ subcategories = getAllSubCategories(categoryName);
+ if (subcategories.isRight()) {
+ filters.remove(FilterKeyEnum.SUB_CATEGORY);
+ return Either.right(subcategories.right().value());
+ }
+ }
+ if (subCategoryName != null) { // primary filter
+ if (categoryName != null) {
+ subCategoryData = validateCategoryHierarcy(subcategories.left().value(), subCategoryName);
+ if (!subCategoryData.isPresent()) {
+ return Either.right(StorageOperationStatus.MATCH_NOT_FOUND);
+ }
+ return fetchByCategoryOrSubCategoryUid((String) subCategoryData.get().getLeft().getUniqueId(), NodeTypeEnum.ResourceSubcategory, GraphEdgeLabels.SUB_CATEGORY.getProperty(), NodeTypeEnum.Resource, inTransaction,
+ ResourceMetadataData.class, resourceType);
+ }
+
+ return fetchByCategoryOrSubCategoryName(subCategoryName, NodeTypeEnum.ResourceSubcategory, GraphEdgeLabels.SUB_CATEGORY.getProperty(), NodeTypeEnum.Resource, inTransaction, ResourceMetadataData.class, resourceType);
+ }
+ if(subcategories != null){
+ return fetchByMainCategory(subcategories.left().value(), inTransaction, resourceType);
+ }
+ return fetchByResourceType(filters.get(FilterKeyEnum.RESOURCE_TYPE), inTransaction);
+ }
+
+ private Either<List<ImmutablePair<SubCategoryData, GraphEdge>>, StorageOperationStatus> getAllSubCategories(String categoryName) {
+ Either<CategoryData, StorageOperationStatus> categoryResult = elementOperation.getNewCategoryData(categoryName, NodeTypeEnum.ResourceNewCategory, CategoryData.class);
+ if (categoryResult.isRight()) {
+ return Either.right(categoryResult.right().value());
+ }
+ CategoryData categoryData = categoryResult.left().value();
+
+ Either<List<ImmutablePair<SubCategoryData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceNewCategory), (String) categoryData.getUniqueId(),
+ GraphEdgeLabels.SUB_CATEGORY, NodeTypeEnum.ResourceSubcategory, SubCategoryData.class);
+ if (childrenNodes.isRight()) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(childrenNodes.right().value()));
+ }
+ return Either.left(childrenNodes.left().value());
+ }
+
+ private Optional<ImmutablePair<SubCategoryData, GraphEdge>> validateCategoryHierarcy(List<ImmutablePair<SubCategoryData, GraphEdge>> childNodes, String subCategoryName) {
+ Predicate<ImmutablePair<SubCategoryData, GraphEdge>> matchName = p -> p.getLeft().getSubCategoryDataDefinition().getName().equals(subCategoryName);
+ return childNodes.stream().filter(matchName).findAny();
+ }
+
+ protected <T, S extends ComponentMetadataData> Either<List<T>, StorageOperationStatus> fetchByCategoryOrSubCategoryUid(String categoryUid, NodeTypeEnum categoryType, String categoryLabel, NodeTypeEnum neededType, boolean inTransaction,
+ Class<S> clazz, ResourceTypeEnum resourceType) {
+ try {
+ Either<TitanGraph, TitanOperationStatus> graph = titanDao.getGraph();
+ if (graph.isRight()) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graph.right().value()));
+
+ }
+ return collectComponents(graph.left().value(), neededType, categoryUid, categoryType, clazz, resourceType);
+
+ } finally {
+ if (false == inTransaction) {
+ titanDao.commit();
+ }
+ }
+ }
+
+ protected <T, S extends ComponentMetadataData> Either<List<T>, StorageOperationStatus> fetchByCategoryOrSubCategoryName(String categoryName, NodeTypeEnum categoryType, String categoryLabel, NodeTypeEnum neededType, boolean inTransaction,
+ Class<S> clazz, ResourceTypeEnum resourceType) {
+ List<T> components = new ArrayList<>();
+ try {
+ Class categoryClazz = categoryType == NodeTypeEnum.ServiceNewCategory ? CategoryData.class : SubCategoryData.class;
+ Map<String, Object> props = new HashMap<String, Object>();
+ props.put(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty(), ValidationUtils.normalizeCategoryName4Uniqueness(categoryName));
+ Either<List<GraphNode>, TitanOperationStatus> getCategory = titanGenericDao.getByCriteria(categoryType, props, categoryClazz);
+ if (getCategory.isRight()) {
+ return Either.right(StorageOperationStatus.CATEGORY_NOT_FOUND);
+ }
+ Either<TitanGraph, TitanOperationStatus> graph = titanDao.getGraph();
+ if (graph.isRight()) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graph.right().value()));
+
+ }
+ for (GraphNode category : getCategory.left().value()) {
+ Either<List<T>, StorageOperationStatus> result = collectComponents(graph.left().value(), neededType, (String) category.getUniqueId(), categoryType, clazz, resourceType);
+ if (result.isRight()) {
+ return result;
+ }
+ components.addAll(result.left().value());
+ }
+
+ return Either.left(components);
+ } finally {
+ if (false == inTransaction) {
+ titanDao.commit();
+ }
+ }
+ }
+
+ private <T, S extends ComponentMetadataData> Either<List<T>, StorageOperationStatus> collectComponents(TitanGraph graph, NodeTypeEnum neededType, String categoryUid, NodeTypeEnum categoryType, Class<S> clazz, ResourceTypeEnum resourceType) {
+ List<T> components = new ArrayList<>();
+ Either<List<ImmutablePair<S, GraphEdge>>, TitanOperationStatus> parentNodes = titanGenericDao.getParentNodes(UniqueIdBuilder.getKeyByNodeType(categoryType), categoryUid, GraphEdgeLabels.CATEGORY, neededType, clazz);
+ if (parentNodes.isLeft()) {
+ for (ImmutablePair<S, GraphEdge> component : parentNodes.left().value()) {
+ ComponentMetadataDataDefinition componentData = component.getLeft().getMetadataDataDefinition();
+ Boolean isHighest = componentData.isHighestVersion();
+ boolean isMatchingResourceType = isMatchingByResourceType(neededType, resourceType, componentData);
+
+ if (isHighest && isMatchingResourceType) {
+ Either<T, StorageOperationStatus> result = (Either<T, StorageOperationStatus>) toscaOperationFacade.getToscaElement(componentData.getUniqueId(), JsonParseFlagEnum.ParseMetadata);
+ if (result.isRight()) {
+ return Either.right(result.right().value());
+ }
+ components.add(result.left().value());
+ }
+ }
+ }
+ return Either.left(components);
+ }
+
+ private boolean isMatchingByResourceType(NodeTypeEnum componentType, ResourceTypeEnum resourceType,
+ ComponentMetadataDataDefinition componentData) {
+
+ boolean isMatching;
+ if (componentType == NodeTypeEnum.Resource) {
+ if (resourceType == null) {
+ isMatching = true;
+ } else {
+ isMatching = resourceType == ((ResourceMetadataDataDefinition)componentData).getResourceType();
+ }
+ } else {
+ isMatching = true;
+ }
+ return isMatching;
+ }
+
+ private <T> Either<List<T>, StorageOperationStatus> fetchByMainCategory(List<ImmutablePair<SubCategoryData, GraphEdge>> subcategories, boolean inTransaction, ResourceTypeEnum resourceType) {
+ List<T> components = new ArrayList<>();
+
+ for (ImmutablePair<SubCategoryData, GraphEdge> subCategory : subcategories) {
+ Either<List<T>, StorageOperationStatus> fetched = fetchByCategoryOrSubCategoryUid((String) subCategory.getLeft().getUniqueId(), NodeTypeEnum.ResourceSubcategory, GraphEdgeLabels.SUB_CATEGORY.getProperty(), NodeTypeEnum.Resource,
+ inTransaction, ResourceMetadataData.class, resourceType);
+ if (fetched.isRight()) {
+ // return fetched;
+ continue;
+ }
+ components.addAll(fetched.left().value());
+ }
+ return Either.left(components);
+ }
+
+ private Either<List<Component>, StorageOperationStatus> fetchByResourceType(String resourceType, boolean inTransaction) {
+ List<Component> components = null;
+ StorageOperationStatus status;
+ Wrapper<StorageOperationStatus> statusWrapper = new Wrapper<>();
+ Either<List<Component>, StorageOperationStatus> result;
+ try {
+
+ Either<List<Component>, StorageOperationStatus> getResources = toscaOperationFacade.fetchByResourceType(resourceType); //titanGenericDao.getByCriteria(nodeType, props, clazz);
+ if (getResources.isRight()) {
+ status = getResources.right().value();
+ if(status != StorageOperationStatus.NOT_FOUND){
+ statusWrapper.setInnerElement(getResources.right().value());
+ }else{
+ components = new ArrayList<>();
+ }
+ } else{
+ components = getResources.left().value();
+ }
+ if(!statusWrapper.isEmpty()){
+ result = Either.right(statusWrapper.getInnerElement());
+ }else{
+ result = Either.left(components);
+ }
+ return result;
+ } finally {
+ if (!inTransaction) {
+ titanDao.commit();
+ }
+ }
+ }
+
+ Component convertComponentMetadataDataToComponent(ComponentMetadataData componentMetadataData) {
+ return convertResourceDataToResource((ResourceMetadataData) componentMetadataData);
+ }
+ private Resource convertResourceDataToResource(ResourceMetadataData resourceData) {
+
+ ResourceMetadataDefinition resourceMetadataDataDefinition = new ResourceMetadataDefinition((ResourceMetadataDataDefinition) resourceData.getMetadataDataDefinition());
+
+ Resource resource = new Resource(resourceMetadataDataDefinition);
+
+ return resource;
+ }
+ private <T> Either<List<T>, StorageOperationStatus> fetchByDistributionStatus(String status, boolean inTransaction) {
+ Map<String, Object> props = new HashMap<String, Object>();
+ props.put(GraphPropertiesDictionary.DISTRIBUTION_STATUS.getProperty(), status);
+ props.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true);
+ return (Either<List<T>, StorageOperationStatus>) (Either<?, StorageOperationStatus>) getServiceListByCriteria(props, inTransaction);
+ }
+
+ private Either<List<Service>, StorageOperationStatus> getServiceListByCriteria(Map<String, Object> props, boolean inTransaction) {
+ props.put(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.Service.getName());
+ Either<List<ServiceMetadataData>, TitanOperationStatus> byCriteria = titanGenericDao.getByCriteria(NodeTypeEnum.Service, props, ServiceMetadataData.class);
+
+ if (byCriteria.isRight()) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(byCriteria.right().value()));
+ }
+ List<Service> services = new ArrayList<Service>();
+ List<ServiceMetadataData> servicesDataList = byCriteria.left().value();
+ for (ServiceMetadataData data : servicesDataList) {
+ Either<Component, StorageOperationStatus> service = toscaOperationFacade.getToscaElement(data.getMetadataDataDefinition().getUniqueId());
+ if (service.isLeft()) {
+ services.add((Service)service.left().value());
+ } else {
+ log.debug("Failed to fetch resource for name = {} and id = {}",data.getMetadataDataDefinition().getName(),data.getUniqueId());
+ }
+ }
+ return Either.left(services);
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogic.java
index 3b4528d3a3..ba08f11928 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogic.java
@@ -20,9 +20,11 @@
package org.openecomp.sdc.be.components.impl;
+import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
+import java.util.EnumMap;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
@@ -34,11 +36,21 @@ import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
+import org.apache.commons.collections.CollectionUtils;
+import org.apache.commons.collections.MapUtils;
import org.apache.commons.io.FilenameUtils;
+import org.apache.commons.lang.StringUtils;
+import org.apache.commons.lang3.math.NumberUtils;
+import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.codehaus.jackson.JsonGenerationException;
+import org.codehaus.jackson.map.JsonMappingException;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.jsongraph.utils.JsonParserUtils;
import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
+import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.info.ArtifactDefinitionInfo;
@@ -48,29 +60,42 @@ import org.openecomp.sdc.be.model.ArtifactDefinition;
import org.openecomp.sdc.be.model.Component;
import org.openecomp.sdc.be.model.ComponentInstance;
import org.openecomp.sdc.be.model.ComponentParametersView;
+import org.openecomp.sdc.be.model.DataTypeDefinition;
import org.openecomp.sdc.be.model.GroupDefinition;
+import org.openecomp.sdc.be.model.GroupInstance;
+import org.openecomp.sdc.be.model.GroupInstanceProperty;
import org.openecomp.sdc.be.model.GroupProperty;
import org.openecomp.sdc.be.model.GroupTypeDefinition;
+import org.openecomp.sdc.be.model.PropertyDefinition;
+import org.openecomp.sdc.be.model.PropertyDefinition.GroupInstancePropertyValueUpdateBehavior;
+import org.openecomp.sdc.be.model.PropertyDefinition.PropertyNames;
+import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
+import org.openecomp.sdc.be.model.jsontitan.operations.ArtifactsOperations;
+import org.openecomp.sdc.be.model.jsontitan.operations.GroupsOperation;
import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.be.model.operations.impl.ComponentOperation;
+import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
import org.openecomp.sdc.be.model.operations.impl.GroupOperation;
import org.openecomp.sdc.be.model.operations.impl.GroupTypeOperation;
-import org.openecomp.sdc.be.model.operations.impl.ResourceOperation;
import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.config.EcompErrorName;
import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.JsonSyntaxException;
import fj.data.Either;
@org.springframework.stereotype.Component("groupBusinessLogic")
public class GroupBusinessLogic extends BaseBusinessLogic {
+ private static String ADDING_GROUP = "AddingGroup";
- public static String INITIAL_VERSION = "1";
+ public static final String INITIAL_VERSION = "1";
private static final String CREATE_GROUP = "CreateGroup";
@@ -87,8 +112,15 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
@javax.annotation.Resource
private GroupTypeOperation groupTypeOperation;
- @javax.annotation.Resource
- private GroupOperation groupOperation;
+
+ @Autowired
+ ArtifactsOperations artifactsOperation;
+
+ @Autowired
+ private GroupsOperation groupsOperation;
+ @Autowired
+ private ApplicationDataTypeCache dataTypeCache;
+
/**
*
@@ -113,7 +145,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
* @param inTransaction
* @return
*/
- public Either<GroupDefinition, ResponseFormat> createGroup(String componentId, String userId, ComponentTypeEnum componentType, GroupDefinition groupDefinition, boolean inTransaction) {
+ /*public Either<GroupDefinition, ResponseFormat> createGroup(String componentId, String userId, ComponentTypeEnum componentType, GroupDefinition groupDefinition, boolean inTransaction) {
Either<GroupDefinition, ResponseFormat> result = null;
@@ -142,7 +174,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
componentParametersView.setIgnoreUsers(false);
componentParametersView.setIgnoreComponentInstances(false);
- Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(realComponentId, componentType, componentParametersView, userId, null, user);
+ Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(realComponentId, componentType, componentParametersView);
if (validateComponent.isRight()) {
result = Either.right(validateComponent.right().value());
@@ -164,16 +196,16 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
if (result == null || result.isRight()) {
log.debug("Going to execute rollback on create group.");
- titanGenericDao.rollback();
+ titanDao.rollback();
} else {
log.debug("Going to execute commit on create group.");
- titanGenericDao.commit();
+ titanDao.commit();
}
}
}
- }
+ }*/
private String getComponentTypeForResponse(org.openecomp.sdc.be.model.Component component) {
String componentTypeForResponse = "SERVICE";
@@ -203,7 +235,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
}
List<String> currentArtifacts = deploymentArtifacts.values().stream().map(p -> p.getUniqueId()).collect(Collectors.toList());
- log.debug("The deployment artifacts of component {} are {}", component.getNormalizedName(), deploymentArtifacts);
+ log.debug("The deployment artifacts of component {} are {}" , component.getNormalizedName(), deploymentArtifacts);
if (false == currentArtifacts.containsAll(artifacts)) {
BeEcompErrorManager.getInstance().logInvalidInputError(context, "Not all artifacts belongs to component " + component.getNormalizedName(), ErrorSeverity.INFO);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
@@ -214,43 +246,6 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
}
/**
- * Verify that the artifact members belongs to the component
- *
- * @param component
- * @param artifacts
- * @return
- */
- private Either<List<ArtifactDefinition>, ResponseFormat> getArtifactsBelongsToComponent(Component component, List<String> artifacts, String context) {
-
- /*
- * if (artifacts == null || true == artifacts.isEmpty()) { return Either.left(true); }
- */
-
- Map<String, ArtifactDefinition> deploymentArtifacts = component.getDeploymentArtifacts();
- if (deploymentArtifacts == null || true == deploymentArtifacts.isEmpty()) {
- BeEcompErrorManager.getInstance().logInvalidInputError(context, "No deployment artifact found under component " + component.getNormalizedName(), ErrorSeverity.INFO);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
- }
- List<ArtifactDefinition> resultList = new ArrayList();
-
- for (String artifactId : artifacts) {
- Optional<ArtifactDefinition> groupArtifactOp = deploymentArtifacts.values().stream().filter(p -> p.getUniqueId().equals(artifactId)).findAny();
-
- if (groupArtifactOp.isPresent()) {
- ArtifactDefinition groupArtifact = groupArtifactOp.get();
- resultList.add(groupArtifact);
- } else {
- BeEcompErrorManager.getInstance().logInvalidInputError(context, "Not all artifacts belongs to component " + component.getNormalizedName(), ErrorSeverity.INFO);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
-
- }
- }
-
- return Either.left(resultList);
-
- }
-
- /**
* verify that the members are component instances of the component
*
* @param component
@@ -290,67 +285,54 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
}
}
- ComponentOperation componentOperation = getComponentOperationByParentComponentType(componentType);
- if (componentOperation instanceof ResourceOperation) {
- ResourceOperation resourceOperation = (ResourceOperation) componentOperation;
-
- for (Entry<String, String> groupMember : groupMembers.entrySet()) {
-
- String componentInstName = groupMember.getKey();
- String componentInstUid = groupMember.getValue();
-
- ComponentInstance componentInstance = compInstUidToCompInstMap.get(componentInstUid);
- String componentUid = componentInstance.getComponentUid();
- List<String> componentToscaNames = new ArrayList<>();
- TitanOperationStatus status = resourceOperation.fillResourceDerivedListFromGraph(componentUid, componentToscaNames);
- if (status != TitanOperationStatus.OK) {
- BeEcompErrorManager.getInstance().logInternalFlowError(CREATE_GROUP, "Cannot find tosca list of component id " + componentUid, ErrorSeverity.ERROR);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
-
- log.debug("The tosca names of component id {} are {}", componentUid, memberToscaTypes);
-
- boolean found = false;
- for (String memberToscaType : memberToscaTypes) {
- if (componentToscaNames.contains(memberToscaType)) {
- found = true;
- break;
- }
- }
- if (found == false) {
- BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_GROUP,
- "No tosca types from " + memberToscaTypes + " can be found in the tosca list " + componentToscaNames + " of component " + componentInstance.getNormalizedName(), ErrorSeverity.INFO);
- /*
- * # %1 - member name # %2 - group name # %3 - group type
- */
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_INVALID_TOSCA_NAME_OF_COMPONENT_INSTANCE, componentInstName, groupName, groupType));
- } else {
- log.debug("Component instance {} fits to one of the required tosca types", componentInstance.getNormalizedName());
- }
- }
- } else {
- BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_GROUP, "Cannot find tosca list since it is not supported for product", ErrorSeverity.ERROR);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
+// ComponentOperation componentOperation = getComponentOperationByParentComponentType(componentType);
+// if (componentOperation instanceof ResourceOperation) {
+// ResourceOperation resourceOperation = (ResourceOperation) componentOperation;
+//
+// for (Entry<String, String> groupMember : groupMembers.entrySet()) {
+//
+// String componentInstName = groupMember.getKey();
+// String componentInstUid = groupMember.getValue();
+//
+// ComponentInstance componentInstance = compInstUidToCompInstMap.get(componentInstUid);
+// String componentUid = componentInstance.getComponentUid();
+// List<String> componentToscaNames = new ArrayList<>();
+// TitanOperationStatus status = resourceOperation.fillResourceDerivedListFromGraph(componentUid, componentToscaNames);
+// if (status != TitanOperationStatus.OK) {
+// BeEcompErrorManager.getInstance().logInternalFlowError(CREATE_GROUP, "Cannot find tosca list of component id " + componentUid, ErrorSeverity.ERROR);
+// return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+// }
+//
+// log.debug("The tosca names of component id {} are {}", componentUid, memberToscaTypes);
+//
+// boolean found = false;
+// for (String memberToscaType : memberToscaTypes) {
+// if (componentToscaNames.contains(memberToscaType)) {
+// found = true;
+// break;
+// }
+// }
+// if (found == false) {
+// BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_GROUP,
+// "No tosca types from " + memberToscaTypes + " can be found in the tosca list " + componentToscaNames + " of component " + componentInstance.getNormalizedName(), ErrorSeverity.INFO);
+// /*
+// * # %1 - member name # %2 - group name # %3 - group type
+// */
+// return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_INVALID_TOSCA_NAME_OF_COMPONENT_INSTANCE, componentInstName, groupName, groupType));
+// } else {
+// log.debug("Component instance {} fits to one of the required tosca types", componentInstance.getNormalizedName());
+// }
+// }
+// } else {
+// BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_GROUP, "Cannot find tosca list since it is not supported for product", ErrorSeverity.ERROR);
+// return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+// }
}
return Either.left(true);
}
- public ComponentOperation getComponentOperation(NodeTypeEnum componentType) {
-
- switch (componentType) {
- case Service:
- case ResourceInstance:
- return serviceOperation;
- case Resource:
- return resourceOperation;
- default:
- return null;
- }
- }
-
/**
* Update specific group version
*
@@ -358,7 +340,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
* @param inTransaction
* @return
*/
- public Either<GroupDefinition, StorageOperationStatus> updateGroupVersion(GroupDefinition groupDefinition, boolean inTransaction) {
+ /*public Either<GroupDefinition, StorageOperationStatus> updateGroupVersion(GroupDefinition groupDefinition, boolean inTransaction) {
Either<GroupDefinition, StorageOperationStatus> result = null;
List<String> groupIdsToUpdateVersion = new ArrayList<>();
groupIdsToUpdateVersion.add(groupDefinition.getUniqueId());
@@ -370,7 +352,9 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
result = Either.right(updateGroupVersion.right().value());
}
return result;
- }
+ }*/
+
+
/**
* Update list of groups versions
@@ -379,7 +363,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
* @param inTransaction
* @return
*/
- public Either<List<GroupDefinition>, StorageOperationStatus> updateGroupVersion(List<String> groupsUniqueId, boolean inTransaction) {
+ /*public Either<List<GroupDefinition>, StorageOperationStatus> updateGroupVersion(List<String> groupsUniqueId, boolean inTransaction) {
Either<List<GroupDefinition>, StorageOperationStatus> result = null;
@@ -395,93 +379,396 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
if (result == null || result.isRight()) {
log.debug("Going to execute rollback on create group.");
- titanGenericDao.rollback();
+ titanDao.rollback();
} else {
log.debug("Going to execute commit on create group.");
- titanGenericDao.commit();
+ titanDao.commit();
}
}
}
+ }*/
+
+/**
+ * Update GroupDefinition metadata
+ * @param componentId
+ * @param user
+ * @param componentType
+ * @param updatedGroup
+ * @param inTransaction
+ * @return
+ */
+ public Either<GroupDefinition, ResponseFormat> validateAndUpdateGroupMetadata(
+ String componentId,
+ User user,
+ ComponentTypeEnum componentType,
+ GroupDefinition updatedGroup,
+ boolean inTransaction) {
+
+ Either<GroupDefinition, ResponseFormat> result = null;
+ try{
+ // Validate user exist
+ Either<User, ResponseFormat> validateUserExists = validateUserExists(user.getUserId(), UPDATE_GROUP, inTransaction);
+ if (validateUserExists.isRight()) {
+ result = Either.right(validateUserExists.right().value());
+ return result;
+ }
+ // Validate component exist
+ Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(componentId, componentType, null);
+ if (validateComponent.isRight()) {
+ result = Either.right(validateComponent.right().value());
+ return result;
+ }
+ org.openecomp.sdc.be.model.Component component = validateComponent.left().value();
+ // validate we can work on component
+ Either<Boolean, ResponseFormat> canWork = validateCanWorkOnComponent(component, user.getUserId());
+ if (canWork.isRight()) {
+ result = Either.right(canWork.right().value());
+ return result;
+ }
+ List<GroupDefinition> currentGroups = component.getGroups();
+ if(CollectionUtils.isEmpty(currentGroups)){
+ log.error("Failed to update the metadata of group {} on component {}. The status is {}. ", updatedGroup.getName(), component.getName(), ActionStatus.GROUP_IS_MISSING);
+ result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, updatedGroup.getName(), component.getName(), component.getComponentType().getValue()));
+ return result;
+ }
+ // Validate groups exists in the component
+ Optional<GroupDefinition> currentGroupOpt = currentGroups.stream().filter(g -> g.getUniqueId().equals(updatedGroup.getUniqueId())).findAny();
+ if(!currentGroupOpt.isPresent()){
+ log.error("Failed to update the metadata of group {} on component {}. The status is {}. ", updatedGroup.getName(), component.getName(), ActionStatus.GROUP_IS_MISSING);
+ result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, updatedGroup.getName(), component.getName(), component.getComponentType().getValue()));
+ return result;
+ }
+ GroupDefinition currentGroup = currentGroupOpt.get();
+ Either<Boolean, ResponseFormat> lockResult = lockComponent(componentId, component, "Update GroupDefinition Metadata");
+ if (lockResult.isRight()) {
+ result = Either.right(lockResult.right().value());
+ return result;
+ }
+ // Validate group type is vfModule
+ if (!currentGroup.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)) {
+ log.error("Failed to update the metadata of group {}. Group type is {} and different then: {}", currentGroup.getName(), currentGroup.getType(), Constants.DEFAULT_GROUP_VF_MODULE);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_VF_MODULE_TYPE, updatedGroup.getType());
+ result = Either.right(responseFormat);
+ return result;
+ }
+ result = updateGroupMetadata(component, currentGroup, updatedGroup);
+ return result;
+
+ } finally {
+ if(result.isLeft()){
+ titanDao.commit();
+ } else {
+ titanDao.rollback();
+ }
+ graphLockOperation.unlockComponent(componentId, componentType.getNodeType());
+ }
+ }
+
+ private Either<GroupDefinition, ResponseFormat> updateGroupMetadata(Component component, GroupDefinition currentGroup, GroupDefinition updatedGroup) {
+ String currentGroupName = currentGroup.getName();
+ Either<GroupDefinition, ResponseFormat> result = validateAndUpdateGroupMetadata(currentGroup, updatedGroup);
+
+ if(result.isRight()){
+ log.debug("Failed to validate a metadata of the group {} on component {}. ", updatedGroup.getName(), component.getName());
+ }
+ if(result.isLeft()){
+ result = updateGroup(component, currentGroup, currentGroupName);
+ }
+ return result;
+ }
+
+ private Either<GroupDefinition, ResponseFormat> updateGroup(Component component, GroupDefinition updatedGroup, String currentGroupName) {
+ Either<GroupDefinition, StorageOperationStatus> handleGroupRes;
+ Either<GroupDefinition, ResponseFormat> result = null;
+ if(updatedGroup.getName().equals(currentGroupName)){
+ handleGroupRes = groupsOperation.updateGroup(component, updatedGroup);
+ if(handleGroupRes.isRight()){
+ log.debug("Failed to update a metadata of the group {} on component {}. ", updatedGroup.getName(), component.getName());
+ result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(handleGroupRes.right().value())));
+ }
+ } else {
+ StorageOperationStatus deleteStatus = groupsOperation.deleteGroup(component, currentGroupName);
+ if(deleteStatus != StorageOperationStatus.OK){
+ log.debug("Failed to delete the group {} from component {}. ", updatedGroup.getName(), component.getName());
+ result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteStatus)));
+ }
+ handleGroupRes = groupsOperation.addGroup(component, updatedGroup);
+ if(handleGroupRes.isRight()){
+ log.debug("Failed to add the group {} to component {}. ", updatedGroup.getName(), component.getName());
+ result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(handleGroupRes.right().value())));
+ }
+ }
+ if(result == null){
+ result = Either.left(updatedGroup);
+ }
+ return result;
}
/**
- * Update GroupDefinition metadata
- *
+ * Validate and Update Group Property
* @param componentId
+ * @param groupUniqueId
* @param user
- * @param groupId
* @param componentType
- * @param groupUpdate
+ * @param groupPropertiesToUpdate
* @param inTransaction
* @return
*/
- public Either<GroupDefinition, ResponseFormat> updateGroupMetadata(String componentId, User user, String groupUniqueId, ComponentTypeEnum componentType, GroupDefinition groupUpdate, boolean inTransaction) {
-
- Either<GroupDefinition, ResponseFormat> result = null;
+ public Either<List<GroupProperty>, ResponseFormat> validateAndUpdateGroupProperties(
+ String componentId,
+ String groupUniqueId,
+ User user,
+ ComponentTypeEnum componentType,
+ List<GroupProperty> groupPropertiesToUpdate, boolean inTransaction) {
+
+ Either<List<GroupProperty>, ResponseFormat> result = Either.left(groupPropertiesToUpdate);
+ try{
+ Optional<GroupDefinition> optionalGroupConnectedToVf = null;
+ GroupDefinition currentGroup = null;
+ StorageOperationStatus lockResult = graphLockOperation.lockComponent(componentId, componentType.getNodeType());
+ if( lockResult != StorageOperationStatus.OK ){
+ result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(
+ lockResult, componentType), componentId));
+ }
+ if( result.isLeft() ){
+ //VF exist because lock succedded
+ Resource vf = (Resource) toscaOperationFacade.getToscaElement(componentId).left().value();
+ optionalGroupConnectedToVf =
+ //All groups on resource
+ vf.getGroups().stream().
+ //Filter in group sent is part of VF groups
+ filter( e -> e.getUniqueId().equals(groupUniqueId)).
+ //Collect
+ findAny();
+ if( !optionalGroupConnectedToVf.isPresent() ){
+ result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING,
+ groupUniqueId, vf.getName(), ComponentTypeEnum.RESOURCE.getValue()));
+ }
+ }
+
+ if( result.isLeft() ){
+ currentGroup = optionalGroupConnectedToVf.get();
+ result = validateGroupPropertyAndResetEmptyValue(currentGroup, groupPropertiesToUpdate);
+ }
+ if( result.isLeft() ){
+ result = updateGroupPropertiesValue(componentId, currentGroup, groupPropertiesToUpdate, inTransaction);
+ if (result.isRight()) {
+ BeEcompErrorManager.getInstance().logBeSystemError("Update GroupProperties");
+ log.debug("failed to update Vf {}", componentId);
+ }
+ }
- // Validate user and validate group belongs to component
- List<GroupDefinition> groups = new ArrayList<>();
- groups.add(groupUpdate);
- Either<Component, ResponseFormat> validateGroupsBeforeUpdate = validateGroupsBeforeUpdate(componentId, user.getUserId(), componentType, groups, inTransaction);
- if (validateGroupsBeforeUpdate.isRight()) {
- result = Either.right(validateGroupsBeforeUpdate.right().value());
- return result;
}
- Component component = validateGroupsBeforeUpdate.left().value();
+ catch(Exception e){
+ log.debug("Error in validateAndUpdateGroupProperty {}", e);
+ result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ finally{
+ graphLockOperation.unlockComponent(componentId, componentType.getNodeType());
+ }
+ return result;
+ }
+ private void resetEmptyValueWithDefaults(List<GroupProperty> groupPropertiesToUpdate, GroupDefinition originalGroup) {
+ Map<String, GroupProperty> originalProperties =
+ //Stream of original properties from group
+ originalGroup.convertToGroupProperties().stream().
+ //Collecting to map with name as key
+ collect(Collectors.toMap(e -> e.getName(), e -> e));
+ for( GroupProperty gp : groupPropertiesToUpdate){
+ if( StringUtils.isEmpty(gp.getValue())){
+ gp.setValue(originalProperties.get(gp.getName()).getDefaultValue());
+ }
+ }
+
+ }
- // Get the GroupDefinition object
- Either<GroupDefinition, StorageOperationStatus> groupStatus = groupOperation.getGroup(groupUniqueId);
- if (groupStatus.isRight()) {
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(groupStatus.right().value(), ComponentTypeEnum.SERVICE), ""));
+ private Either<List<GroupProperty>, ResponseFormat> validateGroupPropertyAndResetEmptyValue(
+ GroupDefinition originalGroup, List<GroupProperty> groupPropertiesToUpdate) {
+
+ Either<List<GroupProperty>, ResponseFormat> ret = validateOnlyValueChanged(groupPropertiesToUpdate, originalGroup);
+ if (ret.isLeft()) {
+ resetEmptyValueWithDefaults(groupPropertiesToUpdate, originalGroup);
}
- GroupDefinition currentGroup = groupStatus.left().value();
+ if (ret.isLeft()) {
+ // Validate Type Match Value
+ Optional<StorageOperationStatus> optionalError =
+ //Stream of group properties
+ groupPropertiesToUpdate.stream().
+ //Validate each and map to returned Strorage status value
+ map( e -> groupOperation .validateAndUpdatePropertyValue(e)).
+ //Keep only failed result if there is such
+ filter( e -> e != StorageOperationStatus.OK).
+ //collect
+ findFirst();
+ if( optionalError.isPresent()){
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(optionalError.get());
+ ret = Either.right(componentsUtils.getResponseFormat(actionStatus));
+ }
- // Validate group type is vfModule
- if (!currentGroup.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)) {
- log.error("Group update metadata: Group type is different then: {}", Constants.DEFAULT_GROUP_VF_MODULE);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_VF_MODULE_TYPE, groupUpdate.getType());
- return Either.right(responseFormat);
}
+ if (ret.isLeft()) {
+ // Validate min max ect...
+ ret = validatePropertyBusinessLogic(groupPropertiesToUpdate, originalGroup);
+ }
- Either<GroupDefinition, ResponseFormat> validationRsponse = validateAndUpdateGroupMetadata(currentGroup, groupUpdate);
- if (validationRsponse.isRight()) {
- log.info("Group update metadata: validations field.");
- return validationRsponse;
+ return ret;
+ }
+ private Either<List<GroupProperty>, ResponseFormat> validatePropertyBusinessLogic(
+ List<GroupProperty> groupPropertiesToUpdate, GroupDefinition originalGroup) {
+
+ Either<List<GroupProperty>, ResponseFormat> ret = Either.left(groupPropertiesToUpdate);
+
+ Map<PropertyNames, String> nameValueMap = new HashMap<>();
+ for(GroupProperty gp : groupPropertiesToUpdate){
+ //Filter out non special properties which does not have Enum
+ final PropertyNames gpEnum = PropertyNames.findName(gp.getName());
+ if( gpEnum != null ){
+ nameValueMap.put(gpEnum, gp.getValue());
+ }
+ }
+
+ if ( !MapUtils.isEmpty(nameValueMap) ) {
+
+ if (nameValueMap.containsKey(PropertyNames.INITIAL_COUNT) || nameValueMap.containsKey(PropertyNames.MAX_INSTANCES)
+ || nameValueMap.containsKey(PropertyNames.MIN_INSTANCES)) {
+
+
+ Map<PropertyNames, String> oldValueMap = prepareMapWithOriginalProperties(originalGroup);
+
+ Either<Boolean, ResponseFormat> eitherValid = validateMinMaxAndInitialCountPropertyLogicVF(nameValueMap,
+ oldValueMap);
+ if (eitherValid.isRight()) {
+ ret = Either.right(eitherValid.right().value());
+ }
+ }
+ if (ret.isLeft() && (nameValueMap.containsKey(PropertyNames.VF_MODULE_DESCRIPTION)
+ || nameValueMap.containsKey(PropertyNames.VF_MODULE_LABEL))) {
+
+ Optional<ResponseFormat> optionalError =
+ //Stream of group Properties
+ groupPropertiesToUpdate.stream().
+ //Filter in only properties that needs text validation
+ filter(e -> enumHasValueFilter(e.getName(),
+ enumName -> PropertyNames.findName(enumName),
+ PropertyNames.VF_MODULE_DESCRIPTION, PropertyNames.VF_MODULE_LABEL)).
+ //validate text properties
+ map( e -> validateFreeText(e)).
+ //filter in only errors if exist
+ filter( e -> e.isRight()).
+ //map the Either value to the Error
+ map( e -> e.right().value())
+ //collect
+ .findFirst();
+ if( optionalError.isPresent() ){
+ ret = Either.right(optionalError.get());
+ }
+
+ }
}
- GroupDefinition groupToUpdate = validationRsponse.left().value();
- // lock resource
- Either<Boolean, ResponseFormat> lockResult = lockComponent(componentId, component, "Update GroupDefinition Metadata");
- if (lockResult.isRight()) {
- return Either.right(lockResult.right().value());
+ return ret;
+ }
+
+ private Map<PropertyNames, String> prepareMapWithOriginalProperties(GroupDefinition originalGroup) {
+ Map<PropertyNames, String> oldValueMap = new HashMap<>();
+ PropertyNames[] propertiesToCheck = new PropertyNames[] { PropertyNames.INITIAL_COUNT,
+ PropertyNames.MAX_INSTANCES, PropertyNames.MIN_INSTANCES };
+
+ for(GroupProperty gp : originalGroup.convertToGroupProperties()){
+ if( enumHasValueFilter(gp.getName(), enumName -> PropertyNames.findName(enumName), propertiesToCheck)){
+ oldValueMap.put(PropertyNames.findName(gp.getName()), gp.getValue());
+ }
}
- try {
- Either<GroupDefinition, StorageOperationStatus> updateResponse = groupOperation.updateGroupName(groupUniqueId, groupUpdate.getName(), inTransaction);
- if (updateResponse.isRight()) {
- titanGenericDao.rollback();
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Update GroupDefinition Metadata");
- BeEcompErrorManager.getInstance().logBeSystemError("Update GroupDefinition Metadata");
- log.debug("failed to update sevice {}", groupToUpdate.getUniqueId());
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- titanGenericDao.commit();
- return Either.left(updateResponse.left().value());
- } finally {
- graphLockOperation.unlockComponent(componentId, componentType.getNodeType());
+ if( StringUtils.isEmpty(oldValueMap.get(PropertyNames.MAX_INSTANCES)) ){
+ oldValueMap.put(PropertyNames.MAX_INSTANCES, String.valueOf(Integer.MAX_VALUE));
+ }
+ return oldValueMap;
+ }
+
+ private Either<List<GroupProperty>, ResponseFormat> validateOnlyValueChanged(
+ List<GroupProperty> groupPropertiesToUpdate, GroupDefinition originalGroup) {
+
+ Either<List<GroupProperty>, ResponseFormat> ret = Either.left(groupPropertiesToUpdate);
+ if( CollectionUtils.isEmpty(groupPropertiesToUpdate) ){
+ ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, StringUtils.EMPTY));
+ }
+ else if (CollectionUtils.isEmpty(originalGroup.getProperties())) {
+ ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND,
+ groupPropertiesToUpdate.get(NumberUtils.INTEGER_ZERO).getName()));
+ } else {
+ Map<String, GroupProperty> namePropertyMap =
+ //Original Group Properties Stream
+ originalGroup.convertToGroupProperties().stream().
+ //Collect to map with name as key
+ collect(Collectors.toMap(e -> e.getName(), e -> e));
+
+ Optional<GroupProperty> optionalMissingProperty =
+ //Group Properties to be updated Stream
+ groupPropertiesToUpdate.stream().
+ //Filter in property that is not contained in original if there is such
+ filter(e -> !namePropertyMap.containsKey(e.getName())).
+ //collect
+ findFirst();
+
+ if (optionalMissingProperty.isPresent()) {
+ ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND,
+ optionalMissingProperty.get().getName()));
+ }
+ else{
+ Optional<GroupProperty> optionalNonValueChange =
+ //groups to be updated stream
+ groupPropertiesToUpdate.stream().
+ //filter in only properties with non-value (illegal) change
+ filter( e -> !isOnlyGroupPropertyValueChanged(e, namePropertyMap.get(e.getName()))).
+ //Collect
+ findFirst();
+ if (optionalNonValueChange.isPresent()) {
+ ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY,
+ optionalNonValueChange.get().getName()));
+
+ }
+ }
+
}
+ return ret;
}
/**
+ * if groupProperty are the same or if only value is different returns true, otherwise returns false.
+ * @param groupProperty
+ * @param groupProperty2
+ * @return
+ */
+ private boolean isOnlyGroupPropertyValueChanged(GroupProperty groupProperty, GroupProperty groupProperty2) {
+ //Create 2 duplicates for groupPropery and reset their values
+ Gson gson = new GsonBuilder().setPrettyPrinting().create();
+ try {
+ GroupProperty groupPropertyDuplicate = new GroupProperty(groupProperty);
+ groupPropertyDuplicate.setValue(null);
+ groupPropertyDuplicate.setSchema(null);
+ groupPropertyDuplicate.setParentUniqueId(null);
+// GroupProperty groupProperty2Duplicate = gson.fromJson(JsonParserUtils.jsonToString(groupProperty2), GroupProperty.class);
+ GroupProperty groupProperty2Duplicate = new GroupProperty(groupProperty2);
+ groupProperty2Duplicate.setValue(null);
+ groupProperty2Duplicate.setSchema(null);
+ groupProperty2Duplicate.setParentUniqueId(null);
+ return groupPropertyDuplicate.equals(groupProperty2Duplicate) && StringUtils.equals(groupPropertyDuplicate.getValueUniqueUid(), groupProperty2Duplicate.getValueUniqueUid());
+ } catch (Exception e) {
+ log.debug("Failed validate group properties. ", e);
+ return false;
+ }
+ }
+ /**
* Validate and update GroupDefinition metadata
*
* @param user
* @param currentGroup
* @param groupUpdate
* @return
- */
+ **/
private Either<GroupDefinition, ResponseFormat> validateAndUpdateGroupMetadata(GroupDefinition currentGroup, GroupDefinition groupUpdate) {
// Check if to update, and update GroupDefinition name.
Either<Boolean, ResponseFormat> response = validateAndUpdateGroupName(currentGroup, groupUpdate);
@@ -577,7 +864,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
* @param inTransaction
* @return
*/
- public Either<List<GroupDefinition>, ResponseFormat> associateArtifactsToGroup(String componentId, String userId, ComponentTypeEnum componentType, List<GroupDefinition> groups, boolean shouldLockComp, boolean inTransaction) {
+ /*public Either<List<GroupDefinition>, ResponseFormat> associateArtifactsToGroup(String componentId, String userId, ComponentTypeEnum componentType, List<GroupDefinition> groups, boolean shouldLockComp, boolean inTransaction) {
Either<List<GroupDefinition>, ResponseFormat> result = null;
@@ -634,7 +921,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
boolean isChanged = componentArtifacts.removeAll(artifactsToAssociate);
if (isChanged) {// I.e. At least one artifact is already
// associated to the group
- log.debug("Some of the artifacts already associated to group {}", groupDefinition.getUniqueId());
+ log.debug("Some of the artifacts already associated to group {}" , groupDefinition.getUniqueId());
return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_ARTIFACT_ALREADY_ASSOCIATED, componentGroup.getName()));
}
}
@@ -661,10 +948,10 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
if (result == null || result.isRight()) {
log.debug("Going to execute rollback on create group.");
- titanGenericDao.rollback();
+ titanDao.rollback();
} else {
log.debug("Going to execute commit on create group.");
- titanGenericDao.commit();
+ titanDao.commit();
}
}
@@ -675,9 +962,9 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
}
}
- }
+ }*/
- public Either<List<GroupDefinition>, ResponseFormat> associateMembersToGroup(String componentId, String userId, ComponentTypeEnum componentType, List<GroupDefinition> groups, boolean shouldLockComp, boolean inTransaction) {
+ /*public Either<List<GroupDefinition>, ResponseFormat> associateMembersToGroup(String componentId, String userId, ComponentTypeEnum componentType, List<GroupDefinition> groups, boolean shouldLockComp, boolean inTransaction) {
Either<List<GroupDefinition>, ResponseFormat> result = null;
@@ -739,10 +1026,10 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
if (result == null || result.isRight()) {
log.debug("Going to execute rollback on create group.");
- titanGenericDao.rollback();
+ titanDao.rollback();
} else {
log.debug("Going to execute commit on create group.");
- titanGenericDao.commit();
+ titanDao.commit();
}
}
@@ -753,7 +1040,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
}
}
- }
+ }*/
/**
* associate artifacts to a given group
@@ -778,8 +1065,6 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
return result;
}
- User user = validateUserExists.left().value();
-
// Validate component exist
org.openecomp.sdc.be.model.Component component = null;
String realComponentId = componentId;
@@ -790,85 +1075,88 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
componentParametersView.setIgnoreGroups(false);
componentParametersView.setIgnoreArtifacts(false);
componentParametersView.setIgnoreUsers(false);
- componentParametersView.setIgnoreComponentInstances(false);
- Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(realComponentId, componentType, componentParametersView, userId, null, user);
+ Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(realComponentId, componentType, componentParametersView);
if (validateComponent.isRight()) {
result = Either.right(validateComponent.right().value());
return result;
}
component = validateComponent.left().value();
- // validate we can work on component
- /*
- * Either<Boolean, ResponseFormat> canWork = validateCanWorkOnComponent( component, userId); if (canWork.isRight()) { result = Either.right(canWork.right().value()); return result; }
- */
- List<GroupDefinition> groups = component.getGroups();
- Optional<GroupDefinition> findAny = groups.stream().filter(p -> p.getUniqueId().equals(groupId)).findAny();
- if (findAny.isPresent()) {
- GroupDefinition group = findAny.get();
- Boolean isBase = null;// Constants.IS_BASE;
- List<GroupProperty> props = group.getProperties();
- if (props != null && !props.isEmpty()) {
- Optional<GroupProperty> isBasePropOp = props.stream().filter(p -> p.getName().equals(Constants.IS_BASE)).findAny();
- if (isBasePropOp.isPresent()) {
- GroupProperty propIsBase = isBasePropOp.get();
- isBase = Boolean.parseBoolean(propIsBase.getValue());
+ Either<GroupDefinition, StorageOperationStatus> groupEither = findGroupOnComponent(component, groupId);
+
+ if (groupEither.isRight()) {
+ log.debug("Faild to find group {} under component {}", groupId, component.getUniqueId());
+ BeEcompErrorManager.getInstance().logInvalidInputError(GET_GROUP, "group " + groupId + " not found under component " + component.getUniqueId(), ErrorSeverity.INFO);
+ String componentTypeForResponse = getComponentTypeForResponse(component);
+ result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, groupId, component.getSystemName(), componentTypeForResponse));
+ return result;
+ }
+ GroupDefinition group = groupEither.left().value();
+
+
+ Boolean isBase = null;// Constants.IS_BASE;
+ List<GroupProperty> props = group.convertToGroupProperties();
+ if (props != null && !props.isEmpty()) {
+ Optional<GroupProperty> isBasePropOp = props.stream().filter(p -> p.getName().equals(Constants.IS_BASE)).findAny();
+ if (isBasePropOp.isPresent()) {
+ GroupProperty propIsBase = isBasePropOp.get();
+ isBase = Boolean.parseBoolean(propIsBase.getValue());
- } else {
- BeEcompErrorManager.getInstance().logInvalidInputError(GET_GROUP, "failed to find prop isBase " + component.getNormalizedName(), ErrorSeverity.INFO);
- // return
- // Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
+ } else {
+ BeEcompErrorManager.getInstance().logInvalidInputError(GET_GROUP, "failed to find prop isBase " + component.getNormalizedName(), ErrorSeverity.INFO);
+ // return
+ // Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
- }
}
+ }
- List<ArtifactDefinitionInfo> artifacts = new ArrayList();
- List<String> artifactsIds = group.getArtifacts();
- if (artifactsIds != null && !artifactsIds.isEmpty()) {
- Either<List<ArtifactDefinition>, ResponseFormat> getArtifacts = getArtifactsBelongsToComponent(component, artifactsIds, GET_GROUP);
- if (getArtifacts.isRight()) {
- log.debug("Faild to find artifacts in group {} under component {}", groupId, component.getUniqueId());
- // result = Either.right(getArtifacts.right().value());
- // return result;
- } else {
-
- List<ArtifactDefinition> artifactsFromComponent = getArtifacts.left().value();
- if (artifactsFromComponent != null && !artifactsFromComponent.isEmpty()) {
- for (ArtifactDefinition artifactDefinition : artifactsFromComponent) {
- ArtifactDefinitionInfo artifactDefinitionInfo = new ArtifactDefinitionInfo(artifactDefinition);
- artifacts.add(artifactDefinitionInfo);
- }
- }
+ List<ArtifactDefinitionInfo> artifacts = new ArrayList<>();
+ List<ArtifactDefinition> artifactsFromComponent = new ArrayList<>();
+ List<String> artifactsIds = group.getArtifacts();
+
+ Map<String, ArtifactDefinition> deploymentArtifacts = null;
+ if(MapUtils.isNotEmpty(component.getDeploymentArtifacts())){
+ deploymentArtifacts = component.getDeploymentArtifacts().values().stream().collect(Collectors.toMap(a -> a.getUniqueId(), a -> a));
+ }
+
+ if (artifactsIds != null && !artifactsIds.isEmpty()) {
+ for(String id: artifactsIds){
+ if (MapUtils.isEmpty(deploymentArtifacts) || !deploymentArtifacts.containsKey(id)) {
+ log.debug("Failed to get artifact {} . Status is {} ", id, StorageOperationStatus.NOT_FOUND);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND));
+ result = Either.right(responseFormat);
+ return result;
+ }
+ artifactsFromComponent.add(deploymentArtifacts.get(id));
+ }
+ if (!artifactsFromComponent.isEmpty()) {
+ for (ArtifactDefinition artifactDefinition : artifactsFromComponent) {
+ ArtifactDefinitionInfo artifactDefinitionInfo = new ArtifactDefinitionInfo(artifactDefinition);
+ artifacts.add(artifactDefinitionInfo);
}
}
- GroupDefinitionInfo resultInfo = new GroupDefinitionInfo(group);
- resultInfo.setIsBase(isBase);
- if (!artifacts.isEmpty())
- resultInfo.setArtifacts(artifacts);
- result = Either.left(resultInfo);
+ }
+ GroupDefinitionInfo resultInfo = new GroupDefinitionInfo(group);
+ resultInfo.setIsBase(isBase);
+ if (!artifacts.isEmpty())
+ resultInfo.setArtifacts(artifacts);
- return result;
+ result = Either.left(resultInfo);
- } else {
- log.debug("Faild to find group {} under component {}", groupId, component.getUniqueId());
- BeEcompErrorManager.getInstance().logInvalidInputError(GET_GROUP, "group " + groupId + " not found under component " + component.getUniqueId(), ErrorSeverity.INFO);
- String componentTypeForResponse = getComponentTypeForResponse(component);
- result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, groupId, component.getSystemName(), componentTypeForResponse));
- return result;
+ return result;
- }
} finally {
if (false == inTransaction) {
if (result == null || result.isRight()) {
log.debug("Going to execute rollback on create group.");
- titanGenericDao.rollback();
+ titanDao.rollback();
} else {
log.debug("Going to execute commit on create group.");
- titanGenericDao.commit();
+ titanDao.commit();
}
}
@@ -877,6 +1165,21 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
}
+ private Either<GroupDefinition, StorageOperationStatus> findGroupOnComponent(Component component, String groupId) {
+
+ Either<GroupDefinition, StorageOperationStatus> result = null;
+ if(CollectionUtils.isNotEmpty(component.getGroups())){
+ Optional<GroupDefinition> foundGroup = component.getGroups().stream().filter(g -> g.getUniqueId().equals(groupId)).findFirst();
+ if(foundGroup.isPresent()){
+ result = Either.left(foundGroup.get());
+ }
+ }
+ if(result == null){
+ result = Either.right(StorageOperationStatus.NOT_FOUND);
+ }
+ return result;
+ }
+
/**
* @param componentId
* @param userId
@@ -895,7 +1198,6 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
result = Either.right(validateUserExists.right().value());
return result;
}
- User user = validateUserExists.left().value();
// Validate component exist
String realComponentId = componentId;
@@ -907,7 +1209,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
componentParametersView.setIgnoreUsers(false);
componentParametersView.setIgnoreComponentInstances(false);
- Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(realComponentId, componentType, componentParametersView, userId, null, user);
+ Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(realComponentId, componentType, componentParametersView);
if (validateComponent.isRight()) {
result = Either.right(validateComponent.right().value());
@@ -945,14 +1247,6 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
return Either.left(component);
}
- private ResponseFormat validateGroupsInComponent(List<GroupDefinition> groups, org.openecomp.sdc.be.model.Component component) {
-
- Function<GroupDefinition, String> getByName = s -> s.getName();
-
- return validateGroupsInComponentByFunc(groups, component, getByName);
-
- }
-
/**
* @param groups
* @param component
@@ -1014,7 +1308,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
* @param inTransaction
* @return
*/
- public Either<List<GroupDefinition>, ResponseFormat> dissociateArtifactsFromGroup(String componentId, String userId, ComponentTypeEnum componentType, List<GroupDefinition> groups, boolean shouldLockComp, boolean inTransaction) {
+ /*public Either<List<GroupDefinition>, ResponseFormat> dissociateArtifactsFromGroup(String componentId, String userId, ComponentTypeEnum componentType, List<GroupDefinition> groups, boolean shouldLockComp, boolean inTransaction) {
Either<List<GroupDefinition>, ResponseFormat> result = null;
@@ -1073,13 +1367,13 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
if (false == containsAll) { // At least one artifact is
// not associated to the
// group
- log.debug("Some of the artifacts already dissociated to group {}", groupDefinition.getUniqueId());
+ log.debug("Some of the artifacts already dissociated to group {}" , groupDefinition.getUniqueId());
return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_ARTIFACT_ALREADY_DISSOCIATED, componentGroup.getName()));
}
} else {
if (artifactsSizeInGroup == 0) {
if (artifactsToDissociate != null && false == artifactsToDissociate.isEmpty()) {
- log.debug("No artifact is found under the group {}", groupDefinition.getUniqueId());
+ log.debug("No artifact is found under the group {}" , groupDefinition.getUniqueId());
return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_ARTIFACT_ALREADY_DISSOCIATED, componentGroup.getName()));
}
}
@@ -1107,10 +1401,10 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
if (result == null || result.isRight()) {
log.debug("Going to execute rollback on create group.");
- titanGenericDao.rollback();
+ titanDao.rollback();
} else {
log.debug("Going to execute commit on create group.");
- titanGenericDao.commit();
+ titanDao.commit();
}
}
@@ -1121,9 +1415,9 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
}
- }
+ }*/
- public Either<List<GroupDefinition>, ResponseFormat> createGroups(String componentId, String userId, ComponentTypeEnum componentType, List<GroupDefinition> groupDefinitions, boolean shouldLockComp, boolean inTransaction) {
+ /*public Either<List<GroupDefinition>, ResponseFormat> createGroups(String componentId, String userId, ComponentTypeEnum componentType, List<GroupDefinition> groupDefinitions, boolean shouldLockComp, boolean inTransaction) {
Either<List<GroupDefinition>, ResponseFormat> result = null;
@@ -1131,9 +1425,9 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
org.openecomp.sdc.be.model.Component component = null;
try {
- if (groupDefinitions != null && false == groupDefinitions.isEmpty()) {
+ if (groupDefinitions != null && !groupDefinitions.isEmpty()) {
- if (shouldLockComp == true && inTransaction == true) {
+ if (shouldLockComp && inTransaction) {
BeEcompErrorManager.getInstance().logInternalFlowError("createGroups", "Cannot lock component since we are inside a transaction", ErrorSeverity.ERROR);
// Cannot lock component since we are in a middle of another
// transaction.
@@ -1157,7 +1451,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
componentParametersView.setIgnoreUsers(false);
componentParametersView.setIgnoreComponentInstances(false);
- Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(componentId, componentType, componentParametersView, userId, null, user);
+ Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(componentId, componentType, componentParametersView);
if (validateComponent.isRight()) {
result = Either.right(validateComponent.right().value());
@@ -1181,7 +1475,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
for (GroupDefinition groupDefinition : groupDefinitions) {
Either<GroupDefinition, ResponseFormat> createGroup = this.createGroup(component, user, componentType, groupDefinition, true);
if (createGroup.isRight()) {
- log.debug("Failed to create group {}.", groupDefinition);
+ log.debug("Failed to create group {}." , groupDefinition );
result = Either.right(createGroup.right().value());
return result;
}
@@ -1199,10 +1493,10 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
if (result == null || result.isRight()) {
log.debug("Going to execute rollback on create group.");
- titanGenericDao.rollback();
+ titanDao.rollback();
} else {
log.debug("Going to execute commit on create group.");
- titanGenericDao.commit();
+ titanDao.commit();
}
}
@@ -1219,7 +1513,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
Either<GroupDefinition, ResponseFormat> result = null;
- log.debug("Going to create group {}", groupDefinition);
+ log.trace("Going to create group {}" , groupDefinition);
try {
@@ -1314,10 +1608,10 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
if (result == null || result.isRight()) {
log.debug("Going to execute rollback on create group.");
- titanGenericDao.rollback();
+ titanDao.rollback();
} else {
log.debug("Going to execute commit on create group.");
- titanGenericDao.commit();
+ titanDao.commit();
}
}
@@ -1351,8 +1645,23 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
updatedGroups.add(updateGroupNameRes.left().value());
}
return updateGroupNamesRes;
- }
+ }*/
+
+ private Either<List<GroupProperty>, ResponseFormat> updateGroupPropertiesValue(String componentId,
+ GroupDefinition currentGroup, List<GroupProperty> groupPropertyToUpdate, boolean inTransaction) {
+ Either<List<GroupProperty>, ResponseFormat> result;
+ Either<List<GroupProperty>, StorageOperationStatus> eitherUpdate = groupsOperation
+ .updateGroupPropertiesOnComponent(componentId, currentGroup, groupPropertyToUpdate);
+ if (eitherUpdate.isRight()) {
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(eitherUpdate.right().value());
+ result = Either.right(componentsUtils.getResponseFormat(actionStatus));
+ } else {
+ result = Either.left(eitherUpdate.left().value());
+ }
+ return result;
+ }
+
public Either<Boolean, ResponseFormat> validateGenerateVfModuleGroupNames(List<ArtifactTemplateInfo> allGroups, String resourceSystemName, int startGroupCounter) {
Either<Boolean, ResponseFormat> validateGenerateGroupNamesRes = Either.left(true);
Collections.sort(allGroups, (art1, art2) -> ArtifactTemplateInfo.compareByGroupName(art1, art2));
@@ -1438,7 +1747,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
return counter;
}
- public Either<List<GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesOnGraph(List<GroupDefinition> groups, String resourceSystemName, boolean inTransaction) {
+ public Either<List<GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesOnGraph(List<GroupDefinition> groups, Component component, boolean inTransaction) {
List<GroupDefinition> updatedGroups = new ArrayList<>();
Either<List<GroupDefinition>, ResponseFormat> result = Either.left(updatedGroups);
@@ -1451,27 +1760,25 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
int counter;
if (groupType.equals(Constants.DEFAULT_GROUP_VF_MODULE) && Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(oldGroupName).matches()) {
counter = Integer.parseInt(group.getName().split(Constants.MODULE_NAME_DELIMITER)[1]);
- newGroupNameRes = validateGenerateVfModuleGroupName(resourceSystemName, group.getDescription(), counter);
+ newGroupNameRes = validateGenerateVfModuleGroupName(component.getSystemName(), group.getDescription(), counter);
if (newGroupNameRes.isRight()) {
log.debug("Failed to generate new vf module group name. Status is {} ", newGroupNameRes.right().value());
result = Either.right(newGroupNameRes.right().value());
break;
}
newGroupName = newGroupNameRes.left().value();
- updateGroupNameRes = groupOperation.updateGroupName(group.getUniqueId(), newGroupName, inTransaction);
- if (updateGroupNameRes.isRight()) {
- log.debug("Failed to update vf module group name for group {} . Status is {} ", oldGroupName, updateGroupNameRes.right().value());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateGroupNameRes.right().value()));
- result = Either.right(responseFormat);
- break;
- }
+ group.setName(newGroupName);
+
}
updatedGroups.add(group);
+
}
+
+ result = Either.left(updatedGroups);
return result;
}
- public Either<List<GroupDefinition>, ResponseFormat> createGroups(Component component, User user, ComponentTypeEnum componentType, List<GroupDefinition> groupDefinitions, boolean inTransaction) {
+ /*public Either<List<GroupDefinition>, ResponseFormat> createGroups(Component component, User user, ComponentTypeEnum componentType, List<GroupDefinition> groupDefinitions, boolean inTransaction) {
List<GroupDefinition> generatedGroups = new ArrayList<>();
Either<List<GroupDefinition>, ResponseFormat> result = Either.left(generatedGroups);
@@ -1497,16 +1804,710 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
if (result == null || result.isRight()) {
log.debug("Going to execute rollback on create group.");
- titanGenericDao.rollback();
+ titanDao.rollback();
+ } else {
+ log.debug("Going to execute commit on create group.");
+ titanDao.commit();
+ }
+
+ }
+
+ }
+
+ }*/
+
+ public Either<GroupDefinitionInfo, ResponseFormat> getGroupInstWithArtifactsById(ComponentTypeEnum componentType, String componentId, String componentInstanceId, String groupInstId, String userId, boolean inTransaction) {
+ Either<GroupDefinitionInfo, ResponseFormat> result = null;
+
+ // Validate user exist
+ Either<User, ResponseFormat> validateUserExists = validateUserExists(userId, UPDATE_GROUP, true);
+
+ if (validateUserExists.isRight()) {
+ result = Either.right(validateUserExists.right().value());
+ return result;
+ }
+
+ // Validate component exist
+ org.openecomp.sdc.be.model.Component component = null;
+ String realComponentId = componentId;
+
+ try {
+ ComponentParametersView componentParametersView = new ComponentParametersView();
+ componentParametersView.disableAll();
+ componentParametersView.setIgnoreUsers(false);
+ componentParametersView.setIgnoreComponentInstances(false);
+ componentParametersView.setIgnoreArtifacts(false);
+
+ Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(realComponentId, componentType, componentParametersView);
+ if (validateComponent.isRight()) {
+ result = Either.right(validateComponent.right().value());
+ return result;
+ }
+ component = validateComponent.left().value();
+ Either<ImmutablePair<ComponentInstance, GroupInstance>, StorageOperationStatus> findComponentInstanceAndGroupInstanceRes = findComponentInstanceAndGroupInstanceOnComponent(component, componentInstanceId, groupInstId);
+
+ if (findComponentInstanceAndGroupInstanceRes.isRight()) {
+ log.debug("Failed to get group {} . Status is {} ", groupInstId, findComponentInstanceAndGroupInstanceRes.right().value());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(findComponentInstanceAndGroupInstanceRes.right().value()));
+ result = Either.right(responseFormat);
+ return result;
+ }
+
+ GroupInstance group = findComponentInstanceAndGroupInstanceRes.left().value().getRight();
+ ComponentInstance componentInstance = findComponentInstanceAndGroupInstanceRes.left().value().getLeft();
+
+ Boolean isBase = null;// Constants.IS_BASE;
+ List<? extends GroupProperty> props = group.convertToGroupInstancesProperties();
+ if (props != null && !props.isEmpty()) {
+ Optional<? extends GroupProperty> isBasePropOp = props.stream().filter(p -> p.getName().equals(Constants.IS_BASE)).findAny();
+ if (isBasePropOp.isPresent()) {
+ GroupProperty propIsBase = isBasePropOp.get();
+ isBase = Boolean.parseBoolean(propIsBase.getValue());
+
+ } else {
+ BeEcompErrorManager.getInstance().logInvalidInputError(GET_GROUP, "failed to find prop isBase " + component.getNormalizedName(), ErrorSeverity.INFO);
+ // return
+ // Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
+
+ }
+ }
+
+ List<ArtifactDefinitionInfo> artifacts = new ArrayList<>();
+ List<ArtifactDefinition> artifactsFromComponent = new ArrayList<>();
+ List<String> artifactsIds = group.getArtifacts();
+ if (artifactsIds != null && !artifactsIds.isEmpty()) {
+
+ for(String id: artifactsIds){
+ Either<ArtifactDefinition, StorageOperationStatus> artifactEither = artifactsOperation.getArtifactById(componentInstance.getComponentUid(), id);
+ if (artifactEither.isRight()) {
+ log.debug("Failed to get artifact {} . Status is {} ", id, artifactEither.right().value());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(artifactEither.right().value()));
+ result = Either.right(responseFormat);
+ return result;
+ }
+ artifactsFromComponent.add(artifactEither.left().value());
+ }
+ if (!artifactsFromComponent.isEmpty()) {
+ for (ArtifactDefinition artifactDefinition : artifactsFromComponent) {
+ ArtifactDefinitionInfo artifactDefinitionInfo = new ArtifactDefinitionInfo(artifactDefinition);
+ artifacts.add(artifactDefinitionInfo);
+ }
+ }
+
+
+ }
+ GroupDefinitionInfo resultInfo = new GroupDefinitionInfo(group);
+ resultInfo.setIsBase(isBase);
+ if (!artifacts.isEmpty())
+ resultInfo.setArtifacts(artifacts);
+
+ result = Either.left(resultInfo);
+
+ return result;
+
+
+ } finally {
+
+ if (false == inTransaction) {
+
+ if (result == null || result.isRight()) {
+ log.debug("Going to execute rollback on create group.");
+ titanDao.rollback();
} else {
log.debug("Going to execute commit on create group.");
- titanGenericDao.commit();
+ titanDao.commit();
+ }
+
+ }
+
+ }
+ }
+
+ private Either<ImmutablePair<ComponentInstance, GroupInstance>, StorageOperationStatus> findComponentInstanceAndGroupInstanceOnComponent(Component component, String componentInstanceId, String groupInstId) {
+
+ Either<ImmutablePair<ComponentInstance,GroupInstance>, StorageOperationStatus> result = null;
+ if(CollectionUtils.isNotEmpty(component.getComponentInstances())){
+ Optional<GroupInstance> foundGroup;
+ Optional<ComponentInstance> foundComponent = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(componentInstanceId)).findFirst();
+ if(foundComponent.isPresent() && CollectionUtils.isNotEmpty(foundComponent.get().getGroupInstances())){
+ foundGroup = foundComponent.get().getGroupInstances().stream().filter(gi -> gi.getUniqueId().equals(groupInstId)).findFirst();
+ if(foundGroup.isPresent()){
+ result = Either.left(new ImmutablePair<>(foundComponent.get(), foundGroup.get()));
+ }
+ }
+ }
+ if(result == null){
+ result = Either.right(StorageOperationStatus.NOT_FOUND);
+ }
+ return result;
+ }
+
+ private int getLatestIntProperty(Map<PropertyNames, String> newValues, Map<PropertyNames, String> parentValues,
+ PropertyNames propertyKey) {
+ String value;
+ if( newValues.containsKey(propertyKey) ){
+ value = newValues.get(propertyKey);
+ }
+ else{
+ value = parentValues.get(propertyKey);
+ }
+ return Integer.valueOf(value);
+ }
+
+ private boolean isPropertyChanged(Map<PropertyNames, String> newValues, Map<PropertyNames, String> parentValues,
+ final PropertyNames minInstances) {
+ return newValues.containsKey(minInstances) && newValues.containsKey(minInstances) && !newValues.get(minInstances).equals(parentValues.get(minInstances));
+ }
+
+ private Either<Boolean, ResponseFormat> validateMinMaxAndInitialCountPropertyLogicVF(
+ Map<PropertyNames, String> newValues, Map<PropertyNames, String> parentValues) {
+
+ int latestMaxInstances = getLatestIntProperty(newValues, parentValues, PropertyNames.MAX_INSTANCES);
+ int latestInitialCount = getLatestIntProperty(newValues, parentValues, PropertyNames.INITIAL_COUNT);
+ int latestMinInstances = getLatestIntProperty(newValues, parentValues, PropertyNames.MIN_INSTANCES);
+ Either<Boolean, ResponseFormat> result = Either.left(true);
+
+ if (isPropertyChanged(newValues, parentValues, PropertyNames.INITIAL_COUNT) && result.isLeft()) {
+ if (latestInitialCount > latestMaxInstances || latestInitialCount < latestMinInstances) {
+ result = Either.right(
+ componentsUtils.getResponseFormat(ActionStatus.INVALID_GROUP_INITIAL_COUNT_PROPERTY_VALUE,
+ PropertyNames.INITIAL_COUNT.getPropertyName(), String.valueOf(latestMinInstances),
+ String.valueOf(latestMaxInstances)));
+ }
+ }
+ if (isPropertyChanged(newValues, parentValues, PropertyNames.MAX_INSTANCES) && result.isLeft()) {
+ if (latestMaxInstances < latestInitialCount) {
+ result = Either.right(componentsUtils.getResponseFormat(
+ ActionStatus.INVALID_GROUP_PROPERTY_VALUE_LOWER_HIGHER,
+ PropertyNames.MAX_INSTANCES.getPropertyName(), "higher", String.valueOf(latestInitialCount)));
+ }
+
+ }
+ if (isPropertyChanged(newValues, parentValues, PropertyNames.MIN_INSTANCES) && result.isLeft()) {
+ if (latestMinInstances > latestInitialCount) {
+ result = Either.right(componentsUtils.getResponseFormat(
+ ActionStatus.INVALID_GROUP_PROPERTY_VALUE_LOWER_HIGHER,
+ PropertyNames.MIN_INSTANCES.getPropertyName(), "lower", String.valueOf(latestInitialCount)));
+ }
+
+ }
+ return result;
+ }
+ private Either<Boolean, ResponseFormat> validateMinMaxAndInitialCountPropertyLogic(Map<PropertyNames, String> newValues, Map<PropertyNames, String> currValues, Map<PropertyNames, String> parentValues) {
+
+ Either<Boolean, ResponseFormat> result;
+ for(Entry<PropertyNames, String> entry : newValues.entrySet()){
+ PropertyNames currPropertyName = entry.getKey();
+ if(currPropertyName == PropertyNames.MIN_INSTANCES){
+ String minValue = parentValues.get(PropertyNames.MIN_INSTANCES);
+ String maxValue = newValues.containsKey(PropertyNames.INITIAL_COUNT) ? newValues.get(PropertyNames.MAX_INSTANCES) : currValues.get(PropertyNames.INITIAL_COUNT);
+ result = validateValueInRange(new ImmutablePair<PropertyNames, String>(currPropertyName, entry.getValue()),
+ new ImmutablePair<PropertyNames, String>(PropertyNames.MIN_INSTANCES, minValue),
+ new ImmutablePair<PropertyNames, String>(PropertyNames.MAX_INSTANCES, maxValue));
+ if(result.isRight()){
+ return result;
+ }
+ }
+ else if(currPropertyName == PropertyNames.INITIAL_COUNT){
+ String minValue = newValues.containsKey(PropertyNames.MIN_INSTANCES) ? newValues.get(PropertyNames.MIN_INSTANCES) : currValues.get(PropertyNames.MIN_INSTANCES);
+ String maxValue = newValues.containsKey(PropertyNames.MAX_INSTANCES) ? newValues.get(PropertyNames.MAX_INSTANCES) : currValues.get(PropertyNames.MAX_INSTANCES);
+ result = validateValueInRange(new ImmutablePair<PropertyNames, String>(currPropertyName, entry.getValue()),
+ new ImmutablePair<PropertyNames, String>(PropertyNames.MIN_INSTANCES,minValue),
+ new ImmutablePair<PropertyNames, String>(PropertyNames.MAX_INSTANCES, maxValue));
+ if(result.isRight()){
+ return result;
+ }
+ }
+ else if(currPropertyName == PropertyNames.MAX_INSTANCES){
+ String minValue = newValues.containsKey(PropertyNames.INITIAL_COUNT) ? newValues.get(PropertyNames.MIN_INSTANCES) : currValues.get(PropertyNames.INITIAL_COUNT);
+ String maxValue = parentValues.get(PropertyNames.MAX_INSTANCES);
+ result = validateValueInRange(new ImmutablePair<PropertyNames, String>(currPropertyName, entry.getValue()),
+ new ImmutablePair<PropertyNames, String>(PropertyNames.MIN_INSTANCES, minValue),
+ new ImmutablePair<PropertyNames, String>(PropertyNames.MAX_INSTANCES, maxValue));
+ if(result.isRight()){
+ return result;
}
+ }
+ }
+ return Either.left(true);
+ }
+ private Either<Boolean, ResponseFormat> validateValueInRange(ImmutablePair<PropertyNames,String> newValue, ImmutablePair<PropertyNames,String> min, ImmutablePair<PropertyNames,String> max) {
+ Either<Boolean, ResponseFormat> result;
+ final String warnMessage = "Failed to validate {} as property value of {}. It must be not higher than {}, and not lower than {}.";
+ int newValueInt = parseIntValue(newValue.getValue(), newValue.getKey());
+ int minInt = parseIntValue(min.getValue(), min.getKey());
+ int maxInt = parseIntValue(max.getValue(), max.getKey());
+ if(newValueInt < 0 || minInt < 0 || maxInt < 0){
+ result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY));
+ }
+ else if (newValueInt < minInt || newValueInt > maxInt) {
+ log.debug(warnMessage, newValue.getValue(), newValue.getKey().getPropertyName(), min.getValue(), max.getValue());
+ result = Either.right(componentsUtils.getResponseFormat(
+ ActionStatus.INVALID_GROUP_MIN_MAX_INSTANCES_PROPERTY_VALUE,
+ newValue.getKey().getPropertyName(), maxInt == Integer.MAX_VALUE ? Constants.UNBOUNDED : max.getValue(), min.getValue()));
+ }else{
+ result = Either.left(true);
+ }
+ return result;
+ }
+
+ private int parseIntValue(String value, PropertyNames propertyName) {
+ int result;
+ if(propertyName == PropertyNames.MAX_INSTANCES ){
+ result = convertIfUnboundMax(value);
+ } else if (NumberUtils.isNumber(value)) {
+ result = Integer.parseInt(value);
+ } else{
+ result = -1;
+ }
+ return result;
+ }
+
+/**
+ * validates received new property values and updates group instance in case of success
+ * @param oldGroupInstance
+ * @param groupInstanceId
+ * @param newProperties
+ * @param inTransaction
+ * @return
+ */
+ public Either<GroupInstance, ResponseFormat> validateAndUpdateGroupInstancePropertyValues(String componentId, String instanceId, GroupInstance oldGroupInstance, List<GroupInstanceProperty> newProperties, boolean inTransaction) {
+
+ Either<GroupInstance, ResponseFormat> actionResult = null;
+ Either<GroupInstance, StorageOperationStatus> updateGroupInstanceResult = null;
+ Either<List<GroupInstanceProperty>, ResponseFormat> validateRes = validateReduceGroupInstancePropertiesBeforeUpdate(oldGroupInstance, newProperties);
+ if(validateRes.isRight()){
+ log.debug("Failed to validate group instance {} properties before update. ", oldGroupInstance.getName());
+ actionResult = Either.right(validateRes.right().value());
+ }
+ if(actionResult == null){
+ List<GroupInstanceProperty> validatedReducedNewProperties = validateRes.left().value();
+ updateGroupInstanceResult = groupsOperation.updateGroupInstancePropertyValuesOnGraph(componentId, instanceId, oldGroupInstance, validatedReducedNewProperties);
+ if(updateGroupInstanceResult.isRight()){
+ log.debug("Failed to update group instance {} property values. ", oldGroupInstance.getName());
+ actionResult = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateGroupInstanceResult.right().value())));
+ }
+ }
+ if(actionResult == null){
+ actionResult = Either.left(updateGroupInstanceResult.left().value());
+ }
+ return actionResult;
+ }
+
+ private Either<List<GroupInstanceProperty>, ResponseFormat> validateReduceGroupInstancePropertiesBeforeUpdate(GroupInstance oldGroupInstance, List<GroupInstanceProperty> newProperties) {
+
+ Either<Boolean, ResponseFormat> validationRes = null;
+ Either<List<GroupInstanceProperty>, ResponseFormat> actionResult;
+ Map<String,GroupInstanceProperty> existingProperties = oldGroupInstance.convertToGroupInstancesProperties().stream().collect(Collectors.toMap(p->p.getName(),p->p));
+ Map<PropertyNames, String> newPropertyValues = new EnumMap<>(PropertyNames.class);
+ List<GroupInstanceProperty> reducedProperties = new ArrayList<>();
+ String currPropertyName;
+ try{
+ for(GroupInstanceProperty currNewProperty : newProperties){
+ currPropertyName = currNewProperty.getName();
+ validationRes = handleAndAddProperty(reducedProperties, newPropertyValues, currNewProperty, existingProperties.get(currPropertyName));
+ if(validationRes.isRight()){
+ log.debug("Failed to handle property {} of group instance {}. ", currPropertyName, oldGroupInstance.getName());
+ break;
+ }
}
+ if(validationRes == null || validationRes.isLeft()){
+ Map<PropertyNames, String> existingPropertyValues = new EnumMap<>(PropertyNames.class);
+ Map<PropertyNames, String> parentPropertyValues = new EnumMap<>(PropertyNames.class);
+ fillValuesAndParentValuesFromExistingProperties(existingProperties, existingPropertyValues, parentPropertyValues);
+ validationRes = validateMinMaxAndInitialCountPropertyLogic(newPropertyValues, existingPropertyValues, parentPropertyValues);
+ }
+ if(validationRes.isLeft()){
+ actionResult = Either.left(reducedProperties);
+ } else {
+ actionResult = Either.right(validationRes.right().value());
+ }
+ } catch( Exception e){
+ log.error("Exception occured during validation and reducing group instance properties. The message is {}", e.getMessage(), e);
+ actionResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ return actionResult;
+ }
+ private void fillValuesAndParentValuesFromExistingProperties(Map<String, GroupInstanceProperty> existingProperties,
+ Map<PropertyNames, String> propertyValues, Map<PropertyNames, String> parentPropertyValues) {
+ PropertyNames[] allPropertyNames = PropertyNames.values();
+ for(PropertyNames name : allPropertyNames){
+ if(isUpdatable(name)){
+ propertyValues.put(name, String.valueOf(existingProperties.get(name.getPropertyName()).getValue()));
+ parentPropertyValues.put(name, String.valueOf(existingProperties.get(name.getPropertyName()).getParentValue()));
+ }
}
+ }
+ private Either<Boolean, ResponseFormat> handleAndAddProperty(List<GroupInstanceProperty> reducedProperties, Map<PropertyNames, String> newPropertyValues,
+ GroupInstanceProperty currNewProperty, GroupInstanceProperty currExistingProperty) {
+
+ Either<Boolean, ResponseFormat> validationRes = null;
+ String currPropertyName = currNewProperty.getName();
+ PropertyNames propertyName = PropertyNames.findName(currPropertyName);
+ try{
+ if(currExistingProperty == null){
+ log.warn("The value of property with the name {} cannot be updated. The property not found on group instance. ", currPropertyName);
+ }
+ else if(isUpdatable(propertyName)){
+ validationRes = validateAndUpdatePropertyValue(currNewProperty, currExistingProperty);
+ if(validationRes.isRight()){
+ log.debug("Failed to validate property value {} of property {}. ", currNewProperty.getValue() , currPropertyName);
+ } else {
+ addPropertyUpdatedValues(reducedProperties, propertyName, newPropertyValues, currNewProperty, currExistingProperty);
+ }
+ }
+ else{
+ validateImmutableProperty(currExistingProperty, currNewProperty);
+ }
+ if(validationRes == null){
+ validationRes = Either.left(true);
+ }
+ } catch( Exception e){
+ log.error("Exception occured during handle and adding property. The message is {}", e.getMessage(), e);
+ validationRes = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ return validationRes;
}
+ private boolean isUpdatable(PropertyNames updatablePropertyName) {
+ return updatablePropertyName != null &&
+ updatablePropertyName.getUpdateBehavior().getLevelNumber() >= GroupInstancePropertyValueUpdateBehavior.UPDATABLE_ON_SERVICE_LEVEL.getLevelNumber();
+ }
+
+ private void addPropertyUpdatedValues(List<GroupInstanceProperty> reducedProperties, PropertyNames propertyName, Map<PropertyNames, String> newPropertyValues,
+ GroupInstanceProperty newProperty, GroupInstanceProperty existingProperty) {
+
+ String newValue = newProperty.getValue();
+ if(!newValue.equals(String.valueOf(existingProperty.getValue()))){
+ newProperty.setValueUniqueUid(existingProperty.getValueUniqueUid());
+ reducedProperties.add(newProperty);
+ }
+ if(!isEmptyMinInitialCountValue(propertyName, newValue)){
+ newPropertyValues.put(propertyName, newValue);
+ }
+ }
+
+ private boolean isEmptyMinInitialCountValue(PropertyNames propertyName, String newValue) {
+ boolean result = false;
+ if((propertyName == PropertyNames.MIN_INSTANCES || propertyName == PropertyNames.INITIAL_COUNT) && !NumberUtils.isNumber(newValue)){
+ result = true;
+ }
+ return result;
+ }
+
+ private int convertIfUnboundMax(String value) {
+
+ int result;
+ if(!NumberUtils.isNumber(value)){
+ result = Integer.MAX_VALUE;
+ }
+ else{
+ result = Integer.parseInt(value);
+ }
+ return result;
+ }
+
+ private Either<Boolean, ResponseFormat> validateAndUpdatePropertyValue(GroupInstanceProperty newProperty, GroupInstanceProperty existingProperty) {
+
+ Either<Boolean, ResponseFormat> validationRes = null;
+ String parentValue = existingProperty.getParentValue();
+
+ newProperty.setParentValue(parentValue);
+ if(StringUtils.isEmpty(newProperty.getValue())){
+ newProperty.setValue(parentValue);
+ }
+ if(StringUtils.isEmpty(existingProperty.getValue())){
+ existingProperty.setValue(parentValue);
+ }
+ StorageOperationStatus status = groupOperation.validateAndUpdatePropertyValue(newProperty);
+ if(status != StorageOperationStatus.OK){
+ log.debug("Failed to validate property value {} of property with name {}. Status is {}. ", newProperty.getValue(), newProperty.getName(), status);
+ validationRes = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
+ }
+ if(validationRes == null){
+ validationRes = Either.left(true);
+ }
+ return validationRes;
+ }
+
+ private void validateImmutableProperty(GroupProperty oldProperty, GroupProperty newProperty) {
+ if(oldProperty.getValue() == null && newProperty.getValue() != null || oldProperty.getValue()!=null && !oldProperty.getValue().equals(newProperty.getValue())){
+ log.warn("The value of property with the name {} cannot be updated on service level. Going to ignore new property value {}. ",oldProperty.getName(), newProperty.getValue());
+ }
+ }
+
+ public Either<List<GroupDefinition>, ResponseFormat> createGroups(Component component, User user, ComponentTypeEnum componentType, List<GroupDefinition> groupDefinitions) {
+
+ Map<String,GroupDataDefinition> groups = new HashMap<>();
+ //Map<String, MapPropertiesDataDefinition> groupsPropertiesMap = new HashMap<>();
+ Either<List<GroupDefinition>, ResponseFormat> result = null;
+ Either<List<GroupDefinition>, StorageOperationStatus> createGroupsResult = null;
+ Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll();
+ if (allDataTypes.isRight()) {
+ TitanOperationStatus status = allDataTypes.right().value();
+ BeEcompErrorManager.getInstance().logInternalFlowError("AddPropertyToGroup", "Failed to add property to group. Status is " + status, ErrorSeverity.ERROR);
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status))));
+
+ }
+
+ //handle groups and convert to tosca data
+ if (groupDefinitions != null && !groupDefinitions.isEmpty()) {
+ for (GroupDefinition groupDefinition : groupDefinitions) {
+ Either<GroupDefinition, ResponseFormat> handleGroupRes = handleGroup(component, user, componentType, groupDefinition, allDataTypes.left().value());
+ if (handleGroupRes.isRight()) {
+ result = Either.right(handleGroupRes.right().value());
+ break;
+ }
+ GroupDefinition handledGroup = handleGroupRes.left().value();
+ groups.put(handledGroup.getName(), new GroupDataDefinition(handledGroup));
+
+ }
+ }
+ if(result == null){
+ createGroupsResult = groupsOperation.createGroups(component, user, componentType, groups);
+ if(createGroupsResult.isRight()){
+ result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createGroupsResult.right().value())));
+ }
+ }
+ if(result == null){
+ result = Either.left(createGroupsResult.left().value());
+ }
+ return result;
+ }
+
+ public Either<List<GroupDefinition>, ResponseFormat> addGroups(Component component, User user, ComponentTypeEnum componentType, List<GroupDefinition> groupDefinitions) {
+
+
+ Either<List<GroupDefinition>, ResponseFormat> result = null;
+ Either<List<GroupDefinition>, StorageOperationStatus> createGroupsResult = null;
+ List<GroupDataDefinition> groups = new ArrayList<>();
+
+ Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll();
+ if (allDataTypes.isRight()) {
+ TitanOperationStatus status = allDataTypes.right().value();
+ BeEcompErrorManager.getInstance().logInternalFlowError("AddPropertyToGroup", "Failed to add property to group. Status is " + status, ErrorSeverity.ERROR);
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status))));
+
+ }
+
+ //handle groups and convert to tosca data
+ if (groupDefinitions != null && !groupDefinitions.isEmpty()) {
+ for (GroupDefinition groupDefinition : groupDefinitions) {
+ Either<GroupDefinition, ResponseFormat> handleGroupRes = handleGroup(component, user, componentType, groupDefinition, allDataTypes.left().value());
+ if (handleGroupRes.isRight()) {
+ result = Either.right(handleGroupRes.right().value());
+ break;
+ }
+ GroupDefinition handledGroup = handleGroupRes.left().value();
+ groups.add(new GroupDataDefinition(handledGroup));
+ }
+ }
+ if(result == null){
+ createGroupsResult = groupsOperation.addGroups(component, user, componentType, groups);
+ if(createGroupsResult.isRight()){
+ result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createGroupsResult.right().value())));
+ }
+ }
+ if(result == null){
+ result = Either.left(createGroupsResult.left().value());
+ }
+ return result;
+ }
+
+ public Either<List<GroupDefinition>, ResponseFormat> deleteGroups(Component component, User user, ComponentTypeEnum componentType, List<GroupDefinition> groupDefinitions) {
+
+
+ Either<List<GroupDefinition>, ResponseFormat> result = null;
+ Either<List<GroupDefinition>, StorageOperationStatus> createGroupsResult = null;
+
+ createGroupsResult = groupsOperation.deleteGroups(component, user, componentType, groupDefinitions.stream().map(x-> new GroupDataDefinition(x)).collect(Collectors.toList()));
+ if(createGroupsResult.isRight()){
+ result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createGroupsResult.right().value())));
+ }
+
+ if(result == null){
+ result = Either.left(createGroupsResult.left().value());
+ }
+ return result;
+ }
+
+ /**
+ * Update specific group version
+ *
+ * @param groupDefinition
+ * @param inTransaction
+ * @return
+ */
+ public Either<List<GroupDefinition>, ResponseFormat> updateGroups(Component component, ComponentTypeEnum componentType, List<GroupDefinition> groupDefinitions) {
+
+ Either<List<GroupDefinition>, ResponseFormat> result = null;
+ Either<List<GroupDefinition>, StorageOperationStatus> createGroupsResult = null;
+
+ createGroupsResult = groupsOperation.updateGroups(component, componentType, groupDefinitions.stream().map(x-> new GroupDataDefinition(x)).collect(Collectors.toList()));
+ if(createGroupsResult.isRight()){
+ result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createGroupsResult.right().value())));
+ }
+
+ if(result == null){
+ result = Either.left(createGroupsResult.left().value());
+ }
+ return result;
+ }
+
+ public Either<GroupDefinition, ResponseFormat> handleGroup(Component component, User user, ComponentTypeEnum componentType, GroupDefinition groupDefinition, Map<String, DataTypeDefinition> allDAtaTypes) {
+
+ Either<GroupDefinition, ResponseFormat> result = null;
+
+ log.trace("Going to create group {}" , groupDefinition);
+ // 3. verify group not already exist
+ List<GroupDefinition> groups = component.getGroups();
+ boolean found = false;
+ if (groups != null && false == groups.isEmpty()) {
+
+ GroupDefinition existGroupDef = groups.stream().filter(p -> p.getName().equalsIgnoreCase(groupDefinition.getName())).findFirst().orElse(null);
+
+ found = existGroupDef != null;
+ }
+ if (true == found) {
+ String componentTypeForResponse = getComponentTypeForResponse(component);
+ result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_ALREADY_EXIST, groupDefinition.getName(), component.getNormalizedName(), componentTypeForResponse));
+ return result;
+ }
+ // 4. verify type of group exist
+ String groupType = groupDefinition.getType();
+ if (groupType == null || groupType.isEmpty()) {
+ result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_MISSING_GROUP_TYPE, groupDefinition.getName()));
+ return result;
+ }
+ Either<GroupTypeDefinition, StorageOperationStatus> getGroupType = groupTypeOperation.getLatestGroupTypeByType(groupType, true);
+ if (getGroupType.isRight()) {
+ StorageOperationStatus status = getGroupType.right().value();
+ if (status == StorageOperationStatus.NOT_FOUND) {
+ BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_GROUP, "group type " + groupType + " cannot be found", ErrorSeverity.INFO);
+ result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_TYPE_IS_INVALID, groupType));
+ return result;
+ } else {
+ result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ return result;
+ }
+ }
+ // 6. verify the component instances type are allowed according to
+ // the member types in the group type
+ GroupTypeDefinition groupTypeDefinition = getGroupType.left().value();
+
+ Either<Boolean, ResponseFormat> areValidMembers = verifyComponentInstancesAreValidMembers(component, componentType, groupDefinition.getName(), groupType, groupDefinition.getMembers(), groupTypeDefinition.getMembers());
+
+ if (areValidMembers.isRight()) {
+ ResponseFormat responseFormat = areValidMembers.right().value();
+ result = Either.right(responseFormat);
+ return result;
+ }
+ // 7. verify the artifacts belongs to the component
+ Either<Boolean, ResponseFormat> areValidArtifacts = verifyArtifactsBelongsToComponent(component, groupDefinition.getArtifacts(), CREATE_GROUP);
+ if (areValidArtifacts.isRight()) {
+ ResponseFormat responseFormat = areValidArtifacts.right().value();
+ result = Either.right(responseFormat);
+ return result;
+ }
+ List<PropertyDefinition> groupTypeProperties = groupTypeDefinition.getProperties();
+
+ List<GroupProperty> properties = groupDefinition.convertToGroupProperties();
+ List<GroupProperty> updatedGroupTypeProperties = new ArrayList<>();
+ if (properties != null && false == properties.isEmpty()) {
+
+ if (groupTypeProperties == null || true == groupTypeProperties.isEmpty()) {
+ BeEcompErrorManager.getInstance().logInvalidInputError(ADDING_GROUP, "group type does not have properties", ErrorSeverity.INFO);
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.MATCH_NOT_FOUND))));
+ }
+
+ Map<String, PropertyDefinition> groupTypePropertiesMap = groupTypeProperties.stream().collect(Collectors.toMap(p -> p.getName(), p -> p));
+
+ Either<GroupProperty, TitanOperationStatus> addPropertyResult = null;
+ int i = 1;
+ for (GroupProperty prop : properties) {
+ addPropertyResult = handleProperty(prop, groupTypePropertiesMap.get(prop.getName()), i, allDAtaTypes);
+ if(addPropertyResult.isRight()){
+ BeEcompErrorManager.getInstance().logInvalidInputError(ADDING_GROUP, "failed to validate property", ErrorSeverity.INFO);
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(addPropertyResult.right().value()))));
+ }
+ updatedGroupTypeProperties.add(addPropertyResult.left().value());
+
+ i++;
+ }
+ }
+ if(groupDefinition.getUniqueId() == null){
+ String uid = UniqueIdBuilder.buildGroupingUid(component.getUniqueId(), groupDefinition.getName());
+ groupDefinition.setUniqueId(uid);
+ }
+ groupDefinition.convertFromGroupProperties(updatedGroupTypeProperties);
+ groupDefinition.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID());
+ groupDefinition.setGroupUUID(UniqueIdBuilder.generateUUID());
+ groupDefinition.setVersion(INITIAL_VERSION);
+ groupDefinition.setTypeUid(groupTypeDefinition.getUniqueId());
+
+ return Either.left(groupDefinition);
+ }
+
+
+
+ public Either<GroupProperty, TitanOperationStatus> handleProperty(GroupProperty groupProperty, PropertyDefinition prop, Integer index, Map<String, DataTypeDefinition> allDataTypes) {
+
+ if (prop == null) {
+ return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
+ }
+
+ PropertyDataDefinition propDataDef = prop;
+ String propertyType = propDataDef.getType();
+ String value = groupProperty.getValue();
+
+ Either<String, TitanOperationStatus> checkInnerType = propertyOperation.checkInnerType(propDataDef);
+ if (checkInnerType.isRight()) {
+ TitanOperationStatus status = checkInnerType.right().value();
+ return Either.right(status);
+ }
+
+ String innerType = checkInnerType.left().value();
+
+
+ log.debug("Before validateAndUpdatePropertyValue");
+ Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, value, innerType, allDataTypes);
+ log.debug("After validateAndUpdatePropertyValue. isValid = {}", isValid);
+
+ String newValue = value;
+ if (isValid.isRight()) {
+ Boolean res = isValid.right().value();
+ if (res == false) {
+ return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
+ }
+ } else {
+ Object object = isValid.left().value();
+ if (object != null) {
+ newValue = object.toString();
+ }
+ }
+
+ String uniqueId = UniqueIdBuilder.buildGroupPropertyValueUid((String) prop.getUniqueId(), index);
+
+ groupProperty.setUniqueId(uniqueId);
+ groupProperty.setValue(newValue);
+ groupProperty.setType(prop.getType());
+ groupProperty.setDefaultValue(prop.getDefaultValue());
+ groupProperty.setDescription(prop.getDescription());
+ groupProperty.setSchema(prop.getSchema());
+ groupProperty.setPassword(prop.isPassword());
+ groupProperty.setParentUniqueId(prop.getUniqueId());
+
+
+ log.debug("Before adding property value to graph {}", groupProperty);
+
+
+ return Either.left(groupProperty);
+ }
+
+
+
+
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/HealthCheckBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/HealthCheckBusinessLogic.java
index 81dfc1a256..e535214d70 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/HealthCheckBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/HealthCheckBusinessLogic.java
@@ -39,7 +39,6 @@ import javax.servlet.ServletContext;
import org.openecomp.sdc.be.components.distribution.engine.DistributionEngineClusterHealth;
import org.openecomp.sdc.be.components.distribution.engine.UebHealthCheckCall;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
-import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
import org.openecomp.sdc.be.dao.api.IEsHealthCheckDao;
import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
import org.openecomp.sdc.be.impl.WebAppContextWrapper;
@@ -102,7 +101,7 @@ public class HealthCheckBusinessLogic {
lastBeHealthCheckInfos = getBeHealthCheckInfos();
- log.debug("After initializing lastBeHealthCheckInfos :{}", lastBeHealthCheckInfos);
+ log.debug("After initializing lastBeHealthCheckInfos: {}", lastBeHealthCheckInfos);
healthCheckScheduledTask = new HealthCheckScheduledTask();
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/IDeploymentArtifactTypeConfigGetter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/IDeploymentArtifactTypeConfigGetter.java
index 68569ebc3b..66c1868223 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/IDeploymentArtifactTypeConfigGetter.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/IDeploymentArtifactTypeConfigGetter.java
@@ -20,8 +20,8 @@
package org.openecomp.sdc.be.components.impl;
-import org.openecomp.sdc.be.config.Configuration.DeploymentArtifactTypeConfig;
+import org.openecomp.sdc.be.config.Configuration.ArtifactTypeConfig;
public interface IDeploymentArtifactTypeConfigGetter {
- DeploymentArtifactTypeConfig getDeploymentArtifactConfig();
+ ArtifactTypeConfig getDeploymentArtifactConfig();
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ImportUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ImportUtils.java
index 94a7340ff7..33390e7e98 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ImportUtils.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ImportUtils.java
@@ -32,7 +32,6 @@ import java.util.function.Consumer;
import java.util.function.Function;
import org.apache.commons.lang3.StringEscapeUtils;
-import org.apache.commons.lang3.text.translate.CharSequenceTranslator;
import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
import org.openecomp.sdc.be.model.AttributeDefinition;
import org.openecomp.sdc.be.model.HeatParameterDefinition;
@@ -48,6 +47,7 @@ import org.openecomp.sdc.common.util.GsonFactory;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.Constructor;
+import org.yaml.snakeyaml.nodes.Tag;
import org.yaml.snakeyaml.representer.Representer;
import org.yaml.snakeyaml.resolver.Resolver;
@@ -65,13 +65,20 @@ public final class ImportUtils {
private static CustomResolver customResolver = new CustomResolver();
private static class CustomResolver extends Resolver {
+ @Override
protected void addImplicitResolvers() {
- // avoid implicit resolvers
+ // avoid implicit resolvers for strings that can be interpreted as boolean values
+ addImplicitResolver(Tag.STR, EMPTY, "");
+ addImplicitResolver(Tag.STR, NULL, null);
+ addImplicitResolver(Tag.NULL, NULL, "~nN\0");
+ addImplicitResolver(Tag.NULL, EMPTY, null);
+ addImplicitResolver(Tag.YAML, YAML, "!&*");
}
}
+ @SuppressWarnings("unchecked")
public static Either<List<HeatParameterDefinition>, ResultStatusEnum> getHeatParamsWithoutImplicitTypes(String heatDecodedPayload, String artifactType) {
- Map<String, Object> heatData = (Map<String, Object>) new Yaml(new Constructor(), new Representer(), new DumperOptions(), customResolver).load(heatDecodedPayload);
+ Map<String, Object> heatData = (Map<String, Object>) new Yaml(new Constructor(), new Representer(), new DumperOptions(), customResolver).load(heatDecodedPayload);
return getHeatParameters(heatData, artifactType);
}
@@ -82,6 +89,7 @@ public final class ImportUtils {
public static final String VENDOR_NAME = "ATT (Tosca)";
public static final String VENDOR_RELEASE = "1.0.0.wd03";
public static final LifecycleStateEnum NORMATIVE_TYPE_LIFE_CYCLE = LifecycleStateEnum.CERTIFIED;
+ public static final LifecycleStateEnum NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT = LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT;
public static final boolean NORMATIVE_TYPE_HIGHEST_VERSION = true;
// public static final String ABSTRACT_CATEGORY = "Generic/Abstract";
public static final String ABSTRACT_CATEGORY_NAME = "Generic";
@@ -92,7 +100,6 @@ public final class ImportUtils {
public static final List<String> TOSCA_DEFINITION_VERSIONS = Arrays.asList(new String[] { "tosca_simple_yaml_1_0_0", "tosca_simple_profile_for_nfv_1_0_0", "tosca_simple_yaml_1_0" });
public static final List<String> TOSCA_YML_CSAR_VALID_SUFFIX = Arrays.asList(new String[] { ".yml", ".yaml", ".csar" });
public static final String UI_JSON_PAYLOAD_NAME = "payloadName";
- public static final String ABSTRACT_NODE = "abstact";
}
public enum ResultStatusEnum {
@@ -172,10 +179,7 @@ public final class ImportUtils {
else if (elementType == ToscaElementTypeEnum.ALL) {
if (elementValue != null) {
returnedList.add(String.valueOf(elementValue));
- } else {
- returnedList.add(elementValue);
- }
-
+ }
}
}
@@ -622,7 +626,7 @@ public final class ImportUtils {
Iterator<Entry<String, Object>> propertiesNameValue = jsonProperties.entrySet().iterator();
while (propertiesNameValue.hasNext()) {
Entry<String, Object> propertyNameValue = propertiesNameValue.next();
- if (propertyNameValue.getValue() instanceof Map) {
+ if (propertyNameValue.getValue() instanceof Map || propertyNameValue.getValue() instanceof List) {
if (!artifactType.equals(ArtifactTypeEnum.HEAT_ENV.getType())) {
@SuppressWarnings("unchecked")
Either<HeatParameterDefinition, ResultStatusEnum> propertyStatus = createModuleHeatParameter((Map<String, Object>) propertyNameValue.getValue());
@@ -695,7 +699,7 @@ public final class ImportUtils {
return null;
}
ToscaPropertyType validType = ToscaPropertyType.isValidType(type);
- if (validType == null || validType.equals(ToscaPropertyType.MAP) || validType.equals(ToscaPropertyType.LIST)) {
+ if (validType == null || validType.equals(ToscaPropertyType.JSON) ||validType.equals(ToscaPropertyType.MAP) || validType.equals(ToscaPropertyType.LIST)) {
return gson.toJson(value);
}
return value.toString();
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InformationDeployedArtifactsBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InformationDeployedArtifactsBusinessLogic.java
index 129110e13f..3b6e0f7a76 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InformationDeployedArtifactsBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InformationDeployedArtifactsBusinessLogic.java
@@ -28,7 +28,7 @@ import java.util.stream.Collectors;
import org.apache.commons.codec.binary.Base64;
import org.openecomp.sdc.be.config.ConfigurationManager;
-import org.openecomp.sdc.be.config.Configuration.DeploymentArtifactTypeConfig;
+import org.openecomp.sdc.be.config.Configuration.ArtifactTypeConfig;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.model.ArtifactDefinition;
@@ -79,7 +79,7 @@ public class InformationDeployedArtifactsBusinessLogic {
* String message = (response.isLeft()) ? "informationalDeployable artifact {} is valid" : "informationalDeployable artifact {} is not valid"; log.debug(message, artifactInfo.getArtifactName()); return response; }
*
* private void validatePayloadContent(Wrapper<ResponseFormat> responseFormatWrapper, ArtifactDefinition artifactToVerify) { ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactToVerify.getArtifactType()); if( artifactType ==
- * ArtifactTypeEnum.YANG_XML ){ String rawPayloadData = artifactToVerify.getPayloadData(); String xmlToParse = Base64.isBase64(rawPayloadData) ? new String(org.apache.commons.codec.binary.Base64.decodeBase64(rawPayloadData )) : rawPayloadData;
+ * ArtifactTypeEnum.YANG_XML ){ String rawPayloadData = artifactToVerify.getPayloadData(); String xmlToParse = new String(org.apache.commons.codec.binary.Base64.decodeBase64(rawPayloadData ));
*
* boolean isXmlValid = artifactBusinessLogic.isValidXml(xmlToParse.getBytes()); if( !isXmlValid ){ ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus. INVALID_XML,
* artifactToVerify.getArtifactType()); responseFormatWrapper.setInnerElement(responseFormat); log.debug("Xml is not valid for artifact : {}", artifactToVerify.getArtifactName()); } } }
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogic.java
index 7d0624440e..8ffee1fd34 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogic.java
@@ -21,57 +21,95 @@
package org.openecomp.sdc.be.components.impl;
import java.util.ArrayList;
+import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
-
+import java.util.UUID;
+import java.util.Map.Entry;
+import java.util.function.BiConsumer;
+import java.util.function.Predicate;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import org.json.simple.JSONObject;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
+import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation;
+import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels;
+import org.openecomp.sdc.be.dao.neo4j.GraphEdgePropertiesDictionary;
+import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
+import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
+import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.ListCapabilityDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.be.model.CapabilityDefinition;
import org.openecomp.sdc.be.model.ComponentInstInputsMap;
+import org.openecomp.sdc.be.model.ComponentInstance;
import org.openecomp.sdc.be.model.ComponentInstanceInput;
+import org.openecomp.sdc.be.model.ComponentInstancePropInput;
import org.openecomp.sdc.be.model.ComponentInstanceProperty;
import org.openecomp.sdc.be.model.ComponentParametersView;
import org.openecomp.sdc.be.model.DataTypeDefinition;
import org.openecomp.sdc.be.model.InputDefinition;
+import org.openecomp.sdc.be.model.PropertyDefinition;
import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.be.model.operations.api.IResourceOperation;
+
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
import org.openecomp.sdc.be.model.operations.impl.InputsOperation;
import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
+import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
import org.openecomp.sdc.be.model.tosca.converters.PropertyValueConverter;
+import org.openecomp.sdc.be.resources.data.InputValueData;
import org.openecomp.sdc.be.resources.data.InputsData;
+import org.openecomp.sdc.be.resources.data.PropertyValueData;
+import org.openecomp.sdc.be.resources.data.UniqueIdData;
import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.support.MergedBeanDefinitionPostProcessor;
import org.springframework.stereotype.Component;
+import org.yaml.snakeyaml.Yaml;
+import com.google.gson.Gson;
+import com.thinkaurelius.titan.core.TitanVertex;
+
+import fj.Function;
import fj.data.Either;
@Component("inputsBusinessLogic")
public class InputsBusinessLogic extends BaseBusinessLogic {
private static final String CREATE_INPUT = "CreateInput";
+ private static final String UPDATE_INPUT = "UpdateInput";
private static Logger log = LoggerFactory.getLogger(InputsBusinessLogic.class.getName());
- @Autowired
- private IResourceOperation resourceOperation = null;
-
- @javax.annotation.Resource
- private InputsOperation inputsOperation = null;
+
@javax.annotation.Resource
private PropertyOperation propertyOperation = null;
+
@Autowired
private ComponentsUtils componentsUtils;
+
+ private static final String GET_INPUT = "get_input";
+
+ private static String ASSOCIATING_INPUT_TO_PROP = "AssociatingInputToComponentInstanceProperty";
+ private Gson gson = new Gson();
+
/**
* associate inputs to a given component with paging
@@ -82,28 +120,64 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
* @param amount
* @return
*/
- public Either<List<InputDefinition>, ResponseFormat> getInputs(String userId, String componentId, String fromName,
- int amount) {
+ public Either<List<InputDefinition>, ResponseFormat> getInputs(String userId, String componentId, String fromName, int amount) {
Either<User, ResponseFormat> resp = validateUserExists(userId, "get Inputs", false);
if (resp.isRight()) {
return Either.right(resp.right().value());
}
-
- Either<List<InputDefinition>, StorageOperationStatus> inputsEitherRes = inputsOperation
- .getInputsOfComponent(componentId, fromName, amount);
- if (inputsEitherRes.isRight()) {
- if (inputsEitherRes.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
- return Either.left(new ArrayList<InputDefinition>());
- }
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(inputsEitherRes.right().value());
- log.debug("Failed to get inputs under component {}, error: {}", componentId, actionStatus.name());
+
+
+ ComponentParametersView filters = new ComponentParametersView();
+ filters.disableAll();
+ filters.setIgnoreInputs(false);
+
+ Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentEither = toscaOperationFacade.getToscaElement(componentId, filters);
+ if(getComponentEither.isRight()){
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
+ log.debug("Failed to found component {}, error: {}", componentId, actionStatus.name());
return Either.right(componentsUtils.getResponseFormat(actionStatus));
-
+
}
+ org.openecomp.sdc.be.model.Component component = getComponentEither.left().value();
+ List<InputDefinition> inputs = component.getInputs();
+
+ return Either.left(inputs);
- return Either.left(inputsEitherRes.left().value());
+ }
+
+ public Either<List<ComponentInstanceInput>, ResponseFormat> getComponentInstanceInputs(String userId, String componentId, String componentInstanceId,String fromName, int amount) {
+
+ Either<User, ResponseFormat> resp = validateUserExists(userId, "get Inputs", false);
+
+ if (resp.isRight()) {
+ return Either.right(resp.right().value());
+ }
+
+
+ ComponentParametersView filters = new ComponentParametersView();
+ filters.disableAll();
+ filters.setIgnoreInputs(false);
+ filters.setIgnoreComponentInstances(false);
+ filters.setIgnoreComponentInstancesInputs(false);
+
+ Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentEither = toscaOperationFacade.getToscaElement(componentId, filters);
+ if(getComponentEither.isRight()){
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
+ log.debug("Failed to found component {}, error: {}", componentId, actionStatus.name());
+ return Either.right(componentsUtils.getResponseFormat(actionStatus));
+
+ }
+ org.openecomp.sdc.be.model.Component component = getComponentEither.left().value();
+ Map<String, List<ComponentInstanceInput>> ciInputs = component.getComponentInstancesInputs();
+ if(!ciInputs.containsKey(componentInstanceId)){
+ ActionStatus actionStatus = ActionStatus.COMPONENT_INSTANCE_NOT_FOUND;
+ log.debug("Failed to found component instance inputs {}, error: {}", componentInstanceId, actionStatus.name());
+ return Either.right(componentsUtils.getResponseFormat(actionStatus));
+ }
+
+ return Either.left(ciInputs.get(componentInstanceId));
}
@@ -116,62 +190,239 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
* @return
*/
- public Either<List<ComponentInstanceProperty>, ResponseFormat> getComponentInstancePropertiesByInputId(
- String userId, String instanceId, String inputId) {
+ public Either<List<ComponentInstanceProperty>, ResponseFormat> getComponentInstancePropertiesByInputId(String userId, String componentId, String instanceId, String inputId) {
Either<User, ResponseFormat> resp = validateUserExists(userId, "get Properties by input", false);
if (resp.isRight()) {
return Either.right(resp.right().value());
}
+ String parentId = componentId;
+ org.openecomp.sdc.be.model.Component component = null;
+ ComponentParametersView filters = new ComponentParametersView();
+ filters.disableAll();
+ filters.setIgnoreComponentInstances(false);
+
+ if(!instanceId.equals(inputId)){
+
+
+ Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentEither = toscaOperationFacade.getToscaElement(parentId, filters);
+
+ if(getComponentEither.isRight()){
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
+ log.debug("Failed to found component {}, error: {}", parentId, actionStatus.name());
+ return Either.right(componentsUtils.getResponseFormat(actionStatus));
+
+ }
+ component = getComponentEither.left().value();
+ Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci ->ci.getUniqueId().equals(instanceId)).findAny();
+ if(ciOp.isPresent()){
+ parentId = ciOp.get().getComponentUid();
+ }
+
+ }
+
+ filters.setIgnoreInputs(false);
+
+ filters.setIgnoreComponentInstancesProperties(false);
+ filters.setIgnoreComponentInstancesInputs(false);
+ filters.setIgnoreProperties(false);
+
+ Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentEither = toscaOperationFacade.getToscaElement(parentId, filters);
+
+ if(getComponentEither.isRight()){
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
+ log.debug("Failed to found component {}, error: {}", parentId, actionStatus.name());
+ return Either.right(componentsUtils.getResponseFormat(actionStatus));
+
+ }
+ component = getComponentEither.left().value();
+
+ Optional<InputDefinition> op = component.getInputs().stream().filter(in -> in.getUniqueId().equals(inputId)).findFirst();
+ if(!op.isPresent()){
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
+ log.debug("Failed to found input {} under component {}, error: {}", inputId, parentId, actionStatus.name());
+ return Either.right(componentsUtils.getResponseFormat(actionStatus));
+ }
+
+ return Either.left(getComponentInstancePropertiesByInputId(component, inputId));
- Either<List<ComponentInstanceProperty>, StorageOperationStatus> propertiesEitherRes = inputsOperation
- .getComponentInstancePropertiesByInputId(instanceId, inputId);
- if (propertiesEitherRes.isRight()) {
+ }
+
+ public Either<InputDefinition, ResponseFormat> updateInputValue(ComponentTypeEnum componentType, String componentId, InputDefinition input, String userId, boolean shouldLockComp, boolean inTransaction) {
+
+ Either<InputDefinition, ResponseFormat> result = null;
+ org.openecomp.sdc.be.model.Component component = null;
+
+
+ try {
+ Either<User, ResponseFormat> resp = validateUserExists(userId, "get input", false);
- if (propertiesEitherRes.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
- return Either.left(new ArrayList<ComponentInstanceProperty>());
+ if (resp.isRight()) {
+ result = Either.right(resp.right().value());
+ return result;
}
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(propertiesEitherRes.right().value());
- log.debug("Failed to get inputs under component {}, error: {}", instanceId, actionStatus.name());
- return Either.right(componentsUtils.getResponseFormat(actionStatus));
+ ComponentParametersView componentParametersView = new ComponentParametersView();
+ componentParametersView.disableAll();
+ componentParametersView.setIgnoreInputs(false);
+ componentParametersView.setIgnoreUsers(false);
- }
+ Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(componentId, componentType, componentParametersView);
- return Either.left(propertiesEitherRes.left().value());
+ if (validateComponent.isRight()) {
+ result = Either.right(validateComponent.right().value());
+ return result;
+ }
+ component = validateComponent.left().value();
- }
+ if (shouldLockComp) {
+ Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, UPDATE_INPUT);
+ if (lockComponent.isRight()) {
+ result = Either.right(lockComponent.right().value());
+ return result;
+ }
+ }
- public Either<List<ComponentInstanceInput>, ResponseFormat> getInputsForComponentInput(String userId,
- String componentId, String inputId) {
- Either<User, ResponseFormat> resp = validateUserExists(userId, "get Inputs by input", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
+ Either<Boolean, ResponseFormat> canWork = validateCanWorkOnComponent(component, userId);
+ if (canWork.isRight()) {
+ result = Either.right(canWork.right().value());
+ return result;
+ }
- Either<List<ComponentInstanceInput>, StorageOperationStatus> inputsEitherRes = inputsOperation
- .getComponentInstanceInputsByInputId(componentId, inputId);
- if (inputsEitherRes.isRight()) {
+ Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes = getAllDataTypes(applicationDataTypeCache);
+ if (allDataTypes.isRight()) {
+ result = Either.right(allDataTypes.right().value());
+ return result;
+ }
- if (inputsEitherRes.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
- return Either.left(new ArrayList<ComponentInstanceInput>());
+ Map<String, DataTypeDefinition> dataTypes = allDataTypes.left().value();
+
+ Optional<InputDefinition> op = component.getInputs().stream().filter(in -> in.getUniqueId().equals(input.getUniqueId())).findFirst();
+ if(!op.isPresent()){
+ ActionStatus actionStatus = ActionStatus.COMPONENT_NOT_FOUND;
+ log.debug("Failed to found input {} under component {}, error: {}", input.getUniqueId(), componentId, actionStatus.name());
+ result = Either.right(componentsUtils.getResponseFormat(actionStatus));
+ return result;
+ }
+ InputDefinition currentInput = op.get();
+
+ String innerType = null;
+ String propertyType = currentInput.getType();
+ ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
+ log.debug("The type of the property {} is {}", currentInput.getUniqueId(), propertyType);
+
+ if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
+ SchemaDefinition def = currentInput.getSchema();
+ if (def == null) {
+ log.debug("Schema doesn't exists for property of type {}", type);
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
+ }
+ PropertyDataDefinition propDef = def.getProperty();
+ if (propDef == null) {
+ log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
+ }
+ innerType = propDef.getType();
}
+ // Specific Update Logic
+
+ Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, input.getDefaultValue(), true, innerType, allDataTypes.left().value());
+
+ String newValue = currentInput.getDefaultValue();
+ if (isValid.isRight()) {
+ Boolean res = isValid.right().value();
+ if (res == false) {
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT))));
+ }
+ } else {
+ Object object = isValid.left().value();
+ if (object != null) {
+ newValue = object.toString();
+ }
+ }
+
+ currentInput.setDefaultValue(newValue);
+
+ Either<InputDefinition, StorageOperationStatus> status = toscaOperationFacade.updateInputOfComponent(component, currentInput);
+
+ if(status.isRight()){
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status.right().value());
+ result = Either.right(componentsUtils.getResponseFormat(actionStatus, ""));
+ return result;
+ }
+
+
+ result = Either.left(status.left().value());
+
+ return result;
+
+
+ }finally {
+
+ if (false == inTransaction) {
+
+ if (result == null || result.isRight()) {
+ log.debug("Going to execute rollback on create group.");
+ titanDao.rollback();
+ } else {
+ log.debug("Going to execute commit on create group.");
+ titanDao.commit();
+ }
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(inputsEitherRes.right().value());
- log.debug("Failed to get inputs for input under component {}, error: {}", componentId, actionStatus.name());
- return Either.right(componentsUtils.getResponseFormat(actionStatus));
+ }
+ // unlock resource
+ if (shouldLockComp && component != null) {
+ graphLockOperation.unlockComponent(componentId, componentType.getNodeType());
+ }
+
+ }
- }
- return Either.left(inputsEitherRes.left().value());
+ }
+
+ public Either<List<ComponentInstanceInput>, ResponseFormat> getInputsForComponentInput(String userId, String componentId, String inputId) {
+ Either<User, ResponseFormat> resp = validateUserExists(userId, "get Properties by input", false);
+ if (resp.isRight()) {
+ return Either.right(resp.right().value());
+ }
+ String parentId = componentId;
+ org.openecomp.sdc.be.model.Component component = null;
+ ComponentParametersView filters = new ComponentParametersView();
+ filters.disableAll();
+ filters.setIgnoreComponentInstances(false);
+ filters.setIgnoreInputs(false);
+ filters.setIgnoreComponentInstancesInputs(false);
+ filters.setIgnoreProperties(false);
+
+ Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentEither = toscaOperationFacade.getToscaElement(parentId, filters);
+
+ if(getComponentEither.isRight()){
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
+ log.debug("Failed to found component {}, error: {}", parentId, actionStatus.name());
+ return Either.right(componentsUtils.getResponseFormat(actionStatus));
+
+ }
+ component = getComponentEither.left().value();
+
+ Optional<InputDefinition> op = component.getInputs().stream().filter(in -> in.getUniqueId().equals(inputId)).findFirst();
+ if(!op.isPresent()){
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
+ log.debug("Failed to found input {} under component {}, error: {}", inputId, parentId, actionStatus.name());
+ return Either.right(componentsUtils.getResponseFormat(actionStatus));
+ }
+
+ return Either.left(getComponentInstanceInputsByInputId(component, inputId));
}
- public Either<List<InputDefinition>, ResponseFormat> createMultipleInputs(String userId, String componentId,
- ComponentTypeEnum componentType, ComponentInstInputsMap componentInstInputsMapUi, boolean shouldLockComp,
- boolean inTransaction) {
+ public Either<List<InputDefinition>, ResponseFormat> createMultipleInputs(String userId, String componentId, ComponentTypeEnum componentType, ComponentInstInputsMap componentInstInputsMapUi, boolean shouldLockComp, boolean inTransaction) {
Either<List<InputDefinition>, ResponseFormat> result = null;
org.openecomp.sdc.be.model.Component component = null;
+
+ Map<String, List<ComponentInstanceInput>> inputsValueToCreateMap = new HashMap<>();
+ Map<String, List<ComponentInstanceProperty>> propertiesToCreateMap = new HashMap<>();
+ Map<String, InputDefinition> inputsToCreate = new HashMap<>();
+
try {
Either<User, ResponseFormat> resp = validateUserExists(userId, "get Properties by input", false);
@@ -180,15 +431,15 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
return result;
}
- User user = resp.left().value();
ComponentParametersView componentParametersView = new ComponentParametersView();
componentParametersView.disableAll();
- componentParametersView.setIgnoreGroups(false);
- componentParametersView.setIgnoreArtifacts(false);
+ componentParametersView.setIgnoreInputs(false);
+ componentParametersView.setIgnoreComponentInstancesInputs(false);
+ componentParametersView.setIgnoreComponentInstances(false);
+ componentParametersView.setIgnoreComponentInstancesProperties(false);
componentParametersView.setIgnoreUsers(false);
- Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(
- componentId, componentType, componentParametersView, userId, null, user);
+ Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(componentId, componentType, componentParametersView);
if (validateComponent.isRight()) {
result = Either.right(validateComponent.right().value());
@@ -210,40 +461,120 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
return result;
}
- Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes = getAllDataTypes(
- applicationDataTypeCache);
+ Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes = getAllDataTypes(applicationDataTypeCache);
if (allDataTypes.isRight()) {
result = Either.right(allDataTypes.right().value());
return result;
}
Map<String, DataTypeDefinition> dataTypes = allDataTypes.left().value();
-
- Either<List<InputDefinition>, StorageOperationStatus> createInputsResult = this.inputsOperation
- .addInputsToComponent(componentId, componentType.getNodeType(), componentInstInputsMapUi,
- dataTypes);
-
- if (createInputsResult.isRight()) {
- ActionStatus actionStatus = componentsUtils
- .convertFromStorageResponse(createInputsResult.right().value());
- log.debug("Failed to create inputs under component {}, error: {}", componentId, actionStatus.name());
- result = Either.right(componentsUtils.getResponseFormat(actionStatus));
+ Map<String, org.openecomp.sdc.be.model.Component> origComponentMap = new HashMap<>();
+
+
+ //////////////////////////////////////////////////////////////////////////////////////////////////////
+
+ List<InputDefinition> resList = new ArrayList<InputDefinition>();
+ Map<String, List<InputDefinition>> newInputsMap = componentInstInputsMapUi.getComponentInstanceInputsMap();
+ List<ComponentInstance> ciList = component.getComponentInstances();
+ if (newInputsMap != null && !newInputsMap.isEmpty()) {
+ int index = 0;
+ for (Entry<String, List<InputDefinition>> entry : newInputsMap.entrySet()) {
+ List<ComponentInstanceInput> inputsValueToCreate = new ArrayList<>();
+ String compInstId = entry.getKey();
+
+ Optional<ComponentInstance> op = ciList.stream().filter(ci -> ci.getUniqueId().equals(compInstId)).findAny();
+ if(!op.isPresent()){
+ ActionStatus actionStatus = ActionStatus.INVALID_CONTENT;
+ log.debug("Failed to find component instance {} under component {}", compInstId, componentId);
+ result = Either.right(componentsUtils.getResponseFormat(actionStatus));
+ return result;
+ }
+ ComponentInstance ci = op.get();
+ String compInstname = ci.getNormalizedName();
+ Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> origComponentEither = getOriginComponent(ci, origComponentMap);
+ if(origComponentEither.isRight()){
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(origComponentEither.right().value());
+ log.debug("Failed to create inputs value under component {}, error: {}", componentId, actionStatus.name());
+ result = Either.right(componentsUtils.getResponseFormat(actionStatus));
+ return result;
+ }
+ org.openecomp.sdc.be.model.Component origComponent = origComponentEither.left().value();
+
+ List<InputDefinition> inputs = entry.getValue();
+
+ if (inputs != null && !inputs.isEmpty()) {
+
+ for (InputDefinition input : inputs) {
+
+ StorageOperationStatus status = addInputsToComponent(componentId, inputsToCreate, allDataTypes.left().value(), resList, index, inputsValueToCreate, compInstId, compInstname, origComponent, input);
+ if(status != StorageOperationStatus.OK ){
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(status);
+ log.debug("Failed to create inputs value under component {}, error: {}", componentId, actionStatus.name());
+ result = Either.right(componentsUtils.getResponseFormat(actionStatus));
+ return result;
+ }
+
+ }
+ }
+ if(!inputsValueToCreate.isEmpty()){
+ inputsValueToCreateMap.put(compInstId, inputsValueToCreate);
+ }
+ }
+
+ }
+
+ Map<String, List<ComponentInstancePropInput>> newInputsPropsMap = componentInstInputsMapUi.getComponentInstanceProperties();
+ if (newInputsPropsMap != null && !newInputsPropsMap.isEmpty()) {
+
+ result = createInputsFromProperty(component, origComponentMap, inputsToCreate, propertiesToCreateMap, dataTypes, resList, newInputsPropsMap);
+
+ if (result.isRight()) {
+ log.debug("Failed to create inputs of resource for id {} error {}", component.getUniqueId(), result.right().value());
+ return result;
+ }
+ resList = result.left().value();
+
+ }
+
+
+ Either<List<InputDefinition>, StorageOperationStatus> assotiateInputsEither = toscaOperationFacade.addInputsToComponent(inputsToCreate, component.getUniqueId());
+ if(assotiateInputsEither.isRight()){
+ log.debug("Failed to create inputs under component {}. Status is {}", component.getUniqueId(), assotiateInputsEither.right().value());
+ result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(assotiateInputsEither.right().value())));
return result;
-
}
- result = Either.left(createInputsResult.left().value());
-
+
+ Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> assotiatePropsEither = toscaOperationFacade.addComponentInstancePropertiesToComponent(component, propertiesToCreateMap, component.getUniqueId());
+ if(assotiatePropsEither.isRight()){
+ log.debug("Failed to add inputs values under component {}. Status is {}", component.getUniqueId(), assotiateInputsEither.right().value());
+ result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(assotiateInputsEither.right().value())));
+ return result;
+ }
+
+ Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addciInputsEither = toscaOperationFacade.addComponentInstanceInputsToComponent(inputsValueToCreateMap, component.getUniqueId());
+ if(addciInputsEither.isRight()){
+ log.debug("Failed to add inputs values under component {}. Status is {}", component.getUniqueId(), assotiateInputsEither.right().value());
+ result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(assotiateInputsEither.right().value())));
+ return result;
+ }
+
+
+
+
+ result = Either.left(resList);
return result;
+ ///////////////////////////////////////////////////////////////////////////////////////////
+
} finally {
if (false == inTransaction) {
if (result == null || result.isRight()) {
log.debug("Going to execute rollback on create group.");
- titanGenericDao.rollback();
+ titanDao.rollback();
} else {
log.debug("Going to execute commit on create group.");
- titanGenericDao.commit();
+ titanDao.commit();
}
}
@@ -256,9 +587,59 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
}
- public Either<List<InputDefinition>, ResponseFormat> createInputs(String componentId, String userId,
- ComponentTypeEnum componentType, List<InputDefinition> inputsDefinitions, boolean shouldLockComp,
- boolean inTransaction) {
+ private StorageOperationStatus addInputsToComponent(String componentId, Map<String, InputDefinition> inputsToCreate, Map<String, DataTypeDefinition> allDataTypes, List<InputDefinition> resList, int index,
+ List<ComponentInstanceInput> inputsValueToCreate, String compInstId, String compInstname, org.openecomp.sdc.be.model.Component origComponent, InputDefinition input) {
+
+ Either<List<InputDefinition>, ResponseFormat> result;
+ String innerType = null;
+ InputDefinition oldInput = origComponent.getInputs().stream().filter(ciIn -> ciIn.getUniqueId().equals(input.getUniqueId())).findAny().get();
+ String serviceInputName = compInstname + "_" + input.getName();
+ input.setName(serviceInputName);
+
+ JSONObject jobject = new JSONObject();
+ jobject.put(GET_INPUT, input.getName());
+
+ ComponentInstanceInput inputValue = new ComponentInstanceInput(oldInput, jobject.toJSONString(), null);
+
+ Either<String, StorageOperationStatus> validatevalueEiter = validateInputValueBeforeCreate(inputValue, jobject.toJSONString(), false, innerType, allDataTypes);
+ if (validatevalueEiter.isRight()) {
+
+ return validatevalueEiter.right().value();
+ }
+
+ String uniqueId = UniqueIdBuilder.buildResourceInstanceInputValueUid(compInstId, index++);
+ inputValue.setUniqueId(uniqueId);
+ inputValue.setValue(validatevalueEiter.left().value());
+
+
+ input.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(componentId, input.getName()));
+ input.setSchema(oldInput.getSchema());
+ input.setDefaultValue(oldInput.getDefaultValue());
+ input.setConstraints(oldInput.getConstraints());
+ input.setDescription(oldInput.getDescription());
+ input.setHidden(oldInput.isHidden());
+ input.setImmutable(oldInput.isImmutable());
+ input.setDefinition(oldInput.isDefinition());
+ input.setRequired(oldInput.isRequired());
+ inputsToCreate.put(input.getName(), input);
+
+
+
+ List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
+ GetInputValueDataDefinition getInputValueDataDefinition = new GetInputValueDataDefinition();
+ getInputValueDataDefinition.setInputId(input.getUniqueId());
+ getInputValueDataDefinition.setInputName(input.getName());
+ getInputValues.add(getInputValueDataDefinition);
+ inputValue.setGetInputValues(getInputValues);
+
+ inputsValueToCreate.add(inputValue);
+ input.setInputs(inputsValueToCreate);
+
+ resList.add(input);
+ return StorageOperationStatus.OK;
+ }
+
+ public Either<List<InputDefinition>, ResponseFormat> createInputs(String componentId, String userId, ComponentTypeEnum componentType, List<InputDefinition> inputsDefinitions, boolean shouldLockComp, boolean inTransaction) {
Either<List<InputDefinition>, ResponseFormat> result = null;
@@ -268,8 +649,7 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
if (inputsDefinitions != null && false == inputsDefinitions.isEmpty()) {
if (shouldLockComp == true && inTransaction == true) {
- BeEcompErrorManager.getInstance().logInternalFlowError("createGroups",
- "Cannot lock component since we are inside a transaction", ErrorSeverity.ERROR);
+ BeEcompErrorManager.getInstance().logInternalFlowError("createGroups", "Cannot lock component since we are inside a transaction", ErrorSeverity.ERROR);
// Cannot lock component since we are in a middle of another
// transaction.
ActionStatus actionStatus = ActionStatus.INVALID_CONTENT;
@@ -285,8 +665,7 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
User user = validateUserExists.left().value();
- Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(
- componentId, componentType, inTransaction, false);
+ Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(componentId, componentType, null);
if (validateComponent.isRight()) {
result = Either.right(validateComponent.right().value());
return result;
@@ -305,8 +684,9 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
result = Either.right(canWork.right().value());
return result;
}
+ Map<String, InputDefinition> inputs = inputsDefinitions.stream().collect(Collectors.toMap( o -> o.getName(), o -> o));
- result = createInputsInGraph(inputsDefinitions, component, user, inTransaction);
+ result = createInputsInGraph(inputs, component, user, inTransaction);
}
return result;
@@ -317,10 +697,10 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
if (result == null || result.isRight()) {
log.debug("Going to execute rollback on create group.");
- titanGenericDao.rollback();
+ titanDao.rollback();
} else {
log.debug("Going to execute commit on create group.");
- titanGenericDao.commit();
+ titanDao.commit();
}
}
@@ -333,66 +713,99 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
}
- public Either<List<InputDefinition>, ResponseFormat> createInputsInGraph(List<InputDefinition> inputsDefinitions,
- org.openecomp.sdc.be.model.Component component, User user, boolean inTransaction) {
- Either<List<InputDefinition>, ResponseFormat> result;
- List<InputDefinition> inputs = new ArrayList<InputDefinition>();
- for (InputDefinition inputDefinition : inputsDefinitions) {
- // String resourceId, String inputName, InputDefinition
- // newInputDefinition, String userId, boolean inTransaction
- Either<InputDefinition, ResponseFormat> createInput = createInput(component, user,
- component.getComponentType(), inputDefinition.getName(), inputDefinition, inTransaction);
- if (createInput.isRight()) {
- log.debug("Failed to create group {}.", createInput);
- result = Either.right(createInput.right().value());
- return result;
+ public Either<List<InputDefinition>, ResponseFormat> createInputsInGraph(Map<String, InputDefinition> inputs, org.openecomp.sdc.be.model.Component component, User user, boolean inTransaction) {
+
+ List<InputDefinition> resList = inputs.values().stream().collect(Collectors.toList());
+ Either<List<InputDefinition>, ResponseFormat> result = Either.left(resList);
+ List<InputDefinition> resourceProperties = component.getInputs();
+
+ if(inputs != null && !inputs.isEmpty()){
+ Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes = getAllDataTypes(applicationDataTypeCache);
+ if (allDataTypes.isRight()) {
+ return Either.right(allDataTypes.right().value());
+ }
+
+ Map<String, DataTypeDefinition> dataTypes = allDataTypes.left().value();
+
+ for (Map.Entry<String, InputDefinition> inputDefinition : inputs.entrySet()) {
+ String inputName = inputDefinition.getKey();
+ inputDefinition.getValue().setName(inputName);
+
+ Either<InputDefinition, ResponseFormat> preparedInputEither = prepareAndValidateInputBeforeCreate(inputDefinition.getValue(), dataTypes);
+ if(preparedInputEither.isRight()){
+ return Either.right(preparedInputEither.right().value());
+ }
+
+ }
+ if (resourceProperties != null) {
+ Map<String, InputDefinition> generatedInputs = resourceProperties.stream().collect(Collectors.toMap(i -> i.getName(), i -> i));
+ Either<Map<String, InputDefinition>, String> mergeEither = PropertyDataDefinition.mergeProperties(generatedInputs, inputs, false);
+ if(mergeEither.isRight()){
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_ALREADY_EXIST, mergeEither.right().value()));
+ }
+ inputs = mergeEither.left().value();
+ }
+
+ Either<List<InputDefinition>, StorageOperationStatus> assotiateInputsEither = toscaOperationFacade.createAndAssociateInputs(inputs, component.getUniqueId());
+ if(assotiateInputsEither.isRight()){
+ log.debug("Failed to create inputs under component {}. Status is {}", component.getUniqueId(), assotiateInputsEither.right().value());
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(assotiateInputsEither.right().value())));
}
- InputDefinition createdGroup = createInput.left().value();
- inputs.add(createdGroup);
+ result = Either.left(assotiateInputsEither.left().value());
+
}
- result = Either.left(inputs);
+
+
return result;
}
/**
* Delete input from service
*
- * @param component
- * @param user
* @param componentType
* @param inputId
- * @param inTransaction
+ * @param component
+ * @param user
+ *
* @return
*/
- public Either<InputDefinition, ResponseFormat> deleteInput(String componentType, String componentId, String userId, String inputId, boolean inTransaction) {
+ public Either<InputDefinition, ResponseFormat> deleteInput(String componentType, String componentId, String userId, String inputId) {
+ Either<InputDefinition, ResponseFormat> deleteEither = null;
if (log.isDebugEnabled())
log.debug("Going to delete input id: {}", inputId);
// Validate user (exists)
Either<User, ResponseFormat> userEither = validateUserExists(userId, "Delete input", true);
if (userEither.isRight()) {
- return Either.right(userEither.right().value());
+ deleteEither = Either.right(userEither.right().value());
+ return deleteEither;
}
// Get component using componentType, componentId
- Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentEither = serviceOperation.getComponent(componentId, true);
+
+ ComponentParametersView componentParametersView = new ComponentParametersView();
+ componentParametersView.disableAll();
+ componentParametersView.setIgnoreInputs(false);
+ componentParametersView.setIgnoreComponentInstances(false);
+ componentParametersView.setIgnoreComponentInstancesInputs(false);
+ componentParametersView.setIgnoreComponentInstancesProperties(false);
+ componentParametersView.setIgnoreUsers(false);
+
+ Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentEither = toscaOperationFacade.getToscaElement(componentId, componentParametersView);
if (componentEither.isRight()) {
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(componentEither.right().value())));
+ deleteEither = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(componentEither.right().value())));
+ return deleteEither;
}
org.openecomp.sdc.be.model.Component component = componentEither.left().value();
// Validate inputId is child of the component
- // And get the inputDefinition for the response
- InputDefinition inputDefinition = null;
Optional<InputDefinition> optionalInput = component.getInputs().stream().
// filter by ID
filter(input -> input.getUniqueId().equals(inputId)).
// Get the input
findAny();
- if (optionalInput.isPresent()) {
- inputDefinition = optionalInput.get();
- } else {
+ if (!optionalInput.isPresent()) {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.INPUT_IS_NOT_CHILD_OF_COMPONENT, inputId, componentId));
}
@@ -400,75 +813,118 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
Either<Boolean, ResponseFormat> lockResultEither = lockComponent(componentId, component, "deleteInput");
if (lockResultEither.isRight()) {
ResponseFormat responseFormat = lockResultEither.right().value();
- return Either.right(responseFormat);
+ deleteEither = Either.right(responseFormat);
+ return deleteEither;
}
// Delete input operations
- Either<String, StorageOperationStatus> deleteEither = Either.right(StorageOperationStatus.GENERAL_ERROR);
+
+ InputDefinition inputForDelete = optionalInput.get();
try {
- deleteEither = inputsOperation.deleteInput(inputId);
- if (deleteEither.isRight()){
+ StorageOperationStatus status = toscaOperationFacade.deleteInputOfResource(component, inputForDelete.getName());
+ if(status != StorageOperationStatus.OK){
log.debug("Component id: {} delete input id: {} failed", componentId, inputId);
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteEither.right().value()), component.getName()));
+ deleteEither = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), component.getName()));
+ return deleteEither;
}
- return Either.left(inputDefinition);
+
+ List<ComponentInstanceInput> inputsValue= getComponentInstanceInputsByInputId(component, inputId);
+ Map<String, List<ComponentInstanceInput>> insInputsMatToDelete = new HashMap<>();
+
+ if(inputsValue != null && !inputsValue.isEmpty()){
+ for(ComponentInstanceInput inputValue: inputsValue){
+ List<ComponentInstanceInput> inputList = null;
+ String ciId = inputValue.getComponentInstanceId();
+ if(!insInputsMatToDelete.containsKey(ciId)){
+ inputList = new ArrayList<>();
+ }else{
+ inputList = insInputsMatToDelete.get(ciId);
+ }
+ inputList.add(inputValue);
+ insInputsMatToDelete.put(ciId, inputList);
+ }
+ status = toscaOperationFacade.deleteComponentInstanceInputsToComponent(insInputsMatToDelete, component.getUniqueId());
+ if(status != StorageOperationStatus.OK){
+ log.debug("Component id: {} delete component instance input id: {} failed", componentId, inputId);
+ deleteEither = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), component.getName()));
+ return deleteEither;
+ }
+ }
+
+ // US848813 delete service input that relates to VL / CP property
+
+ List<ComponentInstanceProperty> propertiesValue = getComponentInstancePropertiesByInputId(component, inputId);
+ if(propertiesValue != null && !propertiesValue.isEmpty()){
+ //propertyList = propertyValueStatus.left().value();
+ for(ComponentInstanceProperty propertyValue: propertiesValue){
+
+ String value = propertyValue.getValue();
+ Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(value);
+
+ resetInputName(mappedToscaTemplate, inputForDelete.getName());
+
+ value = gson.toJson(mappedToscaTemplate);
+ propertyValue.setValue(value);
+ String compInstId = propertyValue.getComponentInstanceId();
+ propertyValue.setRules(null);
+ List<GetInputValueDataDefinition> getInputsValues = propertyValue.getGetInputValues();
+ if(getInputsValues != null && !getInputsValues.isEmpty()){
+ Optional<GetInputValueDataDefinition> op = getInputsValues.stream().filter(gi -> gi.getInputId().equals(inputForDelete.getUniqueId())).findAny();
+ if(op.isPresent()){
+ getInputsValues.remove(op.get());
+ }
+ }
+ propertyValue.setGetInputValues(getInputsValues);
+ if(status != StorageOperationStatus.OK){
+ log.debug("Component id: {} delete component instance property {} id: {} failed", componentId, propertyValue.getUniqueId(), inputId);
+ deleteEither = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), component.getName()));
+ return deleteEither;
+ }
+ Either<String, TitanOperationStatus> findDefaultValue = propertyOperation.findDefaultValueFromSecondPosition(propertyValue.getPath(), propertyValue.getUniqueId(), propertyValue.getDefaultValue());
+ if (findDefaultValue.isRight()) {
+ deleteEither = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(findDefaultValue.right().value()))));
+ return deleteEither;
+
+ }
+ String defaultValue = findDefaultValue.left().value();
+ propertyValue.setDefaultValue(defaultValue);
+ log.debug("The returned default value in ResourceInstanceProperty is {}", defaultValue);
+ status = toscaOperationFacade.updateComponentInstanceProperty(component, compInstId, propertyValue);
+ if(status != StorageOperationStatus.OK){
+ log.debug("Component id: {} update component instance property {} id: {} failed", componentId, propertyValue.getUniqueId(), inputId);
+ deleteEither = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), component.getName()));
+ return deleteEither;
+ }
+
+ }
+ }
+
+
+ deleteEither = Either.left(inputForDelete);
+ return deleteEither;
} finally {
- if (deleteEither.isRight()) {
+ if (deleteEither == null || deleteEither.isRight()) {
log.debug("Component id: {} delete input id: {} failed", componentId, inputId);
- titanGenericDao.rollback();
+ titanDao.rollback();
} else {
log.debug("Component id: {} delete input id: {} success", componentId, inputId);
- titanGenericDao.commit();
+ titanDao.commit();
}
unlockComponent(deleteEither, component);
}
}
- /**
- * Create new property on resource in graph
- *
- * @param resourceId
- * @param propertyName
- * @param newPropertyDefinition
- * @param userId
- * @return Either<PropertyDefinition, ActionStatus>
- */
-
- private Either<InputDefinition, ResponseFormat> createInput(org.openecomp.sdc.be.model.Component component,
- User user, ComponentTypeEnum componentType, String inputName, InputDefinition newInputDefinition,
- boolean inTransaction) {
-
- Either<InputDefinition, ResponseFormat> result = null;
- if (log.isDebugEnabled())
- log.debug("Going to create input {}", newInputDefinition);
-
- try {
-
- // verify property not exist in resource
- List<InputDefinition> resourceProperties = component.getInputs();
-
- if (resourceProperties != null) {
- if (inputsOperation.isInputExist(resourceProperties, component.getUniqueId(), inputName)) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_ALREADY_EXIST, ""));
- }
- }
+ private Either<InputDefinition, ResponseFormat> prepareAndValidateInputBeforeCreate(InputDefinition newInputDefinition, Map<String, DataTypeDefinition> dataTypes) {
+
- Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes = getAllDataTypes(
- applicationDataTypeCache);
- if (allDataTypes.isRight()) {
- return Either.right(allDataTypes.right().value());
- }
-
- Map<String, DataTypeDefinition> dataTypes = allDataTypes.left().value();
-
- // validate input default values
- Either<Boolean, ResponseFormat> defaultValuesValidation = validatePropertyDefaultValue(newInputDefinition,
- dataTypes);
- if (defaultValuesValidation.isRight()) {
- return Either.right(defaultValuesValidation.right().value());
- }
- // convert property
- ToscaPropertyType type = getType(newInputDefinition.getType());
+ // validate input default values
+ Either<Boolean, ResponseFormat> defaultValuesValidation = validatePropertyDefaultValue(newInputDefinition, dataTypes);
+ if (defaultValuesValidation.isRight()) {
+ return Either.right(defaultValuesValidation.right().value());
+ }
+ // convert property
+ ToscaPropertyType type = getType(newInputDefinition.getType());
+ if (type != null) {
PropertyValueConverter converter = type.getConverter();
// get inner type
String innerType = null;
@@ -482,29 +938,81 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
}
String convertedValue = null;
if (newInputDefinition.getDefaultValue() != null) {
- convertedValue = converter.convert(newInputDefinition.getDefaultValue(), innerType,
- allDataTypes.left().value());
+ convertedValue = converter.convert(newInputDefinition.getDefaultValue(), innerType, dataTypes);
newInputDefinition.setDefaultValue(convertedValue);
}
}
+ }
+ return Either.left(newInputDefinition);
+ }
+
+ public boolean isInputExist(List<InputDefinition> inputs, String resourceUid, String inputName) {
+
+ if (inputs == null) {
+ return false;
+ }
+
+ for (InputDefinition propertyDefinition : inputs) {
+ String parentUniqueId = propertyDefinition.getParentUniqueId();
+ String name = propertyDefinition.getName();
+
+ if (parentUniqueId.equals(resourceUid) && name.equals(inputName)) {
+ return true;
+ }
+ }
- // add the new property to resource on graph
- // need to get StorageOpaerationStatus and convert to ActionStatus
- // from componentsUtils
- Either<InputsData, StorageOperationStatus> either = inputsOperation.addInput(inputName, newInputDefinition,
- component.getUniqueId(), componentType.getNodeType());
- if (either.isRight()) {
- return Either.right(componentsUtils.getResponseFormat(
- componentsUtils.convertFromStorageResponse(either.right().value()), component.getName()));
+ return false;
+
+ }
+
+
+ public Either<InputDefinition, ResponseFormat> getInputsAndPropertiesForComponentInput(String userId, String componentId, String inputId, boolean inTransaction) {
+ Either<InputDefinition, ResponseFormat> result = null;
+ try {
+
+ Either<User, ResponseFormat> resp = validateUserExists(userId, "get Properties by input", false);
+ if (resp.isRight()) {
+ return Either.right(resp.right().value());
}
- // @TODO commit
- // inputsOperation.getTitanGenericDao().commit();
- InputDefinition createdInputyDefinition = inputsOperation
- .convertInputDataToInputDefinition(either.left().value());
- createdInputyDefinition.setName(inputName);
- createdInputyDefinition.setParentUniqueId(component.getUniqueId());
+ Either<List<ComponentInstanceProperty>, StorageOperationStatus> propertiesEitherRes = null;
+
+ ComponentParametersView filters = new ComponentParametersView();
+ filters.disableAll();
+ filters.setIgnoreComponentInstances(false);
+ filters.setIgnoreInputs(false);
+ filters.setIgnoreComponentInstancesInputs(false);
+ filters.setIgnoreComponentInstancesProperties(false);
+ filters.setIgnoreProperties(false);
+ Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentEither = toscaOperationFacade.getToscaElement(componentId, filters);
+ if(getComponentEither.isRight()){
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
+ log.debug("Failed to found component {}, error: {}", componentId, actionStatus.name());
+ return Either.right(componentsUtils.getResponseFormat(actionStatus));
+
+ }
+ org.openecomp.sdc.be.model.Component component = getComponentEither.left().value();
+ Optional<InputDefinition> op = component.getInputs().stream().filter(in -> in.getUniqueId().equals(inputId)).findFirst();
+ if(!op.isPresent()){
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
+ log.debug("Failed to found input {} under component {}, error: {}", inputId, componentId, actionStatus.name());
+ return Either.right(componentsUtils.getResponseFormat(actionStatus));
+ }
+
+ InputDefinition resObj = op.get();
+
+ List<ComponentInstanceInput> inputCIInput = getComponentInstanceInputsByInputId(component, inputId) ;
+
+ resObj.setInputs(inputCIInput);
+
+
+ List<ComponentInstanceProperty> inputProps = getComponentInstancePropertiesByInputId(component, inputId) ;
+
+ resObj.setProperties(inputProps);
+
+
+ result = Either.left(resObj);
- return Either.left(createdInputyDefinition);
+ return result;
} finally {
@@ -512,10 +1020,10 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
if (result == null || result.isRight()) {
log.debug("Going to execute rollback on create group.");
- titanGenericDao.rollback();
+ titanDao.rollback();
} else {
log.debug("Going to execute commit on create group.");
- titanGenericDao.commit();
+ titanDao.commit();
}
}
@@ -523,4 +1031,318 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
}
}
+
+ private List<ComponentInstanceProperty> getComponentInstancePropertiesByInputId(org.openecomp.sdc.be.model.Component component, String inputId){
+ List<ComponentInstanceProperty> resList = new ArrayList<>();
+ Map<String, List<ComponentInstanceProperty>> ciPropertiesMap = component.getComponentInstancesProperties();
+ if(ciPropertiesMap != null && !ciPropertiesMap.isEmpty()){
+ ciPropertiesMap.forEach(new BiConsumer<String, List<ComponentInstanceProperty>>() {
+ @Override
+ public void accept(String s, List<ComponentInstanceProperty> ciPropList) {
+ String ciName = "";
+ Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci ->ci.getUniqueId().equals(s)).findAny();
+ if(ciOp.isPresent())
+ ciName = ciOp.get().getName();
+ if (ciPropList != null && !ciPropList.isEmpty()) {
+ for(ComponentInstanceProperty prop: ciPropList){
+ List<GetInputValueDataDefinition> inputsValues = prop.getGetInputValues();
+ if(inputsValues != null && !inputsValues.isEmpty()){
+ for(GetInputValueDataDefinition inputData: inputsValues){
+ if(inputData.getInputId().equals(inputId) || (inputData.getGetInputIndex() != null && inputData.getGetInputIndex().getInputId().equals(inputId))){
+ prop.setComponentInstanceId(s);
+ prop.setComponentInstanceName(ciName);
+ resList.add(prop);
+ break;
+ }
+ }
+ }
+
+ }
+ }
+ }
+ });
+ }
+ return resList;
+
+ }
+
+ private List<ComponentInstanceInput> getComponentInstanceInputsByInputId(org.openecomp.sdc.be.model.Component component, String inputId){
+ List<ComponentInstanceInput> resList = new ArrayList<>();
+ Map<String, List<ComponentInstanceInput>> ciInputsMap = component.getComponentInstancesInputs();
+ if(ciInputsMap != null && !ciInputsMap.isEmpty()){
+ ciInputsMap.forEach(new BiConsumer<String, List<ComponentInstanceInput>>() {
+ @Override
+ public void accept(String s, List<ComponentInstanceInput> ciPropList) {
+ String ciName = "";
+ Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci ->ci.getUniqueId().equals(s)).findAny();
+ if(ciOp.isPresent())
+ ciName = ciOp.get().getName();
+ if (ciPropList != null && !ciPropList.isEmpty()) {
+ for(ComponentInstanceInput prop: ciPropList){
+ List<GetInputValueDataDefinition> inputsValues = prop.getGetInputValues();
+ if(inputsValues != null && !inputsValues.isEmpty()){
+ for(GetInputValueDataDefinition inputData: inputsValues){
+ if(inputData.getInputId().equals(inputId) || (inputData.getGetInputIndex() != null && inputData.getGetInputIndex().getInputId().equals(inputId))){
+ prop.setComponentInstanceId(s);
+ prop.setComponentInstanceName(ciName);
+ resList.add(prop);
+ break;
+ }
+ }
+ }
+
+ }
+ }
+ }
+ });
+ }
+ return resList;
+
+ }
+
+ private Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getOriginComponent(ComponentInstance ci, Map<String, org.openecomp.sdc.be.model.Component> origComponentMap){
+ Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> result = null;
+ String compInstname = ci.getNormalizedName();
+
+ ComponentParametersView componentParametersView = new ComponentParametersView();
+ componentParametersView.disableAll();
+ componentParametersView.setIgnoreInputs(false);
+ org.openecomp.sdc.be.model.Component origComponent = null;
+ if(!origComponentMap.containsKey(ci.getComponentUid())){
+ Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentFound = toscaOperationFacade.getToscaElement(ci.getComponentUid(), componentParametersView);
+
+ if (componentFound.isRight()) {
+ result = Either.right(componentFound.right().value());
+ return result;
+ }
+ origComponent = componentFound.left().value();
+ origComponentMap.put(origComponent.getUniqueId(), origComponent);
+ }else{
+ origComponent = origComponentMap.get(ci.getComponentUid());
+ }
+ result = Either.left(origComponent);
+ return result;
+ }
+
+
+
+ private Either<List<InputDefinition>, ResponseFormat> createInputsFromProperty(org.openecomp.sdc.be.model.Component component, Map<String, org.openecomp.sdc.be.model.Component> origComponentMap, Map<String, InputDefinition> inputsToCreate, Map<String, List<ComponentInstanceProperty>> propertiesToCreateMap, Map<String, DataTypeDefinition> dataTypes, List<InputDefinition> resList, Map<String, List<ComponentInstancePropInput>> newInputsPropsMap) {
+ List<ComponentInstance> ciList = component.getComponentInstances();
+ String componentId = component.getUniqueId();
+ for (Entry<String, List<ComponentInstancePropInput>> entry : newInputsPropsMap.entrySet()) {
+ List<ComponentInstanceProperty> propertiesToCreate = new ArrayList<>();
+ String compInstId = entry.getKey();
+ List<ComponentInstancePropInput> properties = entry.getValue();
+
+ Optional<ComponentInstance> op = ciList.stream().filter(ci -> ci.getUniqueId().equals(compInstId)).findAny();
+ if(!op.isPresent()){
+ ActionStatus actionStatus = ActionStatus.INVALID_CONTENT;
+ log.debug("Failed to find component instance {} under component {}", compInstId, componentId);
+ return Either.right(componentsUtils.getResponseFormat(actionStatus));
+
+ }
+ ComponentInstance ci = op.get();
+ String compInstname = ci.getNormalizedName();
+ Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> origComponentEither = getOriginComponent(ci, origComponentMap);
+ if(origComponentEither.isRight()){
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(origComponentEither.right().value());
+ log.debug("Failed to create inputs value under component {}, error: {}", componentId, actionStatus.name());
+ return Either.right(componentsUtils.getResponseFormat(actionStatus));
+
+ }
+ org.openecomp.sdc.be.model.Component origComponent = origComponentEither.left().value();
+
+
+ //String originType = (String) titanGenericDao.getProperty(originVertex, GraphPropertiesDictionary.LABEL.getProperty());
+
+ String inputName = compInstname;
+
+ if (properties != null && !properties.isEmpty()) {
+ for (ComponentInstancePropInput propInput : properties) {
+ Either<InputDefinition, StorageOperationStatus> createInputRes = createInputForComponentInstance(component, origComponent,ci, inputsToCreate, propertiesToCreate, dataTypes, inputName, propInput);
+
+ if (createInputRes.isRight()) {
+ log.debug("Failed to create input of resource instance for id {} error {}", compInstId, createInputRes.right().value());
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createInputRes.right().value())));
+
+ }
+
+ resList.add(createInputRes.left().value());
+
+ }
+ propertiesToCreateMap.put(compInstId, propertiesToCreate);
+ }
+
+ }
+ return Either.left(resList);
+ }
+
+ private Either<InputDefinition, StorageOperationStatus> createInputForComponentInstance(org.openecomp.sdc.be.model.Component component,org.openecomp.sdc.be.model.Component orignComponent, ComponentInstance ci, Map<String, InputDefinition> inputsToCreate, List<ComponentInstanceProperty> propertiesToCreate, Map<String, DataTypeDefinition> dataTypes, String inputName, ComponentInstancePropInput propInput) {
+ String propertiesName = propInput.getPropertiesName() ;
+ PropertyDefinition selectedProp = propInput.getInput();
+ String[] parsedPropNames = propInput.getParsedPropNames();
+
+ if(parsedPropNames != null){
+ for(String str: parsedPropNames){
+ inputName += "_" + str;
+ }
+ } else {
+ inputName += "_" + propInput.getName();
+ }
+
+ InputDefinition input = null;
+ ComponentInstanceProperty prop = propInput;
+
+ if(propertiesName != null && !propertiesName.isEmpty() && selectedProp != null){
+ input = new InputDefinition(selectedProp);
+ }else{
+ input = new InputDefinition(prop);
+ input.setName(inputName + "_" + prop.getName());
+
+ }
+ input.setName(inputName);
+ input.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(component.getUniqueId(), input.getName()));
+ input.setInputPath(propertiesName);
+
+ JSONObject jobject = new JSONObject();
+
+
+ if(prop.getValue() == null || prop.getValue().isEmpty()){
+ if(propertiesName != null && !propertiesName.isEmpty() && selectedProp != null){
+
+ jobject = createJSONValueForProperty(parsedPropNames.length -1, parsedPropNames, jobject, inputName);
+ prop.setValue(jobject.toJSONString());
+
+ }else{
+
+ jobject.put(GET_INPUT, input.getName());
+ prop.setValue(jobject.toJSONString());
+
+ }
+
+ }else{
+
+ String value = prop.getValue();
+ Object objValue = new Yaml().load(value);
+ if( objValue instanceof Map || objValue instanceof List ){
+ if(propertiesName == null ||propertiesName.isEmpty()){
+ jobject.put(GET_INPUT, input.getName());
+ prop.setValue(jobject.toJSONString());
+ prop.setRules(null);
+
+ }else{
+ Map<String, Object> mappedToscaTemplate = (Map<String, Object>) objValue;
+ createInputValue(mappedToscaTemplate, 1, parsedPropNames, inputName);
+
+ String json = gson.toJson(mappedToscaTemplate);
+ prop.setValue(json);
+ prop.setRules(null);
+ }
+
+ }else{
+ jobject.put(GET_INPUT, input.getName());
+ prop.setValue(jobject.toJSONString());
+ prop.setRules(null);
+ }
+
+ }
+ prop.setComponentInstanceId(ci.getUniqueId());
+ prop.setComponentInstanceName(ci.getName());
+
+ List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
+ GetInputValueDataDefinition getInputValueDataDefinition = new GetInputValueDataDefinition();
+ getInputValueDataDefinition.setInputId(input.getUniqueId());
+ getInputValueDataDefinition.setInputName(input.getName());
+ getInputValues.add(getInputValueDataDefinition);
+ prop.setGetInputValues(getInputValues);
+
+ propertiesToCreate.add(prop);
+
+ inputsToCreate.put(input.getName(), input);
+
+ return Either.left(input);
+
+ }
+
+ private JSONObject createJSONValueForProperty (int i, String [] parsedPropNames, JSONObject ooj, String inputName){
+
+ while(i >= 1){
+ if( i == parsedPropNames.length -1){
+ JSONObject jobProp = new JSONObject();
+ jobProp.put(GET_INPUT, inputName);
+ ooj.put(parsedPropNames[i], jobProp);
+ i--;
+ return createJSONValueForProperty (i, parsedPropNames, ooj, inputName);
+ }else{
+ JSONObject res = new JSONObject();
+ res.put(parsedPropNames[i], ooj);
+ i --;
+ res = createJSONValueForProperty (i, parsedPropNames, res, inputName);
+ return res;
+ }
+ }
+
+ return ooj;
+ }
+
+ public void resetInputName(Map<String, Object> lhm1, String inputName){
+ for (Map.Entry<String, Object> entry : lhm1.entrySet()) {
+ String key = entry.getKey();
+ Object value = entry.getValue();
+ if (value instanceof String && ((String) value).equalsIgnoreCase(inputName) && key.equals(GET_INPUT)) {
+ value = "";
+ lhm1.remove(key);
+ } else if (value instanceof Map) {
+ Map<String, Object> subMap = (Map<String, Object>)value;
+ resetInputName(subMap, inputName);
+ } else {
+ continue;
+ }
+
+ }
+ }
+
+ private Map<String, Object> createInputValue(Map<String, Object> lhm1, int index, String[] inputNames, String inputName){
+ while(index < inputNames.length){
+ if(lhm1.containsKey(inputNames[index])){
+ Object value = lhm1.get(inputNames[index]);
+ if (value instanceof Map){
+ if(index == inputNames.length -1){
+ ((Map) value).put(GET_INPUT, inputName);
+ return ((Map) value);
+
+ }else{
+ index++;
+ return createInputValue((Map)value, index, inputNames, inputName);
+ }
+ }else{
+ Map<String, Object> jobProp = new HashMap<>();
+ if(index == inputNames.length -1){
+ jobProp.put(GET_INPUT, inputName);
+ lhm1.put(inputNames[index], jobProp);
+ return lhm1;
+ }else{
+ lhm1.put(inputNames[index], jobProp);
+ index++;
+ return createInputValue(jobProp, index, inputNames, inputName);
+ }
+ }
+ }else{
+ Map<String, Object> jobProp = new HashMap<>();
+ lhm1.put(inputNames[index], jobProp);
+ if(index == inputNames.length -1){
+ jobProp.put(GET_INPUT, inputName);
+ return jobProp;
+ }else{
+ index++;
+ return createInputValue(jobProp, index, inputNames, inputName);
+ }
+ }
+ }
+ return lhm1;
+ }
+
+
+
+
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceLifecycleTypeImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceLifecycleTypeImportManager.java
index 780980ba08..e7d051290f 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceLifecycleTypeImportManager.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceLifecycleTypeImportManager.java
@@ -113,7 +113,7 @@ public class InterfaceLifecycleTypeImportManager {
operation.setDescription((String) opProp.get("description"));
operations.put(entry.getKey(), operation);
}
- interfaceDef.setOperations(operations);
+ interfaceDef.setOperationsMap(operations);
return interfaceDef;
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductBusinessLogic.java
index 3a54513b0b..96f7eec2d8 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductBusinessLogic.java
@@ -28,7 +28,6 @@ import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
-import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.datamodel.api.CategoryTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
@@ -40,6 +39,7 @@ import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.model.category.CategoryDefinition;
import org.openecomp.sdc.be.model.category.GroupingDefinition;
import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
import org.openecomp.sdc.be.model.operations.api.ICacheMangerOperation;
import org.openecomp.sdc.be.model.operations.api.IElementOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
@@ -47,9 +47,9 @@ import org.openecomp.sdc.be.model.operations.impl.ProductOperation;
import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer;
import org.openecomp.sdc.be.user.Role;
import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.config.EcompErrorName;
import org.openecomp.sdc.common.util.ValidationUtils;
import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
@@ -89,6 +89,9 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
@Autowired
private ICacheMangerOperation cacheManagerOperation;
+
+ @Autowired
+ ToscaOperationFacade toscaOperationFacade;
public Either<Product, ResponseFormat> createProduct(Product product, User user) {
AuditingActionEnum actionEnum = AuditingActionEnum.CREATE_RESOURCE;
@@ -136,7 +139,7 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
log.debug("Product name locked is {}, status = {}", product.getSystemName(), lockResult);
try {
- Either<Product, StorageOperationStatus> createProductEither = productOperation.createProduct(product);
+ Either<Product, StorageOperationStatus> createProductEither = toscaOperationFacade.createToscaComponent(product);
if (createProductEither.isRight()) {
ResponseFormat responseFormat = componentsUtils.getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(createProductEither.right().value()), product, typeEnum);
@@ -259,8 +262,10 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
return Either.right(resp.right().value());
}
- Either<Boolean, StorageOperationStatus> dataModelResponse = productOperation.validateComponentNameExists(productName);
-
+ Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade.validateComponentNameUniqueness(productName, null, ComponentTypeEnum.PRODUCT);
+ // DE242223
+ titanDao.commit();
+
if (dataModelResponse.isLeft()) {
Map<String, Boolean> result = new HashMap<>();
result.put("isValid", dataModelResponse.left().value());
@@ -325,7 +330,7 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
contacts.add(modifierUserId);
}
- // passed - setting all contacts user ids to lowercase
+ // passed - setting all contacts userIds to lowercase
List<String> tempContacts = contacts.stream().map(e -> e.toLowerCase()).collect(Collectors.toList());
ValidationUtils.removeDuplicateFromList(tempContacts);
product.setContacts(tempContacts);
@@ -336,7 +341,7 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
private Either<Boolean, ResponseFormat> validateGrouping(User user, Product product, AuditingActionEnum actionEnum) {
List<CategoryDefinition> categories = product.getCategories();
if (categories == null || categories.isEmpty()) {
- log.debug("Grouping list is empty for product {}", product.getName());
+ log.debug("Grouping list is empty for product: {}", product.getName());
return Either.left(true);
}
Map<String, Map<String, Set<String>>> nonDuplicatedCategories = new HashMap<String, Map<String, Set<String>>>();
@@ -345,7 +350,7 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
String catName = cat.getName();
if (ValidationUtils.validateStringNotEmpty(catName) == false) {
// error missing cat name
- log.debug("Missing category name for product {}", product.getName());
+ log.debug("Missing category name for product: {}", product.getName());
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.PRODUCT.getValue());
componentsUtils.auditComponentAdmin(responseFormat, user, product, "", "", actionEnum, ComponentTypeEnum.PRODUCT);
return Either.right(responseFormat);
@@ -382,7 +387,7 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
String groupName = group.getName();
if (ValidationUtils.validateStringNotEmpty(groupName) == false) {
// error missing grouping for sub cat name and cat
- log.debug("Missing or empty groupng name for sub-category {} for category {} in product {}", subCatName, catName, product.getName());
+ log.debug("Missing or empty groupng name for sub-category: {} for categor: {} in product: {}", subCatName, catName, product.getName());
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_SUBCATEGORY);
componentsUtils.auditComponentAdmin(responseFormat, user, product, "", "", actionEnum, ComponentTypeEnum.PRODUCT);
return Either.right(responseFormat);
@@ -390,7 +395,7 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
if (!subcatEntry.contains(groupName)) {
subcatEntry.add(groupName);
} else {
- log.debug("Grouping [ {} ] already exist for category [ {} ] and subcategory [ {} ]", groupName, catName, subCatName);
+ log.debug("Grouping: {}, already exist for category: {} and subcategory: {}", groupName, catName, subCatName);
}
}
}
@@ -495,7 +500,7 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
return Either.right(eitherCreator.right().value());
}
- Either<Product, StorageOperationStatus> storageStatus = productOperation.getComponent(productId, false);
+ Either<Product, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(productId);
if (storageStatus.isRight()) {
log.debug("failed to get resource by id {}", productId);
@@ -521,7 +526,7 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
return Either.right(eitherCreator.right().value());
}
- Either<Product, StorageOperationStatus> storageStatus = productOperation.deleteProduct(productId, false);
+ Either<Product, StorageOperationStatus> storageStatus = toscaOperationFacade.deleteToscaComponent(productId);
if (storageStatus.isRight()) {
log.debug("failed to delete resource by id {}", productId);
@@ -635,7 +640,7 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
return Either.right(responseFormat);
}
- Either<Product, StorageOperationStatus> storageStatus = productOperation.getComponent(productId, false);
+ Either<Product, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(productId);
if (storageStatus.isRight()) {
if (storageStatus.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.PRODUCT_NOT_FOUND, ComponentTypeEnum.PRODUCT.name().toLowerCase()));
@@ -645,8 +650,8 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
Product currentProduct = storageStatus.left().value();
- if (!ComponentValidationUtils.canWorkOnComponent(productId, productOperation, user.getUserId())) {
- log.info("Restricted operation for user {} on product {}", user.getUserId(), currentProduct.getCreatorUserId());
+ if (!ComponentValidationUtils.canWorkOnComponent(productId, toscaOperationFacade, user.getUserId())) {
+ log.info("Restricted operation for user: {}, on product: {}" , user.getUserId(), currentProduct.getCreatorUserId());
return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
}
@@ -663,14 +668,13 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
return Either.right(lockResult.right().value());
}
try {
- Either<Product, StorageOperationStatus> updateResponse = productOperation.updateComponent(productToUpdate, true);
+ Either<Product, StorageOperationStatus> updateResponse = toscaOperationFacade.updateToscaElement(productToUpdate);
if (updateResponse.isRight()) {
- productOperation.rollback();
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Update Product Metadata");
+ toscaOperationFacade.rollback();
log.debug("failed to update product {}", productToUpdate.getUniqueId());
return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
}
- productOperation.commit();
+ toscaOperationFacade.commit();
return Either.left(updateResponse.left().value());
} finally {
graphLockOperation.unlockComponent(productId, NodeTypeEnum.Product);
@@ -791,7 +795,6 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
private Either<Boolean, ResponseFormat> validateAndUpdateCategory(User user, Product currentProduct, Product updatedProduct) {
List<CategoryDefinition> categoryUpdated = updatedProduct.getCategories();
- List<CategoryDefinition> categoryCurrent = currentProduct.getCategories();
Either<Boolean, ResponseFormat> validatCategoryResponse = validateGrouping(user, updatedProduct, null);
if (validatCategoryResponse.isRight()) {
@@ -854,7 +857,7 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
if (resp.isRight()) {
return Either.right(resp.right().value());
}
- Either<Product, StorageOperationStatus> storageStatus = productOperation.getProductByNameAndVersion(productName, productVersion, false);
+ Either<Product, StorageOperationStatus> storageStatus = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.PRODUCT, productName, productVersion);
if (storageStatus.isRight()) {
log.debug("failed to get service by name {} and version {}", productName, productVersion);
return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.PRODUCT), productName));
@@ -881,7 +884,11 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
this.cacheManagerOperation = cacheManagerOperation;
}
- public void setProductOperation(ProductOperation productOperation) {
- this.productOperation = productOperation;
+ @Override
+ public Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String componentId,
+ List<String> dataParamsToReturn) {
+ // TODO Auto-generated method stub
+ return null;
}
+
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductComponentInstanceBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductComponentInstanceBusinessLogic.java
index 46188012d8..ab0969358c 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductComponentInstanceBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductComponentInstanceBusinessLogic.java
@@ -22,7 +22,6 @@ package org.openecomp.sdc.be.components.impl;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.model.operations.impl.ComponentOperation;
import org.openecomp.sdc.exception.ResponseFormat;
import org.springframework.stereotype.Component;
@@ -43,17 +42,9 @@ public class ProductComponentInstanceBusinessLogic extends ComponentInstanceBusi
}
@Override
- protected ComponentOperation getContainerComponentOperation() {
- return productOperation;
- }
-
- @Override
- protected ComponentOperation getCompInstOriginComponentOperation() {
- return serviceOperation;
- }
-
- @Override
protected ComponentTypeEnum getComponentTypeOfComponentInstance() {
+ // TODO Auto-generated method stub
return ComponentTypeEnum.SERVICE_INSTANCE;
}
+
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PropertyBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PropertyBusinessLogic.java
index 1e6b1c1d82..e0d531d622 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PropertyBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PropertyBusinessLogic.java
@@ -20,40 +20,60 @@
package org.openecomp.sdc.be.components.impl;
+import java.lang.reflect.Type;
+import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
+import java.util.function.Supplier;
import javax.servlet.ServletContext;
+import org.apache.commons.collections.CollectionUtils;
+import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.impl.WebAppContextWrapper;
import org.openecomp.sdc.be.model.DataTypeDefinition;
+import org.openecomp.sdc.be.model.IComplexDefaultValue;
+import org.openecomp.sdc.be.model.PropertyConstraint;
import org.openecomp.sdc.be.model.PropertyDefinition;
import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
import org.openecomp.sdc.be.model.operations.api.IElementOperation;
import org.openecomp.sdc.be.model.operations.api.IResourceOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
+import org.openecomp.sdc.be.model.operations.impl.PropertyOperation.PropertyConstraintDeserialiser;
import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
import org.openecomp.sdc.be.model.tosca.converters.PropertyValueConverter;
+import org.openecomp.sdc.be.model.tosca.validators.DataTypeValidatorConverter;
+import org.openecomp.sdc.be.model.tosca.validators.PropertyTypeValidator;
import org.openecomp.sdc.be.resources.data.EntryData;
import org.openecomp.sdc.be.resources.data.PropertyData;
import org.openecomp.sdc.common.api.Constants;
+import org.openecomp.sdc.common.config.EcompErrorName;
import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.JsonElement;
+import com.google.gson.reflect.TypeToken;
+
import fj.data.Either;
@Component("propertyBusinessLogic")
@@ -63,11 +83,15 @@ public class PropertyBusinessLogic extends BaseBusinessLogic {
private static Logger log = LoggerFactory.getLogger(PropertyBusinessLogic.class.getName());
+ private static final String EMPTY_VALUE = null;
+
+ private DataTypeValidatorConverter dataTypeValidatorConverter = DataTypeValidatorConverter.getInstance();
+
@javax.annotation.Resource
private IResourceOperation resourceOperation = null;
- @javax.annotation.Resource
- private PropertyOperation propertyOperation = null;
+ @Autowired
+ private ToscaOperationFacade toscaOperationFacade;
@javax.annotation.Resource
private ComponentsUtils componentsUtils;
@@ -114,7 +138,7 @@ public class PropertyBusinessLogic extends BaseBusinessLogic {
try {
// Get the resource from DB
- Either<Resource, StorageOperationStatus> status = getResource(resourceId);
+ Either<Resource, StorageOperationStatus> status = toscaOperationFacade.getToscaElement(resourceId);
if (status.isRight()) {
result = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, ""));
return result;
@@ -132,8 +156,8 @@ public class PropertyBusinessLogic extends BaseBusinessLogic {
List<PropertyDefinition> resourceProperties = resource.getProperties();
if (resourceProperties != null) {
- if (propertyOperation.isPropertyExist(resourceProperties, resourceId, propertyName)) {
- result = Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_ALREADY_EXIST, ""));
+ if (isPropertyExist(resourceProperties, resourceId, propertyName, newPropertyDefinition.getType())) {
+ result = Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_ALREADY_EXIST, propertyName));
return result;
}
}
@@ -177,13 +201,13 @@ public class PropertyBusinessLogic extends BaseBusinessLogic {
// add the new property to resource on graph
// need to get StorageOpaerationStatus and convert to ActionStatus
// from componentsUtils
- Either<PropertyData, StorageOperationStatus> either = propertyOperation.addProperty(propertyName, newPropertyDefinition, resourceId);
+ Either<PropertyDefinition, StorageOperationStatus> either = toscaOperationFacade.addPropertyToResource(propertyName, newPropertyDefinition, resource);
if (either.isRight()) {
result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(either.right().value()), resource.getName()));
return result;
}
- PropertyDefinition createdPropertyDefinition = propertyOperation.convertPropertyDataToPropertyDefinition(either.left().value(), propertyName, resourceId);
+ PropertyDefinition createdPropertyDefinition = either.left().value();
EntryData<String, PropertyDefinition> property = new EntryData<String, PropertyDefinition>(propertyName, createdPropertyDefinition);
result = Either.left(property);
return result;
@@ -202,7 +226,6 @@ public class PropertyBusinessLogic extends BaseBusinessLogic {
* @param resourceId
* @param propertyId
* @param userId
- * TODO
* @return
*/
public Either<Entry<String, PropertyDefinition>, ResponseFormat> getProperty(String resourceId, String propertyId, String userId) {
@@ -213,7 +236,7 @@ public class PropertyBusinessLogic extends BaseBusinessLogic {
}
// Get the resource from DB
- Either<Resource, StorageOperationStatus> status = getResource(resourceId);
+ Either<Resource, StorageOperationStatus> status = toscaOperationFacade.getToscaElement(resourceId);
if (status.isRight()) {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, ""));
}
@@ -244,9 +267,9 @@ public class PropertyBusinessLogic extends BaseBusinessLogic {
* @param userId
* @return
*/
- public Either<EntryData<String, PropertyDefinition>, ResponseFormat> deleteProperty(String resourceId, String propertyId, String userId) {
+ public Either<Entry<String, PropertyDefinition>, ResponseFormat> deleteProperty(String resourceId, String propertyId, String userId) {
- Either<EntryData<String, PropertyDefinition>, ResponseFormat> result = null;
+ Either<Entry<String, PropertyDefinition>, ResponseFormat> result = null;
Either<User, ResponseFormat> resp = validateUserExists(userId, "delete Property", false);
if (resp.isRight()) {
@@ -263,12 +286,12 @@ public class PropertyBusinessLogic extends BaseBusinessLogic {
try {
// Get the resource from DB
- Either<Resource, StorageOperationStatus> status = getResource(resourceId);
- if (status.isRight()) {
+ Either<Resource, StorageOperationStatus> getResourceRes = toscaOperationFacade.getToscaElement(resourceId);
+ if (getResourceRes.isRight()) {
result = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, ""));
return result;
}
- Resource resource = status.left().value();
+ Resource resource = getResourceRes.left().value();
// verify that resource is checked-out and the user is the last
// updater
@@ -283,21 +306,14 @@ public class PropertyBusinessLogic extends BaseBusinessLogic {
result = Either.right(statusGetProperty.right().value());
return result;
}
- String propertyName = statusGetProperty.left().value().getKey();
- // delete property of resource from graph
- // TODO: need to get StorageOperationStatus
- Either<PropertyData, StorageOperationStatus> either = propertyOperation.deleteProperty(propertyId);
- // Either<PropertyData, StorageOperationStatus> either =
- // propertyOperation.deletePropertyFromGraph(propertyId);
- if (either.isRight()) {
- result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(either.right().value()), resource.getName()));
+ StorageOperationStatus status = toscaOperationFacade.deletePropertyOfResource(resource, statusGetProperty.left().value().getKey());
+ if (status != StorageOperationStatus.OK) {
+ result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), resource.getName()));
return result;
}
// propertyOperation.getTitanGenericDao().commit();
- PropertyDefinition createdPropertyDefinition = propertyOperation.convertPropertyDataToPropertyDefinition(either.left().value(), propertyName, resourceId);
- EntryData<String, PropertyDefinition> property = new EntryData<String, PropertyDefinition>(propertyName, createdPropertyDefinition);
- result = Either.left(property);
+ result = Either.left(statusGetProperty.left().value());
return result;
} finally {
@@ -320,14 +336,12 @@ public class PropertyBusinessLogic extends BaseBusinessLogic {
Either<EntryData<String, PropertyDefinition>, ResponseFormat> result = null;
- // Get the resource from DB
- Either<Resource, StorageOperationStatus> status = getResource(resourceId);
+ Either<Resource, StorageOperationStatus> status = toscaOperationFacade.getToscaElement(resourceId);
if (status.isRight()) {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, ""));
}
Resource resource = status.left().value();
- // verify that resource is checked-out and the user is the last updater
if (!ComponentValidationUtils.canWorkOnResource(resource, userId)) {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
}
@@ -340,8 +354,6 @@ public class PropertyBusinessLogic extends BaseBusinessLogic {
}
try {
-
- // verify property exist in resource
Either<Entry<String, PropertyDefinition>, ResponseFormat> statusGetProperty = getProperty(resourceId, propertyId, userId);
if (statusGetProperty.isRight()) {
result = Either.right(statusGetProperty.right().value());
@@ -355,37 +367,222 @@ public class PropertyBusinessLogic extends BaseBusinessLogic {
return result;
}
Map<String, DataTypeDefinition> dataTypes = allDataTypes.left().value();
- // validate property default values
+
Either<Boolean, ResponseFormat> defaultValuesValidation = validatePropertyDefaultValue(newPropertyDefinition, dataTypes);
if (defaultValuesValidation.isRight()) {
result = Either.right(defaultValuesValidation.right().value());
return result;
}
- // add the new property to resource on graph
- // TODO: convert TitanOperationStatus to Storgae...
- Either<PropertyData, StorageOperationStatus> either = propertyOperation.updateProperty(propertyId, newPropertyDefinition, dataTypes);
- // Either<PropertyData, StorageOperationStatus> either =
- // propertyOperation.updatePropertyFromGraph(propertyId,
- // newPropertyDefinition);
+ Either<PropertyDefinition, StorageOperationStatus> either = handleProperty(propertyId, newPropertyDefinition, dataTypes);
if (either.isRight()) {
log.debug("Problem while updating property with id {}. Reason - {}", propertyId, either.right().value());
result = Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(either.right().value()), resource.getName()));
return result;
- // return Either.right(ActionStatus.GENERAL_ERROR);
}
- PropertyDefinition createdPropertyDefinition = propertyOperation.convertPropertyDataToPropertyDefinition(either.left().value(), propertyName, resourceId);
- EntryData<String, PropertyDefinition> property = new EntryData<String, PropertyDefinition>(propertyName, createdPropertyDefinition);
+
+ either = toscaOperationFacade.updatePropertyOfResource(resource, newPropertyDefinition);
+ if (either.isRight()) {
+ result = Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(either.right().value()), resource.getName()));
+ return result;
+ }
+
+ EntryData<String, PropertyDefinition> property = new EntryData<String, PropertyDefinition>(propertyName, either.left().value());
result = Either.left(property);
return result;
} finally {
commitOrRollback(result);
- // unlock component
graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource);
}
}
+
+ private boolean isPropertyExist(List<PropertyDefinition> properties, String resourceUid, String propertyName, String propertyType) {
+ boolean result = false;
+ if (!CollectionUtils.isEmpty(properties)) {
+ for (PropertyDefinition propertyDefinition : properties) {
+
+ if ( propertyDefinition.getName().equals(propertyName) &&
+ (propertyDefinition.getParentUniqueId().equals(resourceUid) || !propertyDefinition.getType().equals(propertyType)) ) {
+ result = true;
+ break;
+ }
+ }
+ }
+ return result;
+ }
+
+ private PropertyDefinition convertPropertyDataToPropertyDefinition(PropertyData propertyDataResult, String propertyName, String resourceId) {
+ log.debug("The object returned after create property is {}", propertyDataResult);
+ PropertyDefinition propertyDefResult = new PropertyDefinition(propertyDataResult.getPropertyDataDefinition());
+ propertyDefResult.setConstraints(convertConstraints(propertyDataResult.getConstraints()));
+ propertyDefResult.setName(propertyName);
+ propertyDefResult.setParentUniqueId(resourceId);
+ return propertyDefResult;
+ }
+
+ private List<PropertyConstraint> convertConstraints(List<String> constraints) {
+
+ if (constraints == null || constraints.size() == 0) {
+ return null;
+ }
+
+ List<PropertyConstraint> list = new ArrayList<PropertyConstraint>();
+ Type constraintType = new TypeToken<PropertyConstraint>() {
+ }.getType();
+
+ Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyConstraintDeserialiser()).create();
+
+ for (String constraintJson : constraints) {
+ PropertyConstraint propertyConstraint = gson.fromJson(constraintJson, constraintType);
+ list.add(propertyConstraint);
+ }
+
+ return list;
+ }
+
+ private Either<PropertyDefinition, StorageOperationStatus> handleProperty(String propertyId, PropertyDefinition newPropertyDefinition, Map<String, DataTypeDefinition> dataTypes) {
+
+ StorageOperationStatus validateAndUpdateProperty = validateAndUpdateProperty(newPropertyDefinition, dataTypes);
+ if (validateAndUpdateProperty != StorageOperationStatus.OK) {
+ return Either.right(validateAndUpdateProperty);
+ }
+
+ return Either.left(newPropertyDefinition);
+ }
+
+ private StorageOperationStatus validateAndUpdateProperty(IComplexDefaultValue propertyDefinition, Map<String, DataTypeDefinition> dataTypes) {
+
+ log.trace("Going to validate property type and value. {}", propertyDefinition);
+
+ String propertyType = propertyDefinition.getType();
+ String value = propertyDefinition.getDefaultValue();
+
+ ToscaPropertyType type = getType(propertyType);
+ if (type == null) {
+
+ DataTypeDefinition dataTypeDefinition = dataTypes.get(propertyType);
+ if (dataTypeDefinition == null) {
+ log.debug("The type {} of property cannot be found.", propertyType);
+ return StorageOperationStatus.INVALID_TYPE;
+ }
+
+ StorageOperationStatus status = validateAndUpdateComplexValue(propertyDefinition, propertyType, value, dataTypeDefinition, dataTypes);
+
+ return status;
+
+ }
+ String innerType = null;
+
+ Either<String, TitanOperationStatus> checkInnerType = getInnerType(type, () -> propertyDefinition.getSchema());
+ if (checkInnerType.isRight()) {
+ return StorageOperationStatus.INVALID_TYPE;
+ }
+ innerType = checkInnerType.left().value();
+
+ log.trace("After validating property type {}", propertyType);
+
+ boolean isValidProperty = isValidValue(type, value, innerType, dataTypes);
+ if (false == isValidProperty) {
+ log.info("The value {} of property from type {} is invalid", value, type);
+ return StorageOperationStatus.INVALID_VALUE;
+ }
+
+ PropertyValueConverter converter = type.getConverter();
+
+ if (isEmptyValue(value)) {
+ log.debug("Default value was not sent for property {}. Set default value to {}", propertyDefinition.getName(), EMPTY_VALUE);
+ propertyDefinition.setDefaultValue(EMPTY_VALUE);
+ } else if (false == isEmptyValue(value)) {
+ String convertedValue = converter.convert(value, innerType, dataTypes);
+ propertyDefinition.setDefaultValue(convertedValue);
+ }
+ return StorageOperationStatus.OK;
+ }
+
+ protected StorageOperationStatus validateAndUpdateComplexValue(IComplexDefaultValue propertyDefinition, String propertyType,
+
+ String value, DataTypeDefinition dataTypeDefinition, Map<String, DataTypeDefinition> dataTypes) {
+
+ ImmutablePair<JsonElement, Boolean> validateResult = dataTypeValidatorConverter.validateAndUpdate(value, dataTypeDefinition, dataTypes);
+
+ if (validateResult.right.booleanValue() == false) {
+ log.debug("The value {} of property from type {} is invalid", propertyType, propertyType);
+ return StorageOperationStatus.INVALID_VALUE;
+ }
+
+ JsonElement jsonElement = validateResult.left;
+
+ log.trace("Going to update value in property definition {} {}" , propertyDefinition.getName() , (jsonElement != null ? jsonElement.toString() : null));
+
+ updateValue(propertyDefinition, jsonElement);
+
+ return StorageOperationStatus.OK;
+ }
+
+ protected void updateValue(IComplexDefaultValue propertyDefinition, JsonElement jsonElement) {
+
+ propertyDefinition.setDefaultValue(getValueFromJsonElement(jsonElement));
+
+ }
+
+ protected String getValueFromJsonElement(JsonElement jsonElement) {
+ String value = null;
+
+ if (jsonElement == null || jsonElement.isJsonNull()) {
+ value = EMPTY_VALUE;
+ } else {
+ if (jsonElement.toString().isEmpty()) {
+ value = "";
+ } else {
+ value = jsonElement.toString();
+ }
+ }
+
+ return value;
+ }
+
+ protected Either<String, TitanOperationStatus> getInnerType(ToscaPropertyType type, Supplier<SchemaDefinition> schemeGen) {
+ String innerType = null;
+ if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
+
+ SchemaDefinition def = schemeGen.get();// propDataDef.getSchema();
+ if (def == null) {
+ log.debug("Schema doesn't exists for property of type {}", type);
+ return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
+ }
+ PropertyDataDefinition propDef = def.getProperty();
+ if (propDef == null) {
+ log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
+ return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
+ }
+ innerType = propDef.getType();
+ }
+ return Either.left(innerType);
+ }
+ protected boolean isValidValue(ToscaPropertyType type, String value, String innerType, Map<String, DataTypeDefinition> dataTypes) {
+ if (isEmptyValue(value)) {
+ return true;
+ }
+
+ PropertyTypeValidator validator = type.getValidator();
+
+ boolean isValid = validator.isValid(value, innerType, dataTypes);
+ if (true == isValid) {
+ return true;
+ } else {
+ return false;
+ }
+
+ }
+
+ public boolean isEmptyValue(String value) {
+ if (value == null) {
+ return true;
+ }
+ return false;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogic.java
index ddc03e14e8..ffcb87c99c 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogic.java
@@ -20,10 +20,14 @@
package org.openecomp.sdc.be.components.impl;
+import static org.openecomp.sdc.be.tosca.CsarUtils.ARTIFACTS_PATH;
+import static org.openecomp.sdc.be.tosca.CsarUtils.VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN;
+
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
+import java.util.EnumMap;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
@@ -40,8 +44,10 @@ import java.util.stream.Collectors;
import javax.servlet.ServletContext;
import org.apache.commons.codec.binary.Base64;
+import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
-import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperation;
+import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum;
+import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationInfo;
import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum;
import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaElementTypeEnum;
import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaTagNamesEnum;
@@ -49,13 +55,17 @@ import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction.LifecycleChanceActionEnum;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
-import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
+import org.openecomp.sdc.be.config.Configuration.VfModuleProperty;
+import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
import org.openecomp.sdc.be.datamodel.api.HighestFilterEnum;
import org.openecomp.sdc.be.datamodel.utils.ArtifactUtils;
+import org.openecomp.sdc.be.datamodel.utils.UiComponentDataConverter;
+import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
@@ -64,15 +74,14 @@ import org.openecomp.sdc.be.impl.WebAppContextWrapper;
import org.openecomp.sdc.be.info.ArtifactTemplateInfo;
import org.openecomp.sdc.be.info.MergedArtifactInfo;
import org.openecomp.sdc.be.model.ArtifactDefinition;
+import org.openecomp.sdc.be.model.AttributeDefinition;
import org.openecomp.sdc.be.model.CapabilityDefinition;
import org.openecomp.sdc.be.model.CapabilityTypeDefinition;
import org.openecomp.sdc.be.model.Component;
import org.openecomp.sdc.be.model.ComponentInstance;
-import org.openecomp.sdc.be.model.ComponentInstanceInput;
import org.openecomp.sdc.be.model.ComponentInstanceProperty;
import org.openecomp.sdc.be.model.ComponentParametersView;
import org.openecomp.sdc.be.model.DataTypeDefinition;
-import org.openecomp.sdc.be.model.GetInputValueInfo;
import org.openecomp.sdc.be.model.GroupDefinition;
import org.openecomp.sdc.be.model.GroupProperty;
import org.openecomp.sdc.be.model.GroupTypeDefinition;
@@ -84,6 +93,7 @@ import org.openecomp.sdc.be.model.LifecycleStateEnum;
import org.openecomp.sdc.be.model.Operation;
import org.openecomp.sdc.be.model.ParsedToscaYamlInfo;
import org.openecomp.sdc.be.model.PropertyDefinition;
+import org.openecomp.sdc.be.model.RelationshipImpl;
import org.openecomp.sdc.be.model.RequirementAndRelationshipPair;
import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
import org.openecomp.sdc.be.model.RequirementDefinition;
@@ -98,29 +108,24 @@ import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
import org.openecomp.sdc.be.model.category.CategoryDefinition;
import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
import org.openecomp.sdc.be.model.heat.HeatParameterType;
-import org.openecomp.sdc.be.model.operations.api.IArtifactOperation;
import org.openecomp.sdc.be.model.operations.api.ICacheMangerOperation;
import org.openecomp.sdc.be.model.operations.api.ICapabilityTypeOperation;
-import org.openecomp.sdc.be.model.operations.api.IComponentInstanceOperation;
import org.openecomp.sdc.be.model.operations.api.IElementOperation;
import org.openecomp.sdc.be.model.operations.api.IHeatParametersOperation;
import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation;
import org.openecomp.sdc.be.model.operations.api.IPropertyOperation;
-import org.openecomp.sdc.be.model.operations.api.IResourceOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.be.model.operations.impl.CapabilityInstanceOperation;
import org.openecomp.sdc.be.model.operations.impl.CsarOperation;
import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
-import org.openecomp.sdc.be.model.operations.impl.GroupOperation;
import org.openecomp.sdc.be.model.operations.impl.InputsOperation;
-import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
-import org.openecomp.sdc.be.model.operations.impl.ResourceOperation;
import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
-import org.openecomp.sdc.be.resources.data.ResourceMetadataData;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
import org.openecomp.sdc.be.servlets.RepresentationUtils;
+import org.openecomp.sdc.be.tosca.CsarUtils;
+import org.openecomp.sdc.be.tosca.CsarUtils.NonMetaArtifactInfo;
+import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer;
import org.openecomp.sdc.be.user.IUserBusinessLogic;
import org.openecomp.sdc.be.user.Role;
import org.openecomp.sdc.be.user.UserBusinessLogic;
@@ -129,6 +134,8 @@ import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
import org.openecomp.sdc.common.api.ArtifactTypeEnum;
import org.openecomp.sdc.common.api.Constants;
import org.openecomp.sdc.common.config.EcompErrorName;
+import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
+import org.openecomp.sdc.common.datastructure.FunctionalInterfaces;
import org.openecomp.sdc.common.datastructure.Wrapper;
import org.openecomp.sdc.common.kpi.api.ASDCKpiApi;
import org.openecomp.sdc.common.util.GeneralUtility;
@@ -140,9 +147,6 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.WebApplicationContext;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
-import org.yaml.snakeyaml.constructor.Constructor;
-import org.yaml.snakeyaml.representer.Representer;
-import org.yaml.snakeyaml.resolver.Resolver;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
@@ -156,13 +160,18 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
private static final String PLACE_HOLDER_RESOURCE_TYPES = "validForResourceTypes";
public static final String INITIAL_VERSION = "0.1";
- Pattern STR_REPLACE_PATTERN = Pattern.compile("^[ ]*\\{[ ]*" + "str_replace" + "=");
- Pattern TOKEN_PATTERN = Pattern.compile("[ ]*\\{[ ]*" + "token" + "=");
- Pattern GET_PROPERTY_PATTERN = Pattern.compile("[ ]*\\{[ ]*" + "get_property" + "=");
- Pattern CONCAT_PATTERN = Pattern.compile("[ ]*\\{[ ]*" + "concat" + "=");
+ private Pattern STR_REPLACE_PATTERN = Pattern.compile("^[ ]*\\{[ ]*" + "str_replace" + "=");
+ private Pattern TOKEN_PATTERN = Pattern.compile("[ ]*\\{[ ]*" + "token" + "=");
+ private Pattern GET_PROPERTY_PATTERN = Pattern.compile("[ ]*\\{[ ]*" + "get_property" + "=");
+ private Pattern CONCAT_PATTERN = Pattern.compile("[ ]*\\{[ ]*" + "concat" + "=");
private static Logger log = LoggerFactory.getLogger(ResourceBusinessLogic.class.getName());
+ private static Pattern pattern = Pattern.compile("\\..(.*?)\\..");
+
+ /**
+ * Default constructor
+ */
public ResourceBusinessLogic() {
log.debug("ResourceBusinessLogic started");
}
@@ -174,9 +183,6 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
private IInterfaceLifecycleOperation interfaceTypeOperation = null;
@Autowired
- private IComponentInstanceOperation componentInstanceOperation;
-
- @Autowired
private LifecycleBusinessLogic lifecycleBusinessLogic;
@Autowired
@@ -193,23 +199,21 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
@Autowired
private GroupBusinessLogic groupBusinessLogic;
+
@Autowired
private InputsBusinessLogic inputsBusinessLogic;
@javax.annotation.Resource
private InputsOperation inputOperation;
- @Autowired
- private GroupOperation groupOperation;
+ // @Autowired
+ // private GroupOperation groupOperation;
@Autowired
private IHeatParametersOperation heatParametersOperation;
- @Autowired
- private IArtifactOperation artifactOperation;
-
- @Autowired
- private CapabilityInstanceOperation capabilityInstanceOperation;
+ // @Autowired
+ // private IArtifactOperation artifactOperation;
@Autowired
private CompositionBusinessLogic compositionBusinessLogic;
@@ -217,6 +221,9 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
@Autowired
private ICacheMangerOperation cacheManagerOperation;
+ @Autowired
+ private ApplicationDataTypeCache dataTypeCache;
+
private Gson gson = new Gson();
public CsarOperation getCsarOperation() {
@@ -227,14 +234,6 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
this.csarOperation = csarOperation;
}
- public IResourceOperation getResourceOperation() {
- return this.resourceOperation;
- }
-
- public void setResourceOperation(ResourceOperation resourceOperation) {
- this.resourceOperation = resourceOperation;
- }
-
public LifecycleBusinessLogic getLifecycleBusinessLogic() {
return lifecycleBusinessLogic;
}
@@ -300,7 +299,6 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (resp.isRight()) {
return Either.right(resp.right().value());
}
- IResourceOperation dataModel = getResourceOperation();
Boolean isHighest = null;
switch (highestFilter) {
case ALL:
@@ -314,17 +312,13 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
default:
break;
}
+ Either<List<Resource>, StorageOperationStatus> getResponse = toscaOperationFacade.getAllCertifiedResources(getAbstract, isHighest);
- Either<List<Resource>, StorageOperationStatus> dataModelResponse = dataModel.getAllCertifiedResources(getAbstract, isHighest);
-
- if (dataModelResponse.isLeft()) {
- log.debug("Retrived Resource successfully.");
- return Either.left(dataModelResponse.left().value());
+ if (getResponse.isRight()) {
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getResponse.right().value())));
}
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()));
-
- return Either.right(responseFormat);
+ return Either.left(getResponse.left().value());
}
public Either<Map<String, Boolean>, ResponseFormat> validateResourceNameExists(String resourceName, ResourceTypeEnum resourceTypeEnum, String userId) {
@@ -334,9 +328,9 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return Either.right(resp.right().value());
}
- IResourceOperation dataModel = getResourceOperation();
-
- Either<Boolean, StorageOperationStatus> dataModelResponse = dataModel.validateResourceNameExists(resourceName, resourceTypeEnum);
+ Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade.validateComponentNameUniqueness(resourceName, resourceTypeEnum, ComponentTypeEnum.RESOURCE);
+ // DE242223
+ titanDao.commit();
if (dataModelResponse.isLeft()) {
Map<String, Boolean> result = new HashMap<>();
@@ -350,7 +344,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return Either.right(responseFormat);
}
- public Either<Resource, ResponseFormat> createResource(Resource resource, User user, Map<String, byte[]> csarUIPayload, String payloadName) {
+ public Either<Resource, ResponseFormat> createResource(Resource resource, AuditingActionEnum auditingAction, User user, Map<String, byte[]> csarUIPayload, String payloadName) {
Either<Resource, ResponseFormat> createResourceResponse = validateResourceBeforeCreate(resource, user, false);
if (createResourceResponse.isRight()) {
return createResourceResponse;
@@ -366,26 +360,26 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (csarUUID != null && !csarUUID.isEmpty()) {
// check if VF with the same Csar UUID or with he same name already
// exists
- Either<List<ResourceMetadataData>, StorageOperationStatus> validateCsarUuidUniquenessRes = resourceOperation.validateCsarUuidUniqueness(csarUUID);
+ Either<Integer, StorageOperationStatus> validateCsarUuidUniquenessRes = toscaOperationFacade.validateCsarUuidUniqueness(csarUUID);
if (validateCsarUuidUniquenessRes.isRight()) {
log.debug("Failed to validate uniqueness of CsarUUID {} for resource", csarUUID, resource.getSystemName());
return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validateCsarUuidUniquenessRes.right().value())));
}
- List<ResourceMetadataData> existingResourceRes = validateCsarUuidUniquenessRes.left().value();
- if (existingResourceRes != null && existingResourceRes.size() > 0) {
- log.debug("Failed to create resource {}, csarUUID {} already exist for a different VF {}", resource.getSystemName(), csarUUID, existingResourceRes.get(0).getMetadataDataDefinition().getName());
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VSP_ALREADY_EXISTS, csarUUID, existingResourceRes.get(0).getMetadataDataDefinition().getName());
- componentsUtils.auditResource(errorResponse, user, resource, "", "", AuditingActionEnum.CREATE_RESOURCE, null);
+ Integer existingResourceRes = validateCsarUuidUniquenessRes.left().value();
+ if (existingResourceRes.intValue() > 0) {
+ log.debug("Failed to create resource {}, csarUUID {} already exist for a different VF ", resource.getSystemName(), csarUUID);
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VSP_ALREADY_EXISTS, csarUUID);
+ componentsUtils.auditResource(errorResponse, user, resource, "", "", auditingAction, null);
return Either.right(errorResponse);
}
log.debug("CsarUUID is {} - going to create resource from CSAR", csarUUID);
- createResourceResponse = createResourceFromCsar(resource, user, AuditingActionEnum.CREATE_RESOURCE, false, Either.left(csarUIPayload), csarUUID);
+ createResourceResponse = createResourceFromCsar(resource, user, Either.left(csarUIPayload), csarUUID);
return createResourceResponse;
}
- return createResourceByDao(resource, user, AuditingActionEnum.CREATE_RESOURCE, false);
+ return createResourceByDao(resource, user, auditingAction, false, false, null);
}
public Either<Resource, ResponseFormat> validateAndUpdateResourceFromCsar(Resource resource, User user, Map<String, byte[]> csarUIPayload, String payloadName, String resourceUniqueId) {
@@ -448,7 +442,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
// "Error: The VSP with UUID %1 was already imported for VF %2. Please
// select another or update the existing VF." %1 - csarUUID, %2 - VF
// name
- Either<Resource, StorageOperationStatus> resourceLinkedToCsarRes = resourceOperation.getLatestResourceByCsarOrName(csarUUID, resource.getSystemName());
+ Either<Resource, StorageOperationStatus> resourceLinkedToCsarRes = toscaOperationFacade.getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUUID, resource.getSystemName());
if (resourceLinkedToCsarRes.isRight()) {
if (!StorageOperationStatus.NOT_FOUND.equals(resourceLinkedToCsarRes.right().value())) {
log.debug("Failed to find previous resource by CSAR {} and system name {}", csarUUID, resource.getSystemName());
@@ -476,7 +470,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
private Resource getResourceByUniqueId(Wrapper<ResponseFormat> responseWrapper, String resourceUniqueId) {
- Either<Resource, StorageOperationStatus> oldResourceRes = resourceOperation.getResource(resourceUniqueId);
+ Either<Resource, StorageOperationStatus> oldResourceRes = toscaOperationFacade.getToscaElement(resourceUniqueId);
if (oldResourceRes.isRight()) {
log.debug("Failed to find previous resource by UniqueId {}, status: {}", resourceUniqueId, oldResourceRes.right().value());
responseWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(oldResourceRes.right().value())));
@@ -505,7 +499,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
}
String lockedResourceId = oldRresource.getUniqueId();
- List<ArtifactDefinition> createdArtifacts = new ArrayList<ArtifactDefinition>();
+ List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
+ List<ArtifactDefinition> nodeTypesNewCreatedArtifacts = new ArrayList<>();
Either<Map<String, byte[]>, StorageOperationStatus> csar = null;
if (csarUIPayload != null && csarUIPayload.left() != null && csarUIPayload.left().value() != null) {
@@ -542,29 +537,33 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
Either<Resource, ResponseFormat> result = null;
+ String yamlFileName = toscaYamlCsarStatus.left().value().getKey();
+ Either<Map<String, Resource>, ResponseFormat> parseNodeTypeInfoYamlEither = null;
try {
Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> prepareForUpdate = null;
Resource preparedResource = null;
- if (isUpdateYaml) {
- prepareForUpdate = updateExistingResourceByImport(newRresource, oldRresource, user, true, false);
+ Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(csar.left().value(), csarUUID, yamlFileName, oldRresource, user, true);
+ if (findNodeTypesArtifactsToHandleRes.isRight()) {
+ log.debug("failed to find node types for update with artifacts during import csar {}. ", csarUUID);
+ result = Either.right(findNodeTypesArtifactsToHandleRes.right().value());
+ return result;
+ }
+ Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = findNodeTypesArtifactsToHandleRes.left().value();
+ if (isUpdateYaml || !nodeTypesArtifactsToHandle.isEmpty()) {
+ prepareForUpdate = updateExistingResourceByImport(newRresource, oldRresource, user, true, false);
if (prepareForUpdate.isRight()) {
log.debug("Failed to prepare resource for update : {}", prepareForUpdate.right().value());
result = Either.right(prepareForUpdate.right().value());
return result;
}
preparedResource = prepareForUpdate.left().value().left;
- String yamlFileName = toscaYamlCsarStatus.left().value().getKey();
+
String yamlFileContents = toscaYamlCsarStatus.left().value().getValue();
log.trace("YAML topology file found in CSAR, file name: {}, contents: {}", yamlFileName, yamlFileContents);
- // Either<Map<String, Resource>, ResponseFormat>
- // parseNodeTypeInfoYamlEither =
- // createResourcesFromYamlNodeTypesList(yamlFileName,preparedResource,
- // yamlFileContents, user,false);
-
- Either<Map<String, Resource>, ResponseFormat> parseNodeTypeInfoYamlEither = this.handleNodeTypes(yamlFileName, preparedResource, user, yamlFileContents, csar.left().value(), false);
+ parseNodeTypeInfoYamlEither = this.handleNodeTypes(yamlFileName, preparedResource, user, yamlFileContents, csar.left().value(), false, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts);
if (parseNodeTypeInfoYamlEither.isRight()) {
ResponseFormat responseFormat = parseNodeTypeInfoYamlEither.right().value();
componentsUtils.auditResource(responseFormat, user, preparedResource, "", "", updateResource, null);
@@ -638,12 +637,11 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
result = Either.right(dataModelResponse.right().value());
return result;
}
-
preparedResource = dataModelResponse.left().value();
-
}
- Either<Resource, ResponseFormat> createdCsarArtifactsEither = handleCsarArtifacts(preparedResource, user, csarUUID, csar.left().value(), createdArtifacts, ArtifactOperation.Update, false, true);
+ Either<Resource, ResponseFormat> createdCsarArtifactsEither = handleCsarArtifacts(preparedResource, user, csarUUID, csar.left().value(), createdArtifacts,
+ artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Update), false, true);
if (createdCsarArtifactsEither.isRight()) {
return createdCsarArtifactsEither;
@@ -658,8 +656,9 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
} finally {
if (result == null || result.isRight()) {
log.warn("operation failed. do rollback");
- titanGenericDao.rollback();
- if (!createdArtifacts.isEmpty()) {
+ titanDao.rollback();
+ if (!createdArtifacts.isEmpty() || !nodeTypesNewCreatedArtifacts.isEmpty()) {
+ createdArtifacts.addAll(nodeTypesNewCreatedArtifacts);
StorageOperationStatus deleteFromEsRes = artifactsBusinessLogic.deleteAllComponentArtifactsIfNotOnGraph(createdArtifacts);
if (!deleteFromEsRes.equals(StorageOperationStatus.OK)) {
ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(deleteFromEsRes);
@@ -669,7 +668,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
} else {
log.debug("operation success. do commit");
- titanGenericDao.commit();
+ titanDao.commit();
}
log.debug("unlock resource {}", lockedResourceId);
graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource);
@@ -677,7 +676,318 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
- public Either<Resource, ResponseFormat> createResourceFromCsar(Resource resource, User user, AuditingActionEnum createResource, boolean inTransaction, Either<Map<String, byte[]>, StorageOperationStatus> csarUIPayload, String csarUUID) {
+ private Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandle(Map<String, byte[]> csar, String csarUUID, String yamlFileName, Resource oldResource, User user,
+ boolean inTransaction) {
+
+ Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts = CsarUtils.extractVfcsArtifactsFromCsar(csar);
+ Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = new HashMap<>();
+ Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> nodeTypesArtifactsToHandleRes;
+
+ try {
+ nodeTypesArtifactsToHandleRes = Either.left(nodeTypesArtifactsToHandle);
+ List<ImmutablePair<ImmutablePair<String, List<String>>, String>> extractedVfcToscaNames = extractVfcToscaNames(csar, yamlFileName, oldResource.getSystemName());
+ validateNodeTypeIdentifiers(extractedVfcsArtifacts, extractedVfcToscaNames);
+ Either<EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>, ResponseFormat> curNodeTypeArtifactsToHandleRes = null;
+ EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> curNodeTypeArtifactsToHandle = null;
+ log.debug("Going to fetch node types for resource with name {} during import csar with UUID {}. ", oldResource.getName(), csarUUID);
+
+ for (ImmutablePair<ImmutablePair<String, List<String>>, String> currVfcToscaNameEntry : extractedVfcToscaNames) {
+ String currVfcToscaName = currVfcToscaNameEntry.getValue();
+ log.debug("Going to fetch node type with tosca name {}. ", currVfcToscaName);
+
+ Either<Resource, StorageOperationStatus> curVfcRes = toscaOperationFacade.getLatestByToscaResourceName(currVfcToscaName);
+ Resource curNodeType = null;
+ if (curVfcRes.isRight() && curVfcRes.right().value() != StorageOperationStatus.NOT_FOUND) {
+ log.debug("Error occured during fetching node type with tosca name {}, error: {}", currVfcToscaName, curVfcRes.right().value());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(curVfcRes.right().value()), csarUUID);
+ componentsUtils.auditResource(responseFormat, user, oldResource, "", "", AuditingActionEnum.CREATE_RESOURCE, null);
+ nodeTypesArtifactsToHandleRes = Either.right(responseFormat);
+ break;
+ } else if (curVfcRes.isLeft()) {
+ curNodeType = curVfcRes.left().value();
+ }
+ if (!MapUtils.isEmpty(extractedVfcsArtifacts)) {
+ List<ArtifactDefinition> currArtifacts = new ArrayList<>();
+ for (String currNamespace : currVfcToscaNameEntry.getKey().getValue()) {
+ if (extractedVfcsArtifacts.containsKey(currNamespace)) {
+ handleAndAddExtractedVfcsArtifacts(currArtifacts, extractedVfcsArtifacts.get(currNamespace));
+ }
+ }
+ curNodeTypeArtifactsToHandleRes = findNodeTypeArtifactsToHandle(curNodeType, currArtifacts);
+ if (curNodeTypeArtifactsToHandleRes.isRight()) {
+ nodeTypesArtifactsToHandleRes = Either.right(curNodeTypeArtifactsToHandleRes.right().value());
+ break;
+ }
+ curNodeTypeArtifactsToHandle = curNodeTypeArtifactsToHandleRes.left().value();
+
+ } else if (curNodeType != null) {
+ // delete all artifacts if have not received artifacts from csar
+ curNodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
+ List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
+ // delete all informational artifacts
+ artifactsToDelete.addAll(curNodeType.getArtifacts().values().stream().filter(a -> a.getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL).collect(Collectors.toList()));
+ // delete all deployment artifacts
+ artifactsToDelete.addAll(curNodeType.getDeploymentArtifacts().values());
+ if (!artifactsToDelete.isEmpty()) {
+ curNodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Delete, artifactsToDelete);
+ }
+ }
+ if (MapUtils.isNotEmpty(curNodeTypeArtifactsToHandle)) {
+ nodeTypesArtifactsToHandle.put(currVfcToscaNameEntry.getKey().getKey(), curNodeTypeArtifactsToHandle);
+ }
+ }
+ } catch (Exception e) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
+ nodeTypesArtifactsToHandleRes = Either.right(responseFormat);
+ log.debug("Exception occured when findNodeTypesUpdatedArtifacts, error is:{}", e.getMessage(), e);
+ }
+ return nodeTypesArtifactsToHandleRes;
+ }
+
+ private void validateNodeTypeIdentifiers(Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts, List<ImmutablePair<ImmutablePair<String, List<String>>, String>> extractedVfcToscaNames) {
+ if (extractedVfcsArtifacts != null) {
+ List<String> validIdentifiers = new ArrayList<>();
+ if (extractedVfcToscaNames != null) {
+ extractedVfcToscaNames.stream().forEach(pair -> {
+ validIdentifiers.addAll(pair.getKey().getValue());
+ validIdentifiers.add(pair.getKey().getKey());
+ });
+ }
+ for (String curIdentifier : extractedVfcsArtifacts.keySet()) {
+ if (validIdentifiers != null && !validIdentifiers.contains(curIdentifier))
+ log.warn("Warning - VFC identification {} provided in the Artifacts folder of the CSAR is not valid. ", curIdentifier);
+ }
+ }
+ }
+
+ private Either<EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>, ResponseFormat> findNodeTypeArtifactsToHandle(Resource curNodeType, List<ArtifactDefinition> extractedArtifacts) {
+
+ Either<EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>, ResponseFormat> nodeTypeArtifactsToHandleRes = null;
+ EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = null;
+ Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
+ try {
+ List<ArtifactDefinition> artifactsToUpload = new ArrayList<>(extractedArtifacts);
+ List<ArtifactDefinition> artifactsToUpdate = new ArrayList<>();
+ List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
+ if (curNodeType != null) {
+ Map<String, ArtifactDefinition> existingArtifacts = new HashMap<>();
+ if (curNodeType.getDeploymentArtifacts() != null) {
+ existingArtifacts.putAll(curNodeType.getDeploymentArtifacts());
+ }
+ if (curNodeType.getArtifacts() != null) {
+ existingArtifacts.putAll(curNodeType.getArtifacts().entrySet().stream().filter(e -> e.getValue().getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL).collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue())));
+ }
+ for (ArtifactDefinition currNewArtifact : extractedArtifacts) {
+ ArtifactDefinition foundArtifact;
+
+ if (!existingArtifacts.isEmpty()) {
+ foundArtifact = existingArtifacts.values().stream().filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName())).findFirst().orElse(null);
+ if (foundArtifact != null) {
+ if (foundArtifact.getArtifactType().equals(currNewArtifact.getArtifactType())) {
+ if (!foundArtifact.getArtifactChecksum().equals(currNewArtifact.getArtifactChecksum())) {
+ foundArtifact.setPayload(currNewArtifact.getPayloadData());
+ foundArtifact.setPayloadData(Base64.encodeBase64String(currNewArtifact.getPayloadData()));
+ foundArtifact.setArtifactChecksum(GeneralUtility.calculateMD5ByByteArray(currNewArtifact.getPayloadData()));
+ artifactsToUpdate.add(foundArtifact);
+ }
+ existingArtifacts.remove(foundArtifact.getArtifactLabel());
+ artifactsToUpload.remove(currNewArtifact);
+ } else {
+ log.debug("Can't upload two artifact with the same name {}.", currNewArtifact.getArtifactName());
+ ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType(),
+ foundArtifact.getArtifactType());
+ responseWrapper.setInnerElement(responseFormat);
+ break;
+ }
+ }
+ }
+ }
+ if (responseWrapper.isEmpty()) {
+ artifactsToDelete.addAll(existingArtifacts.values());
+ }
+ }
+ if (responseWrapper.isEmpty()) {
+ if (!artifactsToUpload.isEmpty() || !artifactsToUpdate.isEmpty() || !artifactsToDelete.isEmpty()) {
+ nodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
+ if (!artifactsToUpload.isEmpty())
+ nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Create, artifactsToUpload);
+ if (!artifactsToUpdate.isEmpty())
+ nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Update, artifactsToUpdate);
+ if (!artifactsToDelete.isEmpty())
+ nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Delete, artifactsToDelete);
+ }
+ nodeTypeArtifactsToHandleRes = Either.left(nodeTypeArtifactsToHandle);
+ }
+ if (!responseWrapper.isEmpty()) {
+ nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement());
+ }
+ } catch (Exception e) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
+ responseWrapper.setInnerElement(responseFormat);
+ log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
+ }
+ return nodeTypeArtifactsToHandleRes;
+ }
+
+ /**
+ * Changes resource life cycle state to checked out
+ *
+ * @param resource
+ * @param user
+ * @param inTransaction
+ * @return
+ */
+ private Either<Resource, ResponseFormat> checkoutResource(Resource resource, User user, boolean inTransaction) {
+ Either<Resource, ResponseFormat> checkoutResourceRes;
+ try {
+ if (!resource.getComponentMetadataDefinition().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
+ log.debug("************* Going to change life cycle state of resource {} to not certified checked out. ", resource.getName());
+ Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic.changeComponentState(resource.getComponentType(), resource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT,
+ new LifecycleChangeInfoWithAction("certification on import", LifecycleChanceActionEnum.CREATE_FROM_CSAR), inTransaction, true);
+ if (checkoutRes.isRight()) {
+ log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ", resource.getComponentType().getNodeType(), resource.getUniqueId(), checkoutRes.right().value().getStatus());
+ checkoutResourceRes = Either.right(checkoutRes.right().value());
+ } else {
+ checkoutResourceRes = Either.left((Resource) checkoutRes.left().value());
+ }
+ } else {
+ checkoutResourceRes = Either.left(resource);
+ }
+ } catch (Exception e) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
+ checkoutResourceRes = Either.right(responseFormat);
+ log.debug("Exception occured when checkoutResource {} , error is:{}", resource.getName(), e.getMessage(), e);
+ }
+ return checkoutResourceRes;
+ }
+
+ /**
+ * Handles Artifacts of NodeType
+ *
+ * @param nodeTypeResource
+ * @param nodeTypeArtifactsToHandle
+ * @param vfcsNewCreatedArtifacts
+ * @param user
+ * @param inTransaction
+ * @return
+ */
+ public Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifacts(Resource nodeTypeResource, Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle, List<ArtifactDefinition> vfcsNewCreatedArtifacts,
+ User user, boolean inTransaction) {
+ Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRequestRes;
+ Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes = null;
+ Either<Resource, ResponseFormat> changeStateResponse;
+ try {
+ changeStateResponse = checkoutResource(nodeTypeResource, user, inTransaction);
+ if (changeStateResponse.isRight()) {
+ return Either.right(changeStateResponse.right().value());
+ }
+ nodeTypeResource = changeStateResponse.left().value();
+
+ List<ArtifactDefinition> handledNodeTypeArtifacts = new ArrayList<>();
+ log.debug("************* Going to handle artifacts of node type resource {}. ", nodeTypeResource.getName());
+ for (Entry<ArtifactOperationEnum, List<ArtifactDefinition>> curOperationEntry : nodeTypeArtifactsToHandle.entrySet()) {
+ ArtifactOperationEnum curOperation = curOperationEntry.getKey();
+ List<ArtifactDefinition> curArtifactsToHandle = curOperationEntry.getValue();
+ if (curArtifactsToHandle != null && !curArtifactsToHandle.isEmpty()) {
+ log.debug("************* Going to {} artifact to vfc {}", curOperation.name(), nodeTypeResource.getName());
+ handleNodeTypeArtifactsRequestRes = artifactsBusinessLogic.handleArtifactsRequestForInnerVfcComponent(curArtifactsToHandle, nodeTypeResource, user, vfcsNewCreatedArtifacts,
+ artifactsBusinessLogic.new ArtifactOperationInfo(false, false, curOperation), false, inTransaction);
+ if (handleNodeTypeArtifactsRequestRes.isRight()) {
+ handleNodeTypeArtifactsRes = Either.right(handleNodeTypeArtifactsRequestRes.right().value());
+ break;
+ }
+ if (curOperation == ArtifactOperationEnum.Create) {
+ vfcsNewCreatedArtifacts.addAll(handleNodeTypeArtifactsRequestRes.left().value());
+ }
+ handledNodeTypeArtifacts.addAll(handleNodeTypeArtifactsRequestRes.left().value());
+ }
+ }
+ if (handleNodeTypeArtifactsRes == null) {
+ handleNodeTypeArtifactsRes = Either.left(handledNodeTypeArtifacts);
+ }
+ } catch (Exception e) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
+ handleNodeTypeArtifactsRes = Either.right(responseFormat);
+ log.debug("Exception occured when handleVfcArtifacts, error is:{}", e.getMessage(), e);
+ }
+ return handleNodeTypeArtifactsRes;
+ }
+
+ private List<ImmutablePair<ImmutablePair<String, List<String>>, String>> extractVfcToscaNames(Map<String, byte[]> csar, String yamlFileName, String vfResourceName) {
+ List<ImmutablePair<ImmutablePair<String, List<String>>, String>> vfcToscaNames = new ArrayList<>();
+ Map<String, Object> nodeTypes;
+ if (csar != null) {
+ nodeTypes = new HashMap<>();
+ putNodeTypesFromYaml(csar, yamlFileName, nodeTypes);
+ putNodeTypesFromYaml(csar, Constants.GLOBAL_SUBSTITUTION_TYPES_SERVICE_TEMPLATE, nodeTypes);
+ putNodeTypesFromYaml(csar, Constants.ABSTRACT_SUBSTITUTE_GLOBAL_TYPES_SERVICE_TEMPLATE, nodeTypes);
+
+ if (!nodeTypes.isEmpty()) {
+ Iterator<Entry<String, Object>> nodesNameEntry = nodeTypes.entrySet().iterator();
+ while (nodesNameEntry.hasNext()) {
+ Entry<String, Object> nodeType = nodesNameEntry.next();
+ addVfcToscaNameFindSubstitutes(csar, vfResourceName, vfcToscaNames, nodeType.getKey());
+ }
+ }
+ }
+ return vfcToscaNames;
+ }
+
+ @SuppressWarnings("unchecked")
+ private void putNodeTypesFromYaml(Map<String, byte[]> csar, String yamlFileName, Map<String, Object> nodeTypes) {
+
+ if (csar.containsKey(yamlFileName)) {
+ Map<String, Object> mappedToscaTemplate;
+ Either<Map<String, Object>, ResultStatusEnum> eitherNodeTypes;
+ mappedToscaTemplate = (Map<String, Object>) new Yaml().load(new String(csar.get(yamlFileName), StandardCharsets.UTF_8));
+ eitherNodeTypes = ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, ToscaTagNamesEnum.NODE_TYPES);
+ if (eitherNodeTypes.isLeft()) {
+ nodeTypes.putAll(eitherNodeTypes.left().value());
+ }
+ }
+ }
+
+ private void addVfcToscaNameFindSubstitutes(Map<String, byte[]> csar, String vfResourceName, List<ImmutablePair<ImmutablePair<String, List<String>>, String>> vfcToscaNames, String nodeTypeFullName) {
+
+ String toscaResourceName = buildNestedVfcToscaResourceName(vfResourceName, nodeTypeFullName);
+ String nodeTypeTemplateYamlName = buildNestedSubstituteYamlName(nodeTypeFullName);
+ List<String> relatedVfcsToscaNameSpaces = new ArrayList<>();
+ relatedVfcsToscaNameSpaces.add(buildNestedVfcToscaNamespace(nodeTypeFullName));
+ if (csar.containsKey(nodeTypeTemplateYamlName)) {
+ addSubstituteToscaNamespacesRecursively(csar, nodeTypeTemplateYamlName, relatedVfcsToscaNameSpaces);
+ }
+ ImmutablePair<String, List<String>> toscaNameSpacesHierarchy = new ImmutablePair<>(nodeTypeFullName, relatedVfcsToscaNameSpaces);
+ vfcToscaNames.add(new ImmutablePair<>(toscaNameSpacesHierarchy, toscaResourceName));
+ }
+
+ private void addSubstituteToscaNamespacesRecursively(Map<String, byte[]> csar, String yamlFileName, List<String> toscaNameSpaces) {
+
+ Map<String, Object> nodeTypes = new HashMap<>();
+
+ if (csar.containsKey(yamlFileName)) {
+ putNodeTypesFromYaml(csar, yamlFileName, nodeTypes);
+ }
+ if (!nodeTypes.isEmpty()) {
+ Iterator<Entry<String, Object>> nodesNameEntry = nodeTypes.entrySet().iterator();
+ while (nodesNameEntry.hasNext()) {
+ Entry<String, Object> nodeType = nodesNameEntry.next();
+ String nodeTypeFullName = nodeType.getKey();
+ String toscaNameSpace = buildNestedVfcToscaNamespace(nodeTypeFullName);
+ if (toscaNameSpaces.contains(toscaNameSpace)) {
+ break;
+ }
+ toscaNameSpaces.add(toscaNameSpace);
+
+ String nodeTypeTemplateYamlName = buildNestedSubstituteYamlName(nodeTypeFullName);
+
+ if (csar.containsKey(nodeTypeTemplateYamlName)) {
+ addSubstituteToscaNamespacesRecursively(csar, nodeTypeTemplateYamlName, toscaNameSpaces);
+ }
+ }
+ }
+ }
+
+ public Either<Resource, ResponseFormat> createResourceFromCsar(Resource resource, User user, Either<Map<String, byte[]>, StorageOperationStatus> csarUIPayload, String csarUUID) {
log.trace("************* created successfully from YAML, resource TOSCA ");
Either<Map<String, byte[]>, StorageOperationStatus> csar = null;
@@ -793,7 +1103,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
- public Either<Map<String, Resource>, ResponseFormat> createResourcesFromYamlNodeTypesList(String yamlName, Resource resource, String resourceYml, User user, boolean needLock) {
+ public Either<Map<String, Resource>, ResponseFormat> createResourcesFromYamlNodeTypesList(String yamlName, Resource resource, String resourceYml, User user, boolean needLock,
+ Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts) {
Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(resourceYml);
@@ -818,8 +1129,9 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
while (nodesNameValue.hasNext()) {
Entry<String, Object> nodeType = nodesNameValue.next();
+ Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = nodeTypesArtifactsToHandle == null || nodeTypesArtifactsToHandle.isEmpty() ? null : nodeTypesArtifactsToHandle.get(nodeType.getKey());
log.trace("************* Going to create node {}", nodeType.getKey());
- Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> resourceCreated = this.createNodeTypeResourceFromYaml(yamlName, nodeType, user, mapToConvert, resource, needLock);
+ Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> resourceCreated = this.createNodeTypeResourceFromYaml(yamlName, nodeType, user, mapToConvert, resource, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts);
log.trace("************* finished to create node {}", nodeType.getKey());
if (resourceCreated.isRight()) {
return Either.right(resourceCreated.right().value());
@@ -842,7 +1154,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return nameWithouNamespacePrefix.substring(resourceType.length());
}
- private Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createNodeTypeResourceFromYaml(String yamlName, Entry<String, Object> nodeNameValue, User user, Map<String, Object> mapToConvert, Resource resourceVf, boolean needLock) {
+ private Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createNodeTypeResourceFromYaml(String yamlName, Entry<String, Object> nodeNameValue, User user, Map<String, Object> mapToConvert, Resource resourceVf, boolean needLock,
+ Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts) {
Either<UploadResourceInfo, ResponseFormat> resourceMetaData = fillResourceMetadata(yamlName, resourceVf, nodeNameValue.getKey(), user);
if (resourceMetaData.isRight()) {
@@ -858,8 +1171,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
Map<String, Object> singleVfc = new HashMap<>();
String actualName = this.getNodeTypeActualName(nodeNameValue.getKey());
- if (!actualName.startsWith(ImportUtils.Constants.ABSTRACT_NODE)) {
- actualName = "." + ImportUtils.Constants.ABSTRACT_NODE + actualName;
+ if (!actualName.startsWith(Constants.ABSTRACT)) {
+ actualName = "." + Constants.ABSTRACT + actualName;
}
// Setting tosca name
@@ -875,7 +1188,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
user = eitherCreator.left().value();
- return this.createResourceFromNodeType(singleVfcYaml, resourceMetaData.left().value(), user, true, needLock);
+ return this.createResourceFromNodeType(singleVfcYaml, resourceMetaData.left().value(), user, true, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts);
}
public Either<Boolean, ResponseFormat> validateResourceCreationFromNodeType(Resource resource, User creator) {
@@ -887,11 +1200,12 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return Either.left(true);
}
- public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createResourceFromNodeType(String nodeTypeYaml, UploadResourceInfo resourceMetaData, User creator, boolean isInTransaction, boolean needLock) {
+ public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createResourceFromNodeType(String nodeTypeYaml, UploadResourceInfo resourceMetaData, User creator, boolean isInTransaction, boolean needLock,
+ Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts) {
LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction("certification on import", LifecycleChanceActionEnum.CREATE_FROM_CSAR);
Function<Resource, Either<Boolean, ResponseFormat>> validator = (resource) -> this.validateResourceCreationFromNodeType(resource, creator);
- return this.resourceImportManager.importCertifiedResource(nodeTypeYaml, resourceMetaData, creator, validator, lifecycleChangeInfo, isInTransaction, true, needLock);
+ return this.resourceImportManager.importCertifiedResource(nodeTypeYaml, resourceMetaData, creator, validator, lifecycleChangeInfo, isInTransaction, true, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts);
}
private Either<UploadResourceInfo, ResponseFormat> fillResourceMetadata(String yamlName, Resource resourceVf, String nodeTypeName, User user) {
@@ -915,7 +1229,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
resourceType = ResourceTypeEnum.VFC.name().toLowerCase();
}
// validating type
- if (!ResourceTypeEnum.contains(resourceType.toUpperCase())) {
+ if (!ResourceTypeEnum.containsName(resourceType.toUpperCase())) {
log.debug("invalid resourceType:{} the type is not one of the valide types:{}.", resourceType.toUpperCase(), ResourceTypeEnum.values());
ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, resourceMetaData.getName(), nodeTypeName);
return Either.right(responseFormat);
@@ -956,7 +1270,9 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
Map<String, byte[]> csar, List<ArtifactDefinition> createdArtifacts, String topologyTemplateYaml) {
boolean result = true;
-
+ boolean inTransaction = true;
+ Map<String, Resource> createdVfcs = new HashMap<>();
+ List<ArtifactDefinition> nodeTypesNewCreatedArtifacts = new ArrayList<>();
Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource, "Create Resource");
if (lockResult.isRight()) {
ResponseFormat responseFormat = lockResult.right().value();
@@ -966,7 +1282,12 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
try {
log.trace("************* createResourceFromYaml before full create resource {}", yamlName);
- Either<Resource, ResponseFormat> createResourcesEither = createResourceTransaction(resource, user, actionEnum, isNormative, true);
+ Either<Resource, ResponseFormat> genericResourceEither = fetchAndSetDerivedFromGenericType(resource);
+ if (genericResourceEither.isRight()) {
+ result = false;
+ return genericResourceEither;
+ }
+ Either<Resource, ResponseFormat> createResourcesEither = createResourceTransaction(resource, user, isNormative, inTransaction);
log.trace("************* createResourceFromYaml after full create resource {}", yamlName);
if (createResourcesEither.isRight()) {
result = false;
@@ -975,9 +1296,11 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
resource = createResourcesEither.left().value();
// add groups to resource
log.trace("************* Going to add inputs from yaml {}", yamlName);
+ if (resource.shouldGenerateInputs())
+ generateInputsFromGenericTypeProperties(resource, genericResourceEither.left().value());
Map<String, InputDefinition> inputs = parsedToscaYamlInfo.getInputs();
- Either<Resource, ResponseFormat> createInputsOnResource = createInputsOnResource(resource, user, inputs, true);
+ Either<Resource, ResponseFormat> createInputsOnResource = createInputsOnResource(resource, user, inputs, inTransaction);
if (createInputsOnResource.isRight()) {
result = false;
return createInputsOnResource;
@@ -987,7 +1310,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap = parsedToscaYamlInfo.getInstances();
log.trace("************* Going to create nodes, RI's and Relations from yaml {}", yamlName);
- createResourcesEither = createRIAndRelationsFromYaml(yamlName, resource, user, uploadComponentInstanceInfoMap, actionEnum, topologyTemplateYaml, csar, csarUUID);
+ createResourcesEither = createRIAndRelationsFromYaml(yamlName, resource, user, uploadComponentInstanceInfoMap, actionEnum, topologyTemplateYaml, csar, csarUUID, nodeTypesNewCreatedArtifacts, createdVfcs);
log.trace("************* Finished to create nodes, RI and Relation from yaml {}", yamlName);
if (createResourcesEither.isRight()) {
result = false;
@@ -1019,14 +1342,15 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
log.trace("************* Finished to add groups from yaml {}", yamlName);
log.trace("************* Going to add artifacts from yaml {}", yamlName);
- Either<Resource, ResponseFormat> createdCsarArtifactsEither = this.handleCsarArtifacts(resource, user, csarUUID, csar, createdArtifacts, ArtifactOperation.Create, false, true);
+ Either<Resource, ResponseFormat> createdCsarArtifactsEither = this.handleCsarArtifacts(resource, user, csarUUID, csar, createdArtifacts, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Create), false,
+ inTransaction);
log.trace("************* Finished to add artifacts from yaml {}", yamlName);
if (createdCsarArtifactsEither.isRight()) {
result = false;
return createdCsarArtifactsEither;
}
- resource = createdCsarArtifactsEither.left().value();
+ resource = createdCsarArtifactsEither.left().value();
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
ASDCKpiApi.countCreatedResourcesKPI();
@@ -1035,8 +1359,9 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
} finally {
if (!result) {
log.warn("operation failed. do rollback");
- titanGenericDao.rollback();
- if (!createdArtifacts.isEmpty()) {
+ titanDao.rollback();
+ if (!createdArtifacts.isEmpty() || !nodeTypesNewCreatedArtifacts.isEmpty()) {
+ createdArtifacts.addAll(nodeTypesNewCreatedArtifacts);
StorageOperationStatus deleteFromEsRes = artifactsBusinessLogic.deleteAllComponentArtifactsIfNotOnGraph(createdArtifacts);
if (!deleteFromEsRes.equals(StorageOperationStatus.OK)) {
ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(deleteFromEsRes);
@@ -1047,7 +1372,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
} else {
log.debug("operation success. do commit");
- titanGenericDao.commit();
+ titanDao.commit();
}
graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(), NodeTypeEnum.Resource);
@@ -1057,7 +1382,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
private Either<Resource, ResponseFormat> createGroupsOnResource(Resource resource, User user, Map<String, GroupDefinition> groups) {
- if (groups != null && false == groups.isEmpty()) {
+ if (groups != null && !groups.isEmpty()) {
Either<List<GroupDefinition>, ResponseFormat> mergeGroupsUsingResource = updateGroupMembersUsingResource(groups, resource);
if (mergeGroupsUsingResource.isRight()) {
@@ -1065,22 +1390,14 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return Either.right(mergeGroupsUsingResource.right().value());
}
List<GroupDefinition> groupsAsList = mergeGroupsUsingResource.left().value();
-
- // Either<List<GroupDefinition>, ResponseFormat> createGroups =
- // groupBusinessLogic.createGroups(
- // resource.getUniqueId(), user.getUserId(),
- // ComponentTypeEnum.RESOURCE, groupsAsList, false,
- // true);
- // In this method we assume all instances exists in resource
- Either<List<GroupDefinition>, ResponseFormat> createGroups = groupBusinessLogic.createGroups(resource, user, ComponentTypeEnum.RESOURCE, groupsAsList, true);
+ Either<List<GroupDefinition>, ResponseFormat> createGroups = groupBusinessLogic.createGroups(resource, user, ComponentTypeEnum.RESOURCE, groupsAsList);
if (createGroups.isRight()) {
return Either.right(createGroups.right().value());
}
} else {
return Either.left(resource);
}
-
- Either<Resource, StorageOperationStatus> updatedResource = resourceOperation.getResource(resource.getUniqueId(), true);
+ Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
if (updatedResource.isRight()) {
ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource);
return Either.right(responseFormat);
@@ -1122,42 +1439,31 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
} else
groupsToCreate.addAll(groupsAsList);
-
+ Either<List<GroupDefinition>, ResponseFormat> prepareGroups = null;
if (!groupsToCreate.isEmpty()) {
- Either<List<GroupDefinition>, ResponseFormat> createGroups = groupBusinessLogic.createGroups(resource, user, ComponentTypeEnum.RESOURCE, groupsToCreate, true);
- if (createGroups.isRight()) {
- return Either.right(createGroups.right().value());
+ if (groupsFromResource != null && !groupsFromResource.isEmpty()) {
+ prepareGroups = groupBusinessLogic.addGroups(resource, user, ComponentTypeEnum.RESOURCE, groupsToCreate);
+ } else {
+ prepareGroups = groupBusinessLogic.createGroups(resource, user, ComponentTypeEnum.RESOURCE, groupsToCreate);
}
- }
- if (!groupsToDelete.isEmpty()) {
- for (GroupDefinition group : groupsToDelete) {
- Either<GroupDefinition, StorageOperationStatus> deleteGroupEither = groupOperation.deleteGroup(group.getUniqueId(), true);
- if (deleteGroupEither.isRight()) {
- StorageOperationStatus storageOperationStatus = deleteGroupEither.right().value();
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageOperationStatus);
- log.debug("Failed to delete group {} under component {}, error: {}", group.getUniqueId(), resource.getNormalizedName(), actionStatus.name());
- return Either.right(componentsUtils.getResponseFormat(actionStatus));
- }
+ if (prepareGroups.isRight()) {
+ return Either.right(prepareGroups.right().value());
}
}
- if (groupsToUpdate != null && !groupsToUpdate.isEmpty()) {
- Either<List<GroupDefinition>, ResponseFormat> assotiateGroupEither = groupBusinessLogic.associateMembersToGroup(resource.getUniqueId(), user.getUserId(), ComponentTypeEnum.RESOURCE, groupsToUpdate, false, true);
- if (assotiateGroupEither.isRight()) {
- log.debug("Failed to associate artifacts to groups. Status is {} ", assotiateGroupEither.right().value());
- return Either.right(assotiateGroupEither.right().value());
+ if (!groupsToDelete.isEmpty()) {
+ prepareGroups = groupBusinessLogic.deleteGroups(resource, user, ComponentTypeEnum.RESOURCE, groupsToDelete);
+ if (prepareGroups.isRight()) {
+ return Either.right(prepareGroups.right().value());
}
- List<GroupDefinition> updatedGroups = assotiateGroupEither.left().value();
- List<String> groupsId = updatedGroups.stream().map(e -> e.getUniqueId()).collect(Collectors.toList());
-
- Either<List<GroupDefinition>, StorageOperationStatus> updateVersionEither = groupBusinessLogic.updateGroupVersion(groupsId, true);
- if (updateVersionEither.isRight()) {
- log.debug("Failed to update groups version. Status is {} ", updateVersionEither.right().value());
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(updateVersionEither.right().value()), resource);
- return Either.right(responseFormat);
+ }
+ if (groupsToUpdate != null && !groupsToUpdate.isEmpty()) {
+ prepareGroups = groupBusinessLogic.updateGroups(resource, ComponentTypeEnum.RESOURCE, groupsToUpdate);
+ if (prepareGroups.isRight()) {
+ return Either.right(prepareGroups.right().value());
}
}
@@ -1165,7 +1471,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return Either.left(resource);
}
- Either<Resource, StorageOperationStatus> updatedResource = resourceOperation.getResource(resource.getUniqueId(), true);
+ Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
if (updatedResource.isRight()) {
ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource);
return Either.right(responseFormat);
@@ -1175,13 +1481,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
private Either<Resource, ResponseFormat> createInputsOnResource(Resource resource, User user, Map<String, InputDefinition> inputs, boolean inTransaction) {
if (inputs != null && false == inputs.isEmpty()) {
- List<InputDefinition> inputsAsList = new ArrayList<InputDefinition>();
- for (Entry<String, InputDefinition> entry : inputs.entrySet()) {
- InputDefinition input = entry.getValue();
- input.setName(entry.getKey());
- inputsAsList.add(input);
- }
- Either<List<InputDefinition>, ResponseFormat> createGroups = inputsBusinessLogic.createInputsInGraph(inputsAsList, resource, user, inTransaction);
+
+ Either<List<InputDefinition>, ResponseFormat> createGroups = inputsBusinessLogic.createInputsInGraph(inputs, resource, user, inTransaction);
if (createGroups.isRight()) {
return Either.right(createGroups.right().value());
}
@@ -1189,7 +1490,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return Either.left(resource);
}
- Either<Resource, StorageOperationStatus> updatedResource = resourceOperation.getResource(resource.getUniqueId(), true);
+ Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
if (updatedResource.isRight()) {
ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource);
return Either.right(responseFormat);
@@ -1204,6 +1505,10 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
List<ComponentInstance> componentInstances = component.getComponentInstances();
if (groups != null) {
+ Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies = validateCyclicGroupsDependencies(groups);
+ if (validateCyclicGroupsDependencies.isRight()) {
+ return FunctionalInterfaces.convertEitherRight(validateCyclicGroupsDependencies);
+ }
for (Entry<String, GroupDefinition> entry : groups.entrySet()) {
String groupName = entry.getKey();
@@ -1219,7 +1524,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (componentInstances == null || true == componentInstances.isEmpty()) {
String membersAstString = compInstancesNames.stream().collect(Collectors.joining(","));
- log.debug("The members {} in group {} cannot be found in component {}. There are no component instances", membersAstString, groupName, component.getNormalizedName());
+ log.debug("The members: {}, in group: {}, cannot be found in component {}. There are no component instances.", membersAstString, groupName, component.getNormalizedName());
return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, component.getNormalizedName(), getComponentTypeForResponse(component)));
}
// Find all component instances with the member names
@@ -1235,7 +1540,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
compInstancesNames.removeAll(foundMembers);
String membersAstString = compInstancesNames.stream().collect(Collectors.joining(","));
- log.debug("The members {} in group {} cannot be found in component {}", membersAstString, groupName, component.getNormalizedName());
+ log.debug("The members: {}, in group: {}, cannot be found in component: {}", membersAstString, groupName, component.getNormalizedName());
return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, component.getNormalizedName(), getComponentTypeForResponse(component)));
}
@@ -1248,19 +1553,116 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return Either.left(result);
}
+ /**
+ * This Method validates that there is no cyclic group dependencies. meaning group A as member in group B which is member in group A
+ *
+ * @param allGroups
+ * @return
+ */
+ private Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies(Map<String, GroupDefinition> allGroups) {
+
+ Either<Boolean, ResponseFormat> result = Either.left(true);
+ try {
+ Iterator<Entry<String, GroupDefinition>> allGroupsItr = allGroups.entrySet().iterator();
+ while (allGroupsItr.hasNext() && result.isLeft()) {
+ Entry<String, GroupDefinition> groupAEntry = allGroupsItr.next();
+ // Fetches a group member A
+ String groupAName = groupAEntry.getKey();
+ // Finds all group members in group A
+ Set<String> allGroupAMembersNames = new HashSet<>();
+ fillAllGroupMemebersRecursivly(groupAEntry.getKey(), allGroups, allGroupAMembersNames);
+ // If A is a group member of itself found cyclic dependency
+ if (allGroupAMembersNames.contains(groupAName)) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GROUP_HAS_CYCLIC_DEPENDENCY, groupAName);
+ result = Either.right(responseFormat);
+ }
+ }
+ } catch (Exception e) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
+ result = Either.right(responseFormat);
+ log.debug("Exception occured when validateCyclicGroupsDependencies, error is:{}", e.getMessage(), e);
+ }
+ return result;
+ }
+
+ /**
+ * This Method fills recursively the set groupMembers with all the members of the given group which are also of type group.
+ *
+ * @param groupName
+ * @param allGroups
+ * @param allGroupMembers
+ * @return
+ */
+ private void fillAllGroupMemebersRecursivly(String groupName, Map<String, GroupDefinition> allGroups, Set<String> allGroupMembers) {
+
+ // Found Cyclic dependency
+ if (isfillGroupMemebersRecursivlyStopCondition(groupName, allGroups, allGroupMembers)) {
+ return;
+ }
+ GroupDefinition groupDefinition = allGroups.get(groupName);
+ // All Members Of Current Group Resource Instances & Other Groups
+ Set<String> currGroupMembers = groupDefinition.getMembers().keySet();
+ // Filtered Members Of Current Group containing only members which
+ // are groups
+ List<String> currGroupFilteredMembers = currGroupMembers.stream().
+ // Keep Only Elements of type group and not Resource Instances
+ filter(innerGroupName -> allGroups.containsKey(innerGroupName)).
+ // Add Filtered Elements to main Set
+ peek(innerGroupName -> allGroupMembers.add(innerGroupName)).
+ // Collect results
+ collect(Collectors.toList());
+
+ // Recursively call the method for all the filtered group members
+ for (String innerGroupName : currGroupFilteredMembers) {
+ fillAllGroupMemebersRecursivly(innerGroupName, allGroups, allGroupMembers);
+ }
+
+ }
+
+ private boolean isfillGroupMemebersRecursivlyStopCondition(String groupName, Map<String, GroupDefinition> allGroups, Set<String> allGroupMembers) {
+
+ boolean stop = false;
+ // In Case Not Group Stop
+ if (!allGroups.containsKey(groupName)) {
+ stop = true;
+ }
+ // In Case Group Has no members stop
+ if (!stop) {
+ GroupDefinition groupDefinition = allGroups.get(groupName);
+ stop = MapUtils.isEmpty(groupDefinition.getMembers());
+
+ }
+ // In Case all group members already contained stop
+ if (!stop) {
+ final Set<String> allMembers = allGroups.get(groupName).getMembers().keySet();
+ Set<String> membersOfTypeGroup = allMembers.stream().
+ // Filter In Only Group members
+ filter(innerGroupName -> allGroups.containsKey(innerGroupName)).
+ // Collect
+ collect(Collectors.toSet());
+ stop = allGroupMembers.containsAll(membersOfTypeGroup);
+ }
+ return stop;
+ }
+
private Either<Resource, ResponseFormat> createRIAndRelationsFromYaml(String yamlName, Resource resource, User user, Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap, AuditingActionEnum actionEnum,
- String topologyTemplateYaml, Map<String, byte[]> csar, String csarUUID) {
+ String topologyTemplateYaml, Map<String, byte[]> csar, String csarUUID, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, Resource> createdVfcs) {
Either<Resource, ResponseFormat> result;
Either<Resource, ResponseFormat> createResourcesInstancesEither;
+
+ Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate = findNodeTypeArtifactsToCreate(csar, yamlName, resource);
+
log.debug("************* Going to create all nodes {}", yamlName);
- Either<Map<String, Resource>, ResponseFormat> createdResourcesFromdNodeTypeMap = this.handleNodeTypes(yamlName, resource, user, topologyTemplateYaml, csar, false);
+ Either<Map<String, Resource>, ResponseFormat> createdResourcesFromdNodeTypeMap = this.handleNodeTypes(yamlName, resource, user, topologyTemplateYaml, csar, false, nodeTypesArtifactsToCreate, nodeTypesNewCreatedArtifacts);
log.debug("************* Finished to create all nodes {}", yamlName);
if (createdResourcesFromdNodeTypeMap.isRight()) {
log.debug("failed to resources from node types status is {}", createdResourcesFromdNodeTypeMap.right().value());
return Either.right(createdResourcesFromdNodeTypeMap.right().value());
}
+ createdVfcs.putAll(createdResourcesFromdNodeTypeMap.left().value());
+
log.debug("************* Going to create all resource instances {}", yamlName);
createResourcesInstancesEither = createResourceInstances(user, yamlName, resource, uploadComponentInstanceInfoMap, true, false, createdResourcesFromdNodeTypeMap.left().value());
@@ -1292,17 +1694,66 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return result;
}
- private Either<Map<String, Resource>, ResponseFormat> handleNodeTypes(String yamlName, Resource resource, User user, String topologyTemplateYaml, Map<String, byte[]> csar, boolean needLock) {
+ private Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> findNodeTypeArtifactsToCreate(Map<String, byte[]> csar, String yamlName, Resource resource) {
+
+ Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts = CsarUtils.extractVfcsArtifactsFromCsar(csar);
+ List<ImmutablePair<ImmutablePair<String, List<String>>, String>> extractedVfcToscaNames = extractVfcToscaNames(csar, yamlName, resource.getSystemName());
+ validateNodeTypeIdentifiers(extractedVfcsArtifacts, extractedVfcToscaNames);
+ Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = null;
+ if (!extractedVfcsArtifacts.isEmpty() && !extractedVfcToscaNames.isEmpty()) {
+ for (ImmutablePair<ImmutablePair<String, List<String>>, String> currToscaNamePair : extractedVfcToscaNames) {
+ EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> curNodeTypeArtifacts = null;
+ String currVfcToscaNamespace = currToscaNamePair.getKey().getKey();
+ List<String> relatedVfcs = currToscaNamePair.getKey().getValue();
+ List<ArtifactDefinition> currArtifactList = null;
+
+ for (String currSubstitute : relatedVfcs) {
+ if (extractedVfcsArtifacts.containsKey(currSubstitute)) {
+ if (MapUtils.isEmpty(curNodeTypeArtifacts)) {
+ curNodeTypeArtifacts = new EnumMap<>(ArtifactOperationEnum.class);
+ currArtifactList = new ArrayList<>();
+ curNodeTypeArtifacts.put(ArtifactOperationEnum.Create, currArtifactList);
+ } else {
+ currArtifactList = curNodeTypeArtifacts.get(ArtifactOperationEnum.Create);
+ }
+ handleAndAddExtractedVfcsArtifacts(currArtifactList, extractedVfcsArtifacts.get(currSubstitute));
+ }
+ }
+
+ if (nodeTypesArtifactsToHandle == null) {
+ nodeTypesArtifactsToHandle = new HashMap<>();
+ }
+ nodeTypesArtifactsToHandle.put(currVfcToscaNamespace, curNodeTypeArtifacts);
+ }
+ }
+ return nodeTypesArtifactsToHandle;
+ }
+
+ private void handleAndAddExtractedVfcsArtifacts(List<ArtifactDefinition> vfcArtifacts, List<ArtifactDefinition> artifactsToAdd) {
+ List<String> vfcArtifactNames = vfcArtifacts.stream().map(a -> a.getArtifactName()).collect(Collectors.toList());
+ artifactsToAdd.stream().forEach(a -> {
+ if (!vfcArtifactNames.contains(a.getArtifactName())) {
+ vfcArtifacts.add(a);
+ } else {
+ log.error("Can't upload two artifact with the same name {}. ", a.getArtifactName());
+ }
+ });
+
+ }
+
+ private Either<Map<String, Resource>, ResponseFormat> handleNodeTypes(String yamlName, Resource resource, User user, String topologyTemplateYaml, Map<String, byte[]> csar, boolean needLock,
+ Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts) {
Map<String, Resource> createdResourcesFromdNodeTypeMap = new HashMap<>();
Either<Map<String, Resource>, ResponseFormat> result = Either.left(createdResourcesFromdNodeTypeMap);
- String yamlFileName = Constants.GLOBAL_SUBSTITUTION_TYPE_SERVICE_TEMPLATE;
+ String yamlFileName = Constants.GLOBAL_SUBSTITUTION_TYPES_SERVICE_TEMPLATE;
if (csar != null && csar.containsKey(yamlFileName)) {
byte[] yamlFileBytes = csar.get(yamlFileName);
String globalTypesYaml = new String(yamlFileBytes, StandardCharsets.UTF_8);
- Either<Map<String, Resource>, ResponseFormat> createdNodeTypesFromGlobalTypesTemplateEither = this.createResourcesFromYamlNodeTypesList(yamlFileName, resource, globalTypesYaml, user, needLock);
+ Either<Map<String, Resource>, ResponseFormat> createdNodeTypesFromGlobalTypesTemplateEither = this.createResourcesFromYamlNodeTypesList(yamlFileName, resource, globalTypesYaml, user, needLock, nodeTypesArtifactsToHandle,
+ nodeTypesNewCreatedArtifacts);
if (createdNodeTypesFromGlobalTypesTemplateEither.isRight()) {
ResponseFormat responseFormat = createdNodeTypesFromGlobalTypesTemplateEither.right().value();
componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
@@ -1311,7 +1762,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
createdResourcesFromdNodeTypeMap.putAll(createdNodeTypesFromGlobalTypesTemplateEither.left().value());
}
- Either<Map<String, Resource>, ResponseFormat> createdNodeTypeFromMainTemplateEither = createResourcesFromYamlNodeTypesList(yamlName, resource, topologyTemplateYaml, user, needLock);
+ Either<Map<String, Resource>, ResponseFormat> createdNodeTypeFromMainTemplateEither = createResourcesFromYamlNodeTypesList(yamlName, resource, topologyTemplateYaml, user, needLock, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts);
if (createdNodeTypeFromMainTemplateEither.isRight()) {
ResponseFormat responseFormat = createdNodeTypeFromMainTemplateEither.right().value();
componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
@@ -1327,14 +1778,14 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return result;
}
- private Either<Resource, ResponseFormat> handleCsarArtifacts(Resource resource, User user, String csarUUID, Map<String, byte[]> csar, List<ArtifactDefinition> createdArtifacts, ArtifactOperation artifactOperation, boolean shouldLock,
+ private Either<Resource, ResponseFormat> handleCsarArtifacts(Resource resource, User user, String csarUUID, Map<String, byte[]> csar, List<ArtifactDefinition> createdArtifacts, ArtifactOperationInfo artifactOperation, boolean shouldLock,
boolean inTransaction) {
if (csar != null) {
String vendorLicenseModelId = null;
String vfLicenseModelId = null;
- if (artifactOperation.equals(ArtifactOperation.Update)) {
+ if (artifactOperation.getArtifactOperationEnum() == ArtifactOperationEnum.Update) {
Map<String, ArtifactDefinition> deploymentArtifactsMap = resource.getDeploymentArtifacts();
if (deploymentArtifactsMap != null && !deploymentArtifactsMap.isEmpty()) {
for (Entry<String, ArtifactDefinition> artifactEntry : deploymentArtifactsMap.entrySet()) {
@@ -1346,17 +1797,24 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
}
- createOrUpdateLicenseArtifact(resource, user, csarUUID, csar, Constants.VENDOR_LICENSE_MODEL, ArtifactTypeEnum.VENDOR_LICENSE.getType(), Constants.VENDOR_LICENSE_LABEL, Constants.VENDOR_LICENSE_DISPLAY_NAME,
- Constants.VENDOR_LICENSE_DESCRIPTION, vendorLicenseModelId, artifactOperation, shouldLock, inTransaction);
- createOrUpdateLicenseArtifact(resource, user, csarUUID, csar, Constants.VF_LICENSE_MODEL, ArtifactTypeEnum.VF_LICENSE.getType(), Constants.VF_LICENSE_LABEL, Constants.VF_LICENSE_DISPLAY_NAME, Constants.VF_LICENSE_DESCRIPTION,
- vfLicenseModelId, artifactOperation, shouldLock, inTransaction);
+ // Specific Behavior for license artifacts
+ createOrUpdateSingleNonMetaArtifact(resource, user, csarUUID, csar, CsarUtils.ARTIFACTS_PATH + Constants.VENDOR_LICENSE_MODEL, Constants.VENDOR_LICENSE_MODEL, ArtifactTypeEnum.VENDOR_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT,
+ Constants.VENDOR_LICENSE_LABEL, Constants.VENDOR_LICENSE_DISPLAY_NAME, Constants.VENDOR_LICENSE_DESCRIPTION, vendorLicenseModelId, artifactOperation, null, shouldLock, inTransaction);
+ createOrUpdateSingleNonMetaArtifact(resource, user, csarUUID, csar, CsarUtils.ARTIFACTS_PATH + Constants.VF_LICENSE_MODEL, Constants.VF_LICENSE_MODEL, ArtifactTypeEnum.VF_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT,
+ Constants.VF_LICENSE_LABEL, Constants.VF_LICENSE_DISPLAY_NAME, Constants.VF_LICENSE_DESCRIPTION, vfLicenseModelId, artifactOperation, null, shouldLock, inTransaction);
+
+ Either<Resource, ResponseFormat> eitherCreateResult = createOrUpdateNonMetaArtifacts(csarUUID, csar, resource, user, createdArtifacts, shouldLock, inTransaction, artifactOperation);
+ if (eitherCreateResult.isRight()) {
+ return Either.right(eitherCreateResult.right().value());
+ }
+
Either<ImmutablePair<String, String>, ResponseFormat> artifacsMetaCsarStatus = CsarValidationUtils.getArtifactsMeta(csar, csarUUID, componentsUtils);
if (artifacsMetaCsarStatus.isLeft()) {
String artifactsFileName = artifacsMetaCsarStatus.left().value().getKey();
String artifactsContents = artifacsMetaCsarStatus.left().value().getValue();
Either<Resource, ResponseFormat> createArtifactsFromCsar = Either.left(resource);
- if (artifactOperation.equals(ArtifactOperation.Create))
+ if (artifactOperation.getArtifactOperationEnum() == ArtifactOperationEnum.Create)
createArtifactsFromCsar = createResourceArtifactsFromCsar(csarUUID, csar, resource, user, artifactsContents, artifactsFileName, createdArtifacts, shouldLock, inTransaction);
else
createArtifactsFromCsar = updateResourceArtifactsFromCsar(csarUUID, csar, resource, user, artifactsContents, artifactsFileName, createdArtifacts, shouldLock, inTransaction);
@@ -1371,19 +1829,12 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (groupsToDelete != null && !groupsToDelete.isEmpty()) {
Set<String> artifactsToDelete = new HashSet<String>();
- for (GroupDefinition group : groupsToDelete) {
- List<String> artifacts = group.getArtifacts();
- if (artifacts != null) {
- artifactsToDelete.addAll(artifacts);
- Either<GroupDefinition, StorageOperationStatus> deleteGroupEither = groupOperation.deleteGroup(group.getUniqueId(), inTransaction);
- if (deleteGroupEither.isRight()) {
- StorageOperationStatus storageOperationStatus = deleteGroupEither.right().value();
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageOperationStatus);
- log.debug("Failed to delete group {} under component {}, error: {}", group.getUniqueId(), resource.getNormalizedName(), actionStatus.name());
- return Either.right(componentsUtils.getResponseFormat(actionStatus));
- }
- }
- }
+ /*
+ * for (GroupDefinition group : groupsToDelete) { List<String> artifacts = group.getArtifacts(); if (artifacts != null) { artifactsToDelete.addAll(artifacts); Either<GroupDefinition, StorageOperationStatus> deleteGroupEither =
+ * groupOperation.deleteGroup(group.getUniqueId(), inTransaction); if (deleteGroupEither.isRight()) { StorageOperationStatus storageOperationStatus = deleteGroupEither.right().value(); ActionStatus actionStatus =
+ * componentsUtils.convertFromStorageResponse(storageOperationStatus); log.debug("Failed to delete group {} under component {}, error: {}", group.getUniqueId(), resource.getNormalizedName(), actionStatus.name()); return
+ * Either.right(componentsUtils.getResponseFormat(actionStatus)); } } }
+ */
for (String artifactId : artifactsToDelete) {
Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = artifactsBusinessLogic.handleDelete(resource.getUniqueId(), artifactId, user, AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE,
resource, null, null, shouldLock, inTransaction);
@@ -1391,31 +1842,31 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
log.debug("Couldn't delete artifact {}", artifactId);
return Either.right(handleDelete.right().value());
}
-
}
- Either<Resource, StorageOperationStatus> eitherGerResource = resourceOperation.getResource(resource.getUniqueId(), inTransaction);
- if (eitherGerResource.isRight()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
+ Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
+ if (eitherGetResource.isRight()) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource);
return Either.right(responseFormat);
}
- resource = eitherGerResource.left().value();
+ resource = eitherGetResource.left().value();
}
}
}
return Either.left(resource);
}
- private Either<Boolean, ResponseFormat> createOrUpdateLicenseArtifact(Resource resource, User user, String csarUUID, Map<String, byte[]> csar, String artifactFileName, String artifactType, String artifactLabel, String artifactDisplayName,
- String artifactDescription, String artifactId, ArtifactOperation operation, boolean shouldLock, boolean inTransaction) {
+ private Either<Boolean, ResponseFormat> createOrUpdateSingleNonMetaArtifact(Resource resource, User user, String csarUUID, Map<String, byte[]> csar, String artifactPath, String artifactFileName, String artifactType,
+ ArtifactGroupTypeEnum artifactGroupType, String artifactLabel, String artifactDisplayName, String artifactDescription, String artifactId, ArtifactOperationInfo operation, List<ArtifactDefinition> createdArtifacts, boolean shouldLock,
+ boolean inTransaction) {
byte[] artifactFileBytes = null;
- if (csar.containsKey(Constants.ARTIFACTS + artifactFileName)) {
- artifactFileBytes = csar.get(Constants.ARTIFACTS + artifactFileName);
+ if (csar.containsKey(artifactPath)) {
+ artifactFileBytes = csar.get(artifactPath);
}
Either<Boolean, ResponseFormat> result = Either.left(true);
- if (operation.equals(ArtifactOperation.Update)) {
+ if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Update || operation.getArtifactOperationEnum() == ArtifactOperationEnum.Delete) {
if (artifactId != null && !artifactId.isEmpty() && artifactFileBytes == null) {
Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = artifactsBusinessLogic.handleDelete(resource.getUniqueId(), artifactId, user, AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, resource, null,
null, shouldLock, inTransaction);
@@ -1426,31 +1877,40 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
if ((artifactId == null || artifactId.isEmpty()) && artifactFileBytes != null) {
- operation = ArtifactOperation.Create;
+ operation = artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Create);
}
}
if (artifactFileBytes != null) {
- Map<String, Object> vendorLicenseModelJson = buildJsonForUpdateArtifact(artifactId, artifactFileName, artifactType, artifactLabel, artifactDisplayName, artifactDescription, artifactFileBytes, null);
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> vfLicenceArtifactCreateEither = createOrUpdateCsarArtifactFromJson(resource, user, vendorLicenseModelJson, operation, shouldLock, inTransaction);
-
- if (vfLicenceArtifactCreateEither.isRight()) {
+ Map<String, Object> vendorLicenseModelJson = buildJsonForUpdateArtifact(artifactId, artifactFileName, artifactType, artifactGroupType, artifactLabel, artifactDisplayName, artifactDescription, artifactFileBytes, null);
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts = createOrUpdateCsarArtifactFromJson(resource, user, vendorLicenseModelJson, operation, shouldLock, inTransaction);
+ addNonMetaCreatedArtifactsToSupportRollback(operation, createdArtifacts, eitherNonMetaArtifacts);
+ if (eitherNonMetaArtifacts.isRight()) {
BeEcompErrorManager.getInstance().logInternalFlowError("UploadLicenseArtifact", "Failed to upload license artifact: " + artifactFileName + "With csar uuid: " + csarUUID, ErrorSeverity.WARNING);
- return Either.right(vfLicenceArtifactCreateEither.right().value());
+ return Either.right(eitherNonMetaArtifacts.right().value());
}
}
return result;
}
- private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> createOrUpdateCsarArtifactFromJson(Resource resource, User user, Map<String, Object> json, ArtifactOperation operation, boolean shoudLock, boolean inTransaction) {
+ private void addNonMetaCreatedArtifactsToSupportRollback(ArtifactOperationInfo operation, List<ArtifactDefinition> createdArtifacts, Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts) {
+ if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create && createdArtifacts != null && eitherNonMetaArtifacts.isLeft()) {
+ Either<ArtifactDefinition, Operation> eitherResult = eitherNonMetaArtifacts.left().value();
+ if (eitherResult.isLeft()) {
+ createdArtifacts.add(eitherResult.left().value());
+ }
+ }
+ }
+
+ private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> createOrUpdateCsarArtifactFromJson(Resource resource, User user, Map<String, Object> json, ArtifactOperationInfo operation, boolean shoudLock, boolean inTransaction) {
String jsonStr = gson.toJson(json);
String origMd5 = GeneralUtility.calculateMD5ByString(jsonStr);
ArtifactDefinition artifactDefinitionFromJson = RepresentationUtils.convertJsonToArtifactDefinition(jsonStr, ArtifactDefinition.class);
-
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = artifactsBusinessLogic.handleArtifactRequest(resource.getUniqueId(), user.getUserId(), ComponentTypeEnum.RESOURCE, operation,
- artifactDefinitionFromJson.getUniqueId(), artifactDefinitionFromJson, origMd5, jsonStr, null, null, null, null, shoudLock, inTransaction);
+ String artifactUniqueId = artifactDefinitionFromJson == null ? null : artifactDefinitionFromJson.getUniqueId();
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = artifactsBusinessLogic.validateAndHandleArtifact(resource.getUniqueId(), ComponentTypeEnum.RESOURCE, operation, artifactUniqueId,
+ artifactDefinitionFromJson, origMd5, jsonStr, null, null, null, user, resource, false, true);
if (uploadArtifactToService.isRight())
return Either.right(uploadArtifactToService.right().value());
@@ -1489,37 +1949,6 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
return createResourceArtifacts(csarUUID, csar, resource, user, parseResourceInfoFromYamlEither.left().value(), AuditingActionEnum.CREATE_RESOURCE, createdNewArtifacts, shouldLock, inTransaction);
}
- // find artifacts to delete
- Set<String> artifactNotInGroupSet = findArtifactsNotInGroupToDelete(groups, createdDeplymentArtifactsAfterDelete);
-
- // delete all artifacts which not in groups
- if (!artifactNotInGroupSet.isEmpty()) {
- for (String artifactId : artifactNotInGroupSet) {
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = artifactsBusinessLogic.handleDelete(resource.getUniqueId(), artifactId, user, AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, resource, null,
- null, shouldLock, inTransaction);
- if (handleDelete.isRight()) {
- return Either.right(handleDelete.right().value());
- }
-
- }
- Either<Resource, StorageOperationStatus> eitherGerResource = resourceOperation.getResource(resource.getUniqueId(), inTransaction);
- if (eitherGerResource.isRight()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
-
- return Either.right(responseFormat);
-
- }
-
- resource = eitherGerResource.left().value();
- deplymentArtifact = resource.getDeploymentArtifacts();
-
- createdDeplymentArtifactsAfterDelete.clear();
- if (deplymentArtifact != null && !deplymentArtifact.isEmpty()) {
- for (Entry<String, ArtifactDefinition> entry : deplymentArtifact.entrySet()) {
- createdDeplymentArtifactsAfterDelete.add(entry.getValue());
- }
- }
- }
// find master in group
Map<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupArtifact = findMasterArtifactInGroup(groups, deplymentArtifact);
@@ -1551,18 +1980,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
Map<String, List<String>> dissocArtifactFromGroup = new HashMap<String, List<String>>();
Set<ArtifactTemplateInfo> jsonMasterArtifacts = parsedGroup.keySet();
-
- Map<GroupDefinition, MergedArtifactInfo> mergedgroup = mergeGroupInUpdateFlow(groupArtifact, parsedGroup, artifactsToDelete, groupToDelete, jsonMasterArtifacts);
-
- // find artifacts to delete
- for (Entry<String, List<ArtifactDefinition>> deleteGroup : groupToDelete.entrySet()) {
-
- List<ArtifactDefinition> artifacts = deleteGroup.getValue();
- for (ArtifactDefinition artifact : artifacts) {
- findArtifactToDelete(parsedGroup, artifactsToDelete, deleteGroup.getKey(), artifact);
- }
-
- }
+ Map<GroupDefinition, MergedArtifactInfo> mergedgroup = mergeGroupInUpdateFlow(groupArtifact, parsedGroup, artifactsToDelete, groupToDelete, jsonMasterArtifacts, createdDeplymentArtifactsAfterDelete);
// Set<String> deletedArtifactsName = new HashSet<String>();
Either<List<ArtifactDefinition>, ResponseFormat> deletedArtifactsEither = deleteArtifactsInUpdateCsarFlow(resource, user, shouldLock, inTransaction, artifactsToDelete, groupToDelete);
@@ -1602,24 +2020,25 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
resource = assDissotiateEither.left().value();
+ deplymentArtifact = resource.getDeploymentArtifacts();
+ createdDeplymentArtifactsAfterDelete.clear();
+ if (deplymentArtifact != null && !deplymentArtifact.isEmpty()) {
+ for (Entry<String, ArtifactDefinition> entry : deplymentArtifact.entrySet()) {
+ createdDeplymentArtifactsAfterDelete.add(entry.getValue());
+ }
+ }
+
groups = resource.getGroups();
List<GroupDefinition> groupToUpdate = new ArrayList<>();
// update vfModule names
Set<GroupDefinition> groupForAssociateWithMembers = mergedgroup.keySet();
if (groups != null && !groups.isEmpty()) {
- Either<List<GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic.validateUpdateVfGroupNamesOnGraph(groups, resource.getSystemName(), inTransaction);
+ Either<List<GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic.validateUpdateVfGroupNamesOnGraph(groups, resource, inTransaction);
if (validateUpdateVfGroupNamesRes.isRight()) {
return Either.right(validateUpdateVfGroupNamesRes.right().value());
}
List<GroupDefinition> heatGroups = null;
- // List<IArtifactInfo> collect = resources.stream().flatMap( e ->
- // e.getArtifacts().stream()).filter(p ->
- // relevantArtifactTypes.contains(p.getArtifactType()
- // )).collect(Collectors.toList());
- // List<GroupDefinition> heatGroups = createdGroups.stream().filter(
- // e -> e.getProperties().stream().filter(p ->
- // p.getName().contains(Constants.HEAT_FILE_PROPS))).collect(Collectors.toList());
heatGroups = groups.stream().filter(e -> e.getMembers() != null).collect(Collectors.toList());
;
@@ -1634,7 +2053,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
Map<String, String> members = new HashMap<String, String>();
Set<String> artifactsGroup = new HashSet<String>();
artifactsGroup.addAll(group.getArtifacts());
- associateMembersTToArtifacts(createdNewArtifacts, createdDeplymentArtifactsAfterDelete, heatGroups, artifactsGroup, members);
+ associateMembersToArtifacts(createdNewArtifacts, createdDeplymentArtifactsAfterDelete, heatGroups, artifactsGroup, members);
if (!members.isEmpty()) {
group.setMembers(members);
@@ -1642,14 +2061,12 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
}
- if (!groupToUpdate.isEmpty()) {
- Either<List<GroupDefinition>, ResponseFormat> assotiateGroupEither = groupBusinessLogic.associateMembersToGroup(resource.getUniqueId(), user.getUserId(), ComponentTypeEnum.RESOURCE, groupToUpdate, false, true);
- if (assotiateGroupEither.isRight()) {
- log.debug("Failed to associate artifacts to groups. Status is {} ", assotiateGroupEither.right().value());
- return Either.right(assotiateGroupEither.right().value());
-
- }
- }
+ /*
+ * if (!groupToUpdate.isEmpty()) { Either<List<GroupDefinition>, ResponseFormat> assotiateGroupEither = groupBusinessLogic.associateMembersToGroup(resource.getUniqueId(), user.getUserId(), ComponentTypeEnum.RESOURCE, groupToUpdate, false,
+ * true); if (assotiateGroupEither.isRight()) { log.debug("Failed to associate artifacts to groups. Status is {} ", assotiateGroupEither.right().value()); return Either.right(assotiateGroupEither.right().value());
+ *
+ * } }
+ */
}
@@ -1689,18 +2106,18 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
// updatedGroup
if (!groupForAssociateWithMembers.isEmpty()) {
- List<String> groupsId = groupForAssociateWithMembers.stream().map(e -> e.getUniqueId()).collect(Collectors.toList());
+ List<GroupDefinition> groupsId = groupForAssociateWithMembers.stream().map(e -> e).collect(Collectors.toList());
- Either<List<GroupDefinition>, StorageOperationStatus> updateVersionEither = groupBusinessLogic.updateGroupVersion(groupsId, true);
+ Either<List<GroupDefinition>, ResponseFormat> updateVersionEither = groupBusinessLogic.updateGroups(resource, ComponentTypeEnum.RESOURCE, groupsId);
if (updateVersionEither.isRight()) {
log.debug("Failed to update groups version. Status is {} ", updateVersionEither.right().value());
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(updateVersionEither.right().value()), resource);
- return Either.right(responseFormat);
+
+ return Either.right(updateVersionEither.right().value());
}
}
- Either<Resource, StorageOperationStatus> eitherGerResource = resourceOperation.getResource(resource.getUniqueId(), inTransaction);
+ Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
if (eitherGerResource.isRight()) {
ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
@@ -1714,30 +2131,50 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
private Either<List<ArtifactDefinition>, ResponseFormat> deleteArtifactsInUpdateCsarFlow(Resource resource, User user, boolean shouldLock, boolean inTransaction, Set<ArtifactDefinition> artifactsToDelete,
Map<String, List<ArtifactDefinition>> groupToDelete) {
List<ArtifactDefinition> deletedArtifacts = new ArrayList<ArtifactDefinition>();
-
+ String resourceId = resource.getUniqueId();
if (!artifactsToDelete.isEmpty()) {
for (ArtifactDefinition artifact : artifactsToDelete) {
+ String artifactType = artifact.getArtifactType();
+ ArtifactTypeEnum artifactTypeEnum = ArtifactTypeEnum.findType(artifactType);
+ if (artifactTypeEnum == ArtifactTypeEnum.HEAT_ENV) {
+
+ /*
+ * Either<ArtifactDefinition, StorageOperationStatus> removeArifactFromGraph = artifactOperation.removeArifactFromResource(resourceId, artifact.getUniqueId(), NodeTypeEnum.Resource, true, true); if
+ * (removeArifactFromGraph.isRight()) { StorageOperationStatus status = removeArifactFromGraph.right().value(); log.debug("Failed to delete heat env artifact {} . status is {}", artifact.getUniqueId(), status); ActionStatus
+ * actionStatus = componentsUtils.convertFromStorageResponse(status); return Either.right(componentsUtils.getResponseFormat(actionStatus)); }
+ *
+ * deletedArtifacts.add(removeArifactFromGraph.left().value());
+ */
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = artifactsBusinessLogic.handleDelete(resource.getUniqueId(), artifact.getUniqueId(), user, AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE,
- resource, null, null, shouldLock, inTransaction);
- if (handleDelete.isRight()) {
- return Either.right(handleDelete.right().value());
}
- deletedArtifacts.add(handleDelete.left().value().left().value());
+
+ else {
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = artifactsBusinessLogic.handleDelete(resourceId, artifact.getUniqueId(), user, AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, resource,
+ null, null, shouldLock, inTransaction);
+ if (handleDelete.isRight()) {
+ return Either.right(handleDelete.right().value());
+ }
+
+ deletedArtifacts.add(handleDelete.left().value().left().value());
+ }
}
}
if (!groupToDelete.isEmpty()) {
log.debug("try to delete group");
+ List<GroupDefinition> groupDefinitionstoDelete = new ArrayList<>();
+ List<GroupDefinition> groups = resource.getGroups();
for (Entry<String, List<ArtifactDefinition>> deleteGroup : groupToDelete.entrySet()) {
- Either<GroupDefinition, StorageOperationStatus> deleteGroupEither = groupOperation.deleteGroup(deleteGroup.getKey(), inTransaction);
- if (deleteGroupEither.isRight()) {
- StorageOperationStatus storageOperationStatus = deleteGroupEither.right().value();
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageOperationStatus);
- log.debug("Failed to delete group {} under component {}, error: {}", deleteGroup.getKey(), resource.getNormalizedName(), actionStatus.name());
-
- return Either.right(componentsUtils.getResponseFormat(actionStatus));
+ Optional<GroupDefinition> op = groups.stream().filter(gr -> gr.getUniqueId().equals(deleteGroup.getKey())).findAny();
+ if (op.isPresent()) {
+ groupDefinitionstoDelete.add(op.get());
+ }
+ }
+ if (!groupDefinitionstoDelete.isEmpty()) {
+ Either<List<GroupDefinition>, ResponseFormat> prepareGroups = groupBusinessLogic.deleteGroups(resource, user, ComponentTypeEnum.RESOURCE, groupDefinitionstoDelete);
+ if (prepareGroups.isRight()) {
+ return Either.right(prepareGroups.right().value());
}
}
}
@@ -1755,6 +2192,10 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
List<String> dissList = new ArrayList<String>();
for (ArtifactDefinition art : dissArtifactsInGroup) {
dissList.add(art.getUniqueId());
+ // String heatEnvId = checkAndGetHeatEnvId(art);
+ // if (!heatEnvId.isEmpty()) {
+ // dissList.add(heatEnvId);
+ // }
}
dissocArtifactFromGroup.put(entry.getKey().getUniqueId(), dissList);
}
@@ -1768,7 +2209,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
artifactsToUpdateMap.put(entry.getKey(), artifactsToUpdate);
}
- // Map<String, Set<String>> dissocArtifactFromGroup = new
+ // Map<String, Set<String>> dissocArtifactFromGroup = new HashMap<String, Set<String>>();
// HashMap<String, Set<String>>();
List<GroupDefinition> dissotiateArtifactsgroups = new ArrayList<GroupDefinition>();
for (Entry<String, List<String>> dissotiateEntry : dissocArtifactFromGroup.entrySet()) {
@@ -1779,15 +2220,13 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
dissotiateArtifactsgroups.add(dissotiateGroup);
}
if (!dissotiateArtifactsgroups.isEmpty()) {
- log.debug("try to dissociate artifacts from groups ");
- Either<List<GroupDefinition>, ResponseFormat> dissotiateGroupEither = groupBusinessLogic.dissociateArtifactsFromGroup(resource.getUniqueId(), user.getUserId(), ComponentTypeEnum.RESOURCE, dissotiateArtifactsgroups, shouldLock,
- inTransaction);
- if (dissotiateGroupEither.isRight()) {
- log.debug("Failed to dissociate artifacts from groups. Status is {} ", dissotiateGroupEither.right().value());
- resEither = Either.right(dissotiateGroupEither.right().value());
- return resEither;
-
- }
+ /*
+ * log.debug("try to dissociate artifacts from groups "); Either<List<GroupDefinition>, ResponseFormat> dissotiateGroupEither = groupBusinessLogic.dissociateArtifactsFromGroup(resource.getUniqueId(), user.getUserId(),
+ * ComponentTypeEnum.RESOURCE, dissotiateArtifactsgroups, shouldLock, inTransaction); if (dissotiateGroupEither.isRight()) { log.debug("Failed to dissociate artifacts from groups. Status is {} ", dissotiateGroupEither.right().value());
+ * resEither = Either.right(dissotiateGroupEither.right().value()); return resEither;
+ *
+ * }
+ */
}
if (!artifactsToUpdateMap.isEmpty()) {
@@ -1825,6 +2264,16 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (artifactTemplate.getFileName().equalsIgnoreCase(createdArtifact.getArtifactName())) {
arifactsUids.add(createdArtifact.getUniqueId());
isCreate = false;
+ String heatEnvId = checkAndGetHeatEnvId(createdArtifact);
+ if (!heatEnvId.isEmpty()) {
+ arifactsUids.add(heatEnvId);
+ Optional<ArtifactDefinition> op = createdDeplymentArtifactsAfterDelete.stream().filter(p -> p.getUniqueId().equals(heatEnvId)).findAny();
+ if (op.isPresent()) {
+ this.artifactToscaOperation.updateHeatEnvPlaceholder(op.get(), resource.getUniqueId(), resource.getComponentType().getNodeType());
+
+ }
+ }
+
break;
}
@@ -1834,18 +2283,33 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (artifactTemplate.getFileName().equalsIgnoreCase(createdNewArtifact.getArtifactName())) {
arifactsUids.add(createdNewArtifact.getUniqueId());
isCreate = false;
+ String heatEnvId = checkAndGetHeatEnvId(createdNewArtifact);
+ if (!heatEnvId.isEmpty()) {
+ arifactsUids.add(heatEnvId);
+ }
break;
}
}
}
if (isCreate) {
- Either<ArtifactDefinition, ResponseFormat> createArtifactEither = createDeploymentArtifact(csarUUID, csar, resource, user, artifactTemplate, createdNewArtifacts, labelCounter, shouldLock, inTransaction);
+ Either<ArtifactDefinition, ResponseFormat> createArtifactEither = createDeploymentArtifact(csarUUID, csar, resource, user, ARTIFACTS_PATH, artifactTemplate, createdNewArtifacts, labelCounter, shouldLock, inTransaction);
if (createArtifactEither.isRight()) {
resEither = Either.right(createArtifactEither.right().value());
return resEither;
}
- arifactsUids.add(createArtifactEither.left().value().getUniqueId());
+ ArtifactDefinition createdArtifact = createArtifactEither.left().value();
+ arifactsUids.add(createdArtifact.getUniqueId());
+ ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(createdArtifact.getArtifactType());
+ if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_VOL) {
+ Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder = artifactsBusinessLogic.createHeatEnvPlaceHolder(createdArtifact, ArtifactsBusinessLogic.HEAT_VF_ENV_NAME, resource.getUniqueId(), NodeTypeEnum.Resource,
+ resource.getName(), user, resource, null);
+ if (createHeatEnvPlaceHolder.isRight()) {
+ return Either.right(createHeatEnvPlaceHolder.right().value());
+ }
+ String heatEnvId = createHeatEnvPlaceHolder.left().value().getUniqueId();
+ arifactsUids.add(heatEnvId);
+ }
}
}
@@ -1860,18 +2324,16 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
}
- if (!associateArtifactGroup.isEmpty()) {
-
- log.debug("Try to associate artifacts to groups.");
-
- Either<List<GroupDefinition>, ResponseFormat> assotiateGroupEither = groupBusinessLogic.associateArtifactsToGroup(resource.getUniqueId(), user.getUserId(), ComponentTypeEnum.RESOURCE, associateArtifactGroup, shouldLock, inTransaction);
- if (assotiateGroupEither.isRight()) {
- log.debug("Failed to associate artifacts to groups. Status is {} ", assotiateGroupEither.right().value());
- resEither = Either.right(assotiateGroupEither.right().value());
- return resEither;
-
- }
- }
+ /*
+ * if (!associateArtifactGroup.isEmpty()) {
+ *
+ * log.debug("Try to associate artifacts to groups.");
+ *
+ * Either<List<GroupDefinition>, ResponseFormat> assotiateGroupEither = groupBusinessLogic.associateArtifactsToGroup(resource.getUniqueId(), user.getUserId(), ComponentTypeEnum.RESOURCE, associateArtifactGroup, shouldLock, inTransaction); if
+ * (assotiateGroupEither.isRight()) { log.debug("Failed to associate artifacts to groups. Status is {} ", assotiateGroupEither.right().value()); resEither = Either.right(assotiateGroupEither.right().value()); return resEither;
+ *
+ * } }
+ */
ComponentParametersView parametersView = new ComponentParametersView();
parametersView.disableAll();
@@ -1879,7 +2341,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
parametersView.setIgnoreUsers(false);
parametersView.setIgnoreArtifacts(false);
parametersView.setIgnoreGroups(false);
- Either<Resource, StorageOperationStatus> eitherGerResource = resourceOperation.getComponent(resource.getUniqueId(), parametersView, inTransaction);
+
+ Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId(), parametersView);
if (eitherGerResource.isRight()) {
ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
@@ -1893,7 +2356,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
private Map<GroupDefinition, MergedArtifactInfo> mergeGroupInUpdateFlow(Map<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupArtifact, Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroup,
- Set<ArtifactDefinition> artifactsToDelete, Map<String, List<ArtifactDefinition>> groupToDelete, Set<ArtifactTemplateInfo> jsonMasterArtifacts) {
+ Set<ArtifactDefinition> artifactsToDelete, Map<String, List<ArtifactDefinition>> groupToDelete, Set<ArtifactTemplateInfo> jsonMasterArtifacts, List<ArtifactDefinition> createdDeplymentArtifacts) {
Map<GroupDefinition, MergedArtifactInfo> mergedgroup = new HashMap<GroupDefinition, MergedArtifactInfo>();
for (Entry<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupListEntry : groupArtifact.entrySet()) {
Map<ArtifactDefinition, List<ArtifactDefinition>> createdArtifactMap = groupListEntry.getValue();
@@ -1902,7 +2365,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
for (ArtifactDefinition maserArtifact : createdArtifactMap.keySet()) {
listToDelete = createdArtifactMap.get(maserArtifact);
for (ArtifactDefinition artToDelete : listToDelete) {
- findArtifactToDelete(parsedGroup, artifactsToDelete, groupListEntry.getKey().getUniqueId(), artToDelete);
+ findArtifactToDelete(parsedGroup, artifactsToDelete, groupListEntry.getKey().getUniqueId(), artToDelete, createdDeplymentArtifacts);
}
for (ArtifactTemplateInfo jsonMasterArtifact : jsonMasterArtifacts) {
if (maserArtifact.getArtifactName().equalsIgnoreCase(jsonMasterArtifact.getFileName())) {
@@ -1950,19 +2413,37 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return artifactNotInGroupSet;
}
- private void findArtifactToDelete(Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroup, Set<ArtifactDefinition> artifactsToDelete, String deleteGroupId, ArtifactDefinition artifact) {
+ private void findArtifactToDelete(Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroup, Set<ArtifactDefinition> artifactsToDelete, String deleteGroupId, ArtifactDefinition artifact,
+ List<ArtifactDefinition> createdDeplymentArtifacts) {
boolean isNeedToDeleteArtifact = true;
+ String artifactType = artifact.getArtifactType();
+ ArtifactDefinition generatedFromArt = null;
+ if (artifact.getGeneratedFromId() != null && !artifact.getGeneratedFromId().isEmpty()) {
+ Optional<ArtifactDefinition> op = createdDeplymentArtifacts.stream().filter(p -> p.getUniqueId().equals(artifact.getGeneratedFromId())).findAny();
+ if (op.isPresent())
+ generatedFromArt = op.get();
+
+ }
+
for (Entry<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroupSetEntry : parsedGroup.entrySet()) {
Set<ArtifactTemplateInfo> artifactsNames = parsedGroupSetEntry.getValue();
for (ArtifactTemplateInfo template : artifactsNames) {
- if (artifact.getArtifactName().equalsIgnoreCase(template.getFileName()) && artifact.getArtifactType().equalsIgnoreCase(template.getType())) {
+ if (artifact.getArtifactName().equalsIgnoreCase(template.getFileName()) && artifactType.equalsIgnoreCase(template.getType())) {
isNeedToDeleteArtifact = false;
+ break;
+ } else {
+ if (generatedFromArt != null) {
+ if (generatedFromArt.getArtifactName().equalsIgnoreCase(template.getFileName()) && generatedFromArt.getArtifactType().equalsIgnoreCase(template.getType())) {
+ isNeedToDeleteArtifact = false;
+ break;
+ }
+ }
}
}
+
}
if (isNeedToDeleteArtifact) {
-
artifactsToDelete.add(artifact);
}
@@ -2017,7 +2498,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
log.debug("createResourceArtifacts end");
log.debug("getResource start");
- Either<Resource, StorageOperationStatus> eitherGerResource = resourceOperation.getResource(resource.getUniqueId(), inTransaction);
+ Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
log.debug("getResource end");
if (eitherGerResource.isRight()) {
ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
@@ -2035,35 +2516,31 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
List<GroupDefinition> createdGroups = resource.getGroups();
List<GroupDefinition> heatGroups = null;
if (createdGroups != null && !createdGroups.isEmpty()) {
-
- // List<IArtifactInfo> collect = resources.stream().flatMap( e ->
- // e.getArtifacts().stream()).filter(p ->
- // relevantArtifactTypes.contains(p.getArtifactType()
- // )).collect(Collectors.toList());
- // List<GroupDefinition> heatGroups = createdGroups.stream().filter(
- // e -> e.getProperties().stream().filter(p ->
- // p.getName().contains(Constants.HEAT_FILE_PROPS))).collect(Collectors.toList());
heatGroups = createdGroups.stream().filter(e -> e.getMembers() != null).collect(Collectors.toList());
- ;
}
+ List<GroupDefinition> needToAdd = new ArrayList<>();
for (ArtifactTemplateInfo groupTemplateInfo : artifactsTemplateList) {
String groupName = groupTemplateInfo.getGroupName();
Set<String> artifactsGroup = new HashSet<String>();
+ Set<String> artifactsUUIDGroup = new HashSet<String>();
- resStatus = createDeploymentArtifactsFromCsar(csarUUID, csar, resource, user, artifactsGroup, groupTemplateInfo, createdNewArtifacts, artifactsFromResource, labelCounter, shouldLock, inTransaction);
+ resStatus = createDeploymentArtifactsFromCsar(csarUUID, csar, resource, user, artifactsGroup, artifactsUUIDGroup, groupTemplateInfo, createdNewArtifacts, artifactsFromResource, labelCounter, shouldLock, inTransaction);
if (resStatus.isRight())
return resStatus;
Map<String, String> members = new HashMap<String, String>();
- associateMembersTToArtifacts(createdNewArtifacts, artifactsFromResource, heatGroups, artifactsGroup, members);
+ associateMembersToArtifacts(createdNewArtifacts, artifactsFromResource, heatGroups, artifactsGroup, members);
List<String> artifactsList = new ArrayList<String>(artifactsGroup);
+ List<String> artifactsUUIDList = new ArrayList<String>(artifactsUUIDGroup);
GroupDefinition groupDefinition = new GroupDefinition();
groupDefinition.setName(groupName);
groupDefinition.setType(Constants.DEFAULT_GROUP_VF_MODULE);
groupDefinition.setArtifacts(artifactsList);
+ groupDefinition.setArtifactsUuid(artifactsUUIDList);
+
if (!members.isEmpty())
groupDefinition.setMembers(members);
@@ -2072,21 +2549,49 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
prop.setName(Constants.IS_BASE);
prop.setValue(Boolean.toString(groupTemplateInfo.isBase()));
- properties.add(prop);
- groupDefinition.setProperties(properties);
- Either<GroupDefinition, ResponseFormat> createGroup = groupBusinessLogic.createGroup(resource.getUniqueId(), user.getUserId(), ComponentTypeEnum.RESOURCE, groupDefinition, inTransaction);
- if (createGroup.isRight())
- return Either.right(createGroup.right().value());
+ List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
+ createdArtifacts.addAll(createdNewArtifacts);
+ createdArtifacts.addAll(artifactsFromResource);
+ Either<GroupTypeDefinition, StorageOperationStatus> getLatestGroupTypeRes = groupTypeOperation.getLatestGroupTypeByType(Constants.DEFAULT_GROUP_VF_MODULE, true);
+ if (getLatestGroupTypeRes.isRight()) {
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getLatestGroupTypeRes.right().value())));
+ }
+ properties = createVfModuleAdditionalProperties(groupTemplateInfo.isBase(), groupName, properties, createdArtifacts, artifactsList, getLatestGroupTypeRes.left().value());
+ groupDefinition.convertFromGroupProperties(properties);
+ properties.add(prop);
+ groupDefinition.convertFromGroupProperties(properties);
+ // Either<GroupDefinition, ResponseFormat> createGroup = groupBusinessLogic.createGroup(resource.getUniqueId(), user.getUserId(), ComponentTypeEnum.RESOURCE, groupDefinition, inTransaction);
+ // if (createGroup.isRight())
+ // return Either.right(createGroup.right().value());
+ needToAdd.add(groupDefinition);
+ }
+ ComponentParametersView componentParametersView = new ComponentParametersView();
+ componentParametersView.disableAll();
+ componentParametersView.setIgnoreArtifacts(false);
+ componentParametersView.setIgnoreGroups(false);
+ componentParametersView.setIgnoreComponentInstances(false);
+
+ Either<Resource, StorageOperationStatus> component = toscaOperationFacade.getToscaElement(resource.getUniqueId(), componentParametersView);
+ if (component.isRight()) {
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
}
+ resource = component.left().value();
+
+ Either<List<GroupDefinition>, ResponseFormat> addGroups = groupBusinessLogic.addGroups(resource, user, ComponentTypeEnum.RESOURCE, needToAdd);
+ if (addGroups.isRight())
+ return Either.right(addGroups.right().value());
+
return resStatus;
}
- private Either<Resource, ResponseFormat> createDeploymentArtifactsFromCsar(String csarUUID, Map<String, byte[]> csar, Resource resource, User user, Set<String> artifactsGroup, ArtifactTemplateInfo artifactTemplateInfo,
- List<ArtifactDefinition> createdArtifacts, List<ArtifactDefinition> artifactsFromResource, int labelCounter, boolean shoudLock, boolean inTransaction) {
+ private Either<Resource, ResponseFormat> createDeploymentArtifactsFromCsar(String csarUUID, Map<String, byte[]> csar, Resource resource, User user, Set<String> artifactsGroup, Set<String> artifactsUUIDGroup,
+ ArtifactTemplateInfo artifactTemplateInfo, List<ArtifactDefinition> createdArtifacts, List<ArtifactDefinition> artifactsFromResource, int labelCounter, boolean shoudLock, boolean inTransaction) {
Either<Resource, ResponseFormat> resStatus = Either.left(resource);
String artifactFileName = artifactTemplateInfo.getFileName();
String artifactUid = "";
+ String artifactUUID = "";
+ String artifactEnvUid = "";
boolean alreadyExist = false;
// check if artifacts already exist
@@ -2094,12 +2599,14 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
for (ArtifactDefinition artifactFromResource : artifactsFromResource) {
if (artifactFromResource.getArtifactName().equals(artifactFileName)) {
artifactUid = artifactFromResource.getUniqueId();
+ artifactUUID = artifactFromResource.getArtifactUUID();
if (!artifactFromResource.getArtifactType().equalsIgnoreCase(artifactTemplateInfo.getType())) {
log.debug("Artifact with name {} and type {} already exist with type {}", artifactFileName, artifactTemplateInfo.getType(), artifactFromResource.getArtifactType());
BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected formatr, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName, artifactTemplateInfo.getType(), artifactFromResource.getArtifactType()));
}
alreadyExist = true;
+ artifactEnvUid = checkAndGetHeatEnvId(artifactFromResource);
break;
}
@@ -2110,12 +2617,15 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
for (ArtifactDefinition createdArtifact : createdArtifacts) {
if (createdArtifact.getArtifactName().equals(artifactFileName)) {
artifactUid = createdArtifact.getUniqueId();
+ artifactUUID = createdArtifact.getArtifactUUID();
+
if (!createdArtifact.getArtifactType().equalsIgnoreCase(artifactTemplateInfo.getType())) {
log.debug("Artifact with name {} and type {} already exist with type {}", artifactFileName, artifactTemplateInfo.getType(), createdArtifact.getArtifactType());
BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected formatr, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName, artifactTemplateInfo.getType(), createdArtifact.getArtifactType()));
}
alreadyExist = true;
+ artifactEnvUid = checkAndGetHeatEnvId(createdArtifact);
break;
}
@@ -2124,21 +2634,35 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
// if not exist need to create
if (!alreadyExist) {
- Either<ArtifactDefinition, ResponseFormat> newArtifactEither = createDeploymentArtifact(csarUUID, csar, resource, user, artifactTemplateInfo, createdArtifacts, labelCounter, shoudLock, inTransaction);
+ Either<ArtifactDefinition, ResponseFormat> newArtifactEither = createDeploymentArtifact(csarUUID, csar, resource, user, ARTIFACTS_PATH, artifactTemplateInfo, createdArtifacts, labelCounter, shoudLock, inTransaction);
if (newArtifactEither.isRight()) {
resStatus = Either.right(newArtifactEither.right().value());
return resStatus;
}
- artifactUid = newArtifactEither.left().value().getUniqueId();
-
+ ArtifactDefinition newArtifact = newArtifactEither.left().value();
+ artifactUid = newArtifact.getUniqueId();
+ artifactUUID = newArtifact.getArtifactUUID();
+ ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(newArtifact.getArtifactType());
+ if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_VOL) {
+ Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder = artifactsBusinessLogic.createHeatEnvPlaceHolder(newArtifact, ArtifactsBusinessLogic.HEAT_VF_ENV_NAME, resource.getUniqueId(), NodeTypeEnum.Resource,
+ resource.getName(), user, resource, null);
+ if (createHeatEnvPlaceHolder.isRight()) {
+ return Either.right(createHeatEnvPlaceHolder.right().value());
+ }
+ artifactEnvUid = createHeatEnvPlaceHolder.left().value().getUniqueId();
+ }
}
artifactsGroup.add(artifactUid);
+ artifactsUUIDGroup.add(artifactUUID);
+ if (!artifactEnvUid.isEmpty()) {
+ artifactsGroup.add(artifactEnvUid);
+ }
List<ArtifactTemplateInfo> relatedArtifacts = artifactTemplateInfo.getRelatedArtifactsInfo();
if (relatedArtifacts != null) {
for (ArtifactTemplateInfo relatedArtifactTemplateInfo : relatedArtifacts) {
- resStatus = createDeploymentArtifactsFromCsar(csarUUID, csar, resource, user, artifactsGroup, relatedArtifactTemplateInfo, createdArtifacts, artifactsFromResource, labelCounter, shoudLock, inTransaction);
+ resStatus = createDeploymentArtifactsFromCsar(csarUUID, csar, resource, user, artifactsGroup, artifactsUUIDGroup, relatedArtifactTemplateInfo, createdArtifacts, artifactsFromResource, labelCounter, shoudLock, inTransaction);
if (resStatus.isRight())
return resStatus;
}
@@ -2165,6 +2689,121 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
+ private Either<Resource, ResponseFormat> createOrUpdateNonMetaArtifacts(String csarUUID, Map<String, byte[]> csar, Resource resource, User user, List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction,
+ ArtifactOperationInfo artifactOperation) {
+
+ Either<Resource, ResponseFormat> resStatus = null;
+ Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>();
+
+ try {
+ List<NonMetaArtifactInfo> artifactPathAndNameList =
+ // Stream of file paths contained in csar
+ csar.entrySet().stream()
+ // Filter in only VF artifact path location
+ .filter(e -> Pattern.compile(VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN).matcher(e.getKey()).matches())
+ // Validate and add warnings
+ .map(e -> CsarUtils.validateNonMetaArtifact(e.getKey(), e.getValue(), collectedWarningMessages))
+ // Filter in Non Warnings
+ .filter(e -> e.isLeft())
+ // Convert from Either to NonMetaArtifactInfo
+ .map(e -> e.left().value())
+ // collect to List
+ .collect(Collectors.toList());
+
+ EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> vfCsarArtifactsToHandle = null;
+
+ if (artifactOperation.getArtifactOperationEnum() == ArtifactOperationEnum.Create) {
+ vfCsarArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
+ vfCsarArtifactsToHandle.put(artifactOperation.getArtifactOperationEnum(), artifactPathAndNameList);
+ } else {
+ Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandleRes = findVfCsarArtifactsToHandle(resource, artifactPathAndNameList, user);
+
+ if (findVfCsarArtifactsToHandleRes.isRight()) {
+ resStatus = Either.right(findVfCsarArtifactsToHandleRes.right().value());
+ }
+ if (resStatus == null) {
+ vfCsarArtifactsToHandle = findVfCsarArtifactsToHandleRes.left().value();
+ }
+ }
+ if (resStatus == null && vfCsarArtifactsToHandle != null) {
+ for (Entry<ArtifactOperationEnum, List<NonMetaArtifactInfo>> currArtifactOperationPair : vfCsarArtifactsToHandle.entrySet()) {
+
+ Optional<ResponseFormat> optionalCreateInDBError =
+ // Stream of artifacts to be created
+ currArtifactOperationPair.getValue().stream()
+ // create each artifact
+ .map(e -> createOrUpdateSingleNonMetaArtifact(resource, user, csarUUID, csar, e.getPath(), e.getArtifactName(), e.getArtifactType().getType(), e.getArtifactGroupType(), e.getArtifactLabel(), e.getDisplayName(),
+ CsarUtils.ARTIFACT_CREATED_FROM_CSAR, e.getArtifactUniqueId(), artifactsBusinessLogic.new ArtifactOperationInfo(false, false, currArtifactOperationPair.getKey()), createdArtifacts, shouldLock,
+ inTransaction))
+ // filter in only error
+ .filter(e -> e.isRight()).
+ // Convert the error from either to ResponseFormat
+ map(e -> e.right().value()).
+ // Check if an error occurred
+ findAny();
+ // Error found on artifact Creation
+ if (optionalCreateInDBError.isPresent()) {
+ resStatus = Either.right(optionalCreateInDBError.get());
+ break;
+ }
+ }
+ }
+ if (resStatus == null) {
+ resStatus = Either.left(resource);
+ }
+ } catch (Exception e) {
+ resStatus = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ log.debug("Exception occured in createNonMetaArtifacts, message:{}", e.getMessage(), e);
+ } finally {
+ CsarUtils.handleWarningMessages(collectedWarningMessages);
+ }
+ return resStatus;
+ }
+
+ private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandle(Resource resource, List<NonMetaArtifactInfo> artifactPathAndNameList, User user) {
+
+ List<ArtifactDefinition> existingArtifacts = new ArrayList<>();
+ // collect all Deployment and Informational artifacts of VF
+ if (resource.getDeploymentArtifacts() != null && !resource.getDeploymentArtifacts().isEmpty()) {
+ existingArtifacts.addAll(resource.getDeploymentArtifacts().values());
+ }
+ if (resource.getArtifacts() != null && !resource.getArtifacts().isEmpty()) {
+ existingArtifacts.addAll(resource.getArtifacts().values());
+ }
+ existingArtifacts = existingArtifacts.stream()
+ // filter MANDATORY artifacts, LICENSE artifacts and artifacts was created from HEAT.meta
+ .filter(this::isNonMetaArtifact).collect(Collectors.toList());
+
+ List<String> artifactsToIgnore = new ArrayList<>();
+ // collect IDs of Artifacts of VF which belongs to any group
+ if (resource.getGroups() != null) {
+ resource.getGroups().stream().forEach(g -> {
+ if (g.getArtifacts() != null && !g.getArtifacts().isEmpty())
+ artifactsToIgnore.addAll(g.getArtifacts());
+ });
+ }
+ existingArtifacts = existingArtifacts.stream()
+ // filter artifacts which belongs to any group
+ .filter(a -> !artifactsToIgnore.contains(a.getUniqueId())).collect(Collectors.toList());
+ return organizeVfCsarArtifactsByArtifactOperation(artifactPathAndNameList, existingArtifacts, resource, user);
+ }
+
+ private boolean isNonMetaArtifact(ArtifactDefinition artifact) {
+ boolean result = true;
+ if (artifact.getMandatory() || artifact.getArtifactName() == null || !isValidArtifactType(artifact)) {
+ result = false;
+ }
+ return result;
+ }
+
+ private boolean isValidArtifactType(ArtifactDefinition artifact) {
+ boolean result = true;
+ if (artifact.getArtifactType() == null || ArtifactTypeEnum.findType(artifact.getArtifactType()) == ArtifactTypeEnum.VENDOR_LICENSE || ArtifactTypeEnum.findType(artifact.getArtifactType()) == ArtifactTypeEnum.VF_LICENSE) {
+ result = false;
+ }
+ return result;
+ }
+
private Either<Resource, ResponseFormat> createGroupDeploymentArtifactsFromCsar(String csarUUID, Map<String, byte[]> csar, Resource resource, User user, List<ArtifactTemplateInfo> artifactsTemplateList, List<ArtifactDefinition> createdArtifacts,
int labelCounter, boolean shouldLock, boolean inTransaction) {
Either<Resource, ResponseFormat> resStatus = Either.left(resource);
@@ -2182,67 +2821,146 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
heatGroups = createdGroups.stream().filter(e -> e.getMembers() != null).collect(Collectors.toList());
;
}
+ List<GroupDefinition> needToCreate = new ArrayList<>();
for (ArtifactTemplateInfo groupTemplateInfo : artifactsTemplateList) {
String groupName = groupTemplateInfo.getGroupName();
Set<String> artifactsGroup = new HashSet<String>();
+ Set<String> artifactsUUIDGroup = new HashSet<String>();
log.debug("createDeploymentArtifactsFromCsar start");
- resStatus = createDeploymentArtifactsFromCsar(csarUUID, csar, resource, user, artifactsGroup, groupTemplateInfo, createdArtifacts, labelCounter, shouldLock, inTransaction);
+ resStatus = createDeploymentArtifactFromCsar(csarUUID, ARTIFACTS_PATH, csar, resource, user, artifactsGroup, artifactsUUIDGroup, groupTemplateInfo, createdArtifacts, labelCounter, shouldLock, inTransaction);
log.debug("createDeploymentArtifactsFromCsar end");
if (resStatus.isRight())
return resStatus;
Map<String, String> members = new HashMap<String, String>();
- associateMembersTToArtifacts(createdArtifacts, null, heatGroups, artifactsGroup, members);
+ associateMembersToArtifacts(createdArtifacts, null, heatGroups, artifactsGroup, members);
List<String> artifactsList = new ArrayList<String>(artifactsGroup);
+ List<String> artifactsUUIDList = new ArrayList<String>(artifactsUUIDGroup);
GroupDefinition groupDefinition = new GroupDefinition();
groupDefinition.setName(groupName);
groupDefinition.setType(Constants.DEFAULT_GROUP_VF_MODULE);
groupDefinition.setArtifacts(artifactsList);
+ groupDefinition.setArtifactsUuid(artifactsUUIDList);
+
if (!members.isEmpty())
groupDefinition.setMembers(members);
List<GroupProperty> properties = new ArrayList<GroupProperty>();
GroupProperty prop = new GroupProperty();
prop.setName(Constants.IS_BASE);
prop.setValue(Boolean.toString(groupTemplateInfo.isBase()));
-
properties.add(prop);
- groupDefinition.setProperties(properties);
+ Either<GroupTypeDefinition, StorageOperationStatus> getLatestGroupTypeRes = groupTypeOperation.getLatestGroupTypeByType(Constants.DEFAULT_GROUP_VF_MODULE, true);
+ if (getLatestGroupTypeRes.isRight()) {
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getLatestGroupTypeRes.right().value())));
+ }
+ properties = createVfModuleAdditionalProperties(groupTemplateInfo.isBase(), groupName, properties, createdArtifacts, artifactsList, getLatestGroupTypeRes.left().value());
+ groupDefinition.convertFromGroupProperties(properties);
log.debug("createGroup start");
- // Either<GroupDefinition, ResponseFormat> createGroup =
- // groupBusinessLogic.createGroup(resource.getUniqueId(),
- // user.getUserId(), ComponentTypeEnum.RESOURCE, groupDefinition,
- // inTransaction);
- // Ignore validations and get component
// Since in these groups we handle only artifacts, then no need to
// fetch component instances
- ComponentParametersView componentParametersView = new ComponentParametersView();
- componentParametersView.disableAll();
- componentParametersView.setIgnoreUsers(false);
- componentParametersView.setIgnoreArtifacts(false);
- componentParametersView.setIgnoreGroups(false);
- componentParametersView.setIgnoreComponentInstances(false);
- Either<Resource, StorageOperationStatus> component = resourceOperation.getComponent(resource.getUniqueId(), componentParametersView, inTransaction);
- if (component.isRight()) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- Either<GroupDefinition, ResponseFormat> createGroup = groupBusinessLogic.createGroup(component.left().value(), user, ComponentTypeEnum.RESOURCE, groupDefinition, inTransaction);
- log.debug("createGroup end");
- if (createGroup.isRight())
- return Either.right(createGroup.right().value());
+ // Either<GroupDefinition, ResponseFormat> createGroup = groupBusinessLogic.createGroup(comp, user, ComponentTypeEnum.RESOURCE, groupDefinition, inTransaction);
+ // log.debug("createGroup end");
+ // if (createGroup.isRight())
+ // return Either.right(createGroup.right().value());
+ needToCreate.add(groupDefinition);
+ }
+
+ ComponentParametersView componentParametersView = new ComponentParametersView();
+ componentParametersView.disableAll();
+ componentParametersView.setIgnoreUsers(false);
+ componentParametersView.setIgnoreArtifacts(false);
+ componentParametersView.setIgnoreGroups(false);
+
+ componentParametersView.setIgnoreComponentInstances(false);
+
+ Either<Resource, StorageOperationStatus> component = toscaOperationFacade.getToscaElement(resource.getUniqueId(), componentParametersView);
+ if (component.isRight()) {
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ Either<List<GroupDefinition>, ResponseFormat> createGroups = groupBusinessLogic.addGroups(component.left().value(), user, ComponentTypeEnum.RESOURCE, needToCreate);
+ if (createGroups.isRight()) {
+ return Either.right(createGroups.right().value());
}
+
return resStatus;
}
- private void associateMembersTToArtifacts(List<ArtifactDefinition> createdArtifacts, List<ArtifactDefinition> artifactsFromResource, List<GroupDefinition> heatGroups, Set<String> artifactsGroup, Map<String, String> members) {
+ public List<GroupProperty> createVfModuleAdditionalProperties(boolean isBase, String moduleName, List<GroupProperty> properties, List<ArtifactDefinition> deploymentArtifacts, List<String> artifactsInGroup, GroupTypeDefinition groupType) {
+ Map<String, VfModuleProperty> vfModuleProperties = ConfigurationManager.getConfigurationManager().getConfiguration().getVfModuleProperties();
+ vfModuleProperties.entrySet().forEach(p -> {
+ GroupProperty prop = new GroupProperty();
+ prop.setName(p.getKey());
+ if (isBase) {
+ prop.setValue(p.getValue().getForBaseModule());
+ prop.setDefaultValue(p.getValue().getForBaseModule());
+ } else {
+ prop.setValue(p.getValue().getForNonBaseModule());
+ prop.setDefaultValue(p.getValue().getForNonBaseModule());
+ }
+ properties.add(prop);
+
+ });
+ GroupProperty proplabel = new GroupProperty();
+ proplabel.setName("vf_module_label");
+
+ Matcher matcher = pattern.matcher(moduleName);
+
+ if (matcher.find()) {
+ proplabel.setValue(matcher.group(1));
+ proplabel.setDefaultValue(matcher.group(1));
+ } else {
+ proplabel.setValue(moduleName);
+ proplabel.setDefaultValue(moduleName);
+ }
+ properties.add(proplabel);
+
+ GroupProperty propvolume = new GroupProperty();
+ propvolume.setName("volume_group");
+ boolean isVolume = false;
+ for (String artifactId : artifactsInGroup) {
+ ArtifactDefinition artifactDef = null;
+ artifactDef = findArtifactInList(deploymentArtifacts, artifactId);
+ if (artifactDef != null && artifactDef.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType())) {
+ isVolume = true;
+ break;
+ }
+ }
+ propvolume.setValue(String.valueOf(isVolume));
+ propvolume.setDefaultValue(String.valueOf(isVolume));
+ properties.add(propvolume);
+ mergeWithGroupTypeProperties(properties, groupType.getProperties());
+ return properties;
+ }
+
+ private void mergeWithGroupTypeProperties(List<GroupProperty> properties, List<PropertyDefinition> groupTypeProperties) {
+
+ Map<String, GroupProperty> propertiesMap = properties.stream().collect(Collectors.toMap(p -> p.getName(), p -> p));
+ for (PropertyDefinition groupTypeProperty : groupTypeProperties) {
+ if (!propertiesMap.containsKey(groupTypeProperty.getName())) {
+ properties.add(new GroupProperty(groupTypeProperty));
+ }
+ }
+ }
+
+ private ArtifactDefinition findArtifactInList(List<ArtifactDefinition> createdArtifacts, String artifactId) {
+ for (ArtifactDefinition artifact : createdArtifacts) {
+ if (artifact.getUniqueId().equals(artifactId)) {
+ return artifact;
+ }
+ }
+ return null;
+ }
+
+ private void associateMembersToArtifacts(List<ArtifactDefinition> createdArtifacts, List<ArtifactDefinition> artifactsFromResource, List<GroupDefinition> heatGroups, Set<String> artifactsGroup, Map<String, String> members) {
if (heatGroups != null && !heatGroups.isEmpty()) {
for (GroupDefinition heatGroup : heatGroups) {
- List<GroupProperty> grpoupProps = heatGroup.getProperties();
+ List<GroupProperty> grpoupProps = heatGroup.convertToGroupProperties();
if (grpoupProps != null) {
Optional<GroupProperty> op = grpoupProps.stream().filter(p -> p.getName().equals(Constants.HEAT_FILE_PROPS)).findAny();
if (op.isPresent()) {
@@ -2274,45 +2992,63 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
}
- private Either<Resource, ResponseFormat> createDeploymentArtifactsFromCsar(String csarUUID, Map<String, byte[]> csar, Resource resource, User user, Set<String> artifactsGroup, ArtifactTemplateInfo artifactTemplateInfo,
- List<ArtifactDefinition> createdArtifacts, int labelCounter, boolean shoudLock, boolean inTransaction) {
+ private Either<Resource, ResponseFormat> createDeploymentArtifactFromCsar(String csarUUID, String artifactPath, Map<String, byte[]> csar, Resource resource, User user, Set<String> artifactsGroup, Set<String> artifactsUUIDGroup,
+ ArtifactTemplateInfo artifactTemplateInfo, List<ArtifactDefinition> createdArtifacts, int labelCounter, boolean shoudLock, boolean inTransaction) {
Either<Resource, ResponseFormat> resStatus = Either.left(resource);
String artifactFileName = artifactTemplateInfo.getFileName();
String artifactUid = "";
+ String artifactEnvUid = "";
+ String artifactUUID = "";
boolean alreadyExist = false;
// check if artifacts already exist
for (ArtifactDefinition createdArtifact : createdArtifacts) {
if (createdArtifact.getArtifactName().equals(artifactFileName)) {
artifactUid = createdArtifact.getUniqueId();
+ artifactUUID = createdArtifact.getArtifactUUID();
if (!createdArtifact.getArtifactType().equalsIgnoreCase(artifactTemplateInfo.getType())) {
log.debug("Artifact with name {} and type {} already exist with type {}", artifactFileName, artifactTemplateInfo.getType(), createdArtifact.getArtifactType());
BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected formatr, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName, artifactTemplateInfo.getType(), createdArtifact.getArtifactType()));
}
alreadyExist = true;
+ artifactEnvUid = checkAndGetHeatEnvId(createdArtifact);
break;
}
-
}
// if not exist need to create
if (!alreadyExist) {
- Either<ArtifactDefinition, ResponseFormat> newArtifactEither = createDeploymentArtifact(csarUUID, csar, resource, user, artifactTemplateInfo, createdArtifacts, labelCounter, shoudLock, inTransaction);
+ Either<ArtifactDefinition, ResponseFormat> newArtifactEither = createDeploymentArtifact(csarUUID, csar, resource, user, artifactPath, artifactTemplateInfo, createdArtifacts, labelCounter, shoudLock, inTransaction);
if (newArtifactEither.isRight()) {
resStatus = Either.right(newArtifactEither.right().value());
return resStatus;
}
- artifactUid = newArtifactEither.left().value().getUniqueId();
+ ArtifactDefinition newArtifact = newArtifactEither.left().value();
+ artifactUid = newArtifact.getUniqueId();
+ artifactUUID = newArtifact.getArtifactUUID();
+ ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(newArtifact.getArtifactType());
+ if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_VOL) {
+ Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder = artifactsBusinessLogic.createHeatEnvPlaceHolder(newArtifact, ArtifactsBusinessLogic.HEAT_VF_ENV_NAME, resource.getUniqueId(), NodeTypeEnum.Resource,
+ resource.getName(), user, resource, null);
+ if (createHeatEnvPlaceHolder.isRight()) {
+ return Either.right(createHeatEnvPlaceHolder.right().value());
+ }
+ artifactEnvUid = createHeatEnvPlaceHolder.left().value().getUniqueId();
+ }
}
artifactsGroup.add(artifactUid);
+ artifactsUUIDGroup.add(artifactUUID);
+ if (!artifactEnvUid.isEmpty()) {
+ artifactsGroup.add(artifactEnvUid);
+ }
List<ArtifactTemplateInfo> relatedArtifacts = artifactTemplateInfo.getRelatedArtifactsInfo();
if (relatedArtifacts != null) {
for (ArtifactTemplateInfo relatedArtifactTemplateInfo : relatedArtifacts) {
- resStatus = createDeploymentArtifactsFromCsar(csarUUID, csar, resource, user, artifactsGroup, relatedArtifactTemplateInfo, createdArtifacts, labelCounter, shoudLock, inTransaction);
+ resStatus = createDeploymentArtifactFromCsar(csarUUID, artifactPath, csar, resource, user, artifactsGroup, artifactsUUIDGroup, relatedArtifactTemplateInfo, createdArtifacts, labelCounter, shoudLock, inTransaction);
if (resStatus.isRight())
return resStatus;
}
@@ -2320,17 +3056,28 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return resStatus;
}
- private Either<ArtifactDefinition, ResponseFormat> createDeploymentArtifact(String csarUUID, Map<String, byte[]> csar, Resource resource, User user, ArtifactTemplateInfo artifactTemplateInfo, List<ArtifactDefinition> createdArtifacts,
- int labelCounter, boolean shoudLock, boolean inTransaction) {
- String artifactUid;
- Either<ImmutablePair<String, byte[]>, ResponseFormat> artifactContententStatus = CsarValidationUtils.getArtifactsContent(csarUUID, csar, artifactTemplateInfo.getFileName(), componentsUtils);
- if (artifactContententStatus.isRight())
+ private String checkAndGetHeatEnvId(ArtifactDefinition createdArtifact) {
+ String artifactEnvUid = "";
+ ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(createdArtifact.getArtifactType());
+ if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_VOL) {
+ artifactEnvUid = createdArtifact.getUniqueId() + ArtifactsBusinessLogic.HEAT_ENV_SUFFIX;
+ }
+ return artifactEnvUid;
+ }
+
+ private Either<ArtifactDefinition, ResponseFormat> createDeploymentArtifact(String csarUUID, Map<String, byte[]> csar, Resource resource, User user, String artifactPath, ArtifactTemplateInfo artifactTemplateInfo,
+ List<ArtifactDefinition> createdArtifacts, int labelCounter, boolean shoudLock, boolean inTransaction) {
+ final String artifactFileName = artifactTemplateInfo.getFileName();
+ Either<ImmutablePair<String, byte[]>, ResponseFormat> artifactContententStatus = CsarValidationUtils.getArtifactsContent(csarUUID, csar, artifactPath + artifactFileName, artifactFileName, componentsUtils);
+ if (artifactContententStatus.isRight()) {
return Either.right(artifactContententStatus.right().value());
+ }
labelCounter += createdArtifacts.size();
Map<String, Object> json = buildJsonForArtifact(artifactTemplateInfo, artifactContententStatus.left().value().getValue(), labelCounter);
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = createOrUpdateCsarArtifactFromJson(resource, user, json, ArtifactOperation.Create, shoudLock, inTransaction);
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = createOrUpdateCsarArtifactFromJson(resource, user, json, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Create),
+ shoudLock, inTransaction);
if (uploadArtifactToService.isRight())
return Either.right(uploadArtifactToService.right().value());
@@ -2338,21 +3085,40 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
ArtifactDefinition currentInfo = uploadArtifactToService.left().value().left().value();
if (currentInfo.getHeatParameters() != null) {
- Either<ArtifactDefinition, ResponseFormat> updateEnvEither = updateHeatParamsFromCsar(csarUUID, csar, artifactTemplateInfo, currentInfo);
+ Either<ArtifactDefinition, ResponseFormat> updateEnvEither = updateHeatParamsFromCsar(resource, csarUUID, csar, artifactTemplateInfo, currentInfo, false);
if (updateEnvEither.isRight()) {
- log.debug("failed to update parameters to artifact {}", artifactTemplateInfo.getFileName());
+ log.debug("failed to update parameters to artifact {}", artifactFileName);
return Either.right(updateEnvEither.right().value());
}
- artifactUid = updateEnvEither.left().value().getUniqueId();
- createdArtifacts.add(updateEnvEither.left().value());
currentInfo = updateEnvEither.left().value();
- } else {
-
- artifactUid = currentInfo.getUniqueId();
- createdArtifacts.add(currentInfo);
}
+
+ createdArtifacts.add(currentInfo);
+
+ return Either.left(currentInfo);
+
+ }
+
+ private Either<ArtifactDefinition, ResponseFormat> createInformationalArtifact(String csarUUID, Map<String, byte[]> csar, Resource resource, User user, ArtifactTemplateInfo artifactTemplateInfo, int labelCounter, boolean shoudLock,
+ boolean inTransaction) {
+ final String artifactFileName = artifactTemplateInfo.getFileName();
+ String artifactPath = CsarUtils.ARTIFACTS_PATH + CsarUtils.INFORMATIONAL_ARTIFACTS + artifactFileName;
+ Either<ImmutablePair<String, byte[]>, ResponseFormat> artifactContententStatus = CsarValidationUtils.getArtifactsContent(csarUUID, csar, artifactPath, artifactFileName, componentsUtils);
+ if (artifactContententStatus.isRight())
+ return Either.right(artifactContententStatus.right().value());
+
+ Map<String, Object> json = buildJsonForArtifact(artifactTemplateInfo, artifactContententStatus.left().value().getValue(), labelCounter);
+
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = createOrUpdateCsarArtifactFromJson(resource, user, json, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Create),
+ shoudLock, inTransaction);
+
+ if (uploadArtifactToService.isRight())
+ return Either.right(uploadArtifactToService.right().value());
+
+ ArtifactDefinition currentInfo = uploadArtifactToService.left().value().left().value();
+
return Either.left(currentInfo);
}
@@ -2380,15 +3146,17 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
- Either<ImmutablePair<String, byte[]>, ResponseFormat> artifactContententStatus = CsarValidationUtils.getArtifactsContent(csarUUID, csar, artifactTemplateInfo.getFileName(), componentsUtils);
+ Either<ImmutablePair<String, byte[]>, ResponseFormat> artifactContententStatus = CsarValidationUtils.getArtifactsContent(csarUUID, csar, CsarUtils.ARTIFACTS_PATH + artifactFileName, artifactFileName, componentsUtils);
if (artifactContententStatus.isRight()) {
resStatus = Either.right(artifactContententStatus.right().value());
return resStatus;
}
- Map<String, Object> json = buildJsonForUpdateArtifact(oldArtifact.getUniqueId(), artifactFileName, oldArtifact.getArtifactType(), oldArtifact.getArtifactLabel(), oldArtifact.getArtifactDisplayName(), oldArtifact.getDescription(),
- artifactContententStatus.left().value().getRight(), updatedRequiredArtifacts);
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = createOrUpdateCsarArtifactFromJson(resource, user, json, ArtifactOperation.Update, shouldLock, inTransaction);
+ Map<String, Object> json = buildJsonForUpdateArtifact(oldArtifact.getUniqueId(), artifactFileName, oldArtifact.getArtifactType(), ArtifactGroupTypeEnum.DEPLOYMENT, oldArtifact.getArtifactLabel(), oldArtifact.getArtifactDisplayName(),
+ oldArtifact.getDescription(), artifactContententStatus.left().value().getRight(), updatedRequiredArtifacts);
+
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = createOrUpdateCsarArtifactFromJson(resource, user, json, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Update),
+ shouldLock, inTransaction);
if (uploadArtifactToService.isRight()) {
resStatus = Either.right(uploadArtifactToService.right().value());
@@ -2396,12 +3164,13 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
ArtifactDefinition currentInfo = uploadArtifactToService.left().value().left().value();
- Either<ArtifactDefinition, ResponseFormat> updateEnvEither = updateHeatParamsFromCsar(csarUUID, csar, artifactTemplateInfo, currentInfo);
+ Either<ArtifactDefinition, ResponseFormat> updateEnvEither = updateHeatParamsFromCsar(resource, csarUUID, csar, artifactTemplateInfo, currentInfo, true);
if (updateEnvEither.isRight()) {
log.debug("failed to update parameters to artifact {}", artifactFileName);
resStatus = Either.right(updateEnvEither.right().value());
return resStatus;
}
+ // TODO evg update env time ( must be separate US for this!!!!)
artifactUid = updateEnvEither.left().value().getUniqueId();
updatedArtifacts.add(updateEnvEither.left().value());
@@ -2411,70 +3180,79 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
- private Either<ArtifactDefinition, ResponseFormat> updateHeatParamsFromCsar(String csarUUID, Map<String, byte[]> csar, ArtifactTemplateInfo artifactTemplateInfo, ArtifactDefinition currentInfo) {
+ private Either<ArtifactDefinition, ResponseFormat> updateHeatParamsFromCsar(Resource resource, String csarUUID, Map<String, byte[]> csar, ArtifactTemplateInfo artifactTemplateInfo, ArtifactDefinition currentInfo, boolean isUpdateEnv) {
Either<ArtifactDefinition, ResponseFormat> resStatus = Either.left(currentInfo);
if (artifactTemplateInfo.getEnv() != null && !artifactTemplateInfo.getEnv().isEmpty()) {
- Either<ImmutablePair<String, byte[]>, ResponseFormat> artifactparamsStatus = CsarValidationUtils.getArtifactsContent(csarUUID, csar, artifactTemplateInfo.getEnv(), componentsUtils);
+ Either<ImmutablePair<String, byte[]>, ResponseFormat> artifactparamsStatus = CsarValidationUtils.getArtifactsContent(csarUUID, csar, CsarUtils.ARTIFACTS_PATH + artifactTemplateInfo.getEnv(), artifactTemplateInfo.getEnv(),
+ componentsUtils);
if (artifactparamsStatus.isRight()) {
resStatus = Either.right(artifactparamsStatus.right().value());
return resStatus;
}
- Either<List<HeatParameterDefinition>, ResponseFormat> propsStatus = extractHeatParameters(ArtifactTypeEnum.HEAT_ENV.getType(), artifactTemplateInfo.getEnv(), artifactparamsStatus.left().value().getValue());
- if (propsStatus.isRight()) {
-
- resStatus = Either.right(propsStatus.right().value());
- return resStatus;
- }
- List<HeatParameterDefinition> updatedHeatEnvParams = propsStatus.left().value();
- List<HeatParameterDefinition> currentHeatEnvParams = currentInfo.getHeatParameters();
- List<HeatParameterDefinition> newHeatEnvParams = new ArrayList<HeatParameterDefinition>();
-
- if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty() && currentHeatEnvParams != null && !currentHeatEnvParams.isEmpty()) {
-
- String paramName;
- for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
-
- paramName = heatEnvParam.getName();
- for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
- if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
-
- String updatedParamValue = heatEnvParam.getCurrentValue();
- if (updatedParamValue == null)
- updatedParamValue = heatEnvParam.getDefaultValue();
- HeatParameterType paramType = HeatParameterType.isValidType(currHeatParam.getType());
- if (!paramType.getValidator().isValid(updatedParamValue, null)) {
- ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, ArtifactTypeEnum.HEAT_ENV.getType(), paramType.getType(), paramName);
- resStatus = Either.right(responseFormat);
- return resStatus;
+ Either<List<HeatParameterDefinition>, ResponseFormat> propsStatus = extractHeatParameters(ArtifactTypeEnum.HEAT_ENV.getType(), artifactTemplateInfo.getEnv(), artifactparamsStatus.left().value().getValue(), false);
+ /*
+ * if (propsStatus.isRight()) {
+ *
+ * resStatus = Either.right(propsStatus.right().value()); return resStatus; }
+ */
+ if (propsStatus.isLeft()) {
+ List<HeatParameterDefinition> updatedHeatEnvParams = propsStatus.left().value();
+ List<HeatParameterDefinition> currentHeatEnvParams = currentInfo.getListHeatParameters();
+ // List<HeatParameterDefinition> newHeatEnvParams = new ArrayList<HeatParameterDefinition>();
+
+ if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty() && currentHeatEnvParams != null && !currentHeatEnvParams.isEmpty()) {
+
+ String paramName;
+ for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
+
+ paramName = heatEnvParam.getName();
+ for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
+ if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
+
+ String updatedParamValue = heatEnvParam.getCurrentValue();
+ if (updatedParamValue == null)
+ updatedParamValue = heatEnvParam.getDefaultValue();
+ HeatParameterType paramType = HeatParameterType.isValidType(currHeatParam.getType());
+ if (!paramType.getValidator().isValid(updatedParamValue, null)) {
+ ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, ArtifactTypeEnum.HEAT_ENV.getType(), paramType.getType(), paramName);
+ resStatus = Either.right(responseFormat);
+ return resStatus;
+ }
+ currHeatParam.setCurrentValue(HeatParameterType.isValidType(currHeatParam.getType()).getConverter().convert(updatedParamValue, null, null));
+ // newHeatEnvParams.add(currHeatParam);
+ break;
}
- currHeatParam.setCurrentValue(paramType.getConverter().convert(updatedParamValue, null, null));
- newHeatEnvParams.add(currHeatParam);
- break;
}
}
- }
- if (!newHeatEnvParams.isEmpty()) {
- StorageOperationStatus operationStatus = heatParametersOperation.updateHeatParameters(currentHeatEnvParams);
-
- if (operationStatus != StorageOperationStatus.OK) {
- log.debug("Failed to update artifact on graph - {}", currentInfo.getUniqueId());
-
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(operationStatus));
- resStatus = Either.right(responseFormat);
- return resStatus;
+ currentInfo.setListHeatParameters(currentHeatEnvParams);
+ Either<ArtifactDefinition, StorageOperationStatus> updateArifactOnResource = artifactToscaOperation.updateArifactOnResource(currentInfo, resource.getUniqueId(), currentInfo.getUniqueId(), null, null);
+ if (updateArifactOnResource.isRight()) {
+ log.debug("Failed to update heat paratemers of heat on CSAR flow for component {} artifact {} label {}", resource.getUniqueId(), currentInfo.getUniqueId(), currentInfo.getArtifactLabel());
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArifactOnResource.right().value())));
}
}
}
-
+ }
+ if (isUpdateEnv) {
+ Map<String, ArtifactDefinition> artifacts = resource.getDeploymentArtifacts();
+ Optional<ArtifactDefinition> op = artifacts.values().stream().filter(p -> p.getGeneratedFromId() != null && p.getGeneratedFromId().equals(currentInfo.getUniqueId())).findAny();
+ if (op.isPresent()) {
+ ArtifactDefinition artifactInfoHeatEnv = op.get();
+ Either<ArtifactDefinition, StorageOperationStatus> updateArifactOnResource = artifactToscaOperation.updateArifactOnResource(artifactInfoHeatEnv, resource.getUniqueId(), artifactInfoHeatEnv.getUniqueId(), null, null);
+ if (updateArifactOnResource.isRight()) {
+ log.debug("Failed to update heat env on CSAR flow for component {} artifact {} label {}", resource.getUniqueId(), artifactInfoHeatEnv.getUniqueId(), artifactInfoHeatEnv.getArtifactLabel());
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArifactOnResource.right().value())));
+ }
+ }
}
return resStatus;
}
- private Either<List<HeatParameterDefinition>, ResponseFormat> extractHeatParameters(String artifactType, String fileName, byte[] content) {
+ private Either<List<HeatParameterDefinition>, ResponseFormat> extractHeatParameters(String artifactType, String fileName, byte[] content, boolean is64Encoded) {
// extract heat parameters
- String heatDecodedPayload = GeneralUtility.isBase64Encoded(content) ? new String(Base64.decodeBase64(content)) : new String(content);
+ String heatDecodedPayload = is64Encoded ? new String(Base64.decodeBase64(content)) : new String(content);
Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParamsWithoutImplicitTypes(heatDecodedPayload, artifactType);
if (heatParameters.isRight()) {
log.debug("File {} is not in expected key-value form in csar ", fileName);
@@ -2495,15 +3273,11 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
json.put(Constants.ARTIFACT_TYPE, artifactTemplateInfo.getType());
json.put(Constants.ARTIFACT_DESCRIPTION, "created from csar");
- /*
- * DE250204
- * There is no need to check if base64 encoding. All files that are inside the CSAR are not encoded and need to encoded. The check for isBase64 is not in cases we get files with extension .cert or .key these files are base64 but if do not
- * encode them again, when the user download them, the decoded file will return not the encoded file that was upload.
- */
+ // DE250204: There is no need to check if base64 encoding.
+
// String encodedPayload = new String(artifactContentent);
// boolean isEncoded = GeneralUtility.isBase64Encoded(artifactContentent);
// if (!isEncoded) {
- // log.debug("payload is encoded. perform decode");
String encodedPayload = Base64.encodeBase64String(artifactContentent);
// }
json.put(Constants.ARTIFACT_PAYLOAD_DATA, encodedPayload);
@@ -2520,7 +3294,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return json;
}
- private Map<String, Object> buildJsonForUpdateArtifact(String artifactId, String artifactName, String artifactType, String label, String displayName, String description, byte[] artifactContentent,
+ private Map<String, Object> buildJsonForUpdateArtifact(String artifactId, String artifactName, String artifactType, ArtifactGroupTypeEnum artifactGroupType, String label, String displayName, String description, byte[] artifactContentent,
List<ArtifactTemplateInfo> updatedRequiredArtifacts) {
Map<String, Object> json = new HashMap<String, Object>();
@@ -2532,17 +3306,17 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
json.put(Constants.ARTIFACT_DESCRIPTION, description);
String encodedPayload = new String(artifactContentent);
- // DE250204 - need to encode all.
- //boolean isEncoded = GeneralUtility.isBase64Encoded(artifactContentent);
- //if (!isEncoded) {
- log.debug("payload is encoded. perform decode");
- encodedPayload = Base64.encodeBase64String(artifactContentent);
- //}
+
+ // boolean isEncoded = GeneralUtility.isBase64Encoded(artifactContentent);
+ // if (!isEncoded) {
+ log.debug("payload is encoded. perform decode");
+ encodedPayload = Base64.encodeBase64String(artifactContentent);
+ // }
json.put(Constants.ARTIFACT_PAYLOAD_DATA, encodedPayload);
json.put(Constants.ARTIFACT_DISPLAY_NAME, displayName);
json.put(Constants.ARTIFACT_LABEL, label);
- json.put(Constants.ARTIFACT_GROUP_TYPE, ArtifactGroupTypeEnum.DEPLOYMENT.getType());
+ json.put(Constants.ARTIFACT_GROUP_TYPE, artifactGroupType.getType());
json.put(Constants.REQUIRED_ARTIFACTS, (updatedRequiredArtifacts == null || updatedRequiredArtifacts.isEmpty()) ? new ArrayList<>()
: updatedRequiredArtifacts.stream().filter(e -> e.getType().equals(ArtifactTypeEnum.HEAT_ARTIFACT.getType()) || e.getType().equals(ArtifactTypeEnum.HEAT_NESTED.getType())).map(e -> e.getFileName()).collect(Collectors.toList()));
return json;
@@ -2642,23 +3416,34 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return Either.right(responseFormat);
}
- Map<String, List<PropertyDefinition>> propertiesListPerResource = new HashMap<>();
+ log.debug("Before validateAndUpdatePropertyValue");
+ Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll();
+ if (allDataTypes.isRight()) {
+ TitanOperationStatus status = allDataTypes.right().value();
+ BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status)), yamlName);
- long totalCreateRel = 0;
- long totalCreatePropVal = 0;
- Iterator<Entry<String, UploadComponentInstanceInfo>> nodesInfoValue = uploadResInstancesMap.entrySet().iterator();
- while (nodesInfoValue.hasNext()) {
- Entry<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoEntry = nodesInfoValue.next();
- UploadComponentInstanceInfo uploadComponentInstanceInfo = uploadComponentInstanceInfoEntry.getValue();
+ }
+ Map<String, List<ComponentInstanceProperty>> instProperties = new HashMap<>();
+ Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties = new HashMap<>();
+ Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements = new HashMap<>();
+ Map<String, Map<String, ArtifactDefinition>> instArtifacts = new HashMap<>();
+ Map<String, List<AttributeDefinition>> instAttributes = new HashMap<>();
+ Map<String, Resource> originCompMap = new HashMap<>();
+ List<RequirementCapabilityRelDef> relations = new ArrayList<>();
+
+ for (Entry<String, UploadComponentInstanceInfo> entry : uploadResInstancesMap.entrySet()) {
+ UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue();
ComponentInstance currentCompInstance = null;
for (ComponentInstance compInstance : componentInstancesList) {
+
if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) {
currentCompInstance = compInstance;
break;
}
- }
+ }
if (currentCompInstance == null) {
log.debug("component instance with name {} in resource {} ", uploadComponentInstanceInfo.getName(), resource.getUniqueId());
BeEcompErrorManager.getInstance().logInternalDataError("component instance with name " + uploadComponentInstanceInfo.getName() + " in resource {} ", resource.getUniqueId(), ErrorSeverity.ERROR);
@@ -2666,107 +3451,115 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return Either.right(responseFormat);
}
String resourceInstanceId = currentCompInstance.getUniqueId();
-
- log.debug("************* addPropertyValuesToRi start");
- long startAddProperty = System.currentTimeMillis();
-
- ResponseFormat addPropertiesValueToRiRes = addPropertyValuesToRi(uploadComponentInstanceInfo, resource, resourceInstanceId, currentCompInstance, yamlName, propertiesListPerResource);
- log.debug("************* addPropertyValuesToRi end");
- totalCreatePropVal += (System.currentTimeMillis() - startAddProperty);
-
+ Resource originResource = null;
+ if (!originCompMap.containsKey(currentCompInstance.getComponentUid())) {
+ Either<Resource, StorageOperationStatus> getPropertyRes = toscaOperationFacade.getToscaFullElement(currentCompInstance.getComponentUid());
+ if (getPropertyRes.isRight()) {
+ log.debug("failed to find properties of resource {} status is {}", currentCompInstance.getComponentUid(), getPropertyRes);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getPropertyRes.right().value()), yamlName);
+ return Either.right(responseFormat);
+ }
+ originResource = getPropertyRes.left().value();
+ originCompMap.put(originResource.getUniqueId(), originResource);
+ } else {
+ originResource = originCompMap.get(currentCompInstance.getComponentUid());
+ }
+ if (originResource.getCapabilities() != null && !originResource.getCapabilities().isEmpty())
+ instCapabilties.put(currentCompInstance, originResource.getCapabilities());
+ if (originResource.getRequirements() != null && !originResource.getRequirements().isEmpty())
+ instRequirements.put(currentCompInstance, originResource.getRequirements());
+ if (originResource.getDeploymentArtifacts() != null && !originResource.getDeploymentArtifacts().isEmpty())
+ instArtifacts.put(resourceInstanceId, originResource.getDeploymentArtifacts());
+ if (originResource.getAttributes() != null && !originResource.getAttributes().isEmpty())
+ instAttributes.put(resourceInstanceId, originResource.getAttributes());
+
+ ResponseFormat addPropertiesValueToRiRes = addPropertyValuesToRi(uploadComponentInstanceInfo, resource, originResource, currentCompInstance, yamlName, instProperties, allDataTypes.left().value());
if (addPropertiesValueToRiRes.getStatus() != 200) {
return Either.right(addPropertiesValueToRiRes);
}
- Map<String, List<UploadReqInfo>> regMap = uploadComponentInstanceInfo.getRequirements();
- if (regMap == null)
- continue;
- Iterator<Entry<String, List<UploadReqInfo>>> nodesRegValue = regMap.entrySet().iterator();
-
- long startAddRelation = System.currentTimeMillis();
-
- while (nodesRegValue.hasNext()) {
- Entry<String, List<UploadReqInfo>> nodesRegInfoEntry = nodesRegValue.next();
-
- List<UploadReqInfo> uploadRegInfoList = nodesRegInfoEntry.getValue();
- for (UploadReqInfo uploadRegInfo : uploadRegInfoList) {
- log.debug("Going to create relation {}", uploadRegInfo.getName());
- String regName = uploadRegInfo.getName();
- String nodeCapName = uploadRegInfo.getNode();
- RequirementCapabilityRelDef regCapRelDef = new RequirementCapabilityRelDef();
- regCapRelDef.setFromNode(resourceInstanceId);
- log.debug("try to find available requirement {} ", regName);
- Either<RequirementDefinition, ResponseFormat> eitherReqStatus = findAviableRequiremen(regName, yamlName, uploadComponentInstanceInfo, currentCompInstance);
- if (eitherReqStatus.isRight()) {
- log.debug("failed to find available requirement {} status is {}", regName, eitherReqStatus.right().value());
- return Either.right(eitherReqStatus.right().value());
- }
- RequirementDefinition validReq = eitherReqStatus.left().value();
- List<RequirementAndRelationshipPair> reqAndRelationshipPairList = regCapRelDef.getRelationships();
- if (reqAndRelationshipPairList == null)
- reqAndRelationshipPairList = new ArrayList<RequirementAndRelationshipPair>();
- RequirementAndRelationshipPair reqAndRelationshipPair = new RequirementAndRelationshipPair();
- reqAndRelationshipPair.setRequirement(regName);
- reqAndRelationshipPair.setRequirementOwnerId(validReq.getOwnerId());
- reqAndRelationshipPair.setRequirementUid(validReq.getUniqueId());
-
- ComponentInstance currentCapCompInstance = null;
- for (ComponentInstance compInstance : componentInstancesList) {
- if (compInstance.getName().equals(uploadRegInfo.getNode())) {
- currentCapCompInstance = compInstance;
- break;
- }
- }
+ }
- if (currentCapCompInstance == null) {
- log.debug("component instance with name {} in resource {} ", uploadRegInfo.getNode(), resource.getUniqueId());
- BeEcompErrorManager.getInstance().logInternalDataError("component instance with name " + uploadRegInfo.getNode() + " in resource {} ", resource.getUniqueId(), ErrorSeverity.ERROR);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
- return Either.right(responseFormat);
- }
- regCapRelDef.setToNode(currentCapCompInstance.getUniqueId());
- log.debug("try to find aviable Capability req name is {} ", validReq.getName());
- CapabilityDefinition aviableCapForRel = findAvailableCapabilityByTypeOrName(validReq, currentCapCompInstance, uploadRegInfo);
- if (aviableCapForRel == null) {
- log.debug("aviable capability was not found. req name is {} component instance is {}", validReq.getName(), currentCapCompInstance.getUniqueId());
- BeEcompErrorManager.getInstance().logInternalDataError("aviable capability was not found. req name is " + validReq.getName() + " component instance is " + currentCapCompInstance.getUniqueId(), resource.getUniqueId(),
- ErrorSeverity.ERROR);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
- return Either.right(responseFormat);
- }
- reqAndRelationshipPair.setCapability(aviableCapForRel.getName());
- reqAndRelationshipPair.setCapabilityUid(aviableCapForRel.getUniqueId());
- reqAndRelationshipPair.setCapabilityOwnerId(aviableCapForRel.getOwnerId());
- reqAndRelationshipPairList.add(reqAndRelationshipPair);
- regCapRelDef.setRelationships(reqAndRelationshipPairList);
- ComponentInstanceBusinessLogic componentInstanceBL = getComponentInstanceBL();
- Either<RequirementCapabilityRelDef, ResponseFormat> eitherRelationRes = componentInstanceBL.associateRIToRIOnGraph(resource.getUniqueId(), regCapRelDef, ComponentTypeEnum.RESOURCE, inTransaction);
- log.debug("************* finished to create relation {}", uploadRegInfo.getName());
- if (eitherRelationRes.isRight()) {
- log.debug("failed to associate ri {} to ri {}", regCapRelDef.getFromNode(), regCapRelDef.getToNode());
- return Either.right(eitherRelationRes.right().value());
- }
+ Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addPropToInst = toscaOperationFacade.associateComponentInstancePropertiesToComponent(instProperties, resource.getUniqueId());
+ if (addPropToInst.isRight()) {
+ log.debug("failed to associate properties of resource {} status is {}", resource.getUniqueId(), addPropToInst.right().value());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addPropToInst.right().value()), yamlName);
+ return Either.right(responseFormat);
+ }
- }
+ StorageOperationStatus addArtToInst = toscaOperationFacade.associateArtifactToInstances(instArtifacts, resource.getUniqueId(), user);
+ if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
+ log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
+ return Either.right(responseFormat);
+ }
- }
- totalCreateRel += (System.currentTimeMillis() - startAddRelation);
+ addArtToInst = toscaOperationFacade.associateCalculatedCapReq(instCapabilties, instRequirements, resource.getUniqueId());
+ if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
+ log.debug("failed to associate cap and req of resource {} status is {}", resource.getUniqueId(), addArtToInst);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
+ return Either.right(responseFormat);
+ }
+
+ addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes, resource.getUniqueId());
+ if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
+ log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(), addArtToInst);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
+ return Either.right(responseFormat);
}
- /*
- * List<InputDefinition> inputs = resource.getInputs(); for(InputDefinition input: inputs){ if(input.getProperties() != null){ this.inputOperation.associatePropertiesToInputOnGraph(input. getUniqueId(), input.getProperties()); } }
- */
- // Either<Resource, StorageOperationStatus> eitherGerResource =
- // resourceOperation.getResource(resource.getUniqueId(), inTransaction);
- log.debug("************* create relations took : create {}, add property value {}", totalCreateRel, totalCreatePropVal);
- log.debug("************* in create relations, getResource start");
ComponentParametersView parametersView = new ComponentParametersView();
parametersView.disableAll();
parametersView.setIgnoreComponentInstances(false);
- parametersView.setIgnoreUsers(false);
- parametersView.setIgnoreArtifacts(false);
- parametersView.setIgnoreGroups(false);
- Either<Resource, StorageOperationStatus> eitherGerResource = resourceOperation.getComponent(resource.getUniqueId(), parametersView, inTransaction);
+ parametersView.setIgnoreComponentInstancesProperties(false);
+ parametersView.setIgnoreCapabilities(false);
+ parametersView.setIgnoreRequirements(false);
+
+ Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId(), parametersView);
+
+ if (eitherGerResource.isRight()) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
+
+ return Either.right(responseFormat);
+
+ }
+
+ resource = eitherGerResource.left().value();
+
+ for (Entry<String, UploadComponentInstanceInfo> entry : uploadResInstancesMap.entrySet()) {
+ UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue();
+ ComponentInstance currentCompInstance = null;
+ for (ComponentInstance compInstance : componentInstancesList) {
+
+ if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) {
+ currentCompInstance = compInstance;
+ break;
+ }
+
+ }
+ if (currentCompInstance == null) {
+ log.debug("component instance with name {} in resource {} ", uploadComponentInstanceInfo.getName(), resource.getUniqueId());
+ BeEcompErrorManager.getInstance().logInternalDataError("component instance with name " + uploadComponentInstanceInfo.getName() + " in resource {} ", resource.getUniqueId(), ErrorSeverity.ERROR);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
+ return Either.right(responseFormat);
+ }
+
+ ResponseFormat addRelationToRiRes = addRelationToRI(yamlName, resource, entry.getValue(), relations);
+ if (addRelationToRiRes.getStatus() != 200) {
+ return Either.right(addRelationToRiRes);
+ }
+ }
+
+ addArtToInst = toscaOperationFacade.associateResourceInstances(resource.getUniqueId(), relations);
+ if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
+ log.debug("failed to associate instances of resource {} status is {}", resource.getUniqueId(), addArtToInst);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
+ return Either.right(responseFormat);
+ }
+
+ log.debug("************* in create relations, getResource start");
+
+ eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
log.debug("************* in create relations, getResource end");
if (eitherGerResource.isRight()) {
ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
@@ -2777,117 +3570,216 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return Either.left(eitherGerResource.left().value());
}
- private ResponseFormat addPropertyValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, Resource resource, String resourceInstanceId, ComponentInstance currentCompInstance, String yamlName,
- Map<String, List<PropertyDefinition>> propertiesListPerResource) {
+ private ResponseFormat addRelationToRI(String yamlName, Resource resource, UploadComponentInstanceInfo nodesInfoValue, List<RequirementCapabilityRelDef> relations) {
+ List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
+ long totalCreateRel = 0;
+ long totalCreatePropVal = 0;
+
+ UploadComponentInstanceInfo uploadComponentInstanceInfo = nodesInfoValue;
+
+ ComponentInstance currentCompInstance = null;
+
+ for (ComponentInstance compInstance : componentInstancesList) {
+
+ if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) {
+ currentCompInstance = compInstance;
+ break;
+ }
+
+ }
+
+ if (currentCompInstance == null) {
+ log.debug("component instance with name {} in resource {} ", uploadComponentInstanceInfo.getName(), resource.getUniqueId());
+ BeEcompErrorManager.getInstance().logInternalDataError("component instance with name " + uploadComponentInstanceInfo.getName() + " in resource {} ", resource.getUniqueId(), ErrorSeverity.ERROR);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
+ return responseFormat;
+ }
+ String resourceInstanceId = currentCompInstance.getUniqueId();
+
+ log.debug("************* addPropertyValuesToRi start");
+ long startAddProperty = System.currentTimeMillis();
+ log.debug("************* addPropertyValuesToRi end");
+ totalCreatePropVal += (System.currentTimeMillis() - startAddProperty);
+ Map<String, List<UploadReqInfo>> regMap = uploadComponentInstanceInfo.getRequirements();
+ if (regMap == null) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK, yamlName);
+ return responseFormat;
+ }
+ Iterator<Entry<String, List<UploadReqInfo>>> nodesRegValue = regMap.entrySet().iterator();
+
+ long startAddRelation = System.currentTimeMillis();
+
+ while (nodesRegValue.hasNext()) {
+ Entry<String, List<UploadReqInfo>> nodesRegInfoEntry = nodesRegValue.next();
+
+ List<UploadReqInfo> uploadRegInfoList = nodesRegInfoEntry.getValue();
+ for (UploadReqInfo uploadRegInfo : uploadRegInfoList) {
+ log.debug("Going to create relation {}", uploadRegInfo.getName());
+ String regName = uploadRegInfo.getName();
+ String nodeCapName = uploadRegInfo.getNode();
+ RequirementCapabilityRelDef regCapRelDef = new RequirementCapabilityRelDef();
+ regCapRelDef.setFromNode(resourceInstanceId);
+ log.debug("try to find available requirement {} ", regName);
+ Either<RequirementDefinition, ResponseFormat> eitherReqStatus = findAviableRequiremen(regName, yamlName, uploadComponentInstanceInfo, currentCompInstance, uploadRegInfo.getCapabilityName());
+ if (eitherReqStatus.isRight()) {
+ log.debug("failed to find available requirement {} status is {}", regName, eitherReqStatus.right().value());
+ return eitherReqStatus.right().value();
+ }
+
+ RequirementDefinition validReq = eitherReqStatus.left().value();
+ List<RequirementAndRelationshipPair> reqAndRelationshipPairList = regCapRelDef.getRelationships();
+ if (reqAndRelationshipPairList == null)
+ reqAndRelationshipPairList = new ArrayList<RequirementAndRelationshipPair>();
+ RequirementAndRelationshipPair reqAndRelationshipPair = new RequirementAndRelationshipPair();
+ reqAndRelationshipPair.setRequirement(regName);
+ reqAndRelationshipPair.setRequirementOwnerId(validReq.getOwnerId());
+ reqAndRelationshipPair.setRequirementUid(validReq.getUniqueId());
+ RelationshipImpl relationship = new RelationshipImpl();
+ relationship.setType(validReq.getCapability());
+ reqAndRelationshipPair.setRelationships(relationship);
+
+ ComponentInstance currentCapCompInstance = null;
+ for (ComponentInstance compInstance : componentInstancesList) {
+ if (compInstance.getName().equals(uploadRegInfo.getNode())) {
+ currentCapCompInstance = compInstance;
+ break;
+ }
+ }
+
+ if (currentCapCompInstance == null) {
+ log.debug("component instance with name {} in resource {} ", uploadRegInfo.getNode(), resource.getUniqueId());
+ BeEcompErrorManager.getInstance().logInternalDataError("component instance with name " + uploadRegInfo.getNode() + " in resource {} ", resource.getUniqueId(), ErrorSeverity.ERROR);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
+ return responseFormat;
+ }
+ regCapRelDef.setToNode(currentCapCompInstance.getUniqueId());
+ log.debug("try to find aviable Capability req name is {} ", validReq.getName());
+ CapabilityDefinition aviableCapForRel = findAvailableCapabilityByTypeOrName(validReq, currentCapCompInstance, uploadRegInfo);
+ if (aviableCapForRel == null) {
+ log.debug("aviable capability was not found. req name is {} component instance is {}", validReq.getName(), currentCapCompInstance.getUniqueId());
+ BeEcompErrorManager.getInstance().logInternalDataError("aviable capability was not found. req name is " + validReq.getName() + " component instance is " + currentCapCompInstance.getUniqueId(), resource.getUniqueId(),
+ ErrorSeverity.ERROR);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
+ return responseFormat;
+ }
+ reqAndRelationshipPair.setCapability(aviableCapForRel.getName());
+ reqAndRelationshipPair.setCapabilityUid(aviableCapForRel.getUniqueId());
+ reqAndRelationshipPair.setCapabilityOwnerId(aviableCapForRel.getOwnerId());
+ reqAndRelationshipPairList.add(reqAndRelationshipPair);
+ regCapRelDef.setRelationships(reqAndRelationshipPairList);
+ relations.add(regCapRelDef);
+
+ }
+
+ }
+ totalCreateRel += (System.currentTimeMillis() - startAddRelation);
+
+ return componentsUtils.getResponseFormat(ActionStatus.OK);
+ }
+
+ private ResponseFormat addPropertyValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, Resource resource, Resource originResource, ComponentInstance currentCompInstance, String yamlName,
+ Map<String, List<ComponentInstanceProperty>> instProperties, Map<String, DataTypeDefinition> allDataTypes) {
Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
if (propMap != null && propMap.size() > 0) {
Map<String, PropertyDefinition> currPropertiesMap = new HashMap<String, PropertyDefinition>();
- List<PropertyDefinition> propertiesList = new ArrayList<PropertyDefinition>();
- Integer index = currentCompInstance.getPropertyValueCounter();
- Integer indexInput = currentCompInstance.getInputValueCounter();
- List<PropertyDefinition> listFromMap = propertiesListPerResource.get(currentCompInstance.getComponentUid());
- if (listFromMap != null) {
- propertiesList = listFromMap;
- } else {
- TitanOperationStatus getPropertyRes = ((PropertyOperation) propertyOperation).findAllResourcePropertiesRecursively(currentCompInstance.getComponentUid(), propertiesList);
- if (!getPropertyRes.equals(TitanOperationStatus.OK)) {
- log.debug("failed to find properties of resource {} status is {}", currentCompInstance.getComponentUid(), getPropertyRes);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(getPropertyRes)), yamlName);
- return responseFormat;
+
+ int index = 0;
+ List<PropertyDefinition> listFromMap = originResource.getProperties();
+ if (listFromMap == null || listFromMap.isEmpty()) {
+ log.debug("failed to find properties ");
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND);
+ return responseFormat;
+ }
+ for (PropertyDefinition prop : listFromMap) {
+ String propName = prop.getName();
+ if (!currPropertiesMap.containsKey(propName)) {
+ currPropertiesMap.put(propName, prop);
}
- propertiesListPerResource.put(currentCompInstance.getComponentUid(), propertiesList);
}
- if (propertiesList.size() > 0) {
- for (PropertyDefinition prop : propertiesList) {
- String propName = prop.getName();
- if (!currPropertiesMap.containsKey(propName)) {
- currPropertiesMap.put(propName, prop);
- }
+ List<ComponentInstanceProperty> instPropList = new ArrayList<>();
+ for (List<UploadPropInfo> propertyList : propMap.values()) {
+
+ UploadPropInfo propertyInfo = propertyList.get(0);
+ String propName = propertyInfo.getName();
+ if (!currPropertiesMap.containsKey(propName)) {
+ log.debug("failed to find property {} ", propName);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, propName);
+ return responseFormat;
}
- for (List<UploadPropInfo> propertyList : propMap.values()) {
- UploadPropInfo propertyInfo = propertyList.get(0);
- String propName = propertyInfo.getName();
- if (!currPropertiesMap.containsKey(propName)) {
- log.debug("failed to find property {} ", propName);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, propName);
- return responseFormat;
- }
- PropertyDefinition curPropertyDef = currPropertiesMap.get(propName);
- ComponentInstanceProperty property = null;
- ComponentInstanceInput inputValue = null;
- // TODO
- String value = null;
- List<GetInputValueInfo> getInputs = null;
- boolean isValidate = true;
- if (propertyInfo.getValue() != null) {
- getInputs = propertyInfo.getGet_input();
- isValidate = getInputs == null || getInputs.isEmpty();
- if (isValidate) {
- value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(), curPropertyDef.getType());
- } else
- value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(), ToscaTagNamesEnum.GET_INPUT.getElementName());
- }
+ PropertyDefinition curPropertyDef = currPropertiesMap.get(propName);
+ ComponentInstanceProperty property = null;
+
+ String value = null;
+ List<GetInputValueDataDefinition> getInputs = null;
+ boolean isValidate = true;
+ if (propertyInfo.getValue() != null) {
+ getInputs = propertyInfo.getGet_input();
+ isValidate = getInputs == null || getInputs.isEmpty();
+ if (isValidate) {
+ value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(), curPropertyDef.getType());
+ } else
+ value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(), ToscaTagNamesEnum.GET_INPUT.getElementName());
+ }
+ String innerType = null;
+ property = new ComponentInstanceProperty(curPropertyDef, value, null);
- property = new ComponentInstanceProperty(curPropertyDef, value, null);
+ Either<String, StorageOperationStatus> validatevalueEiter = validatePropValueBeforeCreate(property, value, isValidate, innerType, allDataTypes);
+ if (validatevalueEiter.isRight()) {
+ return componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validatevalueEiter.right().value()));
+ }
- Either<ComponentInstanceProperty, StorageOperationStatus> result = componentInstanceOperation.addPropertyValueToResourceInstance(property, resourceInstanceId, isValidate, index, true);
- if (result.isRight()) {
- log.debug("Failed to add property value {} to resource instance {}", property, resourceInstanceId);
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
- return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, currentCompInstance.getName());
- }
- Either<Integer, StorageOperationStatus> increaseCounterRes = componentInstanceOperation.increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, GraphPropertiesDictionary.PROPERTY_COUNTER, true);
- if (increaseCounterRes.isRight()) {
- log.debug("Failed to increase resource property counter {} to resource instance {}", property, resourceInstanceId);
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(increaseCounterRes.right().value());
- return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, currentCompInstance.getName());
- }
- index = increaseCounterRes.left().value();
- if (getInputs != null && !getInputs.isEmpty()) {
- for (GetInputValueInfo getInput : getInputs) {
- List<InputDefinition> inputs = resource.getInputs();
- if (inputs == null || inputs.isEmpty()) {
- log.debug("Failed to add property {} to resource instance {}. Inputs list is empty ", property, resourceInstanceId);
- return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
- }
+ // String uniqueId = UniqueIdBuilder.buildResourceInstancePropertyValueUid(currentCompInstance.getComponentUid(), index++);
+ // property.setUniqueId(uniqueId);
+ property.setValue(validatevalueEiter.left().value());
+
+ if (getInputs != null && !getInputs.isEmpty()) {
+ List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
+ for (GetInputValueDataDefinition getInput : getInputs) {
+ List<InputDefinition> inputs = resource.getInputs();
+ if (inputs == null || inputs.isEmpty()) {
+ log.debug("Failed to add property {} to resource instance {}. Inputs list is empty ", property, currentCompInstance.getUniqueId());
+ return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
+ }
+
+ Optional<InputDefinition> optional = inputs.stream().filter(p -> p.getName().equals(getInput.getInputName())).findAny();
+ if (!optional.isPresent()) {
+ log.debug("Failed to find input {} ", getInput.getInputName());
+ // @@TODO error message
+ return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
+ }
+ InputDefinition input = optional.get();
+ getInput.setInputId(input.getUniqueId());
+ getInputValues.add(getInput);
- Optional<InputDefinition> optional = inputs.stream().filter(p -> p.getName().equals(getInput.getInputName())).findAny();
+ GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
+ if (getInputIndex != null) {
+ optional = inputs.stream().filter(p -> p.getName().equals(getInputIndex.getInputName())).findAny();
if (!optional.isPresent()) {
- log.debug("Failed to find input {} ", getInput.getInputName());
+ log.debug("Failed to find input {} ", getInputIndex.getInputName());
// @@TODO error message
return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
}
- InputDefinition input = optional.get();
- TitanOperationStatus status = inputOperation.associatePropertyToInput(resourceInstanceId, input.getUniqueId(), result.left().value(), getInput);
- if (status != TitanOperationStatus.OK) {
- log.debug("Failed to associate input {} tp property value{} ", getInput.getInputName(), result.left().value().getValueUniqueUid());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status)), yamlName);
- return responseFormat;
- }
- GetInputValueInfo getInputIndex = getInput.getGetInputIndex();
- if (getInputIndex != null) {
- optional = inputs.stream().filter(p -> p.getName().equals(getInputIndex.getInputName())).findAny();
- if (!optional.isPresent()) {
- log.debug("Failed to find input {} ", getInputIndex.getInputName());
- // @@TODO error message
- return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
- }
- InputDefinition inputIndex = optional.get();
- status = inputOperation.associatePropertyToInput(resourceInstanceId, inputIndex.getUniqueId(), result.left().value(), getInputIndex);
- if (status != TitanOperationStatus.OK) {
- log.debug("Failed to associate input {} tp property value{} ", getInput.getInputName(), result.left().value().getValueUniqueUid());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status)), yamlName);
- return responseFormat;
- }
-
- }
+ InputDefinition inputIndex = optional.get();
+ getInputIndex.setInputId(inputIndex.getUniqueId());
+ getInputValues.add(getInputIndex);
}
- }
+ }
+ property.setGetInputValues(getInputValues);
+ }
+ instPropList.add(property);
+ // delete overriden property
+ currPropertiesMap.remove(property.getName());
+ }
+ // add rest of properties
+ if (!currPropertiesMap.isEmpty()) {
+ for (PropertyDefinition value : currPropertiesMap.values()) {
+ instPropList.add(new ComponentInstanceProperty(value));
}
}
+ instProperties.put(currentCompInstance.getUniqueId(), instPropList);
}
return componentsUtils.getResponseFormat(ActionStatus.OK);
}
@@ -2904,6 +3796,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
private CapabilityDefinition findAvailableCapability(RequirementDefinition validReq, ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) {
+ CapabilityDefinition cap = null;
Map<String, List<CapabilityDefinition>> capMap = currentCapCompInstance.getCapabilities();
if (!capMap.containsKey(validReq.getCapability())) {
return null;
@@ -2912,18 +3805,30 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (!capByName.isPresent()) {
return null;
}
- CapabilityDefinition cap = capByName.get();
+ cap = capByName.get();
+
+ if (cap.getMaxOccurrences() != null && !cap.getMaxOccurrences().equals(CapabilityDataDefinition.MAX_OCCURRENCES)) {
+ String leftOccurrences = cap.getLeftOccurrences();
+ int left = Integer.parseInt(leftOccurrences);
+ if (left > 0) {
+ --left;
+ cap.setLeftOccurrences(String.valueOf(left));
+
+ }
+
+ }
+
// TODO temporary fix - remove specific capability node validation -
// String reqNode = validReq.getNode();
// if (reqNode != null && !reqNode.isEmpty() &&
// !cap.getCapabilitySources().contains(reqNode)) {
// return null;
// }
- RequirementAndRelationshipPair relationPair = getReqRelPair(cap);
- Either<Boolean, StorageOperationStatus> eitherStatus = componentInstanceOperation.isAvailableCapabilty(currentCapCompInstance, relationPair);
- if (eitherStatus.isRight() || eitherStatus.left().value() == false) {
- return null;
- }
+ // RequirementAndRelationshipPair relationPair = getReqRelPair(cap);
+ // Either<Boolean, StorageOperationStatus> eitherStatus = componentInstanceOperation.isAvailableCapabilty(currentCapCompInstance, relationPair);
+ // if (eitherStatus.isRight() || eitherStatus.left().value() == false) {
+ // return null;
+ // }
return cap;
}
@@ -2949,12 +3854,21 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
// continue;
// }
// }
-
- RequirementAndRelationshipPair relationPair = getReqRelPair(cap);
- Either<Boolean, StorageOperationStatus> eitherStatus = componentInstanceOperation.isAvailableCapabilty(currentCapCompInstance, relationPair);
- if (eitherStatus.isRight() || eitherStatus.left().value() == false)
- continue;
- else {
+ if (cap.getMaxOccurrences() != null && !cap.getMaxOccurrences().equals(CapabilityDataDefinition.MAX_OCCURRENCES)) {
+ String leftOccurrences = cap.getLeftOccurrences();
+ if (leftOccurrences == null) {
+ leftOccurrences = cap.getMaxOccurrences();
+ }
+ int left = Integer.parseInt(leftOccurrences);
+ if (left > 0) {
+ --left;
+ cap.setLeftOccurrences(String.valueOf(left));
+ aviableCapForRel = cap;
+ break;
+ } else {
+ continue;
+ }
+ } else {
aviableCapForRel = cap;
break;
}
@@ -2963,33 +3877,63 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return aviableCapForRel;
}
- private Either<RequirementDefinition, ResponseFormat> findAviableRequiremen(String regName, String yamlName, UploadComponentInstanceInfo uploadComponentInstanceInfo, ComponentInstance currentCompInstance) {
+ private Either<RequirementDefinition, ResponseFormat> findAviableRequiremen(String regName, String yamlName, UploadComponentInstanceInfo uploadComponentInstanceInfo, ComponentInstance currentCompInstance, String capName) {
Map<String, List<RequirementDefinition>> comInstRegDefMap = currentCompInstance.getRequirements();
-
- Iterator<Entry<String, List<RequirementDefinition>>> regListValue = comInstRegDefMap.entrySet().iterator();
+ List<RequirementDefinition> list = comInstRegDefMap.get(capName);
RequirementDefinition validRegDef = null;
- while (regListValue.hasNext()) {
- Entry<String, List<RequirementDefinition>> regInfoEntry = regListValue.next();
-
- List<RequirementDefinition> comInstRegDefList = regInfoEntry.getValue();
+ if (list == null) {
+ for (Entry<String, List<RequirementDefinition>> entry : comInstRegDefMap.entrySet()) {
+ for (RequirementDefinition reqDef : entry.getValue()) {
+ if (reqDef.getName().equals(regName)) {
+ if (reqDef.getMaxOccurrences() != null && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
+ String leftOccurrences = reqDef.getLeftOccurrences();
+ if (leftOccurrences == null) {
+ leftOccurrences = reqDef.getMaxOccurrences();
+ }
+ int left = Integer.parseInt(leftOccurrences);
+ if (left > 0) {
+ --left;
+ reqDef.setLeftOccurrences(String.valueOf(left));
+ validRegDef = reqDef;
+ break;
+ } else {
+ continue;
+ }
+ } else {
+ validRegDef = reqDef;
+ break;
+ }
- for (RequirementDefinition comInstRegDef : comInstRegDefList) {
- if (!regName.equals(comInstRegDef.getName()))
- continue;
- RequirementAndRelationshipPair relationPair = new RequirementAndRelationshipPair();
- relationPair.setRequirementUid(comInstRegDef.getUniqueId());
- relationPair.setCapability(comInstRegDef.getCapability());
- relationPair.setRequirementOwnerId(comInstRegDef.getOwnerId());
- Either<Boolean, StorageOperationStatus> eitherStatus = componentInstanceOperation.isAvailableRequirement(currentCompInstance, relationPair);
- if (eitherStatus.isLeft() && eitherStatus.left().value() == true) {
- validRegDef = comInstRegDef;
+ }
+ }
+ if (validRegDef != null) {
break;
}
}
- if (validRegDef != null)
- break;
+ } else {
+ for (RequirementDefinition reqDef : list) {
+ if (reqDef.getName().equals(regName)) {
+ if (reqDef.getMaxOccurrences() != null && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
+ String leftOccurrences = reqDef.getLeftOccurrences();
+ if (leftOccurrences == null) {
+ leftOccurrences = reqDef.getMaxOccurrences();
+ }
+ int left = Integer.parseInt(leftOccurrences);
+ if (left > 0) {
+ --left;
+ reqDef.setLeftOccurrences(String.valueOf(left));
+ validRegDef = reqDef;
+ break;
+ } else {
+ continue;
+ }
+ } else {
+ validRegDef = reqDef;
+ break;
+ }
+ }
+ }
}
-
if (validRegDef == null) {
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
return Either.right(responseFormat);
@@ -2997,6 +3941,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return Either.left(validRegDef);
}
+ @SuppressWarnings("unchecked")
public Either<ParsedToscaYamlInfo, ResponseFormat> parseResourceInfoFromYaml(String yamlFileName, Resource resource, String resourceYml, User user) {
Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(resourceYml);
@@ -3034,6 +3979,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
private Either<Resource, ResponseFormat> createResourceInstances(User user, String yamlName, Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap, boolean inTransaction, boolean needLock,
Map<String, Resource> nodeTypeNamespaceMap) {
+
+ Either<Resource, ResponseFormat> eitherResource = null;
log.debug("createResourceInstances is {} - going to create resource instanse from CSAR", yamlName);
if (uploadResInstancesMap == null || uploadResInstancesMap.isEmpty()) {
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
@@ -3041,25 +3988,26 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return Either.right(responseFormat);
}
- Map<String, Resource> existingnodeTypeMap = new HashMap<String, Resource>();
+ Map<String, Resource> existingnodeTypeMap = new HashMap<>();
if (nodeTypeNamespaceMap != null && !nodeTypeNamespaceMap.isEmpty()) {
nodeTypeNamespaceMap.entrySet().stream().forEach(x -> existingnodeTypeMap.put(x.getValue().getToscaResourceName(), x.getValue()));
}
Iterator<Entry<String, UploadComponentInstanceInfo>> nodesInfoValue = uploadResInstancesMap.entrySet().iterator();
+ Map<ComponentInstance, Resource> resourcesInstancesMap = new HashMap<>();
while (nodesInfoValue.hasNext()) {
- log.debug("*************Going to create resource instances {}", yamlName);
+ log.debug("*************Going to create resource instances {}", yamlName);
Entry<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoEntry = nodesInfoValue.next();
UploadComponentInstanceInfo uploadComponentInstanceInfo = uploadComponentInstanceInfoEntry.getValue();
// updating type if the type is node type name - we need to take the
// updated name
- log.debug("*************Going to create resource instances {}", uploadComponentInstanceInfo.getName());
+ log.debug("*************Going to create resource instances {}", uploadComponentInstanceInfo.getName());
if (nodeTypeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
uploadComponentInstanceInfo.setType(nodeTypeNamespaceMap.get(uploadComponentInstanceInfo.getType()).getToscaResourceName());
}
- Either<Resource, ResponseFormat> eitherResource = validateResourceInstanceBeforeCreate(yamlName, inTransaction, uploadComponentInstanceInfo, existingnodeTypeMap);
+ eitherResource = validateResourceInstanceBeforeCreate(yamlName, uploadComponentInstanceInfo, existingnodeTypeMap);
if (eitherResource.isRight()) {
return eitherResource;
}
@@ -3067,7 +4015,6 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
ComponentInstance componentInstance = new ComponentInstance();
- componentInstance.setName(uploadComponentInstanceInfo.getName());
componentInstance.setComponentUid(refResource.getUniqueId());
ComponentTypeEnum containerComponentType = resource.getComponentType();
@@ -3087,26 +4034,24 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return Either.right(responseFormat);
}
Resource origResource = existingnodeTypeMap.get(uploadComponentInstanceInfo.getType());
- ComponentInstanceBusinessLogic componentInstanceBL = getComponentInstanceBL();
- Either<ComponentInstance, ResponseFormat> eitherCreateCI = componentInstanceBL.createComponentInstanceOnGraph(ComponentTypeEnum.RESOURCE_PARAM_NAME, resource, origResource, componentInstance, user.getUserId(), needLock, inTransaction);
- if (eitherCreateCI.isRight()) {
- log.debug("createResourceInstances - failed to create resource instance with name {} and type ", uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
- return Either.right(eitherCreateCI.right().value());
- }
+ componentInstance.setName(uploadComponentInstanceInfo.getName());
+ componentInstance.setIcon(origResource.getIcon());
- ComponentInstance createdCI = eitherCreateCI.left().value();
- createdCI.setName(uploadComponentInstanceInfo.getName());
- /*
- * updateComponentInstance(String containerComponentParam, org.openecomp.sdc.be.model.Component containerComponent, String componentInstanceId, ComponentInstance componentInstance, boolean inTransaction, boolean needLock)
- */
- eitherCreateCI = componentInstanceBL.updateComponentInstance(ComponentTypeEnum.RESOURCE_PARAM_NAME, resource, origResource, createdCI.getUniqueId(), createdCI, needLock, inTransaction);
- if (eitherCreateCI.isRight()) {
- log.debug("createResourceInstances - failed to update resource instance with name {} and type ", uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
- return Either.right(eitherCreateCI.right().value());
+ resourcesInstancesMap.put(componentInstance, origResource);
+
+ }
+ if (MapUtils.isNotEmpty(resourcesInstancesMap)) {
+
+ StorageOperationStatus status = toscaOperationFacade.associateComponentInstancesToComponent(resource, resourcesInstancesMap, false);
+ if (status != null && status != StorageOperationStatus.OK) {
+ log.debug("Failed to add component instances to container component {}", resource.getName());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status));
+ eitherResource = Either.right(responseFormat);
+ return eitherResource;
}
- log.debug("*************finished to create and update resource instances {}", uploadComponentInstanceInfo.getName());
}
+
log.debug("*************Going to get resource {}", resource.getUniqueId());
ComponentParametersView parametersView = new ComponentParametersView();
parametersView.disableAll();
@@ -3114,7 +4059,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
parametersView.setIgnoreUsers(false);
parametersView.setIgnoreInputs(false); // inputs are read when creating
// property values on instances
- Either<Resource, StorageOperationStatus> eitherGerResource = resourceOperation.getComponent(resource.getUniqueId(), parametersView, inTransaction);
+ Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId(), parametersView);
log.debug("*************finished to get resource {}", resource.getUniqueId());
if (eitherGerResource.isRight()) {
ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
@@ -3135,20 +4080,13 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return Either.left(eitherGerResource.left().value());
}
- private Either<Resource, ResponseFormat> validateResourceInstanceBeforeCreate(String yamlName, boolean inTransaction, UploadComponentInstanceInfo uploadComponentInstanceInfo, Map<String, Resource> nodeTypeNamespaceMap) {
+ private Either<Resource, ResponseFormat> validateResourceInstanceBeforeCreate(String yamlName, UploadComponentInstanceInfo uploadComponentInstanceInfo, Map<String, Resource> nodeTypeNamespaceMap) {
log.debug("validateResourceInstanceBeforeCreate - going to validate resource instance with name {} and type before create", uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
Resource refResource = null;
if (nodeTypeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
refResource = nodeTypeNamespaceMap.get(uploadComponentInstanceInfo.getType());
} else {
-
- Either<Boolean, StorageOperationStatus> eithervalidateResource = resourceOperation.validateToscaResourceNameExists(uploadComponentInstanceInfo.getType());
- if ((eithervalidateResource.isRight() && eithervalidateResource.right().value() == StorageOperationStatus.NOT_FOUND) || eithervalidateResource.left().value() == true) {
- log.debug("validateResourceInstanceBeforeCreate - resource instance with name {} and type not valid", uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
- return Either.right(responseFormat);
- }
- Either<Resource, StorageOperationStatus> findResourceEither = resourceOperation.getLatestCertifiedByToscaResourceName(uploadComponentInstanceInfo.getType(), inTransaction);
+ Either<Resource, StorageOperationStatus> findResourceEither = toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(uploadComponentInstanceInfo.getType());
if (findResourceEither.isRight()) {
log.debug("validateResourceInstanceBeforeCreate - not found lates version for resource instance with name {} and type ", uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(findResourceEither.right().value()));
@@ -3291,6 +4229,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
UploadPropInfo propertyDef = new UploadPropInfo();
propertyDef.setValue(propValue);
+ propertyDef.setName(propName);
if (propValue instanceof Map) {
if (((Map<String, Object>) propValue).containsKey(ToscaTagNamesEnum.TYPE.getElementName())) {
propertyDef.setType(((Map<String, Object>) propValue).get(ToscaTagNamesEnum.TYPE.getElementName()).toString());
@@ -3319,7 +4258,6 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
propertyDef.setValue(propValue);
}
- propertyDef.setName(propName);
if (moduleProp.containsKey(propName)) {
moduleProp.get(propName).add(propertyDef);
} else {
@@ -3337,18 +4275,22 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (objValue instanceof Map) {
Map<String, Object> objMap = (Map<String, Object>) objValue;
- Set<String> keys = objMap.keySet();
- for (String key : keys) {
- Object value = objMap.get(key);
- if (value instanceof Map) {
- createGetInputModuleFromMap(key, (Map<String, Object>) value, propertyDef);
+ if (objMap.containsKey(ToscaTagNamesEnum.GET_INPUT.getElementName()))
+ createGetInputModuleFromMap(propertyDef.getName(), objMap, propertyDef);
+ else {
+ Set<String> keys = objMap.keySet();
+ for (String key : keys) {
+ Object value = objMap.get(key);
+ if (value instanceof Map) {
+ createGetInputModuleFromMap(key, (Map<String, Object>) value, propertyDef);
- } else if (value instanceof List) {
- List<Object> propSubValueList = (List<Object>) value;
+ } else if (value instanceof List) {
+ List<Object> propSubValueList = (List<Object>) value;
- createInputPropList(propertyDef, propSubValueList);
- }
+ createInputPropList(propertyDef, propSubValueList);
+ }
+ }
}
} else if (objValue instanceof List) {
@@ -3365,10 +4307,10 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (propValue.containsKey(ToscaTagNamesEnum.GET_INPUT.getElementName())) {
Object getInput = propValue.get(ToscaTagNamesEnum.GET_INPUT.getElementName());
- GetInputValueInfo getInputInfo = new GetInputValueInfo();
- List<GetInputValueInfo> getInputs = propertyDef.getGet_input();
+ GetInputValueDataDefinition getInputInfo = new GetInputValueDataDefinition();
+ List<GetInputValueDataDefinition> getInputs = propertyDef.getGet_input();
if (getInputs == null) {
- getInputs = new ArrayList<GetInputValueInfo>();
+ getInputs = new ArrayList<GetInputValueDataDefinition>();
}
if (getInput instanceof String) {
@@ -3388,7 +4330,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
getInputInfo.setIndexValue(index);
} else if (indexObj instanceof Map && ((Map<String, Object>) indexObj).containsKey(ToscaTagNamesEnum.GET_INPUT.getElementName())) {
Object index = ((Map<String, Object>) indexObj).get(ToscaTagNamesEnum.GET_INPUT.getElementName());
- GetInputValueInfo getInputInfoIndex = new GetInputValueInfo();
+ GetInputValueDataDefinition getInputInfoIndex = new GetInputValueDataDefinition();
getInputInfoIndex.setInputName((String) index);
getInputInfoIndex.setPropName(propName);
getInputInfo.setGetInputIndex(getInputInfoIndex);
@@ -3607,32 +4549,35 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify");
if (inTransaction == false) {
log.debug("operation failed. do rollback");
- titanGenericDao.rollback();
+ titanDao.rollback();
}
} else if (inTransaction == false) {
log.debug("operation success. do commit");
- titanGenericDao.commit();
+ titanDao.commit();
}
}
}
- /**
+ /*
+ * /**
+ *
* @deprecated Use {@link #createOrUpdateResourceByImport(Resource,User,boolean, boolean,boolean)} instead
*/
- public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createOrUpdateResourceByImport(Resource resource, User user, AuditingActionEnum auditingEnum, boolean isNormative, boolean needLock) {
- return createOrUpdateResourceByImport(resource, user, isNormative, false, needLock);
- }
+ /*
+ * public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createOrUpdateResourceByImport(Resource resource, User user, AuditingActionEnum auditingEnum, boolean isNormative, boolean needLock) { return
+ * createOrUpdateResourceByImport(resource, user, isNormative, false, needLock); }
+ */
public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createOrUpdateResourceByImport(Resource resource, User user, boolean isNormative, boolean isInTransaction, boolean needLock) {
// check if resource already exist
- Either<Resource, StorageOperationStatus> latestByName = resourceOperation.getLatestByName(resource.getName(), true);
+ Either<Resource, StorageOperationStatus> latestByName = toscaOperationFacade.getLatestByName(resource.getName());
Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> result = null;
// create
if (latestByName.isRight() && latestByName.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
- Either<Resource, StorageOperationStatus> latestByToscaName = resourceOperation.getLatestByToscaResourceName(resource.getToscaResourceName(), true);
+ Either<Resource, StorageOperationStatus> latestByToscaName = toscaOperationFacade.getLatestByToscaResourceName(resource.getToscaResourceName());
if (latestByToscaName.isRight() && latestByToscaName.right().value().equals(StorageOperationStatus.NOT_FOUND))
result = createResourceByImport(resource, user, isNormative, isInTransaction);
@@ -3672,7 +4617,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (response.isRight()) {
return Either.right(response.right().value());
}
- Either<Resource, ResponseFormat> createResponse = createResourceByDao(resource, user, AuditingActionEnum.IMPORT_RESOURCE, isNormative, isInTransaction);
+ Either<Resource, ResponseFormat> createResponse = createResourceByDao(resource, user, AuditingActionEnum.IMPORT_RESOURCE, isNormative, isInTransaction, null);
if (createResponse.isRight()) {
return Either.right(createResponse.right().value());
} else {
@@ -3684,7 +4629,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
public boolean isResourceExist(String resourceName) {
- Either<Resource, StorageOperationStatus> latestByName = resourceOperation.getLatestByName(resourceName, false);
+ Either<Resource, StorageOperationStatus> latestByName = toscaOperationFacade.getLatestByName(resourceName);
return latestByName.isLeft();
}
@@ -3750,7 +4695,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (newResource.getToscaArtifacts() == null || newResource.getToscaArtifacts().isEmpty()) {
setToscaArtifactsPlaceHolders(newResource, user);
}
- Either<Resource, StorageOperationStatus> overrideResource = resourceOperation.overrideResource(newResource, oldResource, true);
+ Either<Resource, StorageOperationStatus> overrideResource = toscaOperationFacade.overrideComponent(newResource, oldResource);
if (overrideResource.isRight()) {
ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(overrideResource.right().value()), newResource);
@@ -3771,10 +4716,10 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Change LifecycleState - Certify");
BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify");
log.debug("operation failed. do rollback");
- titanGenericDao.rollback();
+ titanDao.rollback();
} else if (inTransaction == false) {
log.debug("operation success. do commit");
- titanGenericDao.commit();
+ titanDao.commit();
}
if (needLock == true) {
log.debug("unlock resource {}", lockedResourceId);
@@ -3829,7 +4774,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
public Either<Resource, ResponseFormat> validateResourceBeforeCreate(Resource resource, User user, AuditingActionEnum actionEnum, boolean inTransaction) {
- Either<Boolean, ResponseFormat> eitherValidation = validateResourceFieldsBeforeCreate(user, getResourceOperation(), resource, actionEnum, inTransaction);
+ Either<Boolean, ResponseFormat> eitherValidation = validateResourceFieldsBeforeCreate(user, resource, actionEnum, inTransaction);
if (eitherValidation.isRight()) {
return Either.right(eitherValidation.right().value());
}
@@ -3908,9 +4853,9 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (resource.getCapabilities() != null && resource.getCapabilities().size() > 0) {
log.debug("validate capability Types Exist - capabilities section");
- for (String type : resource.getCapabilities().keySet()) {
+ for (Entry<String, List<CapabilityDefinition>> typeEntry : resource.getCapabilities().entrySet()) {
- eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, actionEnum, eitherResult, type, inTransaction);
+ eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, actionEnum, eitherResult, typeEntry, inTransaction);
if (eitherResult.isRight()) {
return Either.right(eitherResult.right().value());
}
@@ -3951,11 +4896,54 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return eitherResult;
}
- public Either<Resource, ResponseFormat> createResourceByDao(Resource resource, User user, AuditingActionEnum actionEnum, boolean isNormative) {
- return createResourceByDao(resource, user, actionEnum, isNormative, false);
+ private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user, ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum, Either<Boolean, ResponseFormat> eitherResult,
+ Entry<String, List<CapabilityDefinition>> typeEntry, boolean inTransaction) {
+ Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation.getCapabilityType(typeEntry.getKey(), inTransaction);
+ if (eitherCapTypeFound.isRight()) {
+ if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
+ BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeCapabilityTypeMissingError, "Create Resource - validateCapabilityTypesCreate", typeEntry.getKey());
+ BeEcompErrorManager.getInstance().logBeGraphObjectMissingError("Create Resource - validateCapabilityTypesCreate", "Capability Type", typeEntry.getKey());
+ log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", typeEntry.getKey(), resource.getName());
+ BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateCapabilityTypesCreate");
+ }
+ BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError, "Create Resource - validateCapabilityTypesCreate");
+ log.debug("Trying to get capability type {} failed with error: {}", typeEntry.getKey(), eitherCapTypeFound.right().value().name());
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, typeEntry.getKey());
+ eitherResult = Either.right(errorResponse);
+ componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null);
+ }
+ CapabilityTypeDefinition capabilityTypeDefinition = eitherCapTypeFound.left().value();
+ if (capabilityTypeDefinition.getProperties() != null) {
+ for (CapabilityDefinition capDef : typeEntry.getValue()) {
+ List<ComponentInstanceProperty> properties = capDef.getProperties();
+ if (properties == null || properties.isEmpty()) {
+ properties = new ArrayList<ComponentInstanceProperty>();
+ for (Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
+ ComponentInstanceProperty newProp = new ComponentInstanceProperty(prop.getValue());
+ properties.add(newProp);
+ }
+ } else {
+ for (Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
+ PropertyDefinition porpFromDef = prop.getValue();
+ List<ComponentInstanceProperty> propsToAdd = new ArrayList<>();
+ for (ComponentInstanceProperty cip : properties) {
+ if (!cip.getName().equals(porpFromDef.getName())) {
+ ComponentInstanceProperty newProp = new ComponentInstanceProperty(porpFromDef);
+ propsToAdd.add(newProp);
+ }
+ }
+ if (!propsToAdd.isEmpty()) {
+ properties.addAll(propsToAdd);
+ }
+ }
+ }
+ capDef.setProperties(properties);
+ }
+ }
+ return eitherResult;
}
- public Either<Resource, ResponseFormat> createResourceByDao(Resource resource, User user, AuditingActionEnum actionEnum, boolean isNormative, boolean inTransaction) {
+ public Either<Resource, ResponseFormat> createResourceByDao(Resource resource, User user, AuditingActionEnum actionEnum, boolean isNormative, boolean inTransaction, EnumMap<AuditingFieldsKeysEnum, Object> additionalParams) {
// create resource
// lock new resource name in order to avoid creation resource with same
@@ -3964,37 +4952,50 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource, "Create Resource");
if (lockResult.isRight()) {
ResponseFormat responseFormat = lockResult.right().value();
- componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
+ componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, additionalParams);
return Either.right(responseFormat);
}
- log.debug("name is locked {}. status = {}", resource.getSystemName(), lockResult);
+ log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult);
}
try {
- Either<Resource, ResponseFormat> respStatus = createResourceTransaction(resource, user, actionEnum, isNormative, inTransaction);
+ if (resource.deriveFromGeneric()) {
+ Either<Resource, ResponseFormat> genericResourceEither = fetchAndSetDerivedFromGenericType(resource);
+ if (genericResourceEither.isRight())
+ return genericResourceEither;
+ if (resource.shouldGenerateInputs())
+ generateInputsFromGenericTypeProperties(resource, genericResourceEither.left().value());
+ }
+
+ Either<Resource, ResponseFormat> respStatus = createResourceTransaction(resource, user, isNormative, inTransaction);
if (respStatus.isLeft()) {
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
- componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
+ componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, additionalParams);
ASDCKpiApi.countCreatedResourcesKPI();
} else
- componentsUtils.auditResource(respStatus.right().value(), user, resource, "", "", actionEnum, null);
+ componentsUtils.auditResource(respStatus.right().value(), user, resource, "", "", actionEnum, additionalParams);
return respStatus;
} finally {
if (inTransaction == false) {
- // graphLockOperation.unlockComponent(resource.getSystemName(),
- // NodeTypeEnum.Resource);
graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(), NodeTypeEnum.Resource);
}
}
}
- private Either<Resource, ResponseFormat> createResourceTransaction(Resource resource, User user, AuditingActionEnum actionEnum, boolean isNormative, boolean inTransaction) {
+ private Either<Resource, ResponseFormat> createResourceTransaction(Resource resource, User user, boolean isNormative, boolean inTransaction) {
// validate resource name uniqueness
log.debug("validate resource name");
- Either<Boolean, ResponseFormat> eitherValidation = validateResourceNameExists(user, resource, actionEnum);
+ Either<Boolean, StorageOperationStatus> eitherValidation = toscaOperationFacade.validateComponentNameExists(resource.getName(), resource.getResourceType(), resource.getComponentType());
if (eitherValidation.isRight()) {
- return Either.right(eitherValidation.right().value());
+ log.debug("Failed to validate component name {}. Status is {}. ", resource.getName(), eitherValidation.right().value());
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(eitherValidation.right().value()));
+ return Either.right(errorResponse);
+ }
+ if (eitherValidation.left().value()) {
+ log.debug("resource with name: {}, already exists", resource.getName());
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
+ return Either.right(errorResponse);
}
log.debug("send resource {} to dao for create", resource.getName());
@@ -4002,8 +5003,9 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
createArtifactsPlaceHolderData(resource, user);
//
+
+ // enrich object
if (!isNormative) {
- // enrich object
log.debug("enrich resource with creator, version and state");
resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
resource.setVersion(INITIAL_VERSION);
@@ -4011,16 +5013,12 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
resource.setAbstract(false);
}
- Either<Resource, StorageOperationStatus> dataModelResponse = resourceOperation.createResource(resource, inTransaction);
-
- // Resource created successfully!!!
- if (dataModelResponse.isLeft()) {
- log.debug("Resource created successfully!!!");
-
- return Either.left(dataModelResponse.left().value());
+ Either<Resource, StorageOperationStatus> createToscaElement = toscaOperationFacade.createToscaComponent(resource);
+ if (createToscaElement.isLeft()) {
+ return Either.left(createToscaElement.left().value());
}
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()), resource);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(createToscaElement.right().value()), resource);
return Either.right(responseFormat);
}
@@ -4123,7 +5121,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return eitherCreator.right().value();
}
- Either<Resource, StorageOperationStatus> resourceStatus = resourceOperation.getResource(resourceId);
+ Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade.getToscaElement(resourceId);
if (resourceStatus.isRight()) {
log.debug("failed to get resource {}", resourceId);
return componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceStatus.right().value()), "");
@@ -4152,10 +5150,10 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
} finally {
if (result == null || !result.equals(StorageOperationStatus.OK)) {
log.warn("operation failed. do rollback");
- titanGenericDao.rollback();
+ titanDao.rollback();
} else {
log.debug("operation success. do commit");
- titanGenericDao.commit();
+ titanDao.commit();
}
graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource);
}
@@ -4170,30 +5168,30 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
// Resource resource = null;
- List<Resource> resourcesList = null;
+ Resource resource = null;
StorageOperationStatus result = StorageOperationStatus.OK;
try {
- Either<List<Resource>, StorageOperationStatus> resourceStatus = resourceOperation.getResourceByNameAndVersion(resourceName, version, true);
+ Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, version);
if (resourceStatus.isRight()) {
log.debug("failed to get resource {} version {}", resourceName, version);
return componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(resourceStatus.right().value()), resourceName);
}
- resourcesList = resourceStatus.left().value();
+ resource = resourceStatus.left().value();
} finally {
if (result == null || !result.equals(StorageOperationStatus.OK)) {
log.warn("operation failed. do rollback");
- titanGenericDao.rollback();
+ titanDao.rollback();
ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resourceName);
} else {
log.debug("operation success. do commit");
- titanGenericDao.commit();
+ titanDao.commit();
}
}
- for (Resource resource : resourcesList) {
+ if (resource != null) {
Either<Boolean, ResponseFormat> lockResult = lockComponent(resource.getUniqueId(), resource, "Delete Resource");
if (lockResult.isRight()) {
result = StorageOperationStatus.GENERAL_ERROR;
@@ -4210,10 +5208,10 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
} finally {
if (result == null || !result.equals(StorageOperationStatus.OK)) {
log.warn("operation failed. do rollback");
- titanGenericDao.rollback();
+ titanDao.rollback();
} else {
log.debug("operation success. do commit");
- titanGenericDao.commit();
+ titanDao.commit();
}
graphLockOperation.unlockComponent(resource.getUniqueId(), NodeTypeEnum.Resource);
}
@@ -4230,8 +5228,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
}
- IResourceOperation dataModel = getResourceOperation();
- Either<Resource, StorageOperationStatus> storageStatus = dataModel.getResource(resourceId);
+ // IResourceOperation dataModel = getResourceOperation();
+ Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(resourceId);
if (storageStatus.isRight()) {
log.debug("failed to get resource by id {}", resourceId);
@@ -4241,14 +5239,14 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
- public Either<List<Resource>, ResponseFormat> getResourceByNameAndVersion(String resourceName, String resourceVersion, String userId) {
+ public Either<Resource, ResponseFormat> getResourceByNameAndVersion(String resourceName, String resourceVersion, String userId) {
Either<User, ResponseFormat> resp = validateUserExists(userId, "get Resource By Name And Version", false);
if (resp.isRight()) {
return Either.right(resp.right().value());
}
- Either<List<Resource>, StorageOperationStatus> getResource = resourceOperation.getResourceByNameAndVersion(resourceName, resourceVersion, false);
+ Either<Resource, StorageOperationStatus> getResource = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion);
if (getResource.isRight()) {
log.debug("failed to get resource by name {} and version {}", resourceName, resourceVersion);
return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(getResource.right().value()), resourceName));
@@ -4276,7 +5274,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return Either.right(resp.right().value());
}
- IResourceOperation dataModel = getResourceOperation();
+ // IResourceOperation dataModel = getResourceOperation();
log.debug("Get resource with id {}", resourceIdToUpdate);
boolean needToUnlock = false;
boolean rollbackNeeded = true;
@@ -4285,7 +5283,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
// Either<Resource, StorageOperationStatus> storageStatus =
// dataModel.getResource_tx(resourceIdToUpdate, false);
if (currentResource == null) {
- Either<Resource, StorageOperationStatus> storageStatus = dataModel.getResource(resourceIdToUpdate, false);
+ Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(resourceIdToUpdate);
if (storageStatus.isRight()) {
return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus.right().value()), ""));
}
@@ -4303,7 +5301,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (!lockResult.equals(StorageOperationStatus.OK)) {
BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedLockObjectError, "Upload Artifact - lock " + resourceIdToUpdate + ": " + NodeTypeEnum.Resource);
BeEcompErrorManager.getInstance().logBeFailedLockObjectError("Upload Artifact - lock ", NodeTypeEnum.Resource.getName(), resourceIdToUpdate);
- log.debug("Failed to lock resource {} error - {}", resourceIdToUpdate, lockResult);
+ log.debug("Failed to lock resource: {}, error - {}", resourceIdToUpdate, lockResult);
ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockResult));
return Either.right(responseFormat);
}
@@ -4347,9 +5345,9 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
} finally {
if (!inTransaction) {
if (rollbackNeeded) {
- titanGenericDao.rollback();
+ titanDao.rollback();
} else {
- titanGenericDao.commit();
+ titanDao.commit();
}
}
@@ -4361,7 +5359,6 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
private Either<Resource, ResponseFormat> updateResourceMetadata(String resourceIdToUpdate, Resource newResource, User user, Resource currentResource, boolean shouldLock, boolean inTransaction) {
- IResourceOperation dataModel = getResourceOperation();
Either<Boolean, ResponseFormat> validateResourceFields = validateResourceFieldsBeforeUpdate(currentResource, newResource, inTransaction);
if (validateResourceFields.isRight()) {
return Either.right(validateResourceFields.right().value());
@@ -4371,7 +5368,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
newResource.setLastUpdaterUserId(user.getUserId());
newResource.setUniqueId(resourceIdToUpdate);
// Cannot set highest version through UI
- newResource.setHighestVersion(null);
+ newResource.setHighestVersion(currentResource.isHighestVersion());
newResource.setCreationDate(currentResource.getCreationDate());
Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom = processUpdateOfDerivedFrom(currentResource, newResource, user.getUserId(), shouldLock, inTransaction);
@@ -4382,7 +5379,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
log.debug("send resource {} to dao for update", newResource.getUniqueId());
- Either<Resource, StorageOperationStatus> dataModelResponse = dataModel.updateResource(newResource, inTransaction);
+ Either<Resource, StorageOperationStatus> dataModelResponse = toscaOperationFacade.updateToscaElement(newResource);
if (dataModelResponse.isRight()) {
ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()), newResource);
@@ -4405,7 +5402,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
* - Resource object to validate
* @return Either<Boolean, ErrorResponse>
*/
- private Either<Boolean, ResponseFormat> validateResourceFieldsBeforeCreate(User user, IResourceOperation dataModel, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
+ private Either<Boolean, ResponseFormat> validateResourceFieldsBeforeCreate(User user, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
Either<Boolean, ResponseFormat> componentsFieldsValidation = validateComponentFieldsBeforeCreate(user, resource, actionEnum);
if (componentsFieldsValidation.isRight()) {
return componentsFieldsValidation;
@@ -4449,6 +5446,11 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return eitherValidation;
}
+ // validate contact info
+ /*
+ * log.debug("validate contact info"); eitherValidation = validateContactIdContactId(user, resource, actionEnum); if (eitherValidation.isRight()) { return eitherValidation; }
+ */
+
// validate cost
log.debug("validate cost");
eitherValidation = validateCost(user, resource, actionEnum);
@@ -4577,7 +5579,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
String updatedCreatorUserId = updateInfoResource.getCreatorUserId();
if ((updatedCreatorUserId != null) && (!updatedCreatorUserId.equals(currentCreatorUserId))) {
- log.warn("Resource Creator User id is automatically set and cannot be updated");
+ log.warn("Resource Creator UserId is automatically set and cannot be updated");
}
String currentCreatorFullName = currentResource.getCreatorFullName();
@@ -4689,7 +5691,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
ResponseFormat errorResponse = validateResourceNameResponse.right().value();
return Either.right(errorResponse);
}
- validateResourceNameResponse = validateResourceNameExists(null, updateInfoResource, null);
+ validateResourceNameResponse = validateResourceNameExists(updateInfoResource);
if (validateResourceNameResponse.isRight()) {
ResponseFormat errorResponse = validateResourceNameResponse.right().value();
return Either.right(errorResponse);
@@ -4699,7 +5701,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
currentResource.setSystemName(ValidationUtils.convertToSystemName(resourceNameUpdated));
} else {
- log.info("Resource name {} cannot be updated once the resource has been certified once.", resourceNameUpdated);
+ log.info("Resource name: {}, cannot be updated once the resource has been certified once.", resourceNameUpdated);
ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED);
return Either.right(errorResponse);
}
@@ -4784,9 +5786,12 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return validateDerivedFromExistsEither;
}
} else {
- log.debug("Derived from cannot be updated once the resource has been certified once.");
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_DERIVED_FROM_CANNOT_BE_CHANGED);
- return Either.right(errorResponse);
+ Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null, currentResource, updateInfoResource, null);
+
+ if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left().value()) {
+ log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance");
+ return validateDerivedFromExtending;
+ }
}
} else {
// For derived from, we must know whether it was actually changed,
@@ -4806,11 +5811,11 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return Either.left(true);
}
- IResourceOperation resourceOperation = getResourceOperation();
+ // IResourceOperation resourceOperation = getResourceOperation();
String templateName = resource.getDerivedFrom().get(0);
- Either<Boolean, StorageOperationStatus> dataModelResponse = resourceOperation.validateToscaResourceNameExists(templateName);
+ Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade.validateToscaResourceNameExists(templateName);
if (dataModelResponse.isRight()) {
StorageOperationStatus storageStatus = dataModelResponse.right().value();
BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError, "Create Resource - validateDerivedFromExist");
@@ -4822,8 +5827,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return Either.right(responseFormat);
}
- if (dataModelResponse.left().value()) {
- log.info("resource template with name {} does not exists", templateName);
+ else if (!dataModelResponse.left().value()) {
+ log.info("resource template with name: {}, does not exists", templateName);
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PARENT_RESOURCE_NOT_FOUND);
componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
@@ -4833,6 +5838,41 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return Either.left(true);
}
+ // Tal G for extending inheritance US815447
+ private Either<Boolean, ResponseFormat> validateDerivedFromExtending(User user, Resource currentResource, Resource updateInfoResource, AuditingActionEnum actionEnum) {
+ // If updated resource is not deriving, should fail validation
+ /*
+ * if (currentResource.getDerivedFrom() == null || currentResource.getDerivedFrom().isEmpty()) { return Either.left(false); }
+ */
+ // If current resource is deriving from certain type and it is updated to not deriving, should fail validation
+ /*
+ * if (updateInfoResource.getDerivedFrom() == null || updateInfoResource.getDerivedFrom().isEmpty()) { return Either.left(false); }
+ */
+ String currentTemplateName = currentResource.getDerivedFrom().get(0);
+ String updatedTemplateName = updateInfoResource.getDerivedFrom().get(0);
+
+ Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade.validateToscaResourceNameExtends(currentTemplateName, updatedTemplateName);
+ if (dataModelResponse.isRight()) {
+ StorageOperationStatus storageStatus = dataModelResponse.right().value();
+ BeEcompErrorManager.getInstance().logBeDaoSystemError("Create/Update Resource - validateDerivingFromExtendingType");
+ log.debug("request to data model failed with error: {}", storageStatus.name());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), currentResource);
+ log.trace("audit before sending response");
+ componentsUtils.auditResource(responseFormat, user, currentResource, "", "", actionEnum, null);
+ return Either.right(responseFormat);
+ }
+
+ if (!dataModelResponse.left().value()) {
+ log.info("resource template with name {} does not inherit as original {}", updatedTemplateName, currentTemplateName);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PARENT_RESOURCE_DOES_NOT_EXTEND);
+ componentsUtils.auditResource(responseFormat, user, currentResource, "", "", actionEnum, null);
+
+ return Either.right(responseFormat);
+
+ }
+ return Either.left(true);
+ }
+
public Either<Boolean, ResponseFormat> validateDerivedFromNotEmpty(User user, Resource resource, AuditingActionEnum actionEnum) {
log.debug("validate resource derivedFrom field");
if ((resource.getDerivedFrom() == null) || (resource.getDerivedFrom().isEmpty()) || (resource.getDerivedFrom().get(0)) == null || (resource.getDerivedFrom().get(0).trim().isEmpty())) {
@@ -4845,23 +5885,20 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return Either.left(true);
}
- private Either<Boolean, ResponseFormat> validateResourceNameExists(User user, Resource resource, AuditingActionEnum actionEnum) {
+ private Either<Boolean, ResponseFormat> validateResourceNameExists(Resource resource) {
- IResourceOperation resourceOperation = getResourceOperation();
- Either<Boolean, StorageOperationStatus> resourceOperationResponse = resourceOperation.validateResourceNameExists(resource.getName(), resource.getResourceType());
+ Either<Boolean, StorageOperationStatus> resourceOperationResponse = toscaOperationFacade.validateComponentNameExists(resource.getName(), resource.getResourceType(), resource.getComponentType());
if (resourceOperationResponse.isLeft()) {
- if (resourceOperationResponse.left().value()) {
- return Either.left(true);
+ if (!resourceOperationResponse.left().value()) {
+ return Either.left(false);
} else {
- log.debug("resource with name {} already exists", resource.getName());
+ log.debug("resource with name: {}, already exists", resource.getName());
ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
- componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null);
return Either.right(errorResponse);
}
}
log.debug("error while validateResourceNameExists for resource: {}", resource.getName());
ResponseFormat errorResponse = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceOperationResponse.right().value()));
- componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null);
return Either.right(errorResponse);
}
@@ -5037,7 +6074,57 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return Either.left(false);
}
-
+
+ /*
+ * private Either<Boolean, ResponseFormat> validateDescriptionAndCleanup(User user, Resource resource, AuditingActionEnum actionEnum) { String description = resource.getDescription(); if (!ValidationUtils.validateStringNotEmpty(description)) {
+ * log.debug("Resource description is empty"); ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus. COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.RESOURCE.getValue()); componentsUtils.auditResource(errorResponse,
+ * user, resource, "", "", actionEnum, null); return Either.right(errorResponse); }
+ *
+ * description = ValidationUtils.removeNoneUtf8Chars(description); description = ValidationUtils.removeHtmlTags(description); description = ValidationUtils.normaliseWhitespace(description); description = ValidationUtils.stripOctets(description);
+ *
+ * Either<Boolean, ResponseFormat> validatDescription = validateResourceDescription(description); if (validatDescription.isRight()) { ResponseFormat responseFormat = validatDescription.right().value();
+ * componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); return Either.right(responseFormat); } resource.setDescription(description); return Either.left(true); }
+ *
+ * private Either<Boolean, ResponseFormat> validateResourceDescription(String description) { if (description != null) { if (!ValidationUtils.validateDescriptionLength(description)) { return
+ * Either.right(componentsUtils.getResponseFormat(ActionStatus. COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH)); }
+ *
+ * if (!ValidationUtils.validateIsEnglish(description)) { return Either.right(componentsUtils.getResponseFormat(ActionStatus. COMPONENT_INVALID_DESCRIPTION, ComponentTypeEnum.RESOURCE.getValue())); } return Either.left(true); } return
+ * Either.left(false); }
+ */
+
+ /*
+ * private Either<Boolean, ResponseFormat> validateContactId(User user, Resource resource, AuditingActionEnum actionEnum) { String contactId = resource.getContactId();
+ *
+ * if (!ValidationUtils.validateStringNotEmpty(contactId)) { log.info("contact info is missing."); ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus. COMPONENT_MISSING_CONTACT, ComponentTypeEnum.RESOURCE.getValue());
+ * componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null); return Either.right(errorResponse); }
+ *
+ * Either<Boolean, ResponseFormat> validateContactIdResponse = validateContactId(contactId); if (validateContactIdResponse.isRight()) { ResponseFormat responseFormat = validateContactIdResponse.right().value();
+ * componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); } return validateContactIdResponse; }
+ *
+ * private Either<Boolean, ResponseFormat> validateContactId(String contactId) { if (contactId != null) { if (!ValidationUtils.validateContactId(contactId)) { log.debug("contact {} is invalid.", contactId); ResponseFormat errorResponse =
+ * componentsUtils.getResponseFormat(ActionStatus. COMPONENT_INVALID_CONTACT, ComponentTypeEnum.RESOURCE.getValue()); return Either.right(errorResponse); } return Either.left(true); } return Either.left(false);
+ *
+ * }
+ */
+
+ /*
+ * private Either<Boolean, ResponseFormat> validateIcon(User user, Resource resource, AuditingActionEnum actionEnum) { String icon = resource.getIcon();
+ *
+ * if (!ValidationUtils.validateStringNotEmpty(icon)) { log.debug("icon is missing."); ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_ICON, ComponentTypeEnum.RESOURCE.getValue());
+ * componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null); return Either.right(errorResponse); }
+ *
+ * Either<Boolean, ResponseFormat> validateIcon = validateIcon(icon); if (validateIcon.isRight()) { ResponseFormat responseFormat = validateIcon.right().value(); componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum,
+ * null); } return validateIcon;
+ *
+ * }
+ *
+ * public Either<Boolean, ResponseFormat> validateIcon(String icon) { if (icon != null) { if (!ValidationUtils.validateIconLength(icon)) { log.debug("icon exceeds max length"); return Either.right(componentsUtils.getResponseFormat(ActionStatus.
+ * COMPONENT_ICON_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.ICON_MAX_LENGTH)); } if (!ValidationUtils.validateIcon(icon)) { log.debug("icon is invalid." ); ResponseFormat errorResponse =
+ * componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_ICON, ComponentTypeEnum.RESOURCE.getValue()); return Either.right(errorResponse); } return Either.left(true); } return Either.left(false);
+ *
+ * }
+ */
+
private Either<Boolean, ResponseFormat> validateCost(User user, Resource resource, AuditingActionEnum actionEnum) {
String cost = resource.getCost();
if (cost != null) {
@@ -5084,11 +6171,11 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
String interfaceType = interfaceTypeOperation.getShortInterfaceName(interfaceDefinition);
log.trace("Starting interface artifacts removal for interface type {}", interfaceType);
- Map<String, Operation> operations = interfaceDefinition.getOperations();
+ Map<String, Operation> operations = interfaceDefinition.getOperationsMap();
if (operations != null) {
for (Entry<String, Operation> operationEntry : operations.entrySet()) {
Operation operation = operationEntry.getValue();
- ArtifactDefinition implementation = operation.getImplementation();
+ ArtifactDefinition implementation = operation.getImplementationArtifact();
if (implementation != null) {
String uniqueId = implementation.getUniqueId();
log.debug("Removing interface artifact definition {}, operation {}, interfaceType {}", uniqueId, operationEntry.getKey(), interfaceType);
@@ -5097,7 +6184,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (deleteArtifactByInterface.isRight()) {
log.debug("Couldn't remove artifact definition with id {}", uniqueId);
if (!inTransaction) {
- titanGenericDao.rollback();
+ titanDao.rollback();
}
return Either.right(deleteArtifactByInterface.right().value());
}
@@ -5116,7 +6203,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (findPropertiesOfNode.isRight() && !findPropertiesOfNode.right().value().equals(StorageOperationStatus.OK)) {
log.debug("Failed to remove all properties of resource");
if (!inTransaction)
- titanGenericDao.rollback();
+ titanDao.rollback();
return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(findPropertiesOfNode.right().value())));
}
@@ -5125,7 +6212,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
if (!inTransaction)
- titanGenericDao.commit();
+ titanDao.commit();
return Either.left(true);
}
@@ -5309,7 +6396,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (regResponse.isRight())
return Either.right(regResponse.right().value());
if (regResponse.left().value().size() > 0) {
- groupInfo.setProperties(regResponse.left().value());
+ groupInfo.convertFromGroupProperties(regResponse.left().value());
}
}
@@ -5378,7 +6465,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
groupProperty.setValue(convertedValue);
groupProperty.setName(propName);
- log.debug("After building group property {}", groupProperty);
+ log.trace("After building group property {}", groupProperty);
result.add(groupProperty);
}
@@ -5401,7 +6488,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
// get resource from csar uuid
- Either<Resource, StorageOperationStatus> either = resourceOperation.getLatestResourceByCsarOrName(csarUuid, "");
+ Either<Resource, StorageOperationStatus> either = toscaOperationFacade.getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUuid, "");
if (either.isRight()) {
ResponseFormat resp = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_FROM_CSAR_NOT_FOUND, csarUuid);
return Either.right(resp);
@@ -5464,6 +6551,94 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return Either.left(true);
}
+ private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> organizeVfCsarArtifactsByArtifactOperation(List<NonMetaArtifactInfo> artifactPathAndNameList, List<ArtifactDefinition> existingArtifactsToHandle,
+ Resource resource, User user) {
+
+ EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> nodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
+ Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
+ Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> nodeTypeArtifactsToHandleRes = Either.left(nodeTypeArtifactsToHandle);
+ ;
+ try {
+ // add all found Csar artifacts to list to upload
+ List<NonMetaArtifactInfo> artifactsToUpload = new ArrayList<>(artifactPathAndNameList);
+ List<NonMetaArtifactInfo> artifactsToUpdate = new ArrayList<>();
+ List<NonMetaArtifactInfo> artifactsToDelete = new ArrayList<>();
+ for (NonMetaArtifactInfo currNewArtifact : artifactPathAndNameList) {
+ ArtifactDefinition foundArtifact;
+
+ if (!existingArtifactsToHandle.isEmpty()) {
+ foundArtifact = existingArtifactsToHandle.stream().filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName())).findFirst().orElse(null);
+ if (foundArtifact != null) {
+ if (ArtifactTypeEnum.findType(foundArtifact.getArtifactType()) == currNewArtifact.getArtifactType()) {
+ if (!foundArtifact.getArtifactChecksum().equals(currNewArtifact.getArtifactChecksum())) {
+ currNewArtifact.setArtifactUniqueId(foundArtifact.getUniqueId());
+ // if current artifact already exists, but has different content, add him to the list to update
+ artifactsToUpdate.add(currNewArtifact);
+ }
+ // remove found artifact from the list of existing artifacts to handle, because it was already handled
+ existingArtifactsToHandle.remove(foundArtifact);
+ // and remove found artifact from the list to upload, because it should either be updated or be ignored
+ artifactsToUpload.remove(currNewArtifact);
+ } else {
+ log.debug("Can't upload two artifact with the same name {}.", currNewArtifact.getArtifactName());
+ ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, currNewArtifact.getArtifactName(),
+ currNewArtifact.getArtifactType().name(), foundArtifact.getArtifactType());
+ AuditingActionEnum auditingAction = artifactsBusinessLogic.detectAuditingType(artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Create), foundArtifact.getArtifactChecksum());
+ artifactsBusinessLogic.handleAuditing(auditingAction, resource, resource.getUniqueId(), user, null, null, foundArtifact.getUniqueId(), responseFormat, resource.getComponentType(), null);
+ responseWrapper.setInnerElement(responseFormat);
+ break;
+ }
+ }
+ }
+ }
+ if (responseWrapper.isEmpty()) {
+ existingArtifactsToHandle.stream()
+ // add all artifacts which was not detected as artifact to update or to ignore to the list to delete
+ .forEach(a -> artifactsToDelete.add(new NonMetaArtifactInfo(a.getArtifactName(), null, ArtifactTypeEnum.findType(a.getArtifactType()), a.getArtifactGroupType(), null, a.getUniqueId())));
+ }
+ if (responseWrapper.isEmpty()) {
+ if (!artifactsToUpload.isEmpty())
+ nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Create, artifactsToUpload);
+ if (!artifactsToUpdate.isEmpty())
+ nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Update, artifactsToUpdate);
+ if (!artifactsToDelete.isEmpty())
+ nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Delete, artifactsToDelete);
+ }
+ if (!responseWrapper.isEmpty()) {
+ nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement());
+ }
+ } catch (Exception e) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
+ responseWrapper.setInnerElement(responseFormat);
+ log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
+ }
+ return nodeTypeArtifactsToHandleRes;
+ }
+
+ private String buildNestedVfcToscaNamespace(String nodeTypeFullName) {
+
+ String actualName = this.getNodeTypeActualName(nodeTypeFullName);
+ return ImportUtils.Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + ResourceTypeEnum.VFC.name().toLowerCase() + actualName;
+
+ }
+
+ private String buildNestedVfcToscaResourceName(String vfResourceName, String nodeTypeFullName) {
+ String toscaResourceName;
+ String nameWithouNamespacePrefix = getNodeTypeActualName(nodeTypeFullName);
+ if (nameWithouNamespacePrefix.startsWith(Constants.ABSTRACT)) {
+ toscaResourceName = Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + ResourceTypeEnum.VFC.name().toLowerCase() + '.' + vfResourceName + '.' + nameWithouNamespacePrefix;
+ } else {
+ toscaResourceName = Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + ResourceTypeEnum.VFC.name().toLowerCase() + '.' + vfResourceName + '.' + Constants.ABSTRACT + nameWithouNamespacePrefix;
+ }
+ return toscaResourceName;
+ }
+
+ private String buildNestedSubstituteYamlName(String nodeTypeFullName) {
+ String[] nodeTypeFullNameParsed = nodeTypeFullName.split("\\.");
+ String nodeTypeActualName = nodeTypeFullNameParsed[nodeTypeFullNameParsed.length - 1];
+ return CsarUtils.DEFINITIONS_PATH + nodeTypeActualName + Constants.SERVICE_TEMPLATE_FILE_POSTFIX;
+ }
+
public ICacheMangerOperation getCacheManagerOperation() {
return cacheManagerOperation;
}
@@ -5472,4 +6647,92 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
this.cacheManagerOperation = cacheManagerOperation;
}
+ ///////////////////////////////////////// DataModel refactoring/////////////////////////////////////////////
+
+ /*
+ * /**
+ *
+ * @deprecated Use {@link #createOrUpdateResourceByImport(Resource,User,boolean, boolean,boolean)} instead
+ */
+ /*
+ * public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createOrUpdateResourceByImport(Resource resource, User user, AuditingActionEnum auditingEnum, boolean isNormative, boolean needLock) { return
+ * createOrUpdateResourceByImport(resource, user, isNormative, false, needLock); }
+ */
+
+ public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createOrUpdateNodeTypeByImport(Resource resource, User user, boolean isNormative, boolean isInTransaction, boolean needLock) {
+
+ // check if resource already exist
+ Either<Resource, StorageOperationStatus> latestByName = toscaOperationFacade.getLatestByName(resource.getName());
+ Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> result = null;
+
+ // create
+ if (latestByName.isRight() && latestByName.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
+
+ Either<Resource, StorageOperationStatus> latestByToscaName = toscaOperationFacade.getLatestByToscaResourceName(resource.getToscaResourceName());
+ if (latestByToscaName.isRight() && latestByToscaName.right().value().equals(StorageOperationStatus.NOT_FOUND))
+ result = createNodeTypeByImport(resource, user, isNormative, isInTransaction);
+
+ else {
+ StorageOperationStatus status = latestByName.right().value();
+ BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeResourceMissingError, "Create / Update resource by import", resource.getName());
+ BeEcompErrorManager.getInstance().logBeComponentMissingError("Create / Update resource by import", ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
+ log.debug("resource already exist {}. status={}", resource.getName(), status);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_ALREADY_EXISTS);
+ componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
+ result = Either.right(responseFormat);
+ }
+
+ }
+
+ // update
+ else if (latestByName.isLeft()) {
+ // result = updateExistingNodeTypeByImport(resource, latestByName.left().value(), user, isNormative, needLock);
+ }
+
+ // error
+ else {
+ StorageOperationStatus status = latestByName.right().value();
+ BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeResourceMissingError, "Create / Update resource by import", resource.getName());
+ log.debug("failed to get latest version of resource {}. status={}", resource.getName(), status);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(latestByName.right().value()), resource);
+ componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
+ result = Either.right(responseFormat);
+ }
+ return result;
+
+ }
+
+ private Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createNodeTypeByImport(Resource resource, User user, boolean isNormative, boolean isInTransaction) {
+ log.debug("resource with name {} does not exist. create new resource", resource.getName());
+ Either<Resource, ResponseFormat> response = validateResourceBeforeCreate(resource, user, AuditingActionEnum.IMPORT_RESOURCE, isInTransaction);
+ if (response.isRight()) {
+ return Either.right(response.right().value());
+ }
+
+ Either<Resource, ResponseFormat> createResponse = createResourceByDao(resource, user, AuditingActionEnum.IMPORT_RESOURCE, isNormative, isInTransaction, null);
+ if (createResponse.isRight()) {
+ return Either.right(createResponse.right().value());
+ } else {
+ ImmutablePair<Resource, ActionStatus> resourcePair = new ImmutablePair<>(createResponse.left().value(), ActionStatus.CREATED);
+ ASDCKpiApi.countImportResourcesKPI();
+ return Either.left(resourcePair);
+
+ }
+ }
+
+ public Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String resourceId, List<String> dataParamsToReturn) {
+
+ ComponentParametersView paramsToRetuen = new ComponentParametersView(dataParamsToReturn);
+ Either<Resource, StorageOperationStatus> resourceResultEither = toscaOperationFacade.getToscaElement(resourceId, paramsToRetuen);
+
+ if (resourceResultEither.isRight()) {
+ log.debug("failed to get resource by id {} with filters {}", resourceId, dataParamsToReturn.toString());
+ return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(resourceResultEither.right().value()), ""));
+ }
+
+ Resource resource = resourceResultEither.left().value();
+ UiComponentDataTransfer dataTransfer = UiComponentDataConverter.getUiDataTransferFromResourceByParams(resource, dataParamsToReturn);
+ return Either.left(dataTransfer);
+ }
+
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceImportManager.java
index 329481a546..f35515f8fe 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceImportManager.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceImportManager.java
@@ -37,6 +37,7 @@ import javax.servlet.ServletContext;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.auditing.api.IAuditingManager;
+import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum;
import org.openecomp.sdc.be.components.impl.ImportUtils.Constants;
import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum;
import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaTagNamesEnum;
@@ -49,6 +50,7 @@ import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.impl.WebAppContextWrapper;
+import org.openecomp.sdc.be.model.ArtifactDefinition;
import org.openecomp.sdc.be.model.AttributeDefinition;
import org.openecomp.sdc.be.model.CapabilityDefinition;
import org.openecomp.sdc.be.model.ComponentInstanceProperty;
@@ -61,6 +63,7 @@ import org.openecomp.sdc.be.model.UploadResourceInfo;
import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.model.category.CategoryDefinition;
import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.CapabilityTypeOperation;
@@ -101,29 +104,45 @@ public class ResourceImportManager {
@Autowired
protected CapabilityTypeOperation capabilityTypeOperation;
+ @Autowired
+ protected ToscaOperationFacade toscaOperationFacade;
private ResponseFormatManager responseFormatManager;
private static Logger log = LoggerFactory.getLogger(ResourceImportManager.class.getName());
+ public void setToscaOperationFacade(ToscaOperationFacade toscaOperationFacade) {
+ this.toscaOperationFacade = toscaOperationFacade;
+ }
+
public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> importNormativeResource(String resourceYml, UploadResourceInfo resourceMetaData, User creator, boolean createNewVersion, boolean needLock) {
LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction();
lifecycleChangeInfo.setUserRemarks("certification on import");
Function<Resource, Either<Boolean, ResponseFormat>> validator = (resource) -> resourceBusinessLogic.validatePropertiesDefaultValues(resource);
- return importCertifiedResource(resourceYml, resourceMetaData, creator, validator, lifecycleChangeInfo, false, createNewVersion, needLock);
+ return importCertifiedResource(resourceYml, resourceMetaData, creator, validator, lifecycleChangeInfo, false, createNewVersion, needLock, null, null);
+ }
+
+ public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> importNormativeResourceFromCsar(String resourceYml, UploadResourceInfo resourceMetaData, User creator, boolean createNewVersion, boolean needLock) {
+
+ LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction();
+ lifecycleChangeInfo.setUserRemarks("certification on import");
+ Function<Resource, Either<Boolean, ResponseFormat>> validator = (resource) -> resourceBusinessLogic.validatePropertiesDefaultValues(resource);
+
+ return importCertifiedResource(resourceYml, resourceMetaData, creator, validator, lifecycleChangeInfo, false, createNewVersion, needLock, null, null);
}
public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> importCertifiedResource(String resourceYml, UploadResourceInfo resourceMetaData, User creator, Function<Resource, Either<Boolean, ResponseFormat>> validationFunction,
- LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean isInTransaction, boolean createNewVersion, boolean needLock) {
+ LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean isInTransaction, boolean createNewVersion, boolean needLock, Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts) {
Resource resource = new Resource();
- ImmutablePair<Resource, ActionStatus> responsePair = new ImmutablePair<Resource, ActionStatus>(resource, ActionStatus.CREATED);
+ ImmutablePair<Resource, ActionStatus> responsePair = new ImmutablePair<>(resource, ActionStatus.CREATED);
Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> response = Either.left(responsePair);
String latestCertifiedResourceId = null;
try {
- setConstantMetaData(resource);
+ boolean shouldBeCertified = nodeTypeArtifactsToHandle == null || nodeTypeArtifactsToHandle.isEmpty() ? true : false;
+ setConstantMetaData(resource, shouldBeCertified);
setMetaDataFromJson(resourceMetaData, resource);
Either<Boolean, ResponseFormat> validateResourceFromYaml = populateResourceFromYaml(resourceYml, resource, isInTransaction);
@@ -138,21 +157,30 @@ public class ResourceImportManager {
if (isValidResource.isLeft()) {
// The flag createNewVersion if false doesn't create new version
if (!createNewVersion) {
- Either<Resource, StorageOperationStatus> latestByName = resourceOperation.getLatestByName(resource.getName(), isInTransaction);
+ Either<Resource, StorageOperationStatus> latestByName = toscaOperationFacade.getLatestByName(resource.getName());
if (latestByName.isLeft()) {
return Either.right(componentsUtils.getResponseFormatByResource(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, resource));
}
}
response = resourceBusinessLogic.createOrUpdateResourceByImport(resource, creator, true, isInTransaction, needLock);
+ Either<Resource, ResponseFormat> changeStateResponse;
if (response.isLeft()) {
resource = response.left().value().left;
+
+ if(nodeTypeArtifactsToHandle !=null && !nodeTypeArtifactsToHandle.isEmpty()){
+ Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes =
+ resourceBusinessLogic.handleNodeTypeArtifacts(resource, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, creator, isInTransaction);
+ if(handleNodeTypeArtifactsRes.isRight()){
+ return Either.right(handleNodeTypeArtifactsRes.right().value());
+ }
+ }
latestCertifiedResourceId = getLatestCertifiedResourceId(resource);
- Either<Resource, ResponseFormat> certificationResponse = resourceBusinessLogic.propagateStateToCertified(creator, resource, lifecycleChangeInfo, isInTransaction, needLock);
- if (certificationResponse.isRight()) {
- response = Either.right(certificationResponse.right().value());
+ changeStateResponse = resourceBusinessLogic.propagateStateToCertified(creator, resource, lifecycleChangeInfo, isInTransaction, needLock);
+ if (changeStateResponse.isRight()) {
+ response = Either.right(changeStateResponse.right().value());
} else {
- responsePair = new ImmutablePair<Resource, ActionStatus>(certificationResponse.left().value(), response.left().value().right);
+ responsePair = new ImmutablePair<>(changeStateResponse.left().value(), response.left().value().right);
response = Either.left(responsePair);
}
}
@@ -490,7 +518,8 @@ public class ResourceImportManager {
String derivedFrom = toscaDerivedFromElement.left().value();
log.debug("Derived from TOSCA name is {}", derivedFrom);
resource.setDerivedFrom(Arrays.asList(new String[] { derivedFrom }));
- Either<Resource, StorageOperationStatus> latestByToscaResourceName = resourceOperation.getLatestByToscaResourceName(derivedFrom, inTransaction);
+ Either<Resource, StorageOperationStatus> latestByToscaResourceName = toscaOperationFacade.getLatestByToscaResourceName(derivedFrom);
+
if (latestByToscaResourceName.isRight()) {
StorageOperationStatus operationStatus = latestByToscaResourceName.right().value();
if (operationStatus.equals(StorageOperationStatus.NOT_FOUND)) {
@@ -775,10 +804,18 @@ public class ResourceImportManager {
}
- private void setConstantMetaData(Resource resource) {
- resource.setVersion(ImportUtils.Constants.FIRST_CERTIFIED_VERSION_VERSION);
- ;
- resource.setLifecycleState(ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE);
+ private void setConstantMetaData(Resource resource, boolean shouldBeCertified) {
+ String version;
+ LifecycleStateEnum state;
+ if(shouldBeCertified){
+ version = ImportUtils.Constants.FIRST_CERTIFIED_VERSION_VERSION;
+ state = ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE;
+ }else{
+ version = ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION;
+ state = ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT;
+ }
+ resource.setVersion(version);
+ resource.setLifecycleState(state);
resource.setHighestVersion(ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION);
resource.setVendorName(ImportUtils.Constants.VENDOR_NAME);
resource.setVendorRelease(ImportUtils.Constants.VENDOR_RELEASE);
@@ -833,7 +870,7 @@ public class ResourceImportManager {
}
if (maxOccurrences <= 0 || maxOccurrences < minOccurrences) {
- log.debug("Invalid occurrenses format. min occurrence is {}. Max occurrence is {}", minOccurrences, maxOccurrences);
+ log.debug("Invalid occurrenses format. min occurrence is {}, Max occurrence is {}", minOccurrences, maxOccurrences);
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_OCCURRENCES);
return Either.right(responseFormat);
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogic.java
index 6bbe88f30c..1f481a7b5a 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogic.java
@@ -32,10 +32,6 @@ import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.Callable;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.Future;
-import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;
@@ -44,6 +40,7 @@ import javax.servlet.http.HttpServletRequest;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
+import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.components.distribution.engine.IDistributionEngine;
import org.openecomp.sdc.be.components.distribution.engine.INotificationData;
import org.openecomp.sdc.be.components.distribution.engine.VfModuleArtifactPayload;
@@ -52,17 +49,20 @@ import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao;
+import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
+import org.openecomp.sdc.be.datamodel.utils.UiComponentDataConverter;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.GroupTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
import org.openecomp.sdc.be.impl.WebAppContextWrapper;
import org.openecomp.sdc.be.model.ArtifactDefinition;
import org.openecomp.sdc.be.model.Component;
import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.ComponentParametersView;
import org.openecomp.sdc.be.model.DistributionStatusEnum;
import org.openecomp.sdc.be.model.DistributionTransitionEnum;
-import org.openecomp.sdc.be.model.GroupDefinition;
+import org.openecomp.sdc.be.model.GroupInstance;
+import org.openecomp.sdc.be.model.GroupInstanceProperty;
import org.openecomp.sdc.be.model.LifecycleStateEnum;
import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.Service;
@@ -70,25 +70,25 @@ import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.model.category.CategoryDefinition;
import org.openecomp.sdc.be.model.operations.api.ICacheMangerOperation;
import org.openecomp.sdc.be.model.operations.api.IElementOperation;
-import org.openecomp.sdc.be.model.operations.api.IServiceOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.be.model.operations.impl.ComponentOperation;
-import org.openecomp.sdc.be.model.operations.impl.ServiceOperation;
import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
+import org.openecomp.sdc.be.resources.data.ComponentInstanceData;
+import org.openecomp.sdc.be.resources.data.ComponentMetadataData;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent;
import org.openecomp.sdc.be.resources.data.auditing.DistributionDeployEvent;
import org.openecomp.sdc.be.resources.data.auditing.DistributionNotificationEvent;
import org.openecomp.sdc.be.resources.data.auditing.ResourceAdminEvent;
+import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer;
import org.openecomp.sdc.be.user.Role;
import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
import org.openecomp.sdc.common.api.ArtifactTypeEnum;
import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.config.EcompErrorName;
import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
import org.openecomp.sdc.common.datastructure.Wrapper;
import org.openecomp.sdc.common.kpi.api.ASDCKpiApi;
+import org.openecomp.sdc.common.util.GeneralUtility;
import org.openecomp.sdc.common.util.ThreadLocalsHolder;
import org.openecomp.sdc.common.util.ValidationUtils;
import org.openecomp.sdc.exception.ResponseFormat;
@@ -125,6 +125,9 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
private ServiceComponentInstanceBusinessLogic serviceComponentInstanceBusinessLogic;
@Autowired
+ private GroupBusinessLogic groupBusinessLogic;
+
+ @Autowired
private ICacheMangerOperation cacheManagerOperation;
private static Logger log = LoggerFactory.getLogger(ServiceBusinessLogic.class.getName());
@@ -190,17 +193,16 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
} else {
newState = DistributionStatusEnum.DISTRIBUTION_REJECTED;
}
- Either<Service, StorageOperationStatus> result = serviceOperation.updateDestributionStatus(service, user, newState);
+ Either<Service, StorageOperationStatus> result = toscaOperationFacade.updateDistributionStatus(service, user, newState);
if (result.isRight()) {
- titanGenericDao.rollback();
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "ChangeServiceDistributionState");
+ titanDao.rollback();
BeEcompErrorManager.getInstance().logBeSystemError("ChangeServiceDistributionState");
log.debug("service {} is change destribuation status failed", service.getUniqueId());
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR, service.getVersion(), service.getName());
createAudit(user, auditAction, comment, service, responseFormat);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
}
- titanGenericDao.commit();
+ titanDao.commit();
Service updatedService = result.left().value();
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
@@ -319,13 +321,14 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
log.debug("enrich service with version and state");
service.setState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
service.setVersion(INITIAL_VERSION);
+ service.setConformanceLevel(ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel());
service.setDistributionStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED);
Either<Service, ResponseFormat> createServiceResponse = validateServiceBeforeCreate(service, user, AuditingActionEnum.CREATE_RESOURCE);
if (createServiceResponse.isRight()) {
return createServiceResponse;
}
- return createServiceByDao(service, AuditingActionEnum.CREATE_RESOURCE, serviceOperation, user);
+ return createServiceByDao(service, AuditingActionEnum.CREATE_RESOURCE, user);
}
private void checkFieldsForOverideAttampt(Service service) {
@@ -335,7 +338,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
}
}
- private Either<Service, ResponseFormat> createServiceByDao(Service service, AuditingActionEnum actionEnum, IServiceOperation dataModel, User user) {
+ private Either<Service, ResponseFormat> createServiceByDao(Service service, AuditingActionEnum actionEnum, User user) {
log.debug("send service {} to dao for create", service.getComponentMetadataDefinition().getMetadataDataDefinition().getName());
Either<Boolean, ResponseFormat> lockResult = lockComponentByName(service.getSystemName(), service, "Create Service");
@@ -352,8 +355,13 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
createMandatoryArtifactsData(service, user);
createServiceApiArtifactsData(service, user);
setToscaArtifactsPlaceHolders(service, user);
+ Either<Resource, ResponseFormat> genericServiceEither = fetchAndSetDerivedFromGenericType(service);
+ if (genericServiceEither.isRight())
+ return Either.right(genericServiceEither.right().value());
- Either<Service, StorageOperationStatus> dataModelResponse = dataModel.createService(service);
+ generateInputsFromGenericTypeProperties(service, genericServiceEither.left().value());
+
+ Either<Service, StorageOperationStatus> dataModelResponse = toscaOperationFacade.createToscaComponent(service);
// service created successfully!!!
if (dataModelResponse.isLeft()) {
@@ -361,12 +369,6 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
componentsUtils.auditComponentAdmin(responseFormat, user, service, "", "", actionEnum, ComponentTypeEnum.SERVICE);
ASDCKpiApi.countCreatedServicesKPI();
-
- Service createdService = dataModelResponse.left().value();
- // //add service to cache
- // cacheManagerOperation.updateComponentInCache(createdService.getUniqueId(),
- // createdService.getLastUpdateDate(), NodeTypeEnum.Service);
-
return Either.left(dataModelResponse.left().value());
}
@@ -380,6 +382,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
}
}
+ @SuppressWarnings("unchecked")
private void createServiceApiArtifactsData(Service service, User user) {
// create mandatory artifacts
@@ -389,7 +392,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
// UniqueIdBuilder.buildServiceUniqueId(service.getComponentMetadataDefinition().getMetadataDataDefinition().getName(),
// service.getComponentMetadataDefinition().getMetadataDataDefinition().getVersion());
String serviceUniqueId = service.getUniqueId();
- Map<String, ArtifactDefinition> artifactMap = service.getArtifacts();
+ Map<String, ArtifactDefinition> artifactMap = service.getServiceApiArtifacts();
if (artifactMap == null)
artifactMap = new HashMap<String, ArtifactDefinition>();
@@ -417,7 +420,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
}
- service.setArtifacts(artifactMap);
+ service.setServiceApiArtifacts(artifactMap);
}
}
@@ -458,6 +461,8 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
return categoryValidation;
}
+ // validate project name (ProjectCode) - mandatory in service
+
log.debug("validate projectName");
Either<Boolean, ResponseFormat> projectCodeValidation = validateProjectCode(user, service, actionEnum);
if (projectCodeValidation.isRight()) {
@@ -494,7 +499,10 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
return Either.right(resp.right().value());
}
- Either<Boolean, StorageOperationStatus> dataModelResponse = serviceOperation.validateServiceNameExists(serviceName);
+ Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade.validateComponentNameUniqueness(serviceName, null, ComponentTypeEnum.SERVICE);
+
+ // DE242223
+ titanDao.commit();
if (dataModelResponse.isLeft()) {
Map<String, Boolean> result = new HashMap<>();
@@ -512,10 +520,6 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
this.elementDao = elementDao;
}
- public void setServiceOperation(ServiceOperation serviceOperation) {
- this.serviceOperation = serviceOperation;
- }
-
public void setCassandraAuditingDao(AuditCassandraDao auditingDao) {
this.auditCassandraDao = auditingDao;
}
@@ -549,15 +553,15 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
return Either.right(validateRes.right().value());
}
- Either<Service, StorageOperationStatus> storageStatus = serviceOperation.getService(serviceId);
+ Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(serviceId);
if (storageStatus.isRight()) {
return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), ""));
}
Service currentService = storageStatus.left().value();
- if (!ComponentValidationUtils.canWorkOnService(currentService.getUniqueId(), serviceOperation, user.getUserId())) {
- log.info("Restricted operation for user {} on service {}", user.getUserId(), currentService.getCreatorUserId());
+ if (!ComponentValidationUtils.canWorkOnComponent(currentService, user.getUserId())) {
+ log.info("Restricted operation for user: {}, on service: {}", user.getUserId(), currentService.getCreatorUserId());
return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
}
@@ -574,15 +578,14 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
return Either.right(lockResult.right().value());
}
try {
- Either<Service, StorageOperationStatus> updateResponse = serviceOperation.updateService(serviceToUpdate, true);
+ Either<Service, StorageOperationStatus> updateResponse = toscaOperationFacade.updateToscaElement(serviceToUpdate);
if (updateResponse.isRight()) {
- titanGenericDao.rollback();
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Update Service Metadata");
+ titanDao.rollback();
BeEcompErrorManager.getInstance().logBeSystemError("Update Service Metadata");
log.debug("failed to update sevice {}", serviceToUpdate.getUniqueId());
return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
}
- titanGenericDao.commit();
+ titanDao.commit();
return Either.left(updateResponse.left().value());
} finally {
graphLockOperation.unlockComponent(serviceId, NodeTypeEnum.Service);
@@ -619,7 +622,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
String lastUpdaterFullNameUpdated = serviceUpdate.getLastUpdaterFullName();
String lastUpdaterFullNameCurrent = currentService.getLastUpdaterFullName();
if (lastUpdaterFullNameUpdated != null && !lastUpdaterFullNameCurrent.equals(lastUpdaterFullNameUpdated)) {
- log.info("update srvice: recived request to update lastUpdaterFullName to {} the field is not updatable ignoring.", lastUpdaterFullNameUpdated );
+ log.info("update srvice: recived request to update lastUpdaterFullName to {} the field is not updatable ignoring.", lastUpdaterFullNameUpdated);
}
response = validateAndUpdateServiceName(user, currentService, serviceUpdate, hasBeenCertified, null);
@@ -709,10 +712,31 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
log.warn("Product invariant UUID is automatically set and cannot be updated");
serviceUpdate.setInvariantUUID(currentInvariantUuid);
}
+ validateAndUpdateEcompNaming(currentService, serviceUpdate);
+
return Either.left(currentService);
}
+ private void validateAndUpdateEcompNaming(Service currentService, Service serviceUpdate) {
+ Boolean isEcompoGeneratedCurr = currentService.isEcompGeneratedNaming();
+ Boolean isEcompoGeneratedUpdate = serviceUpdate.isEcompGeneratedNaming();
+ if (isEcompoGeneratedUpdate != null && isEcompoGeneratedCurr != isEcompoGeneratedUpdate) {
+ currentService.setEcompGeneratedNaming(isEcompoGeneratedUpdate);
+ }
+ String namingPolicyUpd = serviceUpdate.getNamingPolicy();
+ if (!currentService.isEcompGeneratedNaming()) {
+ if (ValidationUtils.validateStringNotEmpty(namingPolicyUpd)) {
+ log.warn("NamingPolicy must be empty for EcompGeneratedNaming=false");
+ currentService.setNamingPolicy("");
+ } else {
+ currentService.setNamingPolicy(namingPolicyUpd);
+ }
+ }else{
+ currentService.setNamingPolicy(namingPolicyUpd);
+ }
+ }
+
private Either<Boolean, ResponseFormat> validateAndUpdateContactId(User user, Service currentService, Service serviceUpdate, AuditingActionEnum audatingAction) {
String contactIdUpdated = serviceUpdate.getContactId();
String contactIdCurrent = currentService.getContactId();
@@ -765,12 +789,14 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
String projectCodeUpdated = serviceUpdate.getProjectCode();
String projectCodeCurrent = currentService.getProjectCode();
if (!projectCodeCurrent.equals(projectCodeUpdated)) {
+
Either<Boolean, ResponseFormat> validatProjectCodeResponse = validateProjectCode(user, serviceUpdate, audatingAction);
if (validatProjectCodeResponse.isRight()) {
ResponseFormat errorRespons = validatProjectCodeResponse.right().value();
return Either.right(errorRespons);
}
currentService.setProjectCode(projectCodeUpdated);
+
}
return Either.left(true);
}
@@ -892,7 +918,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
}
user = eitherCreator.left().value();
- Either<Service, StorageOperationStatus> serviceStatus = serviceOperation.getService(serviceId);
+ Either<Service, StorageOperationStatus> serviceStatus = toscaOperationFacade.getToscaElement(serviceId);
if (serviceStatus.isRight()) {
log.debug("failed to get service {}", serviceId);
return componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceStatus.right().value()), "");
@@ -922,10 +948,10 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
if (result == null || !result.equals(StorageOperationStatus.OK)) {
log.warn("operation failed. do rollback");
BeEcompErrorManager.getInstance().logBeSystemError("Delete Service");
- titanGenericDao.rollback();
+ titanDao.rollback();
} else {
log.debug("operation success. do commit");
- titanGenericDao.commit();
+ titanDao.commit();
}
graphLockOperation.unlockComponent(serviceId, NodeTypeEnum.Service);
}
@@ -972,10 +998,10 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
if (result == null || !result.equals(StorageOperationStatus.OK)) {
log.warn("operation failed. do rollback");
BeEcompErrorManager.getInstance().logBeSystemError("Delete Service");
- titanGenericDao.rollback();
+ titanDao.rollback();
} else {
log.debug("operation success. do commit");
- titanGenericDao.commit();
+ titanDao.commit();
}
graphLockOperation.unlockComponent(service.getUniqueId(), NodeTypeEnum.Service);
}
@@ -994,7 +1020,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
}
user = eitherCreator.left().value();
- Either<Service, StorageOperationStatus> storageStatus = serviceOperation.getService(serviceId);
+ Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(serviceId);
if (storageStatus.isRight()) {
log.debug("failed to get service by id {}", serviceId);
return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), serviceId));
@@ -1010,7 +1036,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
if (resp.isRight()) {
return Either.right(resp.right().value());
}
- Either<Service, StorageOperationStatus> storageStatus = serviceOperation.getServiceByNameAndVersion(serviceName, serviceVersion, null, false);
+ Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.SERVICE, serviceName, serviceVersion);
if (storageStatus.isRight()) {
log.debug("failed to get service by name {} and version {}", serviceName, serviceVersion);
return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), serviceName));
@@ -1019,6 +1045,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
return Either.left(service);
}
+ @SuppressWarnings("unchecked")
private void createMandatoryArtifactsData(Service service, User user) {
// create mandatory artifacts
@@ -1076,7 +1103,6 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
transitionEnum = DistributionTransitionEnum.getFromDisplayName(distributionTransition);
if (transitionEnum == null) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Change Service Distribution");
BeEcompErrorManager.getInstance().logBeSystemError("Change Service Distribution");
log.info("state operation is not valid. operations allowed are: {}", DistributionTransitionEnum.valuesAsString());
ResponseFormat error = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
@@ -1090,7 +1116,6 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
String data = comment.getUserRemarks();
if (data == null || data.trim().isEmpty()) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeInvalidJsonInput, "Change Service Distribution");
BeEcompErrorManager.getInstance().logBeInvalidJsonInput("Change Service Distribution");
log.debug("user comment cannot be empty or null.");
return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
@@ -1101,7 +1126,6 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
data = ValidationUtils.stripOctets(data);
if (!ValidationUtils.validateLength(data, ValidationUtils.COMMENT_MAX_LENGTH)) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeInvalidJsonInput, "Change Service Distribution");
BeEcompErrorManager.getInstance().logBeInvalidJsonInput("Change Service Distribution");
log.debug("user comment exceeds limit.");
return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, "comment", String.valueOf(ValidationUtils.COMMENT_MAX_LENGTH)));
@@ -1113,7 +1137,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
}
private Either<Service, ResponseFormat> validateServiceDistributionChange(User user, String serviceId, AuditingActionEnum auditAction, String comment) {
- Either<Service, StorageOperationStatus> storageStatus = serviceOperation.getService(serviceId);
+ Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(serviceId);
if (storageStatus.isRight()) {
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_FOUND, serviceId);
createAudit(user, auditAction, comment, responseFormat);
@@ -1132,13 +1156,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
private Either<User, ResponseFormat> validateUserDistributionChange(User user, Service service, AuditingActionEnum auditAction, String comment) {
log.debug("get user from DB");
- /*
- * Either<User, ActionStatus> eitherCreator = userAdmin.getUser(user.getUserId());s if (eitherCreator.isRight() || eitherCreator.left().value() == null) { BeEcompErrorManager.getInstance().processEcompError(EcompErrorName. BeUserMissingError,
- * "Activate Distribution", user.getUserId()); log. debug("changeServiceDistributionState method - user is not listed. userId=" + user.getUserId()); ResponseFormat responseFormat =
- * componentsUtils.getResponseFormat(ActionStatus.USER_NOT_FOUND); createAudit(user, auditAction, comment, responseFormat); return Either.right(responseFormat); } user = eitherCreator.left().value(); log.debug("validate user role"); if
- * (!validateUserTemp(user, Role.ADMIN, Role.GOVERNOR)) { log.info("role {} is not allowed to perform this action", user.getRole()); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
- * createAudit(user, auditAction, comment, service, responseFormat); return Either.right(responseFormat); }
- */
+
// get user details
Either<User, ResponseFormat> eitherCreator = validateUser(user, "Activate Distribution", service, auditAction, false);
if (eitherCreator.isRight()) {
@@ -1150,6 +1168,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
List<Role> roles = new ArrayList<>();
roles.add(Role.ADMIN);
roles.add(Role.GOVERNOR);
+ roles.add(Role.OPS);
Either<Boolean, ResponseFormat> validateRes = validateUserRole(user, service, roles, auditAction, comment);
if (validateRes.isRight()) {
return Either.right(validateRes.right().value());
@@ -1208,14 +1227,13 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
ServletContext servletContext = request.getSession().getServletContext();
boolean isDistributionEngineUp = getHealthCheckBL(servletContext).isDistributionEngineUp(request.getSession().getServletContext()); // DE
if (!isDistributionEngineUp) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Distribution Engine is DOWN");
BeEcompErrorManager.getInstance().logBeSystemError("Distribution Engine is DOWN");
log.debug("Distribution Engine is DOWN");
response = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
return Either.right(response);
}
- Either<Service, StorageOperationStatus> serviceRes = serviceOperation.getService(serviceId);
+ Either<Service, StorageOperationStatus> serviceRes = toscaOperationFacade.getToscaElement(serviceId);
if (serviceRes.isRight()) {
log.debug("failed retrieving service");
response = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceRes.right().value(), ComponentTypeEnum.SERVICE), serviceId);
@@ -1243,7 +1261,6 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
response = componentsUtils.getResponseFormat(ActionStatus.OK);
result = Either.left(updatedService);
} else {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Activate Distribution - send notification");
BeEcompErrorManager.getInstance().logBeSystemError("Activate Distribution - send notification");
log.debug("distributionEngine.notifyService response is: {}", notifyServiceResponse);
response = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
@@ -1273,15 +1290,14 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
return Either.right(lockResult.right().value());
}
try {
- Either<Service, StorageOperationStatus> result = serviceOperation.updateDestributionStatus(service, user, state);
+ Either<Service, StorageOperationStatus> result = toscaOperationFacade.updateDistributionStatus(service, user, state);
if (result.isRight()) {
- titanGenericDao.rollback();
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "updateDistributionStatusForActivation");
+ titanDao.rollback();
BeEcompErrorManager.getInstance().logBeSystemError("updateDistributionStatusForActivation");
log.debug("service {} change distribution status failed", serviceId);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
}
- titanGenericDao.commit();
+ titanDao.commit();
return Either.left(result.left().value());
} finally {
graphLockOperation.unlockComponent(serviceId, NodeTypeEnum.Service);
@@ -1298,9 +1314,8 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
log.debug("mark distribution deployed");
AuditingActionEnum auditAction = AuditingActionEnum.DISTRIBUTION_DEPLOY;
- Either<Service, StorageOperationStatus> getServiceResponse = serviceOperation.getService(serviceId);
+ Either<Service, StorageOperationStatus> getServiceResponse = toscaOperationFacade.getToscaElement(serviceId);
if (getServiceResponse.isRight()) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeServiceMissingError, "markDistributionAsDeployed", serviceId);
BeEcompErrorManager.getInstance().logBeComponentMissingError("markDistributionAsDeployed", ComponentTypeEnum.SERVICE.getValue(), serviceId);
log.debug("service {} not found", serviceId);
ResponseFormat responseFormat = auditDeployError(did, user, auditAction, null, componentsUtils.convertFromStorageResponse(getServiceResponse.right().value(), ComponentTypeEnum.SERVICE), "");
@@ -1323,36 +1338,35 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
public Either<Service, ResponseFormat> generateVfModuleArtifacts(Service service, User modifier, boolean shouldLock) {
Function<ComponentInstance, List<ArtifactGenerator<ArtifactDefinition>>> artifactTaskGeneratorCreator = ri ->
// Only one VF Module Artifact per instance - add it to a list of one
- Arrays.asList(new VfModuleArtifacGenerator(modifier, ri, service, shouldLock));
+ buildArtifactGenList(service, modifier, shouldLock, ri);
return generateDeploymentArtifacts(service, modifier, artifactTaskGeneratorCreator);
}
- private List<GroupDefinition> collectGroupsForCompInstance(ComponentInstance currVF, Wrapper<ResponseFormat> responseWrapper) {
- List<GroupDefinition> relevantGroups = new ArrayList<>();
- Either<List<GroupDefinition>, StorageOperationStatus> eitherGroups = groupOperation.getAllGroups(currVF.getComponentUid(), NodeTypeEnum.Resource);
-
- if (eitherGroups.isRight()) {
- final StorageOperationStatus storageStatus = eitherGroups.right().value();
- if (storageStatus != StorageOperationStatus.NOT_FOUND && storageStatus != StorageOperationStatus.OK) {
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageStatus);
- responseWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus));
- }
+ private List<ArtifactGenerator<ArtifactDefinition>> buildArtifactGenList(Service service, User modifier, boolean shouldLock, ComponentInstance ri) {
+ List<ArtifactGenerator<ArtifactDefinition>> asList = new ArrayList<ArtifactGenerator<ArtifactDefinition>>();
- } else {
- relevantGroups = eitherGroups.left().value().stream().filter(p -> GroupTypeEnum.VF_MODULE.getGroupTypeName().equals(p.getType())).collect(Collectors.toList());
+ if (ri.getOriginType() == OriginTypeEnum.VF) {
+ asList = Arrays.asList(new VfModuleArtifacGenerator(modifier, ri, service, shouldLock));
}
- return relevantGroups;
+ return asList;
}
- private ArtifactDefinition getVfModuleArtifactForCompInstance(ComponentInstance currVF, Service service, User modifier, List<GroupDefinition> groupsForCurrVF, Wrapper<String> payloadWrapper, Wrapper<ResponseFormat> responseWrapper) {
- ArtifactDefinition vfModuleAertifact = null;
+ private List<GroupInstance> collectGroupsInstanceForCompInstance(ComponentInstance currVF, Wrapper<ResponseFormat> responseWrapper) {
- Optional<ArtifactDefinition> optionalVfModuleArtifact = currVF.getDeploymentArtifacts().values().stream().filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.VF_MODULES_METADATA.name())).findAny();
- if (optionalVfModuleArtifact.isPresent()) {
- vfModuleAertifact = optionalVfModuleArtifact.get();
- } else {
+ return currVF.getGroupInstances();
+ }
+
+ private ArtifactDefinition getVfModuleInstArtifactForCompInstance(ComponentInstance currVF, Service service, User modifier, List<GroupInstance> groupsForCurrVF, Wrapper<String> payloadWrapper, Wrapper<ResponseFormat> responseWrapper) {
+ ArtifactDefinition vfModuleAertifact = null;
+ if (MapUtils.isNotEmpty(currVF.getDeploymentArtifacts())) {
+ Optional<ArtifactDefinition> optionalVfModuleArtifact = currVF.getDeploymentArtifacts().values().stream().filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.VF_MODULES_METADATA.name())).findAny();
+ if (optionalVfModuleArtifact.isPresent()) {
+ vfModuleAertifact = optionalVfModuleArtifact.get();
+ }
+ }
+ if (vfModuleAertifact == null) {
Either<ArtifactDefinition, ResponseFormat> createVfModuleArtifact = createVfModuleArtifact(modifier, currVF, service, payloadWrapper.getInnerElement());
if (createVfModuleArtifact.isLeft()) {
vfModuleAertifact = createVfModuleArtifact.left().value();
@@ -1363,19 +1377,26 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
return vfModuleAertifact;
}
- private void fillVfModuleHeatEnvPayload(List<GroupDefinition> groupsForCurrVF, ComponentInstance currVFInstance, Wrapper<String> payloadWrapper) {
+ private void fillVfModuleInstHeatEnvPayload(List<GroupInstance> groupsForCurrVF, ComponentInstance currVFInstance, Wrapper<String> payloadWrapper) {
// Converts GroupDefinition to VfModuleArtifactPayload which is the
// format used in the payload
- List<VfModuleArtifactPayload> vfModulePayloadForCurrVF = groupsForCurrVF.stream().map(group -> new VfModuleArtifactPayload(group)).collect(Collectors.toList());
- Collections.sort(vfModulePayloadForCurrVF, (art1, art2) -> VfModuleArtifactPayload.compareByGroupName(art1, art2));
- // Update Payload With Heat Env
- vfModulePayloadForCurrVF.stream().forEach(e -> addHeatEnvArtifactsToVFModulePayload(e, currVFInstance));
+ // List<VfModuleArtifactPayload> vfModulePayloadForCurrVF = groupsForCurrVF.stream().map(group -> new VfModuleArtifactPayload(group)).collect(Collectors.toList());
+ List<VfModuleArtifactPayload> vfModulePayloadForCurrVF = new ArrayList<VfModuleArtifactPayload>();
+ if (groupsForCurrVF != null) {
+ for (GroupInstance groupInstance : groupsForCurrVF) {
+ VfModuleArtifactPayload modulePayload = new VfModuleArtifactPayload(groupInstance);
+ vfModulePayloadForCurrVF.add(modulePayload);
+ }
+ Collections.sort(vfModulePayloadForCurrVF, (art1, art2) -> VfModuleArtifactPayload.compareByGroupName(art1, art2));
+ // Update Payload With Heat Env
+ vfModulePayloadForCurrVF.stream().forEach(e -> addHeatEnvArtifactsToVFModulePayload(e, currVFInstance));
- final Gson gson = new GsonBuilder().setPrettyPrinting().create();
+ final Gson gson = new GsonBuilder().setPrettyPrinting().create();
- String vfModulePayloadString = gson.toJson(vfModulePayloadForCurrVF);
- payloadWrapper.setInnerElement(vfModulePayloadString);
+ String vfModulePayloadString = gson.toJson(vfModulePayloadForCurrVF);
+ payloadWrapper.setInnerElement(vfModulePayloadString);
+ }
}
@@ -1383,6 +1404,9 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
List<String> originalModuleArtifacts = vfModulePayload.getArtifacts();
if (!MapUtils.isEmpty(currVFInstance.getDeploymentArtifacts()) && !CollectionUtils.isEmpty(originalModuleArtifacts)) {
+ // EVG : fix now for patch. remove null from list. Need to be fixed later : remove VF HEAT ENV uuid from the list??
+ List<String> filteredUUIDFromModule = originalModuleArtifacts.stream().filter(uuid -> uuid != null).collect(Collectors.toList());
+
final Collection<ArtifactDefinition> depInsArtifacts = currVFInstance.getDeploymentArtifacts().values();
// All Heat_ENV
List<ArtifactDefinition> heatEnvArtifacts = depInsArtifacts.stream().filter(art -> art.getArtifactType().equals(ArtifactTypeEnum.HEAT_ENV.getType())).collect(Collectors.toList());
@@ -1393,23 +1417,23 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
List<String> relevantHeatEnvUUID = heatEnvArtifacts.stream().filter(heatEnv -> moduleArtUniqueId.contains(heatEnv.getGeneratedFromId())).map(heatEnv -> heatEnv.getArtifactUUID()).collect(Collectors.toList());
List<String> fullArtifactList = new ArrayList<>();
- fullArtifactList.addAll(originalModuleArtifacts);
+ fullArtifactList.addAll(filteredUUIDFromModule);
fullArtifactList.addAll(relevantHeatEnvUUID);
vfModulePayload.setArtifacts(fullArtifactList);
}
}
- private Either<ArtifactDefinition, ResponseFormat> generateVfModuleArtifact(User modifier, ComponentInstance currVFInstance, Service service, boolean shouldLock) {
+ private Either<ArtifactDefinition, ResponseFormat> generateVfModuleInstanceArtifact(User modifier, ComponentInstance currVFInstance, Service service, boolean shouldLock) {
ArtifactDefinition vfModuleAertifact = null;
Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
Wrapper<String> payloadWrapper = new Wrapper<>();
- List<GroupDefinition> groupsForCurrVF = collectGroupsForCompInstance(currVFInstance, responseWrapper);
+ List<GroupInstance> groupsForCurrVF = collectGroupsInstanceForCompInstance(currVFInstance, responseWrapper);
if (responseWrapper.isEmpty()) {
- fillVfModuleHeatEnvPayload(groupsForCurrVF, currVFInstance, payloadWrapper);
+ fillVfModuleInstHeatEnvPayload(groupsForCurrVF, currVFInstance, payloadWrapper);
}
- if (responseWrapper.isEmpty()) {
- vfModuleAertifact = getVfModuleArtifactForCompInstance(currVFInstance, service, modifier, groupsForCurrVF, payloadWrapper, responseWrapper);
+ if (responseWrapper.isEmpty() && payloadWrapper.getInnerElement() != null) {
+ vfModuleAertifact = getVfModuleInstArtifactForCompInstance(currVFInstance, service, modifier, groupsForCurrVF, payloadWrapper, responseWrapper);
}
if (responseWrapper.isEmpty() && vfModuleAertifact != null) {
vfModuleAertifact = fillVfModulePayload(modifier, currVFInstance, vfModuleAertifact, shouldLock, payloadWrapper, responseWrapper);
@@ -1425,21 +1449,24 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
return result;
}
- private ArtifactDefinition fillVfModulePayload(User modifier, ComponentInstance currVF, ArtifactDefinition vfModuleAertifact, boolean shouldLock, Wrapper<String> payloadWrapper, Wrapper<ResponseFormat> responseWrapper) {
+ private ArtifactDefinition fillVfModulePayload(User modifier, ComponentInstance currVF, ArtifactDefinition vfModuleArtifact, boolean shouldLock, Wrapper<String> payloadWrapper, Wrapper<ResponseFormat> responseWrapper) {
ArtifactDefinition result = null;
- final Either<Resource, StorageOperationStatus> eitherResource = resourceOperation.getResource(currVF.getComponentUid());
+ final Either<Resource, StorageOperationStatus> eitherResource = toscaOperationFacade.getToscaElement(currVF.getComponentUid());
if (eitherResource.isRight()) {
responseWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(eitherResource.right().value())));
- } else {
+ } else if (!payloadWrapper.isEmpty()) {
Resource resource = eitherResource.left().value();
- Either<ArtifactDefinition, ResponseFormat> eitherPayload = artifactsBusinessLogic.generateArtifactPayload(vfModuleAertifact, resource, currVF.getName(), modifier, shouldLock, () -> System.currentTimeMillis(),
- () -> Either.left(artifactsBusinessLogic.createEsArtifactData(vfModuleAertifact, payloadWrapper.getInnerElement().getBytes(StandardCharsets.UTF_8))));
+ Either<ArtifactDefinition, ResponseFormat> eitherPayload = artifactsBusinessLogic.generateArtifactPayload(vfModuleArtifact, resource.getComponentType(), resource, currVF.getName(), modifier, shouldLock, () -> System.currentTimeMillis(),
+ () -> Either.left(artifactsBusinessLogic.createEsArtifactData(vfModuleArtifact, payloadWrapper.getInnerElement().getBytes(StandardCharsets.UTF_8))), currVF.getUniqueId());
if (eitherPayload.isLeft()) {
result = eitherPayload.left().value();
} else {
responseWrapper.setInnerElement(eitherPayload.right().value());
}
}
+ if (result == null) {
+ result = vfModuleArtifact;
+ }
return result;
}
@@ -1447,6 +1474,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
private Either<ArtifactDefinition, ResponseFormat> createVfModuleArtifact(User modifier, ComponentInstance currVF, Service service, String vfModulePayloadString) {
ArtifactDefinition vfModuleArtifactDefinition = new ArtifactDefinition();
+ String newCheckSum = null;
vfModuleArtifactDefinition.setDescription("Auto-generated VF Modules information artifact");
vfModuleArtifactDefinition.setArtifactDisplayName("Vf Modules Metadata");
@@ -1456,8 +1484,12 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
vfModuleArtifactDefinition.setTimeout(0);
vfModuleArtifactDefinition.setArtifactName(currVF.getNormalizedName() + "_modules.json");
vfModuleArtifactDefinition.setPayloadData(vfModulePayloadString);
+ if (vfModulePayloadString != null) {
+ newCheckSum = GeneralUtility.calculateMD5ByByteArray(vfModulePayloadString.getBytes());
+ }
+ vfModuleArtifactDefinition.setArtifactChecksum(newCheckSum);
- Either<ArtifactDefinition, StorageOperationStatus> addArifactToComponent = artifactOperation.addArifactToComponent(vfModuleArtifactDefinition, currVF.getUniqueId(), NodeTypeEnum.ResourceInstance, true, true);
+ Either<ArtifactDefinition, StorageOperationStatus> addArifactToComponent = artifactToscaOperation.addArifactToComponent(vfModuleArtifactDefinition, service.getUniqueId(), NodeTypeEnum.ResourceInstance, true, currVF.getUniqueId());
Either<ArtifactDefinition, ResponseFormat> result;
if (addArifactToComponent.isLeft()) {
@@ -1477,7 +1509,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
// Filter in Only Heat Env
filter(depArtifact -> ArtifactTypeEnum.HEAT_ENV.getType().equals(depArtifact.getArtifactType())).
// Create ArtifactGenerator from those Artifacts
- map(depArtifact -> new HeatEnvArtifactGenerator(depArtifact, service, resourceInstance.getName(), modifier, shouldLock)).collect(Collectors.toList());
+ map(depArtifact -> new HeatEnvArtifactGenerator(depArtifact, service, resourceInstance.getName(), modifier, shouldLock, resourceInstance.getUniqueId())).collect(Collectors.toList());
return generateDeploymentArtifacts(service, modifier, artifactTaskGeneratorCreator);
@@ -1485,41 +1517,25 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
private <CallVal> Either<Service, ResponseFormat> generateDeploymentArtifacts(Service service, User modifier, Function<ComponentInstance, List<ArtifactGenerator<CallVal>>> artifactTaskGeneratorCreator) {
- List<Future<Either<CallVal, ResponseFormat>>> allFutures = new ArrayList<>();
-
// Get Flat List of (Callable) ArtifactGenerator for all the RI in the
// service
if (service.getComponentInstances() != null) {
List<ArtifactGenerator<CallVal>> artifactGenList = service.getComponentInstances().stream().flatMap(ri -> artifactTaskGeneratorCreator.apply(ri).stream()).collect(Collectors.toList());
if (artifactGenList != null && !artifactGenList.isEmpty()) {
- ExecutorService executor = Executors.newFixedThreadPool(artifactGenList.size());
-
- artifactGenList.stream().forEach(e -> allFutures.add(executor.submit(e)));
-
- boolean isSuccess = true;
- ResponseFormat firstError = null;
- for (Future<Either<CallVal, ResponseFormat>> entry : allFutures) {
+ for (ArtifactGenerator<CallVal> entry : artifactGenList) {
+ Either<CallVal, ResponseFormat> callRes;
try {
- Either<CallVal, ResponseFormat> actionStatus = entry.get(20, TimeUnit.SECONDS);
- if (actionStatus.isRight()) {
- isSuccess = false;
- if (firstError == null) {
- firstError = actionStatus.right().value();
- }
- log.debug("Failed to generate artifact error : {}", actionStatus.right().value());
+ callRes = entry.call();
+ if (callRes.isRight()) {
+ log.debug("Failed to generate artifact error : {}", callRes.right().value());
+ return Either.right(callRes.right().value());
}
} catch (Exception e) {
- log.debug("Failed to collect result from artifact generator ", e);
- isSuccess = false;
- firstError = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
+ log.debug("Failed to generate artifact exception : {}", e);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
}
}
- executor.shutdown();
- if (!isSuccess) {
- return Either.right(firstError);
- }
}
-
}
return Either.left(service);
}
@@ -1533,19 +1549,21 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
Service service;
String resourceInstanceName;
User modifier;
+ String instanceId;
boolean shouldLock;
- HeatEnvArtifactGenerator(ArtifactDefinition artifactDefinition, Service service, String resourceInstanceName, User modifier, boolean shouldLock) {
+ HeatEnvArtifactGenerator(ArtifactDefinition artifactDefinition, Service service, String resourceInstanceName, User modifier, boolean shouldLock, String instanceId) {
this.artifactDefinition = artifactDefinition;
this.service = service;
this.resourceInstanceName = resourceInstanceName;
this.modifier = modifier;
this.shouldLock = shouldLock;
+ this.instanceId = instanceId;
}
@Override
public Either<ArtifactDefinition, ResponseFormat> call() throws Exception {
- return artifactsBusinessLogic.generateHeatEnvArtifact(artifactDefinition, service, resourceInstanceName, modifier, shouldLock);
+ return artifactsBusinessLogic.generateHeatEnvArtifact(artifactDefinition, ComponentTypeEnum.RESOURCE_INSTANCE, service, resourceInstanceName, modifier, shouldLock, instanceId);
}
public ArtifactDefinition getArtifactDefinition() {
@@ -1562,7 +1580,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
@Override
public Either<ArtifactDefinition, ResponseFormat> call() throws Exception {
- return generateVfModuleArtifact(user, componentInstance, service, shouldLock);
+ return generateVfModuleInstanceArtifact(user, componentInstance, service, shouldLock);// generateVfModuleArtifact(user, componentInstance, service, shouldLock);
}
private VfModuleArtifacGenerator(User user, ComponentInstance componentInstance, Service service, boolean shouldLock) {
@@ -1618,7 +1636,6 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
List<ResourceAdminEvent> distributionRequests = distRequestsResponse.left().value();
if (distributionRequests.isEmpty()) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDistributionMissingError, "markDistributionAsDeployed", did);
BeEcompErrorManager.getInstance().logBeDistributionMissingError("markDistributionAsDeployed", did);
log.info("distribution {} is not found", did);
ResponseFormat error = auditDeployError(did, user, auditAction, service, ActionStatus.DISTRIBUTION_REQUESTED_NOT_FOUND);
@@ -1686,9 +1703,8 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
private Either<User, ResponseFormat> validateRoleForDeploy(String did, User user, AuditingActionEnum auditAction, Service service) {
Either<User, ActionStatus> eitherCreator = userAdmin.getUser(user.getUserId(), false);
if (eitherCreator.isRight() || eitherCreator.left().value() == null) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeUserMissingError, "Deploy Service", user.getUserId());
BeEcompErrorManager.getInstance().logBeUserMissingError("Deploy Service", user.getUserId());
- log.debug("validateRoleForDeploy method - user is not listed. userId={}", user.getUserId());
+ log.debug("validateRoleForDeploy method - user is not listed. userId= {}", user.getUserId());
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.USER_NOT_FOUND, user.getUserId());
auditDeployError(did, user, auditAction, service, ActionStatus.USER_NOT_FOUND);
return Either.right(responseFormat);
@@ -1711,7 +1727,6 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
@Override
public void setDeploymentArtifactsPlaceHolder(Component component, User user) {
- // TODO Auto-generated method stub
}
@@ -1739,21 +1754,14 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
if (resp.isRight()) {
return Either.right(resp.right().value());
}
-
- ComponentOperation componentOperation = getComponentOperation(componentTypeEnum);
-
- Either<List<ComponentInstance>, StorageOperationStatus> componentInstancesResponse = componentOperation.getAllComponentInstncesMetadata(componentId, componentTypeEnum.getNodeType());
- if (componentInstancesResponse.isRight()) {
-
- if (componentInstancesResponse.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
- return Either.left(new ArrayList<ComponentInstance>());
- }
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(componentInstancesResponse.right().value()));
+ Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
+ if (getComponentRes.isRight()) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getComponentRes.right().value()));
return Either.right(responseFormat);
}
- List<ComponentInstance> componentInstances = componentInstancesResponse.left().value();
- componentInstances = componentInstances.stream().filter(instance -> instance.getOriginType().equals(OriginTypeEnum.VF)).collect(Collectors.toList());
+ List<ComponentInstance> componentInstances = getComponentRes.left().value().getComponentInstances();
+ // componentInstances = componentInstances.stream().filter(instance -> instance.getOriginType().equals(OriginTypeEnum.VF)).collect(Collectors.toList());
return Either.left(componentInstances);
}
@@ -1765,4 +1773,207 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
public void setCacheManagerOperation(ICacheMangerOperation cacheManagerOperation) {
this.cacheManagerOperation = cacheManagerOperation;
}
+
+ /**
+ * updates group instance with new property values in case of successful update of group instance related component instance will be updated with new modification time and related service will be updated with new last update date
+ *
+ * @param modifier
+ * @param serviceId
+ * @param componentInstanceId
+ * @param groupInstanceId
+ * @param newProperties
+ * @return
+ */
+ public Either<List<GroupInstanceProperty>, ResponseFormat> updateGroupInstancePropertyValues(User modifier, String serviceId, String componentInstanceId, String groupInstanceId, List<GroupInstanceProperty> newProperties) {
+
+ Either<List<GroupInstanceProperty>, ResponseFormat> actionResult = null;
+ Either<ImmutablePair<Component, User>, ResponseFormat> validateUserAndComponentRes;
+ Component component = null;
+ Either<Boolean, ResponseFormat> lockResult = null;
+ log.debug("Going to update group instance {} of service {} with new property values. ", groupInstanceId, serviceId);
+ try {
+ validateUserAndComponentRes = validateUserAndComponent(serviceId, modifier);
+ if (validateUserAndComponentRes.isRight()) {
+ log.debug("Cannot update group instance {} of service {} with new property values. Validation failed. ", groupInstanceId, serviceId);
+ actionResult = Either.right(validateUserAndComponentRes.right().value());
+ }
+ if (actionResult == null) {
+ component = validateUserAndComponentRes.left().value().getKey();
+ lockResult = lockComponentByName(component.getSystemName(), component, "Update Group Instance on Service");
+ if (lockResult.isRight()) {
+ log.debug("Failed to lock service {}. Response is {}. ", component.getName(), lockResult.right().value().getFormattedMessage());
+ actionResult = Either.right(lockResult.right().value());
+ } else {
+ log.debug("The service with system name {} locked. ", component.getSystemName());
+ }
+ }
+ if (actionResult == null) {
+ actionResult = validateAndUpdateGroupInstancePropertyValuesAndContainingParents(component, componentInstanceId, groupInstanceId, newProperties);
+ if (actionResult.isRight()) {
+ log.debug("Failed to validate and update group instance {} property values and containing parents. The message is {}. ", groupInstanceId, actionResult.right().value().getFormattedMessage());
+ }
+ }
+ } catch (Exception e) {
+ log.error("Exception occured during update Group Instance property values: {}", e.getMessage(), e);
+ actionResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ } finally {
+ if (lockResult != null && lockResult.isLeft() && lockResult.left().value()) {
+ graphLockOperation.unlockComponentByName(component.getSystemName(), component.getUniqueId(), NodeTypeEnum.Service);
+ }
+ }
+ return actionResult;
+ }
+
+ private Either<List<GroupInstanceProperty>, ResponseFormat> validateAndUpdateGroupInstancePropertyValuesAndContainingParents(Component component, String componentInstanceId, String groupInstanceId, List<GroupInstanceProperty> newProperties) {
+
+ Either<List<GroupInstanceProperty>, ResponseFormat> actionResult = null;
+ Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat> findGroupInstanceRes;
+ Either<ImmutablePair<ComponentMetadataData, ComponentInstanceData>, ResponseFormat> updateParentsModificationTimeRes;
+ ComponentInstance relatedComponentInstance = null;
+ GroupInstance oldGroupInstance = null;
+ Either<GroupInstance, ResponseFormat> updateGroupInstanceResult = null;
+ GroupInstance updatedGroupInstance = null;
+ boolean inTransaction = true;
+ boolean shouldCloseTransaction = true;
+ findGroupInstanceRes = findGroupInstanceOnRelatedComponentInstance(component, componentInstanceId, groupInstanceId);
+ if (findGroupInstanceRes.isRight()) {
+ log.debug("Group instance {} not found. ", groupInstanceId);
+ actionResult = Either.right(findGroupInstanceRes.right().value());
+ }
+ if (actionResult == null) {
+ oldGroupInstance = findGroupInstanceRes.left().value().getValue();
+ relatedComponentInstance = findGroupInstanceRes.left().value().getKey();
+ updateGroupInstanceResult = groupBusinessLogic.validateAndUpdateGroupInstancePropertyValues(component.getUniqueId(), componentInstanceId, oldGroupInstance, newProperties, inTransaction);
+ if (updateGroupInstanceResult.isRight()) {
+ log.debug("Failed to update group instance {} property values. ", oldGroupInstance.getName());
+ actionResult = Either.right(updateGroupInstanceResult.right().value());
+ }
+ }
+ if (actionResult == null) {
+ updatedGroupInstance = updateGroupInstanceResult.left().value();
+ if (!oldGroupInstance.getModificationTime().equals(updatedGroupInstance.getModificationTime())) {
+ updateParentsModificationTimeRes = updateParentsModificationTimeAndCustomizationUuid(component, relatedComponentInstance, updatedGroupInstance, inTransaction, shouldCloseTransaction);
+ if (updateParentsModificationTimeRes.isRight()) {
+ log.debug("Failed to update modification time. ", oldGroupInstance.getName());
+ actionResult = Either.right(updateParentsModificationTimeRes.right().value());
+ }
+ }
+ }
+ if (actionResult == null) {
+ actionResult = Either.left(updatedGroupInstance.convertToGroupInstancesProperties());
+ }
+ return actionResult;
+ }
+
+ private Either<ImmutablePair<ComponentMetadataData, ComponentInstanceData>, ResponseFormat> updateParentsModificationTimeAndCustomizationUuid(Component component, ComponentInstance relatedComponentInstance, GroupInstance updatedGroupInstance,
+ boolean inTranscation, boolean shouldCloseTransaction) {
+
+ Either<ImmutablePair<ComponentMetadataData, ComponentInstanceData>, ResponseFormat> actionResult;
+ Either<ComponentMetadataData, StorageOperationStatus> serviceMetadataUpdateResult;
+ Either<ComponentInstanceData, ResponseFormat> updateComponentInstanceRes = serviceComponentInstanceBusinessLogic.updateComponentInstanceModificationTimeAndCustomizationUuid(relatedComponentInstance, NodeTypeEnum.ResourceInstance,
+ updatedGroupInstance.getModificationTime(), inTranscation);
+ if (updateComponentInstanceRes.isRight()) {
+ log.debug("Failed to update component instance {} after update of group instance {}. ", relatedComponentInstance.getName(), updatedGroupInstance.getName());
+ actionResult = Either.right(updateComponentInstanceRes.right().value());
+ } else {
+ serviceMetadataUpdateResult = toscaOperationFacade.updateComponentLastUpdateDateOnGraph(component, updatedGroupInstance.getModificationTime());
+ if (serviceMetadataUpdateResult.isRight()) {
+ log.debug("Failed to update service {} after update of component instance {} with new property values of group instance {}. ", component.getName(), relatedComponentInstance.getName(), updatedGroupInstance.getName());
+ actionResult = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceMetadataUpdateResult.right().value())));
+ } else {
+ actionResult = Either.left(new ImmutablePair<>(serviceMetadataUpdateResult.left().value(), updateComponentInstanceRes.left().value()));
+ }
+ }
+ return actionResult;
+ }
+
+ private Either<ImmutablePair<Component, User>, ResponseFormat> validateUserAndComponent(String serviceId, User modifier) {
+
+ Either<ImmutablePair<Component, User>, ResponseFormat> result = null;
+ Either<Component, ResponseFormat> validateComponentExistsRes = null;
+ User currUser = null;
+ Component component = null;
+ Either<User, ResponseFormat> validationUserResult = validateUserIgnoreAudit(modifier, "updateGroupInstancePropertyValues");
+ if (validationUserResult.isRight()) {
+ log.debug("Failed to validate user with userId for update service {}. ", modifier.getUserId(), serviceId);
+ result = Either.right(validationUserResult.right().value());
+ }
+ if (result == null) {
+ currUser = validationUserResult.left().value();
+ validateComponentExistsRes = validateComponentExists(serviceId, ComponentTypeEnum.SERVICE, null);
+ if (validateComponentExistsRes.isRight()) {
+ log.debug("Failed to validate service existing {}. ", serviceId);
+ result = Either.right(validateComponentExistsRes.right().value());
+ }
+ }
+ if (result == null) {
+ component = validateComponentExistsRes.left().value();
+ if (!ComponentValidationUtils.canWorkOnComponent(component, currUser.getUserId())) {
+ log.info("Restricted operation for user: {}, on service: {}", currUser.getUserId(), component.getCreatorUserId());
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
+ }
+ }
+ if (result == null) {
+ result = Either.left(new ImmutablePair<>(component, currUser));
+ }
+ return result;
+ }
+
+ private Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat> findGroupInstanceOnRelatedComponentInstance(Component component, String componentInstanceId, String groupInstanceId) {
+
+ Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat> actionResult = null;
+ GroupInstance groupInstance = null;
+ ComponentInstance foundComponentInstance = findRelatedComponentInstance(component, componentInstanceId);
+ if (foundComponentInstance == null) {
+ log.debug("Component instance {} not found on service {}. ", componentInstanceId, component.getName());
+ actionResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstanceId, "resource instance", "service", component.getName()));
+ } else if (!CollectionUtils.isEmpty(foundComponentInstance.getGroupInstances())) {
+ groupInstance = foundComponentInstance.getGroupInstances().stream().filter(gi -> gi.getUniqueId().equals(groupInstanceId)).findFirst().orElse(null);
+ if (groupInstance == null) {
+ log.debug("Group instance {} not found on component instance {}. ", groupInstanceId, foundComponentInstance.getName());
+ actionResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_INSTANCE_NOT_FOUND_ON_COMPONENT_INSTANCE, groupInstanceId, foundComponentInstance.getName()));
+ }
+ }
+ if (actionResult == null) {
+ actionResult = Either.left(new ImmutablePair<>(foundComponentInstance, groupInstance));
+ }
+ return actionResult;
+ }
+
+ private ComponentInstance findRelatedComponentInstance(Component component, String componentInstanceId) {
+ ComponentInstance componentInstance = null;
+ if (!CollectionUtils.isEmpty(component.getComponentInstances())) {
+ componentInstance = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(componentInstanceId)).findFirst().orElse(null);
+ }
+ return componentInstance;
+ }
+
+ private Either<User, ResponseFormat> validateUserIgnoreAudit(User modifier, String ecompErrorContext) {
+ Either<User, ResponseFormat> result = validateUser(modifier, ecompErrorContext, null, null, false);
+ if (result.isLeft()) {
+ List<Role> roles = new ArrayList<>();
+ roles.add(Role.ADMIN);
+ roles.add(Role.DESIGNER);
+ Either<Boolean, ResponseFormat> validationRoleRes = validateUserRole(result.left().value(), roles);
+ if (validationRoleRes.isRight()) {
+ result = Either.right(validationRoleRes.right().value());
+ }
+ }
+ return result;
+ }
+
+ public Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String resourceId, List<String> dataParamsToReturn) {
+
+ ComponentParametersView paramsToRetuen = new ComponentParametersView(dataParamsToReturn);
+ Either<Service, StorageOperationStatus> serviceResultEither = toscaOperationFacade.getToscaElement(resourceId, paramsToRetuen);
+
+ if (serviceResultEither.isRight()) {
+ log.debug("failed to get resource by id {} with filters {}", resourceId, dataParamsToReturn.toString());
+ return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(serviceResultEither.right().value()), ""));
+ }
+
+ Service service = serviceResultEither.left().value();
+ UiComponentDataTransfer dataTransfer = UiComponentDataConverter.getUiDataTransferFromServiceByParams(service, dataParamsToReturn);
+ return Either.left(dataTransfer);
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceComponentInstanceBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceComponentInstanceBusinessLogic.java
index c42cf004ff..9586be81ea 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceComponentInstanceBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceComponentInstanceBusinessLogic.java
@@ -42,16 +42,6 @@ public class ServiceComponentInstanceBusinessLogic extends ComponentInstanceBusi
}
@Override
- protected ComponentOperation getContainerComponentOperation() {
- return serviceOperation;
- }
-
- @Override
- protected ComponentOperation getCompInstOriginComponentOperation() {
- return resourceOperation;
- }
-
- @Override
protected ComponentTypeEnum getComponentTypeOfComponentInstance() {
return ComponentTypeEnum.RESOURCE_INSTANCE;
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/VFComponentInstanceBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/VFComponentInstanceBusinessLogic.java
index 3e42897c79..61a5af5b74 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/VFComponentInstanceBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/VFComponentInstanceBusinessLogic.java
@@ -25,7 +25,6 @@ import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.operations.impl.ComponentOperation;
import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -55,16 +54,6 @@ public class VFComponentInstanceBusinessLogic extends ComponentInstanceBusinessL
}
@Override
- protected ComponentOperation getContainerComponentOperation() {
- return resourceOperation;
- }
-
- @Override
- protected ComponentOperation getCompInstOriginComponentOperation() {
- return resourceOperation;
- }
-
- @Override
protected ComponentTypeEnum getComponentTypeOfComponentInstance() {
return ComponentTypeEnum.RESOURCE_INSTANCE;
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CertificationChangeTransition.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CertificationChangeTransition.java
index 445b3a9750..0e0f6f9464 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CertificationChangeTransition.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CertificationChangeTransition.java
@@ -21,27 +21,25 @@
package org.openecomp.sdc.be.components.lifecycle;
import java.util.Arrays;
-import java.util.List;
-
import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;
import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.model.ArtifactDefinition;
import org.openecomp.sdc.be.model.Component;
import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
import org.openecomp.sdc.be.model.LifecycleStateEnum;
-import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.be.model.operations.api.ILifecycleOperation;
+import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaElementLifecycleOperation;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
+import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.be.model.operations.impl.ResourceOperation;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
import org.openecomp.sdc.be.user.Role;
-import org.openecomp.sdc.common.config.EcompErrorName;
import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -57,8 +55,8 @@ public class CertificationChangeTransition extends LifeCycleTransition {
private AuditingActionEnum auditingAction;
private ArtifactsBusinessLogic artifactsManager;
- public CertificationChangeTransition(LifeCycleTransitionEnum name, ComponentsUtils componentUtils, ILifecycleOperation lifecycleOperation) {
- super(componentUtils, lifecycleOperation);
+ public CertificationChangeTransition(LifeCycleTransitionEnum name, ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) {
+ super(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao);
this.name = name;
@@ -67,7 +65,11 @@ public class CertificationChangeTransition extends LifeCycleTransition {
addAuthorizedRoles(ComponentTypeEnum.RESOURCE, Arrays.asList(certificationChangeRoles));
addAuthorizedRoles(ComponentTypeEnum.SERVICE, Arrays.asList(certificationChangeRoles));
// TODO to be later defined for product
-
+
+ //additional authorized roles for resource type
+ Role[] resourceRoles = { Role.DESIGNER};
+ addResouceAuthorizedRoles(ResourceTypeEnum.VFCMT, Arrays.asList(resourceRoles));
+
switch (this.name) {
case CERTIFY:
this.auditingAction = AuditingActionEnum.CERTIFICATION_SUCCESS_RESOURCE;
@@ -106,7 +108,6 @@ public class CertificationChangeTransition extends LifeCycleTransition {
}
private ResponseFormat formatCertificationError(Component component, StorageOperationStatus response, ComponentTypeEnum componentType) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError, "Change LifecycleState - Certify failed on graph");
BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState - Certify failed on graph");
log.debug("certification change failed on graph");
@@ -118,20 +119,24 @@ public class CertificationChangeTransition extends LifeCycleTransition {
@Override
public Either<Boolean, ResponseFormat> validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier, User owner, LifecycleStateEnum oldState, LifecycleChangeInfoWithAction lifecycleChangeInfo) {
String componentName = component.getComponentMetadataDefinition().getMetadataDataDefinition().getName();
- log.debug("validate before certification change. resource name={}, oldState={}, owner userId={}", componentName, oldState, owner.getUserId());
+ log.info("validate before certification change. resource name={}, oldState={}, owner userId={}", componentName, oldState, owner.getUserId());
// validate user
- Either<Boolean, ResponseFormat> userValidationResponse = userRoleValidation(modifier, componentType, lifecycleChangeInfo);
- if (userValidationResponse.isRight()) {
+ Either<Boolean, ResponseFormat> userValidationResponse = userRoleValidation(modifier,component, componentType, lifecycleChangeInfo);
+ if (userValidationResponse.isRight()) {
+ log.error("userRoleValidation failed");
return userValidationResponse;
}
if (!oldState.equals(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS)) {
+ log.error("oldState={} should be={}",oldState,ActionStatus.COMPONENT_NOT_READY_FOR_CERTIFICATION);
ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_NOT_READY_FOR_CERTIFICATION, componentName, componentType.name().toLowerCase());
- return Either.right(error);
+ return Either.right(error);
}
if (oldState.equals(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS) && !modifier.equals(owner) && !modifier.getRole().equals(Role.ADMIN.name())) {
+ log.error("oldState={} should not be={}",oldState,ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE);
+ log.error("&& modifier({})!={} && modifier.role({})!={}",modifier,owner);
ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId());
return Either.right(error);
}
@@ -144,14 +149,13 @@ public class CertificationChangeTransition extends LifeCycleTransition {
log.info("start performing certification change for resource {}", component.getUniqueId());
Either<? extends Component, ResponseFormat> result = null;
- NodeTypeEnum nodeType = componentType.getNodeType();
try {
- Either<? extends Component, StorageOperationStatus> certificationChangeResult = Either.right(StorageOperationStatus.GENERAL_ERROR);
+ Either<ToscaElement, StorageOperationStatus> certificationChangeResult = Either.right(StorageOperationStatus.GENERAL_ERROR);
if (nextState.equals(LifecycleStateEnum.CERTIFIED)) {
- certificationChangeResult = lifeCycleOperation.certifyComponent(nodeType, component, modifier, owner, true);
+ certificationChangeResult = lifeCycleOperation.certifyToscaElement(component.getUniqueId(), modifier.getUserId(), owner.getUserId());
} else {
- certificationChangeResult = lifeCycleOperation.cancelOrFailCertification(nodeType, component, modifier, owner, nextState, true);
+ certificationChangeResult = lifeCycleOperation.cancelOrFailCertification(component.getUniqueId(), modifier.getUserId(), owner.getUserId(), nextState);
}
if (certificationChangeResult.isRight()) {
@@ -159,51 +163,32 @@ public class CertificationChangeTransition extends LifeCycleTransition {
result = Either.right(responseFormat);
return result;
}
-
+
if (nextState.equals(LifecycleStateEnum.CERTIFIED)) {
- Either<Boolean, StorageOperationStatus> deleteOldComponentVersions = lifeCycleOperation.deleteOldComponentVersions(nodeType, component.getComponentMetadataDefinition().getMetadataDataDefinition().getName(),
- component.getComponentMetadataDefinition().getMetadataDataDefinition().getUUID(), true);
+ Either<Boolean, StorageOperationStatus> deleteOldComponentVersions = lifeCycleOperation.deleteOldToscaElementVersions(ModelConverter.getVertexType(component), componentType, component.getComponentMetadataDefinition().getMetadataDataDefinition().getName(),
+ component.getComponentMetadataDefinition().getMetadataDataDefinition().getUUID());
if (deleteOldComponentVersions.isRight()) {
ResponseFormat responseFormat = formatCertificationError(component, deleteOldComponentVersions.right().value(), componentType);
result = Either.right(responseFormat);
- return result;
}
}
- result = Either.left(certificationChangeResult.left().value());
+ result = Either.left(ModelConverter.convertFromToscaElement(certificationChangeResult.left().value()));
return result;
} finally {
if (result == null || result.isRight()) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError, "Change LifecycleState");
BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState");
if (inTransaction == false) {
log.debug("operation failed. do rollback");
- lifeCycleOperation.getResourceOperation().getTitanGenericDao().rollback();
+ titanDao.rollback();
}
} else {
if (inTransaction == false) {
log.debug("operation success. do commit");
- lifeCycleOperation.getResourceOperation().getTitanGenericDao().commit();
+ titanDao.commit();
}
}
}
}
-
- public StorageOperationStatus deleteOldVersion(List<ArtifactDefinition> artifactsToDelete, Resource resourceToDelete) {
- ResourceOperation resourceOperation = lifeCycleOperation.getResourceOperation();
-
- Either<List<ArtifactDefinition>, StorageOperationStatus> artifactsRes = resourceOperation.getComponentArtifactsForDelete(resourceToDelete.getUniqueId(), NodeTypeEnum.Resource, true);
- if (artifactsRes.isRight()) {
- return artifactsRes.right().value();
- }
- Either<Resource, StorageOperationStatus> deleteResourceRes = resourceOperation.deleteResource(resourceToDelete.getUniqueId(), true);
- if (deleteResourceRes.isRight()) {
- return deleteResourceRes.right().value();
- }
- artifactsToDelete.addAll(artifactsRes.left().value());
-
- return StorageOperationStatus.OK;
- }
-
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CertificationRequestTransition.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CertificationRequestTransition.java
index 69a9cbdb24..042af54383 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CertificationRequestTransition.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CertificationRequestTransition.java
@@ -29,10 +29,14 @@ import java.util.Map.Entry;
import java.util.Optional;
import java.util.Set;
+import org.apache.commons.codec.binary.Base64;
import org.openecomp.sdc.be.components.distribution.engine.ServiceDistributionArtifactsBuilder;
+import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;
import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic;
import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;
+import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
@@ -50,13 +54,20 @@ import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.Service;
import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaElementLifecycleOperation;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
+import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
import org.openecomp.sdc.be.model.operations.api.ILifecycleOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.CapabilityOperation;
import org.openecomp.sdc.be.model.operations.impl.ResourceOperation;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.tosca.ToscaError;
import org.openecomp.sdc.be.tosca.ToscaExportHandler;
+import org.openecomp.sdc.be.tosca.ToscaRepresentation;
import org.openecomp.sdc.be.user.Role;
+import org.openecomp.sdc.common.api.ArtifactTypeEnum;
import org.openecomp.sdc.common.util.ValidationUtils;
import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
@@ -68,15 +79,11 @@ public class CertificationRequestTransition extends LifeCycleTransition {
private static Logger log = LoggerFactory.getLogger(CertificationRequestTransition.class.getName());
- private ServiceDistributionArtifactsBuilder serviceDistributionArtifactsBuilder;
- private ResourceOperation resourceOperation;
private CapabilityOperation capabilityOperation;
private ServiceBusinessLogic serviceBusinessLogic;
- private ToscaExportHandler toscaExportUtils;
-
- public CertificationRequestTransition(ComponentsUtils componentUtils, ILifecycleOperation lifecycleOperation, ServiceDistributionArtifactsBuilder serviceDistributionArtifactsBuilder, ServiceBusinessLogic serviceBusinessLogic,
- CapabilityOperation capabilityOperation, ToscaExportHandler toscaExportUtils) {
- super(componentUtils, lifecycleOperation);
+ public CertificationRequestTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ServiceDistributionArtifactsBuilder serviceDistributionArtifactsBuilder, ServiceBusinessLogic serviceBusinessLogic,
+ CapabilityOperation capabilityOperation, ToscaExportHandler toscaExportUtils, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) {
+ super(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao);
// authorized roles
Role[] resourceServiceCheckoutRoles = { Role.ADMIN, Role.DESIGNER };
@@ -87,13 +94,13 @@ public class CertificationRequestTransition extends LifeCycleTransition {
// TODO to be later defined for product
// addAuthorizedRoles(ComponentTypeEnum.PRODUCT,
// Arrays.asList(productCheckoutRoles));
+
+ //additional authorized roles for resource type
+ Role[] resourceRoles = { Role.TESTER};
+ addResouceAuthorizedRoles(ResourceTypeEnum.VFCMT, Arrays.asList(resourceRoles));
- this.serviceDistributionArtifactsBuilder = serviceDistributionArtifactsBuilder;
- if (lifeCycleOperation != null)
- this.resourceOperation = lifeCycleOperation.getResourceOperation();
this.serviceBusinessLogic = serviceBusinessLogic;
this.capabilityOperation = capabilityOperation;
- this.toscaExportUtils = toscaExportUtils;
}
@Override
@@ -125,7 +132,7 @@ public class CertificationRequestTransition extends LifeCycleTransition {
private ResponseFormat getRelevantResponseFormatUncertifiedRI(ComponentInstance nonCertifiedRI, ComponentTypeEnum componentType) {
ResponseFormat responseFormat;
- Either<Resource, StorageOperationStatus> eitherResource = resourceOperation.getResource(nonCertifiedRI.getComponentUid());
+ Either<Resource, StorageOperationStatus> eitherResource = toscaOperationFacade.getToscaElement(nonCertifiedRI.getComponentUid());
if (eitherResource.isRight()) {
responseFormat = componentUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
@@ -133,16 +140,16 @@ public class CertificationRequestTransition extends LifeCycleTransition {
} else {
ActionStatus actionStatus;
Resource resource = eitherResource.left().value();
- Either<List<Resource>, StorageOperationStatus> status = resourceOperation.findLastCertifiedResourceByUUID(resource);
+ Either<Resource, StorageOperationStatus> status = toscaOperationFacade.findLastCertifiedToscaElementByUUID(resource);
if (ValidationUtils.validateMinorVersion(nonCertifiedRI.getComponentVersion())) {
- if (status.isRight() || status.left().value() == null || status.left().value().isEmpty()) {
+ if (status.isRight() || status.left().value() == null) {
actionStatus = ActionStatus.VALIDATED_RESOURCE_NOT_FOUND;
} else {
actionStatus = ActionStatus.FOUND_ALREADY_VALIDATED_RESOURCE;
}
} else {
- if (status.isRight() || status.left().value() == null || status.left().value().isEmpty())
+ if (status.isRight() || status.left().value() == null)
actionStatus = ActionStatus.FOUND_LIST_VALIDATED_RESOURCES;
else {
actionStatus = ActionStatus.FOUND_ALREADY_VALIDATED_RESOURCE;
@@ -157,23 +164,23 @@ public class CertificationRequestTransition extends LifeCycleTransition {
private Either<ActionStatus, Map<String, ArtifactDefinition>> validateMandatoryArtifactsSupplied(Map<String, ArtifactDefinition> artifacts) {
- if (artifacts == null || true == artifacts.isEmpty()) {
+ if (artifacts == null || artifacts.isEmpty()) {
return Either.left(ActionStatus.OK);
}
- Map<String, ArtifactDefinition> invalidArtifacts = new HashMap<String, ArtifactDefinition>();
+ Map<String, ArtifactDefinition> invalidArtifacts = new HashMap<>();
for (Entry<String, ArtifactDefinition> artifact : artifacts.entrySet()) {
ArtifactDefinition artifactDefinition = artifact.getValue();
- if (true == artifactDefinition.getMandatory()) {
+ if (artifactDefinition.getMandatory()) {
String artifactEsId = artifactDefinition.getEsId();
- if (artifactEsId == null || true == artifactEsId.isEmpty()) {
+ if (artifactEsId == null || artifactEsId.isEmpty()) {
invalidArtifacts.put(artifact.getKey(), artifactDefinition);
}
}
}
- if (true == invalidArtifacts.isEmpty()) {
+ if (invalidArtifacts.isEmpty()) {
return Either.left(ActionStatus.OK);
} else {
return Either.right(invalidArtifacts);
@@ -185,81 +192,73 @@ public class CertificationRequestTransition extends LifeCycleTransition {
log.debug("start performing certification request for resource {}", component.getUniqueId());
- // Either<ActionStatus, Map<String, ArtifactDefinition>>
- // validateMandatoryArtifacts =
- // validateMandatoryArtifactsSupplied(component.getArtifacts());
- // log.debug("After checking mandatory artifacts were populated. Result
- // is " + validateMandatoryArtifacts);
- // if (validateMandatoryArtifacts.isRight()) {
- // ResponseFormat responseFormat = componentUtils
- // .getResponseFormatByMissingArtifacts(
- // componentType,
- // validateMandatoryArtifacts.right().value());
- // return Either.right(responseFormat);
- // }
- ActionStatus actionStatus = null;
- ResponseFormat responseFormat = null;
-
- if (componentType == ComponentTypeEnum.SERVICE || (componentType == ComponentTypeEnum.RESOURCE && ((Resource) component).getResourceType() == ResourceTypeEnum.VF)) {
-
- Either<Boolean, ResponseFormat> statusCert = validateAllResourceInstanceCertified(component);
- if (statusCert.isRight()) {
- return Either.right(statusCert.right().value());
- }
-
- statusCert = validateConfiguredAtomicReqCapSatisfied(component);
- if (statusCert.isRight()) {
- return Either.right(statusCert.right().value());
+ ActionStatus actionStatus;
+ ResponseFormat responseFormat;
+ Either<? extends Component, ResponseFormat> result = null;
+ try{
+ if (componentType == ComponentTypeEnum.SERVICE || (componentType == ComponentTypeEnum.RESOURCE && ((Resource) component).getResourceType() == ResourceTypeEnum.VF)) {
+
+ Either<Boolean, ResponseFormat> statusCert = validateAllResourceInstanceCertified(component);
+ if (statusCert.isRight()) {
+ return Either.right(statusCert.right().value());
+ }
+
+ statusCert = validateConfiguredAtomicReqCapSatisfied(component);
+ if (statusCert.isRight()) {
+ return Either.right(statusCert.right().value());
+ }
}
- }
- if (componentType == ComponentTypeEnum.SERVICE) {
- Either<Boolean, StorageOperationStatus> status = validateDeloymentArtifactSupplied((Service) component);
- if (status.isRight()) {
- StorageOperationStatus operationStatus = status.right().value();
- actionStatus = componentUtils.convertFromStorageResponse(operationStatus);
- } else {
- Boolean isDeploymentArtifactExists = status.left().value();
- if (isDeploymentArtifactExists == null || isDeploymentArtifactExists.booleanValue() == false) {
- actionStatus = ActionStatus.SERVICE_DEPLOYMENT_ARTIFACT_NOT_FOUND;
- } else {
- Either<Service, ResponseFormat> generateHeatEnvResult = serviceBusinessLogic.generateHeatEnvArtifacts((Service) component, modifier, shouldLock);
- if (generateHeatEnvResult.isRight()) {
+ if (componentType == ComponentTypeEnum.SERVICE) {
+
+ Either<Service, ResponseFormat> generateHeatEnvResult = serviceBusinessLogic.generateHeatEnvArtifacts((Service) component, modifier, shouldLock);
+
+ if (generateHeatEnvResult.isRight()) {
return Either.right(generateHeatEnvResult.right().value());
}
- Either<Service, ResponseFormat> generateVfModuleResult = serviceBusinessLogic.generateVfModuleArtifacts((Service) component, modifier, shouldLock);
- if (generateVfModuleResult.isRight()) {
+ Either<Service, ResponseFormat> generateVfModuleResult = serviceBusinessLogic.generateVfModuleArtifacts((Service) component, modifier, shouldLock);
+ if (generateVfModuleResult.isRight()) {
return Either.right(generateVfModuleResult.right().value());
- }
}
}
-
- if (actionStatus != null) {
+
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherPopulated = componentBl.populateToscaArtifacts(component, modifier, true, inTransaction, shouldLock);
+ if (eitherPopulated != null && eitherPopulated.isRight()) {
+ return Either.right(eitherPopulated.right().value());
+ }
+
+ NodeTypeEnum nodeType = componentType.equals(ComponentTypeEnum.SERVICE) ? NodeTypeEnum.Service : NodeTypeEnum.Resource;
+
+
+ Either<ToscaElement, StorageOperationStatus> certificationRequestResult = lifeCycleOperation.requestCertificationToscaElement(component.getUniqueId(), modifier.getUserId(), owner.getUserId());
+ if (certificationRequestResult.isRight()) {
+ log.debug("checkout failed on graph");
+ StorageOperationStatus response = certificationRequestResult.right().value();
+ actionStatus = componentUtils.convertFromStorageResponse(response);
+
+ if (response.equals(StorageOperationStatus.ENTITY_ALREADY_EXISTS)) {
+ actionStatus = ActionStatus.COMPONENT_VERSION_ALREADY_EXIST;
+ }
responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType);
- return Either.right(responseFormat);
+ result = Either.right(responseFormat);
}
-
- }
-
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherPopulated = componentBl.populateToscaArtifacts(component, modifier, true, inTransaction, shouldLock);
- if (eitherPopulated != null && eitherPopulated.isRight()) {
- return Either.right(eitherPopulated.right().value());
- }
-
- NodeTypeEnum nodeType = (componentType.equals(ComponentTypeEnum.SERVICE)) ? NodeTypeEnum.Service : NodeTypeEnum.Resource;
- Either<? extends Component, StorageOperationStatus> certificationRequestResult = lifeCycleOperation.requestCertificationComponent(nodeType, component, modifier, owner, inTransaction);
- if (certificationRequestResult.isRight()) {
- log.debug("checkout failed on graph");
- StorageOperationStatus response = certificationRequestResult.right().value();
- actionStatus = componentUtils.convertFromStorageResponse(response);
-
- if (response.equals(StorageOperationStatus.ENTITY_ALREADY_EXISTS)) {
- actionStatus = ActionStatus.COMPONENT_VERSION_ALREADY_EXIST;
+ else {
+ result = Either.left(ModelConverter.convertFromToscaElement(certificationRequestResult.left().value()));
+ }
+ } finally {
+ if (result == null || result.isRight()) {
+ BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState");
+ if (inTransaction == false) {
+ log.debug("operation failed. do rollback");
+ titanDao.rollback();
+ }
+ } else {
+ if (inTransaction == false) {
+ log.debug("operation success. do commit");
+ titanDao.commit();
}
- responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType);
- return Either.right(responseFormat);
}
-
- return Either.left(certificationRequestResult.left().value());
+ }
+ return result;
}
private Either<Boolean, ResponseFormat> validateConfiguredAtomicReqCapSatisfied(Component component) {
@@ -369,7 +368,7 @@ public class CertificationRequestTransition extends LifeCycleTransition {
log.debug("validate before certification request. resource name={}, oldState={}, owner userId={}", componentName, oldState, owner.getUserId());
// validate user
- Either<Boolean, ResponseFormat> userValidationResponse = userRoleValidation(modifier, componentType, lifecycleChangeInfo);
+ Either<Boolean, ResponseFormat> userValidationResponse = userRoleValidation(modifier,component, componentType, lifecycleChangeInfo);
if (userValidationResponse.isRight()) {
return userValidationResponse;
}
@@ -397,13 +396,4 @@ public class CertificationRequestTransition extends LifeCycleTransition {
return Either.left(true);
}
-
- private Either<Boolean, StorageOperationStatus> validateDeloymentArtifactSupplied(Service service) {
-
- Either<Boolean, StorageOperationStatus> serviceContainsDeploymentArtifacts = this.serviceDistributionArtifactsBuilder.isServiceContainsDeploymentArtifacts(service);
-
- return serviceContainsDeploymentArtifacts;
-
- }
-
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CheckinTransition.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CheckinTransition.java
index 28227285f1..bfe51ded48 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CheckinTransition.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CheckinTransition.java
@@ -23,15 +23,19 @@ package org.openecomp.sdc.be.components.lifecycle;
import java.util.Arrays;
import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic;
+import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.model.Component;
import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
import org.openecomp.sdc.be.model.LifecycleStateEnum;
import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.be.model.operations.api.ILifecycleOperation;
+import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaElementLifecycleOperation;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
+import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
import org.openecomp.sdc.be.user.Role;
@@ -45,8 +49,8 @@ public class CheckinTransition extends LifeCycleTransition {
private static Logger log = LoggerFactory.getLogger(CheckinTransition.class.getName());
- public CheckinTransition(ComponentsUtils componentUtils, ILifecycleOperation lifecycleOperation) {
- super(componentUtils, lifecycleOperation);
+ public CheckinTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) {
+ super(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao);
// authorized roles
Role[] resourceServiceCheckoutRoles = { Role.ADMIN, Role.DESIGNER };
@@ -71,21 +75,40 @@ public class CheckinTransition extends LifeCycleTransition {
public Either<? extends Component, ResponseFormat> changeState(ComponentTypeEnum componentType, Component component, ComponentBusinessLogic componentBl, User modifier, User owner, boolean shouldLock, boolean inTransaction) {
log.debug("start performing checkin for {} {}", componentType.name(), component.getUniqueId());
- NodeTypeEnum nodeType = componentType.getNodeType();
- Either<? extends Component, StorageOperationStatus> checkinResourceResult = lifeCycleOperation.checkinComponent(nodeType, component, modifier, owner, inTransaction);
- if (checkinResourceResult.isRight()) {
- log.debug("checkout failed on graph");
- StorageOperationStatus response = checkinResourceResult.right().value();
- ActionStatus actionStatus = componentUtils.convertFromStorageResponse(response);
-
- if (response.equals(StorageOperationStatus.ENTITY_ALREADY_EXISTS)) {
- actionStatus = ActionStatus.COMPONENT_VERSION_ALREADY_EXIST;
+ Either<? extends Component, ResponseFormat> result = null;
+ try{
+ Either<ToscaElement, StorageOperationStatus> checkinResourceResult = lifeCycleOperation.
+ checkinToscaELement(component.getLifecycleState(), component.getUniqueId(), modifier.getUserId(), owner.getUserId());
+
+ if (checkinResourceResult.isRight()) {
+ log.debug("checkout failed on graph");
+ StorageOperationStatus response = checkinResourceResult.right().value();
+ ActionStatus actionStatus = componentUtils.convertFromStorageResponse(response);
+
+ if (response.equals(StorageOperationStatus.ENTITY_ALREADY_EXISTS)) {
+ actionStatus = ActionStatus.COMPONENT_VERSION_ALREADY_EXIST;
+ }
+ ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType);
+ result = Either.right(responseFormat);
+ }
+ else {
+ result = Either.left(ModelConverter.convertFromToscaElement(checkinResourceResult.left().value()));
+ }
+ } finally {
+ if (result == null || result.isRight()) {
+ BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState");
+ if (inTransaction == false) {
+ log.debug("operation failed. do rollback");
+ titanDao.rollback();
+ }
+ } else {
+ if (inTransaction == false) {
+ log.debug("operation success. do commit");
+ titanDao.commit();
+ }
}
- ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType);
- return Either.right(responseFormat);
}
-
- return Either.left(checkinResourceResult.left().value());
+ return result;
}
@Override
@@ -94,13 +117,19 @@ public class CheckinTransition extends LifeCycleTransition {
log.debug("validate before checkin. component name={}, oldState={}, owner userId={}", componentName, oldState, owner.getUserId());
// validate user
- Either<Boolean, ResponseFormat> userValidationResponse = userRoleValidation(modifier, componentType, lifecycleChangeInfo);
+ Either<Boolean, ResponseFormat> userValidationResponse = userRoleValidation(modifier,component, componentType, lifecycleChangeInfo);
if (userValidationResponse.isRight()) {
return userValidationResponse;
}
if (!oldState.equals(LifecycleStateEnum.READY_FOR_CERTIFICATION) && !oldState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) {
- ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_ALREADY_CHECKED_IN, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId());
+ ActionStatus action = ActionStatus.COMPONENT_ALREADY_CHECKED_IN;
+ if (oldState.equals(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS)){
+ action = ActionStatus.COMPONENT_SENT_FOR_CERTIFICATION;
+ } else if (oldState.equals(LifecycleStateEnum.CERTIFIED)){
+ action = ActionStatus.COMPONENT_ALREADY_CERTIFIED;
+ }
+ ResponseFormat error = componentUtils.getResponseFormat(action, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId());
return Either.right(error);
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CheckoutTransition.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CheckoutTransition.java
index a4e6bdb86c..d6cbd3663c 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CheckoutTransition.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CheckoutTransition.java
@@ -21,17 +21,26 @@
package org.openecomp.sdc.be.components.lifecycle;
import java.util.Arrays;
+import java.util.List;
import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic;
+import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
+import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
+import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.InputDefinition;
import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
import org.openecomp.sdc.be.model.LifecycleStateEnum;
import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.be.model.operations.api.ILifecycleOperation;
+import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaElementLifecycleOperation;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
+import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
import org.openecomp.sdc.be.user.Role;
@@ -43,12 +52,10 @@ import fj.data.Either;
public class CheckoutTransition extends LifeCycleTransition {
- private static final String PLACE_HOLDER_RESOURCE_TYPES = "validForResourceTypes";
-
private static Logger log = LoggerFactory.getLogger(CheckoutTransition.class.getName());
- public CheckoutTransition(ComponentsUtils componentUtils, ILifecycleOperation lifecycleOperation) {
- super(componentUtils, lifecycleOperation);
+ public CheckoutTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) {
+ super(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao);
// authorized roles
Role[] resourceServiceCheckoutRoles = { Role.ADMIN, Role.DESIGNER };
@@ -74,24 +81,66 @@ public class CheckoutTransition extends LifeCycleTransition {
log.debug("start performing {} for resource {}", getName().name(), component.getUniqueId());
- if (componentBl != null)
- componentBl.setDeploymentArtifactsPlaceHolder(component, modifier);
- NodeTypeEnum nodeType = componentType.getNodeType();
- Either<? extends Component, StorageOperationStatus> checkoutResourceResult = lifeCycleOperation.checkoutComponent(nodeType, component, modifier, owner, inTransaction);
+ Either<? extends Component, ResponseFormat> result = null;
+ try {
+
+ Either<ToscaElement, StorageOperationStatus> checkoutResourceResult = lifeCycleOperation.checkoutToscaElement(component.getUniqueId(), modifier.getUserId(), owner.getUserId());
+
+ if (checkoutResourceResult.isRight()) {
+ log.debug("checkout failed on graph");
+ StorageOperationStatus response = checkoutResourceResult.right().value();
+ ActionStatus actionStatus = componentUtils.convertFromStorageResponse(response);
+
+ if (response.equals(StorageOperationStatus.ENTITY_ALREADY_EXISTS)) {
+ actionStatus = ActionStatus.COMPONENT_VERSION_ALREADY_EXIST;
+ }
+ ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType);
+ result = Either.right(responseFormat);
+ } else {
+ Component clonedComponent = ModelConverter.convertFromToscaElement(checkoutResourceResult.left().value());
+ result = Either.left(clonedComponent);
+ Either<Boolean, ResponseFormat> upgradeToLatestGeneric = componentBl.shouldUpgradeToLatestGeneric(clonedComponent);
+ if (upgradeToLatestGeneric.isRight())
+ result = Either.right(upgradeToLatestGeneric.right().value());
+ else if (upgradeToLatestGeneric.left().value()) {
+ StorageOperationStatus response = upgradeToLatestGenericData(clonedComponent);
+ if (StorageOperationStatus.OK != response) {
+ ActionStatus actionStatus = componentUtils.convertFromStorageResponse(response);
+ ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType);
+ result = Either.right(responseFormat);
+ }
+ }
- if (checkoutResourceResult.isRight()) {
- log.debug("checkout failed on graph");
- StorageOperationStatus response = checkoutResourceResult.right().value();
- ActionStatus actionStatus = componentUtils.convertFromStorageResponse(response);
+ }
- if (response.equals(StorageOperationStatus.ENTITY_ALREADY_EXISTS)) {
- actionStatus = ActionStatus.COMPONENT_VERSION_ALREADY_EXIST;
+ } finally {
+ if (result == null || result.isRight()) {
+ BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState");
+ if (inTransaction == false) {
+ log.debug("operation failed. do rollback");
+ titanDao.rollback();
+ }
+ } else {
+ if (inTransaction == false) {
+ log.debug("operation success. do commit");
+ titanDao.commit();
+ }
}
- ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType);
- return Either.right(responseFormat);
}
+ return result;
+ }
- return Either.left(checkoutResourceResult.left().value());
+ private StorageOperationStatus upgradeToLatestGenericData(Component clonedComponent) {
+
+ StorageOperationStatus updateStatus = null;
+ Either<Component, StorageOperationStatus> updateEither = toscaOperationFacade.updateToscaElement(clonedComponent);
+ if (updateEither.isRight())
+ updateStatus = updateEither.right().value();
+ else if (clonedComponent.shouldGenerateInputs()) {
+ List<InputDefinition> newInputs = clonedComponent.getInputs();
+ updateStatus = lifeCycleOperation.updateToscaDataOfToscaElement(clonedComponent.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, newInputs, JsonPresentationFields.NAME);
+ }
+ return updateStatus;
}
@Override
@@ -100,7 +149,7 @@ public class CheckoutTransition extends LifeCycleTransition {
log.debug("validate before checkout. resource name={}, oldState={}, owner userId={}", componentName, oldState, owner.getUserId());
// validate user
- Either<Boolean, ResponseFormat> userValidationResponse = userRoleValidation(modifier, componentType, lifecycleChangeInfo);
+ Either<Boolean, ResponseFormat> userValidationResponse = userRoleValidation(modifier, component, componentType, lifecycleChangeInfo);
if (userValidationResponse.isRight()) {
return userValidationResponse;
}
@@ -131,11 +180,4 @@ public class CheckoutTransition extends LifeCycleTransition {
return Either.left(true);
}
- /*
- * private Either<Boolean, ResponseFormat> productContactsValidation(Product product, User modifier) { // validate user Either<Boolean, ResponseFormat> eitherResponse = Either.left(true); String role = modifier.getRole(); if
- * (UserRoleEnum.PRODUCT_MANAGER.getName().equals(role) || UserRoleEnum.PRODUCT_STRATEGIST.getName().equals(role)){ String userId = modifier.getUserId(); if (!product.getContacts().contains(userId)){ log.
- * debug("User with userId {} cannot checkout product. userId not found in product contacts list" , userId); ResponseFormat responseFormat = componentUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); return Either.right(responseFormat);
- * } else { log. trace("Found user userId {} in product contacts - checkout request validated" ); } } return eitherResponse; }
- */
-
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifeCycleTransition.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifeCycleTransition.java
index 49d94dc80b..0d0e06fe6d 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifeCycleTransition.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifeCycleTransition.java
@@ -24,44 +24,53 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;
import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic;
import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction.LifecycleChanceActionEnum;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
+import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.model.Component;
import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
import org.openecomp.sdc.be.model.LifecycleStateEnum;
import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaElementLifecycleOperation;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
import org.openecomp.sdc.be.model.operations.api.ILifecycleOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
import org.openecomp.sdc.be.user.Role;
import org.openecomp.sdc.exception.ResponseFormat;
+import org.springframework.beans.factory.annotation.Autowired;
import fj.data.Either;
public abstract class LifeCycleTransition {
protected ConfigurationManager configurationManager;
- protected ILifecycleOperation lifeCycleOperation;
+ @Autowired
+ protected ToscaElementLifecycleOperation lifeCycleOperation;
+ @Autowired
+ protected TitanDao titanDao;
protected ComponentsUtils componentUtils;
protected Map<ComponentTypeEnum, List<Role>> authorizedRoles;
+ protected Map<ResourceTypeEnum, List<Role>> resourceAuthorizedRoles;
+
+ ToscaOperationFacade toscaOperationFacade;
- protected LifeCycleTransition(ComponentsUtils componentUtils, ILifecycleOperation lifecycleOperation) {
+ protected LifeCycleTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation2, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) {
- // configurationManager = (ConfigurationManager)
- // context.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR);
- // lifeCycleOperation = LifecycleOperation.getInstance();
this.configurationManager = ConfigurationManager.getConfigurationManager();
- this.lifeCycleOperation = lifecycleOperation;
+ this.lifeCycleOperation = lifecycleOperation2;
this.componentUtils = componentUtils;
this.authorizedRoles = new HashMap<>();
-
+ this.resourceAuthorizedRoles = new HashMap<>();
+ this.toscaOperationFacade = toscaOperationFacade;
+ this.titanDao = titanDao;
}
public abstract LifeCycleTransitionEnum getName();
@@ -76,11 +85,11 @@ public abstract class LifeCycleTransition {
this.configurationManager = configurationManager;
}
- public ILifecycleOperation getLifeCycleOperation() {
+ public ToscaElementLifecycleOperation getLifeCycleOperation() {
return lifeCycleOperation;
}
- public void setLifeCycleOperation(ILifecycleOperation lifeCycleOperation) {
+ public void setLifeCycleOperation(ToscaElementLifecycleOperation lifeCycleOperation) {
this.lifeCycleOperation = lifeCycleOperation;
}
@@ -91,14 +100,14 @@ public abstract class LifeCycleTransition {
public void addAuthorizedRoles(ComponentTypeEnum componentType, List<Role> authorizedRoles) {
this.authorizedRoles.put(componentType, authorizedRoles);
}
+
+ public List<Role> getResourceAuthorizedRoles(ResourceTypeEnum resourceType) {
+ return resourceAuthorizedRoles.get(resourceType);
+ }
- //
- // public Either<? extends Component, ResponseFormat>
- // changeState(ComponentTypeEnum componentType, Component component,
- // ComponentBusinessLogic componentBl, User modifier, User owner){
- // return changeState(componentType, component, componentBl, modifier,
- // owner, false);
- // }
+ public void addResouceAuthorizedRoles(ResourceTypeEnum resourceType, List<Role> authorizedRoles) {
+ this.resourceAuthorizedRoles.put(resourceType, authorizedRoles);
+ }
public abstract Either<? extends Component, ResponseFormat> changeState(ComponentTypeEnum componentType, Component component, ComponentBusinessLogic componentBl, User modifier, User owner, boolean needLock, boolean inTransaction);
@@ -122,8 +131,7 @@ public abstract class LifeCycleTransition {
protected Either<User, ResponseFormat> getComponentOwner(Component component, ComponentTypeEnum componentType, boolean inTransaction) {
- NodeTypeEnum nodeType = componentType.getNodeType();
- Either<User, StorageOperationStatus> resourceOwnerResult = getLifeCycleOperation().getComponentOwner(component.getUniqueId(), nodeType, inTransaction);
+ Either<User, StorageOperationStatus> resourceOwnerResult = getLifeCycleOperation().getToscaElementOwner(component.getUniqueId());
if (resourceOwnerResult.isRight()) {
ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(componentUtils.convertFromStorageResponse(resourceOwnerResult.right().value()), component, componentType);
return Either.right(responseFormat);
@@ -131,21 +139,13 @@ public abstract class LifeCycleTransition {
return Either.left(resourceOwnerResult.left().value());
}
- /**
- * isUserValidForRequest
- *
- * @param modifier
- * @param action
- * TODO
- * @return
- */
- protected Either<Boolean, ResponseFormat> userRoleValidation(User modifier, ComponentTypeEnum componentType, LifecycleChangeInfoWithAction lifecycleChangeInfo) {
+ protected Either<Boolean, ResponseFormat> userRoleValidation(User modifier,Component component, ComponentTypeEnum componentType, LifecycleChangeInfoWithAction lifecycleChangeInfo) {
// validate user
- if (getAuthorizedRoles(componentType).contains(Role.valueOf(modifier.getRole()))) {
+ //first check the user for the component and then for the resource
+ if (getAuthorizedRoles(componentType).contains(Role.valueOf(modifier.getRole())) || userResourceRoleValidation(component,componentType,modifier)) {
return Either.left(true);
}
-
// this is only when creating vfc/cp when import vf from csar - when we
// create resources from node type, we create need to change the state
// to certified
@@ -156,5 +156,18 @@ public abstract class LifeCycleTransition {
ResponseFormat responseFormat = componentUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
return Either.right(responseFormat);
}
+
+ protected boolean userResourceRoleValidation(Component component, ComponentTypeEnum componentType, User modifier) {
+ if (componentType.equals(ComponentTypeEnum.RESOURCE)){
+ ResourceTypeEnum resourceType = ((ResourceMetadataDataDefinition)component.getComponentMetadataDefinition().getMetadataDataDefinition()).getResourceType();
+ if (getResourceAuthorizedRoles(resourceType)!=null && getResourceAuthorizedRoles(resourceType).contains(Role.valueOf(modifier.getRole()))) {
+ return true;
+ }
+ } else {
+ return false;
+ }
+
+ return false;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifecycleBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifecycleBusinessLogic.java
index 27709bb332..8e89a6bf31 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifecycleBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifecycleBusinessLogic.java
@@ -34,8 +34,11 @@ import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic;
import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
+import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.model.Component;
import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
@@ -43,14 +46,13 @@ import org.openecomp.sdc.be.model.LifecycleStateEnum;
import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.Service;
import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaElementLifecycleOperation;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
import org.openecomp.sdc.be.model.operations.api.ICacheMangerOperation;
import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation;
-import org.openecomp.sdc.be.model.operations.api.ILifecycleOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.CapabilityOperation;
-import org.openecomp.sdc.be.model.operations.impl.ProductOperation;
-import org.openecomp.sdc.be.model.operations.impl.ResourceOperation;
-import org.openecomp.sdc.be.model.operations.impl.ServiceOperation;
+import org.openecomp.sdc.be.model.operations.impl.ComponentOperation;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
import org.openecomp.sdc.be.tosca.ToscaExportHandler;
import org.openecomp.sdc.common.api.Constants;
@@ -76,13 +78,7 @@ public class LifecycleBusinessLogic {
private ArtifactsBusinessLogic artifactsBusinessLogic;
@Autowired
- private ResourceOperation resourceOperation;
-
- @Autowired
- private ServiceOperation serviceOperation;
-
- @Autowired
- private ProductOperation productOperation;
+ private TitanDao titanDao;
@Autowired
private CapabilityOperation capabilityOperation;
@@ -93,7 +89,7 @@ public class LifecycleBusinessLogic {
private ComponentsUtils componentUtils;
@javax.annotation.Resource
- private ILifecycleOperation lifecycleOperation;
+ private ToscaElementLifecycleOperation lifecycleOperation;
@javax.annotation.Resource
ArtifactsBusinessLogic artifactsManager;
@@ -114,6 +110,9 @@ public class LifecycleBusinessLogic {
@Autowired
ICacheMangerOperation cacheManagerOperation;
+
+ @Autowired
+ ToscaOperationFacade toscaOperationFacade;
private Map<String, LifeCycleTransition> stateTransitions;
private static volatile boolean isInitialized = false;
@@ -134,29 +133,29 @@ public class LifecycleBusinessLogic {
private void initStateOperations() {
stateTransitions = new HashMap<String, LifeCycleTransition>();
- LifeCycleTransition checkoutOp = new CheckoutTransition(componentUtils, lifecycleOperation);
+ LifeCycleTransition checkoutOp = new CheckoutTransition(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao);
stateTransitions.put(checkoutOp.getName().name(), checkoutOp);
- UndoCheckoutTransition undoCheckoutOp = new UndoCheckoutTransition(componentUtils, lifecycleOperation);
+ UndoCheckoutTransition undoCheckoutOp = new UndoCheckoutTransition(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao);
undoCheckoutOp.setArtifactsBusinessLogic(artifactsBusinessLogic);
stateTransitions.put(undoCheckoutOp.getName().name(), undoCheckoutOp);
- LifeCycleTransition checkinOp = new CheckinTransition(componentUtils, lifecycleOperation);
+ LifeCycleTransition checkinOp = new CheckinTransition(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao);
stateTransitions.put(checkinOp.getName().name(), checkinOp);
- LifeCycleTransition certificationRequest = new CertificationRequestTransition(componentUtils, lifecycleOperation, serviceDistributionArtifactsBuilder, serviceBusinessLogic, capabilityOperation, toscaExportUtils);
+ LifeCycleTransition certificationRequest = new CertificationRequestTransition(componentUtils, lifecycleOperation, serviceDistributionArtifactsBuilder, serviceBusinessLogic, capabilityOperation, toscaExportUtils, toscaOperationFacade, titanDao);
stateTransitions.put(certificationRequest.getName().name(), certificationRequest);
- LifeCycleTransition startCertification = new StartCertificationTransition(componentUtils, lifecycleOperation);
+ LifeCycleTransition startCertification = new StartCertificationTransition(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao);
stateTransitions.put(startCertification.getName().name(), startCertification);
- LifeCycleTransition failCertification = new CertificationChangeTransition(LifeCycleTransitionEnum.FAIL_CERTIFICATION, componentUtils, lifecycleOperation);
+ LifeCycleTransition failCertification = new CertificationChangeTransition(LifeCycleTransitionEnum.FAIL_CERTIFICATION, componentUtils, lifecycleOperation, toscaOperationFacade, titanDao);
stateTransitions.put(failCertification.getName().name(), failCertification);
- LifeCycleTransition cancelCertification = new CertificationChangeTransition(LifeCycleTransitionEnum.CANCEL_CERTIFICATION, componentUtils, lifecycleOperation);
+ LifeCycleTransition cancelCertification = new CertificationChangeTransition(LifeCycleTransitionEnum.CANCEL_CERTIFICATION, componentUtils, lifecycleOperation, toscaOperationFacade, titanDao);
stateTransitions.put(cancelCertification.getName().name(), cancelCertification);
- CertificationChangeTransition successCertification = new CertificationChangeTransition(LifeCycleTransitionEnum.CERTIFY, componentUtils, lifecycleOperation);
+ CertificationChangeTransition successCertification = new CertificationChangeTransition(LifeCycleTransitionEnum.CERTIFY, componentUtils, lifecycleOperation, toscaOperationFacade, titanDao);
successCertification.setArtifactsManager(artifactsBusinessLogic);
stateTransitions.put(successCertification.getName().name(), successCertification);
}
@@ -172,132 +171,16 @@ public class LifecycleBusinessLogic {
// TODO: rhalili - should use changeComponentState when possible
public Either<Resource, ResponseFormat> changeState(String resourceId, User modifier, LifeCycleTransitionEnum transitionEnum, LifecycleChangeInfoWithAction changeInfo, boolean inTransaction, boolean needLock) {
return (Either<Resource, ResponseFormat>) changeComponentState(ComponentTypeEnum.RESOURCE, resourceId, modifier, transitionEnum, changeInfo, inTransaction, needLock);
-
- // LifeCycleTransition lifeCycleTransition =
- // stateTransitions.get(transitionEnum.name());
- // if (lifeCycleTransition == null) {
- // log.debug("state operation is not valid. operations allowed are: {}",
- // LifeCycleTransitionEnum.valuesAsString());
- // ResponseFormat error =
- // componentUtils.getInvalidContentErrorAndAudit(modifier,
- // AuditingActionEnum.CHECKOUT_RESOURCE);
- // return Either.right(error);
- // }
- //
- // Either<Resource, ResponseFormat> operationResult;
- // Resource resource = null;
- // boolean needToUnlockResource = false;
- //
- // log.debug("get resource from graph");
- // ResponseFormat errorResponse;
- // Either<Resource, ResponseFormat> eitherResourceResponse =
- // getResourceForChange(resourceId, modifier, lifeCycleTransition);
- // if (eitherResourceResponse.isRight()) {
- // return eitherResourceResponse;
- // }
- // resource = eitherResourceResponse.left().value();
- // String resourceCurrVersion = resource.getResourceVersion();
- // LifecycleStateEnum resourceCurrState = resource.getLifecycleState();
- //
- // if (inTransaction == false) {
- // // lock resource
- // Either<Boolean, ResponseFormat> eitherLockResource =
- // lockResource(resource);
- // if (eitherLockResource.isRight()) {
- // errorResponse = eitherLockResource.right().value();
- // componentUtils.auditResource(errorResponse, modifier, resource,
- // resourceCurrState.name(), resourceCurrVersion,
- // lifeCycleTransition.getAuditingAction(), null);
- // return Either.right(errorResponse);
- // }
- // needToUnlockResource = true;
- // }
- //
- // try {
- // Either<Boolean, ResponseFormat> resourceNotDeleted =
- // validateResourceNotDeleted(modifier, lifeCycleTransition, resource,
- // resourceCurrVersion);
- // if (resourceNotDeleted.isRight()) {
- // return Either.right(resourceNotDeleted.right().value());
- // }
- //
- // Either<Boolean, ResponseFormat> validateHighestVersion =
- // validateHighestVersion(modifier, lifeCycleTransition, resource,
- // resourceCurrVersion);
- // if (validateHighestVersion.isRight()) {
- // return Either.right(validateHighestVersion.right().value());
- // }
- //
- // Either<User, ResponseFormat> ownerResult =
- // lifeCycleTransition.getResourceOwner(resource);
- // if (ownerResult.isRight()) {
- // return Either.right(ownerResult.right().value());
- // }
- // User owner = ownerResult.left().value();
- // log.debug("owner of resource {} is {}", resource.getUniqueId(),
- // owner.getUserId());
- //
- // LifecycleStateEnum oldState = resource.getLifecycleState();
- //
- // Either<String, ResponseFormat> commentValidationResult =
- // validateComment(changeInfo, transitionEnum);
- // if (commentValidationResult.isRight()) {
- // errorResponse = commentValidationResult.right().value();
- // EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new
- // EnumMap<AuditingFieldsKeysEnum,
- // Object>(AuditingFieldsKeysEnum.class);
- // auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT,
- // changeInfo.getUserRemarks());
- // componentUtils.auditResource(errorResponse, modifier, resource,
- // resourceCurrState.name(), resourceCurrVersion,
- // lifeCycleTransition.getAuditingAction(), auditingFields);
- // return Either.right(errorResponse);
- // }
- // changeInfo.setUserRemarks(commentValidationResult.left().value());
- //
- // Either<Boolean, ResponseFormat> stateValidationResult =
- // lifeCycleTransition.validateResourceBeforeTransition(resource.getResourceName(),
- // ComponentTypeEnum.RESOURCE, modifier, owner, oldState);
- // if (stateValidationResult.isRight()) {
- // errorResponse = stateValidationResult.right().value();
- // componentUtils.auditResource(errorResponse, modifier, resource,
- // resourceCurrState.name(), resourceCurrVersion,
- // lifeCycleTransition.getAuditingAction(), null);
- // return Either.right(errorResponse);
- // }
- //
- // operationResult = lifeCycleTransition.changeStateOperation(resource,
- // modifier, owner, inTransaction);
- //
- // if (operationResult.isRight()) {
- // errorResponse = operationResult.right().value();
- // log.debug("audit before sending response");
- // componentUtils.auditResource(errorResponse, modifier, resource,
- // resourceCurrState.name(), resourceCurrVersion,
- // lifeCycleTransition.getAuditingAction(), null);
- //
- // return Either.right(errorResponse);
- // }
- // Resource resourceAfterOperation = operationResult.left().value();
- // EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new
- // EnumMap<AuditingFieldsKeysEnum,
- // Object>(AuditingFieldsKeysEnum.class);
- // auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT,
- // changeInfo.getUserRemarks());
- // componentUtils.auditResource(componentUtils.getResponseFormat(ActionStatus.OK),
- // modifier, resourceAfterOperation, resourceCurrState.name(),
- // resourceCurrVersion, lifeCycleTransition.getAuditingAction(),
- // auditingFields);
- // return operationResult;
- //
- // } finally {
- // log.debug("unlock resource {}", resourceId);
- // if (needToUnlockResource && resource != null) {
- // resource.setUniqueId(resourceId);
- // graphLockOperation.unlockResource(resource);
- // }
- // }
-
+ }
+
+ private boolean isComponentVFCMT(Component component, ComponentTypeEnum componentType){
+ if (componentType.equals(ComponentTypeEnum.RESOURCE)){
+ ResourceTypeEnum resourceType = ((ResourceMetadataDataDefinition)component.getComponentMetadataDefinition().getMetadataDataDefinition()).getResourceType();
+ if (resourceType.equals(ResourceTypeEnum.VFCMT)){
+ return true;
+ }
+ }
+ return false;
}
public Either<? extends Component, ResponseFormat> changeComponentState(ComponentTypeEnum componentType, String componentId, User modifier, LifeCycleTransitionEnum transitionEnum, LifecycleChangeInfoWithAction changeInfo, boolean inTransaction,
@@ -309,12 +192,8 @@ public class LifecycleBusinessLogic {
ResponseFormat error = componentUtils.getInvalidContentErrorAndAudit(modifier, AuditingActionEnum.CHECKOUT_RESOURCE);
return Either.right(error);
}
- ComponentBusinessLogic bl = getComponentBL(componentType);
-
- Either<? extends Component, ResponseFormat> operationResult = null;
Component component = null;
- // boolean needToUnlockResource = false;
- log.debug("get resource from graph");
+ log.info("get resource from graph");
ResponseFormat errorResponse;
Either<? extends Component, ResponseFormat> eitherResourceResponse = getComponentForChange(componentType, componentId, modifier, lifeCycleTransition, changeInfo);
@@ -325,110 +204,133 @@ public class LifecycleBusinessLogic {
String resourceCurrVersion = component.getVersion();
LifecycleStateEnum resourceCurrState = component.getLifecycleState();
+ log.info("lock component {}", componentId);
// lock resource
if (inTransaction == false && needLock) {
Either<Boolean, ResponseFormat> eitherLockResource = lockComponent(componentType, component);
if (eitherLockResource.isRight()) {
errorResponse = eitherLockResource.right().value();
componentUtils.auditComponent(errorResponse, modifier, component, resourceCurrState.name(), resourceCurrVersion, lifeCycleTransition.getAuditingAction(), componentType, null);
+ log.error("lock component {} failed", componentId);
return Either.right(errorResponse);
}
- // needToUnlockResource = true;
}
+ log.info("after lock component {}", componentId);
try {
Either<String, ResponseFormat> commentValidationResult = validateComment(changeInfo, transitionEnum);
if (commentValidationResult.isRight()) {
errorResponse = commentValidationResult.right().value();
- EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
+ EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class);
auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT, changeInfo.getUserRemarks());
componentUtils.auditComponent(errorResponse, modifier, component, resourceCurrState.name(), resourceCurrVersion, lifeCycleTransition.getAuditingAction(), componentType, auditingFields);
return Either.right(errorResponse);
}
changeInfo.setUserRemarks(commentValidationResult.left().value());
-
+ log.info("after validate component");
Either<Boolean, ResponseFormat> validateHighestVersion = validateHighestVersion(modifier, lifeCycleTransition, component, resourceCurrVersion, componentType);
if (validateHighestVersion.isRight()) {
return Either.right(validateHighestVersion.right().value());
}
-
- Either<User, ResponseFormat> ownerResult = lifeCycleTransition.getComponentOwner(component, componentType, inTransaction);
- if (ownerResult.isRight()) {
- return Either.right(ownerResult.right().value());
- }
- User owner = ownerResult.left().value();
- log.debug("owner of resource {} is {}", component.getUniqueId(), owner.getUserId());
-
- LifecycleStateEnum oldState = component.getLifecycleState();
-
- Either<Boolean, ResponseFormat> stateValidationResult = lifeCycleTransition.validateBeforeTransition(component, componentType, modifier, owner, oldState, changeInfo);
- if (stateValidationResult.isRight()) {
- errorResponse = stateValidationResult.right().value();
- EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT, changeInfo.getUserRemarks());
- componentUtils.auditComponent(errorResponse, modifier, component, resourceCurrState.name(), resourceCurrVersion, lifeCycleTransition.getAuditingAction(), componentType, auditingFields);
- return Either.right(errorResponse);
-
- }
-
- operationResult = lifeCycleTransition.changeState(componentType, component, bl, modifier, owner, false, inTransaction);
-
- if (operationResult.isRight()) {
- errorResponse = operationResult.right().value();
- log.debug("audit before sending response");
- componentUtils.auditComponentAdmin(errorResponse, modifier, component, resourceCurrState.name(), resourceCurrVersion, lifeCycleTransition.getAuditingAction(), componentType);
-
- return Either.right(errorResponse);
+ log.info("after validate Highest Version");
+ if (isComponentVFCMT(component,componentType)){
+ Either<? extends Component, ResponseFormat> changeVFCMTStateResponse = changeVFCMTState(componentType, modifier, transitionEnum, changeInfo, inTransaction, component);
+ if (changeVFCMTStateResponse.isRight()){
+ return changeVFCMTStateResponse;
+ }
}
- Component resourceAfterOperation = operationResult.left().value();
- EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT, changeInfo.getUserRemarks());
- componentUtils.auditComponent(componentUtils.getResponseFormat(ActionStatus.OK), modifier, resourceAfterOperation, resourceCurrState.name(), resourceCurrVersion, lifeCycleTransition.getAuditingAction(), componentType, auditingFields);
- return operationResult;
+ return changeState(component, lifeCycleTransition, componentType, modifier, changeInfo, inTransaction);
} finally {
- log.debug("unlock component {}", componentId);
+ log.info("unlock component {}", componentId);
if (inTransaction == false && needLock && component != null) {
component.setUniqueId(componentId);
NodeTypeEnum nodeType = componentType.getNodeType();
+ log.info("During change state, another component {} has been created/updated", componentId);
+ graphLockOperation.unlockComponent(componentId, nodeType);
- // Handle component change in the cache of the side affect of
- // the operation
- if (operationResult != null && operationResult.isLeft()) {
- Component componentAfterOpertion = operationResult.left().value();
- String uniqueId = componentAfterOpertion.getUniqueId();
- if (false == componentId.equals(uniqueId)) {
- log.debug("During change state, another component {} has been created/updated", uniqueId);
- if (uniqueId != null) {
- cacheManagerOperation.updateComponentInCache(uniqueId, componentAfterOpertion.getLastUpdateDate(), nodeType);
- }
- }
- }
+ }
+ }
- graphLockOperation.unlockComponent(componentId, nodeType);
+ }
+ /*
+ * special case for certification of VFCMT - VFCMT can be certified by Designer or Tester right after checkin
+ * in case the operation "submit for test" / "start testing" is done to "VFCMT" - please return error 400
+ */
+ private Either<? extends Component, ResponseFormat> changeVFCMTState(ComponentTypeEnum componentType, User modifier,
+ LifeCycleTransitionEnum transitionEnum, LifecycleChangeInfoWithAction changeInfo, boolean inTransaction,
+ Component component) {
+ LifecycleStateEnum oldState = component.getLifecycleState();
+ if (transitionEnum.equals(LifeCycleTransitionEnum.START_CERTIFICATION) ||
+ transitionEnum.equals(LifeCycleTransitionEnum.CERTIFICATION_REQUEST)){
+ return Either.right(componentUtils.getResponseFormat(
+ ActionStatus.RESOURCE_VFCMT_LIFECYCLE_STATE_NOT_VALID, transitionEnum.getDisplayName()));
+ } //certify is done directly from checkin
+ else if (transitionEnum.equals(LifeCycleTransitionEnum.CERTIFY) && oldState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN)){
+ //we will call for submit for testing first and then for certify
+ Either<? extends Component, ResponseFormat> actionResponse = changeState(component,
+ stateTransitions.get(LifeCycleTransitionEnum.CERTIFICATION_REQUEST.name()),
+ componentType, modifier, changeInfo, inTransaction);
+ if (actionResponse.isRight()) {
+ return actionResponse;
}
+ actionResponse = changeState(component,
+ stateTransitions.get(LifeCycleTransitionEnum.START_CERTIFICATION.name()),
+ componentType, modifier, changeInfo, inTransaction);
+ if (actionResponse.isRight()) {
+ return actionResponse;
+ }
}
+ return Either.left(null);
+ }
+
+ private Either<? extends Component, ResponseFormat> changeState(Component component, LifeCycleTransition lifeCycleTransition,
+ ComponentTypeEnum componentType, User modifier, LifecycleChangeInfoWithAction changeInfo,boolean inTransaction){
+ ResponseFormat errorResponse;
+
+ LifecycleStateEnum oldState = component.getLifecycleState();
+ String resourceCurrVersion = component.getVersion();
+ ComponentBusinessLogic bl = getComponentBL(componentType);
+
+ Either<User, ResponseFormat> ownerResult = lifeCycleTransition.getComponentOwner(component, componentType, inTransaction);
+ if (ownerResult.isRight()) {
+ return Either.right(ownerResult.right().value());
+ }
+ User owner = ownerResult.left().value();
+ log.info("owner of resource {} is {}", component.getUniqueId(), owner.getUserId());
+
+ Either<Boolean, ResponseFormat> stateValidationResult = lifeCycleTransition.validateBeforeTransition(component, componentType, modifier, owner, oldState, changeInfo);
+ if (stateValidationResult.isRight()) {
+ log.error("Failed to validateBeforeTransition");
+ errorResponse = stateValidationResult.right().value();
+ EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT, changeInfo.getUserRemarks());
+ componentUtils.auditComponent(errorResponse, modifier, component, oldState.name(), resourceCurrVersion, lifeCycleTransition.getAuditingAction(), componentType, auditingFields);
+ return Either.right(errorResponse);
+ }
+
+ Either<? extends Component, ResponseFormat> operationResult = lifeCycleTransition.changeState(componentType, component, bl, modifier, owner, false, inTransaction);
+
+ if (operationResult.isRight()) {
+ errorResponse = operationResult.right().value();
+ log.info("audit before sending error response");
+ componentUtils.auditComponentAdmin(errorResponse, modifier, component, oldState.name(), resourceCurrVersion, lifeCycleTransition.getAuditingAction(), componentType);
+
+ return Either.right(errorResponse);
+ }
+ Component resourceAfterOperation = operationResult.left().value();
+ EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT, changeInfo.getUserRemarks());
+ componentUtils.auditComponent(componentUtils.getResponseFormat(ActionStatus.OK), modifier, resourceAfterOperation, oldState.name(), resourceCurrVersion, lifeCycleTransition.getAuditingAction(), componentType, auditingFields);
+ return operationResult;
}
private Either<? extends Component, ResponseFormat> getComponentForChange(ComponentTypeEnum componentType, String componentId, User modifier, LifeCycleTransition lifeCycleTransition, LifecycleChangeInfoWithAction changeInfo) {
- Either<? extends Component, StorageOperationStatus> eitherResourceResponse = Either.right(StorageOperationStatus.GENERAL_ERROR);
- switch (componentType) {
- case SERVICE:
- eitherResourceResponse = serviceOperation.getComponent(componentId, true);
- break;
- case PRODUCT:
- eitherResourceResponse = productOperation.getComponent(componentId, true);
- break;
- case RESOURCE:
- eitherResourceResponse = resourceOperation.getComponent(componentId, true);
- break;
- default:
- break;
- }
+ Either<? extends Component, StorageOperationStatus> eitherResourceResponse = toscaOperationFacade.getToscaElement(componentId);
- ResponseFormat errorResponse = null;
+ ResponseFormat errorResponse;
if (eitherResourceResponse.isRight()) {
ActionStatus actionStatus = componentUtils.convertFromStorageResponse(eitherResourceResponse.right().value(), componentType);
errorResponse = componentUtils.getResponseFormat(actionStatus, Constants.EMPTY_STRING);
@@ -494,28 +396,6 @@ public class LifecycleBusinessLogic {
}
- private Either<Resource, ResponseFormat> getResourceForChange(String resourceId, User modifier, LifeCycleTransition lifeCycleTransition) {
- Either<Resource, StorageOperationStatus> eitherResourceResponse = resourceOperation.getResource(resourceId, true);
-
- ResponseFormat errorResponse = null;
- if (eitherResourceResponse.isRight()) {
- ActionStatus actionStatus = componentUtils.convertFromStorageResponse(eitherResourceResponse.right().value());
- errorResponse = componentUtils.getResponseFormatByResource(actionStatus, "");
- log.debug("audit before sending response");
- // For audit of not found, resourceName should be uniqueID according
- // to Ella
- EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceId);
- componentUtils.auditResource(errorResponse, modifier, null, "", "", lifeCycleTransition.getAuditingAction(), null);
-
- return Either.right(errorResponse);
- }
- Resource resource = eitherResourceResponse.left().value();
-
- return Either.left(resource);
-
- }
-
private Either<String, ResponseFormat> validateComment(LifecycleChangeInfoWithAction changeInfo, LifeCycleTransitionEnum transitionEnum) {
String comment = changeInfo.getUserRemarks();
if (LifeCycleTransitionEnum.CANCEL_CERTIFICATION == transitionEnum || LifeCycleTransitionEnum.CERTIFY == transitionEnum || LifeCycleTransitionEnum.FAIL_CERTIFICATION == transitionEnum || LifeCycleTransitionEnum.CHECKIN == transitionEnum
@@ -548,25 +428,39 @@ public class LifecycleBusinessLogic {
private ComponentBusinessLogic getComponentBL(ComponentTypeEnum componentTypeEnum) {
ComponentBusinessLogic businessLogic;
switch (componentTypeEnum) {
- case RESOURCE: {
- businessLogic = this.resourceBusinessLogic;
- break;
- }
- case SERVICE: {
- businessLogic = this.serviceBusinessLogic;
- break;
- }
- case PRODUCT: {
- businessLogic = this.productBusinessLogic;
- break;
- }
-
- default: {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "getComponentBL");
- throw new IllegalArgumentException("Illegal component type:" + componentTypeEnum.getValue());
- }
+ case RESOURCE: {
+ businessLogic = this.resourceBusinessLogic;
+ break;
+ }
+ case SERVICE: {
+ businessLogic = this.serviceBusinessLogic;
+ break;
+ }
+ case PRODUCT: {
+ businessLogic = this.productBusinessLogic;
+ break;
+ }
+
+ default: {
+ BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "getComponentBL");
+ throw new IllegalArgumentException("Illegal component type:" + componentTypeEnum.getValue());
+ }
}
return businessLogic;
}
+
+ public Either<Component, ResponseFormat> getLatestComponentByUuid(ComponentTypeEnum componentTypeEnum, String uuid) {
+
+ Either<Component, StorageOperationStatus> latestVersionEither = toscaOperationFacade.getLatestComponentByUuid(uuid);
+
+ if (latestVersionEither.isRight()) {
+
+ return Either.right(componentUtils.getResponseFormat(componentUtils.convertFromStorageResponse(latestVersionEither.right().value(), componentTypeEnum), uuid));
+ }
+
+ Component latestComponent = latestVersionEither.left().value();
+
+ return Either.left(latestComponent);
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/StartCertificationTransition.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/StartCertificationTransition.java
index 918140b0af..8a80e0bb64 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/StartCertificationTransition.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/StartCertificationTransition.java
@@ -22,15 +22,23 @@ package org.openecomp.sdc.be.components.lifecycle;
import java.util.Arrays;
+import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;
import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic;
+import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.model.Component;
import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
import org.openecomp.sdc.be.model.LifecycleStateEnum;
import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaElementLifecycleOperation;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
+import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
import org.openecomp.sdc.be.model.operations.api.ILifecycleOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
@@ -45,14 +53,18 @@ public class StartCertificationTransition extends LifeCycleTransition {
private static Logger log = LoggerFactory.getLogger(StartCertificationTransition.class.getName());
- public StartCertificationTransition(ComponentsUtils componentUtils, ILifecycleOperation lifecycleOperation) {
- super(componentUtils, lifecycleOperation);
+ public StartCertificationTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) {
+ super(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao);
// authorized roles
Role[] rsrcServiceStartCertificationRoles = { Role.ADMIN, Role.TESTER };
addAuthorizedRoles(ComponentTypeEnum.RESOURCE, Arrays.asList(rsrcServiceStartCertificationRoles));
addAuthorizedRoles(ComponentTypeEnum.SERVICE, Arrays.asList(rsrcServiceStartCertificationRoles));
// TODO to be later defined for product
+
+ //additional authorized roles for resource type
+ Role[] resourceRoles = { Role.DESIGNER};
+ addResouceAuthorizedRoles(ResourceTypeEnum.VFCMT, Arrays.asList(resourceRoles));
}
@Override
@@ -69,22 +81,38 @@ public class StartCertificationTransition extends LifeCycleTransition {
public Either<? extends Component, ResponseFormat> changeState(ComponentTypeEnum componentType, Component component, ComponentBusinessLogic componentBl, User modifier, User owner, boolean shouldLock, boolean inTransaction) {
log.debug("start performing certification test for resource {}", component.getUniqueId());
-
- NodeTypeEnum nodeType = (componentType.equals(ComponentTypeEnum.SERVICE)) ? NodeTypeEnum.Service : NodeTypeEnum.Resource;
- Either<? extends Component, StorageOperationStatus> stateChangeResult = lifeCycleOperation.startComponentCertification(nodeType, component, modifier, owner, inTransaction);
- if (stateChangeResult.isRight()) {
- log.debug("start certification failed on graph");
- StorageOperationStatus response = stateChangeResult.right().value();
- ActionStatus actionStatus = componentUtils.convertFromStorageResponse(response);
-
- if (response.equals(StorageOperationStatus.ENTITY_ALREADY_EXISTS)) {
- actionStatus = ActionStatus.COMPONENT_VERSION_ALREADY_EXIST;
+ Either<? extends Component, ResponseFormat> result = null;
+ try{
+ Either<ToscaElement, StorageOperationStatus> stateChangeResult = lifeCycleOperation.startCertificationToscaElement(component.getUniqueId(), modifier.getUserId(), owner.getUserId());
+ if (stateChangeResult.isRight()) {
+ log.debug("start certification failed on graph");
+ StorageOperationStatus response = stateChangeResult.right().value();
+ ActionStatus actionStatus = componentUtils.convertFromStorageResponse(response);
+
+ if (response.equals(StorageOperationStatus.ENTITY_ALREADY_EXISTS)) {
+ actionStatus = ActionStatus.COMPONENT_VERSION_ALREADY_EXIST;
+ }
+ ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType);
+ result = Either.right(responseFormat);
+ }
+ else {
+ result = Either.left(ModelConverter.convertFromToscaElement(stateChangeResult.left().value()));
+ }
+ } finally {
+ if (result == null || result.isRight()) {
+ BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState");
+ if (inTransaction == false) {
+ log.debug("operation failed. do rollback");
+ titanDao.rollback();
+ }
+ } else {
+ if (inTransaction == false) {
+ log.debug("operation success. do commit");
+ titanDao.commit();
+ }
}
- ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType);
- return Either.right(responseFormat);
}
-
- return Either.left(stateChangeResult.left().value());
+ return result;
}
@Override
@@ -93,11 +121,11 @@ public class StartCertificationTransition extends LifeCycleTransition {
log.debug("validate before start certification test. resource name={}, oldState={}, owner userId={}", componentName, oldState, owner.getUserId());
// validate user
- Either<Boolean, ResponseFormat> userValidationResponse = userRoleValidation(modifier, componentType, lifecycleChangeInfo);
+ Either<Boolean, ResponseFormat> userValidationResponse = userRoleValidation(modifier,component, componentType, lifecycleChangeInfo);
if (userValidationResponse.isRight()) {
return userValidationResponse;
}
-
+
if (oldState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN) || oldState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) {
ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_NOT_READY_FOR_CERTIFICATION, componentName, componentType.name().toLowerCase());
return Either.right(error);
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/UndoCheckoutTransition.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/UndoCheckoutTransition.java
index fcb211bc3e..277cd173aa 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/UndoCheckoutTransition.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/UndoCheckoutTransition.java
@@ -21,25 +21,24 @@
package org.openecomp.sdc.be.components.lifecycle;
import java.util.Arrays;
-import java.util.List;
-
import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;
import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.model.ArtifactDefinition;
import org.openecomp.sdc.be.model.Component;
import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
import org.openecomp.sdc.be.model.LifecycleStateEnum;
import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.be.model.operations.api.ILifecycleOperation;
+import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaElementLifecycleOperation;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
+import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
import org.openecomp.sdc.be.user.Role;
-import org.openecomp.sdc.common.config.EcompErrorName;
import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -50,8 +49,8 @@ public class UndoCheckoutTransition extends LifeCycleTransition {
private static Logger log = LoggerFactory.getLogger(CheckoutTransition.class.getName());
private ArtifactsBusinessLogic artifactsManager;
- public UndoCheckoutTransition(ComponentsUtils componentUtils, ILifecycleOperation lifecycleOperation) {
- super(componentUtils, lifecycleOperation);
+ public UndoCheckoutTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) {
+ super(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao);
// authorized roles
Role[] resourceServiceCheckoutRoles = { Role.ADMIN, Role.DESIGNER };
@@ -86,7 +85,7 @@ public class UndoCheckoutTransition extends LifeCycleTransition {
log.debug("validate before undo checkout. resource name={}, oldState={}, owner userId={}", componentName, oldState, owner.getUserId());
// validate user
- Either<Boolean, ResponseFormat> userValidationResponse = userRoleValidation(modifier, componentType, lifecycleChangeInfo);
+ Either<Boolean, ResponseFormat> userValidationResponse = userRoleValidation(modifier,component, componentType, lifecycleChangeInfo);
if (userValidationResponse.isRight()) {
return userValidationResponse;
}
@@ -111,59 +110,29 @@ public class UndoCheckoutTransition extends LifeCycleTransition {
Either<? extends Component, ResponseFormat> result = null;
log.debug("start performing undo-checkout for resource {}", component.getUniqueId());
- Either<List<ArtifactDefinition>, StorageOperationStatus> artifactsRes = lifeCycleOperation.getComponentOperation(componentType.getNodeType()).getComponentArtifactsForDelete(component.getUniqueId(), componentType.getNodeType(), true);
- if (artifactsRes.isRight()) {
- ActionStatus actionStatus = componentUtils.convertFromStorageResponse(artifactsRes.right().value());
- ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType);
- result = Either.right(responseFormat);
- return result;
- }
- // TODO - start transaction
try {
- NodeTypeEnum nodeType = componentType.getNodeType();
-
- // 1. perform undo checkout on graph (update status and delete
- // current version)
- Either<? extends Component, StorageOperationStatus> undoCheckoutResourceResult = lifeCycleOperation.undoCheckout(nodeType, component, modifier, owner, true);
+ Either<ToscaElement, StorageOperationStatus> undoCheckoutResourceResult = lifeCycleOperation.undoCheckout(component.getUniqueId());
if (undoCheckoutResourceResult.isRight()) {
log.debug("checkout failed on graph");
StorageOperationStatus response = undoCheckoutResourceResult.right().value();
ActionStatus actionStatus = componentUtils.convertFromStorageResponse(response);
ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType);
- result = Either.right(responseFormat);
- return result;
+ result = Either.right(responseFormat);
}
-
- // 2. delete unrelated artifacts
- // use artifacts API to delete artifacts from swift / elasticsearch
-
- if (artifactsRes.left().value() != null) {
- List<ArtifactDefinition> artifacts = artifactsRes.left().value();
- StorageOperationStatus deleteAllResourceArtifacts = artifactsManager.deleteAllComponentArtifactsIfNotOnGraph(artifacts);
-
- if (!deleteAllResourceArtifacts.equals(StorageOperationStatus.OK)) {
- ActionStatus actionStatus = componentUtils.convertFromStorageResponse(deleteAllResourceArtifacts);
- ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType);
- result = Either.right(responseFormat);
- return result;
- }
+ else {
+ result = Either.left(ModelConverter.convertFromToscaElement(undoCheckoutResourceResult.left().value()));
}
-
- result = Either.left(undoCheckoutResourceResult.left().value());
} finally {
if (result == null || result.isRight()) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError, "Change LifecycleState - Undo Checkout failed on graph");
BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState - Undo Checkout failed on graph");
-
log.debug("operation failed. do rollback");
- lifeCycleOperation.getResourceOperation().getTitanGenericDao().rollback();
+ titanDao.rollback();
} else {
log.debug("operation success. do commit");
- lifeCycleOperation.getResourceOperation().getTitanGenericDao().commit();
+ titanDao.commit();
}
}
-
return result;
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/api/CategoryTypeEnum.java b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/api/CategoryTypeEnum.java
index edfe56ebfa..921aefaa8e 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/api/CategoryTypeEnum.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/api/CategoryTypeEnum.java
@@ -24,7 +24,7 @@ import java.io.Serializable;
public enum CategoryTypeEnum implements Serializable {
- CATEGORY("category"), SUBCATEGORY("sub-category"), GROUPING("grouping");
+ CATEGORY("category"), SUBCATEGORY("subcategory"), GROUPING("grouping");
private String value;
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/UiComponentDataConverter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/UiComponentDataConverter.java
new file mode 100644
index 0000000000..46505b843e
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/UiComponentDataConverter.java
@@ -0,0 +1,218 @@
+package org.openecomp.sdc.be.datamodel.utils;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+
+import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition;
+import org.openecomp.sdc.be.datatypes.components.ServiceMetadataDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.ComponentFieldsEnum;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer;
+import org.openecomp.sdc.be.ui.model.UiResourceDataTransfer;
+import org.openecomp.sdc.be.ui.model.UiResourceMetadata;
+import org.openecomp.sdc.be.ui.model.UiServiceDataTransfer;
+import org.openecomp.sdc.be.ui.model.UiServiceMetadata;
+
+public class UiComponentDataConverter {
+
+ public static void setUiTranferDataByFieldName(UiComponentDataTransfer dataTransfer, Component component, String fieldName) {
+
+ switch (ComponentFieldsEnum.findByValue(fieldName)) {
+
+ case INPUTS:
+ if(component.getInputs() == null){
+ dataTransfer.setInputs(new ArrayList<>());
+ } else {
+ dataTransfer.setInputs(component.getInputs());
+ }
+ break;
+
+ case COMPONENT_INSTANCE_RELATION:
+ if(component.getComponentInstancesRelations() == null){
+ dataTransfer.setComponentInstancesRelations(new ArrayList<>());
+ } else {
+ dataTransfer.setComponentInstancesRelations(component.getComponentInstancesRelations());
+ }
+
+ break;
+
+ case GROUPS:
+ if(component.getGroups() == null){
+ dataTransfer.setGroups(new ArrayList<>());
+ } else {
+ dataTransfer.setGroups(component.getGroups());
+ }
+ break;
+
+ case COMPONENT_INSTANCES:
+ if(component.getComponentInstances() == null) {
+ dataTransfer.setComponentInstances(new ArrayList<>());
+ } else {
+ dataTransfer.setComponentInstances(component.getComponentInstances());
+ }
+ break;
+
+ case COMPONENT_INSTANCES_PROPERTIES:
+ if(component.getComponentInstancesProperties() == null) {
+ dataTransfer.setComponentInstancesProperties(new HashMap<>());
+ } else {
+ dataTransfer.setComponentInstancesProperties(component.getComponentInstancesProperties());
+ }
+ break;
+
+ case CAPABILITIES:
+ if(component.getCapabilities() == null) {
+ dataTransfer.setCapabilities(new HashMap<>());
+ } else {
+ dataTransfer.setCapabilities(component.getCapabilities());
+ }
+ break;
+
+ case REQUIREMENTS:
+ if(component.getRequirements() == null) {
+ dataTransfer.setRequirements(new HashMap<>());
+ } else {
+ dataTransfer.setRequirements(component.getRequirements());
+ }
+ break;
+
+ case DEPLOYMENT_ARTIFACTS:
+ if(component.getDeploymentArtifacts() == null) {
+ dataTransfer.setDeploymentArtifacts(new HashMap<>());
+ } else {
+ dataTransfer.setDeploymentArtifacts(component.getDeploymentArtifacts());
+ }
+ break;
+
+ case TOSCA_ARTIFACTS:
+ if(component.getToscaArtifacts() == null) {
+ dataTransfer.setToscaArtifacts(new HashMap<>());
+ } else {
+ dataTransfer.setToscaArtifacts(component.getToscaArtifacts());
+ }
+ break;
+
+ case ARTIFACTS:
+ if(component.getArtifacts() == null) {
+ dataTransfer.setArtifacts(new HashMap<>());
+ } else {
+ dataTransfer.setArtifacts(component.getArtifacts());
+ }
+ break;
+
+ case COMPONENT_INSTANCES_ATTRIBUTES:
+ if(component.getComponentInstancesAttributes() == null) {
+ dataTransfer.setComponentInstancesAttributes(new HashMap<>());
+ } else {
+ dataTransfer.setComponentInstancesAttributes(component.getComponentInstancesAttributes());
+ }
+ break;
+
+ case COMPONENT_INSTANCE_INPUTS:
+ if(component.getComponentInstancesInputs() == null) {
+ dataTransfer.setComponentInstancesInputs(new HashMap<>());
+ } else {
+ dataTransfer.setComponentInstancesInputs(component.getComponentInstancesInputs());
+ }
+
+ break;
+
+
+ default:
+ break;
+ }
+
+ }
+
+
+ public static UiComponentDataTransfer getUiDataTransferFromResourceByParams(Resource resource, List<String> paramsToReturn) {
+ UiResourceDataTransfer dataTransfer = new UiResourceDataTransfer();
+
+ for(String fieldName: paramsToReturn){
+
+ switch (ComponentFieldsEnum.findByValue(fieldName)) {
+
+ case PROPERTIES:
+ if(resource.getProperties() == null) {
+ dataTransfer.setProperties(new ArrayList<>());
+ } else {
+ dataTransfer.setProperties(resource.getProperties());
+ }
+ break;
+
+ case INTERFACES:
+ if(resource.getInterfaces() == null) {
+ dataTransfer.setInterfaces(new HashMap<>());
+ } else {
+ dataTransfer.setInterfaces(resource.getInterfaces());
+ }
+ break;
+
+ case DERIVED_FROM:
+ if(resource.getDerivedFrom() == null) {
+ dataTransfer.setDerivedFrom(new ArrayList<>());
+ } else {
+ dataTransfer.setDerivedFrom(resource.getDerivedFrom());
+ }
+ break;
+
+ case ATTRIBUTES:
+ if(resource.getAttributes() == null) {
+ dataTransfer.setAttributes(new ArrayList<>());
+ } else {
+ dataTransfer.setAttributes(resource.getAttributes());
+ }
+ break;
+
+ case ADDITIONAL_INFORMATION:
+ if(resource.getAdditionalInformation() == null) {
+ dataTransfer.setAdditionalInformation(new ArrayList<>());
+ } else {
+ dataTransfer.setAdditionalInformation(resource.getAdditionalInformation());
+ }
+ break;
+ case METADATA:
+ UiResourceMetadata metadata = new UiResourceMetadata(resource.getCategories(), resource.getDerivedFrom(), (ResourceMetadataDataDefinition) resource.getComponentMetadataDefinition().getMetadataDataDefinition());
+ dataTransfer.setMetadata(metadata);
+ break;
+
+ default:
+ setUiTranferDataByFieldName(dataTransfer, resource, fieldName);
+ }
+ }
+
+ return dataTransfer;
+ }
+
+ public static UiComponentDataTransfer getUiDataTransferFromServiceByParams(Service service, List<String> paramsToReturn) {
+ UiServiceDataTransfer dataTransfer = new UiServiceDataTransfer();
+
+ for(String fieldName: paramsToReturn){
+
+ switch (ComponentFieldsEnum.findByValue(fieldName)) {
+
+ case SERVICE_API_ARTIFACTS:
+ if(service.getServiceApiArtifacts() == null) {
+ dataTransfer.setServiceApiArtifacts(new HashMap<>());
+ } else {
+ dataTransfer.setServiceApiArtifacts(service.getServiceApiArtifacts());
+ }
+
+ break;
+
+ case METADATA:
+ UiServiceMetadata metadata = new UiServiceMetadata(service.getCategories(), (ServiceMetadataDataDefinition) service.getComponentMetadataDefinition().getMetadataDataDefinition());
+ dataTransfer.setMetadata(metadata);
+ break;
+ default:
+ setUiTranferDataByFieldName(dataTransfer, service, fieldName);
+ }
+ }
+
+ return dataTransfer;
+ }
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/EcompIntImpl.java b/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/EcompIntImpl.java
index 5670239ef7..7b49d3fcea 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/EcompIntImpl.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/EcompIntImpl.java
@@ -25,6 +25,10 @@ import java.util.List;
import javax.servlet.http.HttpServletRequest;
+import org.openecomp.portalsdk.core.onboarding.crossapi.IPortalRestAPIService;
+import org.openecomp.portalsdk.core.onboarding.crossapi.PortalAPIException;
+import org.openecomp.portalsdk.core.restful.domain.EcompRole;
+import org.openecomp.portalsdk.core.restful.domain.EcompUser;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
import org.openecomp.sdc.be.dao.api.ActionStatus;
@@ -39,11 +43,6 @@ import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.ContextLoader;
-import org.openecomp.portalsdk.core.onboarding.crossapi.IPortalRestAPIService;
-import org.openecomp.portalsdk.core.onboarding.crossapi.PortalAPIException;
-import org.openecomp.portalsdk.core.restful.domain.EcompRole;
-import org.openecomp.portalsdk.core.restful.domain.EcompUser;
-
import fj.data.Either;
/*
@@ -76,7 +75,7 @@ public class EcompIntImpl implements IPortalRestAPIService {
Either<User, String> newASDCUser = EcompUserConverter.convertEcompUserToUser(user);
if (newASDCUser.isRight()) {
BeEcompErrorManager.getInstance().logInvalidInputError("PushUser", "Failed to convert user", ErrorSeverity.INFO);
- log.debug("Failed to create user {}",user.toString());
+ log.debug("Failed to create user {}", user.toString());
throw new PortalAPIException("Failed to create user " + newASDCUser.right().value());
} else if (newASDCUser.left().value() == null) {
BeEcompErrorManager.getInstance().logInvalidInputError("PushUser", "NULL pointer returned from user converter", ErrorSeverity.INFO);
@@ -292,23 +291,29 @@ public class EcompIntImpl implements IPortalRestAPIService {
String updatedRole = null;
if (roles == null) {
- throw new PortalAPIException("Error: Recieved null for roles");
+ throw new PortalAPIException("Error: Recieved null for roles");
} else if (roles.iterator().hasNext()) {
EcompRole ecompRole = roles.iterator().next();
updatedRole = EcompRoleConverter.convertEcompRoleToRole(ecompRole);
log.debug("pushing role: {} to user: {}", updatedRole, loginId);
+ Either<User, ResponseFormat> updateUserRoleResponse = userBusinessLogic.updateUserRole(modifier, loginId, updatedRole);
+ if (updateUserRoleResponse.isRight()) {
+ log.debug("Error: Failed to update role");
+ BeEcompErrorManager.getInstance().logInvalidInputError("PushUserRole", "Failed to update role", ErrorSeverity.INFO);
+ throw new PortalAPIException("Failed to update role" + updateUserRoleResponse.right().value().toString());
+ }
} else {
log.debug("Error: No roles in List");
BeEcompErrorManager.getInstance().logInvalidInputError("PushUserRole", "Failed to fetch roles", ErrorSeverity.INFO);
- throw new PortalAPIException("Error: No roles in List");
- }
-
- Either<User, ResponseFormat> updateUserRoleResponse = userBusinessLogic.updateUserRole(modifier, loginId, updatedRole);
- if (updateUserRoleResponse.isRight()) {
- log.debug("Error: Failed to update role");
- BeEcompErrorManager.getInstance().logInvalidInputError("PushUserRole", "Failed to update role", ErrorSeverity.INFO);
- throw new PortalAPIException("Failed to update role" + updateUserRoleResponse.right().value().toString());
- }
+ //throw new PortalAPIException("Error: No roles in List");
+ //in this cases we want to deactivate the user
+ Either<User, ResponseFormat> deActivateUserResponse = userBusinessLogic.deActivateUser(modifier, loginId);
+ if (deActivateUserResponse.isRight()) {
+ log.debug("Error: Failed to deactivate user {}",loginId);
+ BeEcompErrorManager.getInstance().logInvalidInputError("PushUserRole", "Failed to deactivate user", ErrorSeverity.INFO);
+ throw new PortalAPIException(deActivateUserResponse.right().value().getFormattedMessage());
+ }
+ }
}
@Override
@@ -359,7 +364,7 @@ public class EcompIntImpl implements IPortalRestAPIService {
if (USERNAME != null && PASSWORD != null) {
if (!USERNAME.equals("") && !PASSWORD.equals("")) {
- log.debug("User authenticated - Username: {} Password: {}", USERNAME, PASSWORD);
+ log.debug("User authenticated - Username: ,Password: {}", USERNAME, PASSWORD);
return true;
}
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/EcompRoleConverter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/EcompRoleConverter.java
index ca970ce45f..4ee3605703 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/EcompRoleConverter.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/EcompRoleConverter.java
@@ -20,12 +20,11 @@
package org.openecomp.sdc.be.ecomp.converters;
+import org.openecomp.portalsdk.core.restful.domain.EcompRole;
import org.openecomp.sdc.be.user.Role;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.openecomp.portalsdk.core.restful.domain.EcompRole;
-
public final class EcompRoleConverter {
private static Logger log = LoggerFactory.getLogger(EcompRoleConverter.class.getName());
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/EcompUserConverter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/EcompUserConverter.java
index e83b53c2a4..19ef31feaf 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/EcompUserConverter.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/EcompUserConverter.java
@@ -24,13 +24,12 @@ import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
+import org.openecomp.portalsdk.core.restful.domain.EcompRole;
+import org.openecomp.portalsdk.core.restful.domain.EcompUser;
import org.openecomp.sdc.be.dao.utils.UserStatusEnum;
import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.user.Role;
-import org.openecomp.portalsdk.core.restful.domain.EcompRole;
-import org.openecomp.portalsdk.core.restful.domain.EcompUser;
-
import fj.data.Either;
public final class EcompUserConverter {
@@ -38,13 +37,6 @@ public final class EcompUserConverter {
private EcompUserConverter() {
}
- // private static final EcompUserConverter instance = new
- // EcompUserConverter();
-
- /*
- * public static EcompUserConverter getInsatnce() { return instance; }
- */
-
public static Either<EcompUser, String> convertUserToEcompUser(User asdcUser) {
EcompUser convertedUser = new EcompUser();
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/ArtifactExternalServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/ArtifactExternalServlet.java
index ecdce79b29..ec1a460417 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/ArtifactExternalServlet.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/ArtifactExternalServlet.java
@@ -40,11 +40,12 @@ import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;
+import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.model.ArtifactDefinition;
-import org.openecomp.sdc.be.servlets.BeGenericServlet;
+import org.openecomp.sdc.be.servlets.AbstractValidationsServlet;
import org.openecomp.sdc.be.servlets.RepresentationUtils;
import org.openecomp.sdc.common.api.Constants;
import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
@@ -71,12 +72,14 @@ import fj.data.Either;
@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
@Path("/v1/catalog")
@Singleton
-public class ArtifactExternalServlet extends BeGenericServlet {
+public class ArtifactExternalServlet extends AbstractValidationsServlet {
@Context
private HttpServletRequest request;
private static Logger log = LoggerFactory.getLogger(ArtifactExternalServlet.class.getName());
+
+ private static String startLog = "Start handle request of ";
/**
* Uploads an artifact to resource or service
@@ -92,60 +95,58 @@ public class ArtifactExternalServlet extends BeGenericServlet {
@ApiResponses(value = { @ApiResponse(code = 200, message = "Artifact uploaded"), @ApiResponse(code = 401, message = "Authorization required"), @ApiResponse(code = 403, message = "Restricted operation"),
@ApiResponse(code = 404, message = "Asset not found") })
public Response uploadArtifact(@PathParam("assetType") final String assetType, @PathParam("uuid") final String uuid, @ApiParam(value = "json describe the artifact", required = true) String data) {
-
- Wrapper<Response> responseWrapper = new Wrapper<>();
- ResponseFormat responseFormat = null;
+ init(log);
+
+ Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
String instanceIdHeader = request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER);
String requestURI = request.getRequestURI();
String userId = request.getHeader(Constants.USER_ID_HEADER);
String url = request.getMethod() + " " + requestURI;
- log.debug("Start handle request of {}", url);
+ log.debug("{} {}", startLog, url);
ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
+ String componentTypeValue = componentType == null ? null : componentType.getValue();
+ EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class);
+
if (componentType == null) {
log.debug("uploadArtifact: assetType parameter {} is not valid", assetType);
- responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
- responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
+ responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
}
- EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class);
-
- if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) {
- log.debug("uploadArtifact: Missing X-ECOMP-InstanceID header");
- responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
- getComponentsUtils().auditExternalUploadArtifact(responseFormat, componentType.getValue(), request, additionalParams);
- responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
+ if (responseWrapper.isEmpty()) {
+ validateXECOMPInstanceIDHeader(instanceIdHeader, responseWrapper);
}
- if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) {
- log.debug("uploadArtifact: Missing USER_ID header");
- responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.COMPONENT_MISSING_CONTACT);
- getComponentsUtils().auditExternalUploadArtifact(responseFormat, componentType.getValue(), request, additionalParams);
- responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
+ if (responseWrapper.isEmpty() ) {
+ validateHttpCspUserIdHeader(userId, responseWrapper);
}
- if (responseWrapper.isEmpty()) {
- try {
+ Response response = null;
+ try {
+ if (responseWrapper.isEmpty()) {
ServletContext context = request.getSession().getServletContext();
ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
- Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither = artifactsLogic.uploadArtifactToComponentByUUID(data, request, componentType, uuid, additionalParams);
+ Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither = artifactsLogic.uploadArtifactToComponentByUUID(data, request, componentType, uuid,
+ additionalParams, artifactsLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.Create));
if (uploadArtifactEither.isRight()) {
log.debug("failed to upload artifact");
- responseFormat = uploadArtifactEither.right().value();
- getComponentsUtils().auditExternalUploadArtifact(responseFormat, componentType.getValue(), request, additionalParams);
- responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
+ responseWrapper.setInnerElement(uploadArtifactEither.right().value());
} else {
Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value());
Map<String, String> headers = new HashMap<>();
headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5ByString((String) representation));
- responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
- getComponentsUtils().auditExternalUploadArtifact(responseFormat, componentType.getValue(), request, additionalParams);
- responseWrapper.setInnerElement(buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers));
+ responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.OK));
+ response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers);
}
- } catch (Exception e) {
- final String message = "failed to upload artifact to a resource or service";
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);
- log.debug(message, e);
- responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
+ }
+ if( response == null ){
+ response = buildErrorResponse(responseWrapper.getInnerElement());
}
+ return response;
+ } catch (Exception e) {
+ final String message = "failed to upload artifact to a resource or service";
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);
+ log.debug(message, e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ } finally {
+ getComponentsUtils().auditExternalUploadArtifact(responseWrapper.getInnerElement(), componentTypeValue, request, additionalParams);
}
- return responseWrapper.getInnerElement();
}
/**
@@ -171,51 +172,51 @@ public class ArtifactExternalServlet extends BeGenericServlet {
String requestURI = request.getRequestURI();
String userId = request.getHeader(Constants.USER_ID_HEADER);
String url = request.getMethod() + " " + requestURI;
- log.debug("Start handle request of {}", url);
+ log.debug("{} {}", startLog, url);
ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
+ String componentTypeValue = componentType == null ? null : componentType.getValue();
+ EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class);
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInstanceName);
if (componentType == null) {
log.debug("uploadArtifact: assetType parameter {} is not valid", assetType);
responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
}
- EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class);
-
if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) {
log.debug("uploadArtifact: Missing X-ECOMP-InstanceID header");
responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
- getComponentsUtils().auditExternalUploadArtifact(responseFormat, componentType.getValue(), request, additionalParams);
responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
}
if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) {
log.debug("uploadArtifact: Missing USER_ID header");
- responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.COMPONENT_MISSING_CONTACT);
- getComponentsUtils().auditExternalUploadArtifact(responseFormat, componentType.getValue(), request, additionalParams);
+ responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID);
responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
}
- if (responseWrapper.isEmpty()) {
- try {
+ try {
+ if (responseWrapper.isEmpty()) {
ServletContext context = request.getSession().getServletContext();
ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
- Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither = artifactsLogic.uploadArtifactToRiByUUID(data, request, componentType, uuid, resourceInstanceName, additionalParams);
+ Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither = artifactsLogic.uploadArtifactToRiByUUID(data, request, componentType, uuid, resourceInstanceName,
+ additionalParams, artifactsLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.Create));
if (uploadArtifactEither.isRight()) {
log.debug("failed to upload artifact");
responseFormat = uploadArtifactEither.right().value();
- getComponentsUtils().auditExternalUploadArtifact(responseFormat, componentType.getValue(), request, additionalParams);
responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
} else {
Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value());
Map<String, String> headers = new HashMap<>();
headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5ByString((String) representation));
responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
- getComponentsUtils().auditExternalUploadArtifact(responseFormat, componentType.getValue(), request, additionalParams);
responseWrapper.setInnerElement(buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers));
}
- } catch (Exception e) {
- final String message = "failed to upload artifact to a resource instance";
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);
- log.debug(message, e);
- responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
- }
+ }
+ }catch (Exception e) {
+ final String message = "failed to upload artifact to a resource instance";
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);
+ log.debug(message, e);
+ responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
+ } finally {
+ getComponentsUtils().auditExternalUploadArtifact(responseFormat, componentTypeValue, request, additionalParams);
}
return responseWrapper.getInnerElement();
}
@@ -243,52 +244,51 @@ public class ArtifactExternalServlet extends BeGenericServlet {
String requestURI = request.getRequestURI();
String userId = request.getHeader(Constants.USER_ID_HEADER);
String url = request.getMethod() + " " + requestURI;
- log.debug("Start handle request of {}", url);
+ log.debug("{} {}", startLog, url);
ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
+ String componentTypeValue = componentType == null ? null : componentType.getValue();
+ EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class);
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifactUUID);
if (componentType == null) {
log.debug("updateArtifact: assetType parameter {} is not valid", assetType);
responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
}
- EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class);
-
- // Mandatory
if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) {
log.debug("updateArtifact: Missing X-ECOMP-InstanceID header");
responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
- getComponentsUtils().auditExternalUpdateArtifact(responseFormat, componentType.getValue(), request, additionalParams);
responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
}
if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) {
- log.debug("updateArtifact: Missing USER_ID header");
- responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.COMPONENT_MISSING_CONTACT);
- getComponentsUtils().auditExternalUpdateArtifact(responseFormat, componentType.getValue(), request, additionalParams);
+ log.debug("updateArtifact: Missing USER_ID");
+ responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID);
responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
}
- if (responseWrapper.isEmpty()) {
- try {
+ try {
+ if (responseWrapper.isEmpty()) {
ServletContext context = request.getSession().getServletContext();
ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
- Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither = artifactsLogic.updateArtifactOnComponentByUUID(data, request, componentType, uuid, artifactUUID, additionalParams);
+ Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither = artifactsLogic.updateArtifactOnComponentByUUID(data, request, componentType, uuid, artifactUUID,
+ additionalParams, artifactsLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.Update));
if (uploadArtifactEither.isRight()) {
log.debug("failed to update artifact");
responseFormat = uploadArtifactEither.right().value();
- getComponentsUtils().auditExternalUpdateArtifact(responseFormat, componentType.getValue(), request, additionalParams);
responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
} else {
Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value());
Map<String, String> headers = new HashMap<>();
headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5ByString((String) representation));
responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
- getComponentsUtils().auditExternalUpdateArtifact(responseFormat, componentType.getValue(), request, additionalParams);
responseWrapper.setInnerElement(buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers));
}
- } catch (Exception e) {
- final String message = "failed to update artifact on a resource or service";
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);
- log.debug(message, e);
- responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
}
+ } catch (Exception e) {
+ final String message = "failed to update artifact on a resource or service";
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);
+ log.debug(message, e);
+ responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
+ } finally {
+ getComponentsUtils().auditExternalUpdateArtifact(responseFormat, componentTypeValue, request, additionalParams);
}
return responseWrapper.getInnerElement();
}
@@ -317,51 +317,52 @@ public class ArtifactExternalServlet extends BeGenericServlet {
String requestURI = request.getRequestURI();
String userId = request.getHeader(Constants.USER_ID_HEADER);
String url = request.getMethod() + " " + requestURI;
- log.debug("Start handle request of {}", url);
+ log.debug("{} {}", startLog, url);
ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
+ String componentTypeValue = componentType == null ? null : componentType.getValue();
+ EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class);
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInstanceName);
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifactUUID);
if (componentType == null) {
log.debug("updateArtifactOnResourceInstance: assetType parameter {} is not valid", assetType);
responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
}
- EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class);
-
if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) {
log.debug("updateArtifactOnResourceInstance: Missing X-ECOMP-InstanceID header");
responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
- getComponentsUtils().auditExternalUpdateArtifact(responseFormat, componentType.getValue(), request, additionalParams);
responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
}
if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) {
log.debug("updateArtifactOnResourceInstance: Missing USER_ID header");
- responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.COMPONENT_MISSING_CONTACT);
- getComponentsUtils().auditExternalUpdateArtifact(responseFormat, componentType.getValue(), request, additionalParams);
+ responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID);
responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
}
- if (responseWrapper.isEmpty()) {
- try {
+ try {
+ if (responseWrapper.isEmpty()) {
ServletContext context = request.getSession().getServletContext();
ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
- Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither = artifactsLogic.updateArtifactOnRiByUUID(data, request, componentType, uuid, resourceInstanceName, artifactUUID, additionalParams);
+ Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither = artifactsLogic.updateArtifactOnRiByUUID(data, request, componentType, uuid, resourceInstanceName, artifactUUID,
+ additionalParams, artifactsLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.Update));
if (uploadArtifactEither.isRight()) {
log.debug("failed to update artifact");
responseFormat = uploadArtifactEither.right().value();
- getComponentsUtils().auditExternalUpdateArtifact(responseFormat, componentType.getValue(), request, additionalParams);
responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
} else {
Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value());
Map<String, String> headers = new HashMap<>();
headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5ByString((String) representation));
responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
- getComponentsUtils().auditExternalUpdateArtifact(responseFormat, componentType.getValue(), request, additionalParams);
responseWrapper.setInnerElement(buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers));
}
- } catch (Exception e) {
- final String message = "failed to update artifact on resource instance";
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);
- log.debug(message, e);
- responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
}
+ } catch (Exception e) {
+ final String message = "failed to update artifact on resource instance";
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);
+ log.debug(message, e);
+ responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
+ } finally {
+ getComponentsUtils().auditExternalUpdateArtifact(responseFormat, componentTypeValue, request, additionalParams);
}
return responseWrapper.getInnerElement();
}
@@ -383,57 +384,56 @@ public class ArtifactExternalServlet extends BeGenericServlet {
public Response deleteArtifact(@PathParam("assetType") final String assetType, @PathParam("uuid") final String uuid, @PathParam("artifactUUID") final String artifactUUID) {
Wrapper<Response> responseWrapper = new Wrapper<>();
- ResponseFormat responseFormat;
+ ResponseFormat responseFormat = null;
String instanceIdHeader = request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER);
String userId = request.getHeader(Constants.USER_ID_HEADER);
String requestURI = request.getRequestURI();
String url = request.getMethod() + " " + requestURI;
- log.debug("Start handle request of {}", url);
-
+ log.debug("{} {}", startLog, url);
ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
+ String componentTypeValue = componentType == null ? null : componentType.getValue();
+ EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class);
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifactUUID);
if (componentType == null) {
log.debug("deleteArtifact: assetType parameter {} is not valid", assetType);
responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
}
- EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class);
-
if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) {
log.debug("deleteArtifact: Missing X-ECOMP-InstanceID header");
responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
- getComponentsUtils().auditExternalDeleteArtifact(responseFormat, componentType.getValue(), request, additionalParams);
responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
}
if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) {
log.debug("deleteArtifact: Missing USER_ID header");
- responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.COMPONENT_MISSING_CONTACT);
- getComponentsUtils().auditExternalDeleteArtifact(responseFormat, componentType.getValue(), request, additionalParams);
+ responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID);
responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
}
- if (responseWrapper.isEmpty()) {
- try {
+ try {
+ if (responseWrapper.isEmpty()) {
ServletContext context = request.getSession().getServletContext();
ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
- Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither = artifactsLogic.deleteArtifactOnComponentByUUID(request, componentType, uuid, artifactUUID, additionalParams);
+ Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither = artifactsLogic.deleteArtifactOnComponentByUUID(request, componentType, uuid, artifactUUID,
+ additionalParams, artifactsLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.Delete));
if (uploadArtifactEither.isRight()) {
log.debug("failed to delete artifact");
responseFormat = uploadArtifactEither.right().value();
- getComponentsUtils().auditExternalDeleteArtifact(responseFormat, componentType.getValue(), request, additionalParams);
responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
} else {
Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value());
Map<String, String> headers = new HashMap<>();
headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5ByString((String) representation));
responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
- getComponentsUtils().auditExternalDeleteArtifact(responseFormat, componentType.getValue(), request, additionalParams);
responseWrapper.setInnerElement(buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers));
}
- } catch (Exception e) {
- final String message = "failed to delete an artifact of a resource or service";
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);
- log.debug(message, e);
- responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
}
+ } catch (Exception e) {
+ final String message = "failed to delete an artifact of a resource or service";
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);
+ log.debug(message, e);
+ responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
+ } finally {
+ getComponentsUtils().auditExternalDeleteArtifact(responseFormat, componentTypeValue, request, additionalParams);
}
return responseWrapper.getInnerElement();
}
@@ -456,57 +456,57 @@ public class ArtifactExternalServlet extends BeGenericServlet {
@PathParam("artifactUUID") final String artifactUUID) {
Wrapper<Response> responseWrapper = new Wrapper<>();
- ResponseFormat responseFormat;
+ ResponseFormat responseFormat = null;
String instanceIdHeader = request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER);
String userId = request.getHeader(Constants.USER_ID_HEADER);
String requestURI = request.getRequestURI();
String url = request.getMethod() + " " + requestURI;
- log.debug("Start handle request of {}", url);
-
+ log.debug("{} {}", startLog, url);
ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
+ String componentTypeValue = componentType == null ? null : componentType.getValue();
+ EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class);
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInstanceName);
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifactUUID);
if (componentType == null) {
log.debug("deleteArtifactOnResourceInsatnce: assetType parameter {} is not valid", assetType);
responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
}
- EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class);
-
if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) {
log.debug("deleteArtifactOnResourceInsatnce: Missing X-ECOMP-InstanceID header");
responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
- getComponentsUtils().auditExternalDeleteArtifact(responseFormat, componentType.getValue(), request, additionalParams);
responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
}
if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) {
log.debug("deleteArtifactOnResourceInsatnce: Missing USER_ID header");
- responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.COMPONENT_MISSING_CONTACT);
- getComponentsUtils().auditExternalDeleteArtifact(responseFormat, componentType.getValue(), request, additionalParams);
+ responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID);
responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
}
- if (responseWrapper.isEmpty()) {
- try {
+ try {
+ if (responseWrapper.isEmpty()) {
ServletContext context = request.getSession().getServletContext();
ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
- Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither = artifactsLogic.deleteArtifactOnRiByUUID(request, componentType, uuid, resourceInstanceName, artifactUUID, additionalParams);
+ Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither = artifactsLogic.deleteArtifactOnRiByUUID(request, componentType, uuid, resourceInstanceName, artifactUUID,
+ additionalParams, artifactsLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.Delete));
if (uploadArtifactEither.isRight()) {
log.debug("failed to delete artifact");
responseFormat = uploadArtifactEither.right().value();
- getComponentsUtils().auditExternalDeleteArtifact(responseFormat, componentType.getValue(), request, additionalParams);
responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
} else {
Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value());
Map<String, String> headers = new HashMap<>();
headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5ByString((String) representation));
responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
- getComponentsUtils().auditExternalDeleteArtifact(responseFormat, componentType.getValue(), request, additionalParams);
responseWrapper.setInnerElement(buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers));
}
- } catch (Exception e) {
- final String message = "failed to delete an artifact of a resource instance";
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);
- log.debug(message, e);
- responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
- }
+ }
+ } catch (Exception e) {
+ final String message = "failed to delete an artifact of a resource instance";
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);
+ log.debug(message, e);
+ responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
+ } finally {
+ getComponentsUtils().auditExternalDeleteArtifact(responseFormat, componentTypeValue, request, additionalParams);
}
return responseWrapper.getInnerElement();
}
@@ -530,33 +530,32 @@ public class ArtifactExternalServlet extends BeGenericServlet {
@PathParam("uuid") final String uuid, @PathParam("artifactUUID") final String artifactUUID) {
Wrapper<Response> responseWrapper = new Wrapper<>();
- ResponseFormat responseFormat;
+ ResponseFormat responseFormat = null;
String instanceIdHeader = request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER);
String requestURI = request.getRequestURI();
String url = request.getMethod() + " " + requestURI;
- log.debug("Start handle request of {}", url);
+ log.debug("{} {}", startLog, url);
ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
+ String componentTypeValue = componentType == null ? null : componentType.getValue();
+ EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class);
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifactUUID);
if (componentType == null) {
log.debug("downloadComponentArtifact: assetType parameter {} is not valid", assetType);
responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
}
- EnumMap<AuditingFieldsKeysEnum, Object> additionalParam = new EnumMap<>(AuditingFieldsKeysEnum.class);
-
if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) {
log.debug("downloadComponentArtifact: Missing X-ECOMP-InstanceID header");
responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
- getComponentsUtils().auditExternalDownloadArtifact(responseFormat, componentType.getValue(), request, additionalParam);
responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
}
- if (responseWrapper.isEmpty()) {
- try {
+ try {
+ if (responseWrapper.isEmpty()) {
ServletContext context = request.getSession().getServletContext();
ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
- Either<byte[], ResponseFormat> downloadComponentArtifactEither = artifactsLogic.downloadComponentArtifactByUUIDs(componentType, uuid, artifactUUID, additionalParam);
+ Either<byte[], ResponseFormat> downloadComponentArtifactEither = artifactsLogic.downloadComponentArtifactByUUIDs(componentType, uuid, artifactUUID, additionalParams);
if (downloadComponentArtifactEither.isRight()) {
responseFormat = downloadComponentArtifactEither.right().value();
- getComponentsUtils().auditExternalDownloadArtifact(responseFormat, componentType.getValue(), request, additionalParam);
responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
} else {
byte[] value = downloadComponentArtifactEither.left().value();
@@ -564,15 +563,16 @@ public class ArtifactExternalServlet extends BeGenericServlet {
Map<String, String> headers = new HashMap<>();
headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5ByByteArray(value));
responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
- getComponentsUtils().auditExternalDownloadArtifact(responseFormat, componentType.getValue(), request, additionalParam);
responseWrapper.setInnerElement(buildOkResponse(responseFormat, is, headers));
}
- } catch (Exception e) {
- final String message = "failed to download an artifact of a resource or service";
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);
- log.debug(message, e);
- responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
}
+ } catch (Exception e) {
+ final String message = "failed to download an artifact of a resource or service";
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);
+ log.debug(message, e);
+ responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
+ } finally {
+ getComponentsUtils().auditExternalDownloadArtifact(responseFormat, componentTypeValue, request, additionalParams);
}
return responseWrapper.getInnerElement();
}
@@ -597,33 +597,33 @@ public class ArtifactExternalServlet extends BeGenericServlet {
@PathParam("uuid") final String uuid, @PathParam("resourceInstanceName") final String resourceInstanceName, @PathParam("artifactUUID") final String artifactUUID) {
Wrapper<Response> responseWrapper = new Wrapper<>();
- ResponseFormat responseFormat;
+ ResponseFormat responseFormat = null;
String instanceIdHeader = request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER);
String requestURI = request.getRequestURI();
String url = request.getMethod() + " " + requestURI;
- log.debug("Start handle request of {}", url);
+ log.debug("{} {}", startLog, url);
ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
+ String componentTypeValue = componentType == null ? null : componentType.getValue();
+ EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class);
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInstanceName);
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifactUUID);
if (componentType == null) {
log.debug("downloadResourceInstanceArtifact: assetType parameter {} is not valid", assetType);
responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
}
- EnumMap<AuditingFieldsKeysEnum, Object> additionalParam = new EnumMap<>(AuditingFieldsKeysEnum.class);
-
if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) {
log.debug("downloadResourceInstanceArtifact: Missing X-ECOMP-InstanceID header");
responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
- getComponentsUtils().auditExternalDownloadArtifact(responseFormat, componentType.getValue(), request, additionalParam);
responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
}
- if (responseWrapper.isEmpty()) {
- try {
+ try {
+ if (responseWrapper.isEmpty()) {
ServletContext context = request.getSession().getServletContext();
ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
- Either<byte[], ResponseFormat> downloadResourceArtifactEither = artifactsLogic.downloadResourceInstanceArtifactByUUIDs(componentType, uuid, resourceInstanceName, artifactUUID, additionalParam);
+ Either<byte[], ResponseFormat> downloadResourceArtifactEither = artifactsLogic.downloadResourceInstanceArtifactByUUIDs(componentType, uuid, resourceInstanceName, artifactUUID, additionalParams);
if (downloadResourceArtifactEither.isRight()) {
responseFormat = downloadResourceArtifactEither.right().value();
- getComponentsUtils().auditExternalDownloadArtifact(responseFormat, componentType.getValue(), request, additionalParam);
responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
} else {
byte[] value = downloadResourceArtifactEither.left().value();
@@ -631,15 +631,16 @@ public class ArtifactExternalServlet extends BeGenericServlet {
Map<String, String> headers = new HashMap<>();
headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5ByByteArray(value));
responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
- getComponentsUtils().auditExternalDownloadArtifact(responseFormat, componentType.getValue(), request, additionalParam);
responseWrapper.setInnerElement(buildOkResponse(responseFormat, is, headers));
}
- } catch (Exception e) {
- final String message = "failed to download an artifact of a resource instance";
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);
- log.debug(message, e);
- responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
}
+ } catch (Exception e) {
+ final String message = "failed to download an artifact of a resource instance";
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);
+ log.debug(message, e);
+ responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
+ } finally {
+ getComponentsUtils().auditExternalDownloadArtifact(responseFormat, componentTypeValue, request, additionalParams);
}
return responseWrapper.getInnerElement();
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/AssetMetadataConverter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/AssetMetadataConverter.java
index 662399142e..2c7de7032c 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/AssetMetadataConverter.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/AssetMetadataConverter.java
@@ -26,9 +26,10 @@ import java.util.LinkedList;
import java.util.List;
import java.util.Map;
+import org.apache.commons.collections.MapUtils;
+import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.distribution.servlet.DistributionCatalogServlet;
import org.openecomp.sdc.be.externalapi.servlet.representation.ArtifactMetadata;
import org.openecomp.sdc.be.externalapi.servlet.representation.AssetMetadata;
@@ -44,7 +45,7 @@ import org.openecomp.sdc.be.model.ComponentInstance;
import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.Service;
import org.openecomp.sdc.be.model.category.CategoryDefinition;
-import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.ResourceOperation;
import org.openecomp.sdc.exception.ResponseFormat;
@@ -60,8 +61,9 @@ public class AssetMetadataConverter {
@Autowired
private ComponentsUtils componentsUtils;
+
@Autowired
- private ResourceOperation resourceOperation;
+ protected ToscaOperationFacade toscaOperationFacade;
/*
* Relative asset’s URL. Should be used in REST GET API to download the asset’s CSAR. https://{serverBaseURL}/{csarPath} can be obtained from (HttpServletRequest)request.getServerName()
@@ -70,19 +72,13 @@ public class AssetMetadataConverter {
if (componentList == null || componentList.isEmpty()) {
return Either.left(new LinkedList<>());
}
-
List<AssetMetadata> retResList = new LinkedList<>();
- Component component = componentList.iterator().next();
- ComponentTypeEnum componentType = component.getComponentType();
for (Component curr : componentList) {
-
- Either<? extends AssetMetadata, ResponseFormat> resMetaData = convertToMetadata(componentType, serverBaseURL, detailed, curr);
-
+ Either<? extends AssetMetadata, ResponseFormat> resMetaData = convertToSingleAssetMetadata(curr, serverBaseURL, detailed);
if (resMetaData.isRight()) {
return Either.right(resMetaData.right().value());
}
-
retResList.add(resMetaData.left().value());
}
@@ -90,6 +86,19 @@ public class AssetMetadataConverter {
}
+ public <T extends Component> Either<? extends AssetMetadata, ResponseFormat> convertToSingleAssetMetadata(T component, String serverBaseURL, boolean detailed) {
+ ComponentTypeEnum componentType = component.getComponentType();
+ Either<? extends AssetMetadata, ResponseFormat> resMetaData = convertToMetadata(componentType, serverBaseURL, detailed, component);
+
+ if (resMetaData.isRight()) {
+ return Either.right(resMetaData.right().value());
+ }
+ else{
+ return Either.left(resMetaData.left().value());
+ }
+
+ }
+
private Either<? extends AssetMetadata, ResponseFormat> convertToMetadata(ComponentTypeEnum componentType, String serverBaseURL, boolean detailed, Component curr) {
switch (componentType) {
@@ -188,12 +197,12 @@ public class AssetMetadataConverter {
private <T extends ResourceAssetMetadata> T convertToResourceMetadata(T assetToPopulate, Resource resource, String serverBaseURL, boolean detailed) {
assetToPopulate = convertToAsset(assetToPopulate, resource, serverBaseURL, detailed);
- CategoryDefinition categoryDefinition = resource.getCategories().iterator().next();
- assetToPopulate.setCategory(categoryDefinition.getName());
-
- SubCategoryDefinition subCategoryDefinition = categoryDefinition.getSubcategories().iterator().next();
-
- assetToPopulate.setSubCategory(subCategoryDefinition.getName());
+ CategoryDefinition categoryDefinition;
+ if(resource.getCategories() != null && !resource.getCategories().isEmpty()){
+ categoryDefinition = resource.getCategories().iterator().next();
+ assetToPopulate.setCategory(categoryDefinition.getName());
+ assetToPopulate.setSubCategory(categoryDefinition.getSubcategories().iterator().next().getName());
+ }
assetToPopulate.setResourceType(resource.getResourceType().name());
assetToPopulate.setLifecycleState(resource.getLifecycleState().name());
assetToPopulate.setLastUpdaterUserId(resource.getLastUpdaterUserId());
@@ -232,7 +241,7 @@ public class AssetMetadataConverter {
assetToPopulate.setLastUpdaterFullName(resource.getLastUpdaterFullName());
assetToPopulate.setToscaResourceName(resource.getToscaResourceName());
-
+ assetToPopulate.setDescription(resource.getDescription());
return Either.left(assetToPopulate);
}
@@ -276,9 +285,8 @@ public class AssetMetadataConverter {
}
private List<ArtifactMetadata> populateAssetWithArtifacts(Component component, Map<String, ArtifactDefinition> artifacts) {
- List<ArtifactMetadata> artifactMetaList = null;
- if (artifacts != null) {
- artifactMetaList = new LinkedList<>();
+ List<ArtifactMetadata> artifactMetaList = new LinkedList<>();
+ if (artifacts != null) {
Collection<ArtifactDefinition> artefactDefList = artifacts.values();
for (ArtifactDefinition artifactDefinition : artefactDefList) {
@@ -292,11 +300,11 @@ public class AssetMetadataConverter {
}
private ArtifactMetadata convertToArtifactMetadata(ArtifactDefinition artifact, String componentType, String componentUUID, String resourceInstanceName) {
- // /asdc/v1/catalog/{services/resources}/{componentUUID}/artifacts/{artifactUUID}
- final String COMPONENT_ARTIFACT_URL = "/asdc/v1/catalog/%s/%s/artifacts/%s";
+ // /sdc/v1/catalog/{services/resources}/{componentUUID}/artifacts/{artifactUUID}
+ final String COMPONENT_ARTIFACT_URL = "/sdc/v1/catalog/%s/%s/artifacts/%s";
- // /asdc/v1/catalog/{services/resources}/{componentUUID}/resourceInstances/{resourceInstanceName}/artifacts/{artifactUUID}
- final String RESOURCE_INSTANCE_ARTIFACT_URL = "/asdc/v1/catalog/%s/%s/resourceInstances/%s/artifacts/%s";
+ // /sdc/v1/catalog/{services/resources}/{componentUUID}/resourceInstances/{resourceInstanceName}/artifacts/{artifactUUID}
+ final String RESOURCE_INSTANCE_ARTIFACT_URL = "/sdc/v1/catalog/%s/%s/resourceInstances/%s/artifacts/%s";
ArtifactMetadata metadata = new ArtifactMetadata();
@@ -315,52 +323,55 @@ public class AssetMetadataConverter {
metadata.setArtifactUUID(artifact.getArtifactUUID());
metadata.setArtifactVersion(artifact.getArtifactVersion());
metadata.setGeneratedFromUUID(artifact.getGeneratedFromId());
-
+ metadata.setArtifactLabel(artifact.getArtifactLabel());
+ metadata.setArtifactGroupType(artifact.getArtifactGroupType().getType());
return metadata;
}
private Either<List<ResourceInstanceMetadata>, StorageOperationStatus> convertToResourceInstanceMetadata(List<ComponentInstance> componentInstances, String componentType, String componentUUID) {
List<ResourceInstanceMetadata> retList = new LinkedList<>();
- Map<String, String> uuidDuplicatesMap = new HashMap<>();
+ Map<String, ImmutablePair<String, String>> uuidDuplicatesMap = new HashMap<>();
for (ComponentInstance componentInstance : componentInstances) {
ResourceInstanceMetadata metadata = new ResourceInstanceMetadata();
String componentUid = componentInstance.getComponentUid();
- String invariantUUID;
+ String invariantUUID, resourceUUID;
if (!uuidDuplicatesMap.containsKey(componentUid)) {
- Either<String, StorageOperationStatus> getInvarUuidresponse = resourceOperation.getInvariantUUID(NodeTypeEnum.Resource, componentInstance.getComponentUid(), false);
- if (getInvarUuidresponse.isRight()) {
- log.debug("convertToResourceInstanceMetadata: Failed getting Invariant UUID");
- return Either.right(getInvarUuidresponse.right().value());
+ Either<Resource, StorageOperationStatus> eitherResource = toscaOperationFacade.getToscaElement(componentInstance.getComponentUid());
+ if (eitherResource.isRight()) {
+ log.debug("convertToResourceInstanceMetadata: Failed getting resource with Uid: {}", componentInstance.getComponentUid());
+ return Either.right(eitherResource.right().value());
} else {
- invariantUUID = getInvarUuidresponse.left().value();
- uuidDuplicatesMap.put(componentUid, invariantUUID);
+ final Resource resource = eitherResource.left().value();
+ invariantUUID = resource.getInvariantUUID();
+ resourceUUID = resource.getUUID();
+ ImmutablePair<String, String> uuidInvariantUUIDPair = new ImmutablePair<>(resourceUUID, invariantUUID);
+ uuidDuplicatesMap.put(componentUid, uuidInvariantUUIDPair);
}
} else {
- invariantUUID = uuidDuplicatesMap.get(componentUid);
+ invariantUUID = uuidDuplicatesMap.get(componentUid).getRight();
+ resourceUUID = uuidDuplicatesMap.get(componentUid).getLeft();
}
metadata.setResourceInvariantUUID(invariantUUID);
+ metadata.setResourceUUID(resourceUUID);
metadata.setResourceInstanceName(componentInstance.getName());
metadata.setResourceName(componentInstance.getComponentName());
metadata.setResourceVersion(componentInstance.getComponentVersion());
- metadata.setResourceType(componentInstance.getOriginType().getValue());
- metadata.setResourceUUID(componentInstance.getComponentUid());
-
- Collection<ArtifactDefinition> values = componentInstance.getDeploymentArtifacts().values();
- LinkedList<ArtifactMetadata> artifactMetaList = new LinkedList<>();
-
- for (ArtifactDefinition artifactDefinition : values) {
- ArtifactMetadata converted = convertToArtifactMetadata(artifactDefinition, componentType, componentUUID, componentInstance.getNormalizedName());
- artifactMetaList.add(converted);
+ metadata.setResoucreType(componentInstance.getOriginType().getValue());
+
+ if(MapUtils.isNotEmpty(componentInstance.getDeploymentArtifacts())){
+ LinkedList<ArtifactMetadata> artifactMetaList = new LinkedList<>();
+ Collection<ArtifactDefinition> values = componentInstance.getDeploymentArtifacts().values();
+ for (ArtifactDefinition artifactDefinition : values) {
+ ArtifactMetadata converted = convertToArtifactMetadata(artifactDefinition, componentType, componentUUID, componentInstance.getNormalizedName());
+ artifactMetaList.add(converted);
+ }
+ metadata.setArtifacts(artifactMetaList);
}
-
- metadata.setArtifacts(artifactMetaList);
-
retList.add(metadata);
}
-
return Either.left(retList);
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/AssetsDataServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/AssetsDataServlet.java
index 1b8d6fdb75..552ad163ec 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/AssetsDataServlet.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/AssetsDataServlet.java
@@ -21,19 +21,23 @@
package org.openecomp.sdc.be.externalapi.servlet;
import java.io.ByteArrayInputStream;
+import java.io.IOException;
import java.io.InputStream;
-import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import java.util.function.Predicate;
+import java.util.Optional;
+import java.util.stream.Collectors;
import javax.inject.Singleton;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
+import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
@@ -42,27 +46,50 @@ import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
+import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
-import org.apache.http.NameValuePair;
+import org.codehaus.jackson.JsonGenerationException;
+import org.codehaus.jackson.map.JsonMappingException;
+import org.codehaus.jackson.map.ObjectMapper;
+import org.elasticsearch.common.Strings;
+import org.json.simple.JSONObject;
+import org.json.simple.parser.JSONParser;
import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic;
import org.openecomp.sdc.be.components.impl.ElementBusinessLogic;
+import org.openecomp.sdc.be.components.impl.ImportUtils;
+import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic;
+import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
+import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoBase;
+import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.datamodel.api.CategoryTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.AssetTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.FilterKeyEnum;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
import org.openecomp.sdc.be.externalapi.servlet.representation.AssetMetadata;
-import org.openecomp.sdc.be.impl.WebAppContextWrapper;
import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
+import org.openecomp.sdc.be.model.LifecycleStateEnum;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.category.CategoryDefinition;
+import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
-import org.openecomp.sdc.be.servlets.BeGenericServlet;
+import org.openecomp.sdc.be.servlets.AbstractValidationsServlet;
import org.openecomp.sdc.be.servlets.RepresentationUtils;
+import org.openecomp.sdc.be.utils.CommonBeUtils;
import org.openecomp.sdc.common.api.Constants;
+import org.openecomp.sdc.common.config.EcompErrorName;
import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
+import org.openecomp.sdc.common.datastructure.Wrapper;
import org.openecomp.sdc.common.util.GeneralUtility;
+import org.openecomp.sdc.common.util.ValidationUtils;
import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.springframework.web.context.WebApplicationContext;
import com.jcabi.aspects.Loggable;
import com.wordnik.swagger.annotations.ApiOperation;
@@ -75,12 +102,11 @@ import fj.data.Either;
@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
@Path("/v1/catalog")
@Singleton
-public class AssetsDataServlet extends BeGenericServlet {
+public class AssetsDataServlet extends AbstractValidationsServlet {
@Context
private HttpServletRequest request;
- private AssetMetadataConverter assetMetadataUtils;
private static Logger log = LoggerFactory.getLogger(AssetsDataServlet.class.getName());
@GET
@@ -89,7 +115,8 @@ public class AssetsDataServlet extends BeGenericServlet {
@ApiOperation(value = "Fetch list of assets", httpMethod = "GET", notes = "Returns list of assets", response = Response.class)
@ApiResponses(value = { @ApiResponse(code = 200, message = "Assets Fetched"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), @ApiResponse(code = 401, message = "Authorization required"),
@ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Asset not found") })
- public Response getAssetList(@PathParam("assetType") final String assetType, @QueryParam("category") String category, @QueryParam("subCategory") String subCategory, @QueryParam("distributionStatus") String distributionStatus) {
+ public Response getAssetList(@PathParam("assetType") final String assetType, @QueryParam("category") String category, @QueryParam("subCategory") String subCategory, @QueryParam("distributionStatus") String distributionStatus,
+ @QueryParam("resourceType") String resourceType) {
Response response = null;
ResponseFormat responseFormat = null;
@@ -98,8 +125,7 @@ public class AssetsDataServlet extends BeGenericServlet {
String requestURI = request.getRequestURI();
String url = request.getMethod() + " " + requestURI;
log.debug("Start handle request of {}", url);
- String serverBaseURL = request.getRequestURL().toString();
-
+
AuditingActionEnum auditingActionEnum = query == null ? AuditingActionEnum.GET_ASSET_LIST : AuditingActionEnum.GET_FILTERED_ASSET_LIST;
EnumMap<AuditingFieldsKeysEnum, Object> additionalParam = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
@@ -118,7 +144,7 @@ public class AssetsDataServlet extends BeGenericServlet {
ServletContext context = request.getSession().getServletContext();
ElementBusinessLogic elementLogic = getElementBL(context);
- getAssetUtils(context);
+ AssetMetadataConverter assetMetadataUtils = getAssetUtils(context);
Map<FilterKeyEnum, String> filters = new HashMap<FilterKeyEnum, String>();
if (category != null) {
@@ -130,6 +156,16 @@ public class AssetsDataServlet extends BeGenericServlet {
if (distributionStatus != null) {
filters.put(FilterKeyEnum.DISTRIBUTION_STATUS, distributionStatus);
}
+ if (resourceType != null) {
+ ResourceTypeEnum resourceTypeEnum = ResourceTypeEnum.getTypeIgnoreCase(resourceType);
+ if( resourceTypeEnum == null ){
+ log.debug("getAssetList: Asset Fetching Failed. Invalid resource type was received");
+ responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
+ getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam);
+ return buildErrorResponse(responseFormat);
+ }
+ filters.put(FilterKeyEnum.RESOURCE_TYPE, resourceTypeEnum.name());
+ }
Either<List<? extends Component>, ResponseFormat> assetTypeData = elementLogic.getFilteredCatalogComponents(assetType, filters, query);
@@ -140,7 +176,7 @@ public class AssetsDataServlet extends BeGenericServlet {
return buildErrorResponse(responseFormat);
} else {
log.debug("getAssetList: Asset Fetching Success");
- Either<List<? extends AssetMetadata>, ResponseFormat> resMetadata = assetMetadataUtils.convertToAssetMetadata(assetTypeData.left().value(), serverBaseURL, false);
+ Either<List<? extends AssetMetadata>, ResponseFormat> resMetadata = assetMetadataUtils.convertToAssetMetadata(assetTypeData.left().value(), requestURI, false);
if (resMetadata.isRight()) {
log.debug("getAssetList: Asset conversion Failed");
responseFormat = resMetadata.right().value();
@@ -176,7 +212,6 @@ public class AssetsDataServlet extends BeGenericServlet {
String requestURI = request.getRequestURI();
String url = request.getMethod() + " " + requestURI;
log.debug("Start handle request of {}", url);
- String serverBaseURL = request.getRequestURL().toString();
EnumMap<AuditingFieldsKeysEnum, Object> additionalParam = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
@@ -196,7 +231,7 @@ public class AssetsDataServlet extends BeGenericServlet {
try {
ServletContext context = request.getSession().getServletContext();
ElementBusinessLogic elementLogic = getElementBL(context);
- getAssetUtils(context);
+ AssetMetadataConverter assetMetadataUtils = getAssetUtils(context);
Either<List<? extends Component>, ResponseFormat> assetTypeData = elementLogic.getCatalogComponentsByUuidAndAssetType(assetType, uuid);
@@ -209,7 +244,7 @@ public class AssetsDataServlet extends BeGenericServlet {
} else {
log.debug("getAssetList: Asset Fetching Success");
additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, assetTypeData.left().value().iterator().next().getName());
- Either<List<? extends AssetMetadata>, ResponseFormat> resMetadata = assetMetadataUtils.convertToAssetMetadata(assetTypeData.left().value(), serverBaseURL, true);
+ Either<List<? extends AssetMetadata>, ResponseFormat> resMetadata = assetMetadataUtils.convertToAssetMetadata(assetTypeData.left().value(), requestURI, true);
if (resMetadata.isRight()) {
log.debug("getAssetList: Asset conversion Failed");
responseFormat = resMetadata.right().value();
@@ -230,12 +265,6 @@ public class AssetsDataServlet extends BeGenericServlet {
}
}
- private void getAssetUtils(ServletContext context) {
- WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
- WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
- assetMetadataUtils = webApplicationContext.getBean(AssetMetadataConverter.class);
- }
-
@GET
@Path("/{assetType}/{uuid}/toscaModel")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@@ -297,4 +326,438 @@ public class AssetsDataServlet extends BeGenericServlet {
return response;
}
}
+
+ /**
+ * Creates a new Resource
+ *
+ * @param assetType
+ * @param data
+ * @return
+ */
+ @POST
+ @Path("/{assetType}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "creates a resource", httpMethod = "POST", notes = "creates a resource", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Artifact uploaded"),
+ @ApiResponse(code = 401, message = "Authorization required"),
+ @ApiResponse(code = 403, message = "Restricted operation"),
+ @ApiResponse(code = 201, message = "Resource created"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
+ @ApiResponse(code = 409, message = "Resource already exist") })
+ public Response createResource(@PathParam("assetType") final String assetType, @ApiParam(value = "json describe the artifact", required = true) String data) {
+ init(log);
+
+ Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
+ String requestURI = request.getRequestURI();
+ String userId = request.getHeader(Constants.USER_ID_HEADER);
+ String url = request.getMethod() + " " + requestURI;
+ log.debug("Start handle request of {}", url);
+ Resource resource = null;
+ User modifier = null;
+ EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class);
+ ServletContext context = request.getSession().getServletContext();
+ ResourceBusinessLogic resourceBL = getResourceBL(context);
+ try {
+ // Validate X-ECOMP-InstanceID Header
+ if (responseWrapper.isEmpty()) {
+ validateXECOMPInstanceIDHeader(request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER),
+ responseWrapper);
+ }
+ // Validate USER_ID Header
+ if (responseWrapper.isEmpty()) {
+ validateHttpCspUserIdHeader(userId, responseWrapper);
+ }
+ // Validate assetType
+ if (responseWrapper.isEmpty()) {
+ if( !AssetTypeEnum.RESOURCES.getValue().equals(assetType) ){
+ responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
+ }
+ }
+ //Validate resource type
+ if(responseWrapper.isEmpty()){
+ JSONParser parser = new JSONParser();
+ JSONObject jsonObj = (JSONObject) parser.parse(data);
+ String resourceType = (String) jsonObj.get(FilterKeyEnum.RESOURCE_TYPE.getName());
+ if( StringUtils.isEmpty(resourceType) || !ResourceTypeEnum.containsName(resourceType) ){
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, (String) jsonObj.get("name"));
+ responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
+ }
+ }
+ // Convert the user json to a resource
+ if (responseWrapper.isEmpty()) {
+ modifier = new User();
+ modifier.setUserId(userId);
+ Either<Resource, ResponseFormat> eitherResource = getComponentsUtils()
+ .convertJsonToObjectUsingObjectMapper(data, modifier, Resource.class,
+ null, ComponentTypeEnum.RESOURCE);
+ if( eitherResource.isRight() ){
+ responseWrapper.setInnerElement(eitherResource.right().value());
+ }
+ else{
+ resource = eitherResource.left().value();
+ }
+
+ }
+ //validate name exist
+ if(responseWrapper.isEmpty()){
+ if( Strings.isEmpty(resource.getName())){
+ responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(
+ ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue()));
+
+ }
+ }
+
+ if(responseWrapper.isEmpty()){
+ resource.setDerivedFrom(Arrays.asList("tosca.nodes.Root"));
+ resource.setSystemName(ValidationUtils.convertToSystemName(resource.getName()));
+ resource.setToscaResourceName(CommonBeUtils.generateToscaResourceName(ResourceTypeEnum.VFCMT.name(),
+ resource.getSystemName()));
+ handleCategories(context, data, resource, responseWrapper);
+ }
+ // Create the resource in the dataModel
+ if (responseWrapper.isEmpty()) {
+ Either<Resource, ResponseFormat> eitherCreateResponse = resourceBL.createResource(resource, null,
+ modifier, null, null);
+ if (eitherCreateResponse.isRight()) {
+ responseWrapper.setInnerElement(eitherCreateResponse.right().value());
+ } else {
+ resource = eitherCreateResponse.left().value();
+ }
+ }
+ Response response;
+ //Build Response and store it in the response Wrapper
+ if (responseWrapper.isEmpty()) {
+ response = buildCreatedResourceResponse(resource, context, responseWrapper);
+ }
+ else{
+ response = buildErrorResponse(responseWrapper.getInnerElement());
+ }
+ return response;
+
+ } catch (Exception e) {
+ final String message = "failed to create vfc monitoring template resource";
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);
+ log.debug(message, e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ finally{
+ prepareAdditionalAudit(resource, additionalParams);
+
+ getComponentsUtils().auditExternalCrudApi(responseWrapper.getInnerElement(),
+ ComponentTypeEnum.RESOURCE.getValue(), AuditingActionEnum.CREATE_RESOURCE_BY_API.getName(), request,
+ additionalParams);
+ }
+ }
+
+ private void prepareAdditionalAudit(Resource resource, EnumMap<AuditingFieldsKeysEnum, Object> additionalParams) {
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, StringUtils.EMPTY);
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE, StringUtils.EMPTY);
+
+ if( resource != null ){
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION);
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name());
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resource.getName());
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, resource.getUUID());
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, resource.getInvariantUUID());
+ } else {
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, StringUtils.EMPTY);
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, StringUtils.EMPTY);
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, StringUtils.EMPTY);
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, StringUtils.EMPTY);
+ }
+ }
+
+ private Response buildCreatedResourceResponse(Component resource, ServletContext context,
+ Wrapper<ResponseFormat> responseWrapper) throws IOException, JsonGenerationException, JsonMappingException {
+ ResponseFormat responseFormat;
+ Response response;
+ AssetMetadataConverter assetMetadataUtils = getAssetUtils(context);
+ Either<? extends AssetMetadata, ResponseFormat> resMetadata = assetMetadataUtils
+ .convertToSingleAssetMetadata(resource, request.getRequestURL().toString(),
+ true);
+ if (resMetadata.isRight()) {
+ log.debug("Asset conversion Failed");
+ responseFormat = resMetadata.right().value();
+ responseWrapper.setInnerElement(responseFormat);
+ response = buildErrorResponse(responseFormat);
+ }
+ else{
+ final AssetMetadata assetData = resMetadata.left().value();
+ assetData.setToscaModelURL(null);
+
+ responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.CREATED));
+ Object representation = RepresentationUtils.toRepresentation(assetData);
+ responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
+ response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), representation);
+ }
+ return response;
+ }
+
+ private void handleCategories(ServletContext context, String data, Resource resource,
+ Wrapper<ResponseFormat> responseWrapper) {
+ try {
+ JSONParser parser = new JSONParser();
+ JSONObject jsonObj = (JSONObject) parser.parse(data);
+ String category = (String) jsonObj.get(CategoryTypeEnum.CATEGORY.getValue());
+ String subcategory = (String) jsonObj.get(CategoryTypeEnum.SUBCATEGORY.getValue());
+ if (Strings.isEmpty(category)) {
+ responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(
+ ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()));
+ }
+ else if (Strings.isEmpty(subcategory)) {
+ responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(
+ ActionStatus.COMPONENT_MISSING_SUBCATEGORY));
+ }
+ if (responseWrapper.isEmpty()) {
+ ElementBusinessLogic elementLogic = getElementBL(context);
+ // get All Categories
+ Either<List<CategoryDefinition>, ActionStatus> allResourceCategories = elementLogic
+ .getAllResourceCategories();
+ // Error fetching categories
+ if (allResourceCategories.isRight()) {
+ responseWrapper.setInnerElement(
+ getComponentsUtils().getResponseFormat(allResourceCategories.right().value()));
+ } else {
+ addCategories(resource, category, subcategory, allResourceCategories, responseWrapper);
+ }
+ }
+ } catch (Exception e) {
+ log.debug("Exception occured in addCategories: {}", e.getMessage(), e);
+ responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+
+ }
+
+ private void addCategories(Resource resource, String category, String subcategory,
+ Either<List<CategoryDefinition>, ActionStatus> allResourceCategories,
+ Wrapper<ResponseFormat> responseWrapper) {
+ Optional<CategoryDefinition> optionalCategory =
+ // Stream of all the categories
+ allResourceCategories.left().value().stream()
+ // filter in only relevant category
+ .filter(e -> e.getName().equals(category))
+ // get the result
+ .findAny();
+ if (!optionalCategory.isPresent()) {
+ responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(
+ ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()));
+ } else {
+ CategoryDefinition categoryDefinition = optionalCategory.get();
+
+ List<SubCategoryDefinition> subCaregories =
+ // Stream of all sub-categories of the relevant
+ // category
+ categoryDefinition.getSubcategories().stream()
+ // filter in only relevant sub-category
+ .filter(e -> e.getName().equals(subcategory))
+ // get the result
+ .collect(Collectors.toList());
+
+ if( subCaregories.isEmpty() ){
+ responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(
+ ActionStatus.COMPONENT_INVALID_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue()));
+ }
+ else{
+ categoryDefinition.setSubcategories(subCaregories);
+ resource.setCategories(Arrays.asList(categoryDefinition));
+ }
+
+ }
+ }
+
+
+ /**
+ * Changing the lifecycle of an asset
+ * @param jsonChangeInfo The description - request body
+ * @param assetType The requested asset type.Valid values are: resources / services (for VFCMT – use "resources")
+ * @param uuid The uuid of the desired resource to be changed
+ * @param lifecycleTransition The lifecycle operation to be performed on the asset.Valid values are:Checkin / Checkout / CERTIFICATION_REQUEST
+ * @return
+ */
+ @POST
+ @Path("/{assetType}/{uuid}/lifecycleState/{lifecycleOperation}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Change Resource lifecycle State", httpMethod = "POST", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource state changed"), @ApiResponse(code = 403, message = "Asset is already checked-out by another user")})
+ public Response changeResourceState(@ApiParam(value = "LifecycleChangeInfo - relevant for checkin", required = false) String jsonChangeInfo,
+ @ApiParam(value = "validValues: resources / services ", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam(value = "assetType") final String assetType,
+ @ApiParam(value = "id of component to be changed") @PathParam(value = "uuid") final String uuid,
+ @ApiParam(allowableValues = "checkout, checkin", required = true) @PathParam(value = "lifecycleOperation") final String lifecycleTransition) {
+ Response response = null;
+ EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class);
+
+ init(log);
+
+ String requestURI = request.getRequestURI();
+ String url = request.getMethod() + " " + requestURI;
+ log.debug("Start handle request of {}", url);
+
+ //get the business logic
+ ServletContext context = request.getSession().getServletContext();
+ LifecycleBusinessLogic businessLogic = getLifecycleBL(context);
+
+ Wrapper<ResponseFormat> responseWrapper = runValidations(assetType);
+ ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
+ Component component = null;
+ Component responseObject = null;
+ User modifier = null;
+ String userId = request.getHeader(Constants.USER_ID_HEADER);
+
+ try{
+ if (responseWrapper.isEmpty()) {
+ //get user
+ Either<User, ResponseFormat> eitherGetUser = getUser(request, userId);
+ if (eitherGetUser.isRight()) {
+ ResponseFormat responseFormat = eitherGetUser.right().value();
+ responseWrapper.setInnerElement(responseFormat);
+ return buildErrorResponse(responseFormat);
+ }
+ modifier = eitherGetUser.left().value();
+
+ //get the component id from the uuid
+ Either<Component, ResponseFormat> latestVersion = businessLogic.getLatestComponentByUuid(componentType, uuid);
+ if (latestVersion.isRight()) {
+ ResponseFormat responseFormat = latestVersion.right().value();
+ responseWrapper.setInnerElement(responseFormat);
+ return buildErrorResponse(responseFormat);
+ }
+ component = latestVersion.left().value();
+ String componentId = component.getUniqueId();
+
+ //validate the transition is valid
+ Either<LifeCycleTransitionEnum, ResponseFormat> validateEnum = validateTransitionEnum(lifecycleTransition, modifier);
+ if (validateEnum.isRight()) {
+ ResponseFormat responseFormat = validateEnum.right().value();
+ responseWrapper.setInnerElement(responseFormat);
+ return buildErrorResponse(responseFormat);
+ }
+ LifeCycleTransitionEnum transitionEnum = validateEnum.left().value();
+
+ //create changeInfo
+ LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction();
+ try {
+ if (jsonChangeInfo != null && !jsonChangeInfo.isEmpty()) {
+ ObjectMapper mapper = new ObjectMapper();
+ changeInfo = new LifecycleChangeInfoWithAction(mapper.readValue(jsonChangeInfo, LifecycleChangeInfoBase.class).getUserRemarks());
+ }
+ }
+ catch (Exception e) {
+ BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeInvalidJsonInput, "convertJsonToObject");
+ BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject");
+ log.debug("failed to convert from json {}", jsonChangeInfo, e);
+ ResponseFormat responseFormat = getComponentsUtils().getInvalidContentErrorAndAudit(modifier, AuditingActionEnum.CHECKOUT_RESOURCE);
+ responseWrapper.setInnerElement(responseFormat);
+ return buildErrorResponse(responseFormat);
+ }
+
+ //execute business logic
+ Either<? extends Component, ResponseFormat> actionResponse = businessLogic.changeComponentState(componentType, componentId, modifier, transitionEnum, changeInfo, false, true);
+ if (actionResponse.isRight()) {
+ log.info("failed to change resource state");
+ ResponseFormat responseFormat = actionResponse.right().value();
+ responseWrapper.setInnerElement(responseFormat);
+ return buildErrorResponse(responseFormat);
+ }
+
+ log.debug("change state successful !!!");
+ responseObject = actionResponse.left().value();
+ response = buildCreatedResourceResponse(responseObject, context, responseWrapper);
+ } else {
+ response = buildErrorResponse(responseWrapper.getInnerElement());
+ }
+
+ return response;
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Change Lifecycle State");
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Change Lifecycle State");
+ log.debug("change lifecycle state failed with exception", e);
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
+ responseWrapper.setInnerElement(responseFormat);
+ return buildErrorResponse(responseFormat);
+ } finally{
+ auditChnageLifecycleAction(additionalParams, responseWrapper, componentType, component, responseObject, modifier, userId);
+ }
+ }
+
+ private void auditChnageLifecycleAction(EnumMap<AuditingFieldsKeysEnum, Object> additionalParams,
+ Wrapper<ResponseFormat> responseWrapper, ComponentTypeEnum componentType, Component component,
+ Component responseObject, User modifier, String userId) {
+ if (modifier!=null){
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, modifier.getFullName());
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifier.getUserId());
+ } else {
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, "");
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, userId);
+ }
+
+ if (component!=null){
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getName());
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, component.getVersion());
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE, component.getLifecycleState().name());
+ } else {
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, "");
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, "");
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE, "");
+ }
+
+ if (responseObject!=null){
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, responseObject.getVersion());
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, responseObject.getUUID());
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, responseObject.getInvariantUUID());
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE,responseObject.getLifecycleState().name());
+ } else {
+ if (component!=null){
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, component.getVersion());
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, component.getUUID());
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, component.getInvariantUUID());
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE,component.getLifecycleState().name());
+ } else {
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, "");
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, "");
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, "");
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE,"");
+ }
+ }
+
+ getComponentsUtils().auditExternalCrudApi(responseWrapper.getInnerElement(),
+ componentType.getValue(), AuditingActionEnum.CHANGE_LIFECYCLE_BY_API.getName(), request,
+ additionalParams);
+ }
+
+ private Wrapper<ResponseFormat> runValidations(final String assetType) {
+ Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
+
+ // Validate X-ECOMP-InstanceID Header
+ if (responseWrapper.isEmpty()) {
+ String instanceId = request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER);
+ validateXECOMPInstanceIDHeader(instanceId,responseWrapper);
+ }
+ // Validate USER_ID Header
+ if (responseWrapper.isEmpty()) {
+ validateHttpCspUserIdHeader(request.getHeader(Constants.USER_ID_HEADER),responseWrapper);
+ }
+ // Validate assetType
+ if (responseWrapper.isEmpty()) {
+ if( !AssetTypeEnum.RESOURCES.getValue().equals(assetType) && !AssetTypeEnum.SERVICES.getValue().equals(assetType)){
+ responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
+ }
+ }
+
+ return responseWrapper;
+ }
+
+
+ private Either<LifeCycleTransitionEnum, ResponseFormat> validateTransitionEnum(final String lifecycleTransition, User user) {
+ LifeCycleTransitionEnum transitionEnum = LifeCycleTransitionEnum.CHECKOUT;
+ try {
+ transitionEnum = LifeCycleTransitionEnum.getFromDisplayName(lifecycleTransition);
+ } catch (IllegalArgumentException e) {
+ log.info("state operation is not valid. operations allowed are: {}", LifeCycleTransitionEnum.valuesAsString());
+ ResponseFormat error = getComponentsUtils().getInvalidContentErrorAndAudit(user, AuditingActionEnum.CHECKOUT_RESOURCE);
+ return Either.right(error);
+ }
+ return Either.left(transitionEnum);
+ }
+
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ArtifactMetadata.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ArtifactMetadata.java
index f4194cf2f5..15ebceaa5d 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ArtifactMetadata.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ArtifactMetadata.java
@@ -30,7 +30,9 @@ public class ArtifactMetadata {
private String artifactUUID;
private String artifactVersion;
private String generatedFromUUID;
-
+ private String artifactLabel;
+ private String artifactGroupType;
+
public String getArtifactName() {
return artifactName;
}
@@ -103,4 +105,20 @@ public class ArtifactMetadata {
this.generatedFromUUID = generatedFromUUID;
}
+ public String getArtifactLabel() {
+ return artifactLabel;
+ }
+
+ public void setArtifactLabel(String artifactLabel) {
+ this.artifactLabel = artifactLabel;
+ }
+
+ public String getArtifactGroupType() {
+ return artifactGroupType;
+ }
+
+ public void setArtifactGroupType(String artifactGroupType) {
+ this.artifactGroupType = artifactGroupType;
+ }
+
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ResourceAssetDetailedMetadata.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ResourceAssetDetailedMetadata.java
index ea282ec2e8..0952feea05 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ResourceAssetDetailedMetadata.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ResourceAssetDetailedMetadata.java
@@ -28,6 +28,7 @@ public class ResourceAssetDetailedMetadata extends ResourceAssetMetadata {
private String toscaResourceName;
private List<ResourceInstanceMetadata> resources;
private List<ArtifactMetadata> artifacts;
+ private String description;
public String getLastUpdaterFullName() {
return lastUpdaterFullName;
@@ -60,4 +61,13 @@ public class ResourceAssetDetailedMetadata extends ResourceAssetMetadata {
public void setArtifacts(List<ArtifactMetadata> artifactMetaList) {
this.artifacts = artifactMetaList;
}
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ResourceInstanceMetadata.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ResourceInstanceMetadata.java
index 547bb301f8..a53422f311 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ResourceInstanceMetadata.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ResourceInstanceMetadata.java
@@ -27,7 +27,7 @@ public class ResourceInstanceMetadata {
private String resourceName;
private String resourceInvariantUUID;
private String resourceVersion;
- private String resourceType;
+ private String resoucreType;
private String resourceUUID;
private List<ArtifactMetadata> artifacts;
@@ -63,12 +63,12 @@ public class ResourceInstanceMetadata {
this.resourceVersion = resourceVersion;
}
- public String getResourceType() {
- return resourceType;
+ public String getResoucreType() {
+ return resoucreType;
}
- public void setResourceType(String resourceType) {
- this.resourceType = resourceType;
+ public void setResoucreType(String resoucreType) {
+ this.resoucreType = resoucreType;
}
public String getResourceUUID() {
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BasicAuthenticationFilter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BasicAuthenticationFilter.java
index f7e1d758ac..de95790f4e 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BasicAuthenticationFilter.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BasicAuthenticationFilter.java
@@ -77,7 +77,7 @@ public class BasicAuthenticationFilter implements ContainerRequestFilter {
if (basic.equalsIgnoreCase("Basic")) {
try {
String credentials = new String(Base64.decodeBase64(st.nextToken()), "UTF-8");
- log.debug("Credentials: {}", credentials);
+ log.debug("Credentials: {}" , credentials);
checkUserCredentiles(requestContext, credentials);
} catch (UnsupportedEncodingException e) {
log.error("Authentication Filter Failed Couldn't retrieve authentication", e);
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BeServletFilter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BeServletFilter.java
index f6c11d062e..d24743534c 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BeServletFilter.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BeServletFilter.java
@@ -38,6 +38,7 @@ import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.config.Configuration;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.impl.WebAppContextWrapper;
import org.openecomp.sdc.common.api.Constants;
@@ -115,6 +116,17 @@ public class BeServletFilter implements ContainerRequestFilter, ContainerRespons
outHttpResponse(responseContext);
+ log.debug("Close transaction from filter");
+ TitanDao titanDao = getTitanDao();
+ if ( titanDao != null ){
+ if (responseContext.getStatus() == Response.Status.OK.getStatusCode() || responseContext.getStatus() == Response.Status.CREATED.getStatusCode() ){
+ titanDao.commit();
+ log.debug("Doing commit from filter");
+ }else{
+ titanDao.rollback();
+ log.debug("Doing rollback from filter");
+ }
+ }
// Cleaning up
MDC.clear();
ThreadLocalsHolder.cleanup();
@@ -126,7 +138,7 @@ public class BeServletFilter implements ContainerRequestFilter, ContainerRespons
}
private String processMdcFields(ContainerRequestContext requestContext) {
- // userId for logging
+ // UserId for logging
String userId = requestContext.getHeaderString(Constants.USER_ID_HEADER);
MDC.put("userId", userId);
@@ -165,7 +177,13 @@ public class BeServletFilter implements ContainerRequestFilter, ContainerRespons
WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
return webApplicationContext.getBean(ComponentsUtils.class);
}
+ private TitanDao getTitanDao() {
+ ServletContext context = this.sr.getSession().getServletContext();
+ WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
+ WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
+ return webApplicationContext.getBean(TitanDao.class);
+ }
// Extracted for purpose of clear method name, for logback %M parameter
private void inHttpRequest() {
if (isInfoLog()) {
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/impl/ComponentsUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/impl/ComponentsUtils.java
index 9e2abebdc5..ea2582cd1b 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/impl/ComponentsUtils.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/impl/ComponentsUtils.java
@@ -41,9 +41,9 @@ import org.openecomp.sdc.be.components.impl.ResponseFormatManager;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.dao.graph.datatype.AdditionalInformationEnum;
+import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterInfo;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.model.AdditionalInfoParameterInfo;
import org.openecomp.sdc.be.model.ArtifactDefinition;
import org.openecomp.sdc.be.model.CapabilityTypeDefinition;
import org.openecomp.sdc.be.model.Component;
@@ -454,51 +454,57 @@ public class ComponentsUtils {
getAuditingManager().auditEvent(auditingFields);
}
- public void auditExternalCrudApiArtifact(ResponseFormat responseFormat, String componentType, String actionEnum, HttpServletRequest request, EnumMap<AuditingFieldsKeysEnum, Object> additionalParams) {
+ public void auditExternalCrudApi(ResponseFormat responseFormat, String componentType, String actionEnum, HttpServletRequest request, EnumMap<AuditingFieldsKeysEnum, Object> additionalParams) {
log.trace("Inside auditing for audit action {}", actionEnum);
String instanceIdHeader = request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER);
String requestURI = request.getRequestURI();
- int status = responseFormat.getStatus();
- String message = "";
EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
- if (responseFormat.getMessageId() != null) {
- message = responseFormat.getMessageId() + ": ";
+ int status = 0;
+ String message = "";
+ if(responseFormat != null){
+ status = responseFormat.getStatus();
+ if (responseFormat.getMessageId() != null) {
+ message = responseFormat.getMessageId() + ": ";
+ }
+ message += responseFormat.getFormattedMessage();
}
- message += responseFormat.getFormattedMessage();
auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum);
auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, instanceIdHeader);
auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, requestURI);
auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, componentType);
auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status);
auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, message);
-
+
if (additionalParams != null) {
auditingFields.putAll(additionalParams);
+ if(!additionalParams.containsKey(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME)){
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, "");
+ }
}
getAuditingManager().auditEvent(auditingFields);
}
public void auditExternalDownloadArtifact(ResponseFormat responseFormat, String componentType, HttpServletRequest request, EnumMap<AuditingFieldsKeysEnum, Object> additionalParams) {
- auditExternalCrudApiArtifact(responseFormat, componentType, AuditingActionEnum.DOWNLOAD_ARTIFACT.getName(), request, additionalParams);
+ auditExternalCrudApi(responseFormat, componentType, AuditingActionEnum.DOWNLOAD_ARTIFACT.getName(), request, additionalParams);
}
public void auditExternalUploadArtifact(ResponseFormat responseFormat, String componentType, HttpServletRequest request, EnumMap<AuditingFieldsKeysEnum, Object> additionalParams) {
additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, request.getHeader(Constants.USER_ID_HEADER));
additionalParams.put(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID, "");
- auditExternalCrudApiArtifact(responseFormat, componentType, AuditingActionEnum.ARTIFACT_UPLOAD_BY_API.getName(), request, additionalParams);
+ auditExternalCrudApi(responseFormat, componentType, AuditingActionEnum.ARTIFACT_UPLOAD_BY_API.getName(), request, additionalParams);
}
public void auditExternalUpdateArtifact(ResponseFormat responseFormat, String componentType, HttpServletRequest request, EnumMap<AuditingFieldsKeysEnum, Object> additionalParams) {
additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, request.getHeader(Constants.USER_ID_HEADER));
additionalParams.put(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID, "");
- auditExternalCrudApiArtifact(responseFormat, componentType, AuditingActionEnum.ARTIFACT_UPDATE_BY_API.getName(), request, additionalParams);
+ auditExternalCrudApi(responseFormat, componentType, AuditingActionEnum.ARTIFACT_UPDATE_BY_API.getName(), request, additionalParams);
}
public void auditExternalDeleteArtifact(ResponseFormat responseFormat, String componentType, HttpServletRequest request, EnumMap<AuditingFieldsKeysEnum, Object> additionalParams) {
additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, request.getHeader(Constants.USER_ID_HEADER));
additionalParams.put(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID, "");
- auditExternalCrudApiArtifact(responseFormat, componentType, AuditingActionEnum.ARTIFACT_DELETE_BY_API.getName(), request, additionalParams);
+ auditExternalCrudApi(responseFormat, componentType, AuditingActionEnum.ARTIFACT_DELETE_BY_API.getName(), request, additionalParams);
}
public void auditCategory(ResponseFormat responseFormat, User modifier, String categoryName, String subCategoryName, String groupingName, AuditingActionEnum actionEnum, String componentType) {
@@ -603,6 +609,9 @@ public class ComponentsUtils {
case CATEGORY_NOT_FOUND:
responseEnum = ActionStatus.COMPONENT_CATEGORY_NOT_FOUND;
break;
+ case INVALID_PROPERTY:
+ responseEnum = ActionStatus.INVALID_PROPERTY;
+ break;
default:
responseEnum = ActionStatus.GENERAL_ERROR;
break;
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/impl/DownloadArtifactLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/impl/DownloadArtifactLogic.java
index fff6fd15a4..cfa108ed80 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/impl/DownloadArtifactLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/impl/DownloadArtifactLogic.java
@@ -78,11 +78,8 @@ public class DownloadArtifactLogic {
String payloadStr = new String(artifactPayload);
byte[] decodedPayload = artifactPayload;
- boolean isEncoded = GeneralUtility.isBase64Encoded(payloadStr);
- if (isEncoded) {
- log.debug("payload is encoded. perform decode");
- decodedPayload = Base64.decode(new String(artifactPayload));
- }
+ log.debug("payload is encoded. perform decode");
+ decodedPayload = Base64.decode(new String(artifactPayload));
final InputStream artifactStream = new ByteArrayInputStream(decodedPayload);
log.debug("found artifact for with id: {}", artifactId);
try {
@@ -106,7 +103,7 @@ public class DownloadArtifactLogic {
} catch (IOException e) {
BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Failed to stream artifact data on the response");
BeEcompErrorManager.getInstance().logBeSystemError("Failed to stream artifact data on the response");
- log.debug("Failed to stream artifact data on the response: {}", e.getMessage());
+ log.debug("Failed to stream artifact data on the response: {}", e.getMessage(), e);
response = buildResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, "Failed to stream artifact data on the response");
return response;
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactTemplateInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactTemplateInfo.java
index fca7bf38d8..fa051a9e3d 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactTemplateInfo.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactTemplateInfo.java
@@ -28,7 +28,7 @@ import java.util.Set;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.config.ConfigurationManager;
-import org.openecomp.sdc.be.config.Configuration.DeploymentArtifactTypeConfig;
+import org.openecomp.sdc.be.config.Configuration.ArtifactTypeConfig;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.impl.ComponentsUtils;
@@ -205,7 +205,7 @@ public class ArtifactTemplateInfo {
if (!artifactTypeExist) {
BeEcompErrorManager.getInstance().logBeInvalidTypeError("Artifact", "-Not supported artifact type ", correctType);
- log.debug("Not supported artifact type = {}", correctType);
+ log.debug("Not supported artifact type = {}" , correctType);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, correctType));
}
@@ -275,8 +275,8 @@ public class ArtifactTemplateInfo {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_VALID_IN_MASTER, resourceInfo.getFileName(), resourceInfo.getType(), parentArtifact.getFileName(), parentArtifact.getType()));
}
if (parentArtifact.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_NESTED.getType())) {
- if (resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ARTIFACT.getType())) {
- Either.left(true);
+ if (resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ARTIFACT.getType()) || resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_NESTED.getType())) {
+ return Either.left(true);
}
return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_VALID_IN_MASTER, resourceInfo.getFileName(), resourceInfo.getType(), parentArtifact.getFileName(), parentArtifact.getType()));
}
@@ -285,7 +285,7 @@ public class ArtifactTemplateInfo {
}
if (parentArtifact.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType())) {
- Either.left(true);
+ return Either.left(true);
}
return Either.left(true);
}
@@ -324,7 +324,7 @@ public class ArtifactTemplateInfo {
private static Either<List<ArtifactType>, ActionStatus> getDeploymentArtifactTypes(NodeTypeEnum parentType) {
- Map<String, DeploymentArtifactTypeConfig> deploymentArtifacts = null;
+ Map<String, ArtifactTypeConfig> deploymentArtifacts = null;
List<ArtifactType> artifactTypes = new ArrayList<ArtifactType>();
if (parentType.equals(NodeTypeEnum.Service)) {
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/GroupDefinitionInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/GroupDefinitionInfo.java
index 24d9c5644d..05af87d789 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/GroupDefinitionInfo.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/GroupDefinitionInfo.java
@@ -20,20 +20,19 @@
package org.openecomp.sdc.be.info;
-import java.util.ArrayList;
-import java.util.HashMap;
import java.util.List;
-import java.util.Map;
-import java.util.stream.Collectors;
-
-import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
import org.openecomp.sdc.be.model.GroupDefinition;
+import org.openecomp.sdc.be.model.GroupInstance;
+import org.openecomp.sdc.be.model.GroupProperty;
public class GroupDefinitionInfo {
private String name;
// the id is unique per group instance on graph.
private String uniqueId;
+
+ // the id is unique per group instance on graph.
+ private String groupInstanceUniqueId;
// the group UUID should be changed when one of the artifacts/component
// instances has been changed.
@@ -46,12 +45,15 @@ public class GroupDefinitionInfo {
private String version;
private String invariantUUID;
+ private String customizationUUID;
Boolean isBase = null;
// artifacts - list of artifact uid. All artifacts in the group must already
// be uploaded to the VF
private List<ArtifactDefinitionInfo> artifacts;
+
+ private List<? extends GroupProperty> properties;
public GroupDefinitionInfo() {
super();
@@ -63,6 +65,21 @@ public class GroupDefinitionInfo {
this.setVersion(other.getVersion());
this.setGroupUUID(other.getGroupUUID());
this.setInvariantUUID(other.getInvariantUUID());
+ this.setProperties(other.convertToGroupProperties());
+
+
+ }
+
+ public GroupDefinitionInfo(GroupInstance other) {
+ this.setName(other.getGroupName());
+ this.setUniqueId(other.getGroupUid());
+ this.setGroupInstanceUniqueId(other.getUniqueId());
+ this.setVersion(other.getVersion());
+ this.setGroupUUID(other.getGroupUUID());
+ this.setCustomizationUUID(other.getCustomizationUUID());
+ this.setInvariantUUID(other.getInvariantUUID());
+ this.setProperties(other.convertToGroupInstancesProperties());
+
}
@@ -105,6 +122,15 @@ public class GroupDefinitionInfo {
public void setVersion(String version) {
this.version = version;
}
+
+
+ public String getCustomizationUUID() {
+ return customizationUUID;
+ }
+
+ public void setCustomizationUUID(String customizationUUID) {
+ this.customizationUUID = customizationUUID;
+ }
public Boolean getIsBase() {
return isBase;
@@ -121,10 +147,29 @@ public class GroupDefinitionInfo {
public void setArtifacts(List<ArtifactDefinitionInfo> artifacts) {
this.artifacts = artifacts;
}
+
+ public List<? extends GroupProperty> getProperties() {
+ return properties;
+ }
+
+ public void setProperties(List<? extends GroupProperty> properties) {
+ this.properties = properties;
+ }
+
+
+
+ public String getGroupInstanceUniqueId() {
+ return groupInstanceUniqueId;
+ }
+
+ public void setGroupInstanceUniqueId(String groupInstanceUniqueId) {
+ this.groupInstanceUniqueId = groupInstanceUniqueId;
+ }
@Override
public String toString() {
return "GroupDefinitionInfo [" + super.toString() + ", isBase=" + isBase + ", artifacts=" + artifacts + "]";
}
+
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/GroupTemplateInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/GroupTemplateInfo.java
index 8471a801ac..4a7e925639 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/GroupTemplateInfo.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/GroupTemplateInfo.java
@@ -20,9 +20,6 @@
package org.openecomp.sdc.be.info;
-import java.util.List;
-import java.util.Map;
-
public class GroupTemplateInfo {
String groupName;
boolean isBase;
@@ -30,7 +27,6 @@ public class GroupTemplateInfo {
public GroupTemplateInfo() {
super();
- // TODO Auto-generated constructor stub
}
public String getGroupName() {
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/MergedArtifactInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/MergedArtifactInfo.java
index 95038b1830..25b6b3564b 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/MergedArtifactInfo.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/MergedArtifactInfo.java
@@ -29,6 +29,8 @@ import java.util.Set;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.model.ArtifactDefinition;
+import java.util.Optional;
+
public class MergedArtifactInfo {
private List<ArtifactDefinition> createdArtifact;
@@ -70,7 +72,25 @@ public class MergedArtifactInfo {
public List<ArtifactDefinition> getListToDissotiateArtifactFromGroup(List<ArtifactDefinition> deletedArtifacts) {
List<ArtifactDefinition> resList = new ArrayList<ArtifactDefinition>();
for (ArtifactDefinition artifactDefinition : createdArtifact) {
- if (!parsetArtifactsNames.contains(artifactDefinition.getArtifactName())) {
+ boolean isDissotiate = true;
+ if(parsetArtifactsNames.contains(artifactDefinition.getArtifactName())){
+ isDissotiate = false;
+ }else{
+ if (artifactDefinition.getGeneratedFromId() != null && !artifactDefinition.getGeneratedFromId().isEmpty()){
+ Optional<ArtifactDefinition> op = createdArtifact.stream().filter(p -> p.getUniqueId().equals(artifactDefinition.getGeneratedFromId())).findAny();
+ if(op.isPresent()){
+ ArtifactDefinition generatedFromArt = op.get();
+ if(parsetArtifactsNames.contains(generatedFromArt.getArtifactName())){
+ isDissotiate = false;
+ }
+ }
+ else{
+ isDissotiate = true;
+ }
+
+ }
+ }
+ if (isDissotiate) {
boolean isDeleted = false;
for (ArtifactDefinition deletedArtifact : deletedArtifacts) {
if (artifactDefinition.getUniqueId().equalsIgnoreCase(deletedArtifact.getUniqueId())) {
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/listen/BEAppContextListener.java b/catalog-be/src/main/java/org/openecomp/sdc/be/listen/BEAppContextListener.java
index d40a3d4433..38629ab7a1 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/listen/BEAppContextListener.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/listen/BEAppContextListener.java
@@ -29,6 +29,8 @@ import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
+import org.openecomp.portalsdk.core.onboarding.ueb.UebException;
+import org.openecomp.portalsdk.core.onboarding.ueb.UebManager;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
@@ -43,9 +45,6 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
-import org.openecomp.portalsdk.core.onboarding.ueb.UebException;
-import org.openecomp.portalsdk.core.onboarding.ueb.UebManager;
-
public class BEAppContextListener extends AppContextListener implements ServletContextListener {
private static final String MANIFEST_FILE_NAME = "/META-INF/MANIFEST.MF";
@@ -68,7 +67,7 @@ public class BEAppContextListener extends AppContextListener implements ServletC
DownloadArtifactLogic downloadArtifactLogic = new DownloadArtifactLogic();
context.getServletContext().setAttribute(Constants.DOWNLOAD_ARTIFACT_LOGIC_ATTR, downloadArtifactLogic);
- context.getServletContext().setAttribute(Constants.SDC_RELEASE_VERSION_ATTR, getVersionFromManifest(context));
+ context.getServletContext().setAttribute(Constants.ASDC_RELEASE_VERSION_ATTR, getVersionFromManifest(context));
// Monitoring service
BeMonitoringService bms = new BeMonitoringService(context.getServletContext());
@@ -115,7 +114,7 @@ public class BEAppContextListener extends AppContextListener implements ServletC
try {
Manifest mf = new Manifest(inputStream);
Attributes atts = mf.getMainAttributes();
- version = atts.getValue(Constants.SDC_RELEASE_VERSION_ATTR);
+ version = atts.getValue(Constants.ASDC_RELEASE_VERSION_ATTR);
if (version == null || version.isEmpty()) {
log.warn("failed to read ASDC version from MANIFEST.");
} else {
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AbstractValidationsServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AbstractValidationsServlet.java
index 0e8addf692..d8f834c970 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AbstractValidationsServlet.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AbstractValidationsServlet.java
@@ -25,6 +25,7 @@ import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
+import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.util.EnumMap;
import java.util.HashMap;
@@ -40,6 +41,7 @@ import javax.ws.rs.core.Response;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;
+import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.codehaus.jackson.map.ObjectMapper;
import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
@@ -92,7 +94,6 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
@Autowired
protected ComponentsUtils componentsUtils;
- private static final Object LOCK = new Object();
private Logger log = null;
protected void init(Logger log) {
@@ -101,28 +102,20 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
}
- private void initLog(Logger log) {
+ private synchronized void initLog(Logger log) {
if (this.log == null) {
- synchronized (LOCK) {
- if (this.log == null) {
- this.log = log;
- }
-
- }
+ this.log = log;
}
}
- private void initSpringFromContext() {
+ private synchronized void initSpringFromContext() {
if (servletUtils == null) {
- synchronized (LOCK) {
- if (servletUtils == null) {
- ServletContext context = servletRequest.getSession().getServletContext();
- WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
- WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
- servletUtils = webApplicationContext.getBean(ServletUtils.class);
- resourceImportManager = webApplicationContext.getBean(ResourceImportManager.class);
- }
- }
+ ServletContext context = servletRequest.getSession().getServletContext();
+ WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context
+ .getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
+ WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
+ servletUtils = webApplicationContext.getBean(ServletUtils.class);
+ resourceImportManager = webApplicationContext.getBean(ResourceImportManager.class);
}
}
@@ -137,10 +130,10 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
}
}
- protected void validateUserExist(Wrapper<Response> responseWrapper, Wrapper<User> userWrapper, String userId) {
- log.debug("get user {} from DB", userId);
+ protected void validateUserExist(Wrapper<Response> responseWrapper, Wrapper<User> userWrapper, String userUserId) {
+ log.debug("get user {} from DB", userUserId);
// get user details
- if (userId == null) {
+ if (userUserId == null) {
log.info("user userId is null");
Response response = returnMissingInformation(new User());
responseWrapper.setInnerElement(response);
@@ -148,11 +141,11 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
else {
IUserBusinessLogic userAdmin = getServletUtils().getUserAdmin();
- Either<User, ActionStatus> eitherCreator = userAdmin.getUser(userId, false);
+ Either<User, ActionStatus> eitherCreator = userAdmin.getUser(userUserId, false);
if (eitherCreator.isRight()) {
- log.info("user is not listed. userId={}", userId);
+ log.info("user is not listed. userId={}", userUserId);
User user = new User();
- user.setUserId(userId);
+ user.setUserId(userUserId);
Response response = returnMissingInformation(user);
responseWrapper.setInnerElement(response);
} else {
@@ -203,6 +196,16 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
}
}
+ protected void validateCsar(Wrapper<Response> responseWrapper, File file, String payloadName) throws FileNotFoundException {
+ InputStream fileInputStream = new FileInputStream(file);
+ Map<String, byte[]> unzippedFolder = ZipUtil.readZip(new ZipInputStream(fileInputStream));
+ if (payloadName == null || payloadName.isEmpty() || unzippedFolder.isEmpty()) {
+ log.info("Invalid json was received. payloadName should be yml file name");
+ Response errorResponse = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
+ responseWrapper.setInnerElement(errorResponse);
+ }
+
+ }
protected void fillZipContents(Wrapper<String> yamlStringWrapper, File file) throws FileNotFoundException {
InputStream fileInputStream = new FileInputStream(file);
@@ -219,6 +222,33 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
log.debug("received yaml: {}", yamlAsString);
yamlStringWrapper.setInnerElement(yamlAsString);
}
+
+ protected void fillPayloadDataFromFile(Wrapper<Response> responseWrapper, UploadResourceInfo uploadResourceInfoWrapper, File file) {
+ try(InputStream fileInputStream = new FileInputStream(file);){
+
+ byte [] data = new byte[(int)file.length()];
+ if( fileInputStream.read(data) == -1){
+ log.info("Invalid json was received.");
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
+
+ Response errorResp = buildErrorResponse(responseFormat);
+ responseWrapper.setInnerElement(errorResp);
+ }
+ String payloadData = Base64.encodeBase64String(data);
+ uploadResourceInfoWrapper.setPayloadData(payloadData);
+
+
+
+ } catch (IOException e) {
+ log.info("Invalid json was received or Error while closing input Stream.");
+ log.debug("Invalid json was received or Error while closing input Stream. {}", e.getMessage(), e);
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
+
+ Response errorResp = buildErrorResponse(responseFormat);
+ responseWrapper.setInnerElement(errorResp);
+
+ }
+ }
protected void validateUserRole(Wrapper<Response> errorResponseWrapper, User user, ResourceAuthorityTypeEnum resourceAuthority) {
log.debug("validate user role");
@@ -248,7 +278,7 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
} else {
if (!resourceAuthorityEnum.isBackEndImport()) {
isValid = resourceInfoObject.getPayloadName() != null && !resourceInfoObject.getPayloadName().isEmpty();
- // TODO Tal only resource name is checked
+ //Tal only resource name is checked
} else {
isValid = true;
}
@@ -256,6 +286,7 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
}
} catch (JsonSyntaxException e) {
+ log.debug("Invalid json was received. {}", e.getMessage(), e);
isValid = false;
}
@@ -294,8 +325,7 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
protected void validatePayloadIsTosca(Wrapper<Response> responseWrapper, UploadResourceInfo uploadResourceInfo, User user, String toscaPayload) {
log.debug("checking payload is valid tosca");
boolean isValid;
- String heatDecodedPayload = (GeneralUtility.isBase64Encoded(toscaPayload)) ? new String(Base64.decodeBase64(toscaPayload)) : toscaPayload;
- Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(heatDecodedPayload);
+ Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(toscaPayload);
Either<String, ResultStatusEnum> findFirstToscaStringElement = ImportUtils.findFirstToscaStringElement(mappedToscaTemplate, ToscaTagNamesEnum.TOSCA_VERSION);
if (findFirstToscaStringElement.isRight()) {
@@ -337,9 +367,7 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
protected void validatePayloadNameSpace(Wrapper<Response> responseWrapper, UploadResourceInfo resourceInfo, User user, String toscaPayload) {
boolean isValid;
String nameSpace = "";
-
- String heatDecodedPayload = (GeneralUtility.isBase64Encoded(toscaPayload)) ? new String(Base64.decodeBase64(toscaPayload)) : toscaPayload;
- Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(heatDecodedPayload);
+ Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(toscaPayload);
Either<Map<String, Object>, ResultStatusEnum> toscaElement = ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, ToscaTagNamesEnum.NODE_TYPES);
if (toscaElement.isRight() || toscaElement.left().value().size() != 1) {
isValid = false;
@@ -357,7 +385,7 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
} else {
String str1 = nameSpace.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
String[] findTypes = str1.split("\\.");
- if (ResourceTypeEnum.contains(findTypes[0].toUpperCase())) {
+ if (ResourceTypeEnum.containsName(findTypes[0].toUpperCase())) {
String type = findTypes[0].toUpperCase();
resourceInfo.setResourceType(type);
} else {
@@ -370,8 +398,7 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
protected void validatePayloadIsSingleResource(Wrapper<Response> responseWrapper, UploadResourceInfo uploadResourceInfo, User user, String toscaPayload) {
log.debug("checking payload contains single resource");
boolean isValid;
- String heatDecodedPayload = (GeneralUtility.isBase64Encoded(toscaPayload)) ? new String(Base64.decodeBase64(toscaPayload)) : toscaPayload;
- Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(heatDecodedPayload);
+ Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(toscaPayload);
Either<Map<String, Object>, ResultStatusEnum> toscaElement = ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, ToscaTagNamesEnum.NODE_TYPES);
if (toscaElement.isRight()) {
isValid = false;
@@ -392,8 +419,7 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
protected void validatePayloadIsNotService(Wrapper<Response> responseWrapper, User user, UploadResourceInfo uploadResourceInfo, String toscaPayload) {
log.debug("checking payload is not a tosca service");
- String heatDecodedPayload = (GeneralUtility.isBase64Encoded(toscaPayload)) ? new String(Base64.decodeBase64(toscaPayload)) : toscaPayload;
- Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(heatDecodedPayload);
+ Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(toscaPayload);
Either<Object, ResultStatusEnum> toscaElement = ImportUtils.findToscaElement(mappedToscaTemplate, ToscaTagNamesEnum.TOPOLOGY_TEMPLATE, ToscaElementTypeEnum.ALL);
if (toscaElement.isLeft()) {
@@ -406,24 +432,7 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
}
}
-
- protected void validatePayloadIsTopologyTemplate(Wrapper<Response> responseWrapper, User user, UploadResourceInfo uploadResourceInfo, String toscaPayload) {
- log.debug("checking payload is a tosca topology template");
- String heatDecodedPayload = (GeneralUtility.isBase64Encoded(toscaPayload)) ? new String(Base64.decodeBase64(toscaPayload)) : toscaPayload;
- Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(heatDecodedPayload);
- Either<Object, ResultStatusEnum> toscaElement = ImportUtils.findToscaElement(mappedToscaTemplate, ToscaTagNamesEnum.TOPOLOGY_TEMPLATE, ToscaElementTypeEnum.ALL);
-
- if (toscaElement.isRight()) {
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
- Response errorResponse = buildErrorResponse(responseFormat);
- EnumMap<AuditingFieldsKeysEnum, Object> additionalParam = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
- additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, uploadResourceInfo.getName());
- getComponentsUtils().auditResource(responseFormat, user, null, "", "", AuditingActionEnum.IMPORT_RESOURCE, additionalParam);
- responseWrapper.setInnerElement(errorResponse);
- }
-
- }
-
+
protected void validateToscaTemplatePayloadName(Wrapper<Response> responseWrapper, UploadResourceInfo uploadResourceInfo, User user) {
String toscaTemplatePayloadName = uploadResourceInfo.getPayloadName();
boolean isValidSuffix = false;
@@ -495,7 +504,7 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
responseWrapper.setInnerElement(errorResponse);
} else {
String toscaPayload = resourceInfo.getPayloadData();
- String decodedPayload = (GeneralUtility.isBase64Encoded(toscaPayload)) ? new String(Base64.decodeBase64(toscaPayload)) : toscaPayload;
+ String decodedPayload = new String(Base64.decodeBase64(toscaPayload));
yamlStringWrapper.setInnerElement(decodedPayload);
}
@@ -510,13 +519,26 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
if (responseWrapper.isEmpty()) {
validateDataNotNull(responseWrapper, file, resourceInfoJsonString);
}
- if (responseWrapper.isEmpty()) {
- validateZip(responseWrapper, file, uploadResourceInfoWrapper.getInnerElement().getPayloadName());
- }
-
- // Fill PayLoad From File
- if (responseWrapper.isEmpty()) {
- fillToscaTemplateFromZip(yamlStringWrapper, uploadResourceInfoWrapper.getInnerElement().getPayloadName(), file);
+ if(!resourceAuthorityEnum.equals(ResourceAuthorityTypeEnum.CSAR_TYPE_BE)){
+ if (responseWrapper.isEmpty()) {
+ validateZip(responseWrapper, file, uploadResourceInfoWrapper.getInnerElement().getPayloadName());
+ }
+
+ // Fill PayLoad From File
+ if (responseWrapper.isEmpty()) {
+ fillToscaTemplateFromZip(yamlStringWrapper, uploadResourceInfoWrapper.getInnerElement().getPayloadName(), file);
+ }
+ }else{
+
+ if (responseWrapper.isEmpty()) {
+ validateCsar(responseWrapper, file, uploadResourceInfoWrapper.getInnerElement().getPayloadName());
+ }
+
+ // Fill PayLoad From File
+ if (responseWrapper.isEmpty()) {
+ fillPayloadDataFromFile(responseWrapper, uploadResourceInfoWrapper.getInnerElement(), file);
+ }
+
}
} else {
@@ -548,12 +570,12 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
}
}
}
-
- protected void commonGeneralValidations(Wrapper<Response> responseWrapper, Wrapper<User> userWrapper, Wrapper<UploadResourceInfo> uploadResourceInfoWrapper, ResourceAuthorityTypeEnum resourceAuthorityEnum, String userId,
+
+ protected void commonGeneralValidations(Wrapper<Response> responseWrapper, Wrapper<User> userWrapper, Wrapper<UploadResourceInfo> uploadResourceInfoWrapper, ResourceAuthorityTypeEnum resourceAuthorityEnum, String userUserId,
String resourceInfoJsonString) {
if (responseWrapper.isEmpty()) {
- validateUserExist(responseWrapper, userWrapper, userId);
+ validateUserExist(responseWrapper, userWrapper, userUserId);
}
if (responseWrapper.isEmpty()) {
@@ -575,7 +597,7 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
private void validateResourceType(Wrapper<Response> responseWrapper, UploadResourceInfo uploadResourceInfo, User user) {
String resourceType = uploadResourceInfo.getResourceType();
- if (resourceType == null || !ResourceTypeEnum.contains(resourceType)) {
+ if (resourceType == null || !ResourceTypeEnum.containsName(resourceType)) {
ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
Response errorResponse = buildErrorResponse(responseFormat);
EnumMap<AuditingFieldsKeysEnum, Object> additionalParam = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
@@ -610,7 +632,7 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
}
}
- protected void topologyTemplatePayloadValidations(Wrapper<Response> responseWrapper, Wrapper<String> yamlStringWrapper, User user, UploadResourceInfo uploadResourceInfo) {
+ /*protected void topologyTemplatePayloadValidations(Wrapper<Response> responseWrapper, Wrapper<String> yamlStringWrapper, User user, UploadResourceInfo uploadResourceInfo) {
if (responseWrapper.isEmpty()) {
validatePayloadIsYml(responseWrapper, user, uploadResourceInfo, yamlStringWrapper.getInnerElement());
@@ -622,16 +644,23 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
validatePayloadIsTopologyTemplate(responseWrapper, user, uploadResourceInfo, yamlStringWrapper.getInnerElement());
}
- }
+ }*/
protected void handleImport(Wrapper<Response> responseWrapper, User user, UploadResourceInfo resourceInfoObject, String yamlAsString, ResourceAuthorityTypeEnum authority, boolean createNewVersion, String resourceUniqueId) {
- Either<ImmutablePair<org.openecomp.sdc.be.model.Resource, ActionStatus>, ResponseFormat> createOrUpdateResponse = null;
- Response response = null;
+ Either<ImmutablePair<org.openecomp.sdc.be.model.Resource, ActionStatus>, ResponseFormat> createOrUpdateResponse;
+ Response response;
Object representation = null;
if (CsarValidationUtils.isCsarPayloadName(resourceInfoObject.getPayloadName())) {
log.debug("import resource from csar");
+
createOrUpdateResponse = importResourceFromUICsar(resourceInfoObject, user, resourceUniqueId);
+ //if (createOrUpdateResponse.isLeft()){
+ // LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction();
+ // lifecycleChangeInfo.setUserRemarks("certification on import");
+ // Function<Resource, Either<Boolean, ResponseFormat>> validator = (resource) -> resourceImportManager.getResourceBusinessLogic().validatePropertiesDefaultValues(createOrUpdateResponse.left().value().left);
+ //}
+
} else if (!authority.isUserTypeResource()) {
log.debug("import normative type resource");
createOrUpdateResponse = resourceImportManager.importNormativeResource(yamlAsString, resourceInfoObject, user, createNewVersion, true);
@@ -645,7 +674,7 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
try {
representation = RepresentationUtils.toRepresentation(createOrUpdateResponse.left().value().getLeft());
} catch (IOException e) {
- e.printStackTrace();
+ log.debug("Error while building resource representation : {}", e.getMessage(), e);
}
ActionStatus successStatus = createOrUpdateResponse.left().value().right;
response = buildOkResponse(getComponentsUtils().getResponseFormat(successStatus), representation);
@@ -655,9 +684,9 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
private Either<ImmutablePair<org.openecomp.sdc.be.model.Resource, ActionStatus>, ResponseFormat> importResourceFromUICsar(UploadResourceInfo resourceInfoObject, User user, String resourceUniqueId) {
- Either<org.openecomp.sdc.be.model.Resource, ResponseFormat> createOrUpdateResourceRes = null;
+ Either<org.openecomp.sdc.be.model.Resource, ResponseFormat> createOrUpdateResourceRes;
ImmutablePair<org.openecomp.sdc.be.model.Resource, ActionStatus> result = null;
- ActionStatus actionStatus = null;
+ ActionStatus actionStatus;
org.openecomp.sdc.be.model.Resource resource = new org.openecomp.sdc.be.model.Resource();
String payloadName = resourceInfoObject.getPayloadName();
fillResourceFromResourceInfoObject(resource, resourceInfoObject);
@@ -673,7 +702,7 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
return Either.right(createOrUpdateResourceRes.right().value());
}
if (resourceUniqueId == null || resourceUniqueId.isEmpty()) {
- createOrUpdateResourceRes = resourceImportManager.getResourceBusinessLogic().createResource(resource, user, csarUIPayload, payloadName);
+ createOrUpdateResourceRes = resourceImportManager.getResourceBusinessLogic().createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, csarUIPayload, payloadName);
if (createOrUpdateResourceRes.isRight()) {
return Either.right(createOrUpdateResourceRes.right().value());
}
@@ -714,7 +743,7 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
}
log.debug("checking payload is valid tosca");
- String heatDecodedPayload = (GeneralUtility.isBase64Encoded(toscaYaml)) ? new String(Base64.decodeBase64(toscaYaml)) : toscaYaml;
+ String heatDecodedPayload = toscaYaml;
Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(heatDecodedPayload);
Either<String, ResultStatusEnum> findFirstToscaStringElement = ImportUtils.findFirstToscaStringElement(mappedToscaTemplate, ToscaTagNamesEnum.TOSCA_VERSION);
@@ -775,8 +804,8 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
log.info("Failed to decode received csar", csarUUID);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_NOT_FOUND, csarUUID));
}
-
- byte[] decodedPayload = (GeneralUtility.isBase64Encoded(payloadData)) ? Base64.decodeBase64(payloadData.getBytes(StandardCharsets.UTF_8)) : payloadData.getBytes(StandardCharsets.UTF_8);
+
+ byte[] decodedPayload = Base64.decodeBase64(payloadData.getBytes(StandardCharsets.UTF_8));
if (decodedPayload == null) {
log.info("Failed to decode received csar", csarUUID);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_NOT_FOUND, csarUUID));
@@ -840,4 +869,59 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
}
return response;
}
+
+ protected void validateXECOMPInstanceIDHeader(String instanceIdHeader, Wrapper<ResponseFormat> responseWrapper) {
+ ResponseFormat responseFormat;
+ if(StringUtils.isEmpty(instanceIdHeader) ){
+ log.debug("Missing X-ECOMP-InstanceID header");
+ responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
+ responseWrapper.setInnerElement(responseFormat);
+ }
+ }
+
+ protected void validateHttpCspUserIdHeader(String header, Wrapper<ResponseFormat> responseWrapper) {
+ ResponseFormat responseFormat;
+ if( StringUtils.isEmpty(header)){
+ log.debug("MissingUSER_ID");
+ responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID);
+ responseWrapper.setInnerElement(responseFormat);
+ }
+ }
+
+ /**
+ * Convert json to Object object
+ * @param <T>
+ * @param classSupplier
+ * @param json
+ * @return
+ */
+ public <T> Either<T, ResponseFormat> parseToObject(String json, Supplier<Class<T>> classSupplier) {
+
+ try {
+ T object = RepresentationUtils.fromRepresentation(json, classSupplier.get());
+ return Either.left(object);
+ } catch (Exception e) {
+ log.debug("Failed to parse json to {} object", classSupplier.get().getName(), e);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
+ return Either.right(responseFormat);
+ }
+ }
+
+ /**
+ * Convert json to Object object
+ * @param <T>
+ * @param json
+ * @param type
+ * @return
+ */
+ public <T> Either<List<T>, ResponseFormat> parseListOfObjects(String json, Type type) {
+ try {
+ List<T> listOfObjects = gson.fromJson(json, type);
+ return Either.left(listOfObjects);
+ } catch (Exception e) {
+ log.debug("Failed to parse json to {} object", type.getClass().getName(), e);
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
+ return Either.right(responseFormat);
+ }
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AdditionalInformationServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AdditionalInformationServlet.java
index aaf8f96dca..560ab7d023 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AdditionalInformationServlet.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AdditionalInformationServlet.java
@@ -39,9 +39,9 @@ import javax.ws.rs.core.Response;
import org.openecomp.sdc.be.components.impl.AdditionalInformationBusinessLogic;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterInfo;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.impl.WebAppContextWrapper;
-import org.openecomp.sdc.be.model.AdditionalInfoParameterInfo;
import org.openecomp.sdc.be.model.AdditionalInformationDefinition;
import org.openecomp.sdc.common.api.Constants;
import org.openecomp.sdc.common.config.EcompErrorName;
@@ -75,9 +75,9 @@ public class AdditionalInformationServlet extends BeGenericServlet {
@ApiResponses(value = { @ApiResponse(code = 201, message = "Additional information created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
@ApiResponse(code = 409, message = "Additional information key already exist") })
public Response createResourceAdditionalInformationLabel(@ApiParam(value = "resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId,
- @ApiParam(value = "Additional information key value to be created", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+ @ApiParam(value = "Additional information key value to be created", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userUserId) {
- return createAdditionalInformationLabelForComponent(NodeTypeEnum.Resource, resourceId, request, userId, data);
+ return createAdditionalInformationLabelForComponent(NodeTypeEnum.Resource, resourceId, request, userUserId, data);
}
@@ -89,9 +89,9 @@ public class AdditionalInformationServlet extends BeGenericServlet {
@ApiResponses(value = { @ApiResponse(code = 201, message = "Additional information created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
@ApiResponse(code = 409, message = "Additional information key already exist") })
public Response createServiceAdditionalInformationLabel(@ApiParam(value = "service id to update with new property", required = true) @PathParam("serviceId") final String serviceId,
- @ApiParam(value = "Additional information key value to be created", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+ @ApiParam(value = "Additional information key value to be created", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userUserId) {
- return createAdditionalInformationLabelForComponent(NodeTypeEnum.Service, serviceId, request, userId, data);
+ return createAdditionalInformationLabelForComponent(NodeTypeEnum.Service, serviceId, request, userUserId, data);
}
@@ -240,7 +240,7 @@ public class AdditionalInformationServlet extends BeGenericServlet {
if (either.isRight()) {
ResponseFormat responseFormat = either.right().value();
- log.info("Failed to create additional information {}. REason - {}", additionalInfoParameterInfo, responseFormat);
+ log.info("Failed to create additional information {}. Reason - {}", additionalInfoParameterInfo, responseFormat);
return buildErrorResponse(responseFormat);
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ArtifactServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ArtifactServlet.java
index b7af00a7d2..b7fef4554f 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ArtifactServlet.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ArtifactServlet.java
@@ -20,6 +20,8 @@
package org.openecomp.sdc.be.servlets;
+import java.util.Map;
+
import javax.inject.Singleton;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
@@ -38,23 +40,18 @@ import javax.ws.rs.core.Response;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;
-import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperation;
+import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.model.ArtifactDefinition;
import org.openecomp.sdc.be.model.ArtifactUiDownloadData;
import org.openecomp.sdc.be.model.Operation;
-import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.config.EcompErrorName;
import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.google.gson.Gson;
-import com.google.gson.JsonElement;
-import com.google.gson.JsonObject;
import com.jcabi.aspects.Loggable;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
@@ -75,8 +72,6 @@ public class ArtifactServlet extends BeGenericServlet {
private static Logger log = LoggerFactory.getLogger(ArtifactServlet.class.getName());
- private Gson gson = new Gson();
-
// *************** Resources
@POST
@Path("/resources/{resourceId}/artifacts")
@@ -88,11 +83,10 @@ public class ArtifactServlet extends BeGenericServlet {
public Response loadArtifact(@PathParam("resourceId") final String resourceId, @ApiParam(value = "json describe the artifact", required = true) String data, @Context final HttpServletRequest request) {
String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
+ log.debug("Start handle request of {}" , url);
try {
return handleUploadRequest(data, request, resourceId, ComponentTypeEnum.RESOURCE);
- } catch (Throwable e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "loadArtifact");
+ } catch (Exception e) {
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("loadArtifact");
log.debug("loadArtifact unexpected exception", e);
return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -109,11 +103,10 @@ public class ArtifactServlet extends BeGenericServlet {
@Context final HttpServletRequest request) {
String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
+ log.debug("Start handle request of {}" , url);
try {
return handleUpdateRequest(data, request, resourceId, artifactId, ComponentTypeEnum.RESOURCE);
- } catch (Throwable e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "updateArtifact");
+ } catch (Exception e) {
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("updateArtifact");
log.debug("updateArtifact unexpected exception", e);
return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -129,11 +122,10 @@ public class ArtifactServlet extends BeGenericServlet {
public Response deleteArtifact(@PathParam("resourceId") final String resourceId, @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) {
String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
+ log.debug("Start handle request of {}" , url);
try {
return handleDeleteRequest(request, resourceId, artifactId, ComponentTypeEnum.RESOURCE, null, null);
- } catch (Throwable e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "deleteArtifact");
+ } catch (Exception e) {
log.debug("deleteArtifact unexpected exception", e);
return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
}
@@ -150,11 +142,10 @@ public class ArtifactServlet extends BeGenericServlet {
public Response loadInformationArtifact(@PathParam("serviceId") final String serviceId, @ApiParam(value = "json describe the artifact", required = true) String data, @Context final HttpServletRequest request) {
String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
+ log.debug("Start handle request of {}" , url);
try {
return handleUploadRequest(data, request, serviceId, ComponentTypeEnum.SERVICE);
- } catch (Throwable e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "loadInformationArtifact");
+ } catch (Exception e) {
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("loadInformationArtifact");
log.debug("loadInformationArtifact unexpected exception", e);
return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -171,11 +162,10 @@ public class ArtifactServlet extends BeGenericServlet {
@Context final HttpServletRequest request) {
String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
+ log.debug("Start handle request of {}" , url);
try {
return handleUpdateRequest(data, request, serviceId, artifactId, ComponentTypeEnum.SERVICE);
- } catch (Throwable e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "updateInformationArtifact");
+ } catch (Exception e) {
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("updateInformationArtifact");
log.debug("updateInformationArtifact unexpected exception", e);
return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -193,11 +183,10 @@ public class ArtifactServlet extends BeGenericServlet {
@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @HeaderParam(value = Constants.MD5_HEADER) String origMd5) {
String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
+ log.debug("Start handle request of {}" , url);
try {
return handleUpdateRequest(data, request, serviceId, artifactId, ComponentTypeEnum.SERVICE);
- } catch (Throwable e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "updateApiArtifact");
+ } catch (Exception e) {
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("updateApiArtifact");
log.debug("updateApiArtifact unexpected exception", e);
return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -214,11 +203,10 @@ public class ArtifactServlet extends BeGenericServlet {
@HeaderParam(value = Constants.MD5_HEADER) String origMd5) {
String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
+ log.debug("Start handle request of {}" , url);
try {
return handleDeleteRequest(request, serviceId, artifactId, ComponentTypeEnum.SERVICE, null, null);
- } catch (Throwable e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "deleteApiArtifact");
+ } catch (Exception e) {
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("deleteApiArtifact");
log.debug("deleteApiArtifact unexpected exception", e);
return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -234,11 +222,10 @@ public class ArtifactServlet extends BeGenericServlet {
public Response deleteInformationalArtifact(@PathParam("serviceId") final String serviceId, @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) {
String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
+ log.debug("Start handle request of {}" , url);
try {
return handleDeleteRequest(request, serviceId, artifactId, ComponentTypeEnum.SERVICE, null, null);
- } catch (Throwable e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "deleteInformationalArtifact");
+ } catch (Exception e) {
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("deleteInformationalArtifact");
log.debug("deleteInformationalArtifact unexpected exception", e);
return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -258,11 +245,10 @@ public class ArtifactServlet extends BeGenericServlet {
public Response downloadServiceArtifactBase64(@PathParam("serviceId") final String serviceId, @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) {
String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
+ log.debug("Start handle request of {}" , url);
try {
return handleDownloadRequest(request, serviceId, artifactId, null, ComponentTypeEnum.SERVICE, null);
- } catch (Throwable e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "downloadServiceArtifactBase64");
+ } catch (Exception e) {
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("downloadServiceArtifactBase64");
log.debug("downloadServiceArtifactBase64 unexpected exception", e);
return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -278,11 +264,10 @@ public class ArtifactServlet extends BeGenericServlet {
public Response downloadResourceArtifactBase64(@PathParam("resourceId") final String resourceId, @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) {
String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
+ log.debug("Start handle request of {}" , url);
try {
return handleDownloadRequest(request, resourceId, artifactId, null, ComponentTypeEnum.RESOURCE, null);
- } catch (Throwable e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "downloadResourceArtifactBase64");
+ } catch (Exception e) {
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("downloadResourceArtifactBase64");
log.debug("downloadResourceArtifactBase64 unexpected exception", e);
return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -300,11 +285,10 @@ public class ArtifactServlet extends BeGenericServlet {
@PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId, @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) {
String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
+ log.debug("Start handle request of {}" , url);
try {
return handleDownloadRequest(request, componentInstanceId, artifactId, componentId, ComponentTypeEnum.RESOURCE_INSTANCE, containerComponentType);
- } catch (Throwable e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "downloadResourceInstanceArtifactBase64");
+ } catch (Exception e) {
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("downloadResourceInstanceArtifactBase64");
log.debug("downloadResourceInstanceArtifactBase64 unexpected exception", e);
return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -325,11 +309,10 @@ public class ArtifactServlet extends BeGenericServlet {
@Context final HttpServletRequest request) {
String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
+ log.debug("Start handle request of {}" , url);
try {
- return handleArtifactRequest(data, request, resourceId, interfaceType, operation, null, ComponentTypeEnum.RESOURCE, ArtifactOperation.Create, null, null);
- } catch (Throwable e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "loadArtifactToInterface");
+ return handleArtifactRequest(data, request, resourceId, interfaceType, operation, null, ComponentTypeEnum.RESOURCE, ArtifactOperationEnum.Create, null, null);
+ } catch (Exception e) {
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("loadArtifactToInterface");
log.debug("loadArtifactToInterface unexpected exception", e);
return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -348,11 +331,10 @@ public class ArtifactServlet extends BeGenericServlet {
@Context final HttpServletRequest request) {
String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
+ log.debug("Start handle request of {}" , url);
try {
return handleDeleteRequest(request, resourceId, artifactId, ComponentTypeEnum.RESOURCE, interfaceType, operation);
- } catch (Throwable e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "deleteArtifactToInterface");
+ } catch (Exception e) {
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("deleteArtifactToInterface");
log.debug("deleteArtifactToInterface unexpected exception", e);
return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -371,11 +353,10 @@ public class ArtifactServlet extends BeGenericServlet {
@ApiParam(value = "json describe the artifact", required = true) String data) {
String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
+ log.debug("Start handle request of {}" , url);
try {
- return handleArtifactRequest(data, request, resourceId, interfaceType, operation, artifactId, ComponentTypeEnum.RESOURCE, ArtifactOperation.Update, null, null);
- } catch (Throwable e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "updateArtifactToInterface");
+ return handleArtifactRequest(data, request, resourceId, interfaceType, operation, artifactId, ComponentTypeEnum.RESOURCE, ArtifactOperationEnum.Update, null, null);
+ } catch (Exception e) {
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("updateArtifactToInterface");
log.debug("updateArtifactToInterface unexpected exception", e);
return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -394,11 +375,10 @@ public class ArtifactServlet extends BeGenericServlet {
@ApiParam(value = "json describe the artifact", required = true) String data, @Context final HttpServletRequest request) {
String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
+ log.debug("Start handle request of {}" , url);
try {
- return handleArtifactRequest(data, request, componentInstanceId, null, null, artifactId, ComponentTypeEnum.RESOURCE_INSTANCE, ArtifactOperation.Update, componentId, containerComponentType);
- } catch (Throwable e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "updateRIArtifact");
+ return handleArtifactRequest(data, request, componentInstanceId, null, null, artifactId, ComponentTypeEnum.RESOURCE_INSTANCE, ArtifactOperationEnum.Update, componentId, containerComponentType);
+ } catch (Exception e) {
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("updateRIArtifact");
log.debug("updateRIArtifact unexpected exception", e);
return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -417,11 +397,10 @@ public class ArtifactServlet extends BeGenericServlet {
@ApiParam(value = "json describe the artifact", required = true) String data, @Context final HttpServletRequest request) {
String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
+ log.debug("Start handle request of {}" , url);
try {
- return handleArtifactRequest(data, request, componentInstanceId, null, null, artifactId, ComponentTypeEnum.RESOURCE_INSTANCE, ArtifactOperation.Update, componentId, containerComponentType);
- } catch (Throwable e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "loadResourceInstanceHeatEnvArtifact");
+ return handleArtifactRequest(data, request, componentInstanceId, null, null, artifactId, ComponentTypeEnum.RESOURCE_INSTANCE, ArtifactOperationEnum.Update, componentId, containerComponentType);
+ } catch (Exception e) {
log.debug("loadResourceInstanceHeatEnvArtifact unexpected exception", e);
return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
}
@@ -439,11 +418,10 @@ public class ArtifactServlet extends BeGenericServlet {
@Context final HttpServletRequest request) {
String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
+ log.debug("Start handle request of {}" , url);
try {
- return handleArtifactRequest(data, request, componentInstanceId, null, null, null, ComponentTypeEnum.RESOURCE_INSTANCE, ArtifactOperation.Create, componentId, containerComponentType);
- } catch (Throwable e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "loadResourceInstanceHeatEnvArtifact");
+ return handleArtifactRequest(data, request, componentInstanceId, null, null, null, ComponentTypeEnum.RESOURCE_INSTANCE, ArtifactOperationEnum.Create, componentId, containerComponentType);
+ } catch (Exception e) {
log.debug("loadResourceInstanceHeatEnvArtifact unexpected exception", e);
return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
}
@@ -461,27 +439,69 @@ public class ArtifactServlet extends BeGenericServlet {
@ApiParam(value = "json describe the artifact", required = true) String data, @Context final HttpServletRequest request) {
String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
+ log.debug("Start handle request of {}" , url);
try {
- ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(containerComponentType);
return handleDeleteRequest(request, componentInstanceId, artifactId, ComponentTypeEnum.RESOURCE_INSTANCE, null, null, componentId);
- } catch (Throwable e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "deleteArtifact");
+ } catch (Exception e) {
log.debug("deleteArtifact unexpected exception", e);
return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
}
}
+
+
+ @GET
+ @Path("/{containerComponentType}/{componentId}/artifactsByType/{artifactGroupType}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Get component Artifacts", httpMethod = "GET", notes = "Returns artifacts", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Component artifacts"), @ApiResponse(code = 404, message = "Resource/Artifact not found") })
+ public Response getComponentArtifacts(
+ @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
+ @PathParam("componentId") final String componentId, @PathParam("artifactGroupType") final String artifactGroupType, @Context final HttpServletRequest request) {
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}" , url);
+ try {
+ return handleGetArtifactsRequest(request, componentId, null, artifactGroupType, containerComponentType);
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("downloadResourceInstanceArtifactBase64");
+ log.debug("downloadResourceInstanceArtifactBase64 unexpected exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ }
+
+ @GET
+ @Path("/{containerComponentType}/{componentId}/resourceInstances/{componentInstanceId}/artifactsByType/{artifactGroupType}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Get component Artifacts", httpMethod = "GET", notes = "Returns artifacts", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Component artifacts"), @ApiResponse(code = 404, message = "Resource/Artifact not found") })
+ public Response getComponentInstanceArtifacts(
+ @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
+ @PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId, @PathParam("artifactGroupType") final String artifactGroupType, @Context final HttpServletRequest request) {
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}" , url);
+ try {
+ return handleGetArtifactsRequest(request,componentInstanceId , componentId, artifactGroupType, containerComponentType);
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("downloadResourceInstanceArtifactBase64");
+ log.debug("downloadResourceInstanceArtifactBase64 unexpected exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ }
+
// ////////// API END ///////////////////////////
// ************ private *********************
private Response handleUploadRequest(String data, HttpServletRequest request, String componentId, ComponentTypeEnum componentType) {
- return handleArtifactRequest(data, request, componentId, null, componentType, ArtifactOperation.Create);
+ return handleArtifactRequest(data, request, componentId, null, componentType, ArtifactOperationEnum.Create);
}
private Response handleUpdateRequest(String data, HttpServletRequest request, String componentId, String artifactId, ComponentTypeEnum componentType) {
- return handleArtifactRequest(data, request, componentId, artifactId, componentType, ArtifactOperation.Update);
+ return handleArtifactRequest(data, request, componentId, artifactId, componentType, ArtifactOperationEnum.Update);
}
private Response handleDownloadRequest(HttpServletRequest request, String componentId, String artifactId, String parentId, ComponentTypeEnum componentType, String containerComponentType) {
@@ -505,6 +525,25 @@ public class ArtifactServlet extends BeGenericServlet {
}
return response;
}
+
+ private Response handleGetArtifactsRequest(HttpServletRequest request, String componentId, String parentId, String artifactGroupType, String containerComponentType) {
+ String userId = request.getHeader(Constants.USER_ID_HEADER);
+ ServletContext context = request.getSession().getServletContext();
+ ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
+ ComponentTypeEnum componentTypeEnum = parentId == null || parentId.isEmpty()? ComponentTypeEnum.findByParamName(containerComponentType): ComponentTypeEnum.RESOURCE_INSTANCE;
+ Either<Map<String, ArtifactDefinition>, ResponseFormat> actionResult = artifactsLogic.handleGetArtifactsByType(containerComponentType, parentId, componentTypeEnum, componentId, artifactGroupType, userId);
+
+ Response response;
+ if (actionResult.isRight()) {
+ response = buildErrorResponse(actionResult.right().value());
+ } else {
+
+ response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResult.left().value());
+ }
+
+ return response;
+ }
+
private Response handleDeleteRequest(HttpServletRequest request, String componentId, String artifactId, ComponentTypeEnum componentType, String interfaceType, String operationName) {
return handleDeleteRequest(request, componentId, artifactId, componentType, interfaceType, operationName, null);
@@ -514,7 +553,7 @@ public class ArtifactServlet extends BeGenericServlet {
String userId = request.getHeader(Constants.USER_ID_HEADER);
ServletContext context = request.getSession().getServletContext();
ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = artifactsLogic.handleArtifactRequest(componentId, userId, componentType, ArtifactOperation.Delete, artifactId, null, null, null, interfaceType, operationName,
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = artifactsLogic.handleArtifactRequest(componentId, userId, componentType, artifactsLogic.new ArtifactOperationInfo (false, false, ArtifactOperationEnum.Delete), artifactId, null, null, null, interfaceType, operationName,
parentId, null);
Response response;
if (actionResult.isRight()) {
@@ -531,7 +570,7 @@ public class ArtifactServlet extends BeGenericServlet {
}
- private Response handleArtifactRequest(String data, HttpServletRequest request, String componentId, String interfaceName, String operationName, String artifactId, ComponentTypeEnum componentType, ArtifactOperation operation, String parentId,
+ private Response handleArtifactRequest(String data, HttpServletRequest request, String componentId, String interfaceName, String operationName, String artifactId, ComponentTypeEnum componentType, ArtifactOperationEnum operationEnum, String parentId,
String containerComponentType) {
ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
String origMd5 = request.getHeader(Constants.MD5_HEADER);
@@ -540,7 +579,8 @@ public class ArtifactServlet extends BeGenericServlet {
ServletContext context = request.getSession().getServletContext();
ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = artifactsLogic.handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, data, interfaceName, operationName, parentId,
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = artifactsLogic.handleArtifactRequest(componentId, userId, componentType,
+ artifactsLogic.new ArtifactOperationInfo (false, false,operationEnum), artifactId, artifactInfo, origMd5, data, interfaceName, operationName, parentId,
containerComponentType);
Response response;
if (actionResult.isRight()) {
@@ -557,7 +597,7 @@ public class ArtifactServlet extends BeGenericServlet {
}
- private Response handleArtifactRequest(String data, HttpServletRequest request, String componentId, String artifactId, ComponentTypeEnum componentType, ArtifactOperation operation) {
+ private Response handleArtifactRequest(String data, HttpServletRequest request, String componentId, String artifactId, ComponentTypeEnum componentType, ArtifactOperationEnum operation) {
return handleArtifactRequest(data, servletRequest, componentId, null, null, artifactId, componentType, operation, null, null);
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AttributeServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AttributeServlet.java
index b5e64ae00e..c7bc481119 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AttributeServlet.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AttributeServlet.java
@@ -92,9 +92,7 @@ public class AttributeServlet extends AbstractValidationsServlet {
ServletContext context = request.getSession().getServletContext();
String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
- log.debug("modifier id is {}", userId);
- log.debug("data is {}", data);
+ log.debug("Start handle request of {} modifier id is {} data is {}", url, userId, data);
try {
Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
@@ -103,7 +101,7 @@ public class AttributeServlet extends AbstractValidationsServlet {
buildAttributeFromString(data, attributesWrapper, errorWrapper);
if (errorWrapper.isEmpty()) {
- AttributeBusinessLogic businessLogic = getBusinessLogic(context, () -> AttributeBusinessLogic.class);
+ AttributeBusinessLogic businessLogic = getClassFromWebAppContext(context, () -> AttributeBusinessLogic.class);
Either<AttributeDefinition, ResponseFormat> createAttribute = businessLogic.createAttribute(resourceId, attributesWrapper.getInnerElement(), userId);
if (createAttribute.isRight()) {
errorWrapper.setInnerElement(createAttribute.right().value());
@@ -173,7 +171,7 @@ public class AttributeServlet extends AbstractValidationsServlet {
buildAttributeFromString(data, attributesWrapper, errorWrapper);
if (errorWrapper.isEmpty()) {
- AttributeBusinessLogic businessLogic = getBusinessLogic(context, () -> AttributeBusinessLogic.class);
+ AttributeBusinessLogic businessLogic = getClassFromWebAppContext(context, () -> AttributeBusinessLogic.class);
Either<AttributeDefinition, ResponseFormat> eitherUpdateAttribute = businessLogic.updateAttribute(resourceId, attributeId, attributesWrapper.getInnerElement(), userId);
// update property
if (eitherUpdateAttribute.isRight()) {
@@ -233,7 +231,7 @@ public class AttributeServlet extends AbstractValidationsServlet {
try {
// delete the property
- AttributeBusinessLogic businessLogic = getBusinessLogic(context, () -> AttributeBusinessLogic.class);
+ AttributeBusinessLogic businessLogic = getClassFromWebAppContext(context, () -> AttributeBusinessLogic.class);
Either<AttributeDefinition, ResponseFormat> eitherAttribute = businessLogic.deleteAttribute(resourceId, attributeId, userId);
if (eitherAttribute.isRight()) {
log.debug("Failed to delete Attribute. Reason - ", eitherAttribute.right().value());
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/BeGenericServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/BeGenericServlet.java
index f21b57f6fb..2d5402f709 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/BeGenericServlet.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/BeGenericServlet.java
@@ -20,6 +20,7 @@
package org.openecomp.sdc.be.servlets;
+import java.util.EnumMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.function.Supplier;
@@ -43,20 +44,28 @@ import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic;
import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;
import org.openecomp.sdc.be.components.impl.ServiceComponentInstanceBusinessLogic;
import org.openecomp.sdc.be.components.impl.VFComponentInstanceBusinessLogic;
+import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.dao.api.IElementDAO;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.externalapi.servlet.AssetMetadataConverter;
import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.impl.WebAppContextWrapper;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
import org.openecomp.sdc.be.user.UserBusinessLogic;
import org.openecomp.sdc.common.api.Constants;
import org.openecomp.sdc.common.config.EcompErrorName;
+import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
import org.openecomp.sdc.common.servlets.BasicServlet;
import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
+import fj.data.Either;
+
public class BeGenericServlet extends BasicServlet {
@Context
@@ -64,11 +73,11 @@ public class BeGenericServlet extends BasicServlet {
private static Logger log = LoggerFactory.getLogger(BeGenericServlet.class.getName());
- /******************** New error response mechanism **************/
-
+ /******************** New error response mechanism
+ * @param additionalParams **************/
+
protected Response buildErrorResponse(ResponseFormat requestErrorWrapper) {
- Response response = Response.status(requestErrorWrapper.getStatus()).entity(gson.toJson(requestErrorWrapper.getRequestError())).build();
- return response;
+ return Response.status(requestErrorWrapper.getStatus()).entity(gson.toJson(requestErrorWrapper.getRequestError())).build();
}
protected Response buildOkResponse(ResponseFormat errorResponseWrapper, Object entity) {
@@ -96,43 +105,64 @@ public class BeGenericServlet extends BasicServlet {
}
/*******************************************************************************************************/
+ protected Either<User, ResponseFormat> getUser(final HttpServletRequest request, String userId) {
+ Either<User, ActionStatus> eitherCreator = getUserAdminManager(request.getSession().getServletContext()).getUser(userId, false);
+ if (eitherCreator.isRight()) {
+ log.info("createResource method - user is not listed. userId= {}", userId);
+ ResponseFormat errorResponse = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_INFORMATION);
+ User user = new User("", "", userId, "", null, null);
+
+ getComponentsUtils().auditResource(errorResponse, user, null, "", "", AuditingActionEnum.CHECKOUT_RESOURCE, null);
+ return Either.right(errorResponse);
+ }
+ return Either.left(eitherCreator.left().value());
+
+ }
protected UserBusinessLogic getUserAdminManager(ServletContext context) {
- return getBusinessLogic(context, () -> UserBusinessLogic.class);
+ return getClassFromWebAppContext(context, () -> UserBusinessLogic.class);
}
protected ResourceBusinessLogic getResourceBL(ServletContext context) {
- return getBusinessLogic(context, () -> ResourceBusinessLogic.class);
+ return getClassFromWebAppContext(context, () -> ResourceBusinessLogic.class);
}
protected ComponentsCleanBusinessLogic getComponentCleanerBL(ServletContext context) {
- return getBusinessLogic(context, () -> ComponentsCleanBusinessLogic.class);
+ return getClassFromWebAppContext(context, () -> ComponentsCleanBusinessLogic.class);
}
protected ServiceBusinessLogic getServiceBL(ServletContext context) {
- return getBusinessLogic(context, () -> ServiceBusinessLogic.class);
+ return getClassFromWebAppContext(context, () -> ServiceBusinessLogic.class);
}
protected ProductBusinessLogic getProductBL(ServletContext context) {
- return getBusinessLogic(context, () -> ProductBusinessLogic.class);
+ return getClassFromWebAppContext(context, () -> ProductBusinessLogic.class);
}
protected ArtifactsBusinessLogic getArtifactBL(ServletContext context) {
- return getBusinessLogic(context, () -> ArtifactsBusinessLogic.class);
+ return getClassFromWebAppContext(context, () -> ArtifactsBusinessLogic.class);
}
protected ElementBusinessLogic getElementBL(ServletContext context) {
- return getBusinessLogic(context, () -> ElementBusinessLogic.class);
+ return getClassFromWebAppContext(context, () -> ElementBusinessLogic.class);
}
protected MonitoringBusinessLogic getMonitoringBL(ServletContext context) {
- return getBusinessLogic(context, () -> MonitoringBusinessLogic.class);
+ return getClassFromWebAppContext(context, () -> MonitoringBusinessLogic.class);
}
- protected <SomeBusinessLogic> SomeBusinessLogic getBusinessLogic(ServletContext context, Supplier<Class<SomeBusinessLogic>> businessLogicClassGen) {
+ protected AssetMetadataConverter getAssetUtils(ServletContext context) {
+ return getClassFromWebAppContext(context, () -> AssetMetadataConverter.class);
+ }
+
+ protected LifecycleBusinessLogic getLifecycleBL(ServletContext context) {
+ return getClassFromWebAppContext(context, () -> LifecycleBusinessLogic.class);
+ }
+
+ protected <SomeClass> SomeClass getClassFromWebAppContext(ServletContext context, Supplier<Class<SomeClass>> businessLogicClassGen) {
WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
- SomeBusinessLogic monitoringBusinessLogic = webApplicationContext.getBean(businessLogicClassGen.get());
+ SomeClass monitoringBusinessLogic = webApplicationContext.getBean(businessLogicClassGen.get());
return monitoringBusinessLogic;
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/BeMonitoringServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/BeMonitoringServlet.java
index ffcd9c68fc..51b0a1dff7 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/BeMonitoringServlet.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/BeMonitoringServlet.java
@@ -135,17 +135,17 @@ public class BeMonitoringServlet extends BeGenericServlet {
@Path("/version")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "return the ASDC application version", notes = "return the SDC application version", response = String.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "return SDC version"), @ApiResponse(code = 500, message = "Internal Error") })
+ @ApiOperation(value = "return the ASDC application version", notes = "return the ASDC application version", response = String.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "return ASDC version"), @ApiResponse(code = 500, message = "Internal Error") })
public Response getSdcVersion(@Context final HttpServletRequest request) {
try {
String url = request.getMethod() + " " + request.getRequestURI();
log.debug("Start handle request of {}", url);
String version = getVersionFromContext(request);
- log.debug("sdc version from manifest is: {}", version);
+ log.debug("asdc version from manifest is: {}", version);
if (version == null || version.isEmpty()) {
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.SDC_VERSION_NOT_FOUND));
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.ASDC_VERSION_NOT_FOUND));
}
HealthCheckInfo versionInfo = new HealthCheckInfo();
@@ -158,14 +158,14 @@ public class BeMonitoringServlet extends BeGenericServlet {
} catch (Exception e) {
BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "getSDCVersion");
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getSDCVersion");
- log.debug("BE get SDC version unexpected exception", e);
+ log.debug("BE get ASDC version unexpected exception", e);
return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
}
}
private String getVersionFromContext(HttpServletRequest request) {
ServletContext servletContext = request.getSession().getServletContext();
- String version = (String) servletContext.getAttribute(Constants.SDC_RELEASE_VERSION_ATTR);
+ String version = (String) servletContext.getAttribute(Constants.ASDC_RELEASE_VERSION_ATTR);
return version;
}
@@ -187,7 +187,7 @@ public class BeMonitoringServlet extends BeGenericServlet {
object = gson.fromJson(content, clazz);
object.setFields(null);
} catch (Exception e) {
- log.debug("Failed to convert the content {} to object. {}", content.substring(0, Math.min(50, content.length())), e);
+ log.debug("Failed to convert the content {} to object.", content.substring(0, Math.min(50, content.length())), e);
}
return object;
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentInstanceServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentInstanceServlet.java
index 4e6d0bcd7f..6a7ecbb5fe 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentInstanceServlet.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentInstanceServlet.java
@@ -30,6 +30,7 @@ import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
+import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
@@ -43,19 +44,24 @@ import javax.ws.rs.core.Response;
import org.apache.commons.io.IOUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
+import org.openecomp.sdc.be.components.impl.GroupBusinessLogic;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.info.CreateAndAssotiateInfo;
+import org.openecomp.sdc.be.info.GroupDefinitionInfo;
import org.openecomp.sdc.be.model.ComponentInstance;
import org.openecomp.sdc.be.model.ComponentInstanceAttribute;
+import org.openecomp.sdc.be.model.ComponentInstanceInput;
import org.openecomp.sdc.be.model.ComponentInstanceProperty;
+import org.openecomp.sdc.be.model.InputDefinition;
import org.openecomp.sdc.be.model.PropertyConstraint;
import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
+import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.model.operations.impl.PropertyOperation.PropertyConstraintDeserialiser;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.config.EcompErrorName;
import org.openecomp.sdc.common.datastructure.Wrapper;
import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
@@ -75,6 +81,7 @@ import fj.data.Either;
/**
* Root resource (exposed at "/" path)
+ * .json
*/
@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
@Path("/v1/catalog")
@@ -118,7 +125,6 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResponse.left().value());
} catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Create Component Instance");
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Component Instance");
log.debug("create component instance failed with exception", e);
return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -131,7 +137,7 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Update resource instance", httpMethod = "POST", notes = "Returns updated resource instance", response = Response.class)
@ApiResponses(value = { @ApiResponse(code = 200, message = "Resource instance updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
- public Response updateComponentInstance(@PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId,
+ public Response updateComponentInstanceMetadata(@PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId,
@ApiParam(value = "valid values: resources / services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + ","
+ ComponentTypeEnum.PRODUCT_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
@Context final HttpServletRequest request) {
@@ -164,14 +170,13 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
Either<ComponentInstance, ResponseFormat> convertResponse = convertToResourceInstance(data);
if (convertResponse.isRight()) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Resource Instance - updateResourceInstance");
BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - updateResourceInstance");
log.debug("Failed to convert received data to BE format.");
return buildErrorResponse(convertResponse.right().value());
}
ComponentInstance resourceInstance = convertResponse.left().value();
- Either<ComponentInstance, ResponseFormat> actionResponse = componentInstanceLogic.updateComponentInstance(containerComponentType, componentId, componentInstanceId, userId, resourceInstance);
+ Either<ComponentInstance, ResponseFormat> actionResponse = componentInstanceLogic.updateComponentInstanceMetadata(containerComponentType, componentId, componentInstanceId, userId, resourceInstance);
if (actionResponse.isRight()) {
return buildErrorResponse(actionResponse.right().value());
@@ -179,7 +184,6 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
} catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Update Resource Instance");
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Resource Instance");
log.debug("update resource instance with exception", e);
return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -284,7 +288,6 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
}
return response;
} catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Delete Resource Instance");
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Resource Instance");
log.debug("delete resource instance with exception", e);
return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -324,7 +327,6 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
Either<RequirementCapabilityRelDef, ResponseFormat> resultOp;
if (regInfoW.isRight()) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Resource Instance - associateRIToRI");
BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - associateRIToRI");
log.debug("Failed to convert received data to BE format.");
resultOp = Either.right(regInfoW.right().value());
@@ -343,7 +345,6 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
return response;
} catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Associate Resource Instance");
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Associate Resource Instance");
log.debug("associate resource instance to another RI with exception", e);
return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -379,7 +380,6 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
Either<RequirementCapabilityRelDef, ResponseFormat> regInfoW = convertToRequirementCapabilityRelDef(data);
if (regInfoW.isRight()) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Resource Instance - dissociateRIFromRI");
BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - dissociateRIFromRI");
log.debug("Failed to convert received data to BE format.");
return buildErrorResponse(regInfoW.right().value());
@@ -394,7 +394,6 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
} catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Dissociate Resource Instance");
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Dissociate Resource Instance");
log.debug("dissociate resource instance from service failed with exception", e);
return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -441,7 +440,6 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
Either<CreateAndAssotiateInfo, ActionStatus> convertStatus = convertJsonToObject(data, CreateAndAssotiateInfo.class);
if (convertStatus.isRight()) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Resource Instance - createAndAssociateRIToRI");
BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - createAndAssociateRIToRI");
log.debug("Failed to convert received data to BE format.");
Either<Object, ResponseFormat> formattedResponse = Either.right(getComponentsUtils().getResponseFormat(convertStatus.right().value()));
@@ -456,7 +454,6 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
}
return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResponse.left().value());
} catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Create and Associate Resource Instance");
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create and Associate Resource Instance");
log.debug("create and associate RI failed with exception", e);
return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -517,8 +514,77 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
} catch (Exception e) {
- log.error("create and associate RI failed with exception: ", e.getMessage());
- log.debug("create and associate RI failed with exception", e);
+ log.error("create and associate RI failed with exception: {}", e.getMessage(), e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+
+ }
+
+ @POST
+ @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/input")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Update resource instance property", httpMethod = "POST", notes = "Returns updated resource instance property", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource instance created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
+ public Response updateResourceInstanceInput(@ApiParam(value = "service id") @PathParam("componentId") final String componentId,
+ @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
+ @ApiParam(value = "resource instance id") @PathParam("componentInstanceId") final String componentInstanceId, @ApiParam(value = "id of user initiating the operation") @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
+ @Context final HttpServletRequest request) {
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+
+ try {
+ Wrapper<String> dataWrapper = new Wrapper<>();
+ Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
+ Wrapper<ComponentInstanceInput> propertyWrapper = new Wrapper<>();
+
+ validateInputStream(request, dataWrapper, errorWrapper);
+ ComponentInstanceInput property = null;
+
+ if (errorWrapper.isEmpty()) {
+ User modifier = new User();
+ modifier.setUserId(userId);
+ log.debug("modifier id is {}", userId);
+
+ Either<ComponentInstanceInput, ResponseFormat> inputEither = getComponentsUtils().convertJsonToObjectUsingObjectMapper(dataWrapper.getInnerElement(), modifier, ComponentInstanceInput.class, AuditingActionEnum.UPDATE_RESOURCE_METADATA, ComponentTypeEnum.SERVICE);;
+ if(inputEither.isRight()){
+ log.debug("Failed to convert data to input definition. Status is {}", inputEither.right().value());
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
+ }
+ property = inputEither.left().value();
+
+ }
+
+ if (property == null) {
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
+ }
+
+
+ log.debug("Start handle request of updateResourceInstanceProperty. Received property is {}", property);
+
+ ServletContext context = request.getSession().getServletContext();
+
+ ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
+ ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum);
+ if (componentInstanceLogic == null) {
+ log.debug("Unsupported component type {}", containerComponentType);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
+ }
+
+ Either<ComponentInstanceInput, ResponseFormat> actionResponse = componentInstanceLogic.createOrUpdateInstanceInputValue(componentTypeEnum, componentId, componentInstanceId, property, userId);
+
+ if (actionResponse.isRight()) {
+ return buildErrorResponse(actionResponse.right().value());
+ }
+
+ ComponentInstanceInput resourceInstanceProperty = actionResponse.left().value();
+ ObjectMapper mapper = new ObjectMapper();
+ String result = mapper.writeValueAsString(resourceInstanceProperty);
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
+
+ } catch (Exception e) {
+ log.error("create and associate RI failed with exception: {}", e.getMessage(), e);
return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
}
@@ -580,8 +646,7 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
return buildResponseFromElement(errorWrapper, attributeWrapper);
} catch (Exception e) {
- log.error("create and associate RI failed with exception: ", e.getMessage());
- log.debug("create and associate RI failed with exception", e);
+ log.error("create and associate RI failed with exception: {}", e.getMessage(), e);
return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
}
@@ -617,8 +682,7 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
}
return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null);
} catch (Exception e) {
- log.error("create and associate RI failed with exception: ", e.getMessage());
- log.debug("create and associate RI failed with exception", e);
+ log.error("create and associate RI failed with exception: {}", e.getMessage(), e);
return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
}
@@ -638,9 +702,6 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
String url = request.getMethod() + " " + request.getRequestURI();
log.debug("Start handle request of {}", url);
try {
-
- log.debug("Start handle request of {}", url);
-
InputStream inputStream = request.getInputStream();
byte[] bytes = IOUtils.toByteArray(inputStream);
@@ -664,7 +725,6 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
Either<ComponentInstance, ResponseFormat> convertResponse = convertToResourceInstance(data);
if (convertResponse.isRight()) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Resource Instance - updateResourceInstance");
BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - updateResourceInstance");
log.debug("Failed to convert received data to BE format.");
return buildErrorResponse(convertResponse.right().value());
@@ -679,14 +739,149 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
} catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Update Resource Instance");
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Resource Instance");
log.debug("update resource instance with exception", e);
return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
}
}
+
+ @POST
+ @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/groupInstance/{groupInstanceId}/property")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Update resource instance property", httpMethod = "POST", notes = "Returns updated resource instance property", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource instance created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
+ public Response updateGroupInstanceProperty(@ApiParam(value = "service id") @PathParam("componentId") final String componentId,
+ @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
+ @ApiParam(value = "resource instance id") @PathParam("componentInstanceId") final String componentInstanceId, @ApiParam(value = "group instance id") @PathParam("groupInstanceId") final String groupInstanceId, @ApiParam(value = "id of user initiating the operation") @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
+ @Context final HttpServletRequest request) {
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+
+ try {
+ Wrapper<String> dataWrapper = new Wrapper<>();
+ Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
+ Wrapper<ComponentInstanceProperty> propertyWrapper = new Wrapper<>();
+
+ validateInputStream(request, dataWrapper, errorWrapper);
+ if (errorWrapper.isEmpty()) {
+ validateClassParse(dataWrapper.getInnerElement(), propertyWrapper, () -> ComponentInstanceProperty.class, errorWrapper);
+ }
+
+ if (!errorWrapper.isEmpty()) {
+ return buildErrorResponse(errorWrapper.getInnerElement());
+ }
+
+ ComponentInstanceProperty property = propertyWrapper.getInnerElement();
+
+ log.debug("Start handle request of updateResourceInstanceProperty. Received property is {}", property);
+
+ ServletContext context = request.getSession().getServletContext();
+
+ ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
+ ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum);
+ if (componentInstanceLogic == null) {
+ log.debug("Unsupported component type {}", containerComponentType);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
+ }
+
+ Either<ComponentInstanceProperty, ResponseFormat> actionResponse = componentInstanceLogic.createOrUpdateGroupInstancePropertyValue(componentTypeEnum, componentId, componentInstanceId, groupInstanceId, property, userId);
+
+ if (actionResponse.isRight()) {
+ return buildErrorResponse(actionResponse.right().value());
+ }
+
+ ComponentInstanceProperty resourceInstanceProperty = actionResponse.left().value();
+ ObjectMapper mapper = new ObjectMapper();
+ String result = mapper.writeValueAsString(resourceInstanceProperty);
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
+
+ } catch (Exception e) {
+ log.error("create and associate RI failed with exception: {}", e.getMessage(), e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+
+ }
+
+ @GET
+ @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/groupInstance/{groupInstId}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Get group artifacts ", httpMethod = "GET", notes = "Returns artifacts metadata according to groupInstId", response = Resource.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "group found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Group not found") })
+ public Response getGroupArtifactById(@PathParam("containerComponentType") final String containerComponentType, @PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId, @PathParam("groupInstId") final String groupInstId,
+ @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+ ServletContext context = request.getSession().getServletContext();
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("(GET) Start handle request of {}", url);
+
+ try {
+
+ GroupBusinessLogic businessLogic = this.getGroupBL(context);
+ ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
+ Either<GroupDefinitionInfo, ResponseFormat> actionResponse = businessLogic.getGroupInstWithArtifactsById(componentTypeEnum, componentId, componentInstanceId, groupInstId, userId, false);
+
+ if (actionResponse.isRight()) {
+ log.debug("failed to get all non abstract {}", containerComponentType);
+ return buildErrorResponse(actionResponse.right().value());
+ }
+
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getGroupArtifactById");
+ log.debug("getGroupArtifactById unexpected exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+
+ }
+
+ //US831698
+ @GET
+ @Path("/{containerComponentType}/{containerComponentId}/componentInstances/{componentInstanceUniqueId}/properties")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Get component instance properties", httpMethod = "GET",
+ notes = "Returns component instance properties", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Properties found"),
+ @ApiResponse(code = 403, message = "Restricted operation"),
+ @ApiResponse(code = 404, message = "Component/Component Instance - not found") })
+ public Response getInstancePropertiesById(@PathParam("containerComponentType") final String containerComponentType,
+ @PathParam("containerComponentId") final String containerComponentId,
+ @PathParam("componentInstanceUniqueId") final String componentInstanceUniqueId,
+ @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+
+ ServletContext context = request.getSession().getServletContext();
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("(GET) Start handle request of {}", url);
+
+ try {
+ ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
+ ComponentInstanceBusinessLogic componentInstanceBL = getComponentInstanceBL(context, componentTypeEnum);
+
+ Either<List<ComponentInstanceProperty>, ResponseFormat> componentInstancePropertiesById = componentInstanceBL
+ .getComponentInstancePropertiesById(containerComponentType, containerComponentId,
+ componentInstanceUniqueId, userId);
+
+ if (componentInstancePropertiesById.isRight()) {
+ log.debug("Failed to get properties of component instance ID: {} in {} with ID: {}",
+ componentInstanceUniqueId, containerComponentType, containerComponentId);
+ return buildErrorResponse(componentInstancePropertiesById.right().value());
+ }
+
+ return buildOkResponse(getComponentsUtils().
+ getResponseFormat(ActionStatus.OK), componentInstancePropertiesById.left().value());
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getGroupArtifactById");
+ log.debug("getGroupArtifactById unexpected exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+
+ }
+
private Either<ComponentInstance, ResponseFormat> convertToResourceInstance(String data) {
// Either<ComponentInstance, ActionStatus> convertStatus =
@@ -700,7 +895,6 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
return Either.left(resourceInstanceInfo);
}
- // TODO Tal New API for Multiple Items move on canvas
private Either<List<ComponentInstance>, ResponseFormat> convertToMultipleResourceInstance(String dataList) {
Either<ComponentInstance[], ResponseFormat> convertStatus = getComponentsUtils().convertJsonToObjectUsingObjectMapper(dataList, new User(), ComponentInstance[].class, null, ComponentTypeEnum.RESOURCE_INSTANCE);
@@ -723,11 +917,10 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
private <T> Either<T, ActionStatus> convertJsonToObject(String data, Class<T> clazz) {
try {
- log.trace("convert json to object. json=\n{}", data);
+ log.trace("convert json to object. json=\n {}", data);
T t = null;
t = gson.fromJson(data, clazz);
if (t == null) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeInvalidJsonInput, "convertJsonToObject");
BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject");
log.debug("object is null after converting from json");
return Either.right(ActionStatus.INVALID_CONTENT);
@@ -735,7 +928,6 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
return Either.left(t);
} catch (Exception e) {
// INVALID JSON
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeInvalidJsonInput, "convertJsonToObject");
BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject");
log.debug("failed to convert from json", e);
return Either.right(ActionStatus.INVALID_CONTENT);
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentServlet.java
index c5bebb41bf..b28700ace4 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentServlet.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentServlet.java
@@ -20,6 +20,11 @@
package org.openecomp.sdc.be.servlets;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.EnumMap;
+import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -38,15 +43,27 @@ import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
+import org.apache.commons.collections.CollectionUtils;
+import org.codehaus.jackson.JsonGenerationException;
+import org.codehaus.jackson.map.JsonMappingException;
import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic;
+import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.datamodel.api.HighestFilterEnum;
+import org.openecomp.sdc.be.datatypes.components.ComponentMetadataDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.FilterKeyEnum;
import org.openecomp.sdc.be.model.CapReqDef;
import org.openecomp.sdc.be.model.Component;
import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.ComponentInstanceProperty;
+import org.openecomp.sdc.be.model.IComponentInstanceConnectedElement;
+import org.openecomp.sdc.be.model.PropertyDefinition;
import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.resources.data.ComponentMetadataData;
+import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer;
import org.openecomp.sdc.common.api.Constants;
import org.openecomp.sdc.common.config.EcompErrorName;
import org.openecomp.sdc.exception.ResponseFormat;
@@ -70,12 +87,12 @@ public class ComponentServlet extends BeGenericServlet {
private static Logger log = LoggerFactory.getLogger(ComponentServlet.class.getName());
@GET
- @Path("/{componentType}/{componentId}/requirmentsCapabilities")
+ @Path("/{componentType}/{componentId}/conformanceLevelValidation")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Get Component Requirments And Capabilities", httpMethod = "GET", notes = "Returns Requirments And Capabilities according to componentId", response = Resource.class)
+ @ApiOperation(value = "Validate Component Conformance Level", httpMethod = "GET", notes = "Returns the result according to conformance level in BE config", response = Resource.class)
@ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") })
- public Response getRequirementAndCapabilities(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @Context final HttpServletRequest request,
+ public Response conformanceLevelValidation(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @Context final HttpServletRequest request,
@HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
Response response;
ServletContext context = request.getSession().getServletContext();
@@ -86,11 +103,11 @@ public class ComponentServlet extends BeGenericServlet {
ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
if (componentTypeEnum != null) {
ComponentBusinessLogic compBL = getComponentBL(componentTypeEnum, context);
- Either<CapReqDef, ResponseFormat> eitherRequirementsAndCapabilities = compBL.getRequirementsAndCapabilities(componentId, componentTypeEnum, userId);
- if (eitherRequirementsAndCapabilities.isRight()) {
- response = buildErrorResponse(eitherRequirementsAndCapabilities.right().value());
+ Either<Boolean, ResponseFormat> eitherConformanceLevel = compBL.validateConformanceLevel(componentId, componentTypeEnum, userId);
+ if (eitherConformanceLevel.isRight()) {
+ response = buildErrorResponse(eitherConformanceLevel.right().value());
} else {
- response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), gson.toJson(eitherRequirementsAndCapabilities.left().value()));
+ response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), gson.toJson(eitherConformanceLevel.left().value()));
}
} else {
response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
@@ -98,6 +115,42 @@ public class ComponentServlet extends BeGenericServlet {
return response;
}
+
+ @GET
+ @Path("/{componentType}/{componentId}/requirmentsCapabilities")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Get Component Requirments And Capabilities", httpMethod = "GET", notes = "Returns Requirments And Capabilities according to componentId", response = Resource.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") })
+ public Response getRequirementAndCapabilities(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @Context final HttpServletRequest request,
+ @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+ Response response;
+ ServletContext context = request.getSession().getServletContext();
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+
+ ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
+ if (componentTypeEnum != null) {
+ try {
+ ComponentBusinessLogic compBL = getComponentBL(componentTypeEnum, context);
+ Either<CapReqDef, ResponseFormat> eitherRequirementsAndCapabilities = compBL.getRequirementsAndCapabilities(componentId, componentTypeEnum, userId);
+ if (eitherRequirementsAndCapabilities.isRight()) {
+ response = buildErrorResponse(eitherRequirementsAndCapabilities.right().value());
+ } else {
+ response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), RepresentationUtils.toRepresentation(eitherRequirementsAndCapabilities.left().value()));
+ }
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Capabilities and requirements for " + componentId);
+ log.debug("getRequirementAndCapabilities failed with exception", e);
+ response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ } else {
+ response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
+ }
+
+ return response;
+ }
@GET
@Path("/{componentType}/latestversion/notabstract")
@@ -119,7 +172,7 @@ public class ComponentServlet extends BeGenericServlet {
ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
ComponentBusinessLogic businessLogic = getComponentBL(componentTypeEnum, context);
- log.debug("Received componentUids size is {}", (componentUids == null ? 0 : componentUids.size()));
+ log.debug("Received componentUids size is {}", componentUids == null ? 0 : componentUids.size());
Either<List<Component>, ResponseFormat> actionResponse = businessLogic.getLatestVersionNotAbstractComponents(false, HighestFilterEnum.HIGHEST_ONLY, componentTypeEnum, internalComponentType, componentUids, userId);
@@ -131,7 +184,6 @@ public class ComponentServlet extends BeGenericServlet {
return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), components);
} catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Certified Non Abstract" + componentType);
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Certified Non Abstract" + componentType);
log.debug("getCertifiedNotAbstractComponents failed with exception", e);
response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -153,8 +205,7 @@ public class ComponentServlet extends BeGenericServlet {
ServletContext context = request.getSession().getServletContext();
String url = request.getMethod() + " " + request.getRequestURI();
- if (log.isDebugEnabled())
- log.debug("(get) Start handle request of {}", url);
+ log.debug("(GET) Start handle request of {}", url);
Response response = null;
try {
@@ -165,12 +216,8 @@ public class ComponentServlet extends BeGenericServlet {
if (log.isDebugEnabled())
log.debug("Received componentUids size is {}", (componentUids == null ? 0 : componentUids.size()));
- // long start = System.currentTimeMillis();
-
Either<List<Component>, ResponseFormat> actionResponse = businessLogic.getLatestVersionNotAbstractComponents(false, HighestFilterEnum.HIGHEST_ONLY, componentTypeEnum, internalComponentType, componentUids, userId);
- // long endBl = System.currentTimeMillis();
-
if (actionResponse.isRight()) {
if (log.isDebugEnabled())
log.debug("failed to get all non abstract {}", componentType);
@@ -180,15 +227,9 @@ public class ComponentServlet extends BeGenericServlet {
Object components = RepresentationUtils.toRepresentation(actionResponse.left().value());
Response responseToReturn = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), components);
- long endResp = System.currentTimeMillis();
-
- // log.info("********** Time calculation in ms: BL {} , Response {},
- // Total {}", (endBl - start ), (endResp - endBl), (endResp -
- // start));
return responseToReturn;
} catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Certified Non Abstract" + componentType);
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Certified Non Abstract" + componentType);
log.debug("getCertifiedNotAbstractComponents failed with exception", e);
response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -199,7 +240,7 @@ public class ComponentServlet extends BeGenericServlet {
}
@GET
- @Path("/{componentType}/latestversion/notabstract/uidonly")
+ @Path("/{componentType}/latestversion/notabstract/metadata")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Get Component uid only", httpMethod = "GET", notes = "Returns componentId", response = Resource.class)
@@ -215,7 +256,7 @@ public class ComponentServlet extends BeGenericServlet {
ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
ComponentBusinessLogic businessLogic = getComponentBL(componentTypeEnum, context);
- Either<List<Map<String, String>>, ResponseFormat> actionResponse = businessLogic.getLatestVersionNotAbstractComponentsUidOnly(false, HighestFilterEnum.HIGHEST_ONLY, componentTypeEnum, internalComponentType, userId);
+ Either<List<Component>, ResponseFormat> actionResponse = businessLogic.getLatestVersionNotAbstractComponentsMetadata(false, HighestFilterEnum.HIGHEST_ONLY, componentTypeEnum, internalComponentType, userId);
if (actionResponse.isRight()) {
log.debug("failed to get all non abstract {}", componentType);
return buildErrorResponse(actionResponse.right().value());
@@ -224,7 +265,6 @@ public class ComponentServlet extends BeGenericServlet {
return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), components);
} catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Certified Non Abstract" + componentType);
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Certified Non Abstract" + componentType);
log.debug("getCertifiedNotAbstractComponents failed with exception", e);
response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -241,11 +281,11 @@ public class ComponentServlet extends BeGenericServlet {
@ApiOperation(value = "Get Component instances", httpMethod = "GET", notes = "Returns component instances", response = Resource.class)
@ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") })
public Response getComponentInstancesFilteredByPropertiesAndInputs(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @Context final HttpServletRequest request,
- @QueryParam("searchText") String searchText, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @ApiParam(value = "uid" + "" + "list", required = true) String data) {
+ @QueryParam("searchText") String searchText, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @ApiParam(value = "uid" + " " + "list", required = true) String data) {
ServletContext context = request.getSession().getServletContext();
String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("(get) Start handle request of {}", url);
+ log.debug("(GET) Start handle request of {}", url);
Response response = null;
try {
ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
@@ -253,18 +293,122 @@ public class ComponentServlet extends BeGenericServlet {
Either<List<ComponentInstance>, ResponseFormat> actionResponse = businessLogic.getComponentInstancesFilteredByPropertiesAndInputs(componentId, componentTypeEnum, userId, searchText);
if (actionResponse.isRight()) {
- log.debug("failed to get all component instances filtered by properties and inputs {}", componentType);
+ log.debug("failed to get all component instances filtered by properties and inputs", componentType);
return buildErrorResponse(actionResponse.right().value());
}
Object components = RepresentationUtils.toRepresentation(actionResponse.left().value());
return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), components);
} catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Component Instances filtered by properties & inputs" + componentType);
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Component Instances filtered by properties & inputs" + componentType);
log.debug("getComponentInstancesFilteredByPropertiesAndInputs failed with exception", e);
response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
return response;
}
}
+
+
+
+ /**
+ * This API is a generic api for ui - the api get a list of strings and return the data on the component according to to list.
+ * for example: list of the string "properties, inputs" will return component with the list of properties and inputs.
+ *
+ * @param componentType
+ * @param componentId
+ * @param dataParamsToReturn
+ * @param request
+ * @param userId
+ * @return
+ */
+
+ @GET
+ @Path("/{componentType}/{componentId}/filteredDataByParams")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Retrieve Resource", httpMethod = "GET", notes = "Returns resource according to resourceId", response = Resource.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Resource not found") })
+ public Response getComponentDataFilteredByParams(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @QueryParam("include") final List<String> dataParamsToReturn, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+
+ ServletContext context = request.getSession().getServletContext();
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}" , url);
+
+ // get modifier id
+ User modifier = new User();
+ modifier.setUserId(userId);
+ log.debug("modifier id is {}" , userId);
+
+ Response response = null;
+
+ try {
+ String resourceIdLower = componentId.toLowerCase();
+
+ ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
+ ComponentBusinessLogic businessLogic = getComponentBL(componentTypeEnum, context);
+
+ log.trace("get component with id {} filtered by ui params", componentId);
+ Either<UiComponentDataTransfer, ResponseFormat> actionResponse = businessLogic.getComponentDataFilteredByParams(resourceIdLower, modifier, dataParamsToReturn);
+
+ if (actionResponse.isRight()) {
+ log.debug("failed to get component data filtered by ui params");
+ response = buildErrorResponse(actionResponse.right().value());
+ return response;
+ }
+ Object resource = RepresentationUtils.toRepresentation(actionResponse.left().value());
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), resource);
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get component filtered by ui params");
+ log.debug("get resource failed with exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+
+ }
+ }
+
+
+ @GET
+ @Path("/{componentType}/{componentId}/filteredproperties/{propertyNameFragment}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Retrieve properties belonging to component instances of specific component by name and optionally resource type", httpMethod = "GET", notes = "Returns properties belonging to component instances of specific component by name and optionally resource type", response = Map.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") })
+ public Response getFilteredComponentInstanceProperties(
+ @PathParam("componentType") final String componentType,
+ @PathParam("componentId") final String componentId,
+ @PathParam("propertyNameFragment") final String propertyNameFragment,
+ @QueryParam("resourceType") List<String> resourceTypes,
+ @Context final HttpServletRequest request,
+ @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+
+ ServletContext context = request.getSession().getServletContext();
+ User user = new User();
+ user.setUserId(userId);
+ log.debug("User Id is {}" , userId);
+ Response response = null;
+ try {
+ ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
+ ComponentBusinessLogic businessLogic = getComponentBL(componentTypeEnum, context);
+ Map<FilterKeyEnum, List<String>> filters = new EnumMap<>(FilterKeyEnum.class);
+ List<String> propertyNameFragments = new ArrayList<>();
+ propertyNameFragments.add(propertyNameFragment);
+ filters.put(FilterKeyEnum.NAME_FRAGMENT, propertyNameFragments);
+ if(CollectionUtils.isNotEmpty(resourceTypes)){
+ filters.put(FilterKeyEnum.RESOURCE_TYPE, resourceTypes);
+ }
+ Either<Map<String, List<IComponentInstanceConnectedElement>>, ResponseFormat> actionResponse = businessLogic.getFilteredComponentInstanceProperties(componentId, filters, userId);
+ if (actionResponse.isRight()) {
+ response = buildErrorResponse(actionResponse.right().value());
+ return response;
+ }
+ Object resource = RepresentationUtils.toRepresentation(actionResponse.left().value());
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), resource);
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Filtered Component Instance Properties");
+ log.debug("Getting of filtered component instance properties failed with exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+
+ }
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ConfigServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ConfigServlet.java
index 2a3a87d942..79202ac94f 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ConfigServlet.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ConfigServlet.java
@@ -63,9 +63,7 @@ public class ConfigServlet extends BasicServlet {
log.warn("Configuration of type {} was not found", Configuration.class);
}
log.debug("{}", configuration);
- if (log.isInfoEnabled()) {
- log.debug("Info level ENABLED...");
- }
+ log.info("Info level ENABLED...");
log.info("The value returned from getConfig is {}", configuration);
result = gson.toJson(configuration);
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ConsumerServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ConsumerServlet.java
index 0603f267ab..5e9056ba75 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ConsumerServlet.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ConsumerServlet.java
@@ -204,7 +204,7 @@ public class ConsumerServlet extends BeGenericServlet {
ConsumerDefinition consumer = null;
Gson gson = new Gson();
try {
- log.trace("convert json to object. json=\n{}", data);
+ log.trace("convert json to object. json=\n {}", data);
consumer = gson.fromJson(data, ConsumerDefinition.class);
if (consumer == null) {
BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeInvalidJsonInput, "convertJsonToObject");
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/CsarBuildServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/CsarBuildServlet.java
index 4ba6b7516d..4f8bffa066 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/CsarBuildServlet.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/CsarBuildServlet.java
@@ -90,77 +90,6 @@ public class CsarBuildServlet extends ToscaDaoServlet {
*/
public static final String TOSCA_META_PATH = "TOSCA-Metadata/TOSCA.meta";
- // protected void addToscaMetaToZip(ZipOutputStream zipOutputStream,
- // TopologyService topService, IResourceUploader resUploader) throws
- // IOException {
- // String serviceVersion = topService.getTopologyVersion();
- // String serviceName = topService.getTopologyName();
- // StringBuffer buff = new StringBuffer();
- //
- // String[] serviceToscaMeta = prepareToscaMetaHeader(serviceName);
- //
- // for( String toAppend : serviceToscaMeta){
- // buff.append(toAppend);
- // }
- //
- // List<String> toscaMetaComponents =
- // prepareToscaMetaComponents(topService.getDependenciesYamls().keySet());
- // for( String toAppend : toscaMetaComponents ){
- // buff.append(toAppend);
- // }
- //
- // Either<ServiceArtifactsDataCollection, ResourceUploadStatus>
- // getServiceArtifactsCollectionStatus =
- // Either.right(ResourceUploadStatus.ERROR);//resUploader.getServiceArtifactsCollection(serviceName,
- // serviceVersion);
- // if(getServiceArtifactsCollectionStatus.isLeft()){
- // List<String> toscaMetaArtifacts =
- // prepareToscaMetaArtifacts(getServiceArtifactsCollectionStatus.left().value());
- // for( String toAppend : toscaMetaArtifacts ){
- // buff.append(toAppend);
- // }
- // }
- //
- // addZipEntry(zipOutputStream, TOSCA_META_PATH, buff.toString());
- // }
-
- // protected List<String> prepareToscaMetaArtifacts(
- // ServiceArtifactsDataCollection serviceArtifactsDataCollection) {
- // List<String> artifactsForToscaMeta = new ArrayList<String>();
- // Iterator<Entry<String, List<ArtifactData>>> nodeTemplateArtifactsItr =
- // serviceArtifactsDataCollection.getServiceArtifactDataMap().entrySet().iterator();
- // while( nodeTemplateArtifactsItr.hasNext() ){
- // Entry<String, List<ArtifactData>> nodeNameArtifacts =
- // nodeTemplateArtifactsItr.next();
- // String nodeName = nodeNameArtifacts.getKey();
- // Iterator<ArtifactData> artifactDataItr =
- // nodeNameArtifacts.getValue().iterator();
- // while( artifactDataItr.hasNext() ){
- // ArtifactData artifactData = artifactDataItr.next();
- // artifactsForToscaMeta.add("\n");
- // artifactsForToscaMeta.add("Name: "+getArtifactPath(nodeName,
- // artifactData)+"\n");
- // artifactsForToscaMeta.add("Content-Type:
- // application/"+getAppliactionMime(artifactData.getArtifactName())+"\n");
- // }
- // }
- // return artifactsForToscaMeta;
- // }
-
- // protected List<String> prepareToscaMetaComponents(Set<String> components)
- // {
- // Iterator<String> resourceNameItr = components.iterator();
- // List<String> componentsForToscaMeta = new ArrayList<String>();
- // while( resourceNameItr.hasNext() ){
- // String resourceName = resourceNameItr.next();
- // componentsForToscaMeta.add("\n");
- // componentsForToscaMeta.add("Name: "+getResourcePath(resourceName)+"\n");
- // componentsForToscaMeta.add("Content-Type:
- // application/vnd.oasis.tosca.definitions.yaml\n");
- //
- // }
- // return componentsForToscaMeta;
- // }
protected String[] prepareToscaMetaHeader(String serviceName) {
return new String[] { "TOSCA-Meta-File-Version: 1.0\n", "CSAR-Version: 1.1\n", "Created-By: INTERWISE\n", "\n", "Entry-Definitions: Definitions/" + serviceName + ".yaml\n", "\n", "Name: Definitions/" + serviceName + ".yaml\n",
@@ -198,17 +127,6 @@ public class CsarBuildServlet extends ToscaDaoServlet {
return mimeType;
}
- // protected void addResourcesToZip(ZipOutputStream zipOutputStream,
- // TopologyService topService) throws IOException {
- // Iterator<Entry<String, String>> resourceNameDataItr =
- // topService.getDependenciesYamls().entrySet().iterator();
- // while( resourceNameDataItr.hasNext() ){
- // Entry<String, String> resourceNameData = resourceNameDataItr.next();
- // addZipEntry(zipOutputStream, getResourcePath(resourceNameData.getKey()),
- // resourceNameData.getValue());
- // }
- // }
-
protected String getArtifactPath(String nodeTamplateName, ESArtifactData artifactData) {
// return "Scripts/"+nodeTamplateName+"/"+
// artifactData.getArtifactName();
@@ -219,57 +137,6 @@ public class CsarBuildServlet extends ToscaDaoServlet {
return "Definitions/" + resourceName + ".yaml";
}
- // protected void addArtifactsToZip(String serviceName, String
- // serviceVersion, ZipOutputStream zipOutputStream, IResourceUploader
- // resourceUploader)
- // throws IOException {
- // //Add Artifacts to Zip
- // Either<ServiceArtifactsDataCollection, ResourceUploadStatus>
- // getServiceArtifactsCollectionStatus =
- // Either.right(ResourceUploadStatus.ERROR);//resourceUploader.getServiceArtifactsCollection(serviceName,
- // serviceVersion);
- // if(getServiceArtifactsCollectionStatus.isLeft()){
- // Iterator<Entry<String, List<ArtifactData>>> nodeTemplateArtifactsItr
- // =getServiceArtifactsCollectionStatus.left().value().getServiceArtifactDataMap().entrySet().iterator();
- // while( nodeTemplateArtifactsItr.hasNext() ){
- // Entry<String, List<ArtifactData>> nodeTemplateArtifacts =
- // nodeTemplateArtifactsItr.next();
- // String nodeTamplateName = nodeTemplateArtifacts.getKey();
- // List<ArtifactData> artifacts = nodeTemplateArtifacts.getValue();
- // for(ArtifactData artifactData : artifacts ){
- // addZipEntry(zipOutputStream,
- // getArtifactPath(nodeTamplateName,artifactData), artifactData.getData());
- // }
- //
- // }
- // }
- // }
-
- // private Response buildResponse(String fileName, ByteArrayOutputStream
- // fileOutputStream) {
- // final InputStream inputStream = new
- // ByteArrayInputStream(fileOutputStream.toByteArray());
- //
- // StreamingOutput stream = new StreamingOutput() {
- // public void write(OutputStream output) throws WebApplicationException {
- // try {
- // IOUtils.copy(inputStream, output);
- // } catch (Exception e) {
- // throw new WebApplicationException(e);
- // }
- // }
- // };
- //
- // return
- // Response.ok(stream).type(MediaType.APPLICATION_OCTET_STREAM_TYPE).header("content-disposition","attachment;
- // filename = "+fileName).build();
- // }
-
- // protected void addZipEntry(ZipOutputStream zipOutputStream, String
- // filePath, String data) throws IOException {
- // addZipEntry(zipOutputStream, filePath, encodeString(data));
- // }
-
private byte[] encodeString(String data) throws CharacterCodingException {
Charset charset = Charset.forName("UTF-8");
CharsetEncoder encoder = charset.newEncoder();
@@ -279,15 +146,6 @@ public class CsarBuildServlet extends ToscaDaoServlet {
return ba;
}
- // private void addZipEntry(ZipOutputStream zipOutputStream, String
- // filePath, byte[] data) throws IOException {
- // log.debug("Adding to CSAR zip :{}", filePath);
- // ZipEntry entry = new ZipEntry(filePath);
- // zipOutputStream.putNextEntry(entry);
- // zipOutputStream.write(data);
- // zipOutputStream.closeEntry();
- // }
-
@Override
public Logger getLogger() {
return log;
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ElementServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ElementServlet.java
index 433a1bfc58..576fc29014 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ElementServlet.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ElementServlet.java
@@ -57,6 +57,7 @@ import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.model.category.CategoryDefinition;
import org.openecomp.sdc.be.model.category.GroupingDefinition;
import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
+import org.openecomp.sdc.be.ui.model.UiCategories;
import org.openecomp.sdc.be.user.UserBusinessLogic;
import org.openecomp.sdc.common.api.Constants;
import org.openecomp.sdc.common.config.EcompErrorName;
@@ -126,6 +127,33 @@ public class ElementServlet extends BeGenericServlet {
return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
}
}
+
+ @GET
+ @Path("/categories")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Retrieve the all resource, service and product categories", httpMethod = "GET", notes = "Retrieve the all resource, service and product categories", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns categories Ok"), @ApiResponse(code = 403, message = "Missing information"),
+ @ApiResponse(code = 409, message = "Restricted operation"), @ApiResponse(code = 500, message = "Internal Server Error") })
+ public Response getAllCategories(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+
+ try {
+ ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext());
+ Either<UiCategories, ResponseFormat> either = elementBL.getAllCategories(userId);
+ if (either.isRight()) {
+ log.debug("No categories were found");
+ return buildErrorResponse(either.right().value());
+ } else {
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), either.left().value());
+ }
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get All Categories");
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get All Categories");
+ log.debug("getAllCategories failed with exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ }
+
@POST
@Path("/category/{componentType}")
@@ -388,7 +416,7 @@ public class ElementServlet extends BeGenericServlet {
@ApiResponses(value = { @ApiResponse(code = 200, message = "Returns artifactTypes Ok"), @ApiResponse(code = 404, message = "No artifactTypes were found"), @ApiResponse(code = 500, message = "Internal Server Error") })
public Response getArtifactTypes(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("(getArtifactTypes) Start handle request of {}", url);
+ log.debug("(GET - getArtifactTypes) Start handle request of {}", url);
try {
ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext());
@@ -568,7 +596,7 @@ public class ElementServlet extends BeGenericServlet {
NodeTypeEnum nodeType = NodeTypeEnum.getByNameIgnoreCase(componentType);
if (nodeType == null) {
- log.info("componentType is not valid: {}", componentType);
+ log.info("componentType is not valid: {]", componentType);
return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/GroupServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/GroupServlet.java
index bde8f93929..32fd06a2a8 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/GroupServlet.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/GroupServlet.java
@@ -20,6 +20,8 @@
package org.openecomp.sdc.be.servlets;
+import java.util.List;
+
import javax.inject.Singleton;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
@@ -40,6 +42,7 @@ import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.info.GroupDefinitionInfo;
import org.openecomp.sdc.be.model.GroupDefinition;
+import org.openecomp.sdc.be.model.GroupProperty;
import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.common.api.Constants;
@@ -48,8 +51,8 @@ import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
import com.jcabi.aspects.Loggable;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
@@ -77,29 +80,33 @@ public class GroupServlet extends AbstractValidationsServlet {
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Get group artifacts ", httpMethod = "GET", notes = "Returns artifacts metadata according to groupId", response = Resource.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "group found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Group not found") })
- public Response getGroupArtifactById(@PathParam("containerComponentType") final String containerComponentType, @PathParam("componentId") final String componentId, @PathParam("groupId") final String groupId,
- @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "group found"),
+ @ApiResponse(code = 403, message = "Restricted operation"),
+ @ApiResponse(code = 404, message = "Group not found") })
+ public Response getGroupArtifactById(@PathParam("containerComponentType") final String containerComponentType,
+ @PathParam("componentId") final String componentId, @PathParam("groupId") final String groupId,
+ @Context final HttpServletRequest request,
+ @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
ServletContext context = request.getSession().getServletContext();
String url = request.getMethod() + " " + request.getRequestURI();
log.debug("(get) Start handle request of {}", url);
- Response response = null;
try {
GroupBusinessLogic businessLogic = this.getGroupBL(context);
ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
- Either<GroupDefinitionInfo, ResponseFormat> actionResponse = businessLogic.getGroupWithArtifactsById(componentTypeEnum, componentId, groupId, userId, false);
+ Either<GroupDefinitionInfo, ResponseFormat> actionResponse = businessLogic
+ .getGroupWithArtifactsById(componentTypeEnum, componentId, groupId, userId, false);
if (actionResponse.isRight()) {
log.debug("failed to get all non abstract {}", containerComponentType);
return buildErrorResponse(actionResponse.right().value());
}
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),
+ actionResponse.left().value());
} catch (Throwable e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "getGroupArtifactById");
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getGroupArtifactById");
log.debug("getGroupArtifactById unexpected exception", e);
return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -112,9 +119,15 @@ public class GroupServlet extends AbstractValidationsServlet {
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Update Group Metadata", httpMethod = "PUT", notes = "Returns updated group definition", response = GroupDefinition.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Group Updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
- public Response updateGroupMetadata(@PathParam("containerComponentType") final String containerComponentType, @PathParam("componentId") final String componentId, @PathParam("groupUniqueId") final String groupUniqueId,
- @ApiParam(value = "Service object to be Updated", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Group Updated"),
+ @ApiResponse(code = 403, message = "Restricted operation"),
+ @ApiResponse(code = 400, message = "Invalid content / Missing content") })
+ public Response updateGroupMetadata(
+ @PathParam("containerComponentType") final String containerComponentType,
+ @PathParam("componentId") final String componentId, @PathParam("groupUniqueId") final String groupUniqueId,
+ @ApiParam(value = "Service object to be Updated", required = true) String data,
+ @Context final HttpServletRequest request,
+ @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
ServletContext context = request.getSession().getServletContext();
String url = request.getMethod() + " " + request.getRequestURI();
@@ -129,7 +142,7 @@ public class GroupServlet extends AbstractValidationsServlet {
try {
GroupBusinessLogic businessLogic = getGroupBL(context);
- Either<GroupDefinition, ResponseFormat> convertResponse = parseToGroup(data);
+ Either<GroupDefinition, ResponseFormat> convertResponse = parseToObject(data, () -> GroupDefinition.class);
if (convertResponse.isRight()) {
log.debug("failed to parse group");
response = buildErrorResponse(convertResponse.right().value());
@@ -139,7 +152,8 @@ public class GroupServlet extends AbstractValidationsServlet {
// Update GroupDefinition
ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
- Either<GroupDefinition, ResponseFormat> actionResponse = businessLogic.updateGroupMetadata(componentId, user, groupUniqueId, componentTypeEnum, updatedGroup, true);
+ Either<GroupDefinition, ResponseFormat> actionResponse = businessLogic
+ .validateAndUpdateGroupMetadata(componentId, user, componentTypeEnum, updatedGroup, true);
if (actionResponse.isRight()) {
log.debug("failed to update GroupDefinition");
@@ -152,7 +166,6 @@ public class GroupServlet extends AbstractValidationsServlet {
return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
} catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Update Group Metadata");
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Group Metadata");
log.debug("update group metadata failed with exception", e);
response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -162,20 +175,74 @@ public class GroupServlet extends AbstractValidationsServlet {
}
/**
- * Convert data to GroupDefinition object
- *
- * @param groupJson
+ * Updates List of properties on a group (only values)
+ * @param containerComponentType
+ * @param componentId
+ * @param groupUniqueId
+ * @param data
+ * @param request
+ * @param userId
* @return
*/
- public Either<GroupDefinition, ResponseFormat> parseToGroup(String groupJson) {
+ @PUT
+ @Path("/{containerComponentType}/{componentId}/groups/{groupUniqueId}/properties")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Updates List of properties on a group (only values)", httpMethod = "PUT", notes = "Returns updated list of properties", response = GroupDefinition.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Group Updated"),
+ @ApiResponse(code = 403, message = "Restricted operation"),
+ @ApiResponse(code = 400, message = "Invalid content / Missing content") })
+ public Response updateGroupProperties(@PathParam("containerComponentType") final String containerComponentType,
+ @PathParam("componentId") final String componentId, @PathParam("groupUniqueId") final String groupUniqueId,
+ @ApiParam(value = "Service object to be Updated", required = true) String data,
+ @Context final HttpServletRequest request,
+ @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+
+ init(log);
+ ServletContext context = request.getSession().getServletContext();
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+
+ User user = new User();
+ user.setUserId(userId);
+ log.debug("modifier id is {}", userId);
+
+ Response response = null;
+
try {
- Gson gson = new GsonBuilder().setPrettyPrinting().create();
- GroupDefinition groupDefinition = gson.fromJson(groupJson, GroupDefinition.class);
- return Either.left(groupDefinition);
+ GroupBusinessLogic businessLogic = getGroupBL(context);
+ Either<List<GroupProperty>, ResponseFormat> convertResponse = parseListOfObjects(data,
+ new TypeToken<List<GroupProperty>>() {
+ }.getType());
+
+ if (convertResponse.isRight()) {
+ log.debug("failed to parse group Property");
+ response = buildErrorResponse(convertResponse.right().value());
+ return response;
+ }
+ List<GroupProperty> groupPropertyToUpdate = convertResponse.left().value();
+
+ // Update GroupDefinition
+ ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
+ Either<List<GroupProperty>, ResponseFormat> actionResponse = businessLogic.validateAndUpdateGroupProperties(
+ componentId, groupUniqueId, user, componentTypeEnum, groupPropertyToUpdate, false);
+
+ if (actionResponse.isRight()) {
+ log.debug("failed to update GroupDefinition");
+ response = buildErrorResponse(actionResponse.right().value());
+ return response;
+ }
+
+ List<GroupProperty> groupProperty = actionResponse.left().value();
+ Object result = RepresentationUtils.toRepresentation(groupProperty);
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
+
} catch (Exception e) {
- log.debug("Failed to parse json (group data) to GroupDefinition object");
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
- return Either.right(responseFormat);
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Group Properties");
+ log.debug("update group properties failed with exception", e);
+ response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ return response;
+
}
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/InputsServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/InputsServlet.java
index e835c43e14..580b2bdb8b 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/InputsServlet.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/InputsServlet.java
@@ -30,6 +30,7 @@ import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
+import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
@@ -38,6 +39,8 @@ import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
+import org.codehaus.jackson.map.ObjectMapper;
+import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
import org.openecomp.sdc.be.components.impl.InputsBusinessLogic;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
@@ -52,6 +55,7 @@ import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
import org.openecomp.sdc.common.api.Constants;
import org.openecomp.sdc.common.config.EcompErrorName;
+import org.openecomp.sdc.common.datastructure.Wrapper;
import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -70,7 +74,7 @@ import fj.data.Either;
@Path("/v1/catalog")
@Api(value = "Input Catalog", description = "Input Servlet")
@Singleton
-public class InputsServlet extends BeGenericServlet {
+public class InputsServlet extends AbstractValidationsServlet {
private static Logger log = LoggerFactory.getLogger(ProductServlet.class.getName());
@@ -102,22 +106,80 @@ public class InputsServlet extends BeGenericServlet {
} catch (Exception e) {
BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Component Instance Inputs" + componentType);
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Inputs" + componentType);
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Inputs " + componentType);
log.debug("getInputs failed with exception", e);
response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
return response;
}
}
+
+
+ @POST
+ @Path("/{containerComponentType}/{componentId}/update/inputs")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Update resource inputs", httpMethod = "POST", notes = "Returns updated input", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Input updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
+ public Response updateComponentInputs(
+ @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
+ @PathParam("componentId") final String componentId,
+ @ApiParam(value = "json describe the input", required = true) String data, @Context final HttpServletRequest request) {
+
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+ String userId = request.getHeader(Constants.USER_ID_HEADER);
+
+ try {
+ User modifier = new User();
+ modifier.setUserId(userId);
+ log.debug("modifier id is {}", userId);
+
+ Either<InputDefinition, ResponseFormat> inputEither = getComponentsUtils().convertJsonToObjectUsingObjectMapper(data, modifier, InputDefinition.class, AuditingActionEnum.UPDATE_RESOURCE_METADATA, ComponentTypeEnum.SERVICE);;
+ if(inputEither.isRight()){
+ log.debug("Failed to convert data to input definition. Status is {}", inputEither.right().value());
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
+ }
+ InputDefinition input = inputEither.left().value();
+
+ log.debug("Start handle request of updateResourceInstanceProperty. Received property is {}", input);
+
+ ServletContext context = request.getSession().getServletContext();
+ ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(containerComponentType);
+
+ InputsBusinessLogic businessLogic = getInputBL(context);
+ if (businessLogic == null) {
+ log.debug("Unsupported component type {}", containerComponentType);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR));
+ }
+
+ Either<InputDefinition, ResponseFormat> actionResponse = businessLogic.updateInputValue(componentType, componentId, input, userId, true, false);
+
+ if (actionResponse.isRight()) {
+ return buildErrorResponse(actionResponse.right().value());
+ }
+
+ InputDefinition resourceInstanceProperty = actionResponse.left().value();
+ ObjectMapper mapper = new ObjectMapper();
+ String result = mapper.writeValueAsString(resourceInstanceProperty);
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
+
+ } catch (Exception e) {
+ log.error("create and associate RI failed with exception: {}", e.getMessage(), e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ }
+
@GET
- @Path("/{componentType}/{componentId}/componentInstances/{instanceId}/{originComonentUid}/inputs")
+ @Path("/{componentType}/{componentId}/componentInstances/{instanceId}/{originComponentUid}/inputs")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Get Inputs only", httpMethod = "GET", notes = "Returns Inputs list", response = Resource.class)
@ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") })
public Response getComponentInstanceInputs(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @PathParam("instanceId") final String instanceId,
- @PathParam("originComonentUid") final String originComonentUid, @Context final HttpServletRequest request, @QueryParam("fromName") String fromName, @QueryParam("amount") int amount,
+ @PathParam("originComponentUid") final String originComonentUid, @Context final HttpServletRequest request, @QueryParam("fromName") String fromName, @QueryParam("amount") int amount,
@HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
ServletContext context = request.getSession().getServletContext();
@@ -128,7 +190,7 @@ public class InputsServlet extends BeGenericServlet {
try {
InputsBusinessLogic businessLogic = getInputBL(context);
- Either<List<InputDefinition>, ResponseFormat> inputsResponse = businessLogic.getInputs(userId, originComonentUid, fromName, amount);
+ Either<List<ComponentInstanceInput>, ResponseFormat> inputsResponse = businessLogic.getComponentInstanceInputs(userId, componentId, instanceId, fromName, amount);
if (inputsResponse.isRight()) {
log.debug("failed to get component instance inputs {}", componentType);
return buildErrorResponse(inputsResponse.right().value());
@@ -138,7 +200,7 @@ public class InputsServlet extends BeGenericServlet {
} catch (Exception e) {
BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Component Instance Inputs" + componentType);
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Inputs" + componentType);
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Inputs " + componentType);
log.debug("getInputs failed with exception", e);
response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
return response;
@@ -157,13 +219,13 @@ public class InputsServlet extends BeGenericServlet {
ServletContext context = request.getSession().getServletContext();
String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("(get) Start handle request of {}", url);
+ log.debug("(GET) Start handle request of {}", url);
Response response = null;
try {
InputsBusinessLogic businessLogic = getInputBL(context);
- Either<List<ComponentInstanceProperty>, ResponseFormat> inputPropertiesRes = businessLogic.getComponentInstancePropertiesByInputId(userId, instanceId, inputId);
+ Either<List<ComponentInstanceProperty>, ResponseFormat> inputPropertiesRes = businessLogic.getComponentInstancePropertiesByInputId(userId, componentId, instanceId, inputId);
if (inputPropertiesRes.isRight()) {
log.debug("failed to get properties of input: {}, with instance id: {}", inputId, instanceId);
return buildErrorResponse(inputPropertiesRes.right().value());
@@ -199,6 +261,43 @@ public class InputsServlet extends BeGenericServlet {
InputsBusinessLogic businessLogic = getInputBL(context);
Either<List<ComponentInstanceInput>, ResponseFormat> inputsRes = businessLogic.getInputsForComponentInput(userId, componentId, inputId);
+
+ if (inputsRes.isRight()) {
+ log.debug("failed to get inputs of input: {}, with instance id: {}", inputId, componentId);
+ return buildErrorResponse(inputsRes.right().value());
+ }
+ Object properties = RepresentationUtils.toRepresentation(inputsRes.left().value());
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), properties);
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get inputs by input id {}, for component {} ", inputId, componentId);
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get inputs by input id: " + inputId + " for component with id: " + componentId);
+ log.debug("getInputsForComponentInput failed with exception", e);
+ response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ return response;
+
+ }
+ }
+
+ @GET
+ @Path("/{componentType}/{componentId}/inputs/{inputId}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Get inputs", httpMethod = "GET", notes = "Returns inputs list", response = Resource.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") })
+ public Response getInputsAndPropertiesForComponentInput(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @PathParam("inputId") final String inputId, @Context final HttpServletRequest request,
+ @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+
+ ServletContext context = request.getSession().getServletContext();
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("(get) Start handle request of {}", url);
+ Response response = null;
+
+ try {
+ InputsBusinessLogic businessLogic = getInputBL(context);
+
+ Either<InputDefinition, ResponseFormat> inputsRes = businessLogic.getInputsAndPropertiesForComponentInput(userId, componentId, inputId, false);
+
if (inputsRes.isRight()) {
log.debug("failed to get inputs of input: {}, with instance id: {}", inputId, componentId);
return buildErrorResponse(inputsRes.right().value());
@@ -270,6 +369,8 @@ public class InputsServlet extends BeGenericServlet {
}
}
+
+
@DELETE
@Path("/{componentType}/{componentId}/delete/{inputId}/input")
@Consumes(MediaType.APPLICATION_JSON)
@@ -291,14 +392,13 @@ public class InputsServlet extends BeGenericServlet {
try {
InputsBusinessLogic businessLogic = getInputBL(context);
- Either<InputDefinition, ResponseFormat> deleteInput = businessLogic.deleteInput(componentType, componentId, userId, inputId, true);
+ Either<InputDefinition, ResponseFormat> deleteInput = businessLogic.deleteInput(componentType, componentId, userId, inputId);
if (deleteInput.isRight()){
ResponseFormat deleteResponseFormat = deleteInput.right().value();
response = buildErrorResponse(deleteResponseFormat);
return response;
}
- InputDefinition inputDefinition = deleteInput.left().value();
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), inputDefinition);
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), deleteInput.left().value());
} catch (Exception e){
BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Delete input for service {} with id: {}", componentId, inputId);
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete input for service + " + componentId + " + with id: " + inputId);
@@ -308,7 +408,46 @@ public class InputsServlet extends BeGenericServlet {
}
}
+
+
+
+ /*@PUT
+ @Path("/{componentType}/{componentId}/edit/{inputId}/input")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Delete input from service", httpMethod = "DELETE", notes = "Delete service input", response = Resource.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Input deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Input not found") })
+ public Response editInputValue (
+ @PathParam("componentType") final String componentType,
+ @PathParam("componentId") final String componentId,
+ @PathParam("inputId") final String inputId,
+ @Context final HttpServletRequest request,
+ @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+
+ ServletContext context = request.getSession().getServletContext();
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("(get) Start handle request of {}", url);
+ Response response = null;
+ try {
+ InputsBusinessLogic businessLogic = getInputBL(context);
+ Either<InputDefinition, ResponseFormat> deleteInput = businessLogic.deleteInput(componentType, componentId, userId, inputId);
+ if (deleteInput.isRight()){
+ ResponseFormat deleteResponseFormat = deleteInput.right().value();
+ response = buildErrorResponse(deleteResponseFormat);
+ return response;
+ }
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), deleteInput.left().value());
+ } catch (Exception e){
+ BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Delete input for service {} with id: {}", componentId, inputId);
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete input for service + " + componentId + " + with id: " + inputId);
+ log.debug("Delete input failed with exception", e);
+ response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ return response;
+
+ }
+ }*/
+
protected InputsBusinessLogic getInputBL(ServletContext context) {
WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/LifecycleServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/LifecycleServlet.java
index 3f8bfd9149..019a6ba8fd 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/LifecycleServlet.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/LifecycleServlet.java
@@ -40,7 +40,6 @@ import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.impl.WebAppContextWrapper;
import org.openecomp.sdc.be.model.Component;
import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
import org.openecomp.sdc.be.model.User;
@@ -50,7 +49,6 @@ import org.openecomp.sdc.common.config.EcompErrorName;
import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.springframework.web.context.WebApplicationContext;
import com.jcabi.aspects.Loggable;
import com.wordnik.swagger.annotations.Api;
@@ -92,9 +90,9 @@ public class LifecycleServlet extends BeGenericServlet {
// get modifier from graph
log.debug("get modifier properties");
- Either<User, Response> eitherGetUser = getUser(request, userId);
+ Either<User, ResponseFormat> eitherGetUser = getUser(request, userId);
if (eitherGetUser.isRight()) {
- return eitherGetUser.right().value();
+ return buildErrorResponse(eitherGetUser.right().value());
}
User user = eitherGetUser.left().value();
@@ -130,27 +128,6 @@ public class LifecycleServlet extends BeGenericServlet {
try {
LifeCycleTransitionEnum transitionEnum = validateEnum.left().value();
ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(componentCollection);
- // if (componentType == ComponentTypeEnum.RESOURCE){
- // Either<Resource, ResponseFormat> actionResponse =
- // businessLogic.changeState(resourceIdLower, user, transitionEnum,
- // changeInfo, false);
- //
- // if (actionResponse.isRight()){
- // log.info("failed to change resource state");
- // response = buildErrorResponse(actionResponse.right().value());
- // return response;
- // }
- //
- // log.debug("change state successful !!!");
- // Object resource =
- // RepresentationUtils.toRepresentation(actionResponse.left().value());
- // response =
- // buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),
- // resource);
- // return response;
- //
- // } else if (componentType == ComponentTypeEnum.SERVICE ||
- // componentType == ComponentTypeEnum.PRODUCT){
if (componentType != null) {
Either<? extends Component, ResponseFormat> actionResponse = businessLogic.changeComponentState(componentType, componentId, user, transitionEnum, changeInfo, false, true);
@@ -192,25 +169,25 @@ public class LifecycleServlet extends BeGenericServlet {
return Either.left(transitionEnum);
}
- private LifecycleBusinessLogic getLifecycleBL(ServletContext context) {
- WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
- WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
- LifecycleBusinessLogic resourceBl = webApplicationContext.getBean(LifecycleBusinessLogic.class);
- return resourceBl;
- }
-
- protected Either<User, Response> getUser(final HttpServletRequest request, String userId) {
-
- Either<User, ActionStatus> eitherCreator = getUserAdminManager(request.getSession().getServletContext()).getUser(userId, false);
- if (eitherCreator.isRight()) {
- log.info("createResource method - user is not listed. userId={}", userId);
- ResponseFormat errorResponse = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_INFORMATION);
- User user = new User("", "", userId, "", null, null);
-
- getComponentsUtils().auditResource(errorResponse, user, null, "", "", AuditingActionEnum.CHECKOUT_RESOURCE, null);
- return Either.right(buildErrorResponse(errorResponse));
- }
- return Either.left(eitherCreator.left().value());
-
- }
+// private LifecycleBusinessLogic getLifecycleBL(ServletContext context) {
+// WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
+// WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
+// LifecycleBusinessLogic resourceBl = webApplicationContext.getBean(LifecycleBusinessLogic.class);
+// return resourceBl;
+// }
+//
+// protected Either<User, Response> getUser(final HttpServletRequest request, String userId) {
+//
+// Either<User, ActionStatus> eitherCreator = getUserAdminManager(request.getSession().getServletContext()).getUser(userId, false);
+// if (eitherCreator.isRight()) {
+// log.info("createResource method - user is not listed. userId= {}", userId);
+// ResponseFormat errorResponse = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_INFORMATION);
+// User user = new User("", "", userId, "", null, null);
+//
+// getComponentsUtils().auditResource(errorResponse, user, null, "", "", AuditingActionEnum.CHECKOUT_RESOURCE, null);
+// return Either.right(buildErrorResponse(errorResponse));
+// }
+// return Either.left(eitherCreator.left().value());
+//
+// }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/PropertyServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/PropertyServlet.java
index 2c693c71a8..df84e07b2c 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/PropertyServlet.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/PropertyServlet.java
@@ -53,9 +53,9 @@ import org.openecomp.sdc.be.impl.WebAppContextWrapper;
import org.openecomp.sdc.be.model.PropertyConstraint;
import org.openecomp.sdc.be.model.PropertyDefinition;
import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
import org.openecomp.sdc.be.model.operations.impl.PropertyOperation.PropertyConstraintDeserialiser;
import org.openecomp.sdc.be.model.operations.impl.PropertyOperation.PropertyConstraintSerialiser;
+import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
import org.openecomp.sdc.be.resources.data.EntryData;
import org.openecomp.sdc.common.api.Constants;
import org.openecomp.sdc.common.config.EcompErrorName;
@@ -97,13 +97,11 @@ public class PropertyServlet extends BeGenericServlet {
ServletContext context = request.getSession().getServletContext();
String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
- log.debug("modifier id is {}", userId);
- log.debug("data is {}", data);
+ log.debug("Start handle request of {} modifier id is {} data is {}", url, userId, data);
try {
// convert json to PropertyDefinition
- Either<Map<String, PropertyDefinition>, ActionStatus> either = getPropertyModel(data);
+ Either<Map<String, PropertyDefinition>, ActionStatus> either = getPropertyModel(resourceId, data);
if (either.isRight()) {
ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(either.right().value());
return buildErrorResponse(responseFormat);
@@ -156,8 +154,7 @@ public class PropertyServlet extends BeGenericServlet {
ServletContext context = request.getSession().getServletContext();
String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
- log.debug("modifier id is {}", userId);
+ log.debug("Start handle request of {}, modifier id is {}", url, userId);
try {
@@ -195,19 +192,18 @@ public class PropertyServlet extends BeGenericServlet {
ServletContext context = request.getSession().getServletContext();
String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
- log.debug("modifier id is {}", userId);
+ log.debug("Start handle request of {} modifier id is {}", url, userId);
try {
// delete the property
PropertyBusinessLogic businessLogic = getPropertyBL(context);
- Either<EntryData<String, PropertyDefinition>, ResponseFormat> status = businessLogic.deleteProperty(resourceId, propertyId, userId);
+ Either<Entry<String, PropertyDefinition>, ResponseFormat> status = businessLogic.deleteProperty(resourceId, propertyId, userId);
if (status.isRight()) {
log.debug("Failed to delete Property. Reason - ", status.right().value());
return buildErrorResponse(status.right().value());
}
- EntryData<String, PropertyDefinition> property = status.left().value();
+ Entry<String, PropertyDefinition> property = status.left().value();
String name = property.getKey();
PropertyDefinition propertyDefinition = property.getValue();
@@ -216,7 +212,6 @@ public class PropertyServlet extends BeGenericServlet {
return buildOkResponse(responseFormat, propertyToJson(property));
} catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Delete Property");
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Property");
log.debug("delete property failed with exception", e);
ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
@@ -247,7 +242,7 @@ public class PropertyServlet extends BeGenericServlet {
try {
// convert json to PropertyDefinition
- Either<Map<String, PropertyDefinition>, ActionStatus> either = getPropertyModel(data);
+ Either<Map<String, PropertyDefinition>, ActionStatus> either = getPropertyModel(resourceId, data);
if (either.isRight()) {
ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(either.right().value());
return buildErrorResponse(responseFormat);
@@ -285,54 +280,7 @@ public class PropertyServlet extends BeGenericServlet {
}
}
- // private String propertyToJsonUi(Map.Entry<String, PropertyDefinition>
- // property) {
- // String name = property.getKey();
- // PropertyDefinition propertyDefinition = property.getValue();
- // JSONObject root = new JSONObject();
- // root.put("type", propertyDefinition.getType());
- // root.put("source", propertyDefinition.getDefaultValue());
- // root.put("name", name);
- // root.put("description", propertyDefinition.getDescription());
- // root.put("uniqueId", propertyDefinition.getUniqueId());
- // return root.toString();
- //
- // }
- //
-
- // private Either<String ,ActionStatus> getJsonModel(String data){
- // Either<UiProperty,ActionStatus> uiPropertyEither = getUiProperty(data);
- // if (uiPropertyEither.isRight()){
- // log.error("Property conetnt is invalid - {}",data);
- // return Either.right(ActionStatus.INVALID_CONTENT);
- // }
- // UiProperty uiProperty = uiPropertyEither.left().value();
- // String json = convertUiPropertyToJsonModel(uiProperty);
- // return Either.left(json);
- // }
- //
-
- // private String convertUiPropertyToJsonModel(UiProperty uiProperty) {
- // JSONObject root = new JSONObject();
- // JSONObject propertyD = new JSONObject();
- // propertyD.put("type",uiProperty.getType());
- // propertyD.put("required",false);
- // propertyD.put("description",uiProperty.getDescription());
- // propertyD.put("isPassword",false);
- // propertyD.put("defaultValue",uiProperty.getSource());
- // JSONArray jsonArr = new JSONArray();
- // JSONArray jsonR = new JSONArray();
- // jsonR.add(100);
- // jsonR.add(500);
- // JSONObject o = new JSONObject();
- // o.put("inRange", jsonR);
- // jsonArr.add(o);
- // propertyD.put("constraints",jsonArr);
- // root.put(uiProperty.getName(), propertyD);
- // return root.toString();
- // }
-
- private Either<Map<String, PropertyDefinition>, ActionStatus> getPropertyModel(String data) {
+ private Either<Map<String, PropertyDefinition>, ActionStatus> getPropertyModel(String resourceId, String data) {
JSONParser parser = new JSONParser();
JSONObject root;
try {
@@ -353,7 +301,7 @@ public class PropertyServlet extends BeGenericServlet {
PropertyDefinition propertyDefinition = convertJsonToObject.left().value();
// PropertyDefinition propertyDefinition =
// gson.fromJson(jsonString , PropertyDefinition.class);
- String uniqueId = UniqueIdBuilder.buildPropertyUniqueId("resourceId", (String) propertyName);
+ String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId, (String) propertyName);
propertyDefinition.setUniqueId(uniqueId);
properties.put(propertyName, propertyDefinition);
}
@@ -384,54 +332,7 @@ public class PropertyServlet extends BeGenericServlet {
}
}
- // private Either<Map<String,PropertyDefinition>,ActionStatus>
- // getProperty(String data){
- // Type constraintType = new TypeToken<PropertyConstraint>() {}.getType();
- // PropertyConstraintDeserialiser propertyConstraintDeserialiser = new
- // PropertyConstraintDeserialiser();
- // Gson gson = new
- // GsonBuilder().registerTypeAdapter(constraintType,propertyConstraintDeserialiser).create();
- // JSONParser parser = new JSONParser();
- // JSONObject root;
- // try {
- // Map<String,PropertyDefinition> properties = new
- // HashMap<String,PropertyDefinition>();
- // root = (JSONObject) parser.parse(data);
- // Set keySet = root.keySet();
- // for (Object propertyName : keySet){
- // JSONObject val = (JSONObject) root.get(propertyName);
- // String jsonString = val.toJSONString();
- // PropertyDefinition propertyDefinition = gson.fromJson(jsonString ,
- // PropertyDefinition.class);
- // String uniqueId = UniqueIdBuilder.buildPropertyUniqueId("resourceId",
- // (String)propertyName);
- // propertyDefinition.setUniqueId(uniqueId);
- // properties.put((String)propertyName,propertyDefinition);
- // }
- // return Either.left(properties);
- // } catch (ParseException e) {
- // log.error("Property conetnt is invalid - {}",data);
- // return Either.right(ActionStatus.INVALID_CONTENT);
- // }
- // }
- //
- // private Either<UiProperty, ActionStatus> getUiProperty(String data) {
- // try{
- // Gson gson = new Gson();
- // UiProperty uiProperty = gson.fromJson(data, UiProperty.class);
- // return Either.left(uiProperty);
- // }catch(JsonSyntaxException e){
- // log.warn("Problem create UiProperty from {}",data);
- // log.debug("Problem create UiProperty from {}",data,e);
- // return Either.right(ActionStatus.INVALID_CONTENT);
- // }
- // }
-
private String propertyToJson(Map.Entry<String, PropertyDefinition> property) {
- // Type constraintType = new TypeToken<PropertyConstraint>()
- // {}.getType();
- // Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new
- // PropertyConstraintDeserialiser()).create();
JSONObject root = new JSONObject();
String propertyName = property.getKey();
PropertyDefinition propertyDefinition = property.getValue();
@@ -461,30 +362,13 @@ public class PropertyServlet extends BeGenericServlet {
}
- // private JSONObject getPropertyDefinitionJSONObject(PropertyDefinition
- // propertyDefinition) {
- // JSONObject root = new JSONObject();
- // root.put("type", propertyDefinition.getType());
- // root.put("required", propertyDefinition.isRequired());
- // root.put("defaultValue", propertyDefinition.getDefaultValue());
- // root.put("description", propertyDefinition.getDescription());
- // root.put("isPassword", propertyDefinition.isPassword());
- // List<PropertyConstraint> constraints =
- // propertyDefinition.getConstraints();
- // for (PropertyConstraint p : constraints){
- // p.toString();
- // }
- // root.put("constraints", propertyDefinition.getConstraints());
- // return root;
- // }
-
private <T> Either<T, ActionStatus> convertJsonToObject(String data, Class<T> clazz) {
T t = null;
Type constraintType = new TypeToken<PropertyConstraint>() {
}.getType();
Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyConstraintDeserialiser()).create();
try {
- log.trace("convert json to object. json=\n{}", data);
+ log.trace("convert json to object. json=\n {}", data);
t = gson.fromJson(data, clazz);
if (t == null) {
log.info("object is null after converting from json");
@@ -504,7 +388,7 @@ public class PropertyServlet extends BeGenericServlet {
}.getType();
Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyConstraintSerialiser()).create();
try {
- log.trace("convert object to json. propertyDefinition={}", propertyDefinition.toString());
+ log.trace("convert object to json. propertyDefinition= {}", propertyDefinition.toString());
String json = gson.toJson(propertyDefinition);
if (json == null) {
log.info("object is null after converting to json");
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/RepresentationUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/RepresentationUtils.java
index 565911eaa9..5eed7eeb0d 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/RepresentationUtils.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/RepresentationUtils.java
@@ -85,6 +85,7 @@ public class RepresentationUtils {
JsonObject jsonElement = new JsonObject();
ArtifactDefinition resourceInfo = null;
+
try {
Gson gson = new Gson();
jsonElement = gson.fromJson(content, jsonElement.getClass());
@@ -109,13 +110,19 @@ public class RepresentationUtils {
payload = artifactPayload.getAsString();
}
jsonElement.remove(Constants.ARTIFACT_PAYLOAD_DATA);
- resourceInfo = gson.fromJson(jsonElement, clazz);
+ String json = gson.toJson(jsonElement);
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ mapper.configure(Feature.FAIL_ON_EMPTY_BEANS, false);
+ mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
+
+ resourceInfo = mapper.readValue(json, clazz);
resourceInfo.setPayloadData(payload);
} catch (Exception e) {
BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeArtifactInformationInvalidError, "Artifact Upload / Update");
BeEcompErrorManager.getInstance().logBeArtifactInformationInvalidError("Artifact Upload / Update");
- log.debug("Failed to convert the content {} to object. {}", content.substring(0, Math.min(50, content.length())), e);
+ log.debug("Failed to convert the content {} to object.", content.substring(0, Math.min(50, content.length())), e);
}
return resourceInfo;
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourceArtifactDownloadServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourceArtifactDownloadServlet.java
index 673187b0a1..54ec6e3b15 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourceArtifactDownloadServlet.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourceArtifactDownloadServlet.java
@@ -56,41 +56,6 @@ public class ResourceArtifactDownloadServlet extends ToscaDaoServlet {
private Gson gson = new GsonBuilder().setPrettyPrinting().create();
- // @GET
- // @Path("/{resourceName}/{resourceVersion}/artifacts")
- // @Produces(MediaType.APPLICATION_JSON)
- // public Response getResourceArtifactList(@PathParam("resourceName") final
- // String resourceName,
- // @PathParam("resourceVersion") final String resourceVersion,
- // @Context final HttpServletRequest request){
- //
- //
- // String url = request.getMethod() + " " + request.getRequestURI();
- // log.info("Start handle request of {}", url);
- //
- // Response response = null;
- //
- // // get artifact list from dao
- // IResourceUploader resourceDao =
- // getResourceUploader(request.getSession().getServletContext());
- // if (resourceDao == null){
- // log.error("resource dao cannot be found");
- // response = buildResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR,
- // "Resource dao cannot be found");
- // return response;
- // }
- // Either<List<ESArtifactData>, ResourceUploadStatus> getArtifactsStatus =
- // resourceDao.getArtifacts(resourceName, resourceVersion);
- //
- // response =
- // getLogic(request.getSession().getServletContext()).createArtifactListResponse(resourceName,
- // getArtifactsStatus, getServletPath(request));
- //
- // log.info("Finish handle request of {} | result = {}", url, response.getStatus() );
- // return response;
- //
- // }
-
@GET
@Path("/{resourceName}/{resourceVersion}/artifacts/{artifactName}")
// @Produces(MediaType.APPLICATION_OCTET_STREAM)
@@ -118,7 +83,7 @@ public class ResourceArtifactDownloadServlet extends ToscaDaoServlet {
}
response = logic.downloadArtifact(resourceName, resourceVersion, artifactName, getArtifactStatus, artifactId);
- log.info("Finish handle request of {} | result = {}", url, response.getStatus());
+ log.info("Finish handle request of {} | result = {}", url, response.getStatus());
return response;
} catch (Exception e) {
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourceUploadServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourceUploadServlet.java
index 5cd765abe0..ef6ddb04ba 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourceUploadServlet.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourceUploadServlet.java
@@ -71,11 +71,12 @@ public class ResourceUploadServlet extends AbstractValidationsServlet {
private static Logger log = LoggerFactory.getLogger(ResourceUploadServlet.class.getName());
public static final String NORMATIVE_TYPE_RESOURCE = "multipart";
+ public static final String CSAR_TYPE_RESOURCE = "csar";
public static final String USER_TYPE_RESOURCE = "user-resource";
public static final String USER_TYPE_RESOURCE_UI_IMPORT = "user-resource-ui-import";
public enum ResourceAuthorityTypeEnum {
- NORMATIVE_TYPE_BE(NORMATIVE_TYPE_RESOURCE, true, false), USER_TYPE_BE(USER_TYPE_RESOURCE, true, true), USER_TYPE_UI(USER_TYPE_RESOURCE_UI_IMPORT, false, true);
+ NORMATIVE_TYPE_BE(NORMATIVE_TYPE_RESOURCE, true, false), USER_TYPE_BE(USER_TYPE_RESOURCE, true, true), USER_TYPE_UI(USER_TYPE_RESOURCE_UI_IMPORT, false, true), CSAR_TYPE_BE(CSAR_TYPE_RESOURCE, true, true);
private String urlPath;
private boolean isBackEndImport, isUserTypeResource;
@@ -150,9 +151,11 @@ public class ResourceUploadServlet extends AbstractValidationsServlet {
fillPayload(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), resourceInfoJsonString, resourceAuthorityEnum, file);
// PayLoad Validations
- commonPayloadValidations(responseWrapper, yamlStringWrapper, userWrapper.getInnerElement(), uploadResourceInfoWrapper.getInnerElement());
+ if(!resourceAuthorityEnum.equals(ResourceAuthorityTypeEnum.CSAR_TYPE_BE)){
+ commonPayloadValidations(responseWrapper, yamlStringWrapper, userWrapper.getInnerElement(), uploadResourceInfoWrapper.getInnerElement());
- specificResourceAuthorityValidations(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), request, resourceInfoJsonString, resourceAuthorityEnum);
+ specificResourceAuthorityValidations(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), request, resourceInfoJsonString, resourceAuthorityEnum);
+ }
if (responseWrapper.isEmpty()) {
handleImport(responseWrapper, userWrapper.getInnerElement(), uploadResourceInfoWrapper.getInnerElement(), yamlStringWrapper.getInnerElement(), resourceAuthorityEnum, createNewVersion, null);
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourcesServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourcesServlet.java
index e3d39610a8..74d81ebd24 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourcesServlet.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourcesServlet.java
@@ -51,12 +51,10 @@ import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.datamodel.api.HighestFilterEnum;
-import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
import org.openecomp.sdc.be.model.PropertyDefinition;
import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.ResourceMetadataDefinition;
import org.openecomp.sdc.be.model.UploadResourceInfo;
import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
@@ -100,7 +98,7 @@ public class ResourcesServlet extends AbstractValidationsServlet {
ServletContext context = request.getSession().getServletContext();
String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
+ log.debug("Start handle request of {}" , url);
// get modifier id
User modifier = new User();
@@ -128,7 +126,7 @@ public class ResourcesServlet extends AbstractValidationsServlet {
}
Resource resource = convertResponse.left().value();
- Either<Resource, ResponseFormat> actionResponse = businessLogic.createResource(resource, modifier, null, null);
+ Either<Resource, ResponseFormat> actionResponse = businessLogic.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, modifier, null, null);
if (actionResponse.isRight()) {
log.debug("failed to create resource");
@@ -160,7 +158,7 @@ public class ResourcesServlet extends AbstractValidationsServlet {
String payloadName = json.getString(ImportUtils.Constants.UI_JSON_PAYLOAD_NAME);
isUIImport = payloadName != null && !payloadName.isEmpty();
} catch (Exception e) {
- log.debug("failed to parse json sent from client, json:{}", data);
+ log.debug("failed to parse json sent from client, json:{}", data, e);
isUIImport = false;
}
return isUIImport;
@@ -177,8 +175,6 @@ public class ResourcesServlet extends AbstractValidationsServlet {
commonGeneralValidations(responseWrapper, userWrapper, uploadResourceInfoWrapper, resourceAuthorityEnum, userId, resourceInfoJsonString);
- // TODO suspect next line is unnecessary
- userWrapper.getInnerElement();
if (!CsarValidationUtils.isCsarPayloadName(uploadResourceInfoWrapper.getInnerElement().getPayloadName())) {
fillPayload(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), resourceInfoJsonString, resourceAuthorityEnum, null);
@@ -212,13 +208,13 @@ public class ResourcesServlet extends AbstractValidationsServlet {
ServletContext context = request.getSession().getServletContext();
String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
+ log.debug("Start handle request of {}" , url);
// get modifier id
String userId = request.getHeader(Constants.USER_ID_HEADER);
User modifier = new User();
modifier.setUserId(userId);
- log.debug("modifier id is {}", userId);
+ log.debug("modifier id is {}" , userId);
Response response = null;
@@ -252,13 +248,13 @@ public class ResourcesServlet extends AbstractValidationsServlet {
ServletContext context = request.getSession().getServletContext();
String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
+ log.debug("Start handle request of {}" , url);
// get modifier id
String userId = request.getHeader(Constants.USER_ID_HEADER);
User modifier = new User();
modifier.setUserId(userId);
- log.debug("modifier id is {}", userId);
+ log.debug("modifier id is {}" , userId);
Response response = null;
@@ -295,12 +291,12 @@ public class ResourcesServlet extends AbstractValidationsServlet {
ServletContext context = request.getSession().getServletContext();
String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
+ log.debug("Start handle request of {}" , url);
// get modifier id
User modifier = new User();
modifier.setUserId(userId);
- log.debug("modifier id is {}", userId);
+ log.debug("modifier id is {}" , userId);
Response response = null;
@@ -340,11 +336,11 @@ public class ResourcesServlet extends AbstractValidationsServlet {
// get modifier id
User modifier = new User();
modifier.setUserId(userId);
- log.debug("modifier id is {}", userId);
+ log.debug("modifier id is {}" , userId);
Response response = null;
try {
ResourceBusinessLogic businessLogic = getResourceBL(context);
- Either<List<Resource>, ResponseFormat> actionResponse = businessLogic.getResourceByNameAndVersion(resourceName, resourceVersion, userId);
+ Either<Resource, ResponseFormat> actionResponse = businessLogic.getResourceByNameAndVersion(resourceName, resourceVersion, userId);
if (actionResponse.isRight()) {
response = buildErrorResponse(actionResponse.right().value());
return response;
@@ -370,17 +366,17 @@ public class ResourcesServlet extends AbstractValidationsServlet {
public Response validateResourceName(@PathParam("resourceName") final String resourceName, @QueryParam("subtype") String resourceType, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
ServletContext context = request.getSession().getServletContext();
String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
+ log.debug("Start handle request of {}" , url);
// get modifier id
User modifier = new User();
modifier.setUserId(userId);
- log.debug("modifier id is {}", userId);
+ log.debug("modifier id is {}" , userId);
Response response = null;
try {
ResourceBusinessLogic businessLogic = getResourceBL(context);
- if (resourceType != null && !ResourceTypeEnum.contains(resourceType)) {
+ if (resourceType != null && !ResourceTypeEnum.containsName(resourceType)) {
log.debug("invalid resource type received");
response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
return response;
@@ -416,7 +412,7 @@ public class ResourcesServlet extends AbstractValidationsServlet {
ServletContext context = request.getSession().getServletContext();
String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("(get) Start handle request of {}", url);
+ log.debug("(get) Start handle request of {}" , url);
Response response = null;
try {
@@ -452,7 +448,7 @@ public class ResourcesServlet extends AbstractValidationsServlet {
ServletContext context = request.getSession().getServletContext();
String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("(get) Start handle request of {}", url);
+ log.debug("(get) Start handle request of {}" , url);
Response response = null;
try {
@@ -492,7 +488,7 @@ public class ResourcesServlet extends AbstractValidationsServlet {
ServletContext context = request.getSession().getServletContext();
String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
+ log.debug("Start handle request of {}" , url);
// get modifier id
User modifier = new User();
@@ -510,8 +506,7 @@ public class ResourcesServlet extends AbstractValidationsServlet {
response = buildErrorResponse(updateInfoResource.right().value());
return response;
}
- Either<Resource, ResponseFormat> actionResponse = businessLogic.updateResourceMetadata(resourceIdLower,
- updateInfoResource.left().value(), null, modifier, false);
+ Either<Resource, ResponseFormat> actionResponse = businessLogic.updateResourceMetadata(resourceIdLower, updateInfoResource.left().value(), null, modifier, false);
if (actionResponse.isRight()) {
log.debug("failed to update resource metadata");
@@ -548,7 +543,7 @@ public class ResourcesServlet extends AbstractValidationsServlet {
ServletContext context = request.getSession().getServletContext();
String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
+ log.debug("Start handle request of {}" , url);
// get modifier id
User modifier = new User();
@@ -607,7 +602,7 @@ public class ResourcesServlet extends AbstractValidationsServlet {
*
* @Produces(MediaType.APPLICATION_JSON) public Response getLatestVersionNotAbstractResources(@Context final HttpServletRequest request) { //TODO: any vlidations??? ServletContext context = request.getSession().getServletContext();
*
- * String url = request.getMethod() + " " + request.getRequestURI(); log.debug("(get) Start handle request of {}", url); Response response=null;
+ * String url = request.getMethod() + " " + request.getRequestURI(); log.debug("(get) Start handle request of " + url); Response response=null;
*
* try {
*
@@ -653,7 +648,7 @@ public class ResourcesServlet extends AbstractValidationsServlet {
ServletContext context = request.getSession().getServletContext();
String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
+ log.debug("Start handle request of {}" , url);
// retrieve user details
userId = (userId != null) ? userId : request.getHeader(Constants.USER_ID_HEADER);
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ServiceServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ServiceServlet.java
index 7e7068f5d7..05a6f5146c 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ServiceServlet.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ServiceServlet.java
@@ -24,7 +24,9 @@ import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
+import java.lang.reflect.Type;
import java.text.MessageFormat;
+import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -46,6 +48,7 @@ import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apache.http.HttpStatus;
+import org.codehaus.jackson.map.ObjectMapper;
import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;
import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
@@ -54,17 +57,18 @@ import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.model.DistributionStatusEnum;
+import org.openecomp.sdc.be.model.GroupInstanceProperty;
import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.Service;
import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.config.EcompErrorName;
import org.openecomp.sdc.common.datastructure.Wrapper;
import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import com.google.gson.reflect.TypeToken;
import com.jcabi.aspects.Loggable;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
@@ -123,7 +127,6 @@ public class ServiceServlet extends AbstractValidationsServlet {
return response;
} catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Create Service");
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Service");
log.debug("create service failed with exception", e);
response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -163,7 +166,6 @@ public class ServiceServlet extends AbstractValidationsServlet {
}
return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
} catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Validate Service Name");
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Validate Service Name");
log.debug("validate service name failed with exception", e);
return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -187,9 +189,9 @@ public class ServiceServlet extends AbstractValidationsServlet {
modifier.setUserId(userId);
log.debug("modifier id is {}", userId);
Wrapper<Response> responseWrapper = new Wrapper<Response>();
- Wrapper<String> uuidWrapper = new Wrapper<String>();
- Wrapper<String> versionWrapper = new Wrapper<String>();
- Wrapper<User> userWrapper = new Wrapper<User>();
+ Wrapper<String> uuidWrapper = new Wrapper<>();
+ Wrapper<String> versionWrapper = new Wrapper<>();
+ Wrapper<User> userWrapper = new Wrapper<>();
Wrapper<ComponentTypeEnum> componentWrapper = new Wrapper<ComponentTypeEnum>();
try {
validateUserExist(responseWrapper, userWrapper, userId);
@@ -217,7 +219,6 @@ public class ServiceServlet extends AbstractValidationsServlet {
}
} catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Validate Service Name");
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Validate Service Name");
log.debug("get Service Audit Records failed with exception", e);
Response errorResponse = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -278,7 +279,6 @@ public class ServiceServlet extends AbstractValidationsServlet {
return response;
} catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Delete Service");
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Service");
log.debug("delete service failed with exception", e);
response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -315,7 +315,6 @@ public class ServiceServlet extends AbstractValidationsServlet {
return response;
} catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Delete Service");
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Service");
log.debug("delete service failed with exception", e);
response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -367,7 +366,6 @@ public class ServiceServlet extends AbstractValidationsServlet {
return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
} catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Update Service Metadata");
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Service Metadata");
log.debug("update service metadata failed with exception", e);
response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -375,6 +373,67 @@ public class ServiceServlet extends AbstractValidationsServlet {
}
}
+ /**
+ * updates group instance property values
+ * Note, than in case of group instance updated successfully, related resourceInstance and containing component modification time will be updated
+ * @param serviceId
+ * @param componentInstanceId
+ * @param groupInstanceId
+ * @param data
+ * @param request
+ * @param userId
+ * @return
+ */
+ @PUT
+ @Path("/{containerComponentType}/{serviceId}/resourceInstance/{componentInstanceId}/groupInstance/{groupInstanceId}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Update Group Instance Property Values", httpMethod = "PUT", notes = "Returns updated group instance", response = Service.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Group Instance Property Values Updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
+ public Response updateGroupInstancePropertyValues(@PathParam("serviceId") final String serviceId,@PathParam("componentInstanceId") final String componentInstanceId, @PathParam("groupInstanceId") final String groupInstanceId, @ApiParam(value = "Group instance object to be Updated", required = true) String data, @Context final HttpServletRequest request,
+ @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+
+ Response response = null;
+ ServletContext context = request.getSession().getServletContext();
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+
+ User modifier = new User();
+ modifier.setUserId(userId);
+ log.debug("modifier id is {}",userId);
+
+ ServiceBusinessLogic businessLogic;
+ Either<List<GroupInstanceProperty>, ResponseFormat> actionResponse = null;
+ try {
+ List<GroupInstanceProperty> updatedProperties;
+ Type listType = new TypeToken<ArrayList<GroupInstanceProperty>>(){}.getType();
+ ArrayList<GroupInstanceProperty> newProperties = gson.fromJson(data, listType);
+ if (newProperties == null) {
+ actionResponse = Either.right(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
+ }
+ if(actionResponse == null){
+ log.debug("Start handle update group instance property values request. Received group instance is {}", groupInstanceId);
+ businessLogic = getServiceBL(context);
+ actionResponse = businessLogic.updateGroupInstancePropertyValues(modifier, serviceId, componentInstanceId, groupInstanceId, newProperties);
+ if(actionResponse.isRight()){
+ actionResponse = Either.right(actionResponse.right().value());
+ }
+ }
+ if(actionResponse.isLeft()){
+ updatedProperties = actionResponse.left().value();
+ ObjectMapper mapper = new ObjectMapper();
+ String result = mapper.writeValueAsString(updatedProperties);
+ response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
+ }
+ else{
+ response = buildErrorResponse(actionResponse.right().value());
+ }
+ } catch (Exception e) {
+ log.error("Exception occured during update Group Instance property values: {}", e.getMessage(), e);
+ response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ return response;
+ }
@GET
@Path("/services/{serviceId}")
@@ -412,7 +471,6 @@ public class ServiceServlet extends AbstractValidationsServlet {
return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
} catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Service");
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Service");
log.debug("get service failed with exception", e);
return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -451,7 +509,6 @@ public class ServiceServlet extends AbstractValidationsServlet {
return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
} catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Service by name and version");
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Service by name and version");
log.debug("get service failed with exception", e);
return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -492,7 +549,6 @@ public class ServiceServlet extends AbstractValidationsServlet {
return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
} catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Update Service Distribution State");
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Service Distribution State");
log.debug("updateServiceDistributionState failed with exception", e);
response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -531,7 +587,6 @@ public class ServiceServlet extends AbstractValidationsServlet {
Object result = RepresentationUtils.toRepresentation(service);
return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
} catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Activate Distribution");
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Activate Distribution");
log.debug("activate distribution failed with exception", e);
response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -570,7 +625,6 @@ public class ServiceServlet extends AbstractValidationsServlet {
Object result = RepresentationUtils.toRepresentation(service);
return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
} catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Mark Distribution As Deployed");
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Mark Distribution As Deployed");
log.debug("mark distribution as deployed failed with exception", e);
response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -604,7 +658,6 @@ public class ServiceServlet extends AbstractValidationsServlet {
}
return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), null);
} catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "tempUrlToBeDeleted");
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("tempUrlToBeDeleted");
log.debug("failed with exception", e);
response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -621,12 +674,9 @@ public class ServiceServlet extends AbstractValidationsServlet {
@ApiResponse(code = 404, message = "Artifact not found") })
public Response downloadServiceArtifact(@PathParam("artifactName") final String artifactName, @Context final HttpServletRequest request) {
Response response = null;
- String instanceIdHeader = request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER);
- String requestURI = request.getRequestURI();
try {
log.debug("artifact name = {}", artifactName);
- ServletContext context = request.getSession().getServletContext();
Either<byte[], ResponseFormat> executeCommand = executeCommand(artifactName);
@@ -640,7 +690,7 @@ public class ServiceServlet extends AbstractValidationsServlet {
InputStream is = new ByteArrayInputStream(value);
Map<String, String> headers = new HashMap<>();
- String heatFileName = null;
+ String heatFileName;
if (artifactName.indexOf(".") > -1) {
heatFileName = artifactName.substring(0, artifactName.indexOf(".")) + ".heat";
} else {
@@ -653,7 +703,6 @@ public class ServiceServlet extends AbstractValidationsServlet {
return response;
} catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "download heat artifact");
log.error("download artifact failed with exception", e);
return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
}
@@ -671,8 +720,7 @@ public class ServiceServlet extends AbstractValidationsServlet {
heatTranslator = "/home/m98835/heat-translator-0.3.0/heat_translator.py";
}
- log.debug("toscaFilesDir={}", toscaFilesDir);
- log.debug("heatTranslator={}", heatTranslator);
+ log.debug("toscaFilesDir= {} | heatTranslator= {}", toscaFilesDir, heatTranslator);
StringBuffer output = new StringBuffer();
@@ -702,19 +750,19 @@ public class ServiceServlet extends AbstractValidationsServlet {
log.debug("waitFor = {}", waitFor);
if (waitFor != 0) {
- log.error("Failed running the command {}", command);
+ log.error("Failed runnign the command {}", command);
return Either.right(getComponentsUtils().getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
}
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
- String line = "";
+ String line;
while ((line = reader.readLine()) != null) {
output.append(line + "\n");
}
} catch (Exception e) {
- log.error("Failed running the command {} {}", command, e);
+ log.error("Failed runnign the command {}", command, e);
e.printStackTrace();
return Either.right(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TypesFetchServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TypesFetchServlet.java
index 0825a25cbe..6541da7e88 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TypesFetchServlet.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TypesFetchServlet.java
@@ -83,14 +83,13 @@ public class TypesFetchServlet extends AbstractValidationsServlet {
if (responseWrapper.isEmpty()) {
String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
- log.debug("modifier id is {}", userId);
+ log.debug("Start handle request of {} | modifier id is {}", url, userId);
PropertyBusinessLogic businessLogic = getPropertyBL(context);
Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes = businessLogic.getAllDataTypes();
if (allDataTypes.isRight()) {
- log.info("Failed to get all dara types. Reason - ", allDataTypes.right().value());
+ log.info("Failed to get all dara types. Reason - {}", allDataTypes.right().value());
Response errorResponse = buildErrorResponse(allDataTypes.right().value());
responseWrapper.setInnerElement(errorResponse);
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TypesUploadServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TypesUploadServlet.java
index 6ba8c521f1..1fcc0fd404 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TypesUploadServlet.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TypesUploadServlet.java
@@ -42,6 +42,8 @@ import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.codehaus.jackson.JsonGenerationException;
+import org.codehaus.jackson.map.JsonMappingException;
import org.glassfish.jersey.media.multipart.FormDataParam;
import org.openecomp.sdc.be.components.impl.CapabilityTypeImportManager;
import org.openecomp.sdc.be.components.impl.CategoriesImportManager;
@@ -105,13 +107,11 @@ public class TypesUploadServlet extends AbstractValidationsServlet {
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Create Capability Type from yaml", httpMethod = "POST", notes = "Returns created Capability Type", response = Response.class)
@ApiResponses(value = { @ApiResponse(code = 201, message = "Capability Type created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
- @ApiResponse(code = 409, message = "Capability Type already exist") })
+ @ApiResponse(code = 409, message = "Capability Type already exist") })
public Response uploadCapabilityType(@ApiParam("FileInputStream") @FormDataParam("capabilityTypeZip") File file, @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) {
-
capabilityTypeImportManager = initElementTypeImportManager(request.getSession().getServletContext(), () -> CapabilityTypeImportManager.class);
ConsumerTwoParam<Wrapper<Response>, String> createElementsMethod = (responseWrapper, ymlPayload) -> createElementsType(responseWrapper, () -> capabilityTypeImportManager.createCapabilityTypes(ymlPayload));
return uploadElementTypeServletLogic(createElementsMethod, file, request, creator, NodeTypeEnum.CapabilityType.name());
-
}
@POST
@@ -120,9 +120,8 @@ public class TypesUploadServlet extends AbstractValidationsServlet {
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Create Interface Lyfecycle Type from yaml", httpMethod = "POST", notes = "Returns created Interface Lifecycle Type", response = Response.class)
@ApiResponses(value = { @ApiResponse(code = 201, message = "Interface Lifecycle Type created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
- @ApiResponse(code = 409, message = "Interface Lifecycle Type already exist") })
+ @ApiResponse(code = 409, message = "Interface Lifecycle Type already exist") })
public Response uploadInterfaceLifecycleType(@ApiParam("FileInputStream") @FormDataParam("interfaceLifecycleTypeZip") File file, @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) {
-
interfaceLifecycleTypeImportManager = initElementTypeImportManager(request.getSession().getServletContext(), () -> InterfaceLifecycleTypeImportManager.class);
ConsumerTwoParam<Wrapper<Response>, String> createElementsMethod = (responseWrapper, ymlPayload) -> createElementsType(responseWrapper, () -> interfaceLifecycleTypeImportManager.createLifecycleTypes(ymlPayload));
return uploadElementTypeServletLogic(createElementsMethod, file, request, creator, "Interface Types");
@@ -134,13 +133,11 @@ public class TypesUploadServlet extends AbstractValidationsServlet {
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Create Categories from yaml", httpMethod = "POST", notes = "Returns created categories", response = Response.class)
@ApiResponses(value = { @ApiResponse(code = 201, message = "Categories created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
- @ApiResponse(code = 409, message = "Category already exist") })
+ @ApiResponse(code = 409, message = "Category already exist") })
public Response uploadCategories(@ApiParam("FileInputStream") @FormDataParam("categoriesZip") File file, @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) {
-
categoriesImportManager = initElementTypeImportManager(request.getSession().getServletContext(), () -> CategoriesImportManager.class);
ConsumerTwoParam<Wrapper<Response>, String> createElementsMethod = (responseWrapper, ymlPayload) -> createElementsType(responseWrapper, () -> categoriesImportManager.createCategories(ymlPayload));
return uploadElementTypeServletLogic(createElementsMethod, file, request, creator, "categories");
-
}
@POST
@@ -149,13 +146,11 @@ public class TypesUploadServlet extends AbstractValidationsServlet {
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Create Categories from yaml", httpMethod = "POST", notes = "Returns created data types", response = Response.class)
@ApiResponses(value = { @ApiResponse(code = 201, message = "Data types created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
- @ApiResponse(code = 409, message = "Data types already exist") })
+ @ApiResponse(code = 409, message = "Data types already exist") })
public Response uploadDataTypes(@ApiParam("FileInputStream") @FormDataParam("dataTypesZip") File file, @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) {
-
dataTypeImportManager = initElementTypeImportManager(request.getSession().getServletContext(), () -> DataTypeImportManager.class);
ConsumerTwoParam<Wrapper<Response>, String> createElementsMethod = (responseWrapper, ymlPayload) -> createDataTypes(responseWrapper, ymlPayload);
return uploadElementTypeServletLogic(createElementsMethod, file, request, creator, NodeTypeEnum.DataType.getName());
-
}
@POST
@@ -164,12 +159,10 @@ public class TypesUploadServlet extends AbstractValidationsServlet {
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Create GroupTypes from yaml", httpMethod = "POST", notes = "Returns created group types", response = Response.class)
@ApiResponses(value = { @ApiResponse(code = 201, message = "group types created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
- @ApiResponse(code = 409, message = "group types already exist") })
+ @ApiResponse(code = 409, message = "group types already exist") })
public Response uploadGroupTypes(@ApiParam("FileInputStream") @FormDataParam("groupTypesZip") File file, @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) {
-
groupTypeImportManager = initElementTypeImportManager(request.getSession().getServletContext(), () -> GroupTypeImportManager.class);
ConsumerTwoParam<Wrapper<Response>, String> createElementsMethod = (responseWrapper, ymlPayload) -> createGroupTypes(responseWrapper, ymlPayload);
-
return uploadElementTypeServletLogic(createElementsMethod, file, request, creator, NodeTypeEnum.GroupType.getName());
}
@@ -179,14 +172,11 @@ public class TypesUploadServlet extends AbstractValidationsServlet {
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Create PolicyTypes from yaml", httpMethod = "POST", notes = "Returns created policy types", response = Response.class)
@ApiResponses(value = { @ApiResponse(code = 201, message = "policy types created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
- @ApiResponse(code = 409, message = "policy types already exist") })
+ @ApiResponse(code = 409, message = "policy types already exist") })
public Response uploadPolicyTypes(@ApiParam("FileInputStream") @FormDataParam("policyTypesZip") File file, @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) {
-
policyTypeImportManager = initElementTypeImportManager(request.getSession().getServletContext(), () -> PolicyTypeImportManager.class);
ConsumerTwoParam<Wrapper<Response>, String> createElementsMethod = (responseWrapper, ymlPayload) -> createPolicyTypes(responseWrapper, ymlPayload);
-
return uploadElementTypeServletLogic(createElementsMethod, file, request, creator, NodeTypeEnum.PolicyType.getName());
-
}
private Response uploadElementTypeServletLogic(ConsumerTwoParam<Wrapper<Response>, String> createElementsMethod, File file, final HttpServletRequest request, String creator, String elementTypeName) {
@@ -221,7 +211,7 @@ public class TypesUploadServlet extends AbstractValidationsServlet {
return responseWrapper.getInnerElement();
} catch (Exception e) {
- log.debug("create {} failed with exception: {}", elementTypeName, e);
+ log.debug("create {} failed with exception:", elementTypeName, e);
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create " + elementTypeName);
return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
}
@@ -233,8 +223,13 @@ public class TypesUploadServlet extends AbstractValidationsServlet {
Response response = buildErrorResponse(eitherResult.right().value());
responseWrapper.setInnerElement(response);
} else {
- Response response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), eitherResult.left().value());
- responseWrapper.setInnerElement(response);
+ try {
+ Response response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), RepresentationUtils.toRepresentation(eitherResult.left().value()));
+ responseWrapper.setInnerElement(response);
+ } catch (Exception e) {
+ Response response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ responseWrapper.setInnerElement(response);
+ }
}
}
@@ -248,20 +243,16 @@ public class TypesUploadServlet extends AbstractValidationsServlet {
private void createGroupTypes(Wrapper<Response> responseWrapper, String groupTypesYml) {
final Supplier<Either<List<ImmutablePair<GroupTypeDefinition, Boolean>>, ResponseFormat>> generateElementTypeFromYml = () -> groupTypeImportManager.createGroupTypes(groupTypesYml);
buildStatusForElementTypeCreate(responseWrapper, generateElementTypeFromYml, ActionStatus.GROUP_TYPE_ALREADY_EXIST, NodeTypeEnum.GroupType.name());
-
}
// policy types
private void createPolicyTypes(Wrapper<Response> responseWrapper, String policyTypesYml) {
final Supplier<Either<List<ImmutablePair<PolicyTypeDefinition, Boolean>>, ResponseFormat>> generateElementTypeFromYml = () -> policyTypeImportManager.createPolicyTypes(policyTypesYml);
buildStatusForElementTypeCreate(responseWrapper, generateElementTypeFromYml, ActionStatus.POLICY_TYPE_ALREADY_EXIST, NodeTypeEnum.PolicyType.name());
-
}
// data types
- private <ElementTypeDefinition> void buildStatusForElementTypeCreate(Wrapper<Response> responseWrapper, Supplier<Either<List<ImmutablePair<ElementTypeDefinition, Boolean>>, ResponseFormat>> generateElementTypeFromYml,
- ActionStatus alreadyExistStatus, String elementTypeName) {
-
+ private <ElementTypeDefinition> void buildStatusForElementTypeCreate(Wrapper<Response> responseWrapper, Supplier<Either<List<ImmutablePair<ElementTypeDefinition, Boolean>>, ResponseFormat>> generateElementTypeFromYml, ActionStatus alreadyExistStatus, String elementTypeName) {
Either<List<ImmutablePair<ElementTypeDefinition, Boolean>>, ResponseFormat> eitherResult = generateElementTypeFromYml.get();
if (eitherResult.isRight()) {
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/UserAdminServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/UserAdminServlet.java
index c700c31a64..a477bcf4fb 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/UserAdminServlet.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/UserAdminServlet.java
@@ -108,7 +108,7 @@ public class UserAdminServlet extends BeGenericServlet {
} catch (Exception e) {
BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get User");
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get User");
- log.debug("get user failed with unexpected error: {}", e);
+ log.debug("get user failed with unexpected error: {}", e.getMessage(), e);
return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
}
}
@@ -140,7 +140,7 @@ public class UserAdminServlet extends BeGenericServlet {
*
* @ApiResponse(code = 409, message = "User already exists"),
*
- * @ApiResponse(code = 500, message = "Internal Server Error") }) public Response updateUser(@ApiParam(value="userId of user to get", required=true) @PathParam("userId") final String UserIdUpdateUser,
+ * @ApiResponse(code = 500, message = "Internal Server Error") }) public Response updateUser(@ApiParam(value="userId of user to get", required=true) @PathParam("userId") final String userIdUpdateUser,
*
* @Context final HttpServletRequest request,
*
@@ -157,7 +157,7 @@ public class UserAdminServlet extends BeGenericServlet {
* Response response = null;
*
* try { UserAdminBuisinessLogic businessLogic = getUserAdminManager(context); User updateInfoUser = getComponentsUtils().convertJsonToObject(data, modifier, User.class, AuditingActionEnum.UPDATE_USER).left().value(); Either<User, ResponseFormat>
- * updateUserResponse = null;// businessLogic.updateUser(modifier, UserIdUpdateUser, updateInfoUser);
+ * updateUserResponse = null;// businessLogic.updateUser(modifier, userIdUpdateUser, updateInfoUser);
*
* if (updateUserResponse.isRight()) { log.debug("failed to update user metadata"); response = buildErrorResponse(updateUserResponse.right().value()); return response; } response =
* buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), updateUserResponse.left().value()); return response;
@@ -216,7 +216,7 @@ public class UserAdminServlet extends BeGenericServlet {
@ApiOperation(value = "update user role", notes = "Update user role", response = User.class)
@ApiResponses(value = { @ApiResponse(code = 200, message = "Update user OK"), @ApiResponse(code = 400, message = "Invalid Content."), @ApiResponse(code = 403, message = "Missing information/Restricted operation"),
@ApiResponse(code = 404, message = "User not found"), @ApiResponse(code = 405, message = "Method Not Allowed"), @ApiResponse(code = 409, message = "User already exists"), @ApiResponse(code = 500, message = "Internal Server Error") })
- public Response updateUserRole(@ApiParam(value = "userId of user to get", required = true) @PathParam("userId") final String UserIdUpdateUser, @Context final HttpServletRequest request,
+ public Response updateUserRole(@ApiParam(value = "userId of user to get", required = true) @PathParam("userId") final String userIdUpdateUser, @Context final HttpServletRequest request,
@ApiParam(value = "json describe the update role", required = true) String data, @HeaderParam(value = Constants.USER_ID_HEADER) String modifierUserId) {
ServletContext context = request.getSession().getServletContext();
@@ -234,7 +234,7 @@ public class UserAdminServlet extends BeGenericServlet {
try {
UserBusinessLogic businessLogic = getUserAdminManager(context);
User updateInfoUser = getComponentsUtils().convertJsonToObject(data, modifier, User.class, AuditingActionEnum.UPDATE_USER).left().value();
- Either<User, ResponseFormat> updateUserResponse = businessLogic.updateUserRole(modifier, UserIdUpdateUser, updateInfoUser.getRole());
+ Either<User, ResponseFormat> updateUserResponse = businessLogic.updateUserRole(modifier, userIdUpdateUser, updateInfoUser.getRole());
if (updateUserResponse.isRight()) {
log.debug("failed to update user role");
@@ -402,13 +402,12 @@ public class UserAdminServlet extends BeGenericServlet {
@ApiOperation(value = "Retrieve the list of all active ASDC users or only group of users having specific roles.", httpMethod = "GET", notes = "Returns list of users with the specified roles, or all of users in the case of empty 'roles' header", response = User.class)
@ApiResponses(value = { @ApiResponse(code = 200, message = "Returns users Ok"), @ApiResponse(code = 204, message = "No provisioned ASDC users of requested role"), @ApiResponse(code = 403, message = "Restricted Access"),
@ApiResponse(code = 400, message = "Missing content"), @ApiResponse(code = 500, message = "Internal Server Error") })
- public Response getUsersList(@Context final HttpServletRequest request, @ApiParam(value = "Any active user's USER_ID") @HeaderParam(Constants.USER_ID_HEADER) final String userId,
+ public Response getUsersList(@Context final HttpServletRequest request, @ApiParam(value = "Any active user's USER_ID ") @HeaderParam(Constants.USER_ID_HEADER) final String userId,
@ApiParam(value = "TESTER,DESIGNER,PRODUCT_STRATEGIST,OPS,PRODUCT_MANAGER,GOVERNOR, ADMIN OR all users by not typing anything") @QueryParam("roles") final String roles) {
ServletContext context = request.getSession().getServletContext();
String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
- log.debug("modifier id is {}", userId);
+ log.debug("Start handle request of {} modifier id is {}", url, userId);
List<String> rolesList = new ArrayList<>();
if (roles != null && !roles.trim().isEmpty()) {
@@ -450,11 +449,10 @@ public class UserAdminServlet extends BeGenericServlet {
ServletContext context = request.getSession().getServletContext();
String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
+ log.debug("Start handle request of {} modifier id is {}", url, userIdHeader);
User modifier = new User();
modifier.setUserId(userIdHeader);
- log.debug("modifier id is {}", userIdHeader);
Response response = null;
try {
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/switchover/detector/SwitchoverDetector.java b/catalog-be/src/main/java/org/openecomp/sdc/be/switchover/detector/SwitchoverDetector.java
index 4027144911..876066b9ba 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/switchover/detector/SwitchoverDetector.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/switchover/detector/SwitchoverDetector.java
@@ -161,7 +161,7 @@ public class SwitchoverDetector {
if (message == null) {
message = e.getClass().getName();
}
- switchoverLogger.debug("Error occured during switchover detector query, Result is {}", message);
+ logger.debug("Error occured during switchover detector query, Result is {}", message, e);
}
}
if (null == result) {
@@ -178,14 +178,18 @@ public class SwitchoverDetector {
@Override
public void run() {
- switchoverLogger.trace("Executing Switchover Detector Task - Start");
+ logger.trace("Executing Switchover Detector Task - Start");
initializeSiteMode();
Boolean beRes = queryBe();
Boolean feRes = queryFe();
- Boolean updateRequired = siteMode == SwitchoverDetectorState.STANDBY.getState() && (beRes || feRes);
+ if (null == beRes || null == feRes) {
+ return;
+ }
+
+ Boolean updateRequired = siteMode == SwitchoverDetectorState.STANDBY.getState() && (beRes || feRes) & (beMatch != beRes || feMatch != feRes);
updateSiteModeAndPriority(beRes && feRes, siteMode == SwitchoverDetectorState.STANDBY.getState(), updateRequired);
@@ -232,7 +236,8 @@ public class SwitchoverDetector {
if (message == null) {
message = e.getClass().getName();
}
- switchoverLogger.error("Error occured during change site priority request, Result is {}", message);
+
+ logger.debug("Error occured during change site priority request, Result is {}", message, e);
}
}
@@ -252,7 +257,8 @@ public class SwitchoverDetector {
if (message == null) {
message = e.getClass().getName();
}
- switchoverLogger.error("Error occured during publish network request, Result is {}", message);
+
+ logger.debug("Error occured during publish network request, Result is {}", message, e);
}
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ArtifactTypes.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ArtifactTypes.java
index 85b4493c8e..13356e5de4 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ArtifactTypes.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ArtifactTypes.java
@@ -24,6 +24,7 @@ import java.util.List;
import org.openecomp.sdc.generator.data.ArtifactType;
+
public class ArtifactTypes {
private List<ArtifactType> artifactTypes;
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CapabiltyRequirementConvertor.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CapabiltyRequirementConvertor.java
index d1f2557413..b21e064a82 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CapabiltyRequirementConvertor.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CapabiltyRequirementConvertor.java
@@ -24,8 +24,11 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import java.util.stream.Collectors;
import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition;
import org.openecomp.sdc.be.model.CapabilityDefinition;
import org.openecomp.sdc.be.model.Component;
import org.openecomp.sdc.be.model.ComponentInstance;
@@ -33,8 +36,6 @@ import org.openecomp.sdc.be.model.ComponentInstanceProperty;
import org.openecomp.sdc.be.model.DataTypeDefinition;
import org.openecomp.sdc.be.model.PropertyDefinition;
import org.openecomp.sdc.be.model.RequirementDefinition;
-import org.openecomp.sdc.be.resources.data.CapabilityData;
-import org.openecomp.sdc.be.resources.data.RequirementData;
import org.openecomp.sdc.be.tosca.model.SubstitutionMapping;
import org.openecomp.sdc.be.tosca.model.ToscaCapability;
import org.openecomp.sdc.be.tosca.model.ToscaNodeTemplate;
@@ -42,14 +43,18 @@ import org.openecomp.sdc.be.tosca.model.ToscaNodeType;
import org.openecomp.sdc.be.tosca.model.ToscaProperty;
import org.openecomp.sdc.be.tosca.model.ToscaRequirement;
import org.openecomp.sdc.be.tosca.model.ToscaTemplateCapability;
+import org.openecomp.sdc.common.util.ValidationUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import com.google.common.collect.Lists;
+
import fj.data.Either;
public class CapabiltyRequirementConvertor {
private static CapabiltyRequirementConvertor instance;
-
+ public final static String PATH_DELIMITER = ".";
+
protected CapabiltyRequirementConvertor() {
}
@@ -131,8 +136,8 @@ public class CapabiltyRequirementConvertor {
return Either.left(nodeType);
}
- public Either<SubstitutionMapping, ToscaError> convertRequirements(Component component, SubstitutionMapping substitutionMapping) {
- Map<String, ToscaRequirement> toscaRequirements = convertRequirementsAsMap(component);
+ public Either<SubstitutionMapping, ToscaError> convertSubstitutionMappingRequirements(Component component, SubstitutionMapping substitutionMapping) {
+ Map<String, String[]> toscaRequirements = convertSubstitutionMappingRequirementsAsMap(component);
if (!toscaRequirements.isEmpty()) {
substitutionMapping.setRequirements(toscaRequirements);
}
@@ -145,9 +150,9 @@ public class CapabiltyRequirementConvertor {
Map<String, List<RequirementDefinition>> requirements = component.getRequirements();
List<Map<String, ToscaRequirement>> toscaRequirements = new ArrayList<>();
if (requirements != null) {
- boolean isNodeType = ToscaUtils.isNodeType(component);
+ boolean isNodeType = ToscaUtils.isAtomicType(component);
for (Map.Entry<String, List<RequirementDefinition>> entry : requirements.entrySet()) {
- entry.getValue().stream().filter(r -> (!isNodeType || (isNodeType && component.getUniqueId().equals(r.getOwnerId())))).forEach(r -> {
+ entry.getValue().stream().filter(r -> (!isNodeType || (isNodeType && component.getUniqueId().equals(r.getOwnerId())) || (isNodeType && r.getOwnerId() == null))).forEach(r -> {
ImmutablePair<String, ToscaRequirement> pair = convertRequirement(component, isNodeType, r);
Map<String, ToscaRequirement> requirement = new HashMap<>();
@@ -163,17 +168,25 @@ public class CapabiltyRequirementConvertor {
return toscaRequirements;
}
- private Map<String, ToscaRequirement> convertRequirementsAsMap(Component component) {
+ private String getSubPathByFirstDelimiterAppearance(String path) {
+ return path.substring(path.indexOf(PATH_DELIMITER) + 1);
+ }
+
+ private String getSubPathByLastDelimiterAppearance(String path) {
+ return path.substring(path.lastIndexOf(PATH_DELIMITER) + 1);
+ }
+
+ //This function calls on Substitution Mapping region - the component is always non-atomic
+ private Map<String, String[]> convertSubstitutionMappingRequirementsAsMap(Component component) {
Map<String, List<RequirementDefinition>> requirements = component.getRequirements();
- Map<String, ToscaRequirement> toscaRequirements = new HashMap<>();
+ Map<String, String[]> toscaRequirements = new HashMap<>();
if (requirements != null) {
- boolean isNodeType = ToscaUtils.isNodeType(component);
for (Map.Entry<String, List<RequirementDefinition>> entry : requirements.entrySet()) {
- entry.getValue().stream().filter(r -> (!isNodeType || (isNodeType && component.getUniqueId().equals(r.getOwnerId())))).forEach(r -> {
- ImmutablePair<String, ToscaRequirement> pair = convertRequirement(component, isNodeType, r);
- toscaRequirements.put(pair.left, pair.right);
+ entry.getValue().stream().forEach(r -> {
+ String fullReqName = getRequirementPath(r);
+ log.debug("the requirement {} belongs to resource {} ", fullReqName, component.getUniqueId());
+ toscaRequirements.put(fullReqName, new String[]{r.getOwnerName(), getSubPathByFirstDelimiterAppearance(fullReqName)});
});
-
log.debug("Finish convert Requirements for node type");
}
} else {
@@ -182,17 +195,25 @@ public class CapabiltyRequirementConvertor {
return toscaRequirements;
}
+ private String getRequirementPath(RequirementDefinition r) {
+ List<String> pathArray = Lists.reverse(r.getPath().stream()
+ .map(path -> ValidationUtils.normalizeComponentInstanceName(getSubPathByLastDelimiterAppearance(path)))
+ .collect(Collectors.toList()));
+ return new StringBuilder().append(String.join(PATH_DELIMITER, pathArray)).append(PATH_DELIMITER).append(r.getName()).toString();
+
+ }
+
private ImmutablePair<String, ToscaRequirement> convertRequirement(Component component, boolean isNodeType, RequirementDefinition r) {
String name = r.getName();
if (!isNodeType) {
- name = r.getOwnerName() + "." + name;
+ name = getRequirementPath(r);
}
log.debug("the requirement {} belongs to resource {} ", name, component.getUniqueId());
ToscaRequirement toscaRequirement = new ToscaRequirement();
List<Object> occurences = new ArrayList<>();
occurences.add(Integer.valueOf(r.getMinOccurrences()));
- if (r.getMaxOccurrences().equals(RequirementData.MAX_OCCURRENCES)) {
+ if (r.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
occurences.add(r.getMaxOccurrences());
} else {
occurences.add(Integer.valueOf(r.getMaxOccurrences()));
@@ -212,9 +233,9 @@ public class CapabiltyRequirementConvertor {
Map<String, List<CapabilityDefinition>> capabilities = component.getCapabilities();
Map<String, ToscaCapability> toscaCapabilities = new HashMap<>();
if (capabilities != null) {
- boolean isNodeType = ToscaUtils.isNodeType(component);
+ boolean isNodeType = ToscaUtils.isAtomicType(component);
for (Map.Entry<String, List<CapabilityDefinition>> entry : capabilities.entrySet()) {
- entry.getValue().stream().filter(c -> (!isNodeType || (isNodeType && component.getUniqueId().equals(c.getOwnerId())))).forEach(c -> {
+ entry.getValue().stream().filter(c -> (!isNodeType || (isNodeType && component.getUniqueId().equals(c.getOwnerId())) || (isNodeType && c.getOwnerId() == null) )).forEach(c -> {
convertCapabilty(component, toscaCapabilities, isNodeType, c, dataTypes);
});
@@ -225,11 +246,39 @@ public class CapabiltyRequirementConvertor {
return toscaCapabilities;
}
+
+ //This function calls on Substitution Mapping region - the component is always non-atomic
+ public Map<String, String[]> convertSubstitutionMappingCapabilities(Component component, Map<String, DataTypeDefinition> dataTypes) {
+ Map<String, List<CapabilityDefinition>> capabilities = component.getCapabilities();
+ Map<String, String[]> toscaCapabilities = new HashMap<>();
+ if (capabilities != null) {
+ for (Map.Entry<String, List<CapabilityDefinition>> entry : capabilities.entrySet()) {
+ entry.getValue().stream().forEach(c -> {
+ String fullCapName = getCapabilityPath(c);
+ log.debug("the capabilty {} belongs to resource {} ", fullCapName, component.getUniqueId());
+ toscaCapabilities.put(fullCapName, new String[]{c.getOwnerName(), getSubPathByFirstDelimiterAppearance(fullCapName)});
+ });
+ }
+ } else {
+ log.debug("No Capabilities for node type");
+ }
+ return toscaCapabilities;
+ }
+
+ private String getCapabilityPath(CapabilityDefinition c) {
+ List<String> pathArray = Lists.reverse(c.getPath().stream()
+ .map(path -> ValidationUtils.normalizeComponentInstanceName(getSubPathByLastDelimiterAppearance(path)))
+ .collect(Collectors.toList()));
+ return new StringBuilder().append(String.join(PATH_DELIMITER, pathArray)).append(PATH_DELIMITER).append(c.getName()).toString();
+ }
+
+
+
private void convertCapabilty(Component component, Map<String, ToscaCapability> toscaCapabilities, boolean isNodeType, CapabilityDefinition c, Map<String, DataTypeDefinition> dataTypes) {
String name = c.getName();
if (!isNodeType) {
- name = c.getOwnerName() + "." + name;
+ name = getCapabilityPath(c);
}
log.debug("the capabilty {} belongs to resource {} ", name, component.getUniqueId());
ToscaCapability toscaCapability = new ToscaCapability();
@@ -238,7 +287,7 @@ public class CapabiltyRequirementConvertor {
List<Object> occurences = new ArrayList<>();
occurences.add(Integer.valueOf(c.getMinOccurrences()));
- if (c.getMaxOccurrences().equals(CapabilityData.MAX_OCCURRENCES)) {
+ if (c.getMaxOccurrences().equals(CapabilityDataDefinition.MAX_OCCURRENCES)) {
occurences.add(c.getMaxOccurrences());
} else {
occurences.add(Integer.valueOf(c.getMaxOccurrences()));
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CsarUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CsarUtils.java
index c8aa188e30..3c0c80666c 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CsarUtils.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CsarUtils.java
@@ -20,65 +20,98 @@
package org.openecomp.sdc.be.tosca;
+import java.io.File;
import java.io.IOException;
-import org.apache.commons.codec.binary.Base64;
-import java.util.Collection;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.EnumMap;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
+import java.util.Map.Entry;
import java.util.Set;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
+import java.util.zip.ZipException;
+import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
+import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
+import org.apache.commons.io.IOUtils;
import org.apache.commons.io.output.ByteArrayOutputStream;
+import org.apache.commons.lang.WordUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.apache.commons.lang3.tuple.ImmutableTriple;
import org.apache.commons.lang3.tuple.Triple;
import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;
-import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperation;
+import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum;
+import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationInfo;
+import org.openecomp.sdc.be.components.impl.ImportUtils;
import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;
+import org.openecomp.sdc.be.config.Configuration.ArtifactTypeConfig;
+import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao;
import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus;
+import org.openecomp.sdc.be.dao.cassandra.SdcSchemaFilesCassandraDao;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.model.ArtifactDefinition;
import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.ComponentInstance;
import org.openecomp.sdc.be.model.LifecycleStateEnum;
import org.openecomp.sdc.be.model.Operation;
+import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.Service;
import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
-import org.openecomp.sdc.be.model.operations.impl.ServiceOperation;
+import org.openecomp.sdc.be.model.operations.impl.LifecycleOperation;
import org.openecomp.sdc.be.resources.data.ESArtifactData;
+import org.openecomp.sdc.be.resources.data.ESSdcSchemaFilesData;
import org.openecomp.sdc.be.tosca.model.ToscaTemplate;
import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
+import org.openecomp.sdc.common.api.ArtifactTypeEnum;
+import org.openecomp.sdc.common.impl.ExternalConfiguration;
import org.openecomp.sdc.common.util.GeneralUtility;
import org.openecomp.sdc.common.util.ValidationUtils;
import org.openecomp.sdc.exception.ResponseFormat;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-
+import org.openecomp.sdc.generator.data.AdditionalParams;
import org.openecomp.sdc.generator.data.Artifact;
import org.openecomp.sdc.generator.data.ArtifactType;
import org.openecomp.sdc.generator.data.GenerationData;
import org.openecomp.sdc.generator.impl.ArtifactGenerationServiceImpl;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+
import com.google.gson.Gson;
import fj.data.Either;
+
/**
* @author tg851x
*
*/
@org.springframework.stereotype.Component("csar-utils")
public class CsarUtils {
- private static Logger log = LoggerFactory.getLogger(ToscaExportHandler.class.getName());
+ private static Logger log = LoggerFactory.getLogger(CsarUtils.class.getName());
@Autowired
+ private SdcSchemaFilesCassandraDao sdcSchemaFilesCassandraDao;
+ @Autowired
private ArtifactCassandraDao artifactCassandraDao;
@Autowired
private ComponentsUtils componentsUtils;
@@ -87,45 +120,68 @@ public class CsarUtils {
@Autowired
private ArtifactsBusinessLogic artifactsBusinessLogic;
@Autowired
- protected ServiceOperation serviceOperation;
+ protected ToscaOperationFacade toscaOperationFacade;
+
@javax.annotation.Resource
private ServiceBusinessLogic serviceBusinessLogic;
private Gson gson = new Gson();
- private static final String DEFINITIONS_PATH = "Definitions/";
- private static final String ARTIFACTS_PATH = "Artifacts/";
+ public static final String CONFORMANCE_LEVEL = ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel();
+ public static final String SDC_VERSION = ExternalConfiguration.getAppVersion();
+
+ public static final Pattern UUID_NORMATIVE_NEW_VERSION = Pattern.compile("^\\d{1,}.0");
+ public static final String ARTIFACTS_PATH = "Artifacts/";
+ public static final String RESOURCES_PATH = "Resources/";
+ public static final String INFORMATIONAL_ARTIFACTS = "Informational/";
+ public static final String DEPLOYMENT_ARTIFACTS = "Deployment/";
+
+ public static final String DEFINITIONS_PATH = "Definitions/";
+ private static final String CSAR_META_VERSION = "1.0";
+ private static final String CSAR_META_PATH_FILE_NAME = "csar.meta";
private static final String TOSCA_META_PATH_FILE_NAME = "TOSCA-Metadata/TOSCA.meta";
private static final String TOSCA_META_VERSION = "1.0";
private static final String CSAR_VERSION = "1.1";
+ public static final String VFC_NODE_TYPE_ARTIFACTS_PATH_PATTERN = ARTIFACTS_PATH + ImportUtils.Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + "([\\w\\_\\-\\.\\s]+)(/)([\\w\\_\\-\\.\\s]+)(/)([\\w\\_\\-\\.\\s\\/]+)";
+
+ public static final String VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN = ARTIFACTS_PATH +
+ // Artifact Group (i.e Deployment/Informational)
+ "([\\w\\_\\-\\.\\s]+)(/)" +
+ // Artifact Type
+ "([\\w\\_\\-\\.\\s]+)(/)" +
+ // Artifact File Name
+ "([\\w\\_\\-\\.\\s]+)";
+ public static final String ARTIFACT_CREATED_FROM_CSAR = "Artifact created from csar";
+
/**
*
* @param component
* @param getFromCS
* @param isInCertificationRequest
- * @param shouldLock
- * @param inTransaction
* @return
*/
- public Either<byte[], ResponseFormat> createCsar(Component component, boolean getFromCS, boolean isInCertificationRequest, boolean shouldLock, boolean inTransaction) {
- return createCsar(component, getFromCS, isInCertificationRequest, false, shouldLock, inTransaction);
+ public Either<byte[], ResponseFormat> createCsar(Component component, boolean getFromCS, boolean isInCertificationRequest) {
+ return createCsar(component, getFromCS, isInCertificationRequest, false);
}
- private Either<byte[], ResponseFormat> createCsar(Component component, boolean getFromCS, boolean isInCertificationRequest, boolean mockGenerator, boolean shouldLock, boolean inTransaction) {
- final String CREATED_BY = component.getCreatorFullName();
+ private Either<byte[], ResponseFormat> createCsar(Component component, boolean getFromCS, boolean isInCertificationRequest, boolean mockGenerator) {
+ final String createdBy = component.getCreatorFullName();
String fileName;
Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts();
ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
fileName = artifactDefinition.getArtifactName();
- String toscaBlock0 = createToscaBlock0(TOSCA_META_VERSION, CSAR_VERSION, CREATED_BY, fileName);
-
+ String toscaConformanceLevel = ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel();
+ String csarBlock0 = createCsarBlock0(CSAR_META_VERSION, toscaConformanceLevel);
+ byte[] csarBlock0Byte = csarBlock0.getBytes();
+
+ final String toscaBlock0 = createToscaBlock0(TOSCA_META_VERSION, CSAR_VERSION, createdBy, fileName);
byte[] toscaBlock0Byte = toscaBlock0.getBytes();
- Either<byte[], ResponseFormat> generateCsarZipResponse = generateCsarZip(toscaBlock0Byte, component, getFromCS, isInCertificationRequest, mockGenerator, shouldLock, inTransaction);
+ Either<byte[], ResponseFormat> generateCsarZipResponse = generateCsarZip(csarBlock0Byte, toscaBlock0Byte, component, getFromCS, isInCertificationRequest, mockGenerator);
if (generateCsarZipResponse.isRight()) {
return Either.right(generateCsarZipResponse.right().value());
@@ -134,64 +190,50 @@ public class CsarUtils {
return Either.left(generateCsarZipResponse.left().value());
}
- private Either<byte[], ResponseFormat> generateCsarZip(byte[] toscaBlock0Byte, Component component, boolean getFromCS, boolean isInCertificationRequest, boolean mockGenerator, boolean shouldLock, boolean inTransaction) {
-
- ZipOutputStream zip = null;
- ByteArrayOutputStream out = null;
- try {
- out = new ByteArrayOutputStream();
- zip = new ZipOutputStream(out);
-
+ private Either<byte[], ResponseFormat> generateCsarZip(byte[] csarBlock0Byte, byte[] toscaBlock0Byte, Component component, boolean getFromCS, boolean isInCertificationRequest, boolean mockGenerator) {
+ try (
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ ZipOutputStream zip = new ZipOutputStream(out);
+ ){
+ zip.putNextEntry(new ZipEntry(CSAR_META_PATH_FILE_NAME));
+ zip.write(csarBlock0Byte);
zip.putNextEntry(new ZipEntry(TOSCA_META_PATH_FILE_NAME));
zip.write(toscaBlock0Byte);
- Either<ZipOutputStream, ResponseFormat> populateZip = populateZip(component, getFromCS, zip, isInCertificationRequest, mockGenerator, shouldLock, inTransaction);
+ Either<ZipOutputStream, ResponseFormat> populateZip = populateZip(component, getFromCS, zip, isInCertificationRequest, mockGenerator);
if (populateZip.isRight()) {
log.debug("Failed to populate CSAR zip file {}", populateZip.right().value());
return Either.right(populateZip.right().value());
}
- zip = populateZip.left().value();
zip.finish();
byte[] byteArray = out.toByteArray();
return Either.left(byteArray);
} catch (IOException e) {
- log.debug("createCsar failed IOexception", e);
+ log.debug("Failed with IOexception to create CSAR zip for component {}", component.getUniqueId(), e);
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
return Either.right(responseFormat);
- } finally {
- try {
- if (zip != null) {
- zip.close();
- }
- if (out != null) {
- out.close();
- }
- } catch (Exception e) {
- log.error("Failed to close resources ", e);
- }
}
}
- private Either<ZipOutputStream, ResponseFormat> populateZip(Component component, boolean getFromCS, ZipOutputStream zip, boolean isInCertificationRequest, boolean mockGenerator, boolean shouldLock, boolean inTransaction) {
+ private Either<ZipOutputStream, ResponseFormat> populateZip(Component component, boolean getFromCS, ZipOutputStream zip, boolean isInCertificationRequest, boolean mockGenerator) throws IOException {
LifecycleStateEnum lifecycleState = component.getLifecycleState();
- String componentYaml = null;
- Either<ToscaRepresentation, ToscaError> exportComponent = null;
- byte[] mainYaml = null;
- // <file name, esid, component>
+ String componentYaml;
+ Either<ToscaRepresentation, ToscaError> exportComponent;
+ byte[] mainYaml;
+ // <file name, cassandraId, component>
List<Triple<String, String, Component>> dependencies = null;
List<ImmutablePair<Component, byte[]>> generatorInputs = new LinkedList<>();
- String fileName;
Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts();
ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
- fileName = artifactDefinition.getArtifactName();
+ String fileName = artifactDefinition.getArtifactName();
if (getFromCS || !(lifecycleState == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN || lifecycleState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) {
- String esId = artifactDefinition.getEsId();
- Either<byte[], ActionStatus> fromCassandra = getFromCassandra(esId);
+ String cassandraId = artifactDefinition.getEsId();
+ Either<byte[], ActionStatus> fromCassandra = getFromCassandra(cassandraId);
if (fromCassandra.isRight()) {
ResponseFormat responseFormat = componentsUtils.getResponseFormat(fromCassandra.right().value());
return Either.right(responseFormat);
@@ -212,147 +254,214 @@ public class CsarUtils {
dependencies = exportResult.getDependencies();
}
- try {
- zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + fileName));
- zip.write(mainYaml);
+ zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + fileName));
+ zip.write(mainYaml);
+ //US798487 - Abstraction of complex types
+ if (!ToscaUtils.isAtomicType(component)){
+ log.debug("Component {} is complex - generating abstract type for it..", component.getName());
+ writeComponentInterface(component, zip, fileName);
+ }
- generatorInputs.add(new ImmutablePair<Component, byte[]>(component, mainYaml));
+ generatorInputs.add(new ImmutablePair<Component, byte[]>(component, mainYaml));
- if (dependencies == null) {
- Either<ToscaTemplate, ToscaError> dependenciesRes = toscaExportUtils.getDependencies(component);
- if (dependenciesRes.isRight()) {
- log.debug("Failed to retrieve dependencies for component {}, error {}", component.getUniqueId(), dependenciesRes.right().value());
- ActionStatus convertFromToscaError = componentsUtils.convertFromToscaError(dependenciesRes.right().value());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(convertFromToscaError);
+ if (dependencies == null) {
+ Either<ToscaTemplate, ToscaError> dependenciesRes = toscaExportUtils.getDependencies(component);
+ if (dependenciesRes.isRight()) {
+ log.debug("Failed to retrieve dependencies for component {}, error {}", component.getUniqueId(),
+ dependenciesRes.right().value());
+ ActionStatus convertFromToscaError = componentsUtils.convertFromToscaError(dependenciesRes.right().value());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(convertFromToscaError);
+ return Either.right(responseFormat);
+ }
+ dependencies = dependenciesRes.left().value().getDependencies();
+ }
+
+ //UID <cassandraId,filename,component>
+ Map<String, ImmutableTriple<String,String, Component>> innerComponentsCache = new HashMap<>();
+
+ if (dependencies != null && !dependencies.isEmpty()) {
+ for (Triple<String, String, Component> d : dependencies) {
+ String cassandraId = d.getMiddle();
+ Component childComponent = d.getRight();
+ Either<byte[], ActionStatus> entryData = getEntryData(cassandraId, childComponent);
+
+ if (entryData.isRight()) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(entryData.right().value());
return Either.right(responseFormat);
}
- dependencies = dependenciesRes.left().value().getDependencies();
- }
- if (dependencies != null && !dependencies.isEmpty()) {
- for (Triple<String, String, Component> d : dependencies) {
- String esId = d.getMiddle();
- Component childComponent = d.getRight();
- fileName = d.getLeft();
- Either<byte[], ActionStatus> entryData = getEntryData(esId, childComponent);
-
- if (entryData.isRight()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(entryData.right().value());
- return Either.right(responseFormat);
- }
+ //fill innerComponentsCache
+ fileName = d.getLeft();
+ innerComponentsCache.put(childComponent.getUniqueId(),
+ new ImmutableTriple<String, String, Component>(cassandraId, fileName, childComponent));
+ insertInnerComponentsToCache(innerComponentsCache, childComponent);
+
byte[] content = entryData.left().value();
- zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + fileName));
- zip.write(content);
-
generatorInputs.add(new ImmutablePair<Component, byte[]>(childComponent, content));
}
- }
-
- List<ArtifactDefinition> aiiArtifactList = new LinkedList<>();
- // Artifact Generation
- if (component.getComponentType() == ComponentTypeEnum.SERVICE && (lifecycleState == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN || lifecycleState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) {
- Either<List<ArtifactDefinition>, ResponseFormat> handleAAIArtifacts = handleAAIArtifacts(component, zip, mockGenerator, shouldLock, inTransaction, generatorInputs);
+
+ //add inner components to CSAR
+ innerComponentsCache.forEach((childUid, innerComponentTriple) -> {
+ Component innerComponent = innerComponentTriple.getRight();
+ String icFileName = innerComponentTriple.getMiddle();
+
+ try {
+ //add component to zip
+ Either<byte[], ActionStatus> entryData = getEntryData(innerComponentTriple.getLeft(), innerComponent);
+ byte[] content = entryData.left().value();
+ zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + icFileName));
+ zip.write(content);
+
+ } catch (IOException e) {
- if (handleAAIArtifacts.isLeft()) {
- aiiArtifactList = handleAAIArtifacts.left().value();
- } else {
- log.debug("AAI Artifacts handling failed");
- return Either.right(handleAAIArtifacts.right().value());
- }
-
- if (isInCertificationRequest) {
- Either<ActionStatus, ResponseFormat> handleAllAAIArtifactsInDataModel = handleAllAAIArtifactsInDataModel(component, aiiArtifactList, shouldLock, inTransaction);
-
- if (handleAllAAIArtifactsInDataModel.isRight()) {
- log.debug("AAI Artifacts handling (create, update, delete) failed");
- return Either.right(handleAllAAIArtifactsInDataModel.right().value());
}
- }
+ //add component interface to zip
+ if(!ToscaUtils.isAtomicType(innerComponent)) {
+ writeComponentInterface(innerComponent, zip, icFileName);
+ }
+ });
+ }
+
+ /*Either<byte[], ActionStatus> latestSchemaFilesFromCassandra = getLatestSchemaFilesFromCassandra();
+
+ if(latestSchemaFilesFromCassandra.isRight()){
+ return null;
+ }*/
+
+ //TODO Tal G this is quick solution until Cassandra US is alligned
+ Either<ZipOutputStream, ResponseFormat> addSchemaFilesFromConfig = addSchemaFilesFromConfig(zip);
+
+ if(addSchemaFilesFromConfig.isRight()){
+ return addSchemaFilesFromConfig;
+ }
+
+ // Artifact Generation
+ if (component.getComponentType() == ComponentTypeEnum.SERVICE
+ && isInCertificationRequest) {
+
+ List<ArtifactDefinition> aiiArtifactList;
+
+ Either<List<ArtifactDefinition>, ResponseFormat> handleAAIArtifacts = handleAAIArtifacts(component, mockGenerator, generatorInputs);
+
+ if (handleAAIArtifacts.isLeft()) {
+ aiiArtifactList = handleAAIArtifacts.left().value();
+ } else {
+ log.debug("AAI Artifacts handling failed");
+ return Either.right(handleAAIArtifacts.right().value());
}
- // Collecting All Deployment Artifacts
- Either<ZipOutputStream, ActionStatus> collectAndWriteToScarDeploymentArtifacts = collectAndWriteToScarDeploymentArtifacts(zip, component, aiiArtifactList);
+ if (isInCertificationRequest) {
+ Either<ActionStatus, ResponseFormat> handleAllAAIArtifactsInDataModel = handleAllAAIArtifactsInDataModel(
+ component, aiiArtifactList, false, true);
- if (collectAndWriteToScarDeploymentArtifacts.isRight()) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ if (handleAllAAIArtifactsInDataModel.isRight()) {
+ log.debug("AAI Artifacts handling (create, update, delete) failed");
+ return Either.right(handleAllAAIArtifactsInDataModel.right().value());
+ }
}
- } catch (IOException e) {
- log.debug("Failed to create CSAR zip for component {}", component.getUniqueId(), e);
- }
-
- return Either.left(zip);
- }
- private Either<ZipOutputStream, ActionStatus> collectAndWriteToScarDeploymentArtifacts(ZipOutputStream zip, Component component, List<ArtifactDefinition> aiiArtifactList) throws IOException {
-
- Collection<ArtifactDefinition> deploymentArtifactsToAdd = null;
- Collection<ArtifactDefinition> allArtifactsToAdd = new LinkedList<>();
+ }
- if (component.getComponentType() == ComponentTypeEnum.SERVICE) {
- Either<Service, StorageOperationStatus> getServiceResponse = serviceOperation.getService(component.getUniqueId());
+ Either<CsarDefinition, ResponseFormat> collectedComponentCsarDefinition = collectComponentCsarDefinition(component);
- if (getServiceResponse.isLeft()) {
- Service service = getServiceResponse.left().value();
+ if (collectedComponentCsarDefinition.isRight()) {
+ return Either.right(collectedComponentCsarDefinition.right().value());
+ }
+
+ return writeAllFilesToScar(component, collectedComponentCsarDefinition.left().value(), zip, isInCertificationRequest);
+ }
- if (!aiiArtifactList.isEmpty()) {
- deploymentArtifactsToAdd = service.getDeploymentArtifacts().values().stream().filter(e -> e.getGenerated() == null || !e.getGenerated()).collect(Collectors.toList());
- allArtifactsToAdd.addAll(aiiArtifactList);
- allArtifactsToAdd.addAll(deploymentArtifactsToAdd);
- } else {
- allArtifactsToAdd.addAll(service.getDeploymentArtifacts().values());
- }
+ private Either<ZipOutputStream, ResponseFormat> addSchemaFilesFromConfig(ZipOutputStream zip) throws ZipException, IOException {
+ final String pathAndFile = "config/SDC.zip";
+
+ File file = new File(pathAndFile);
+ if(!file.exists()){
+ log.debug("SDC.zip schema files archive not found");
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+
+ try(ZipFile zipFile = new ZipFile(new File(pathAndFile));){
+ Enumeration<? extends ZipEntry> entries = zipFile.entries();
+
+ while(entries.hasMoreElements()){
+ ZipEntry nextElement = entries.nextElement();
+ InputStream inputStream = zipFile.getInputStream(nextElement);
+ byte[] byteArray = IOUtils.toByteArray(inputStream);
+
+ zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + nextElement.getName()));
+ zip.write(byteArray);
}
+ zipFile.close();
+ }catch (Exception e) {
+ log.debug("Error in writing SDC.zip schema files to CSAR");
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
}
+
+ return Either.left(zip);
+ }
- if (!allArtifactsToAdd.isEmpty()) {
-
- for (ArtifactDefinition deploymentArtifactDefinition : allArtifactsToAdd) {
- String artifactFileName = deploymentArtifactDefinition.getArtifactName();
- byte[] payloadData = deploymentArtifactDefinition.getPayloadData();
-
- if (payloadData == null) {
- String esId = deploymentArtifactDefinition.getEsId();
- if (esId != null) {
- Either<byte[], ActionStatus> fromCassandra = getFromCassandra(esId);
-
- if (fromCassandra.isRight()) {
- return Either.right(fromCassandra.right().value());
- }
- payloadData = fromCassandra.left().value();
- } else {
- log.debug("Artifact {} payload not supplied in ArtifactDefinition and not found in DB", artifactFileName);
- continue;
+ private void insertInnerComponentsToCache(Map<String, ImmutableTriple<String, String, Component>> componentCache,
+ Component childComponent) {
+
+ List<ComponentInstance> instances = childComponent.getComponentInstances();
+
+ if(instances != null) {
+ instances.forEach(ci -> {
+ ImmutableTriple<String, String, Component> componentRecord = componentCache.get(ci.getComponentUid());
+ if (componentRecord == null) {
+ // all resource must be only once!
+ Either<Resource, StorageOperationStatus> resource = toscaOperationFacade.getToscaElement(ci.getComponentUid());
+ if (resource.isRight()) {
+ log.debug("Failed to fetch resource with id {} for instance {}");
+ }
+ Component componentRI = resource.left().value();
+
+ Map<String, ArtifactDefinition> childToscaArtifacts = componentRI.getToscaArtifacts();
+ ArtifactDefinition childArtifactDefinition = childToscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
+ if (childArtifactDefinition != null) {
+ //add to cache
+ componentCache.put(ci.getComponentUid(),
+ new ImmutableTriple<String, String, Component>(childArtifactDefinition.getEsId(),
+ childArtifactDefinition.getArtifactName(), componentRI));
}
- }
-
- byte[] decodedPayload = null;
- if (Base64.isBase64(payloadData)) {
- // decodedPayload = Base64.getDecoder().decode(payloadData);
- decodedPayload = Base64.decodeBase64(payloadData);
- } else {
- decodedPayload = payloadData;
+ //if not atomic - insert inner components as well
+ if(!ToscaUtils.isAtomicType(componentRI)) {
+ insertInnerComponentsToCache(componentCache, componentRI);
+ }
}
-
- zip.putNextEntry(new ZipEntry(ARTIFACTS_PATH + artifactFileName));
- zip.write(decodedPayload);
- }
+ });
}
-
+ }
+
+ private Either<ZipOutputStream, ResponseFormat> writeComponentInterface(Component component, ZipOutputStream zip, String fileName) {
+ try {
+ Either<ToscaRepresentation, ToscaError> componentInterface = toscaExportUtils.exportComponentInterface(component);
+ ToscaRepresentation componentInterfaceYaml = componentInterface.left().value();
+ String mainYaml = componentInterfaceYaml.getMainYaml();
+ String interfaceFileName = DEFINITIONS_PATH + ToscaExportHandler.getInterfaceFilename(fileName);
+
+ zip.putNextEntry(new ZipEntry(interfaceFileName));
+ zip.write(mainYaml.getBytes());
+
+ } catch (Exception e) {
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+
return Either.left(zip);
}
-
- private Either<List<ArtifactDefinition>, ResponseFormat> handleAAIArtifacts(Component component, ZipOutputStream zip, boolean mockGenerator, boolean shouldLock, boolean inTransaction, List<ImmutablePair<Component, byte[]>> generatorInputs) {
+
+ private Either<List<ArtifactDefinition>, ResponseFormat> handleAAIArtifacts(Component component, boolean mockGenerator, List<ImmutablePair<Component, byte[]>> generatorInputs) {
ComponentTypeEnum componentType = component.getComponentType();
- List<Artifact> generatedArtifacts = null;
- List<ArtifactDefinition> aaiArtifacts = null;
+ List<Artifact> generatedArtifacts;
+ List<ArtifactDefinition> aaiArtifacts = new LinkedList<>();
if (componentType == ComponentTypeEnum.SERVICE && !generatorInputs.isEmpty()) {
List<Artifact> convertedGeneratorInputs = convertToGeneratorArtifactsInput(generatorInputs);
- Either<List<Artifact>, ResponseFormat> generatorResponse;
+ Either<List<Artifact>, String> generatorResponse;
if (mockGenerator) {
generatorResponse = artifactGenerator(convertedGeneratorInputs, ArtifactType.OTHER, component);
@@ -361,7 +470,7 @@ public class CsarUtils {
}
if (generatorResponse.isRight()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.AAI_ARTIFACT_GENERATION_FAILED, component.getComponentType().getValue(), component.getName(), generatorResponse.toString());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.AAI_ARTIFACT_GENERATION_FAILED, component.getComponentType().getValue(), component.getName(), generatorResponse.right().value());
return Either.right(responseFormat);
}
@@ -376,8 +485,8 @@ public class CsarUtils {
private Either<ActionStatus, ResponseFormat> handleAllAAIArtifactsInDataModel(Component component, List<ArtifactDefinition> artifactsFromAAI, boolean shouldLock, boolean inTransaction) {
- Either<ActionStatus, ResponseFormat> handleAAIArtifactsResponse = null;
- User lastComponentUpdater = null;
+ Either<ActionStatus, ResponseFormat> handleAAIArtifactsResponse;
+ User lastComponentUpdater;
List<ArtifactDefinition> aaiArtifatcsToCreate = getAAIArtifatcsForCreate(artifactsFromAAI, component);
List<ArtifactDefinition> aaiArtifatcsToDelete = getAAIArtifatcsForDelete(artifactsFromAAI, component);
@@ -393,19 +502,21 @@ public class CsarUtils {
lastComponentUpdater = validateUserExists.left().value();
- handleAAIArtifactsResponse = handleAAIArtifactsInDataModelByOperationType(component, aaiArtifatcsToDelete, ArtifactOperation.Delete, lastComponentUpdater, shouldLock, inTransaction);
+ handleAAIArtifactsResponse = handleAAIArtifactsInDataModelByOperationType(component, aaiArtifatcsToDelete, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Delete), lastComponentUpdater, shouldLock,
+ inTransaction);
if (handleAAIArtifactsResponse.isRight()) {
return handleAAIArtifactsResponse;
}
- handleAAIArtifactsResponse = handleAAIArtifactsInDataModelByOperationType(component, aaiArtifatcsToCreate, ArtifactOperation.Create, lastComponentUpdater, shouldLock, inTransaction);
+ handleAAIArtifactsResponse = handleAAIArtifactsInDataModelByOperationType(component, aaiArtifatcsToCreate, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Create), lastComponentUpdater, shouldLock,
+ inTransaction);
if (handleAAIArtifactsResponse.isRight()) {
return handleAAIArtifactsResponse;
}
- return handleAAIArtifactsInDataModelByOperationType(component, aaiArtifatcsToUpdate, ArtifactOperation.Update, lastComponentUpdater, shouldLock, inTransaction);
+ return handleAAIArtifactsInDataModelByOperationType(component, aaiArtifatcsToUpdate, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Update), lastComponentUpdater, shouldLock, inTransaction);
}
private List<ArtifactDefinition> getAAIArtifatcsForUpdate(List<ArtifactDefinition> artifactsFromAAI, Component component) {
@@ -413,10 +524,10 @@ public class CsarUtils {
Set<String> componetDeploymentArtifactLables = component.getDeploymentArtifacts().keySet();
Set<String> componetInformationalArtifactLables = component.getArtifacts().keySet();
- List<ArtifactDefinition> artifactsAaiUpdate = artifactsFromAAI.stream().filter(e -> (componetDeploymentArtifactLables.contains(e.getArtifactLabel()) || componetInformationalArtifactLables.contains(e.getArtifactLabel())))
- .filter(e -> checkAaiForUpdate(component, e)).collect(Collectors.toList());
-
- return artifactsAaiUpdate;
+ return artifactsFromAAI.stream()
+ .filter(e -> componetDeploymentArtifactLables.contains(e.getArtifactLabel()) || componetInformationalArtifactLables.contains(e.getArtifactLabel()))
+ .filter(e -> checkAaiForUpdate(component, e))
+ .collect(Collectors.toList());
}
private boolean checkAaiForUpdate(Component component, ArtifactDefinition artifactDefinition) {
@@ -446,21 +557,27 @@ public class CsarUtils {
private List<ArtifactDefinition> getAAIArtifatcsForDelete(List<ArtifactDefinition> artifactsFromAAI, Component component) {
- Set<String> aaiLabels = artifactsFromAAI.stream().map(e -> e.getArtifactLabel()).collect(Collectors.toSet());
+ Set<String> aaiLabels = artifactsFromAAI.stream()
+ .map(ArtifactDefinition::getArtifactLabel)
+ .collect(Collectors.toSet());
- List<ArtifactDefinition> artifactsForDeleteDeployment = component.getDeploymentArtifacts().values().stream().
+ List<ArtifactDefinition> artifactsForDeleteDeployment = component.getDeploymentArtifacts().values().stream()
// Filter Out Artifacts that are not contained in artifacts returned
// from AAI API
- filter(e -> !aaiLabels.contains(e.getArtifactLabel())).collect(Collectors.toList());
+ .filter(e -> !aaiLabels.contains(e.getArtifactLabel()))
+ .collect(Collectors.toList());
- List<ArtifactDefinition> artifactsForDeleteInformational = component.getArtifacts().values().stream().
+ List<ArtifactDefinition> artifactsForDeleteInformational = component.getArtifacts().values().stream()
// Filter Out Artifacts that are not contained in artifacts returned
// from AAI API
- filter(e -> !aaiLabels.contains(e.getArtifactLabel())).collect(Collectors.toList());
+ .filter(e -> !aaiLabels.contains(e.getArtifactLabel()))
+ .collect(Collectors.toList());
artifactsForDeleteDeployment.addAll(artifactsForDeleteInformational);
- return artifactsForDeleteDeployment.stream().filter(e -> (e.getGenerated() != null && e.getGenerated().equals(Boolean.TRUE)) || (e.getGenerated() == null && e.getArtifactLabel().toLowerCase().startsWith("aai"))).collect(Collectors.toList());
+ return artifactsForDeleteDeployment.stream()
+ .filter(e -> (e.getGenerated() != null && e.getGenerated().equals(Boolean.TRUE)) || (e.getGenerated() == null && e.getArtifactLabel().toLowerCase().startsWith("aai")))
+ .collect(Collectors.toList());
}
private List<ArtifactDefinition> getAAIArtifatcsForCreate(List<ArtifactDefinition> artifactsFromAAI, Component component) {
@@ -470,10 +587,12 @@ public class CsarUtils {
// If the artifact label does not exist in the service -
// store the artifact (generate uuid and version, "generated" flag is TRUE)
- return artifactsFromAAI.stream().filter(e -> !componentDeploymentLabels.contains(e.getArtifactLabel()) && !componentInfoLabels.contains(e.getArtifactLabel())).collect(Collectors.toList());
+ return artifactsFromAAI.stream()
+ .filter(e -> !componentDeploymentLabels.contains(e.getArtifactLabel()) && !componentInfoLabels.contains(e.getArtifactLabel()))
+ .collect(Collectors.toList());
}
- private Either<ActionStatus, ResponseFormat> handleAAIArtifactsInDataModelByOperationType(Component component, List<ArtifactDefinition> generatedArtifactsDefinitions, ArtifactOperation operationType, User user, boolean shouldLock,
+ private Either<ActionStatus, ResponseFormat> handleAAIArtifactsInDataModelByOperationType(Component component, List<ArtifactDefinition> generatedArtifactsDefinitions, ArtifactOperationInfo operationType, User user, boolean shouldLock,
boolean inTransaction) {
String componentUniqueId = component.getUniqueId();
@@ -484,7 +603,7 @@ public class CsarUtils {
String dataMD5 = GeneralUtility.calculateMD5ByString(data);
String artifactUniqueId = null;
- if (operationType.equals(ArtifactOperation.Update) || operationType.equals(ArtifactOperation.Delete)) {
+ if ((operationType.getArtifactOperationEnum() == ArtifactOperationEnum.Update) || (operationType.getArtifactOperationEnum() == ArtifactOperationEnum.Delete)) {
String artifactLabel = artDef.getArtifactLabel();
ArtifactDefinition artifactDefinition = component.getDeploymentArtifacts().get(artifactLabel);
if (artifactDefinition != null) {
@@ -496,7 +615,7 @@ public class CsarUtils {
null, null, user, component, shouldLock, inTransaction);
if (validateAndHandleArtifact.isRight()) {
- if (ArtifactOperation.Create == operationType || ArtifactOperation.Update == operationType) {
+ if (ArtifactOperationEnum.Create == operationType.getArtifactOperationEnum() || ArtifactOperationEnum.Update == operationType.getArtifactOperationEnum()) {
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.AAI_ARTIFACT_GENERATION_FAILED, componentType.getValue(), component.getName(), validateAndHandleArtifact.right().value().toString());
Either.right(responseFormat);
@@ -522,7 +641,7 @@ public class CsarUtils {
// Normalizing the artifact label to match those stored in DB
String normalizeArtifactLabel = ValidationUtils.normalizeArtifactLabel(artifact.getLabel());
newEntry.setArtifactLabel(normalizeArtifactLabel);
- newEntry.setPayload(artifact.getPayload());
+ newEntry.setPayload(Base64.decodeBase64(artifact.getPayload()));
newEntry.setArtifactChecksum(artifact.getChecksum());
// Flag that set to true in case that the artifact is generated by AI&I generator
newEntry.setGenerated(Boolean.TRUE);
@@ -551,7 +670,6 @@ public class CsarUtils {
byte[] right = triple.getRight();
// The md5 calculated on the uncoded data
String md5Hex = DigestUtils.md5Hex(right);
- // byte[] payload = Base64.getEncoder().encode(right);
byte[] payload = Base64.encodeBase64(right);
String artifactVersion = artifactDefinition.getArtifactVersion();
@@ -567,9 +685,9 @@ public class CsarUtils {
return listOfArtifactsInput;
}
- private Either<byte[], ActionStatus> getEntryData(String esId, Component childComponent) {
+ private Either<byte[], ActionStatus> getEntryData(String cassandraId, Component childComponent) {
byte[] content;
- if (esId == null || esId.isEmpty()) {
+ if (cassandraId == null || cassandraId.isEmpty()) {
Either<ToscaRepresentation, ToscaError> exportRes = toscaExportUtils.exportComponent(childComponent);
if (exportRes.isRight()) {
log.debug("Failed to export tosca template for child component {} error {}", childComponent.getUniqueId(), exportRes.right().value());
@@ -577,7 +695,7 @@ public class CsarUtils {
}
content = exportRes.left().value().getMainYaml().getBytes();
} else {
- Either<byte[], ActionStatus> fromCassandra = getFromCassandra(esId);
+ Either<byte[], ActionStatus> fromCassandra = getFromCassandra(cassandraId);
if (fromCassandra.isRight()) {
return Either.right(fromCassandra.right().value());
} else {
@@ -586,13 +704,36 @@ public class CsarUtils {
}
return Either.left(content);
}
-
- private Either<byte[], ActionStatus> getFromCassandra(String esId) {
- Either<ESArtifactData, CassandraOperationStatus> artifactResponse = artifactCassandraDao.getArtifact(esId);
+
+ private Either<byte[], ActionStatus> getLatestSchemaFilesFromCassandra() {
+ Matcher matcher = Pattern.compile("(?!\\.)(\\d+(\\.\\d+)+)(?![\\d\\.])").matcher(SDC_VERSION);
+ matcher.find();
+ final String VERSION_FIRST_THREE_OCTATES = matcher.group(0);
+ Either<List<ESSdcSchemaFilesData>, ActionStatus> specificSchemaFiles = sdcSchemaFilesCassandraDao.getSpecificSchemaFiles(VERSION_FIRST_THREE_OCTATES, CONFORMANCE_LEVEL);
+
+ if(specificSchemaFiles.isRight()){
+ log.debug("Failed to get the schema files SDC-Version: {} Conformance-Level {}", VERSION_FIRST_THREE_OCTATES, CONFORMANCE_LEVEL);
+ return Either.right(specificSchemaFiles.right().value());
+ }
+
+ List<ESSdcSchemaFilesData> listOfSchemas = specificSchemaFiles.left().value();
+
+ if(listOfSchemas.isEmpty()){
+ log.debug("Failed to get the schema files SDC-Version: {} Conformance-Level {}", VERSION_FIRST_THREE_OCTATES, CONFORMANCE_LEVEL);
+ return Either.right(ActionStatus.GENERAL_ERROR);
+ }
+
+ ESSdcSchemaFilesData schemaFile = listOfSchemas.iterator().next();
+
+ return Either.left(schemaFile.getPayloadAsArray());
+ }
+
+ private Either<byte[], ActionStatus> getFromCassandra(String cassandraId) {
+ Either<ESArtifactData, CassandraOperationStatus> artifactResponse = artifactCassandraDao.getArtifact(cassandraId);
if (artifactResponse.isRight()) {
log.debug("In createCsar fetching of artifact from CS failed");
- log.debug("Failed to fetch from Cassandra by id {} error {} ", esId, artifactResponse.right().value());
+ log.debug("Failed to fetch from Cassandra by id {} error {} ", cassandraId, artifactResponse.right().value());
StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactResponse.right().value());
ActionStatus convertedFromStorageResponse = componentsUtils.convertFromStorageResponse(storageStatus);
@@ -603,14 +744,20 @@ public class CsarUtils {
}
}
-
- private String createToscaBlock0(String metaFileVersion, String csarVersion, String createdBy, String entryDef) {
- final String BLOCK_0_TEMPLATE = "TOSCA-Meta-File-Version: %s\nCSAR-Version: %s\nCreated-By: %s\nEntry-Definitions: Definitions/%s\n";
- String readyBlock = String.format(BLOCK_0_TEMPLATE, metaFileVersion, csarVersion, createdBy, entryDef);
+
+ private String createCsarBlock0(String metaFileVersion, String toscaConformanceLevel) {
+ final String BLOCK_0_TEMPLATE =
+ "SDC-TOSCA-Meta-File-Version: %s\nSDC-TOSCA-Definitions-Version: %s\n";
+ String readyBlock = String.format(BLOCK_0_TEMPLATE, metaFileVersion, toscaConformanceLevel);
return readyBlock;
}
+
+ private String createToscaBlock0(String metaFileVersion, String csarVersion, String createdBy, String entryDef) {
+ final String block0template = "TOSCA-Meta-File-Version: %s\nCSAR-Version: %s\nCreated-By: %s\nEntry-Definitions: Definitions/%s\n\nName: csar.meta\nContent-Type: text/plain\n";
+ return String.format(block0template, metaFileVersion, csarVersion, createdBy, entryDef);
+ }
- private Either<List<Artifact>, ResponseFormat> artifactGenerator(List<Artifact> artifactList, ArtifactType type, Component component) {
+ private Either<List<Artifact>, String> artifactGenerator(List<Artifact> artifactList, ArtifactType type, Component component) {
ArtifactGenerationServiceImpl artifactGenerationServiceImpl = new ArtifactGenerationServiceImpl();
ArtifactTypes artifactTypes = new ArtifactTypes();
@@ -627,23 +774,739 @@ public class CsarUtils {
artifactTypes.setArtifactTypes(artifactTypesList);
String configJson = gson.toJson(artifactTypes);
- GenerationData generatedArtifacts = artifactGenerationServiceImpl.generateArtifact(artifactList, configJson);
+ Map<String, String> additionalParams = new HashMap<>();
+ String version;
+
+ if (UUID_NORMATIVE_NEW_VERSION.matcher(component.getVersion()).matches() ) {
+ version = component.getVersion();
+ } else {
+ String[] versionParts = component.getVersion().split(LifecycleOperation.VERSION_DELIMETER_REGEXP);
+ Integer majorVersion = Integer.parseInt(versionParts[0]);
+
+ version = (majorVersion + 1) + LifecycleOperation.VERSION_DELIMETER + "0";
+ }
+
+ additionalParams.put(AdditionalParams.ServiceVersion.getName(), version);
+ GenerationData generatedArtifacts = artifactGenerationServiceImpl.generateArtifact(artifactList, configJson, additionalParams);
Map<String, List<String>> errorData = generatedArtifacts.getErrorData();
if (!errorData.isEmpty()) {
Set<String> keySet = errorData.keySet();
+ StringBuilder error = new StringBuilder();
for (String key : keySet) {
List<String> errorList = errorData.get(key);
log.debug("The Artifact Generator Failed - {} with following: {}", key, errorList);
+ error.append(key + errorList);
}
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.AAI_ARTIFACT_GENERATION_FAILED, component.getComponentType().getValue(), component.getName(), errorData.toString());
- return Either.right(responseFormat);
+ return Either.right(error.toString());
}
return Either.left(generatedArtifacts.getResultData());
}
+ /**
+ * Extracts artifacts of VFCs from CSAR
+ *
+ * @param csar
+ * @return Map of <String, List<ArtifactDefinition>> the contains Lists of artifacts according vfcToscaNamespace
+ */
+ public static Map<String, List<ArtifactDefinition>> extractVfcsArtifactsFromCsar(Map<String, byte[]> csar) {
+
+ Map<String, List<ArtifactDefinition>> artifacts = new HashMap<>();
+ if (csar != null) {
+ log.debug("************* Going to extract VFCs artifacts from Csar. ");
+ Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>();
+ csar.entrySet().stream()
+ // filter CSAR entry by node type artifact path
+ .filter(e -> Pattern.compile(VFC_NODE_TYPE_ARTIFACTS_PATH_PATTERN).matcher(e.getKey()).matches())
+ // extract ArtifactDefinition from CSAR entry for each entry with matching artifact path
+ .forEach(e -> addExtractedVfcArtifact(extractVfcArtifact(e, collectedWarningMessages), artifacts));
+ // add counter suffix to artifact labels
+ handleWarningMessages(collectedWarningMessages);
+
+ }
+ return artifacts;
+ }
+
+ /**
+ * Print warnings to log
+ *
+ * @param collectedWarningMessages
+ */
+ public static void handleWarningMessages(Map<String, Set<List<String>>> collectedWarningMessages) {
+ collectedWarningMessages.entrySet().stream()
+ // for each vfc
+ .forEach(e -> e.getValue().stream()
+ // add each warning message to log
+ .forEach(args -> log.warn(e.getKey(), args.toArray())));
+
+ }
+
+ private static void addExtractedVfcArtifact(ImmutablePair<String, ArtifactDefinition> extractedVfcArtifact, Map<String, List<ArtifactDefinition>> artifacts) {
+ if (extractedVfcArtifact != null) {
+ List<ArtifactDefinition> currArtifactsList;
+ String vfcToscaNamespace = extractedVfcArtifact.getKey();
+ if (artifacts.containsKey(vfcToscaNamespace)) {
+ currArtifactsList = artifacts.get(vfcToscaNamespace);
+ } else {
+ currArtifactsList = new ArrayList<>();
+ artifacts.put(vfcToscaNamespace, currArtifactsList);
+ }
+ currArtifactsList.add(extractedVfcArtifact.getValue());
+ }
+ }
+
+ private static ImmutablePair<String, ArtifactDefinition> extractVfcArtifact(Entry<String, byte[]> entry, Map<String, Set<List<String>>> collectedWarningMessages) {
+ ArtifactDefinition artifact;
+ String[] parsedCsarArtifactPath = entry.getKey().split("/");
+ Either<ArtifactGroupTypeEnum, Boolean> eitherArtifactGroupType = detectArtifactGroupType(parsedCsarArtifactPath[2].toUpperCase(), collectedWarningMessages);
+ if (eitherArtifactGroupType.isLeft()) {
+ artifact = buildArtifactDefinitionFromCsarArtifactPath(entry, collectedWarningMessages, parsedCsarArtifactPath, eitherArtifactGroupType.left().value());
+ } else {
+ return null;
+ }
+ return new ImmutablePair<>(parsedCsarArtifactPath[1], artifact);
+ }
+
+ private static Either<ArtifactGroupTypeEnum, Boolean> detectArtifactGroupType(String groupType, Map<String, Set<List<String>>> collectedWarningMessages) {
+ Either<ArtifactGroupTypeEnum, Boolean> result;
+ try {
+ ArtifactGroupTypeEnum artifactGroupType = ArtifactGroupTypeEnum.findType(groupType.toUpperCase());
+ if (artifactGroupType == null || (artifactGroupType != ArtifactGroupTypeEnum.INFORMATIONAL && artifactGroupType != ArtifactGroupTypeEnum.DEPLOYMENT)) {
+ String warningMessage = "Warning - unrecognized artifact group type {} was received.";
+ List<String> messageArguments = new ArrayList<>();
+ messageArguments.add(groupType);
+ if (!collectedWarningMessages.containsKey(warningMessage)) {
+ Set<List<String>> messageArgumentLists = new HashSet<>();
+ messageArgumentLists.add(messageArguments);
+ collectedWarningMessages.put(warningMessage, messageArgumentLists);
+ } else {
+ collectedWarningMessages.get(warningMessage).add(messageArguments);
+ }
+
+ result = Either.right(false);
+ } else {
+
+ result = Either.left(artifactGroupType);
+ }
+ } catch (Exception e) {
+ log.debug("detectArtifactGroupType failed with exception", e);
+ result = Either.right(false);
+ }
+ return result;
+ }
+
+ private static ArtifactDefinition buildArtifactDefinitionFromCsarArtifactPath(Entry<String, byte[]> entry, Map<String, Set<List<String>>> collectedWarningMessages, String[] parsedCsarArtifactPath, ArtifactGroupTypeEnum artifactGroupType) {
+ ArtifactDefinition artifact;
+ artifact = new ArtifactDefinition();
+ artifact.setArtifactGroupType(artifactGroupType);
+ artifact.setArtifactType(detectArtifactTypeVFC(artifactGroupType, parsedCsarArtifactPath[3], parsedCsarArtifactPath[1], collectedWarningMessages));
+ artifact.setArtifactName(ValidationUtils.normalizeFileName(parsedCsarArtifactPath[parsedCsarArtifactPath.length - 1]));
+ artifact.setPayloadData(Base64.encodeBase64String(entry.getValue()));
+ artifact.setArtifactDisplayName(artifact.getArtifactName().lastIndexOf('.') > 0 ? artifact.getArtifactName().substring(0, artifact.getArtifactName().lastIndexOf('.')) : artifact.getArtifactName());
+ artifact.setArtifactLabel(ValidationUtils.normalizeArtifactLabel(artifact.getArtifactName()));
+ artifact.setDescription(ARTIFACT_CREATED_FROM_CSAR);
+ artifact.setArtifactChecksum(GeneralUtility.calculateMD5ByByteArray(entry.getValue()));
+ return artifact;
+ }
+
+ public static final class NonMetaArtifactInfo {
+ private final String path;
+ private final String artifactName;
+ private final String displayName;
+ private final String artifactLabel;
+ private final ArtifactTypeEnum artifactType;
+ private final ArtifactGroupTypeEnum artifactGroupType;
+ private String payloadData;
+ private String artifactChecksum;
+ private String artifactUniqueId;
+
+ public NonMetaArtifactInfo(String artifactName, String path, ArtifactTypeEnum artifactType, ArtifactGroupTypeEnum artifactGroupType, byte[] payloadData, String artifactUniqueId) {
+ super();
+ this.path = path;
+ this.artifactName = ValidationUtils.normalizeFileName(artifactName);
+ this.artifactType = artifactType;
+ this.artifactGroupType = artifactGroupType;
+ final int pointIndex = artifactName.lastIndexOf('.');
+ if (pointIndex > 0) {
+ displayName = artifactName.substring(0, pointIndex);
+ } else {
+ displayName = artifactName;
+ }
+ this.artifactLabel = ValidationUtils.normalizeArtifactLabel(artifactName);
+ if (payloadData != null) {
+ this.payloadData = Base64.encodeBase64String(payloadData);
+ this.artifactChecksum = GeneralUtility.calculateMD5ByByteArray(payloadData);
+ }
+ this.artifactUniqueId = artifactUniqueId;
+ }
+
+ public String getPath() {
+ return path;
+ }
+
+ public String getArtifactName() {
+ return artifactName;
+ }
+
+ public ArtifactTypeEnum getArtifactType() {
+ return artifactType;
+ }
+
+ public String getDisplayName() {
+ return displayName;
+ }
+
+ public ArtifactGroupTypeEnum getArtifactGroupType() {
+ return artifactGroupType;
+ }
+
+ public String getArtifactLabel() {
+ return artifactLabel;
+ }
+
+ public String getPayloadData() {
+ return payloadData;
+ }
+
+ public String getArtifactChecksum() {
+ return artifactChecksum;
+ }
+
+ public String getArtifactUniqueId() {
+ return artifactUniqueId;
+ }
+
+ public void setArtifactUniqueId(String artifactUniqueId) {
+ this.artifactUniqueId = artifactUniqueId;
+ }
+
+ }
+
+ /**
+ * This method checks the artifact GroupType & Artifact Type. <br>
+ * if there is any problem warning messages are added to collectedWarningMessages
+ *
+ * @param artifactPath
+ * @param collectedWarningMessages
+ * @return
+ */
+ public static Either<NonMetaArtifactInfo, Boolean> validateNonMetaArtifact(String artifactPath, byte[] payloadData, Map<String, Set<List<String>>> collectedWarningMessages) {
+ Either<NonMetaArtifactInfo, Boolean> ret;
+ try {
+ String[] parsedArtifactPath = artifactPath.split("/");
+ // Validate Artifact Group Type
+ Either<ArtifactGroupTypeEnum, Boolean> eitherGroupType = detectArtifactGroupType(parsedArtifactPath[1], collectedWarningMessages);
+ if (eitherGroupType.isLeft()) {
+ final ArtifactGroupTypeEnum groupTypeEnum = eitherGroupType.left().value();
+
+ // Validate Artifact Type
+ String artifactType = parsedArtifactPath[2];
+ artifactType = detectArtifactTypeVF(groupTypeEnum, artifactType, collectedWarningMessages);
+
+ String artifactFileNameType = parsedArtifactPath[3];
+ ret = Either.left(new NonMetaArtifactInfo(artifactFileNameType, artifactPath, ArtifactTypeEnum.findType(artifactType), groupTypeEnum, payloadData, null));
+
+ } else {
+ ret = Either.right(eitherGroupType.right().value());
+ }
+ } catch (Exception e) {
+ log.debug("detectArtifactGroupType failed with exception", e);
+ ret = Either.right(false);
+ }
+ return ret;
+
+ }
+
+ private static String detectArtifactTypeVFC(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName, String parentVfName, Map<String, Set<List<String>>> collectedWarningMessages) {
+ String warningMessage = "Warning - artifact type {} that was provided for VFC {} is not recognized.";
+ return detectArtifactType(artifactGroupType, receivedTypeName, warningMessage, collectedWarningMessages, parentVfName);
+ }
+
+ private static String detectArtifactTypeVF(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName, Map<String, Set<List<String>>> collectedWarningMessages) {
+ String warningMessage = "Warning - artifact type {} that was provided for VF is not recognized.";
+ return detectArtifactType(artifactGroupType, receivedTypeName, warningMessage, collectedWarningMessages);
+ }
+
+ private static String detectArtifactType(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName, String warningMessage, Map<String, Set<List<String>>> collectedWarningMessages, String... arguments) {
+
+ ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(receivedTypeName);
+ Map<String, ArtifactTypeConfig> resourceValidTypeArtifacts = null;
+
+ if(artifactGroupType != null){
+ switch (artifactGroupType) {
+ case INFORMATIONAL:
+ resourceValidTypeArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration()
+ .getResourceInformationalArtifacts();
+ break;
+ case DEPLOYMENT:
+ resourceValidTypeArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration()
+ .getResourceDeploymentArtifacts();
+ break;
+ default:
+ break;
+ }
+ }
+
+ Set<String> validArtifactTypes = null;
+ if(resourceValidTypeArtifacts != null){
+ validArtifactTypes = resourceValidTypeArtifacts.keySet();
+ }
+
+ if (validArtifactTypes == null || artifactType == null || !validArtifactTypes.contains(artifactType.getType())) {
+ List<String> messageArguments = new ArrayList<>();
+ messageArguments.add(receivedTypeName);
+ messageArguments.addAll(Arrays.asList(arguments));
+ if (!collectedWarningMessages.containsKey(warningMessage)) {
+ Set<List<String>> messageArgumentLists = new HashSet<>();
+ messageArgumentLists.add(messageArguments);
+ collectedWarningMessages.put(warningMessage, messageArgumentLists);
+ } else {
+ collectedWarningMessages.get(warningMessage).add(messageArguments);
+ }
+ }
+
+ return artifactType == null ? ArtifactTypeEnum.OTHER.getType() : artifactType.getType();
+ }
+
+ private Either<ZipOutputStream, ResponseFormat> writeAllFilesToScar(Component mainComponent, CsarDefinition csarDefinition, ZipOutputStream zipstream, boolean isInCertificationRequest) throws IOException{
+ ComponentArtifacts componentArtifacts = csarDefinition.getComponentArtifacts();
+
+ Either<ZipOutputStream, ResponseFormat> writeComponentArtifactsToSpecifiedtPath = writeComponentArtifactsToSpecifiedtPath(mainComponent, componentArtifacts, zipstream, ARTIFACTS_PATH, isInCertificationRequest);
+
+ if(writeComponentArtifactsToSpecifiedtPath.isRight()){
+ return Either.right(writeComponentArtifactsToSpecifiedtPath.right().value());
+ }
+
+ ComponentTypeArtifacts mainTypeAndCIArtifacts = componentArtifacts.getMainTypeAndCIArtifacts();
+ writeComponentArtifactsToSpecifiedtPath = writeArtifactsInfoToSpecifiedtPath(mainComponent, mainTypeAndCIArtifacts.getComponentArtifacts(), zipstream, ARTIFACTS_PATH, isInCertificationRequest);
+
+ if(writeComponentArtifactsToSpecifiedtPath.isRight()){
+ return Either.right(writeComponentArtifactsToSpecifiedtPath.right().value());
+ }
+
+ Map<String, ArtifactsInfo> componentInstancesArtifacts = mainTypeAndCIArtifacts.getComponentInstancesArtifacts();
+ Set<String> keySet = componentInstancesArtifacts.keySet();
+
+ String currentPath = ARTIFACTS_PATH + RESOURCES_PATH;
+ for (String keyAssetName : keySet) {
+ ArtifactsInfo artifactsInfo = componentInstancesArtifacts.get(keyAssetName);
+ String pathWithAssetName = currentPath + keyAssetName + "/";
+ writeComponentArtifactsToSpecifiedtPath = writeArtifactsInfoToSpecifiedtPath(mainComponent, artifactsInfo, zipstream, pathWithAssetName, isInCertificationRequest);
+
+ if(writeComponentArtifactsToSpecifiedtPath.isRight()){
+ return Either.right(writeComponentArtifactsToSpecifiedtPath.right().value());
+ }
+ }
+
+ return Either.left(zipstream);
+ }
+
+ private Either<ZipOutputStream, ResponseFormat> writeComponentArtifactsToSpecifiedtPath(Component mainComponent, ComponentArtifacts componentArtifacts, ZipOutputStream zipstream,
+ String currentPath, boolean isInCertificationRequest) throws IOException {
+ Map<String, ComponentTypeArtifacts> componentTypeArtifacts = componentArtifacts.getComponentTypeArtifacts();
+ //Keys are defined:
+ //<Inner Asset TOSCA name (e.g. VFC name)> folder name: <Inner Asset TOSCA name (e.g. VFC name)>_v<version>.
+ //E.g. "org.openecomp.resource.vf.vipr_atm_v1.0"
+ Set<String> componentTypeArtifactsKeys = componentTypeArtifacts.keySet();
+ for (String keyAssetName : componentTypeArtifactsKeys) {
+ ComponentTypeArtifacts componentInstanceArtifacts = componentTypeArtifacts.get(keyAssetName);
+ ArtifactsInfo componentArtifacts2 = componentInstanceArtifacts.getComponentArtifacts();
+ String pathWithAssetName = currentPath + keyAssetName + "/";
+ Either<ZipOutputStream, ResponseFormat> writeArtifactsInfoToSpecifiedtPath = writeArtifactsInfoToSpecifiedtPath(mainComponent, componentArtifacts2, zipstream, pathWithAssetName, isInCertificationRequest);
+
+ if(writeArtifactsInfoToSpecifiedtPath.isRight()){
+ return writeArtifactsInfoToSpecifiedtPath;
+ }
+ }
+
+ return Either.left(zipstream);
+ }
+
+ private Either<ZipOutputStream, ResponseFormat> writeArtifactsInfoToSpecifiedtPath(Component mainComponent, ArtifactsInfo currArtifactsInfo, ZipOutputStream zip, String path, boolean isInCertificationRequest) throws IOException {
+ Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> artifactsInfo = currArtifactsInfo
+ .getArtifactsInfo();
+ Set<ArtifactGroupTypeEnum> groupTypeEnumKeySet = artifactsInfo.keySet();
+
+ for (ArtifactGroupTypeEnum artifactGroupTypeEnum : groupTypeEnumKeySet) {
+ String groupTypeFolder = path + WordUtils.capitalizeFully(artifactGroupTypeEnum.getType()) + "/";
+
+ Map<ArtifactTypeEnum, List<ArtifactDefinition>> artifactTypesMap = artifactsInfo.get(artifactGroupTypeEnum);
+ Set<ArtifactTypeEnum> artifactTypeEnumKeySet = artifactTypesMap.keySet();
+
+ for (ArtifactTypeEnum artifactTypeEnum : artifactTypeEnumKeySet) {
+ List<ArtifactDefinition> artifactDefinitionList = artifactTypesMap.get(artifactTypeEnum);
+ String artifactTypeFolder = groupTypeFolder + artifactTypeEnum.toString() + "/";
+
+ Either<ZipOutputStream, ResponseFormat> writeArtifactDefinition = writeArtifactDefinition(mainComponent, zip, artifactDefinitionList, artifactTypeFolder, isInCertificationRequest);
+
+ if(writeArtifactDefinition.isRight()){
+ return writeArtifactDefinition;
+ }
+ }
+ }
+
+ return Either.left(zip);
+ }
+
+ private Either<ZipOutputStream, ResponseFormat> writeArtifactDefinition(Component mainComponent, ZipOutputStream zip, List<ArtifactDefinition> artifactDefinitionList,
+ String artifactPathAndFolder, boolean isInCertificationRequest) throws IOException {
+
+ ComponentTypeEnum componentType = mainComponent.getComponentType();
+ String heatEnvType = ArtifactTypeEnum.HEAT_ENV.getType();
+
+ for (ArtifactDefinition artifactDefinition : artifactDefinitionList) {
+ if (!isInCertificationRequest && componentType == ComponentTypeEnum.SERVICE
+ && artifactDefinition.getArtifactType().equals(heatEnvType)){
+ continue;
+ }
+
+ String esId = artifactDefinition.getEsId();
+ byte[] payloadData = artifactDefinition.getPayloadData();
+ String artifactFileName = artifactDefinition.getArtifactName();
+
+ if (payloadData == null) {
+ Either<byte[], ActionStatus> fromCassandra = getFromCassandra(esId);
+
+ if (fromCassandra.isRight()) {
+ log.debug("Failed to get {} payload from DB reason: {}", artifactFileName, fromCassandra.right().value());
+ continue;
+ }
+ payloadData = fromCassandra.left().value();
+ }
+ zip.putNextEntry(new ZipEntry(artifactPathAndFolder + artifactFileName));
+ zip.write(payloadData);
+ }
+
+ return Either.left(zip);
+ }
+
+ /************************************ Artifacts Structure ******************************************************************/
+ /**
+ * The artifacts Definition saved by their structure
+ */
+ private class ArtifactsInfo {
+ //Key is the type of artifacts(Informational/Deployment)
+ //Value is a map between an artifact type and a list of all artifacts of this type
+ private Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> artifactsInfoField;
+
+ public ArtifactsInfo() {
+ this.artifactsInfoField = new EnumMap<>(ArtifactGroupTypeEnum.class);
+ }
+
+ public Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> getArtifactsInfo() {
+ return artifactsInfoField;
+ }
+
+ public List<ArtifactDefinition> getFlatArtifactsListByType(ArtifactTypeEnum artifactType){
+ List<ArtifactDefinition> artifacts = new ArrayList<>();
+ for (List<ArtifactDefinition> artifactsByType:artifactsInfoField.get(artifactType).values()){
+ artifacts.addAll(artifactsByType);
+ }
+ return artifacts;
+ }
+
+ public void addArtifactsToGroup(ArtifactGroupTypeEnum artifactGroup,Map<ArtifactTypeEnum, List<ArtifactDefinition>> artifactsDefinition){
+ artifactsInfoField.put(artifactGroup, artifactsDefinition);
+ }
+
+ public boolean isEmpty() {
+ return artifactsInfoField.isEmpty();
+ }
+
+ }
+
+ /**
+ * The artifacts of the component and of all its composed instances
+ *
+ */
+ private class ComponentTypeArtifacts {
+ private ArtifactsInfo componentArtifacts; //component artifacts (describes the Informational Deployment folders)
+ private Map<String, ArtifactsInfo> componentInstancesArtifacts; //artifacts of the composed instances mapped by the resourceInstance normalized name (describes the Resources folder)
+
+ public ComponentTypeArtifacts() {
+ componentArtifacts = new ArtifactsInfo();
+ componentInstancesArtifacts = new HashMap<>();
+ }
+
+ public ArtifactsInfo getComponentArtifacts() {
+ return componentArtifacts;
+ }
+ public void setComponentArtifacts(ArtifactsInfo artifactsInfo) {
+ this.componentArtifacts = artifactsInfo;
+ }
+ public Map<String, ArtifactsInfo> getComponentInstancesArtifacts() {
+ return componentInstancesArtifacts;
+ }
+ public void setComponentInstancesArtifacts(Map<String, ArtifactsInfo> componentInstancesArtifacts) {
+ this.componentInstancesArtifacts = componentInstancesArtifacts;
+ }
+
+ public void addComponentInstancesArtifacts(String normalizedName, ArtifactsInfo artifactsInfo) {
+ componentInstancesArtifacts.put(normalizedName, artifactsInfo);
+ }
+
+ }
+
+ private class ComponentArtifacts {
+ //artifacts of the component and CI's artifacts contained in it's composition (represents Informational, Deployment & Resource folders of main component)
+ private ComponentTypeArtifacts mainTypeAndCIArtifacts;
+ //artifacts of all component types mapped by their tosca name
+ private Map<String, ComponentTypeArtifacts> componentTypeArtifacts;
+
+ public ComponentArtifacts(){
+ mainTypeAndCIArtifacts = new ComponentTypeArtifacts();
+ componentTypeArtifacts = new HashMap<>();
+ }
+
+ public ComponentTypeArtifacts getMainTypeAndCIArtifacts() {
+ return mainTypeAndCIArtifacts;
+ }
+
+ public void setMainTypeAndCIArtifacts(ComponentTypeArtifacts componentInstanceArtifacts) {
+ this.mainTypeAndCIArtifacts = componentInstanceArtifacts;
+ }
+
+ public Map<String, ComponentTypeArtifacts> getComponentTypeArtifacts() {
+ return componentTypeArtifacts;
+ }
+
+ public void setComponentTypeArtifacts(Map<String, ComponentTypeArtifacts> componentTypeArtifacts) {
+ this.componentTypeArtifacts = componentTypeArtifacts;
+ }
+ }
+
+ private class CsarDefinition {
+ private ComponentArtifacts componentArtifacts;
+
+ // add list of tosca artifacts and meta describes CSAR zip root
+
+ public CsarDefinition(ComponentArtifacts componentArtifacts) {
+ this.componentArtifacts = componentArtifacts;
+ }
+
+ public ComponentArtifacts getComponentArtifacts() {
+ return componentArtifacts;
+ }
+ }
+
+ /************************************ Artifacts Structure END******************************************************************/
+
+ private Either<CsarDefinition,ResponseFormat> collectComponentCsarDefinition(Component component){
+ ComponentArtifacts componentArtifacts = new ComponentArtifacts();
+ Component updatedComponent = component;
+
+ //get service to receive the AII artifacts uploaded to the service
+ if (updatedComponent.getComponentType() == ComponentTypeEnum.SERVICE) {
+ Either<Service, StorageOperationStatus> getServiceResponse = toscaOperationFacade.getToscaElement(updatedComponent.getUniqueId());
+
+ if(getServiceResponse.isRight()){
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getServiceResponse.right().value());
+ return Either.right(componentsUtils.getResponseFormat(actionStatus));
+ }
+
+ updatedComponent = getServiceResponse.left().value();
+ }
+
+ //find the artifacts of the main component, it would have its composed instances artifacts in a separate folder
+ ComponentTypeArtifacts componentInstanceArtifacts = new ComponentTypeArtifacts();
+ ArtifactsInfo artifactsInfo = collectComponentArtifacts(updatedComponent);
+ componentInstanceArtifacts.setComponentArtifacts(artifactsInfo);
+ componentArtifacts.setMainTypeAndCIArtifacts(componentInstanceArtifacts);
+
+ Map<String,ComponentTypeArtifacts> resourceTypeArtifacts = componentArtifacts.getComponentTypeArtifacts(); //artifacts mapped by the component type(tosca name+version)
+ //get the component instances
+ List<ComponentInstance> componentInstances = updatedComponent.getComponentInstances();
+ if (componentInstances!=null){
+ for (ComponentInstance componentInstance:componentInstances){
+ //call recursive to find artifacts for all the path
+ Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts = collectComponentInstanceArtifacts(
+ updatedComponent, componentInstance, resourceTypeArtifacts, componentInstanceArtifacts);
+ if (collectComponentInstanceArtifacts.isRight()){
+ return Either.right(collectComponentInstanceArtifacts.right().value());
+ }
+ }
+ }
+
+ if(log.isDebugEnabled()){
+ printResult(componentArtifacts,updatedComponent.getName());
+ }
+
+ return Either.left(new CsarDefinition(componentArtifacts));
+ }
+
+ private void printResult(ComponentArtifacts componentArtifacts, String name) {
+ StringBuilder result = new StringBuilder();
+ result.append("Artifacts of main component " + name + "\n");
+ ComponentTypeArtifacts componentInstanceArtifacts = componentArtifacts.getMainTypeAndCIArtifacts();
+ printArtifacts(componentInstanceArtifacts);
+ result.append("Type Artifacts\n");
+ for (Map.Entry<String, ComponentTypeArtifacts> typeArtifacts:componentArtifacts.getComponentTypeArtifacts().entrySet()){
+ result.append("Folder " + typeArtifacts.getKey() + "\n");
+ result.append(printArtifacts(typeArtifacts.getValue()));
+ }
+
+ if(log.isDebugEnabled()){
+ log.debug(result.toString());
+ }
+ }
+
+ private String printArtifacts(ComponentTypeArtifacts componentInstanceArtifacts) {
+ StringBuilder result = new StringBuilder();
+ ArtifactsInfo artifactsInfo = componentInstanceArtifacts.getComponentArtifacts();
+ Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> componetArtifacts = artifactsInfo.getArtifactsInfo();
+ printArtifacts(componetArtifacts);
+ result = result.append("Resources\n");
+ for (Map.Entry<String, ArtifactsInfo> resourceInstance:componentInstanceArtifacts.getComponentInstancesArtifacts().entrySet()){
+ result.append("Folder" + resourceInstance.getKey() + "\n");
+ result.append(printArtifacts(resourceInstance.getValue().getArtifactsInfo()));
+ }
+
+ return result.toString();
+ }
+
+ private String printArtifacts(Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> componetArtifacts) {
+ StringBuilder result = new StringBuilder();
+ for (Map.Entry<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> artifactGroup:componetArtifacts.entrySet()){
+ result.append(" " + artifactGroup.getKey().getType());
+ for (Map.Entry<ArtifactTypeEnum, List<ArtifactDefinition>> groupArtifacts:artifactGroup.getValue().entrySet()){
+ result.append(" " + groupArtifacts.getKey().getType());
+ for (ArtifactDefinition artifact:groupArtifacts.getValue()){
+ result.append(" " + artifact.getArtifactDisplayName());
+ }
+ }
+ }
+
+ return result.toString();
+ }
+
+ private ComponentTypeArtifacts collectComponentTypeArtifacts(Map<String, ComponentTypeArtifacts> resourcesArtifacts, ComponentInstance componentInstance,
+ Resource fetchedComponent) {
+ String toscaComponentName = componentInstance.getToscaComponentName() + "_v" + componentInstance.getComponentVersion();
+
+ ComponentTypeArtifacts componentArtifactsInfo = resourcesArtifacts.get(toscaComponentName);
+ //if there are no artifacts for this component type we need to fetch and build them
+ if (componentArtifactsInfo==null){
+ ArtifactsInfo componentArtifacts = collectComponentArtifacts(fetchedComponent);
+ componentArtifactsInfo = new ComponentTypeArtifacts();
+ if (!componentArtifacts.isEmpty()){
+ componentArtifactsInfo.setComponentArtifacts(componentArtifacts);
+ resourcesArtifacts.put(toscaComponentName, componentArtifactsInfo);
+ }
+ }
+ return componentArtifactsInfo;
+ }
+
+ private Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts(Component parentComponent,ComponentInstance componentInstance,
+ Map<String, ComponentTypeArtifacts> resourcesTypeArtifacts,ComponentTypeArtifacts instanceArtifactsLocation) {
+ //1. get the component instance component
+ String componentUid = componentInstance.getComponentUid();
+ Either<Resource, StorageOperationStatus> resource = toscaOperationFacade.getToscaElement(componentUid);
+ if (resource.isRight()) {
+ log.error("Failed to fetch resource with id {} for instance {}",componentUid, parentComponent.getUUID());
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.ASSET_NOT_FOUND_DURING_CSAR_CREATION,
+ parentComponent.getComponentType().getValue(), parentComponent.getUUID(),
+ componentInstance.getOriginType().getComponentType().getValue(), componentUid));
+ }
+ Resource fetchedComponent = resource.left().value();
+
+ //2. fill the artifacts for the current component parent type
+ ComponentTypeArtifacts componentParentArtifacts = collectComponentTypeArtifacts(resourcesTypeArtifacts, componentInstance, fetchedComponent);
+
+ //3. find the artifacts specific to the instance
+ Map<ArtifactTypeEnum, List<ArtifactDefinition>> componentInstanceSpecificInformationalArtifacts =
+ getComponentInstanceSpecificArtifacts(componentInstance.getArtifacts(),
+ componentParentArtifacts.getComponentArtifacts().getArtifactsInfo(), ArtifactGroupTypeEnum.INFORMATIONAL);
+ Map<ArtifactTypeEnum, List<ArtifactDefinition>> componentInstanceSpecificDeploymentArtifacts =
+ getComponentInstanceSpecificArtifacts(componentInstance.getDeploymentArtifacts(),
+ componentParentArtifacts.getComponentArtifacts().getArtifactsInfo(), ArtifactGroupTypeEnum.DEPLOYMENT);
+
+ //4. add the instances artifacts to the component type
+ ArtifactsInfo artifactsInfo = new ArtifactsInfo();
+ if (!componentInstanceSpecificInformationalArtifacts.isEmpty()){
+ artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.INFORMATIONAL, componentInstanceSpecificInformationalArtifacts);
+ }
+ if (!componentInstanceSpecificDeploymentArtifacts.isEmpty()){
+ artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.DEPLOYMENT, componentInstanceSpecificDeploymentArtifacts);
+ }
+ if (!artifactsInfo.isEmpty()){
+ instanceArtifactsLocation.addComponentInstancesArtifacts(componentInstance.getNormalizedName(), artifactsInfo);
+ }
+
+ //5. do the same for all the component instances
+ List<ComponentInstance> componentInstances = fetchedComponent.getComponentInstances();
+ if (componentInstances!=null){
+ for (ComponentInstance childComponentInstance:componentInstances){
+ Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts = collectComponentInstanceArtifacts(
+ fetchedComponent, childComponentInstance, resourcesTypeArtifacts, componentParentArtifacts);
+ if (collectComponentInstanceArtifacts.isRight()){
+ return collectComponentInstanceArtifacts;
+ }
+ }
+ }
+
+ return Either.left(true);
+ }
+
+ private Map<ArtifactTypeEnum, List<ArtifactDefinition>> getComponentInstanceSpecificArtifacts(Map<String, ArtifactDefinition> componentArtifacts,
+ Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> componentTypeArtifacts, ArtifactGroupTypeEnum artifactGroupTypeEnum) {
+ Map<ArtifactTypeEnum, List<ArtifactDefinition>> parentArtifacts = componentTypeArtifacts.get(artifactGroupTypeEnum); //the artfiacts of the component itself and not the instance
+
+ Map<ArtifactTypeEnum, List<ArtifactDefinition>> artifactsByTypeOfComponentInstance = new EnumMap<>(ArtifactTypeEnum.class);
+ if (componentArtifacts!=null){
+ for (ArtifactDefinition artifact:componentArtifacts.values()){
+ ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifact.getArtifactType());
+ List<ArtifactDefinition> parentArtifactsByType = null;
+ if (parentArtifacts!=null){
+ parentArtifactsByType = parentArtifacts.get(artifactType);
+ }
+ //the artifact is of instance
+ if (parentArtifactsByType == null || !parentArtifactsByType.contains(artifact)){
+ List<ArtifactDefinition> typeArtifacts = artifactsByTypeOfComponentInstance.get(artifactType);
+ if (typeArtifacts == null){
+ typeArtifacts = new ArrayList<>();
+ artifactsByTypeOfComponentInstance.put(artifactType, typeArtifacts);
+ }
+ typeArtifacts.add(artifact);
+ }
+ }
+ }
+
+ return artifactsByTypeOfComponentInstance;
+ }
+
+ private ArtifactsInfo collectComponentArtifacts(Component component) {
+ Map<String, ArtifactDefinition> informationalArtifacts = component.getArtifacts();
+ Map<ArtifactTypeEnum, List<ArtifactDefinition>> informationalArtifactsByType = collectGroupArtifacts(informationalArtifacts);
+ Map<String, ArtifactDefinition> deploymentArtifacts = component.getDeploymentArtifacts();
+ Map<ArtifactTypeEnum, List<ArtifactDefinition>> deploymentArtifactsByType = collectGroupArtifacts(deploymentArtifacts);
+ ArtifactsInfo artifactsInfo = new ArtifactsInfo();
+ if (!informationalArtifactsByType.isEmpty()){
+ artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.INFORMATIONAL, informationalArtifactsByType);
+ }
+ if (!deploymentArtifactsByType.isEmpty() ){
+ artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.DEPLOYMENT, deploymentArtifactsByType);
+ }
+
+ return artifactsInfo;
+ }
+
+ private Map<ArtifactTypeEnum, List<ArtifactDefinition>> collectGroupArtifacts(Map<String, ArtifactDefinition> componentArtifacts) {
+ Map<ArtifactTypeEnum, List<ArtifactDefinition>> artifactsByType = new EnumMap<>(ArtifactTypeEnum.class);
+ for (ArtifactDefinition artifact:componentArtifacts.values()){
+ if (artifact.getArtifactUUID()!=null){
+ ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifact.getArtifactType());
+ List<ArtifactDefinition> typeArtifacts = artifactsByType.get(artifactType);
+ if (typeArtifacts==null){
+ typeArtifacts = new ArrayList<>();
+ artifactsByType.put(artifactType, typeArtifacts);
+ }
+ typeArtifacts.add(artifact);
+ }
+ }
+ return artifactsByType;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/PropertyConvertor.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/PropertyConvertor.java
index 544b85361d..af3b73dc97 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/PropertyConvertor.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/PropertyConvertor.java
@@ -71,11 +71,10 @@ public class PropertyConvertor {
Map<String, ToscaProperty> properties = new HashMap<>();
// take only the properties of this resource
- props.stream().filter(p -> component.getUniqueId().equals(p.getParentUniqueId())).forEach(property -> {
+ props.stream().filter(p -> p.getOwnerId() == null || p.getOwnerId().equals(component.getUniqueId())).forEach(property -> {
ToscaProperty prop = convertProperty(dataTypes, property, false);
properties.put(property.getName(), prop);
-
});
if (!properties.isEmpty()) {
toscaNodeType.setProperties(properties);
@@ -172,7 +171,7 @@ public class PropertyConvertor {
if (innerConverter != null) {
convertedValue = innerConverter.convertToToscaValue(value, innerType, dataTypes);
} else {
- convertedValue = mapConverterInst.convertDataTypeToToscaMap(innerType, dataTypes, innerConverter, isScalar, jsonElement);
+ convertedValue = mapConverterInst.convertDataTypeToToscaObject(innerType, dataTypes, innerConverter, isScalar, jsonElement);
}
}
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaExportHandler.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaExportHandler.java
index 1bf940ffc0..072861ba3a 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaExportHandler.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaExportHandler.java
@@ -25,36 +25,44 @@ import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashSet;
-import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
+import java.util.function.Supplier;
import java.util.stream.Collectors;
+import org.apache.commons.collections.CollectionUtils;
+import org.apache.commons.collections.MapUtils;
+import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.ImmutableTriple;
import org.apache.commons.lang3.tuple.Triple;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
-import org.openecomp.sdc.be.datamodel.utils.ArtifactUtils;
import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.model.ArtifactDefinition;
import org.openecomp.sdc.be.model.Component;
import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.ComponentInstanceInput;
import org.openecomp.sdc.be.model.ComponentInstanceProperty;
import org.openecomp.sdc.be.model.DataTypeDefinition;
import org.openecomp.sdc.be.model.GroupDefinition;
+import org.openecomp.sdc.be.model.GroupInstance;
import org.openecomp.sdc.be.model.GroupProperty;
import org.openecomp.sdc.be.model.InputDefinition;
+import org.openecomp.sdc.be.model.PropertyDefinition;
import org.openecomp.sdc.be.model.RequirementAndRelationshipPair;
import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
import org.openecomp.sdc.be.model.RequirementDefinition;
import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.Service;
import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
import org.openecomp.sdc.be.model.category.CategoryDefinition;
-import org.openecomp.sdc.be.model.operations.api.IResourceOperation;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.be.model.tosca.converters.ToscaValueBaseConverter;
import org.openecomp.sdc.be.tosca.model.IToscaMetadata;
import org.openecomp.sdc.be.tosca.model.SubstitutionMapping;
import org.openecomp.sdc.be.tosca.model.ToscaCapability;
@@ -67,7 +75,6 @@ import org.openecomp.sdc.be.tosca.model.ToscaTemplate;
import org.openecomp.sdc.be.tosca.model.ToscaTemplateRequirement;
import org.openecomp.sdc.be.tosca.model.ToscaTopolgyTemplate;
import org.openecomp.sdc.be.tosca.model.VfModuleToscaMetadata;
-import org.openecomp.sdc.common.api.ArtifactTypeEnum;
import org.openecomp.sdc.common.api.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -94,31 +101,56 @@ public class ToscaExportHandler {
private ApplicationDataTypeCache dataTypeCache;
@Autowired
- private IResourceOperation resourceOperation;
+ private ToscaOperationFacade toscaOperationFacade;
private CapabiltyRequirementConvertor capabiltyRequirementConvertor = CapabiltyRequirementConvertor.getInstance();
private PropertyConvertor propertyConvertor = PropertyConvertor.getInstance();
+
private static Logger log = LoggerFactory.getLogger(ToscaExportHandler.class.getName());
public static final String TOSCA_VERSION = "tosca_simple_yaml_1_0";
public static final String SERVICE_NODE_TYPE_PREFIX = "org.openecomp.service.";
public static final String IMPORTS_FILE_KEY = "file";
public static final String TOSCA_TEMPLATE_NAME = "-template.yml";
+ public static final String TOSCA_INTERFACE_NAME = "-interface.yml";
public static final String ASSET_TOSCA_TEMPLATE = "assettoscatemplate";
public static final String VF_MODULE_TYPE_KEY = "vf_module_type";
public static final String VF_MODULE_DESC_KEY = "vf_module_description";
public static final String VOLUME_GROUP_KEY = "volume_group";
public static final String VF_MODULE_TYPE_BASE = "Base";
public static final String VF_MODULE_TYPE_EXPANSION = "Expansion";
-
+ public static final List<Map<String, Map<String, String>>> DEFAULT_IMPORTS = ConfigurationManager.getConfigurationManager().getConfiguration().getDefaultImports();
+
+
+
public Either<ToscaRepresentation, ToscaError> exportComponent(Component component) {
Either<ToscaTemplate, ToscaError> toscaTemplateRes = convertToToscaTemplate(component);
if (toscaTemplateRes.isRight()) {
return Either.right(toscaTemplateRes.right().value());
}
+
+ ToscaTemplate toscaTemplate = toscaTemplateRes.left().value();
+ ToscaRepresentation toscaRepresentation = this.createToscaRepresentation(toscaTemplate);
+ return Either.left(toscaRepresentation);
+ }
+ public Either<ToscaRepresentation, ToscaError> exportComponentInterface(Component component) {
+ ToscaTemplate toscaTemplate = new ToscaTemplate(TOSCA_VERSION);
+ toscaTemplate.setImports(new ArrayList<>(DEFAULT_IMPORTS));
+ Map<String, ToscaNodeType> nodeTypes = new HashMap<>();
+ Either<ToscaTemplate, ToscaError> toscaTemplateRes = convertInterfaceNodeType(component, toscaTemplate, nodeTypes);
+ if (toscaTemplateRes.isRight()) {
+ return Either.right(toscaTemplateRes.right().value());
+ }
+
+ toscaTemplate = toscaTemplateRes.left().value();
+ ToscaRepresentation toscaRepresentation = this.createToscaRepresentation(toscaTemplate);
+ return Either.left(toscaRepresentation);
+ }
+
+ public ToscaRepresentation createToscaRepresentation(ToscaTemplate toscaTemplate) {
CustomRepresenter representer = new CustomRepresenter();
DumperOptions options = new DumperOptions();
options.setAllowReadOnlyProperties(false);
@@ -127,7 +159,6 @@ public class ToscaExportHandler {
options.setDefaultFlowStyle(FlowStyle.FLOW);
options.setCanonical(false);
- ToscaTemplate toscaTemplate = toscaTemplateRes.left().value();
representer.addClassTag(toscaTemplate.getClass(), Tag.MAP);
representer.setPropertyUtils(new UnsortedPropertyUtils());
@@ -143,13 +174,14 @@ public class ToscaExportHandler {
ToscaRepresentation toscaRepresentation = new ToscaRepresentation();
toscaRepresentation.setMainYaml(sb.toString());
toscaRepresentation.setDependencies(toscaTemplate.getDependencies());
-
- return Either.left(toscaRepresentation);
+
+ return toscaRepresentation;
}
-
+
public Either<ToscaTemplate, ToscaError> getDependencies(Component component) {
ToscaTemplate toscaTemplate = new ToscaTemplate(null);
- Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> fillImports = fillImports(component, toscaTemplate);
+ Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> fillImports = fillImports(component,
+ toscaTemplate);
if (fillImports.isRight()) {
return Either.right(fillImports.right().value());
}
@@ -157,17 +189,17 @@ public class ToscaExportHandler {
}
private Either<ToscaTemplate, ToscaError> convertToToscaTemplate(Component component) {
- log.debug("start tosca export for {}", component.getUniqueId());
+ log.trace("start tosca export for {}", component.getUniqueId());
ToscaTemplate toscaTemplate = new ToscaTemplate(TOSCA_VERSION);
- toscaTemplate.setMetadata(convertMetadata(component, false));
-
- Map<String, ToscaNodeType> node_types = new HashMap<>();
- if (ToscaUtils.isNodeType(component)) {
- log.debug("convert component as node type");
- return convertNodeType(component, toscaTemplate, node_types);
+ toscaTemplate.setMetadata(convertMetadata(component));
+ toscaTemplate.setImports(new ArrayList<>(DEFAULT_IMPORTS));
+ Map<String, ToscaNodeType> nodeTypes = new HashMap<>();
+ if (ToscaUtils.isAtomicType(component)) {
+ log.trace("convert component as node type");
+ return convertNodeType(component, toscaTemplate, nodeTypes);
} else {
- log.debug("convert component as topology template");
+ log.trace("convert component as topology template");
return convertToscaTemplate(component, toscaTemplate);
}
@@ -175,7 +207,8 @@ public class ToscaExportHandler {
private Either<ToscaTemplate, ToscaError> convertToscaTemplate(Component component, ToscaTemplate toscaNode) {
- Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> importsRes = fillImports(component, toscaNode);
+ Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> importsRes = fillImports(component,
+ toscaNode);
if (importsRes.isRight()) {
return Either.right(importsRes.right().value());
}
@@ -189,47 +222,50 @@ public class ToscaExportHandler {
}
Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
- ToscaTopolgyTemplate topology_template = new ToscaTopolgyTemplate();
+ ToscaTopolgyTemplate topologyTemplate = new ToscaTopolgyTemplate();
- Either<ToscaTopolgyTemplate, ToscaError> inputs = fillInputs(component, topology_template, dataTypes);
+ Either<ToscaTopolgyTemplate, ToscaError> inputs = fillInputs(component, topologyTemplate, dataTypes);
if (inputs.isRight()) {
return Either.right(inputs.right().value());
}
- topology_template = inputs.left().value();
+ topologyTemplate = inputs.left().value();
List<ComponentInstance> componentInstances = component.getComponentInstances();
- Map<String, List<ComponentInstanceProperty>> componentInstancesProperties = component.getComponentInstancesProperties();
+ Map<String, List<ComponentInstanceProperty>> componentInstancesProperties = component
+ .getComponentInstancesProperties();
List<GroupDefinition> groups = component.getGroups();
if (componentInstances != null && !componentInstances.isEmpty()) {
- Either<Map<String, ToscaNodeTemplate>, ToscaError> node_templates = convertNodeTemplates(component, componentInstances, componentInstancesProperties, componentCache, dataTypes);
- if (node_templates.isRight()) {
- return Either.right(node_templates.right().value());
+ Either<Map<String, ToscaNodeTemplate>, ToscaError> nodeTemplates = convertNodeTemplates(component,
+ componentInstances, componentInstancesProperties, componentCache, dataTypes, topologyTemplate);
+ if (nodeTemplates.isRight()) {
+ return Either.right(nodeTemplates.right().value());
}
log.debug("node templates converted");
- topology_template.setNode_templates(node_templates.left().value());
+ topologyTemplate.setNode_templates(nodeTemplates.left().value());
}
+ Map<String, ToscaGroupTemplate> groupsMap = null;
if (groups != null && !groups.isEmpty()) {
- Map<String, ToscaGroupTemplate> groupsMap = new HashMap<String, ToscaGroupTemplate>();
+ groupsMap = new HashMap<String, ToscaGroupTemplate>();
for (GroupDefinition group : groups) {
- ToscaGroupTemplate toscaGroup = convertGroup(group, component);
+ ToscaGroupTemplate toscaGroup = convertGroup(group);
groupsMap.put(group.getName(), toscaGroup);
}
- topology_template.setGroups(groupsMap);
log.debug("groups converted");
-
+ topologyTemplate.addGroups(groupsMap);
}
-
SubstitutionMapping substitutionMapping = new SubstitutionMapping();
String toscaResourceName = null;
switch (component.getComponentType()) {
case RESOURCE:
- toscaResourceName = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition().getMetadataDataDefinition()).getToscaResourceName();
+ toscaResourceName = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition()
+ .getMetadataDataDefinition()).getToscaResourceName();
break;
case SERVICE:
- toscaResourceName = SERVICE_NODE_TYPE_PREFIX + component.getComponentMetadataDefinition().getMetadataDataDefinition().getSystemName();
+ toscaResourceName = SERVICE_NODE_TYPE_PREFIX
+ + component.getComponentMetadataDefinition().getMetadataDataDefinition().getSystemName();
break;
default:
log.debug("Not supported component type {}", component.getComponentType());
@@ -237,25 +273,27 @@ public class ToscaExportHandler {
}
substitutionMapping.setNode_type(toscaResourceName);
- Either<SubstitutionMapping, ToscaError> capabilities = convertCapabilities(component, substitutionMapping, dataTypes);
+ Either<SubstitutionMapping, ToscaError> capabilities = convertCapabilities(component, substitutionMapping,
+ dataTypes);
if (capabilities.isRight()) {
return Either.right(capabilities.right().value());
}
substitutionMapping = capabilities.left().value();
- Either<SubstitutionMapping, ToscaError> requirements = capabiltyRequirementConvertor.convertRequirements(component, substitutionMapping);
+ Either<SubstitutionMapping, ToscaError> requirements = capabiltyRequirementConvertor.convertSubstitutionMappingRequirements(component, substitutionMapping);
if (requirements.isRight()) {
return Either.right(requirements.right().value());
}
substitutionMapping = requirements.left().value();
- topology_template.setSubstitution_mappings(substitutionMapping);
+ topologyTemplate.setSubstitution_mappings(substitutionMapping);
- toscaNode.setTopology_template(topology_template);
+ toscaNode.setTopology_template(topologyTemplate);
return Either.left(toscaNode);
}
- private Either<ToscaTopolgyTemplate, ToscaError> fillInputs(Component component, ToscaTopolgyTemplate topology_template, Map<String, DataTypeDefinition> dataTypes) {
+ private Either<ToscaTopolgyTemplate, ToscaError> fillInputs(Component component,
+ ToscaTopolgyTemplate topologyTemplate, Map<String, DataTypeDefinition> dataTypes) {
if (log.isDebugEnabled())
log.debug("fillInputs for component {}", component.getUniqueId());
List<InputDefinition> inputDef = component.getInputs();
@@ -266,14 +304,19 @@ public class ToscaExportHandler {
ToscaProperty property = propertyConvertor.convertProperty(dataTypes, i, false);
inputs.put(i.getName(), property);
});
- if (inputs != null && !inputs.isEmpty()) {
- topology_template.setInputs(inputs);
+ if (!inputs.isEmpty()) {
+ topologyTemplate.setInputs(inputs);
}
}
- return Either.left(topology_template);
+ return Either.left(topologyTemplate);
+ }
+
+ private ToscaMetadata convertMetadata(Component component) {
+ return convertMetadata(component, false, null);
}
- private ToscaMetadata convertMetadata(Component component, boolean isInstance) {
+ private ToscaMetadata convertMetadata(Component component, boolean isInstance,
+ ComponentInstance componentInstance) {
ToscaMetadata toscaMetadata = new ToscaMetadata();
toscaMetadata.setName(component.getComponentMetadataDefinition().getMetadataDataDefinition().getName());
toscaMetadata.setInvariantUUID(component.getInvariantUUID());
@@ -286,6 +329,7 @@ public class ToscaExportHandler {
if (isInstance) {
toscaMetadata.setVersion(component.getVersion());
+ toscaMetadata.setCustomizationUUID(componentInstance.getCustomizationUUID());
}
switch (component.getComponentType()) {
case RESOURCE:
@@ -300,8 +344,10 @@ public class ToscaExportHandler {
case SERVICE:
toscaMetadata.setType(component.getComponentType().getValue());
if (!isInstance) {
- toscaMetadata.setServiceEcompNaming(false);
- toscaMetadata.setServiceHoming(false);
+ // DE268546
+ toscaMetadata.setServiceEcompNaming(((Service)component).isEcompGeneratedNaming());
+ toscaMetadata.setEcompGeneratedNaming(((Service)component).isEcompGeneratedNaming());
+ toscaMetadata.setNamingPolicy(((Service)component).getNamingPolicy());
}
break;
default:
@@ -310,38 +356,59 @@ public class ToscaExportHandler {
return toscaMetadata;
}
- private Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> fillImports(Component component, ToscaTemplate toscaTemplate) {
+ private Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> fillImports(Component component,
+ ToscaTemplate toscaTemplate) {
Map<String, Component> componentCache = new HashMap<>();
- if (!ToscaUtils.isNodeType(component)) {
+
+ if (!ToscaUtils.isAtomicType(component)) {
List<ComponentInstance> componentInstances = component.getComponentInstances();
if (componentInstances != null && !componentInstances.isEmpty()) {
- List<Map<String, Map<String, String>>> imports = new LinkedList<Map<String, Map<String, String>>>();
+
+ List<Map<String, Map<String, String>>> additionalImports =
+ toscaTemplate.getImports() == null ? new ArrayList<>(DEFAULT_IMPORTS) : new ArrayList<>(toscaTemplate.getImports());
+
List<Triple<String, String, Component>> dependecies = new ArrayList<>();
+ Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts();
+ ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
+
+ Map<String, Map<String, String>> importsListMember = new HashMap<>();
+ Map<String, String> interfaceFiles = new HashMap<>();
+ interfaceFiles.put(IMPORTS_FILE_KEY, getInterfaceFilename(artifactDefinition.getArtifactName()));
+ StringBuilder keyNameBuilder = new StringBuilder();
+ keyNameBuilder.append(component.getComponentType().toString().toLowerCase());
+ keyNameBuilder.append("-");
+ keyNameBuilder.append(component.getName());
+ keyNameBuilder.append("-interface");
+ importsListMember.put(keyNameBuilder.toString(), interfaceFiles);
+ additionalImports.add(importsListMember);
+
componentInstances.forEach(ci -> {
- createDependency(componentCache, imports, dependecies, ci);
+ createDependency(componentCache, additionalImports, dependecies, ci);
});
- toscaTemplate.setImports(imports);
toscaTemplate.setDependencies(dependecies);
+ toscaTemplate.setImports(additionalImports);
}
} else {
log.debug("currently imports supported for VF and service only");
- }
+ }
return Either.left(new ImmutablePair<ToscaTemplate, Map<String, Component>>(toscaTemplate, componentCache));
}
- private void createDependency(Map<String, Component> componentCache, List<Map<String, Map<String, String>>> imports, List<Triple<String, String, Component>> dependecies, ComponentInstance ci) {
+ private void createDependency(Map<String, Component> componentCache, List<Map<String, Map<String, String>>> imports,
+ List<Triple<String, String, Component>> dependecies, ComponentInstance ci) {
Map<String, String> files = new HashMap<>();
Map<String, Map<String, String>> importsListMember = new HashMap<>();
+ StringBuilder keyNameBuilder;
Component componentRI = componentCache.get(ci.getComponentUid());
if (componentRI == null) {
// all resource must be only once!
- Either<Resource, StorageOperationStatus> resource = resourceOperation.getResource(ci.getComponentUid(), true);
+ Either<Component, StorageOperationStatus> resource = toscaOperationFacade.getToscaFullElement(ci.getComponentUid());
if (resource.isRight()) {
log.debug("Failed to fetch resource with id {} for instance {}");
}
- Resource fetchedComponent = resource.left().value();
+ Component fetchedComponent = resource.left().value();
componentCache.put(fetchedComponent.getUniqueId(), fetchedComponent);
componentRI = fetchedComponent;
@@ -350,16 +417,34 @@ public class ToscaExportHandler {
if (artifactDefinition != null) {
String artifactName = artifactDefinition.getArtifactName();
files.put(IMPORTS_FILE_KEY, artifactName);
- importsListMember.put(ci.getComponentName(), files);
- dependecies.add(new ImmutableTriple<String, String, Component>(artifactName, artifactDefinition.getEsId(), fetchedComponent));
+ keyNameBuilder = new StringBuilder();
+ keyNameBuilder.append(fetchedComponent.getComponentType().toString().toLowerCase());
+ keyNameBuilder.append("-");
+ keyNameBuilder.append(ci.getComponentName());
+ importsListMember.put(keyNameBuilder.toString(), files);
+ imports.add(importsListMember);
+ dependecies.add(new ImmutableTriple<String, String, Component>(artifactName,
+ artifactDefinition.getEsId(), fetchedComponent));
+
+ if(!ToscaUtils.isAtomicType(componentRI)) {
+ importsListMember = new HashMap<>();
+ Map<String, String> interfaceFiles = new HashMap<>();
+ interfaceFiles.put(IMPORTS_FILE_KEY, getInterfaceFilename(artifactName));
+ keyNameBuilder.append("-interface");
+ importsListMember.put(keyNameBuilder.toString(), interfaceFiles);
+ imports.add(importsListMember);
+ }
}
}
- if (!importsListMember.isEmpty()) {
- imports.add(importsListMember);
- }
}
- private Either<ToscaTemplate, ToscaError> convertNodeType(Component component, ToscaTemplate toscaNode, Map<String, ToscaNodeType> node_types) {
+ public static String getInterfaceFilename(String artifactName) {
+ String interfaceFileName = artifactName.substring(0, artifactName.lastIndexOf('.')) + ToscaExportHandler.TOSCA_INTERFACE_NAME;
+ return interfaceFileName;
+ }
+
+ private Either<ToscaTemplate, ToscaError> convertNodeType(Component component, ToscaTemplate toscaNode,
+ Map<String, ToscaNodeType> nodeTypes) {
log.debug("start convert node type for {}", component.getUniqueId());
ToscaNodeType toscaNodeType = createNodeType(component);
@@ -370,13 +455,51 @@ public class ToscaExportHandler {
}
Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
- Either<ToscaNodeType, ToscaError> properties = propertyConvertor.convertProperties(component, toscaNodeType, dataTypes);
+ Either<ToscaNodeType, ToscaError> properties = propertyConvertor.convertProperties(component, toscaNodeType,
+ dataTypes);
if (properties.isRight()) {
return Either.right(properties.right().value());
}
toscaNodeType = properties.left().value();
log.debug("Properties converted for {}", component.getUniqueId());
+ //Extracted to method for code reuse
+ return convertReqCapAndTypeName(component, toscaNode, nodeTypes, toscaNodeType, dataTypes);
+ }
+
+ private Either<ToscaTemplate, ToscaError> convertInterfaceNodeType(Component component, ToscaTemplate toscaNode,
+ Map<String, ToscaNodeType> nodeTypes) {
+ log.debug("start convert node type for {}", component.getUniqueId());
+ ToscaNodeType toscaNodeType = createNodeType(component);
+
+ Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll();
+ if (dataTypesEither.isRight()) {
+ log.debug("Failed to fetch all data types :", dataTypesEither.right().value());
+ return Either.right(ToscaError.GENERAL_ERROR);
+ }
+
+ Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
+
+ List<InputDefinition> inputDef = component.getInputs();
+ Map<String, ToscaProperty> inputs = new HashMap<>();
+
+ if (inputDef != null) {
+ inputDef.forEach(i -> {
+ ToscaProperty property = propertyConvertor.convertProperty(dataTypes, i, false);
+ inputs.put(i.getName(), property);
+ });
+ if (!inputs.isEmpty()) {
+ toscaNodeType.setProperties(inputs);
+ }
+ }
+
+ //Extracted to method for code reuse
+ return convertReqCapAndTypeName(component, toscaNode, nodeTypes, toscaNodeType, dataTypes);
+ }
+
+ private Either<ToscaTemplate, ToscaError> convertReqCapAndTypeName(Component component, ToscaTemplate toscaNode,
+ Map<String, ToscaNodeType> nodeTypes, ToscaNodeType toscaNodeType,
+ Map<String, DataTypeDefinition> dataTypes) {
Either<ToscaNodeType, ToscaError> capabilities = convertCapabilities(component, toscaNodeType, dataTypes);
if (capabilities.isRight()) {
return Either.right(capabilities.right().value());
@@ -384,150 +507,323 @@ public class ToscaExportHandler {
toscaNodeType = capabilities.left().value();
log.debug("Capabilities converted for {}", component.getUniqueId());
- Either<ToscaNodeType, ToscaError> requirements = capabiltyRequirementConvertor.convertRequirements(component, toscaNodeType);
+ Either<ToscaNodeType, ToscaError> requirements = capabiltyRequirementConvertor.convertRequirements(component,
+ toscaNodeType);
if (requirements.isRight()) {
return Either.right(requirements.right().value());
}
toscaNodeType = requirements.left().value();
log.debug("Requirements converted for {}", component.getUniqueId());
- String toscaResourceName = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition().getMetadataDataDefinition()).getToscaResourceName();
- node_types.put(toscaResourceName, toscaNodeType);
- toscaNode.setNode_types(node_types);
+
+ String toscaResourceName;
+ switch (component.getComponentType()) {
+ case RESOURCE:
+ toscaResourceName = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition()
+ .getMetadataDataDefinition()).getToscaResourceName();
+ break;
+ case SERVICE:
+ toscaResourceName = SERVICE_NODE_TYPE_PREFIX
+ + component.getComponentMetadataDefinition().getMetadataDataDefinition().getSystemName();
+ break;
+ default:
+ log.debug("Not supported component type {}", component.getComponentType());
+ return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE);
+ }
+
+ nodeTypes.put(toscaResourceName, toscaNodeType);
+ toscaNode.setNode_types(nodeTypes);
log.debug("finish convert node type for {}", component.getUniqueId());
return Either.left(toscaNode);
}
- private Either<Map<String, ToscaNodeTemplate>, ToscaError> convertNodeTemplates(Component component, List<ComponentInstance> componentInstances, Map<String, List<ComponentInstanceProperty>> componentInstancesProperties,
- Map<String, Component> componentCache, Map<String, DataTypeDefinition> dataTypes) {
- log.debug("start convert topology template for {} for type {}", component.getUniqueId(), component.getComponentType());
- Map<String, ToscaNodeTemplate> node_templates = new HashMap<>();
+ private Either<Map<String, ToscaNodeTemplate>, ToscaError> convertNodeTemplates(Component component,
+ List<ComponentInstance> componentInstances,
+ Map<String, List<ComponentInstanceProperty>> componentInstancesProperties,
+ Map<String, Component> componentCache, Map<String, DataTypeDefinition> dataTypes,
+ ToscaTopolgyTemplate topologyTemplate) {
+ Either<Map<String, ToscaNodeTemplate>, ToscaError> convertNodeTemplatesRes = null;
+ log.debug("start convert topology template for {} for type {}", component.getUniqueId(),
+ component.getComponentType());
+ Map<String, ToscaNodeTemplate> nodeTemplates = new HashMap<>();
+ Map<String, List<ComponentInstanceInput>> componentInstancesInputs = component.getComponentInstancesInputs();
+
+ Map<String, ToscaGroupTemplate> groupsMap = null;
for (ComponentInstance componentInstance : componentInstances) {
ToscaNodeTemplate nodeTemplate = new ToscaNodeTemplate();
nodeTemplate.setType(componentInstance.getToscaComponentName());
- Either<ToscaNodeTemplate, ToscaError> requirements = convertComponentInstanceRequirements(component, componentInstance, component.getComponentInstancesRelations(), nodeTemplate);
+ Either<ToscaNodeTemplate, ToscaError> requirements = convertComponentInstanceRequirements(component,
+ componentInstance, component.getComponentInstancesRelations(), nodeTemplate);
if (requirements.isRight()) {
- return Either.right(requirements.right().value());
+ convertNodeTemplatesRes = Either.right(requirements.right().value());
+ break;
}
- log.debug("Component instance Requirements converted for instance {}", componentInstance.getUniqueId());
+ String instanceUniqueId = componentInstance.getUniqueId();
+ log.debug("Component instance Requirements converted for instance {}", instanceUniqueId);
nodeTemplate = requirements.left().value();
Component componentOfInstance = componentCache.get(componentInstance.getComponentUid());
- nodeTemplate.setMetadata(convertMetadata(componentOfInstance, true));
+ nodeTemplate.setMetadata(convertMetadata(componentOfInstance, true, componentInstance));
- Either<ToscaNodeTemplate, ToscaError> capabilties = capabiltyRequirementConvertor.convertComponentInstanceCapabilties(componentInstance, dataTypes, nodeTemplate);
+ Either<ToscaNodeTemplate, ToscaError> capabilties = capabiltyRequirementConvertor
+ .convertComponentInstanceCapabilties(componentInstance, dataTypes, nodeTemplate);
if (capabilties.isRight()) {
- return Either.right(requirements.right().value());
+ convertNodeTemplatesRes = Either.right(requirements.right().value());
+ break;
}
- log.debug("Component instance Capabilties converted for instance {}", componentInstance.getUniqueId());
+ log.debug("Component instance Capabilties converted for instance {}", instanceUniqueId);
nodeTemplate = capabilties.left().value();
+ Map<String, Object> props = new HashMap<>();
- if (componentInstancesProperties.containsKey(componentInstance.getUniqueId())) {
- Map<String, Object> props = null;
- List<ComponentInstanceProperty> propList = componentInstancesProperties.get(componentInstance.getUniqueId());
- List<ComponentInstanceProperty> collect = propList.stream().filter(e -> e.getValueUniqueUid() != null && !e.getValueUniqueUid().isEmpty()).collect(Collectors.toList());
- if (collect != null && !collect.isEmpty()) {
- props = new HashMap<String, Object>();
- for (ComponentInstanceProperty prop : collect) {
- Object convertedValue = convertInstanceProperty(dataTypes, componentInstance, prop);
- props.put(prop.getName(), convertedValue);
- }
+ if (componentOfInstance.getComponentType() == ComponentTypeEnum.RESOURCE) {
+ // Adds the properties of parent component to map
+ addPropertiesOfParentComponent(dataTypes, componentInstance, componentOfInstance, props);
+ }
+
+ if (null != componentInstancesProperties && componentInstancesProperties.containsKey(instanceUniqueId)) {
+ addPropertiesOfComponentInstance(componentInstancesProperties, dataTypes, componentInstance,
+ instanceUniqueId, props);
+ }
+
+ if (componentInstancesInputs != null && componentInstancesInputs.containsKey(instanceUniqueId)) {
+ addComponentInstanceInputs(dataTypes, componentInstancesInputs, componentInstance, instanceUniqueId,
+ props);
+ }
+ if (props != null && !props.isEmpty()) {
+ nodeTemplate.setProperties(props);
+ }
+
+ List<GroupInstance> groupInstances = componentInstance.getGroupInstances();
+ if (groupInstances != null) {
+ if (groupsMap == null) {
+ groupsMap = new HashMap<>();
}
- if (props != null && !props.isEmpty()) {
- nodeTemplate.setProperties(props);
+ for (GroupInstance groupInst : groupInstances) {
+ ToscaGroupTemplate toscaGroup = convertGroupInstance(groupInst);
+ String keyName = groupInst.getGroupName();
+
+ groupsMap.put(keyName, toscaGroup);
}
}
- node_templates.put(componentInstance.getName(), nodeTemplate);
+
+ nodeTemplates.put(componentInstance.getName(), nodeTemplate);
+ }
+ if (groupsMap != null) {
+ log.debug("instance groups added");
+ topologyTemplate.addGroups(groupsMap);
+ }
+
+ if (convertNodeTemplatesRes == null) {
+ convertNodeTemplatesRes = Either.left(nodeTemplates);
+ }
+ log.debug("finish convert topology template for {} for type {}", component.getUniqueId(),
+ component.getComponentType());
+ return convertNodeTemplatesRes;
+ }
+
+ private void addComponentInstanceInputs(Map<String, DataTypeDefinition> dataTypes,
+ Map<String, List<ComponentInstanceInput>> componentInstancesInputs, ComponentInstance componentInstance,
+ String instanceUniqueId, Map<String, Object> props) {
+
+ List<ComponentInstanceInput> instanceInputsList = componentInstancesInputs.get(instanceUniqueId);
+ if (instanceInputsList != null) {
+ instanceInputsList.forEach(input -> {
+ Supplier<String> supplier = () -> input.getValue();
+ convertAndAddValue(dataTypes, componentInstance, props, input, supplier);
+ });
+ }
+ }
+
+ private void addPropertiesOfComponentInstance(
+ Map<String, List<ComponentInstanceProperty>> componentInstancesProperties,
+ Map<String, DataTypeDefinition> dataTypes, ComponentInstance componentInstance, String instanceUniqueId,
+ Map<String, Object> props) {
+
+ if (!MapUtils.isEmpty(componentInstancesProperties)) {
+ componentInstancesProperties.get(instanceUniqueId).stream()
+ // Filters out properties with empty ValueUniqueUid
+ .filter(e -> e.getValue() != null && !e.getValue().isEmpty() )
+ // Collects filtered properties to List
+ .collect(Collectors.toList()).stream()
+ // Converts and adds each value to property map
+ .forEach(prop -> convertAndAddValue(dataTypes, componentInstance, props, prop,
+ () -> prop.getValue()));
+ }
+ }
+
+ private void addPropertiesOfParentComponent(Map<String, DataTypeDefinition> dataTypes,
+ ComponentInstance componentInstance, Component componentOfInstance, Map<String, Object> props) {
+
+ List<PropertyDefinition> componentProperties = ((Resource) componentOfInstance).getProperties();
+ if (!CollectionUtils.isEmpty(componentProperties)) {
+ componentProperties.stream()
+ // Filters out properties with empty default values
+ .filter(prop -> !StringUtils.isEmpty(prop.getDefaultValue()))
+ // Collects filtered properties to List
+ .collect(Collectors.toList()).stream()
+ // Converts and adds each value to property map
+ .forEach(prop -> convertAndAddValue(dataTypes, componentInstance, props, prop,
+ () -> prop.getDefaultValue()));
+ }
+ }
+
+ /**
+ * @param dataTypes
+ * @param componentInstance
+ * @param props
+ * @param prop
+ * @param supplier
+ */
+ private void convertAndAddValue(Map<String, DataTypeDefinition> dataTypes, ComponentInstance componentInstance,
+ Map<String, Object> props, PropertyDefinition prop, Supplier<String> supplier) {
+ Object convertedValue = convertValue(dataTypes, componentInstance, prop, supplier);
+ if (!ToscaValueBaseConverter.isEmptyObjectValue(convertedValue)) {
+ props.put(prop.getName(), convertedValue);
}
- log.debug("finish convert topology template for {} for type {}", component.getUniqueId(), component.getComponentType());
- return Either.left(node_templates);
}
- private Object convertInstanceProperty(Map<String, DataTypeDefinition> dataTypes, ComponentInstance componentInstance, ComponentInstanceProperty prop) {
- log.debug("Convert property {} for instance {}", prop.getName(), componentInstance.getUniqueId());
- String propertyType = prop.getType();
+ private <T extends PropertyDefinition> Object convertValue(Map<String, DataTypeDefinition> dataTypes,
+ ComponentInstance componentInstance, T input, Supplier<String> supplier) {
+ log.debug("Convert property or input value {} for instance {}", input.getName(),
+ componentInstance.getUniqueId());
+ String propertyType = input.getType();
String innerType = null;
- if (prop.getSchema() != null && prop.getSchema().getProperty() != null) {
- innerType = prop.getSchema().getProperty().getType();
+ if (input.getSchema() != null && input.getSchema().getProperty() != null) {
+ innerType = input.getSchema().getProperty().getType();
}
- Object convertedValue = propertyConvertor.convertToToscaObject(propertyType, prop.getValue(), innerType, dataTypes);
- return convertedValue;
+ return propertyConvertor.convertToToscaObject(propertyType, supplier.get(), innerType, dataTypes);
}
- private ToscaGroupTemplate convertGroup(GroupDefinition group, Component component) {
+ private ToscaGroupTemplate convertGroup(GroupDefinition group) {
ToscaGroupTemplate toscaGroup = new ToscaGroupTemplate();
Map<String, String> members = group.getMembers();
- toscaGroup.setType(group.getType());
if (members != null)
toscaGroup.setMembers(new ArrayList(members.keySet()));
- boolean isVfModule = group.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE) ? true : false;
+ Supplier<String> supplGroupType = () -> group.getType();
+ Supplier<String> supplDescription = () -> group.getDescription();
+ Supplier<List<? extends GroupProperty>> supplProperties = () -> group.convertToGroupProperties();
+ Supplier<String> supplgroupName = () -> group.getName();
+ Supplier<String> supplInvariantUUID = () -> group.getInvariantUUID();
+ Supplier<String> supplGroupUUID = () -> group.getGroupUUID();
+ Supplier<String> supplVersion = () -> group.getVersion();
+
+ IToscaMetadata toscaMetadata = fillGroup(toscaGroup, supplProperties, supplDescription, supplgroupName,
+ supplInvariantUUID, supplGroupUUID, supplVersion, supplGroupType);
+ toscaGroup.setMetadata(toscaMetadata);
+ return toscaGroup;
+ }
+
+ private ToscaGroupTemplate convertGroupInstance(GroupInstance groupInstance) {
+ ToscaGroupTemplate toscaGroup = new ToscaGroupTemplate();
+
+ Supplier<String> supplGroupType = () -> groupInstance.getType();
+ Supplier<String> supplDescription = () -> groupInstance.getDescription();
+ Supplier<List<? extends GroupProperty>> supplProperties = () -> groupInstance.convertToGroupInstancesProperties();
+ Supplier<String> supplgroupName = () -> groupInstance.getGroupName();
+ Supplier<String> supplInvariantUUID = () -> groupInstance.getInvariantUUID();
+ Supplier<String> supplGroupUUID = () -> groupInstance.getGroupUUID();
+ Supplier<String> supplVersion = () -> groupInstance.getVersion();
+
+ IToscaMetadata toscaMetadata = fillGroup(toscaGroup, supplProperties, supplDescription, supplgroupName,
+ supplInvariantUUID, supplGroupUUID, supplVersion, supplGroupType);
+
+ toscaMetadata.setCustomizationUUID(groupInstance.getCustomizationUUID());
+ toscaGroup.setMetadata(toscaMetadata);
+ return toscaGroup;
+ }
+
+ private IToscaMetadata fillGroup(ToscaGroupTemplate toscaGroup, Supplier<List<? extends GroupProperty>> props,
+ Supplier<String> description, Supplier<String> groupName, Supplier<String> invariantUUID,
+ Supplier<String> groupUUID, Supplier<String> version, Supplier<String> groupType) {
+ boolean isVfModule = groupType.get().equals(Constants.DEFAULT_GROUP_VF_MODULE) ? true : false;
+ toscaGroup.setType(groupType.get());
+
IToscaMetadata toscaMetadata;
if (!isVfModule) {
toscaMetadata = new ToscaMetadata();
} else {
toscaMetadata = new VfModuleToscaMetadata();
- Map<String, Object> properties = new HashMap<>();
- for (GroupProperty gp : group.getProperties()) {
+ Map<String, Object> properties = fillGroupProperties(props.get());
+
+ properties.put(VF_MODULE_DESC_KEY, description.get());
+ toscaGroup.setProperties(properties);
+ }
+ toscaMetadata.setName(groupName.get());
+ toscaMetadata.setInvariantUUID(invariantUUID.get());
+ toscaMetadata.setUUID(groupUUID.get());
+ toscaMetadata.setVersion(version.get());
+ return toscaMetadata;
+ }
+
+ private Map<String, Object> fillGroupProperties(List<? extends GroupProperty> groupProps) {
+ Map<String, Object> properties = new HashMap<>();
+ if(groupProps != null){
+ for (GroupProperty gp : groupProps) {
if (gp.getName().equals(Constants.IS_BASE)) {
Boolean isBase = Boolean.parseBoolean(gp.getValue());
String type = isBase ? VF_MODULE_TYPE_BASE : VF_MODULE_TYPE_EXPANSION;
properties.put(VF_MODULE_TYPE_KEY, type);
- break;
- }
- }
- properties.put(VF_MODULE_DESC_KEY, group.getDescription());
- boolean isVolume = false;
- List<String> artifactsList = group.getArtifacts();
- if (artifactsList != null && !artifactsList.isEmpty()) {
-
- for (String artifactId : artifactsList) {
- Map<String, ArtifactDefinition> deploymentArtifacts = component.getDeploymentArtifacts();
- Optional<ArtifactDefinition> findFirst = deploymentArtifacts.values().stream().filter(p -> p.getUniqueId().equals(artifactId)).findFirst();
- if (findFirst.isPresent()) {
- ArtifactDefinition artifactDefinition = findFirst.get();
- if (artifactDefinition.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType())) {
- isVolume = true;
- break;
+ } else {
+ Object value = null;
+ String type = gp.getType();
+
+ switch (type) {
+ case "integer":
+ if (gp.getValue() != null) {
+ value = Integer.valueOf(gp.getValue());
}
+ break;
+ case "boolean":
+ if (gp.getValue() != null) {
+ value = Boolean.valueOf(gp.getValue());
+ }
+ break;
+
+ default:
+ value = gp.getValue();
+ break;
}
+ properties.put(gp.getName(), value);
}
}
- properties.put(VOLUME_GROUP_KEY, isVolume);
- toscaGroup.setProperties(properties);
}
- toscaMetadata.setName(group.getName());
- toscaMetadata.setInvariantUUID(group.getInvariantUUID());
- toscaMetadata.setUUID(group.getGroupUUID());
- toscaMetadata.setVersion(group.getVersion());
- toscaGroup.setMetadata(toscaMetadata);
- return toscaGroup;
+ return properties;
}
private ToscaNodeType createNodeType(Component component) {
ToscaNodeType toscaNodeType = new ToscaNodeType();
- if (ToscaUtils.isNodeType(component) && ((Resource) component).getDerivedFrom() != null) {
- toscaNodeType.setDerived_from(((Resource) component).getDerivedFrom().get(0));
+ if (ToscaUtils.isAtomicType(component)){
+ if (((Resource) component).getDerivedFrom() != null){
+ toscaNodeType.setDerived_from(((Resource) component).getDerivedFrom().get(0));
+ }
+ toscaNodeType.setDescription(component.getDescription()); // or name??
+ } else {
+ String derivedFrom = null != component.getDerivedFromGenericType()? component.getDerivedFromGenericType() : "tosca.nodes.Root";
+ toscaNodeType.setDerived_from(derivedFrom);
}
- toscaNodeType.setDescription(component.getDescription()); // or name??
return toscaNodeType;
}
-
- private Either<ToscaNodeTemplate, ToscaError> convertComponentInstanceRequirements(Component component, ComponentInstance componentInstance, List<RequirementCapabilityRelDef> relations, ToscaNodeTemplate nodeTypeTemplate) {
+
+ private Either<ToscaNodeTemplate, ToscaError> convertComponentInstanceRequirements(Component component,
+ ComponentInstance componentInstance, List<RequirementCapabilityRelDef> relations,
+ ToscaNodeTemplate nodeTypeTemplate) {
List<ComponentInstance> instancesList = component.getComponentInstances();
List<Map<String, ToscaTemplateRequirement>> toscaRequirements = new ArrayList<>();
Map<String, List<RequirementDefinition>> reqMap = componentInstance.getRequirements();
relations.stream().filter(p -> componentInstance.getUniqueId().equals(p.getFromNode())).forEach(req -> {
- ComponentInstance toComponentInstance = instancesList.stream().filter(i -> req.getToNode().equals(i.getUniqueId())).findFirst().orElse(null);
+ ComponentInstance toComponentInstance = instancesList.stream()
+ .filter(i -> req.getToNode().equals(i.getUniqueId())).findFirst().orElse(null);
if (toComponentInstance == null) {
- log.debug("Faild to create relation between node {} to node {}", componentInstance.getName(), req.getToNode());
+ log.debug("Faild to create relation between node {} to node {}", componentInstance.getName(),
+ req.getToNode());
return;
}
@@ -535,12 +831,14 @@ public class ToscaExportHandler {
ToscaTemplateRequirement toscaRequirement = new ToscaTemplateRequirement();
toscaRequirement.setRelationship(reqAndRelationshopPair.getRelationship().getType());
toscaRequirement.setNode(toComponentInstance.getName());
- Optional<RequirementDefinition> findAny = reqMap.values().stream().flatMap(e -> e.stream()).filter(e -> e.getName().equals(reqAndRelationshopPair.getRequirement())).findAny();
+ Optional<RequirementDefinition> findAny = reqMap.values().stream().flatMap(e -> e.stream())
+ .filter(e -> e.getName().equals(reqAndRelationshopPair.getRequirement())).findAny();
if (findAny.isPresent()) {
RequirementDefinition regDefinition = findAny.get();
toscaRequirement.setCapability(regDefinition.getCapability());
} else {
- log.debug("Faild to find relation between node {} to node {}", componentInstance.getName(), req.getToNode());
+ log.debug("Faild to find relation between node {} to node {}", componentInstance.getName(),
+ req.getToNode());
return;
}
Map<String, ToscaTemplateRequirement> reqmap = new HashMap<String, ToscaTemplateRequirement>();
@@ -557,7 +855,8 @@ public class ToscaExportHandler {
}
private Either<SubstitutionMapping, ToscaError> convertCapabilities(Component component, SubstitutionMapping substitutionMapping, Map<String, DataTypeDefinition> dataTypes) {
- Map<String, ToscaCapability> toscaCapabilities = capabiltyRequirementConvertor.convertCapabilities(component, dataTypes);
+ Map<String, String[]> toscaCapabilities = capabiltyRequirementConvertor.convertSubstitutionMappingCapabilities(component, dataTypes);
+
if (!toscaCapabilities.isEmpty()) {
substitutionMapping.setCapabilities(toscaCapabilities);
}
@@ -566,8 +865,10 @@ public class ToscaExportHandler {
return Either.left(substitutionMapping);
}
- private Either<ToscaNodeType, ToscaError> convertCapabilities(Component component, ToscaNodeType nodeType, Map<String, DataTypeDefinition> dataTypes) {
- Map<String, ToscaCapability> toscaCapabilities = capabiltyRequirementConvertor.convertCapabilities(component, dataTypes);
+ private Either<ToscaNodeType, ToscaError> convertCapabilities(Component component, ToscaNodeType nodeType,
+ Map<String, DataTypeDefinition> dataTypes) {
+ Map<String, ToscaCapability> toscaCapabilities = capabiltyRequirementConvertor.convertCapabilities(component,
+ dataTypes);
if (!toscaCapabilities.isEmpty()) {
nodeType.setCapabilities(toscaCapabilities);
}
@@ -586,7 +887,8 @@ public class ToscaExportHandler {
}
@Override
- protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue, Tag customTag) {
+ protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue,
+ Tag customTag) {
if (propertyValue == null) {
return null;
} else {
@@ -596,7 +898,8 @@ public class ToscaExportHandler {
}
NodeTuple defaultNode = super.representJavaBeanProperty(javaBean, property, propertyValue, customTag);
- return property.getName().equals("_defaultp_") ? new NodeTuple(representData("default"), defaultNode.getValueNode()) : defaultNode;
+ return property.getName().equals("_defaultp_")
+ ? new NodeTuple(representData("default"), defaultNode.getValueNode()) : defaultNode;
}
}
@@ -619,10 +922,10 @@ public class ToscaExportHandler {
private static class UnsortedPropertyUtils extends PropertyUtils {
@Override
- protected Set<Property> createPropertySet(Class<? extends Object> type, BeanAccess bAccess) throws IntrospectionException {
+ protected Set<Property> createPropertySet(Class<? extends Object> type, BeanAccess bAccess)
+ throws IntrospectionException {
Collection<Property> fields = getPropertiesMap(type, BeanAccess.FIELD).values();
- Set<Property> result = new LinkedHashSet<Property>(fields);
- return result;
+ return new LinkedHashSet<Property>(fields);
}
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaUtils.java
index db03ad2307..dce3b3bbc0 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaUtils.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaUtils.java
@@ -34,11 +34,11 @@ import org.openecomp.sdc.be.model.Component;
public class ToscaUtils {
- public static boolean isNodeType(Component component) {
+ public static boolean isAtomicType(Component component) {
ComponentTypeEnum componentType = component.getComponentType();
if (ComponentTypeEnum.RESOURCE.equals(componentType)) {
ResourceTypeEnum resourceType = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition().getMetadataDataDefinition()).getResourceType();
- if (ResourceTypeEnum.CP.equals(resourceType) || ResourceTypeEnum.VL.equals(resourceType) || ResourceTypeEnum.VFC.equals(resourceType)) {
+ if (ResourceTypeEnum.CP == resourceType || ResourceTypeEnum.VL == resourceType || ResourceTypeEnum.VFC == resourceType || ResourceTypeEnum.VFCMT == resourceType || ResourceTypeEnum.ABSTRACT == resourceType) {
return true;
}
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/IToscaMetadata.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/IToscaMetadata.java
index 46f4fd032e..70b05b8158 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/IToscaMetadata.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/IToscaMetadata.java
@@ -29,5 +29,6 @@ public interface IToscaMetadata {
public void setUUID(String uUID);
public void setVersion(String version);
-
+
+ public void setCustomizationUUID(String customizationUUID);
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/SubstitutionMapping.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/SubstitutionMapping.java
index 0fd9daef7d..5dc8ddee2a 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/SubstitutionMapping.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/SubstitutionMapping.java
@@ -24,9 +24,8 @@ import java.util.Map;
public class SubstitutionMapping {
private String node_type;
-
- private Map<String, ToscaCapability> capabilities;
- private Map<String, ToscaRequirement> requirements;
+ private Map<String, String[]> capabilities;
+ private Map<String, String[]> requirements;
public SubstitutionMapping() {
super();
@@ -41,20 +40,19 @@ public class SubstitutionMapping {
this.node_type = node_type;
}
- public Map<String, ToscaCapability> getCapabilities() {
+ public Map<String, String[]> getCapabilities() {
return capabilities;
}
- public void setCapabilities(Map<String, ToscaCapability> capabilities) {
+ public void setCapabilities(Map<String, String[]> capabilities) {
this.capabilities = capabilities;
}
- public Map<String, ToscaRequirement> getRequirements() {
+ public Map<String, String[]> getRequirements() {
return requirements;
}
- public void setRequirements(Map<String, ToscaRequirement> requirements) {
+ public void setRequirements(Map<String, String[]> requirements) {
this.requirements = requirements;
}
-
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaMetadata.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaMetadata.java
index 38cd002726..6573313dbb 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaMetadata.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaMetadata.java
@@ -23,6 +23,7 @@ package org.openecomp.sdc.be.tosca.model;
public class ToscaMetadata implements IToscaMetadata {
private String invariantUUID;
private String UUID;
+ private String customizationUUID;
private String version;
private String name;
private String description;
@@ -32,7 +33,8 @@ public class ToscaMetadata implements IToscaMetadata {
private String resourceVendor;
private String resourceVendorRelease;
private Boolean serviceEcompNaming;
- private Boolean serviceHoming;
+ private Boolean ecompGeneratedNaming;
+ private String namingPolicy;
public String getName() {
return name;
@@ -109,20 +111,28 @@ public class ToscaMetadata implements IToscaMetadata {
this.resourceVendorRelease = resourceVendorRelease;
}
- public Boolean isServiceEcompNaming() {
- return serviceEcompNaming;
+ public Boolean isEcompGeneratedNaming() {
+ return ecompGeneratedNaming;
}
- public void setServiceEcompNaming(Boolean serviceEcompNaming) {
- this.serviceEcompNaming = serviceEcompNaming;
+ public void setEcompGeneratedNaming(Boolean ecompGeneratedNaming) {
+ this.ecompGeneratedNaming = ecompGeneratedNaming;
+ }
+
+ public String isNamingPolicy() {
+ return namingPolicy;
+ }
+
+ public void setNamingPolicy(String namingPolicy) {
+ this.namingPolicy = namingPolicy;
}
- public Boolean isServiceHoming() {
- return serviceHoming;
+ public Boolean getServiceEcompNaming() {
+ return serviceEcompNaming;
}
- public void setServiceHoming(Boolean serviceHoming) {
- this.serviceHoming = serviceHoming;
+ public void setServiceEcompNaming(Boolean serviceEcompNaming) {
+ this.serviceEcompNaming = serviceEcompNaming;
}
public String getVersion() {
@@ -134,4 +144,12 @@ public class ToscaMetadata implements IToscaMetadata {
this.version = version;
}
+ public String getCustomizationUUID() {
+ return customizationUUID;
+ }
+
+ public void setCustomizationUUID(String customizationUUID) {
+ this.customizationUUID = customizationUUID;
+ }
+
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTopolgyTemplate.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTopolgyTemplate.java
index 6804bf6968..df285c6ad9 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTopolgyTemplate.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTopolgyTemplate.java
@@ -20,6 +20,7 @@
package org.openecomp.sdc.be.tosca.model;
+import java.util.HashMap;
import java.util.Map;
public class ToscaTopolgyTemplate {
@@ -40,8 +41,11 @@ public class ToscaTopolgyTemplate {
return groups;
}
- public void setGroups(Map<String, ToscaGroupTemplate> groups) {
- this.groups = groups;
+ public void addGroups(Map<String, ToscaGroupTemplate> groups) {
+ if ( this.groups == null ){
+ this.groups = new HashMap<>();
+ }
+ this.groups.putAll(groups);
}
public SubstitutionMapping getSubstitution_mappings() {
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/VfModuleToscaMetadata.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/VfModuleToscaMetadata.java
index 5f978227ef..26ce118a1a 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/VfModuleToscaMetadata.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/VfModuleToscaMetadata.java
@@ -26,6 +26,7 @@ public class VfModuleToscaMetadata implements IToscaMetadata {
private String vfModuleModelInvariantUUID;
private String vfModuleModelUUID;
private String vfModuleModelVersion;
+ private String vfModuleModelCustomizationUUID;
@Override
public void setName(String name) {
@@ -63,4 +64,12 @@ public class VfModuleToscaMetadata implements IToscaMetadata {
return vfModuleModelVersion;
}
+ public String getVfModuleModelCustomizationUUID() {
+ return vfModuleModelCustomizationUUID;
+ }
+
+ public void setCustomizationUUID(String customizationUUID) {
+ this.vfModuleModelCustomizationUUID = customizationUUID;
+ }
+
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/user/IUserBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/user/IUserBusinessLogic.java
index 5cfa4a12da..54ba9bf571 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/user/IUserBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/user/IUserBusinessLogic.java
@@ -31,6 +31,11 @@ import org.openecomp.sdc.exception.ResponseFormat;
import fj.data.Either;
+/**
+ *
+ * @author tg851x
+ *
+ */
public interface IUserBusinessLogic {
public Either<User, ActionStatus> getUser(String userId, boolean inTransaction);
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserAdminValidator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserAdminValidator.java
index 8e736d4c0e..796b3a78c0 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserAdminValidator.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserAdminValidator.java
@@ -40,8 +40,7 @@ public class UserAdminValidator {
private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
- //private static final String USER_ID_PATTERN = "[mM]{1}[0-9]{5}|[a-zA-Z]{2}[0-9]{4}|[a-zA-Z]{2}[0-9]{4}|[a-zA-Z]{2}[0-9]{3}[a-zA-Z]{1}";
- private static final String USER_ID_PATTERN = "^[\\s\\w_.-]{1,50}$";
+ private static final String USER_ID_PATTERN = "\\w{1,25}";
private UserAdminValidator() {
emailPat = Pattern.compile(EMAIL_PATTERN);
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserBusinessLogic.java
index 8a910fc566..c90cc6118f 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserBusinessLogic.java
@@ -90,7 +90,7 @@ public class UserBusinessLogic implements IUserBusinessLogic {
Either<User, ActionStatus> eitherCreator = getUser(modifierUserId, false);
if (eitherCreator.isRight() || eitherCreator.left().value() == null) {
- log.debug("createUser method - user is not listed. userId={}", modifier.getUserId());
+ log.debug("createUser method - user is not listed. userId = {}", modifier.getUserId());
responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.ADD_USER);
return Either.right(responseFormat);
@@ -98,7 +98,7 @@ public class UserBusinessLogic implements IUserBusinessLogic {
modifier = eitherCreator.left().value();
if (!modifier.getRole().equals(UserRoleEnum.ADMIN.getName())) {
- log.debug("createUser method - user is not admin={}", modifier.getUserId());
+ log.debug("createUser method - user is not admin = {}", modifier.getUserId());
responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.ADD_USER);
return Either.right(responseFormat);
@@ -120,7 +120,7 @@ public class UserBusinessLogic implements IUserBusinessLogic {
// isUserAlreadyExist = true;
if (userFromDb.getStatus() == UserStatusEnum.ACTIVE) {
responseFormat = componentsUtils.getResponseFormatByUserId(ActionStatus.USER_ALREADY_EXIST, newUser.getUserId());
- log.debug("createUser method - user already exist with id: {}", modifier.getUserId(), userFromDb.getUserId());
+ log.debug("createUser method - user with id {} already exist with id: {}", modifier.getUserId(), userFromDb.getUserId());
handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.ADD_USER);
return Either.right(responseFormat);
}
@@ -130,7 +130,7 @@ public class UserBusinessLogic implements IUserBusinessLogic {
// validate Email
if (newUser.getEmail() != null && !userAdminValidator.validateEmail(newUser.getEmail())) {
- log.debug("createUser method - user has invalid email={}", modifier.getUserId());
+ log.debug("createUser method - user has invalid email = {}", modifier.getUserId());
responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_EMAIL_ADDRESS, newUser.getEmail());
handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.ADD_USER);
return Either.right(responseFormat);
@@ -141,7 +141,7 @@ public class UserBusinessLogic implements IUserBusinessLogic {
newUser.setRole(Role.DESIGNER.name());
} else {
if (!userAdminValidator.validateRole(newUser.getRole())) {
- log.debug("createUser method - user has invalid role={}", modifier.getUserId());
+ log.debug("createUser method - user has invalid role = {}", modifier.getUserId());
responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_ROLE, newUser.getRole());
handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.ADD_USER);
return Either.right(responseFormat);
@@ -168,8 +168,9 @@ public class UserBusinessLogic implements IUserBusinessLogic {
addOrUpdateUserReq = userAdminOperation.updateUserData(newUser);
} else { // user not exist - create new user
+
if (newUser.getUserId() != null && !userAdminValidator.validateUserId(newUser.getUserId())) {
- log.debug("createUser method - user has invalid userId={}", modifier.getUserId());
+ log.debug("createUser method - user has invalid userId = {}", modifier.getUserId());
responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_USER_ID, newUser.getUserId());
handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.ADD_USER);
return Either.right(responseFormat);
@@ -204,7 +205,7 @@ public class UserBusinessLogic implements IUserBusinessLogic {
Either<User, ActionStatus> eitherCreator = getUser(modifierUserId, false);
if (eitherCreator.isRight() || eitherCreator.left().value() == null) {
- log.debug("updateUserRole method - user is not listed. userId={}", modifier.getUserId());
+ log.debug("updateUserRole method - user is not listed. userId = {}", modifier.getUserId());
responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.UPDATE_USER);
return Either.right(responseFormat);
@@ -212,14 +213,14 @@ public class UserBusinessLogic implements IUserBusinessLogic {
modifier = eitherCreator.left().value();
if (!modifier.getRole().equals(UserRoleEnum.ADMIN.getName())) {
- log.debug("updateUserRole method - user is not admin. userId={}", modifier.getUserId());
+ log.debug("updateUserRole method - user is not admin. userId = {}", modifier.getUserId());
responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.UPDATE_USER);
return Either.right(responseFormat);
}
if (modifier.getUserId().equals(userIdToUpdate)) {
- log.debug("updateUserRole method - admin role can only be updated by other admin. userId={}", modifier.getUserId());
+ log.debug("updateUserRole method - admin role can only be updated by other admin. userId = {}", modifier.getUserId());
responseFormat = componentsUtils.getResponseFormat(ActionStatus.UPDATE_USER_ADMIN_CONFLICT);
handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.UPDATE_USER);
return Either.right(responseFormat);
@@ -227,14 +228,14 @@ public class UserBusinessLogic implements IUserBusinessLogic {
Either<User, ActionStatus> userToUpdateReq = getUser(userIdToUpdate, false);
if (userToUpdateReq.isRight() || userToUpdateReq.left().value() == null) {
- log.debug("updateUserRole method - user not found. userId={}", modifier.getUserId());
+ log.debug("updateUserRole method - user not found. userId = {}", modifier.getUserId());
responseFormat = componentsUtils.getResponseFormat(ActionStatus.USER_NOT_FOUND, userIdToUpdate);
handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.UPDATE_USER);
return Either.right(responseFormat);
}
if (!userAdminValidator.validateRole(userRole)) {
- log.debug("updateUserRole method - user has invalid role={}", modifier.getUserId());
+ log.debug("updateUserRole method - user has invalid role = {}", modifier.getUserId());
responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_ROLE, userRole);
handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.UPDATE_USER);
return Either.right(responseFormat);
@@ -267,7 +268,7 @@ public class UserBusinessLogic implements IUserBusinessLogic {
Either<User, StorageOperationStatus> updateUserReq = userAdminOperation.updateUserData(newUser);
if (updateUserReq.isRight() || updateUserReq.left().value() == null) {
- log.debug("updateUser method - failed to update user data. userId={}", modifier.getUserId());
+ log.debug("updateUser method - failed to update user data. userId = {}", modifier.getUserId());
return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateUserReq.right().value())));
}
@@ -374,7 +375,7 @@ public class UserBusinessLogic implements IUserBusinessLogic {
Either<User, ActionStatus> eitherCreator = getUser(userId, false);
if (eitherCreator.isRight() || eitherCreator.left().value() == null) {
- log.debug("deActivateUser method - user is not listed. userId={}", modifier.getUserId());
+ log.debug("deActivateUser method - user is not listed. userId = {}", modifier.getUserId());
responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.DELETE_USER);
return Either.right(responseFormat);
@@ -383,14 +384,14 @@ public class UserBusinessLogic implements IUserBusinessLogic {
modifier = eitherCreator.left().value();
if (!modifier.getRole().equals(UserRoleEnum.ADMIN.getName())) {
- log.debug("deActivateUser method - user is not admin. userId={}", modifier.getUserId());
+ log.debug("deActivateUser method - user is not admin. userId = {}", modifier.getUserId());
responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.DELETE_USER);
return Either.right(responseFormat);
}
if (modifier.getUserId().equals(userUniuqeIdToDeactive)) {
- log.debug("deActivateUser deActivateUser - admin can only be deactivate by other admin. userId={}", modifier.getUserId());
+ log.debug("deActivateUser deActivateUser - admin can only be deactivate by other admin. userId = {}", modifier.getUserId());
responseFormat = componentsUtils.getResponseFormat(ActionStatus.DELETE_USER_ADMIN_CONFLICT);
handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.DELETE_USER);
return Either.right(responseFormat);
@@ -706,7 +707,7 @@ public class UserBusinessLogic implements IUserBusinessLogic {
log.debug("Functional menu fetched is {}", functionalMenu);
} catch (UebException e) {
- log.debug("Failed to fetch 'functional menu' of user {} from ecomp portal(via UEB). {}", userId, e);
+ log.debug("Failed to fetch 'functional menu' of user {} from ecomp portal(via UEB)", userId, e);
BeEcompErrorManager.getInstance().logInternalFlowError("FetchFunctionalMenu", "Failed to fetch 'functional menu'", ErrorSeverity.ERROR);
}
return functionalMenu;